1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-17 09:57:01 +00:00

enhanced cookie security and management

Former-commit-id: a97b0b33e87749a2e8c32e63269fcc60fa326ff3
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-05-09 14:04:51 +03:00
parent d5f1649895
commit 50b18c7515
18 changed files with 490 additions and 466 deletions

View File

@@ -13,33 +13,6 @@ const (
DefaultCookieName = "irissessionid"
)
// Encoding is the Cookie Encoder/Decoder interface, which can be passed as configuration field
// alternatively to the `Encode` and `Decode` fields.
type Encoding interface {
// Encode the cookie value if not nil.
// Should accept as first argument the cookie name (config.Name)
// as second argument the server's generated session id.
// Should return the new session id, if error the session id set to empty which is invalid.
//
// Note: Errors are not printed, so you have to know what you're doing,
// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
//
// Defaults to nil
Encode(cookieName string, value interface{}) (string, error)
// Decode the cookie value if not nil.
// Should accept as first argument the cookie name (config.Name)
// as second second accepts the client's cookie value (the encoded session id).
// Should return an error if decode operation failed.
//
// Note: Errors are not printed, so you have to know what you're doing,
// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
//
// Defaults to nil
Decode(cookieName string, cookieValue string, v interface{}) error
}
type (
// Config is the configuration for sessions. Please read it before using sessions.
Config struct {
@@ -66,34 +39,11 @@ type (
// Defaults to false.
AllowReclaim bool
// Encode the cookie value if not nil.
// Should accept as first argument the cookie name (config.Cookie)
// as second argument the server's generated session id.
// Should return the new session id, if error the session id set to empty which is invalid.
//
// Note: Errors are not printed, so you have to know what you're doing,
// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
// Encoding should encodes and decodes
// authenticated and optionally encrypted cookie values.
//
// Defaults to nil.
Encode func(cookieName string, value interface{}) (string, error)
// Decode the cookie value if not nil.
// Should accept as first argument the cookie name (config.Cookie)
// as second second accepts the client's cookie value (the encoded session id).
// Should return an error if decode operation failed.
//
// Note: Errors are not printed, so you have to know what you're doing,
// and remember: if you use AES it only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
//
// Defaults to nil.
Decode func(cookieName string, cookieValue string, v interface{}) error
// Encoding same as Encode and Decode but receives a single instance which
// completes the "CookieEncoder" interface, `Encode` and `Decode` functions.
//
// Defaults to nil.
Encoding Encoding
Encoding context.SecureCookie
// Expires the duration of which the cookie must expires (created_time.Add(Expires)).
// If you want to delete the cookie when the browser closes, set it to -1.
@@ -131,10 +81,5 @@ func (c Config) Validate() Config {
}
}
if c.Encoding != nil {
c.Encode = c.Encoding.Encode
c.Decode = c.Encoding.Decode
}
return c
}

View File

@@ -1,142 +0,0 @@
package sessions
import (
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/kataras/iris/v12/context"
"golang.org/x/net/publicsuffix"
)
var (
// CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie.
CookieExpireDelete = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
// CookieExpireUnlimited indicates that the cookie doesn't expire.
CookieExpireUnlimited = time.Now().AddDate(24, 10, 10)
)
// GetCookie returns cookie's value by it's name
// returns empty string if nothing was found
func GetCookie(ctx context.Context, name string) string {
c, err := ctx.Request().Cookie(name)
if err != nil {
return ""
}
return c.Value
}
// AddCookie adds a cookie
func AddCookie(ctx context.Context, cookie *http.Cookie, reclaim bool) {
if reclaim {
ctx.Request().AddCookie(cookie)
}
ctx.UpsertCookie(cookie)
}
// RemoveCookie deletes a cookie by it's name/key
// If "purge" is true then it removes the, temp, cookie from the request as well.
func RemoveCookie(ctx context.Context, config Config) {
cookie, err := ctx.Request().Cookie(config.Cookie)
if err != nil {
return
}
cookie.Expires = CookieExpireDelete
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
cookie.MaxAge = -1
cookie.Value = ""
cookie.Path = "/"
cookie.Domain = formatCookieDomain(ctx, config.DisableSubdomainPersistence)
AddCookie(ctx, cookie, config.AllowReclaim)
if config.AllowReclaim {
// delete request's cookie also, which is temporary available.
ctx.Request().Header.Set("Cookie", "")
}
}
// IsValidCookieDomain returns true if the receiver is a valid domain to set
// valid means that is recognised as 'domain' by the browser, so it(the cookie) can be shared with subdomains also
func IsValidCookieDomain(domain string) bool {
if net.IP([]byte(domain)).IsLoopback() {
// for these type of hosts, we can't allow subdomains persistence,
// the web browser doesn't understand the mysubdomain.0.0.0.0 and mysubdomain.127.0.0.1 mysubdomain.32.196.56.181. as scorrectly ubdomains because of the many dots
// so don't set a cookie domain here, let browser handle this
return false
}
dotLen := strings.Count(domain, ".")
if dotLen == 0 {
// we don't have a domain, maybe something like 'localhost', browser doesn't see the .localhost as wildcard subdomain+domain
return false
}
if dotLen >= 3 {
if lastDotIdx := strings.LastIndexByte(domain, '.'); lastDotIdx != -1 {
// chekc the last part, if it's number then propably it's ip
if len(domain) > lastDotIdx+1 {
_, err := strconv.Atoi(domain[lastDotIdx+1:])
if err == nil {
return false
}
}
}
}
return true
}
// func formatCookieDomain(ctx context.Context, disableSubdomainPersistence bool) string {
// if disableSubdomainPersistence {
// return ""
// }
// requestDomain := ctx.Host()
// if portIdx := strings.IndexByte(requestDomain, ':'); portIdx > 0 {
// requestDomain = requestDomain[0:portIdx]
// }
// if !IsValidCookieDomain(requestDomain) {
// return ""
// }
// // RFC2109, we allow level 1 subdomains, but no further
// // if we have localhost.com , we want the localhost.com.
// // so if we have something like: mysubdomain.localhost.com we want the localhost here
// // if we have mysubsubdomain.mysubdomain.localhost.com we want the .mysubdomain.localhost.com here
// // slow things here, especially the 'replace' but this is a good and understable( I hope) way to get the be able to set cookies from subdomains & domain with 1-level limit
// if dotIdx := strings.IndexByte(requestDomain, '.'); dotIdx > 0 {
// // is mysubdomain.localhost.com || mysubsubdomain.mysubdomain.localhost.com
// if strings.IndexByte(requestDomain[dotIdx+1:], '.') > 0 {
// requestDomain = requestDomain[dotIdx+1:]
// }
// }
// // finally set the .localhost.com (for(1-level) || .mysubdomain.localhost.com (for 2-level subdomain allow)
// return "." + requestDomain // . to allow persistence
// }
func formatCookieDomain(ctx context.Context, disableSubdomainPersistence bool) string {
if disableSubdomainPersistence {
return ""
}
host := ctx.Host()
if portIdx := strings.IndexByte(host, ':'); portIdx > 0 {
host = host[0:portIdx]
}
domain, err := publicsuffix.EffectiveTLDPlusOne(host)
if err != nil {
return "." + host
}
return "." + domain
}

View File

@@ -2,6 +2,8 @@ package sessions
import (
"time"
"github.com/kataras/iris/v12/context"
)
// LifeTime controls the session expiration datetime.
@@ -50,7 +52,7 @@ func (lt *LifeTime) Shift(d time.Duration) {
// ExpireNow reduce the lifetime completely.
func (lt *LifeTime) ExpireNow() {
lt.Time = CookieExpireDelete
lt.Time = context.CookieExpireDelete
if lt.timer != nil {
lt.timer.Stop()
}

View File

@@ -21,6 +21,8 @@ func init() {
type Sessions struct {
config Config
provider *provider
handlerCookieOpts []context.CookieOption // see `Handler`.
}
// New returns a new fast, feature-rich sessions manager
@@ -38,52 +40,46 @@ func (s *Sessions) UseDatabase(db Database) {
s.provider.RegisterDatabase(db)
}
// GetCookieOptions returns any cookie options registered for the `Handler` method.
func (s *Sessions) GetCookieOptions() []context.CookieOption {
return s.handlerCookieOpts
}
// updateCookie gains the ability of updating the session browser cookie to any method which wants to update it
func (s *Sessions) updateCookie(ctx context.Context, sid string, expires time.Duration, options ...context.CookieOption) {
cookie := &http.Cookie{}
// The RFC makes no mention of encoding url value, so here I think to encode both sessionid key and the value using the safe(to put and to use as cookie) url-encoding
cookie.Name = s.config.Cookie
cookie.Value = sid
cookie.Path = "/"
cookie.Domain = formatCookieDomain(ctx, s.config.DisableSubdomainPersistence)
cookie.HttpOnly = true
if !s.config.DisableSubdomainPersistence {
cookie.SameSite = http.SameSiteLaxMode // allow subdomain sharing.
}
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
if expires >= 0 {
if expires == 0 { // unlimited life
cookie.Expires = CookieExpireUnlimited
cookie.Expires = context.CookieExpireUnlimited
} else { // > 0
cookie.Expires = time.Now().Add(expires)
}
cookie.MaxAge = int(time.Until(cookie.Expires).Seconds())
}
// set the cookie to secure if this is a tls wrapped request
// and the configuration allows it.
if ctx.Request().TLS != nil && s.config.CookieSecureTLS {
cookie.Secure = true
}
// encode the session id cookie client value right before send it.
cookie.Value = s.encodeCookieValue(cookie.Value)
for _, opt := range options {
opt(cookie)
}
AddCookie(ctx, cookie, s.config.AllowReclaim)
ctx.UpsertCookie(cookie, options...)
}
// Start creates or retrieves an existing session for the particular request.
// Note that `Start` method will not respect configuration's `AllowReclaim`, `DisableSubdomainPersistence`, `CookieSecureTLS`,
// and `Encoding` settings.
// Register sessions as a middleware through the `Handler` method instead,
// which provides automatic resolution of a *sessions.Session input argument
// on MVC and APIContainer as well.
//
// NOTE: Use `app.Use(sess.Handler())` instead, avoid using `Start` manually.
func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOption) *Session {
cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
cookieValue := ctx.GetCookie(s.config.Cookie, cookieOptions...)
if cookieValue == "" { // cookie doesn't exist, let's generate a session and set a cookie.
sid := s.config.SessionIDGenerator(ctx)
@@ -99,13 +95,34 @@ func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOpt
return s.provider.Read(s, cookieValue, s.config.Expires)
}
const contextSessionKey = "iris.session"
const sessionContextKey = "iris.session"
// Handler returns a sessions middleware to register on application routes.
// To return the request's Session call the `Get(ctx)` package-level function.
//
// Call `Handler()` once per sessions manager.
func (s *Sessions) Handler(cookieOptions ...context.CookieOption) context.Handler {
s.handlerCookieOpts = cookieOptions
return func(ctx context.Context) {
session := s.Start(ctx, cookieOptions...)
ctx.Values().Set(contextSessionKey, session)
var requestOptions []context.CookieOption
if s.config.AllowReclaim {
requestOptions = append(requestOptions, context.CookieAllowReclaim(ctx, s.config.Cookie))
}
if !s.config.DisableSubdomainPersistence {
requestOptions = append(requestOptions, context.CookieAllowSubdomains(ctx, s.config.Cookie))
}
if s.config.CookieSecureTLS {
requestOptions = append(requestOptions, context.CookieSecure(ctx))
}
if s.config.Encoding != nil {
requestOptions = append(requestOptions, context.CookieEncoding(s.config.Encoding, s.config.Cookie))
}
ctx.AddCookieOptions(requestOptions...) // request life-cycle options.
session := s.Start(ctx, cookieOptions...) // this cookie's end-developer's custom options.
ctx.Values().Set(sessionContextKey, session)
ctx.Next()
}
}
@@ -116,14 +133,17 @@ func (s *Sessions) Handler(cookieOptions ...context.CookieOption) context.Handle
// The `Sessions.Start` should be called previously,
// e.g. register the `Sessions.Handler` as middleware.
// Then call `Get` package-level function as many times as you want.
// The `Sessions.Start` can be called more than one time in the same request life cycle as well.
// Note: It will return nil if the session got destroyed by the same request.
// If you need to destroy and start a new session in the same request you need to call
// sessions manager's `Start` method after Destroy.
func Get(ctx context.Context) *Session {
if v := ctx.Values().Get(contextSessionKey); v != nil {
if v := ctx.Values().Get(sessionContextKey); v != nil {
if sess, ok := v.(*Session); ok {
return sess
}
}
// ctx.Application().Logger().Debugf("Sessions: Get: no session found, prior Destroy(ctx) calls in the same request should follow with a Start(ctx) call too")
return nil
}
@@ -144,7 +164,7 @@ func (s *Sessions) ShiftExpiration(ctx context.Context, cookieOptions ...context
// It will return `ErrNotFound` when trying to update expiration on a non-existence or not valid session entry.
// It will return `ErrNotImplemented` if a database is used and it does not support this feature, yet.
func (s *Sessions) UpdateExpiration(ctx context.Context, expires time.Duration, cookieOptions ...context.CookieOption) error {
cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
cookieValue := ctx.GetCookie(s.config.Cookie)
if cookieValue == "" {
return ErrNotFound
}
@@ -172,17 +192,20 @@ func (s *Sessions) OnDestroy(listeners ...DestroyListener) {
}
}
// Destroy remove the session data and remove the associated cookie.
// Destroy removes the session data, the associated cookie
// and the Context's session value.
// Next calls of `sessions.Get` will occur to a nil Session,
// use `Sessions#Start` method for renewal
// or use the Session's Destroy method which does keep the session entry with its values cleared.
func (s *Sessions) Destroy(ctx context.Context) {
cookieValue := GetCookie(ctx, s.config.Cookie)
// decode the client's cookie value in order to find the server's session id
// to destroy the session data.
cookieValue = s.decodeCookieValue(cookieValue)
cookieValue := ctx.GetCookie(s.config.Cookie)
if cookieValue == "" { // nothing to destroy
return
}
RemoveCookie(ctx, s.config)
ctx.Values().Remove(sessionContextKey)
ctx.RemoveCookie(s.config.Cookie)
s.provider.Destroy(cookieValue)
}
@@ -204,35 +227,3 @@ func (s *Sessions) DestroyByID(sid string) {
func (s *Sessions) DestroyAll() {
s.provider.DestroyAll()
}
// let's keep these funcs simple, we can do it with two lines but we may add more things in the future.
func (s *Sessions) decodeCookieValue(cookieValue string) string {
if cookieValue == "" {
return ""
}
if decode := s.config.Decode; decode != nil {
var cookieValueDecoded string
err := decode(s.config.Cookie, cookieValue, &cookieValueDecoded)
if err == nil {
cookieValue = cookieValueDecoded
} else {
cookieValue = ""
}
}
return cookieValue
}
func (s *Sessions) encodeCookieValue(cookieValue string) string {
if encode := s.config.Encode; encode != nil {
newVal, err := encode(s.config.Cookie, cookieValue)
if err == nil {
cookieValue = newVal
} else {
cookieValue = ""
}
}
return cookieValue
}

View File

@@ -15,14 +15,16 @@ func TestSessions(t *testing.T) {
app := iris.New()
sess := sessions.New(sessions.Config{Cookie: "mycustomsessionid"})
testSessions(t, sess, app)
app.Use(sess.Handler())
testSessions(t, app)
}
const (
testEnableSubdomain = true
)
func testSessions(t *testing.T, sess *sessions.Sessions, app *iris.Application) {
func testSessions(t *testing.T, app *iris.Application) {
values := map[string]interface{}{
"Name": "iris",
"Months": "4",
@@ -30,7 +32,7 @@ func testSessions(t *testing.T, sess *sessions.Sessions, app *iris.Application)
}
writeValues := func(ctx context.Context) {
s := sess.Start(ctx)
s := sessions.Get(ctx)
sessValues := s.GetAll()
_, err := ctx.JSON(sessValues)
@@ -44,7 +46,7 @@ func testSessions(t *testing.T, sess *sessions.Sessions, app *iris.Application)
}
app.Post("/set", func(ctx context.Context) {
s := sess.Start(ctx)
s := sessions.Get(ctx)
vals := make(map[string]interface{})
if err := ctx.ReadJSON(&vals); err != nil {
t.Fatalf("Cannot read JSON. Trace %s", err.Error())
@@ -59,26 +61,38 @@ func testSessions(t *testing.T, sess *sessions.Sessions, app *iris.Application)
})
app.Get("/clear", func(ctx context.Context) {
sess.Start(ctx).Clear()
sessions.Get(ctx).Clear()
writeValues(ctx)
})
app.Get("/destroy", func(ctx context.Context) {
sess.Destroy(ctx)
writeValues(ctx)
session := sessions.Get(ctx)
if session.IsNew() {
t.Fatal("expected session not to be nil on destroy")
}
session.Man.Destroy(ctx)
if sessions.Get(ctx) != nil {
t.Fatal("expected session inside Context to be nil after Manager's Destroy call")
}
ctx.JSON(struct{}{})
// the cookie and all values should be empty
})
// request cookie should be empty
app.Get("/after_destroy", func(ctx context.Context) {
// cookie should be new.
app.Get("/after_destroy_renew", func(ctx context.Context) {
isNew := sessions.Get(ctx).IsNew()
ctx.Writef("%v", isNew)
})
app.Get("/multi_start_set_get", func(ctx context.Context) {
s := sess.Start(ctx)
s := sessions.Get(ctx)
s.Set("key", "value")
ctx.Next()
}, func(ctx context.Context) {
s := sess.Start(ctx)
s := sessions.Get(ctx)
_, err := ctx.Writef(s.GetString("key"))
if err != nil {
t.Fatal(err)
@@ -98,12 +112,13 @@ func testSessions(t *testing.T, sess *sessions.Sessions, app *iris.Application)
// test destroy which also clears first
d := e.GET("/destroy").Expect().Status(iris.StatusOK)
d.JSON().Object().Empty()
// This removed: d.Cookies().Empty(). Reason:
// httpexpect counts the cookies set or deleted at the response time, but cookie is not removed, to be really removed needs to SetExpire(now-1second) so,
// test if the cookies removed on the next request, like the browser's behavior.
e.GET("/after_destroy").Expect().Status(iris.StatusOK).Cookies().Empty()
d = e.GET("/after_destroy_renew").Expect().Status(iris.StatusOK)
d.Body().Equal("true")
d.Cookies().NotEmpty()
// set and clear again
e.POST("/set").WithJSON(values).Expect().Status(iris.StatusOK).Cookies().NotEmpty()
e.POST("/set").WithJSON(values).Expect().Status(iris.StatusOK)
e.GET("/clear").Expect().Status(iris.StatusOK).JSON().Object().Empty()
// test start on the same request but more than one times