traefik/pkg/server/cookie/cookie.go

58 lines
1.1 KiB
Go
Raw Normal View History

2017-10-10 09:10:02 +00:00
package cookie
import (
"crypto/sha1"
"fmt"
"strings"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/log"
2017-10-10 09:10:02 +00:00
)
const cookieNameLength = 6
// GetName of a cookie
func GetName(cookieName string, backendName string) string {
if len(cookieName) != 0 {
return sanitizeName(cookieName)
}
return GenerateName(backendName)
}
// GenerateName Generate a hashed name
func GenerateName(backendName string) string {
data := []byte("_TRAEFIK_BACKEND_" + backendName)
hash := sha1.New()
_, err := hash.Write(data)
if err != nil {
// Impossible case
2019-09-13 17:28:04 +00:00
log.WithoutContext().Errorf("Fail to create cookie name: %v", err)
2017-10-10 09:10:02 +00:00
}
return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength]
}
// sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2
func sanitizeName(backend string) string {
sanitizer := func(r rune) rune {
switch r {
case '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '`', '|', '~':
return r
}
switch {
case 'a' <= r && r <= 'z':
fallthrough
case 'A' <= r && r <= 'Z':
fallthrough
case '0' <= r && r <= '9':
return r
default:
return '_'
}
}
return strings.Map(sanitizer, backend)
}