Skip to content
Open
Show file tree
Hide file tree
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
78 changes: 74 additions & 4 deletions api/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package api
import (
"context"
"crypto/rand"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"html/template"
"io"
"log/slog"
"net/http"
Expand All @@ -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"
Expand All @@ -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 {
Expand Down Expand Up @@ -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),
}
}
Expand Down Expand Up @@ -103,6 +119,7 @@ type OIDCAPI struct {
AutoRegister bool
LinkByUsername bool
Prompt []string
IDPName string
pendingSessions *decaymap.DecayMap[string, *pendingOIDCSession]
}

Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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)
}

Expand Down
23 changes: 23 additions & 0 deletions api/oidc_elevate.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gotify Session Elevation</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body { font-family: sans-serif; max-width: 32em; margin: 3em auto; padding: 0 1em; text-align: center; }
button { display: block; width: 100%; box-sizing: border-box; margin-top: 1em; padding: 0.75em; font-size: 1em; }
</style>
</head>
<body>
<h1>Gotify Session Elevation</h1>
<p>You are about to elevate the client session with id <b>{{.ClientID}}</b> for <b>{{.Duration}}</b>.</p>
<p>Only continue if you want to elevate this client.</p>
<form method="post" action="elevate">
<input type="hidden" name="id" value="{{.ClientID}}" />
<input type="hidden" name="durationSeconds" value="{{.DurationSeconds}}" />
<button type="submit">Continue to {{.IDPName}}</button>
</form>
<p>Close this tab to abort.</p>
</body>
</html>
72 changes: 62 additions & 10 deletions api/oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <b>%d</b> for <b>%s</b>.", 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() {
Expand Down
48 changes: 38 additions & 10 deletions auth/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,38 @@ 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
}
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 {
Expand Down Expand Up @@ -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
}
Expand All @@ -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)
}
}

Expand All @@ -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
Expand Down
18 changes: 18 additions & 0 deletions auth/authentication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading