Skip to content

Commit 2affea1

Browse files
authored
Merge pull request #1094 from gotify/elevate
Confirm session elevation
2 parents 912af9f + c293afb commit 2affea1

8 files changed

Lines changed: 274 additions & 27 deletions

File tree

‎api/oidc.go‎

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ package api
33
import (
44
"context"
55
"crypto/rand"
6+
_ "embed"
67
"encoding/hex"
78
"errors"
89
"fmt"
10+
"html/template"
911
"io"
1012
"log/slog"
1113
"net/http"
@@ -15,6 +17,7 @@ import (
1517
"time"
1618

1719
"github.com/gin-gonic/gin"
20+
"github.com/gin-gonic/gin/render"
1821
"github.com/gotify/server/v3/auth"
1922
"github.com/gotify/server/v3/config"
2023
"github.com/gotify/server/v3/database"
@@ -27,6 +30,18 @@ import (
2730
"github.com/zitadel/oidc/v3/pkg/oidc"
2831
)
2932

33+
type elevateConfirmData struct {
34+
ClientID uint
35+
DurationSeconds int
36+
Duration string
37+
IDPName string
38+
}
39+
40+
//go:embed oidc_elevate.html
41+
var elevateConfirmHTML string
42+
43+
var elevateConfirmTemplate = template.Must(template.New("elevate").Parse(elevateConfirmHTML))
44+
3045
func NewOIDC(conf *config.Configuration, db *database.GormDatabase, userChangeNotifier *UserChangeNotifier) *OIDCAPI {
3146
cookieKey := make([]byte, 32)
3247
if _, err := rand.Read(cookieKey); err != nil {
@@ -71,6 +86,7 @@ func NewOIDC(conf *config.Configuration, db *database.GormDatabase, userChangeNo
7186
AutoRegister: conf.OIDC.AutoRegister,
7287
LinkByUsername: conf.OIDC.LinkByUsername,
7388
Prompt: conf.OIDC.Prompt,
89+
IDPName: conf.OIDC.IDPName,
7490
pendingSessions: decaymap.NewDecayMap[string, *pendingOIDCSession](time.Now(), pendingSessionMaxAge),
7591
}
7692
}
@@ -103,6 +119,7 @@ type OIDCAPI struct {
103119
AutoRegister bool
104120
LinkByUsername bool
105121
Prompt []string
122+
IDPName string
106123
pendingSessions *decaymap.DecayMap[string, *pendingOIDCSession]
107124
}
108125

@@ -148,11 +165,12 @@ func (a *OIDCAPI) LoginHandler() gin.HandlerFunc {
148165
//
149166
// Start the OIDC flow to elevate an existing client session (browser).
150167
//
151-
// Redirects the user to the OIDC provider's authorization endpoint. After
152-
// successful authentication, the referenced client session is elevated for
153-
// the requested duration.
168+
// Redirects to the OIDC provider if the session cookie belongs to the client,
169+
// otherwise shows a confirmation page. After successful authentication, the
170+
// client session is elevated for the requested duration.
154171
//
155172
// ---
173+
// produces: [text/html]
156174
// parameters:
157175
// - name: id
158176
// in: query
@@ -166,6 +184,8 @@ func (a *OIDCAPI) LoginHandler() gin.HandlerFunc {
166184
// required: true
167185
// type: integer
168186
// responses:
187+
// 200:
188+
// description: Confirmation page
169189
// 302:
170190
// description: Redirect to OIDC provider
171191
// default:
@@ -177,12 +197,62 @@ func (a *OIDCAPI) ElevateHandler(ctx *gin.Context) {
177197
if err := ctx.BindQuery(&elevate); err != nil {
178198
return
179199
}
200+
if client := auth.GetClient(ctx); client != nil && client.ID == elevate.ClientID {
201+
a.startElevation(ctx, &elevate)
202+
return
203+
}
204+
ctx.Render(http.StatusOK, render.HTML{Template: elevateConfirmTemplate, Data: elevateConfirmData{
205+
ClientID: elevate.ClientID,
206+
DurationSeconds: elevate.DurationSeconds,
207+
Duration: model.ElevationDuration(elevate.DurationSeconds).String(),
208+
IDPName: a.IDPName,
209+
}})
210+
}
211+
212+
// swagger:operation POST /auth/oidc/elevate oidc oidcElevateConfirm
213+
//
214+
// Confirm the elevation of a client session and start the OIDC flow (browser).
215+
//
216+
// ---
217+
// consumes: [application/x-www-form-urlencoded]
218+
// parameters:
219+
// - name: id
220+
// in: formData
221+
// description: the client id to elevate
222+
// required: true
223+
// type: integer
224+
// format: int64
225+
// - name: durationSeconds
226+
// in: formData
227+
// description: how long the elevation should last, in seconds
228+
// required: true
229+
// type: integer
230+
// responses:
231+
// 302:
232+
// description: Redirect to OIDC provider
233+
// 403:
234+
// description: Forbidden
235+
// schema:
236+
// $ref: "#/definitions/Error"
237+
// default:
238+
// description: Error
239+
// schema:
240+
// $ref: "#/definitions/Error"
241+
func (a *OIDCAPI) ElevateConfirmHandler(ctx *gin.Context) {
242+
var elevate pendingElevation
243+
if err := ctx.Bind(&elevate); err != nil {
244+
return
245+
}
246+
a.startElevation(ctx, &elevate)
247+
}
248+
249+
func (a *OIDCAPI) startElevation(ctx *gin.Context, elevate *pendingElevation) {
180250
state, err := a.generateState()
181251
if err != nil {
182252
ctx.AbortWithError(http.StatusInternalServerError, err)
183253
return
184254
}
185-
a.pendingSessions.Set(time.Now(), state, &pendingOIDCSession{CreatedAt: time.Now(), Elevate: &elevate})
255+
a.pendingSessions.Set(time.Now(), state, &pendingOIDCSession{CreatedAt: time.Now(), Elevate: elevate})
186256
rp.AuthURLHandler(func() string { return state }, a.Provider, a.promptURLParams()...)(ctx.Writer, ctx.Request)
187257
}
188258

‎api/oidc_elevate.html‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<title>Gotify Session Elevation</title>
5+
<meta charset="UTF-8" />
6+
<meta name="viewport" content="width=device-width,initial-scale=1" />
7+
<style>
8+
body { font-family: sans-serif; max-width: 32em; margin: 3em auto; padding: 0 1em; text-align: center; }
9+
button { display: block; width: 100%; box-sizing: border-box; margin-top: 1em; padding: 0.75em; font-size: 1em; }
10+
</style>
11+
</head>
12+
<body>
13+
<h1>Gotify Session Elevation</h1>
14+
<p>You are about to elevate the client session with id <b>{{.ClientID}}</b> for <b>{{.Duration}}</b>.</p>
15+
<p>Only continue if you want to elevate this client.</p>
16+
<form method="post" action="elevate">
17+
<input type="hidden" name="id" value="{{.ClientID}}" />
18+
<input type="hidden" name="durationSeconds" value="{{.DurationSeconds}}" />
19+
<button type="submit">Continue to {{.IDPName}}</button>
20+
</form>
21+
<p>Close this tab to abort.</p>
22+
</body>
23+
</html>

‎api/oidc_test.go‎

Lines changed: 62 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -132,30 +132,82 @@ func (s *OIDCSuite) Test_LoginHandler_AuthURL() {
132132
}
133133
}
134134

135-
func (s *OIDCSuite) Test_ElevateHandler_AuthURL() {
135+
func (s *OIDCSuite) withElevateProvider() {
136136
issuer := newDiscoveryServer(s.T())
137-
138137
provider, err := rp.NewRelyingPartyOIDC(
139138
context.Background(), issuer.URL, "client", "secret", "https://gotify.example/callback", []string{"openid"},
140139
)
141140
assert.NoError(s.T(), err)
142141
s.a.Provider = provider
143142
s.a.Prompt = []string{"login"}
143+
s.a.IDPName = "Example IdP"
144+
}
145+
146+
func (s *OIDCSuite) assertElevateConfirmPage(recorder *httptest.ResponseRecorder, clientID uint, duration string) {
147+
assert.Equal(s.T(), http.StatusOK, recorder.Code)
148+
assert.Empty(s.T(), recorder.Header().Get("Location"))
149+
assert.Contains(s.T(), recorder.Header().Get("Content-Type"), "text/html")
150+
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))
151+
}
152+
153+
func (s *OIDCSuite) Test_ElevateHandler_SessionMatchesClient_RedirectsToIdP() {
154+
s.withElevateProvider()
155+
client := &model.Client{ID: 1, UserID: 1, Token: "t1", Name: "browser"}
156+
assert.NoError(s.T(), s.db.CreateClient(client))
144157

145158
recorder := httptest.NewRecorder()
146159
ctx, _ := gin.CreateTestContext(recorder)
147160
ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=1&durationSeconds=60", nil)
161+
auth.RegisterClient(ctx, client)
148162

149163
s.a.ElevateHandler(ctx)
150164

151-
location, err := url.Parse(recorder.Header().Get("Location"))
152-
assert.NoError(s.T(), err)
153-
query := location.Query()
154-
assert.NotEmpty(s.T(), query.Get("state"))
155-
assert.Equal(s.T(), "login", query.Get("prompt"))
156-
assert.Equal(s.T(), "client", query.Get("client_id"))
157-
assert.Equal(s.T(), "https://gotify.example/callback", query.Get("redirect_uri"))
158-
assert.Equal(s.T(), "openid", query.Get("scope"))
165+
assert.Equal(s.T(), http.StatusFound, recorder.Code)
166+
assert.NotEmpty(s.T(), recorder.Header().Get("Location"))
167+
}
168+
169+
func (s *OIDCSuite) Test_ElevateHandler_SessionOfOtherClient_ShowsConfirmPage() {
170+
s.withElevateProvider()
171+
client := &model.Client{ID: 1, UserID: 1, Token: "t1", Name: "browser"}
172+
assert.NoError(s.T(), s.db.CreateClient(client))
173+
174+
recorder := httptest.NewRecorder()
175+
ctx, _ := gin.CreateTestContext(recorder)
176+
ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=2&durationSeconds=60", nil)
177+
auth.RegisterClient(ctx, client)
178+
179+
s.a.ElevateHandler(ctx)
180+
181+
s.assertElevateConfirmPage(recorder, 2, "1m0s")
182+
}
183+
184+
func (s *OIDCSuite) Test_ElevateHandler_NoSession_ShowsConfirmPage() {
185+
// GHSA-qcrr-392r-g62h
186+
s.withElevateProvider()
187+
188+
recorder := httptest.NewRecorder()
189+
ctx, _ := gin.CreateTestContext(recorder)
190+
ctx.Request = httptest.NewRequest("GET", "/auth/oidc/elevate?id=77&durationSeconds=315360000", nil)
191+
ctx.Request.Header.Set("Sec-Fetch-Site", "cross-site")
192+
193+
s.a.ElevateHandler(ctx)
194+
195+
s.assertElevateConfirmPage(recorder, 77, "87600h0m0s")
196+
}
197+
198+
func (s *OIDCSuite) Test_ElevateConfirmHandler_RedirectsToIdP() {
199+
s.withElevateProvider()
200+
201+
recorder := httptest.NewRecorder()
202+
ctx, _ := gin.CreateTestContext(recorder)
203+
ctx.Request = httptest.NewRequest("POST", "/auth/oidc/elevate", strings.NewReader("id=77&durationSeconds=60"))
204+
ctx.Request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
205+
206+
s.a.ElevateConfirmHandler(ctx)
207+
ctx.Writer.WriteHeaderNow()
208+
209+
assert.Equal(s.T(), http.StatusFound, recorder.Code)
210+
assert.NotEmpty(s.T(), recorder.Header().Get("Location"))
159211
}
160212

161213
func (s *OIDCSuite) Test_ResolveUser_ReturningUser_MatchedByOIDCID() {

‎auth/authentication.go‎

Lines changed: 38 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,38 @@ func (a *Auth) rejectForeignOrigin(ctx *gin.Context) bool {
152152
if _, isCookie := a.readTokenFromRequest(ctx); !isCookie {
153153
return false
154154
}
155+
return a.rejectCrossOrigin(ctx)
156+
}
157+
158+
func (a *Auth) rejectCrossOrigin(ctx *gin.Context) bool {
155159
if err := a.CrossOrigin.Check(ctx.Request); err != nil {
156160
ctx.AbortWithError(403, err)
157161
return true
158162
}
159163
return false
160164
}
161165

166+
// OptionalClientCookie optionally registers the client of the session cookie.
167+
func (a *Auth) OptionalClientCookie(ctx *gin.Context) {
168+
if a.rejectCrossOrigin(ctx) {
169+
return
170+
}
171+
token := a.tokenFromCookie(ctx)
172+
if token == "" {
173+
ctx.Next()
174+
return
175+
}
176+
client, err := a.clientByToken(token)
177+
if err != nil && !errors.Is(err, errCannotParseToken) {
178+
ctx.AbortWithError(500, err)
179+
return
180+
}
181+
if client != nil {
182+
RegisterClient(ctx, client)
183+
}
184+
ctx.Next()
185+
}
186+
162187
func (a *Auth) handleUser(checks ...func(*model.User) (authState, error)) func(ctx *gin.Context) (authState, error) {
163188
return func(ctx *gin.Context) (authState, error) {
164189
if name, pass, ok := ctx.Request.BasicAuth(); ok {
@@ -186,18 +211,10 @@ func (a *Auth) handleUser(checks ...func(*model.User) (authState, error)) func(c
186211
func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) func(ctx *gin.Context) (authState, error) {
187212
return func(ctx *gin.Context) (authState, error) {
188213
token, isCookie := a.readTokenFromRequest(ctx)
189-
originalToken := token
190214
if token == "" {
191215
return authStateSkip, nil
192216
}
193-
if strings.HasPrefix(token, enhancedTokenPrefix) {
194-
complexToken, err := ParseEnhancedToken(token)
195-
if err != nil || !complexToken.ValidateTimestamp(timeNow().Unix()) {
196-
return authStateSkip, err
197-
}
198-
token = complexToken.PublicForm()
199-
}
200-
client, err := a.DB.GetClientByToken(token)
217+
client, err := a.clientByToken(token)
201218
if err != nil {
202219
return authStateSkip, err
203220
}
@@ -212,7 +229,7 @@ func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) fu
212229
return authStateSkip, err
213230
}
214231
if isCookie {
215-
SetCookie(ctx.Writer, originalToken, CookieMaxAge, a.SecureCookie)
232+
SetCookie(ctx.Writer, token, CookieMaxAge, a.SecureCookie)
216233
}
217234
}
218235

@@ -226,6 +243,17 @@ func (a *Auth) handleClient(checks ...func(*model.Client) (authState, error)) fu
226243
}
227244
}
228245

246+
func (a *Auth) clientByToken(token string) (*model.Client, error) {
247+
if strings.HasPrefix(token, enhancedTokenPrefix) {
248+
complexToken, err := ParseEnhancedToken(token)
249+
if err != nil || !complexToken.ValidateTimestamp(timeNow().Unix()) {
250+
return nil, err
251+
}
252+
token = complexToken.PublicForm()
253+
}
254+
return a.DB.GetClientByToken(token)
255+
}
256+
229257
func (a *Auth) handleApplication(ctx *gin.Context) (authState, error) {
230258
token, isCookie := a.readTokenFromRequest(ctx)
231259
originalToken := token

‎auth/authentication_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,3 +461,21 @@ func (s *AuthenticationSuite) assertCsrfRequest(headers map[string]string, cooki
461461
}
462462

463463
type fMiddleware gin.HandlerFunc
464+
465+
func (s *AuthenticationSuite) TestOptionalClientCookie() {
466+
ctx := s.assertRequest(s.auth.OptionalClientCookie, 200)
467+
assert.Nil(s.T(), GetClient(ctx))
468+
469+
ctx = s.assertCookieRequest("clienttoken", s.auth.OptionalClientCookie, 200)
470+
assert.NotNil(s.T(), GetClient(ctx))
471+
472+
ctx = s.assertCookieRequest(enhancedTokenPrefix+"garbage", s.auth.OptionalClientCookie, 200)
473+
assert.Nil(s.T(), GetClient(ctx))
474+
475+
// only the cookie counts
476+
ctx = s.assertQueryRequest("token", "clienttoken", s.auth.OptionalClientCookie, 200)
477+
assert.Nil(s.T(), GetClient(ctx))
478+
479+
// cross-origin is rejected even without a cookie
480+
s.assertCsrfRequest(map[string]string{"Sec-Fetch-Site": "cross-site"}, "", s.auth.OptionalClientCookie, 403)
481+
}

0 commit comments

Comments
 (0)