Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions src/mod/auth/sso/oauth2/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package oauth2

import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -35,6 +37,7 @@ type OAuth2RouterOptions struct {
Logger *logger.Logger
Database *database.Database
OAuth2ConfigCache *ttlcache.Cache[string, *oauth2.Config]
OAuth2SessionStore *ttlcache.Cache[string, *oauth2.Token]
}

type OIDCDiscoveryDocument struct {
Expand Down Expand Up @@ -87,6 +90,11 @@ func NewOAuth2Router(options *OAuth2RouterOptions) *OAuth2Router {
)
go options.OAuth2ConfigCache.Start()

options.OAuth2SessionStore = ttlcache.New[string, *oauth2.Token](
ttlcache.WithDisableTouchOnHit[string, *oauth2.Token](),
)
go options.OAuth2SessionStore.Start()

return ar
}

Expand Down Expand Up @@ -203,6 +211,7 @@ func (ar *OAuth2Router) handleSetOAuthSettingsPOST(w http.ResponseWriter, r *htt

// Flush caches
ar.options.OAuth2ConfigCache.DeleteAll()
ar.options.OAuth2SessionStore.DeleteAll()

utils.SendOK(w)
}
Expand Down Expand Up @@ -349,15 +358,26 @@ func (ar *OAuth2Router) HandleOAuth2Auth(w http.ResponseWriter, r *http.Request)
if cookieExpiry.IsZero() || cookieExpiry.Before(time.Now()) {
cookieExpiry = time.Now().Add(time.Hour)
}
cookie := http.Cookie{Name: tokenCookie, Value: token.AccessToken, Path: "/", Expires: cookieExpiry}
//Store the token server side and only hand out an opaque session id, so the
//cookie value cannot be swapped for a token issued to another OAuth2 client
sessionIdBytes := make([]byte, 32)
if _, err := rand.Read(sessionIdBytes); err != nil {
ar.options.Logger.PrintAndLog("OAuth2", "Failed to generate session id", err)
w.WriteHeader(500)
return errors.New("internal server error")
}
sessionId := base64.RawURLEncoding.EncodeToString(sessionIdBytes)
ar.options.OAuth2SessionStore.Set(sessionId, token, time.Until(cookieExpiry))

cookie := http.Cookie{Name: tokenCookie, Value: sessionId, Path: "/", Expires: cookieExpiry, HttpOnly: true}
if scheme == "https" {
cookie.Secure = true
cookie.SameSite = http.SameSiteLaxMode
}
w.Header().Add("Set-Cookie", cookie.String())

if ar.options.OAuth2CodeChallengeMethod == "PKCE" || ar.options.OAuth2CodeChallengeMethod == "PKCE_S256" {
cookie := http.Cookie{Name: verifierCookie, Value: "", Path: "/", Expires: time.Now().Add(-time.Hour * 1)}
cookie := http.Cookie{Name: verifierCookie, Value: "", Path: "/", Expires: time.Now().Add(-time.Hour * 1), HttpOnly: true}
if scheme == "https" {
cookie.Secure = true
cookie.SameSite = http.SameSiteLaxMode
Expand All @@ -382,11 +402,12 @@ func (ar *OAuth2Router) HandleOAuth2Auth(w http.ResponseWriter, r *http.Request)
unauthorized := false
cookie, err := r.Cookie(tokenCookie)
if err == nil {
if cookie.Value == "" {
session := ar.options.OAuth2SessionStore.Get(cookie.Value)
if cookie.Value == "" || session == nil {
unauthorized = true
} else {
ctx := context.Background()
client := oauthConfig.Client(ctx, &oauth2.Token{AccessToken: cookie.Value})
client := oauthConfig.Client(ctx, session.Value())
req, err := client.Get(ar.options.OAuth2UserInfoUrl)
if err != nil {
ar.options.Logger.PrintAndLog("OAuth2", "Failed to get user info", err)
Expand All @@ -405,7 +426,7 @@ func (ar *OAuth2Router) HandleOAuth2Auth(w http.ResponseWriter, r *http.Request)
state := url.QueryEscape(reqUrl)
var url string
if ar.options.OAuth2CodeChallengeMethod == "PKCE" || ar.options.OAuth2CodeChallengeMethod == "PKCE_S256" {
cookie := http.Cookie{Name: verifierCookie, Value: oauth2.GenerateVerifier(), Path: "/", Expires: time.Now().Add(time.Hour * 1)}
cookie := http.Cookie{Name: verifierCookie, Value: oauth2.GenerateVerifier(), Path: "/", Expires: time.Now().Add(time.Hour * 1), HttpOnly: true}
if scheme == "https" {
cookie.Secure = true
cookie.SameSite = http.SameSiteLaxMode
Expand Down
Loading