diff --git a/api/oidc.go b/api/oidc.go index 11f02e0f2..0a847cfcf 100644 --- a/api/oidc.go +++ b/api/oidc.go @@ -3,9 +3,11 @@ package api import ( "context" "crypto/rand" + _ "embed" "encoding/hex" "errors" "fmt" + "html/template" "io" "log/slog" "net/http" @@ -15,6 +17,7 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/render" "github.com/gotify/server/v3/auth" "github.com/gotify/server/v3/config" "github.com/gotify/server/v3/database" @@ -27,6 +30,18 @@ import ( "github.com/zitadel/oidc/v3/pkg/oidc" ) +type elevateConfirmData struct { + ClientID uint + DurationSeconds int + Duration string + IDPName string +} + +//go:embed oidc_elevate.html +var elevateConfirmHTML string + +var elevateConfirmTemplate = template.Must(template.New("elevate").Parse(elevateConfirmHTML)) + func NewOIDC(conf *config.Configuration, db *database.GormDatabase, userChangeNotifier *UserChangeNotifier) *OIDCAPI { cookieKey := make([]byte, 32) if _, err := rand.Read(cookieKey); err != nil { @@ -71,6 +86,7 @@ func NewOIDC(conf *config.Configuration, db *database.GormDatabase, userChangeNo AutoRegister: conf.OIDC.AutoRegister, LinkByUsername: conf.OIDC.LinkByUsername, Prompt: conf.OIDC.Prompt, + IDPName: conf.OIDC.IDPName, pendingSessions: decaymap.NewDecayMap[string, *pendingOIDCSession](time.Now(), pendingSessionMaxAge), } } @@ -103,6 +119,7 @@ type OIDCAPI struct { AutoRegister bool LinkByUsername bool Prompt []string + IDPName string pendingSessions *decaymap.DecayMap[string, *pendingOIDCSession] } @@ -148,11 +165,12 @@ func (a *OIDCAPI) LoginHandler() gin.HandlerFunc { // // Start the OIDC flow to elevate an existing client session (browser). // -// Redirects the user to the OIDC provider's authorization endpoint. After -// successful authentication, the referenced client session is elevated for -// the requested duration. +// Redirects to the OIDC provider if the session cookie belongs to the client, +// otherwise shows a confirmation page. After successful authentication, the +// client session is elevated for the requested duration. // // --- +// produces: [text/html] // parameters: // - name: id // in: query @@ -166,6 +184,8 @@ func (a *OIDCAPI) LoginHandler() gin.HandlerFunc { // required: true // type: integer // responses: +// 200: +// description: Confirmation page // 302: // description: Redirect to OIDC provider // default: @@ -177,12 +197,62 @@ func (a *OIDCAPI) ElevateHandler(ctx *gin.Context) { if err := ctx.BindQuery(&elevate); err != nil { return } + if client := auth.GetClient(ctx); client != nil && client.ID == elevate.ClientID { + a.startElevation(ctx, &elevate) + return + } + ctx.Render(http.StatusOK, render.HTML{Template: elevateConfirmTemplate, Data: elevateConfirmData{ + ClientID: elevate.ClientID, + DurationSeconds: elevate.DurationSeconds, + Duration: model.ElevationDuration(elevate.DurationSeconds).String(), + IDPName: a.IDPName, + }}) +} + +// swagger:operation POST /auth/oidc/elevate oidc oidcElevateConfirm +// +// Confirm the elevation of a client session and start the OIDC flow (browser). +// +// --- +// consumes: [application/x-www-form-urlencoded] +// parameters: +// - name: id +// in: formData +// description: the client id to elevate +// required: true +// type: integer +// format: int64 +// - name: durationSeconds +// in: formData +// description: how long the elevation should last, in seconds +// required: true +// type: integer +// responses: +// 302: +// description: Redirect to OIDC provider +// 403: +// description: Forbidden +// schema: +// $ref: "#/definitions/Error" +// default: +// description: Error +// schema: +// $ref: "#/definitions/Error" +func (a *OIDCAPI) ElevateConfirmHandler(ctx *gin.Context) { + var elevate pendingElevation + if err := ctx.Bind(&elevate); err != nil { + return + } + a.startElevation(ctx, &elevate) +} + +func (a *OIDCAPI) startElevation(ctx *gin.Context, elevate *pendingElevation) { state, err := a.generateState() if err != nil { ctx.AbortWithError(http.StatusInternalServerError, err) return } - a.pendingSessions.Set(time.Now(), state, &pendingOIDCSession{CreatedAt: time.Now(), Elevate: &elevate}) + a.pendingSessions.Set(time.Now(), state, &pendingOIDCSession{CreatedAt: time.Now(), Elevate: elevate}) rp.AuthURLHandler(func() string { return state }, a.Provider, a.promptURLParams()...)(ctx.Writer, ctx.Request) } diff --git a/api/oidc_elevate.html b/api/oidc_elevate.html new file mode 100644 index 000000000..d0915b51e --- /dev/null +++ b/api/oidc_elevate.html @@ -0,0 +1,23 @@ + + +
+You are about to elevate the client session with id {{.ClientID}} for {{.Duration}}.
+Only continue if you want to elevate this client.
+ +Close this tab to abort.
+ + diff --git a/api/oidc_test.go b/api/oidc_test.go index 913fe21c8..4bb66e3fe 100644 --- a/api/oidc_test.go +++ b/api/oidc_test.go @@ -132,30 +132,82 @@ func (s *OIDCSuite) Test_LoginHandler_AuthURL() { } } -func (s *OIDCSuite) Test_ElevateHandler_AuthURL() { +func (s *OIDCSuite) withElevateProvider() { issuer := newDiscoveryServer(s.T()) - provider, err := rp.NewRelyingPartyOIDC( context.Background(), issuer.URL, "client", "secret", "https://gotify.example/callback", []string{"openid"}, ) assert.NoError(s.T(), err) s.a.Provider = provider s.a.Prompt = []string{"login"} + s.a.IDPName = "Example IdP" +} + +func (s *OIDCSuite) assertElevateConfirmPage(recorder *httptest.ResponseRecorder, clientID uint, duration string) { + assert.Equal(s.T(), http.StatusOK, recorder.Code) + assert.Empty(s.T(), recorder.Header().Get("Location")) + assert.Contains(s.T(), recorder.Header().Get("Content-Type"), "text/html") + assert.Contains(s.T(), recorder.Body.String(), fmt.Sprintf("You are about to elevate the client session with id %d for %s.", clientID, duration)) +} + +func (s *OIDCSuite) Test_ElevateHandler_SessionMatchesClient_RedirectsToIdP() { + s.withElevateProvider() + client := &model.Client{ID: 1, UserID: 1, Token: "t1", Name: "browser"} + assert.NoError(s.T(), s.db.CreateClient(client)) recorder := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(recorder) ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=1&durationSeconds=60", nil) + auth.RegisterClient(ctx, client) s.a.ElevateHandler(ctx) - location, err := url.Parse(recorder.Header().Get("Location")) - assert.NoError(s.T(), err) - query := location.Query() - assert.NotEmpty(s.T(), query.Get("state")) - assert.Equal(s.T(), "login", query.Get("prompt")) - assert.Equal(s.T(), "client", query.Get("client_id")) - assert.Equal(s.T(), "https://gotify.example/callback", query.Get("redirect_uri")) - assert.Equal(s.T(), "openid", query.Get("scope")) + assert.Equal(s.T(), http.StatusFound, recorder.Code) + assert.NotEmpty(s.T(), recorder.Header().Get("Location")) +} + +func (s *OIDCSuite) Test_ElevateHandler_SessionOfOtherClient_ShowsConfirmPage() { + s.withElevateProvider() + client := &model.Client{ID: 1, UserID: 1, Token: "t1", Name: "browser"} + assert.NoError(s.T(), s.db.CreateClient(client)) + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=2&durationSeconds=60", nil) + auth.RegisterClient(ctx, client) + + s.a.ElevateHandler(ctx) + + s.assertElevateConfirmPage(recorder, 2, "1m0s") +} + +func (s *OIDCSuite) Test_ElevateHandler_NoSession_ShowsConfirmPage() { + // GHSA-qcrr-392r-g62h + s.withElevateProvider() + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=77&durationSeconds=315360000", nil) + ctx.Request.Header.Set("Sec-Fetch-Site", "cross-site") + + s.a.ElevateHandler(ctx) + + s.assertElevateConfirmPage(recorder, 77, "87600h0m0s") +} + +func (s *OIDCSuite) Test_ElevateConfirmHandler_RedirectsToIdP() { + s.withElevateProvider() + + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest("POST", "/auth/oidc/elevate", strings.NewReader("id=77&durationSeconds=60")) + ctx.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + s.a.ElevateConfirmHandler(ctx) + ctx.Writer.WriteHeaderNow() + + assert.Equal(s.T(), http.StatusFound, recorder.Code) + assert.NotEmpty(s.T(), recorder.Header().Get("Location")) } func (s *OIDCSuite) Test_ResolveUser_ReturningUser_MatchedByOIDCID() { diff --git a/auth/authentication.go b/auth/authentication.go index 0e1fc3834..b72312d4d 100644 --- a/auth/authentication.go +++ b/auth/authentication.go @@ -152,6 +152,10 @@ func (a *Auth) rejectForeignOrigin(ctx *gin.Context) bool { if _, isCookie := a.readTokenFromRequest(ctx); !isCookie { return false } + return a.rejectCrossOrigin(ctx) +} + +func (a *Auth) rejectCrossOrigin(ctx *gin.Context) bool { if err := a.CrossOrigin.Check(ctx.Request); err != nil { ctx.AbortWithError(403, err) return true @@ -159,6 +163,27 @@ func (a *Auth) rejectForeignOrigin(ctx *gin.Context) bool { return false } +// OptionalClientCookie optionally registers the client of the session cookie. +func (a *Auth) OptionalClientCookie(ctx *gin.Context) { + if a.rejectCrossOrigin(ctx) { + return + } + token := a.tokenFromCookie(ctx) + if token == "" { + ctx.Next() + return + } + client, err := a.clientByToken(token) + if err != nil && !errors.Is(err, errCannotParseToken) { + ctx.AbortWithError(500, err) + return + } + if client != nil { + RegisterClient(ctx, client) + } + ctx.Next() +} + func (a *Auth) handleUser(checks ...func(*model.User) (authState, error)) func(ctx *gin.Context) (authState, error) { return func(ctx *gin.Context) (authState, error) { if name, pass, ok := ctx.Request.BasicAuth(); ok { @@ -186,18 +211,10 @@ func (a *Auth) handleUser(checks ...func(*model.User) (authState, error)) func(c func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) func(ctx *gin.Context) (authState, error) { return func(ctx *gin.Context) (authState, error) { token, isCookie := a.readTokenFromRequest(ctx) - originalToken := token if token == "" { return authStateSkip, nil } - if strings.HasPrefix(token, enhancedTokenPrefix) { - complexToken, err := ParseEnhancedToken(token) - if err != nil || !complexToken.ValidateTimestamp(timeNow().Unix()) { - return authStateSkip, err - } - token = complexToken.PublicForm() - } - client, err := a.DB.GetClientByToken(token) + client, err := a.clientByToken(token) if err != nil { return authStateSkip, err } @@ -212,7 +229,7 @@ func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) fu return authStateSkip, err } if isCookie { - SetCookie(ctx.Writer, originalToken, CookieMaxAge, a.SecureCookie) + SetCookie(ctx.Writer, token, CookieMaxAge, a.SecureCookie) } } @@ -226,6 +243,17 @@ func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) fu } } +func (a *Auth) clientByToken(token string) (*model.Client, error) { + if strings.HasPrefix(token, enhancedTokenPrefix) { + complexToken, err := ParseEnhancedToken(token) + if err != nil || !complexToken.ValidateTimestamp(timeNow().Unix()) { + return nil, err + } + token = complexToken.PublicForm() + } + return a.DB.GetClientByToken(token) +} + func (a *Auth) handleApplication(ctx *gin.Context) (authState, error) { token, isCookie := a.readTokenFromRequest(ctx) originalToken := token diff --git a/auth/authentication_test.go b/auth/authentication_test.go index fd0ce5b0c..024b47132 100644 --- a/auth/authentication_test.go +++ b/auth/authentication_test.go @@ -461,3 +461,21 @@ func (s *AuthenticationSuite) assertCsrfRequest(headers map[string]string, cooki } type fMiddleware gin.HandlerFunc + +func (s *AuthenticationSuite) TestOptionalClientCookie() { + ctx := s.assertRequest(s.auth.OptionalClientCookie, 200) + assert.Nil(s.T(), GetClient(ctx)) + + ctx = s.assertCookieRequest("clienttoken", s.auth.OptionalClientCookie, 200) + assert.NotNil(s.T(), GetClient(ctx)) + + ctx = s.assertCookieRequest(enhancedTokenPrefix+"garbage", s.auth.OptionalClientCookie, 200) + assert.Nil(s.T(), GetClient(ctx)) + + // only the cookie counts + ctx = s.assertQueryRequest("token", "clienttoken", s.auth.OptionalClientCookie, 200) + assert.Nil(s.T(), GetClient(ctx)) + + // cross-origin is rejected even without a cookie + s.assertCsrfRequest(map[string]string{"Sec-Fetch-Site": "cross-site"}, "", s.auth.OptionalClientCookie, 403) +} diff --git a/docs/spec.json b/docs/spec.json index 1aa938fe4..578d9cceb 100644 --- a/docs/spec.json +++ b/docs/spec.json @@ -813,7 +813,10 @@ }, "/auth/oidc/elevate": { "get": { - "description": "Redirects the user to the OIDC provider's authorization endpoint. After\nsuccessful authentication, the referenced client session is elevated for\nthe requested duration.", + "description": "Redirects to the OIDC provider if the session cookie belongs to the client,\notherwise shows a confirmation page. After successful authentication, the\nclient session is elevated for the requested duration.", + "produces": [ + "text/html" + ], "tags": [ "oidc" ], @@ -836,10 +839,57 @@ "required": true } ], + "responses": { + "200": { + "description": "Confirmation page" + }, + "302": { + "description": "Redirect to OIDC provider" + }, + "default": { + "description": "Error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "post": { + "consumes": [ + "application/x-www-form-urlencoded" + ], + "tags": [ + "oidc" + ], + "summary": "Confirm the elevation of a client session and start the OIDC flow (browser).", + "operationId": "oidcElevateConfirm", + "parameters": [ + { + "type": "integer", + "format": "int64", + "description": "the client id to elevate", + "name": "id", + "in": "formData", + "required": true + }, + { + "type": "integer", + "description": "how long the elevation should last, in seconds", + "name": "durationSeconds", + "in": "formData", + "required": true + } + ], "responses": { "302": { "description": "Redirect to OIDC provider" }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/Error" + } + }, "default": { "description": "Error", "schema": { diff --git a/model/elevate.go b/model/elevate.go index c155dac6d..000d26f4d 100644 --- a/model/elevate.go +++ b/model/elevate.go @@ -19,8 +19,13 @@ const maxElevation = 100 * 365 * 24 * time.Hour // ElevationTime calculates the time at which an elevation will expire. func ElevationTime(base time.Time, deltaSeconds int) time.Time { + return base.Add(ElevationDuration(deltaSeconds)) +} + +// ElevationDuration calculates how long an elevation will last. +func ElevationDuration(deltaSeconds int) time.Duration { // Prevent int64 overflow by limiting to an arbitrary high number. seconds := min(time.Duration(deltaSeconds), maxElevation/time.Second) seconds = max(seconds, -1) - return base.Add(seconds * time.Second) + return seconds * time.Second } diff --git a/router/router.go b/router/router.go index 7f71ffaeb..d71f055e5 100644 --- a/router/router.go +++ b/router/router.go @@ -135,7 +135,8 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co oidcGroup.GET("/callback", oidcHandler.CallbackHandler()) oidcGroup.POST("/external/authorize", oidcHandler.ExternalAuthorizeHandler) oidcGroup.POST("/external/token", oidcHandler.ExternalTokenHandler) - oidcGroup.GET("/elevate", oidcHandler.ElevateHandler) + oidcGroup.GET("/elevate", authentication.OptionalClientCookie, oidcHandler.ElevateHandler) + oidcGroup.POST("/elevate", authentication.OptionalClientCookie, oidcHandler.ElevateConfirmHandler) } g.Match([]string{"GET", "HEAD"}, "/health", healthHandler.Health)