Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cloudflare and reverse proxy support #2419

Closed
3 tasks done
justevery opened this issue Apr 15, 2023 · 14 comments · Fixed by #2421
Closed
3 tasks done

Cloudflare and reverse proxy support #2419

justevery opened this issue Apr 15, 2023 · 14 comments · Fixed by #2421

Comments

@justevery
Copy link

Bug Description

A cloudflare and error issue.

How to Reproduce

Steps to reproduce the behavior:

  1. Go to '....'
  2. Click on '....'
  3. Do '....'
  4. See '....'

Expected Behavior

  1. The reverse proxy thing if any attack comes expose the reverse proxy IP address and it shows everyone "dial connection brb brb ip". So your ip address gone, i look the reverse proxy, error handler documents but i don't see how i can made all errors to custom html page.

  2. Ratelimit are need to have a cloudflare mode for get CF-Connecting-IP it so annoying because of i tried 5-6 way for get CF-Connecting-IP and the end i do.

  3. The logging thing has same problem what i said on 2.

Fiber Version

latest

Code Snippet (optional)

No response

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.
@welcome
Copy link

welcome bot commented Apr 15, 2023

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@ReneWerner87
Copy link
Member

ReneWerner87 commented Apr 16, 2023

no 2 and 3 are fixable with

app := fiber.New(fiber.Config{
	ProxyHeader: "CF-Connecting-IP",
})

or

app := fiber.New(fiber.Config{
	ProxyHeader: fiber.HeaderXForwardedFor,
})

according to https://developers.cloudflare.com/fundamentals/get-started/reference/http-request-headers/ and
https://developers.cloudflare.com/fundamentals/get-started/reference/http-request-headers/#cf-connecting-ip

after that the ctx.IP method is using this header for the ip determination
https://docs.gofiber.io/api/ctx#ip

and the logger will log the right ip and the limiter middleware is also using the right one.
image
https://docs.gofiber.io/api/middleware/limiter#config

no 1 is solvable with the ModifiedResponse method
here a small example:

package main

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/proxy"
)

func main() {
	app := fiber.New()


	app.Use(
		proxy.Balancer(proxy.Config{
		        Servers:  []string{
		              "http://localhost:3001",
		              "http://localhost:3002",
	                },
			ModifyResponse: func(c *fiber.Ctx) error {
				if c.Response().StatusCode() == 502 { // Check if the response is a 502 (Bad Gateway) error
					c.Response().Reset() // Reset the response to clear the existing error message
					return c.Status(503).SendString("The requested service is currently unavailable. Please try again later.")
				}
				return nil
			},
		}),
	)

	err := app.Listen(":3000")
	if err != nil {
		fmt.Printf("Error starting server: %v", err)
	}
}

@ReneWerner87 ReneWerner87 changed the title 🐛 [Bug]: It does not support cloudflare and the error pages are horrible. Cloudflare and reverse proxy support Apr 16, 2023
@justevery
Copy link
Author

justevery commented Apr 16, 2023

Well, the proxy.Balancer code has errors. I fixed it the syntax error if someone wants to use it.

	app.Use(
		proxy.Balancer(proxy.Config{
		        Servers:  []string{
		              "http://localhost:3001",
		              "http://localhost:3002",
	                },
			ModifyResponse: func(c *fiber.Ctx) error {
				if c.Response().StatusCode() == 502 { // Check if the response is a 502 (Bad Gateway) error
					c.Response().Reset() // Reset the response to clear the existing error message
					return c.Status(503).SendString("The requested service is currently unavailable. Please try again later.")
				}
				return nil
			},
		}),
	)

@justevery
Copy link
Author

My problem isn't solved it still shows dial tcp errors..

@ReneWerner87
Copy link
Member

@justevery Is it running? Can we mark the report as closed (answered)?

@ReneWerner87
Copy link
Member

Ok then I have to create a reproducible example

Need to know where exactly the error is returned

@ReneWerner87
Copy link
Member

ReneWerner87 commented Apr 16, 2023

package main

import (
	"errors"
	"log"
	"net"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/proxy"
)

func main() {
	app := fiber.New(fiber.Config{
		// Override default error handler
		ErrorHandler: func(ctx *fiber.Ctx, err error) error {

			ctx.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)

			var netError net.Error
			if errors.As(err, &netError) {
				// 502 - Bad Gateway or 503 - ServiceUnavailable
				err = fiber.ErrBadGateway
			}
			code := fiber.StatusInternalServerError
			var e *fiber.Error
			if errors.As(err, &e) {
				code = e.Code
			}

			return ctx.Status(code).SendString(err.Error())
		},
	})
	app.Use(proxy.Balancer(proxy.Config{
		Servers: []string{
			"http://139.144.180.160/",
		},
		ModifyRequest: func(ctx *fiber.Ctx) error {
			ctx.Request().Header.Add("CF-Connecting-IP", ctx.IP())
			return nil
		},
	}))

	log.Fatalln(app.Listen(":8080"))
}

@justevery
Copy link
Author

René patiently solved my problem, I thank him ♥

@ReneWerner87
Copy link
Member

ReneWerner87 commented Apr 16, 2023

@efectn @gaby @leonklingele @li-jin-gou
should we add a part for the net.Error(s) in our default error handler

fiber/app.go

Lines 472 to 480 in 3e9575b

func DefaultErrorHandler(c *Ctx, err error) error {
code := StatusInternalServerError
var e *Error
if errors.As(err, &e) {
code = e.Code
}
c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
return c.Status(code).SendString(err.Error())
}

so that we do not pass on network information for security reasons ?

app := fiber.New(fiber.Config{
    // Override default error handler
    ErrorHandler: func(ctx *fiber.Ctx, err error) error {

        ctx.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)

        var netError net.Error
        if errors.As(err, &netError) {
            // 502 - Bad Gateway or 503 - ServiceUnavailable
            err = fiber.ErrBadGateway
        }
        code := fiber.StatusInternalServerError
        var e *fiber.Error
        if errors.As(err, &e) {
            code = e.Code
        }

        return ctx.Status(code).SendString(err.Error())
    },
})

@gaby
Copy link
Member

gaby commented Apr 16, 2023

@ReneWerner87 Yes, may be worth it.

@leonklingele
Copy link
Member

leonklingele commented Apr 16, 2023 via email

@ReneWerner87
Copy link
Member

Then let us do this

@leonklingele
Copy link
Member

leonklingele commented Apr 16, 2023 via email

@ReneWerner87
Copy link
Member

Don’t forget to log the original error. It’ll be a pain (or even close to impossible) to debug.

Bildschirmfoto 2023-04-17 um 08 13 43

not a problem, the logger is logging the error message

what should i take ? 502 or 503 ?

ReneWerner87 added a commit that referenced this issue Apr 17, 2023
fixes: reverse proxy support #2419
@ReneWerner87 ReneWerner87 linked a pull request Apr 17, 2023 that will close this issue
ReneWerner87 added a commit that referenced this issue Apr 20, 2023
fixes: reverse proxy support #2419
ReneWerner87 added a commit that referenced this issue Apr 20, 2023
fixes: reverse proxy support #2419
ReneWerner87 added a commit that referenced this issue Apr 21, 2023
fixes: reverse proxy support #2419
ReneWerner87 added a commit that referenced this issue Apr 21, 2023
* improve error handling for net error(s)
fixes: reverse proxy support #2419

* Update app.go

Co-authored-by: leonklingele <[email protected]>

* improve error handling for net error(s)
fixes: reverse proxy support #2419

* improve error handling for net error(s)
fixes: reverse proxy support #2419

* improve error handling for net error(s)
fixes: reverse proxy support #2419

---------

Co-authored-by: leonklingele <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants