Skip to content

Commit

Permalink
Merge pull request #409 from supertokens/cookie-domain-fix
Browse files Browse the repository at this point in the history
Cookie domain fix
  • Loading branch information
rishabhpoddar authored May 8, 2024
2 parents 0ca19ca + 5adb33b commit 2029c42
Show file tree
Hide file tree
Showing 12 changed files with 723 additions and 56 deletions.
38 changes: 38 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

## [0.19.0] - 2024-05-01

- Added `OlderCookieDomain` config option in the session recipe. This will allow users to clear cookies from the older domain when the `CookieDomain` is changed.
- If `VerifySession` detects multiple access tokens in the request, it will return a 401 error, prompting a refresh, even if one of the tokens is valid.
- `RefreshPOST` (`/auth/session/refresh` by default) API changes:
- now returns 500 error if multiple access tokens are present in the request and `config.OlderCookieDomain` is not set.
- now clears the access token cookie if it was called without a refresh token (if an access token cookie exists and if using cookie-based sessions).
- now clears cookies from the old domain if `OlderCookieDomain` is specified and multiple refresh/access token cookies exist, without updating the front-token or any of the tokens.
- now a 200 response may not include new session tokens.
- Fixed a bug in the `normaliseSessionScopeOrThrowError` util function that caused it to remove leading dots from the scope string.

### Rationale

This update addresses an edge case where changing the `CookieDomain` config on the server can lead to session integrity issues. For instance, if the API server URL is 'api.example.com' with a cookie domain of '.example.com', and the server updates the cookie domain to 'api.example.com', the client may retain cookies with both '.example.com' and 'api.example.com' domains, resulting in multiple sets of session token cookies existing.

Previously, verifySession would select one of the access tokens from the incoming request. If it chose the older cookie, it would return a 401 status code, prompting a refresh request. However, the `RefreshPOST` API would then set new session token cookies with the updated `CookieDomain`, but older cookies will persist, leading to repeated 401 errors and refresh loops.

With this update, verifySession will return a 401 error if it detects multiple access tokens in the request, prompting a refresh request. The `RefreshPOST` API will clear cookies from the old domain if `OlderCookieDomain` is specified in the configuration, then return a 200 status. If `OlderCookieDomain` is not configured, the `RefreshPOST` API will return a 500 error with a message instructing to set `OlderCookieDomain`.


**Example:**

- `APIDomain`: 'api.example.com'
- `CookieDomain`: 'api.example.com'

**Flow:**

1. After authentication, the frontend has cookies set with `domain=api.example.com`, but the access token has expired.
2. The server updates `CookieDomain` to `.example.com`.
3. An API call requiring session with an expired access token (cookie with `domain=api.example.com`) results in a 401 response.
4. The frontend attempts to refresh the session, generating a new access token saved with `domain=.example.com`.
5. The original API call is retried, but because it sends both the old and new cookies, it again results in a 401 response.
6. The frontend tries to refresh the session with multiple access tokens:
- If `OlderCookieDomain` is not set, the refresh fails with a 500 error.
- The user remains stuck until they clear cookies manually or `OlderCookieDomain` is set.
- If `OlderCookieDomain` is set, the refresh clears the older cookie, returning a 200 response.
- The frontend retries the original API call, sending only the new cookie (`domain=.example.com`), resulting in a successful request.

## [0.18.0] - 2024-04-30

### Changes
Expand Down
67 changes: 67 additions & 0 deletions recipe/session/cookieAndHeaders.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import (
"strings"
"time"

sessionError "github.com/supertokens/supertokens-golang/recipe/session/errors"

"github.com/supertokens/supertokens-golang/supertokens"

"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
Expand Down Expand Up @@ -316,3 +318,68 @@ func getCookieName(cookie string) string {
}
return kv[0]
}

// ClearSessionCookiesFromOlderCookieDomain addresses an edge case where changing the cookieDomain config on the server can
// lead to session integrity issues. For instance, if the API server URL is 'api.example.com'
// with a cookie domain of '.example.com', and the server updates the cookie domain to 'api.example.com',
// the client may retain cookies with both '.example.com' and 'api.example.com' domains.
//
// Consequently, if the server chooses the older cookie, session invalidation occurs, potentially
// resulting in an infinite refresh loop. To fix this, users are asked to specify "OlderCookieDomain" in
// the config.
//
// This function checks for multiple cookies with the same name and clears the cookies for the older domain.
func ClearSessionCookiesFromOlderCookieDomain(req *http.Request, res http.ResponseWriter, config sessmodels.TypeNormalisedInput, userContext supertokens.UserContext) error {
allowedTransferMethod := config.GetTokenTransferMethod(req, false, userContext)

// If the transfer method is 'header', there's no need to clear cookies immediately, even if there are multiple in the request.
if allowedTransferMethod == sessmodels.HeaderTransferMethod {
return nil
}

didClearCookies := false

tokenTypes := []sessmodels.TokenType{sessmodels.AccessToken, sessmodels.RefreshToken}
for _, token := range tokenTypes {
if hasMultipleCookiesForTokenType(req, token) {
// If a request has multiple session cookies and 'olderCookieDomain' is
// unset, we can't identify the correct cookie for refreshing the session.
// Using the wrong cookie can cause an infinite refresh loop. To avoid this,
// we throw a 500 error asking the user to set 'olderCookieDomain'.
if config.OlderCookieDomain == nil {
return errors.New(`The request contains multiple session cookies. This may happen if you've changed the 'cookieDomain' value in your configuration. To clear tokens from the previous domain, set 'olderCookieDomain' in your config.`)
}

supertokens.LogDebugMessage(fmt.Sprint("ClearSessionCookiesFromOlderCookieDomain: Clearing duplicate ", token, " cookie with domain ", config.OlderCookieDomain))
config.CookieDomain = config.OlderCookieDomain
setToken(config, res, token, "", 0, sessmodels.CookieTransferMethod, req, userContext)

didClearCookies = true
}
}

if didClearCookies {
return sessionError.ClearDuplicateSessionCookiesError{
Msg: "The request contains multiple session cookies. We are clearing the cookie from OlderCookieDomain. Session will be refreshed in the next refresh call.",
}
}

return nil
}

func hasMultipleCookiesForTokenType(req *http.Request, tokenType sessmodels.TokenType) bool {
// Count of cookies with the specified token type
count := 0

// Loop through each cookie in the request
for _, cookie := range req.Cookies() {
// Check if the cookie's name matches the token type
cookieName, _ := getCookieNameFromTokenType(tokenType)
if cookie.Name == cookieName {
count++
}
}

// If count is greater than 1, then there are multiple cookies with the given token type
return count > 1
}
17 changes: 13 additions & 4 deletions recipe/session/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ package errors
import "github.com/supertokens/supertokens-golang/recipe/session/claims"

const (
UnauthorizedErrorStr = "UNAUTHORISED"
TryRefreshTokenErrorStr = "TRY_REFRESH_TOKEN"
TokenTheftDetectedErrorStr = "TOKEN_THEFT_DETECTED"
InvalidClaimsErrorStr = "INVALID_CLAIMS"
UnauthorizedErrorStr = "UNAUTHORISED"
TryRefreshTokenErrorStr = "TRY_REFRESH_TOKEN"
TokenTheftDetectedErrorStr = "TOKEN_THEFT_DETECTED"
InvalidClaimsErrorStr = "INVALID_CLAIMS"
ClearDuplicateSessionCookiesErrorStr = "CLEAR_DUPLICATE_SESSION_COOKIES"
)

// TryRefreshTokenError used for when the refresh API needs to be called
Expand Down Expand Up @@ -66,3 +67,11 @@ type InvalidClaimError struct {
func (err InvalidClaimError) Error() string {
return err.Msg
}

type ClearDuplicateSessionCookiesError struct {
Msg string
}

func (err ClearDuplicateSessionCookiesError) Error() string {
return err.Msg
}
7 changes: 7 additions & 0 deletions recipe/session/recipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,13 @@ func (r *Recipe) handleError(err error, req *http.Request, res http.ResponseWrit
supertokens.LogDebugMessage("errorHandler: returning INVALID_CLAIMS")
errs := err.(errors.InvalidClaimError)
return true, r.Config.ErrorHandlers.OnInvalidClaim(errs.InvalidClaims, req, res)
} else if defaultErrors.As(err, &errors.ClearDuplicateSessionCookiesError{}) {
supertokens.LogDebugMessage("errorHandler: returning CLEAR_DUPLICATE_SESSION_COOKIES")
// This error occurs in the `refreshPOST` API when multiple session
// cookies are found in the request and the user has set `olderCookieDomain`.
// We remove session cookies from the olderCookieDomain. The response must return `200 OK`
// to avoid logging out the user, allowing the session to continue with the valid cookie.
return true, r.Config.ErrorHandlers.OnClearDuplicateSessionCookies(err.Error(), req, res)
} else {
return r.OpenIdRecipe.RecipeModule.HandleError(err, req, res, userContext)
}
Expand Down
174 changes: 174 additions & 0 deletions recipe/session/sessionErrorHandlers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/*
* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package session

import (
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/supertokens/supertokens-golang/recipe/session/claims"
sessionErrors "github.com/supertokens/supertokens-golang/recipe/session/errors"
"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
"github.com/supertokens/supertokens-golang/supertokens"
"github.com/supertokens/supertokens-golang/test/unittesting"

"github.com/stretchr/testify/assert"
)

func TestSessionErrorHandlerOverides(t *testing.T) {
BeforeEach()

customAntiCsrfVal := "VIA_TOKEN"
configValue := supertokens.TypeInput{
Supertokens: &supertokens.ConnectionInfo{
ConnectionURI: "http://localhost:8080",
},
AppInfo: supertokens.AppInfo{
AppName: "SuperTokens",
WebsiteDomain: "supertokens.io",
APIDomain: "api.supertokens.io",
},
RecipeList: []supertokens.Recipe{
Init(&sessmodels.TypeInput{
AntiCsrf: &customAntiCsrfVal,
ErrorHandlers: &sessmodels.ErrorHandlers{
OnUnauthorised: func(message string, req *http.Request, res http.ResponseWriter) error {
res.WriteHeader(401)
res.Write([]byte("unauthorised from errorHandler"))
return nil
},
OnTokenTheftDetected: func(sessionHandle, userID string, req *http.Request, res http.ResponseWriter) error {
res.WriteHeader(403)
res.Write([]byte("token theft detected from errorHandler"))
return nil
},
OnTryRefreshToken: func(message string, req *http.Request, res http.ResponseWriter) error {
res.WriteHeader(401)
res.Write([]byte("try refresh token from errorHandler"))
return nil
},
OnInvalidClaim: func(validationErrors []claims.ClaimValidationError, req *http.Request, res http.ResponseWriter) error {
res.WriteHeader(403)
res.Write([]byte("invalid claim from errorHandler"))
return nil
},
OnClearDuplicateSessionCookies: func(message string, req *http.Request, res http.ResponseWriter) error {
res.WriteHeader(200)
res.Write([]byte("clear duplicate session cookies from errorHandler"))
return nil
},
},
GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod {
return sessmodels.CookieTransferMethod
},
}),
},
}

unittesting.StartUpST("localhost", "8080")
defer AfterEach()
err := supertokens.Init(configValue)
if err != nil {
t.Error(err.Error())
}

mux := http.NewServeMux()

mux.HandleFunc("/test/unauthorized", func(rw http.ResponseWriter, r *http.Request) {
supertokens.ErrorHandler(sessionErrors.UnauthorizedError{}, r, rw)
})

mux.HandleFunc("/test/try-refresh", func(rw http.ResponseWriter, r *http.Request) {
supertokens.ErrorHandler(sessionErrors.TryRefreshTokenError{}, r, rw)
})

mux.HandleFunc("/test/token-theft", func(rw http.ResponseWriter, r *http.Request) {
supertokens.ErrorHandler(sessionErrors.TokenTheftDetectedError{}, r, rw)
})

mux.HandleFunc("/test/claim-validation", func(rw http.ResponseWriter, r *http.Request) {
supertokens.ErrorHandler(sessionErrors.InvalidClaimError{}, r, rw)
})

mux.HandleFunc("/test/clear-duplicate-session", func(rw http.ResponseWriter, r *http.Request) {
supertokens.ErrorHandler(sessionErrors.ClearDuplicateSessionCookiesError{}, r, rw)
})

testServer := httptest.NewServer(supertokens.Middleware(mux))
defer func() {
testServer.Close()
}()

t.Run("should override session errorHandlers", func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, testServer.URL+"/test/unauthorized", nil)
assert.NoError(t, err)

res, err := http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, 401, res.StatusCode)

content, err := io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, `{"message":"unauthorised from errorHandler"}`, string(content))

req, err = http.NewRequest(http.MethodGet, testServer.URL+"/test/try-refresh", nil)
assert.NoError(t, err)

res, err = http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, 401, res.StatusCode)

content, err = io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, `{"message":"try refresh token from errorHandler"}`, string(content))

req, err = http.NewRequest(http.MethodGet, testServer.URL+"/test/token-theft", nil)
assert.NoError(t, err)

res, err = http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, 403, res.StatusCode)

content, err = io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, `{"message":"token theft detected from errorHandler"}`, string(content))

req, err = http.NewRequest(http.MethodGet, testServer.URL+"/test/claim-validation", nil)
assert.NoError(t, err)

res, err = http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, 403, res.StatusCode)

content, err = io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, `{"message":"invalid claim from errorHandler"}`, string(content))

req, err = http.NewRequest(http.MethodGet, testServer.URL+"/test/clear-duplicate-session", nil)
assert.NoError(t, err)

res, err = http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, 200, res.StatusCode)

content, err = io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, `{"message":"clear duplicate session cookies from errorHandler"}`, string(content))
})
}
Loading

0 comments on commit 2029c42

Please sign in to comment.