gin icon indicating copy to clipboard operation
gin copied to clipboard

Why gin.Context.Cookie has to do url.QueryUnescape?

Open poom3d opened this issue 7 years ago • 5 comments

  • go version: go1.11.2 darwin/amd64
  • gin version (or commit ref): v1.3.0
  • operating system: macos/linux

Description

Gin replace + sign with whitespace (probably) due to url.QueryUnescape. We need to replace it back to original + sign and then encode to make it back to original value.

The code in question: https://github.com/gin-gonic/gin/blob/master/context.go#L741

If you look at how http package get cookie, it does not unescape the value and return just a string. I would like to know what's the decision to unescape value here.

FYI, it breaks our app, and we need to do a workaround by replacing " " (whitespace) back to +.

poom3d avatar Dec 27 '18 04:12 poom3d

Same problem here! Any application that encodes cookie values using base64 encoding will sometimes break silently (in base64, + is allowed). I would find it helpful if at least a warning was printed.

RFC 6265 even recommends base64 as encoding:

To maximize compatibility with user agents, servers that wish to store arbitrary data in a cookie-value SHOULD encode that data, for example, using Base64 [RFC4648].

In my case, some users were not able to log in, as they were unfortunate enough to have a + in their decryption key. This is unexpected behavior, especially after migrating from a fully working net/http implementation. Why would gin handle cookies differently, especially if it uses the original net/http methods to retrieve the cookie (from context.go):

// Cookie returns the named cookie provided in the request or
// ErrNoCookie if not found. And return the named cookie is unescaped.
// If multiple cookies match the given name, only one cookie will
// be returned.
func (c *Context) Cookie(name string) (string, error) {
	cookie, err := c.Request.Cookie(name)
	if err != nil {
		return "", err
	}
	val, _ := url.QueryUnescape(cookie.Value)
	return val, nil
}

[1] RFC 6265 [2] StackOverflow

jakoblorz avatar Jul 12 '19 11:07 jakoblorz

move to 1.7

appleboy avatar Mar 18 '20 07:03 appleboy

Fixed by https://github.com/gin-gonic/gin/pull/3683

cavedon avatar Aug 01 '23 22:08 cavedon

Any more progress on this one? I think gin need to comply with RFC6265 image so the usage QueryEscape leads to unexpected url encoding

mr-liusg avatar Jun 21 '24 08:06 mr-liusg

https://github.com/gin-gonic/gin/pull/3683#issuecomment-2229336611

A possible reason is to maintain compatibility with other web frameworks. This behavior could be turned into a flag to clarify the intend and use cases.

zzh8829 avatar Jul 15 '24 20:07 zzh8829