diff --git a/CHANGELOG.md b/CHANGELOG.md index d5c8a43..8f9c75e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **`tmbSessionURL` (default unset).** Token-mediating backend endpoint for + single-page apps (draft-ietf-oauth-browser-based-apps). Setting a path + enables it, authenticated by the session cookie: `GET` returns the user, + groups, roles, the claims named in `tmbClaims` (default none) and the + access token; `POST` forces a refresh first. See [TMB.md](docs/TMB.md). + - **`allowUnauthenticatedPreflight` (default `false`).** Every `OPTIONS` request needs authentication by default, as in the last release. Set the option to `true` to let a genuine CORS preflight reach the backend diff --git a/README.md b/README.md index d565aa0..442c777 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ Full reference in [docs/CONFIGURATION.md](docs/CONFIGURATION.md). | `refreshGracePeriodSeconds` | `60` | Proactively refresh tokens this many seconds before expiry. | | `maxRefreshTokenAgeSeconds` | `21600` | Heuristic max stored refresh-token lifetime (6h). Past this, the plugin treats the RT as expired without contacting the IdP — returns 401 to AJAX, full re-auth on navigations. Set `0` to disable. Tune to match your IdP's RT TTL. | | `rateLimit` | `100` | Requests/sec. Min `10`. | -| `perSourceLoginRateLimit` | `0` (off) | Throttle OIDC auth events (authorization-code callback + login initiation) per external client source, auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources (proxies, in-cluster) are never throttled. `0` disables. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. | +| `perSourceLoginRateLimit` | `0` (off) | Throttle OIDC auth events (authorization-code callback, login initiation and forced refreshes at the `tmbSessionURL` endpoint) per external client source, auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources (proxies, in-cluster) are never throttled. `0` disables. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. | | `logLevel` | `info` | `debug`, `info`, `error`. | | `audience` | `clientID`, or `resource` if set | Custom access-token audience (Auth0 custom APIs). | | `resource` | none | RFC 8707 resource indicator, alternative to `audience` for supporting IdPs (see [docs/RFC8707.md](docs/RFC8707.md)). | @@ -151,6 +151,7 @@ Full reference in [docs/CONFIGURATION.md](docs/CONFIGURATION.md). | `clientAssertionAlg` | `RS256` | JWS alg for `private_key_jwt`. Supported: `RS256/384/512`, `PS256/384/512`, `ES256/384/512`. | | `enableBackchannelLogout` / `backchannelLogoutURL` | `false` / none | OIDC Back-Channel Logout (server-to-server). | | `enableFrontchannelLogout` / `frontchannelLogoutURL` | `false` / none | OIDC Front-Channel Logout (iframe). | +| `tmbSessionURL` | none | Path (e.g. `/auth/session`) of an endpoint for SPAs, authenticated by the session cookie: `GET` returns session info and the access token, `POST` forces a refresh. Setting it enables the endpoint; `tmbClaims` lists extra ID-token claims to return. See [docs/TMB.md](docs/TMB.md). | | `redis` | disabled | See [docs/REDIS.md](docs/REDIS.md). | | `dynamicClientRegistration` | disabled | See [docs/DCR.md](docs/DCR.md). | diff --git a/access_token_expiry_test.go b/access_token_expiry_test.go new file mode 100644 index 0000000..da1876d --- /dev/null +++ b/access_token_expiry_test.go @@ -0,0 +1,153 @@ +package traefikoidc + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAccessTokenExpiry(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + jwtWithExp := makeTestJWT(t, map[string]interface{}{"exp": float64(1_700_007_200)}) + jwtNoExp := makeTestJWT(t, map[string]interface{}{"sub": "u"}) + + cases := []struct { + name string + tr *TokenResponse + want int64 + }{ + {"nil response", nil, 0}, + {"expires_in from the response", &TokenResponse{AccessToken: "opaque-access-token-0123456789", ExpiresIn: 1800}, 1_700_001_800}, + {"expires_in wins over the JWT exp", &TokenResponse{AccessToken: jwtWithExp, ExpiresIn: 60}, 1_700_000_060}, + {"JWT exp when the response has no expires_in", &TokenResponse{AccessToken: jwtWithExp}, 1_700_007_200}, + {"opaque token without expires_in", &TokenResponse{AccessToken: "opaque-access-token-0123456789"}, 0}, + {"JWT without exp and no expires_in", &TokenResponse{AccessToken: jwtNoExp}, 0}, + {"non-positive expires_in is ignored", &TokenResponse{AccessToken: jwtWithExp, ExpiresIn: -5}, 1_700_007_200}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + assert.Equal(t, c.want, accessTokenExpiry(c.tr, now)) + }) + } +} + +// saveAndReload stores sd's state and loads it back through a fresh request, +// the way a following request would see it. +func saveAndReload(t *testing.T, sm *SessionManager, sd *SessionData) *SessionData { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + require.NoError(t, sd.Save(req, rec)) + next := httptest.NewRequest(http.MethodGet, "/", nil) + for _, c := range rec.Result().Cookies() { + next.AddCookie(c) + } + loaded, err := sm.GetSession(next) + require.NoError(t, err) + return loaded +} + +func TestSessionAccessTokenExpiresAt(t *testing.T) { + const tokenA = "test-access-token-0123456789abcdefghijklmnopqrstuvwxyz" + const tokenB = "other-access-token-0123456789abcdefghijklmnopqrstuvwxyz" + exp := time.Now().Add(30 * time.Minute).Unix() + + for _, storage := range []struct { + name string + combined bool + }{{"combined cookie storage", true}, {"legacy cookie storage", false}} { + t.Run("survives a save and reload with "+storage.name, func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.useCombinedStorage = storage.combined + sd.SetAccessToken(tokenA) + sd.SetAccessTokenExpiresAt(tokenA, exp) + + loaded := saveAndReload(t, sm, sd) + assert.Equal(t, tokenA, loaded.GetAccessToken()) + assert.Equal(t, exp, loaded.GetAccessTokenExpiresAt()) + }) + } + + t.Run("a session saved without one reports unknown", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.SetAccessToken(tokenA) + assert.Zero(t, saveAndReload(t, sm, sd).GetAccessTokenExpiresAt()) + }) + + t.Run("the expiry belongs to its token", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + + sd.SetAccessToken(tokenA) + sd.SetAccessTokenExpiresAt(tokenA, exp) + sd.SetAccessToken(tokenA) // unchanged token keeps its expiry + assert.Equal(t, exp, sd.GetAccessTokenExpiresAt()) + + sd.SetAccessToken(tokenB) // a different token drops it + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + + sd.SetAccessTokenExpiresAt(tokenB, exp) + sd.SetAccessToken("") // clearing the token drops it + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + }) + + t.Run("a non-positive value clears it", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.SetAccessToken(tokenA) + sd.SetAccessTokenExpiresAt(tokenA, exp) + sd.SetAccessTokenExpiresAt(tokenA, 0) + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + }) + + t.Run("does not leak into the next user of a pooled session", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.SetAccessToken(tokenA) + sd.SetAccessTokenExpiresAt(tokenA, exp) + sd.Reset() + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + }) + + t.Run("a failed store keeps the previous token and its expiry", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.SetAccessToken(tokenA) + sd.SetAccessTokenExpiresAt(tokenA, exp) + + oversized := incompressibleToken(200 * 1024) + sd.SetAccessToken(oversized) // too large even after compression: not stored + sd.SetAccessTokenExpiresAt(oversized, exp+3600) + + assert.Equal(t, tokenA, sd.GetAccessToken()) + assert.Equal(t, exp, sd.GetAccessTokenExpiresAt()) + }) + + t.Run("an expiry for a token that is not stored is ignored", func(t *testing.T) { + sm := createTestSessionManager(t) + sd, err := sm.GetSession(httptest.NewRequest(http.MethodGet, "/", nil)) + require.NoError(t, err) + sd.SetAccessToken(tokenA) + + sd.SetAccessTokenExpiresAt(tokenB, exp) + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + sd.SetAccessTokenExpiresAt("", exp) + assert.Zero(t, sd.GetAccessTokenExpiresAt()) + + sd.SetAccessTokenExpiresAt(tokenA, exp) + sd.SetAccessTokenExpiresAt(tokenB, 0) // cannot clear another token's expiry + assert.Equal(t, exp, sd.GetAccessTokenExpiresAt()) + }) +} diff --git a/auth_flow.go b/auth_flow.go index 8f84eb2..9167111 100644 --- a/auth_flow.go +++ b/auth_flow.go @@ -444,6 +444,7 @@ func (t *TraefikOidc) handleCallback(rw http.ResponseWriter, req *http.Request, session.SetUserIdentifier(userIdentifier) session.SetIDToken(tokenResponse.IDToken) session.SetAccessToken(tokenResponse.AccessToken) + session.SetAccessTokenExpiresAt(tokenResponse.AccessToken, accessTokenExpiry(tokenResponse, time.Now())) session.SetRefreshToken(tokenResponse.RefreshToken) session.SetCSRF("") diff --git a/auth_flow_behaviour_test.go b/auth_flow_behaviour_test.go index 8996dfe..e66f84d 100644 --- a/auth_flow_behaviour_test.go +++ b/auth_flow_behaviour_test.go @@ -6,6 +6,7 @@ import ( "net/http/httptest" "net/url" "testing" + "time" "github.com/stretchr/testify/suite" ) @@ -685,6 +686,60 @@ func (s *AuthFlowBehaviourSuite) TestHandleCallback_SuccessfulAuthentication() { mockVerifier.AssertVerifyTokenCalled(s.T()) } +// TestHandleCallback_RecordsAccessTokenExpiry checks that a successful login +// records the access token's expiry from the token response's expires_in. +func (s *AuthFlowBehaviourSuite) TestHandleCallback_RecordsAccessTokenExpiry() { + sessionManager, err := NewSessionManager("test-encryption-key-32-bytes-long!!", false, "", "", 0, s.logger) + s.Require().NoError(err) + defer sessionManager.Shutdown() + + s.tOidc.sessionManager = sessionManager + s.tOidc.allowedUsers = nil + + nonce := "test-nonce-12345" + idToken := "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiZW1haWwiOiJ0ZXN0QGV4YW1wbGUuY29tIiwibm9uY2UiOiJ0ZXN0LW5vbmNlLTEyMzQ1IiwiaWF0IjoxNTE2MjM5MDIyfQ.signature" + const opaqueAccessToken = "opaque-access-token-0123456789abcdef" + s.tOidc.tokenExchanger = &EnhancedMockTokenExchanger{ + ExchangeResponse: &TokenResponse{ + AccessToken: opaqueAccessToken, // opaque: only expires_in can say when it expires + RefreshToken: "refresh-token-value-0123456789abcdef", + IDToken: idToken, + ExpiresIn: 1800, + }, + } + s.tOidc.tokenVerifier = &EnhancedMockTokenVerifier{} + s.tOidc.extractClaimsFunc = func(token string) (map[string]interface{}, error) { + return map[string]interface{}{"sub": "1234567890", "email": "test@example.com", "nonce": nonce}, nil + } + + csrfToken := "valid-csrf-token" + req := httptest.NewRequest(http.MethodGet, "/callback?code=auth-code&state="+csrfToken, nil) + rw := httptest.NewRecorder() + session, err := sessionManager.GetSession(req) + s.Require().NoError(err) + session.SetCSRF(csrfToken) + session.SetNonce(nonce) + s.Require().NoError(session.Save(req, rw)) + session.returnToPoolSafely() + + req2 := httptest.NewRequest(http.MethodGet, "/callback?code=auth-code&state="+csrfToken, nil) + for _, cookie := range rw.Result().Cookies() { + req2.AddCookie(cookie) + } + rw2 := httptest.NewRecorder() + s.tOidc.handleCallback(rw2, req2, "https://example.com/callback") + s.Require().Equal(http.StatusFound, rw2.Code) + + req3 := httptest.NewRequest(http.MethodGet, "/", nil) + for _, cookie := range rw2.Result().Cookies() { + req3.AddCookie(cookie) + } + loaded, err := sessionManager.GetSession(req3) + s.Require().NoError(err) + s.Equal(opaqueAccessToken, loaded.GetAccessToken()) + s.InDelta(time.Now().Add(30*time.Minute).Unix(), loaded.GetAccessTokenExpiresAt(), 5) +} + // TestHandleExpiredToken tests expired token handling func (s *AuthFlowBehaviourSuite) TestHandleExpiredToken() { sessionManager, err := NewSessionManager( diff --git a/cmd/yaegicheck/main.go b/cmd/yaegicheck/main.go index 85e5b52..b46d494 100644 --- a/cmd/yaegicheck/main.go +++ b/cmd/yaegicheck/main.go @@ -24,6 +24,7 @@ package main import ( "context" "encoding/base64" + "encoding/json" "errors" "fmt" "io" @@ -39,6 +40,7 @@ import ( oidc "github.com/lukaszraczylo/traefikoidc" recovery "github.com/lukaszraczylo/traefikoidc/internal/recovery" + fixtures "github.com/lukaszraczylo/traefikoidc/internal/testutil/fixtures" servers "github.com/lukaszraczylo/traefikoidc/internal/testutil/servers" ) @@ -141,6 +143,8 @@ func main() { runCheck("issue162-websocket-forwards-header-templates", checkIssue162WebSocketHeaderTemplates) runCheck("tojson-header-template", checkToJsonHeaderTemplate) runCheck("streaming-refresh-revoked-grant-rejected", checkStreamingRefreshRevokedGrant) + runCheck("tmb-endpoints-invalid-session", checkTMBEndpointsUnderYaegi) + runCheck("tmb-endpoint-get-and-forced-refresh", checkTMBSuccessUnderYaegi) fmt.Println("OK: all yaegi regression checks passed") } @@ -982,6 +986,268 @@ func checkStreamingRefreshRevokedGrant() (string, error) { return "", nil } +// checkTMBEndpointsUnderYaegi drives the token-mediating endpoints through the real +// middleware under the interpreter: with no session cookie, and with a +// session whose refresh the IdP rejects (invalid_grant), both endpoints must +// answer a JSON 401 invalid_session, never redirect and never reach next. +func checkTMBEndpointsUnderYaegi() (string, error) { + idpCfg := servers.DefaultConfig() + idpCfg.RefreshError = &servers.OIDCError{Error: "invalid_grant"} + idp := servers.NewOIDCServer(idpCfg) + defer idp.Close() + + cfg := oidc.CreateConfig() + cfg.ProviderURL = idp.URL + cfg.ClientID = "yaegi-check-tmb-client" + cfg.ClientSecret = "yaegi-check-tmb-secret" + cfg.CallbackURL = "/oauth2/callback" + cfg.SessionEncryptionKey = "0123456789abcdef0123456789abcdef" + cfg.TMBSessionURL = "/auth/session" + + reached := false + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached = true + }) + h, err := oidc.New(context.Background(), next, cfg, "yaegi-check-tmb") + if err != nil { + return "", fmt.Errorf("New: %w", err) + } + if closer, ok := h.(interface{ Close() error }); ok { + defer closer.Close() + } + // A normal request first, so provider metadata (token endpoint) is known. + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil)) + reached = false + + expect := func(label string, req *http.Request) error { + rw := httptest.NewRecorder() + h.ServeHTTP(rw, req) + if reached { + return fmt.Errorf("%s: next reached", label) + } + if rw.Code != http.StatusUnauthorized { + return fmt.Errorf("%s: status = %d, want 401 (body %q)", label, rw.Code, rw.Body.String()) + } + if loc := rw.Header().Get("Location"); loc != "" { + return fmt.Errorf("%s: unexpected redirect to %q", label, loc) + } + var body map[string]interface{} + if err := json.Unmarshal(rw.Body.Bytes(), &body); err != nil { + return fmt.Errorf("%s: body is not JSON: %v", label, err) + } + if body["error"] != "invalid_session" { + return fmt.Errorf("%s: error = %v, want invalid_session", label, body["error"]) + } + return nil + } + + for _, method := range []string{"GET", "POST"} { + if err := expect("no-cookie "+method, httptest.NewRequest(method, "/auth/session", nil)); err != nil { + return "", err + } + } + + sm, err := oidc.NewSessionManager(cfg.SessionEncryptionKey, cfg.ForceHTTPS, cfg.CookieDomain, cfg.CookiePrefix, time.Duration(cfg.SessionMaxAge)*time.Second, oidc.NewLogger("error")) + if err != nil { + return "", fmt.Errorf("NewSessionManager: %w", err) + } + defer sm.Shutdown() + setupReq := httptest.NewRequest("GET", "/", nil) + session, err := sm.GetSession(setupReq) + if err != nil { + return "", fmt.Errorf("GetSession: %w", err) + } + if err := session.SetAuthenticated(true); err != nil { + return "", fmt.Errorf("SetAuthenticated: %w", err) + } + session.SetUserIdentifier("alice@example.com") + // Built at runtime because a JWT literal trips the pre-commit secret scanner. + b64 := base64.RawURLEncoding.EncodeToString + sig := make([]byte, 32) + for i := range sig { + sig[i] = byte(i + 1) + } + payload := fmt.Sprintf(`{"email":"alice@example.com","exp":%d}`, time.Now().Add(-time.Minute).Unix()) + session.SetAccessToken(b64([]byte(`{"alg":"RS256","typ":"JWT"}`)) + "." + b64([]byte(payload)) + "." + b64(sig)) + session.SetRefreshToken("yaegi-check-bff-refresh-token") + rec := httptest.NewRecorder() + if err := session.Save(setupReq, rec); err != nil { + return "", fmt.Errorf("session.Save: %w", err) + } + session.ReturnToPool() + cookies := rec.Result().Cookies() + + for _, method := range []string{"GET", "POST"} { + req := httptest.NewRequest(method, "/auth/session", nil) + for _, c := range cookies { + req.AddCookie(c) + } + if err := expect("revoked-refresh "+method, req); err != nil { + return "", err + } + } + return "", nil +} + +// checkTMBSuccessUnderYaegi drives the 200 paths of the token-mediating +// endpoint under the interpreter, with tokens the fake IdP's JWKS really +// verifies: GET builds the body (claim extraction, groups, expires_at, JSON +// encoding), POST forces a refresh grant against the fake IdP, and the +// refreshed tokens are served by the next GET from the rotated cookie. +func checkTMBSuccessUnderYaegi() (string, error) { + const clientID = "yaegi-check-tmb-ok-client" + fx, err := fixtures.NewTokenFixture() + if err != nil { + return "", fmt.Errorf("NewTokenFixture: %w", err) + } + idpCfg := servers.DefaultConfig() + idpCfg.TokenFixture = fx + idp := servers.NewOIDCServer(idpCfg) + defer idp.Close() + fx.Issuer = idp.Config.Issuer + fx.Audience = clientID + + mint := func(jtiSuffix string) (string, error) { + return fx.ValidToken(map[string]interface{}{ + "email": "user@example.com", + "groups": []string{"admins"}, + "jti": "yaegi-tmb-" + jtiSuffix, + }) + } + accessTok, err := mint("access") + if err != nil { + return "", fmt.Errorf("mint access: %w", err) + } + idTok, err := mint("id") + if err != nil { + return "", fmt.Errorf("mint id: %w", err) + } + newAccessTok, err := mint("access-new") + if err != nil { + return "", fmt.Errorf("mint new access: %w", err) + } + newIDTok, err := mint("id-new") + if err != nil { + return "", fmt.Errorf("mint new id: %w", err) + } + idp.Config.RefreshResponse = map[string]interface{}{ + "access_token": newAccessTok, + "id_token": newIDTok, + "refresh_token": "yaegi-check-tmb-rotated-refresh-token-0123456789", + "token_type": "Bearer", + "expires_in": 3600, + } + + cfg := oidc.CreateConfig() + cfg.ProviderURL = idp.URL + cfg.ClientID = clientID + cfg.ClientSecret = "yaegi-check-tmb-ok-secret" + cfg.CallbackURL = "/oauth2/callback" + cfg.SessionEncryptionKey = "0123456789abcdef0123456789abcdef" + cfg.TMBSessionURL = "/auth/session" + cfg.TMBClaims = []string{"email"} + + reached := false + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true }) + h, err := oidc.New(context.Background(), next, cfg, "yaegi-check-tmb-ok") + if err != nil { + return "", fmt.Errorf("New: %w", err) + } + if closer, ok := h.(interface{ Close() error }); ok { + defer closer.Close() + } + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil)) + reached = false + + sm, err := oidc.NewSessionManager(cfg.SessionEncryptionKey, cfg.ForceHTTPS, cfg.CookieDomain, cfg.CookiePrefix, time.Duration(cfg.SessionMaxAge)*time.Second, oidc.NewLogger("error")) + if err != nil { + return "", fmt.Errorf("NewSessionManager: %w", err) + } + defer sm.Shutdown() + setupReq := httptest.NewRequest("GET", "/", nil) + session, err := sm.GetSession(setupReq) + if err != nil { + return "", fmt.Errorf("GetSession: %w", err) + } + if err := session.SetAuthenticated(true); err != nil { + return "", fmt.Errorf("SetAuthenticated: %w", err) + } + session.SetUserIdentifier("user@example.com") + session.SetAccessToken(accessTok) + session.SetIDToken(idTok) + session.SetRefreshToken("yaegi-check-tmb-refresh-token-0123456789") + rec := httptest.NewRecorder() + if err := session.Save(setupReq, rec); err != nil { + return "", fmt.Errorf("session.Save: %w", err) + } + session.ReturnToPool() + cookies := rec.Result().Cookies() + + call := func(method string, jar []*http.Cookie) (map[string]interface{}, []*http.Cookie, error) { + req := httptest.NewRequest(method, "/auth/session", nil) + for _, c := range jar { + req.AddCookie(c) + } + rw := httptest.NewRecorder() + h.ServeHTTP(rw, req) + if reached { + return nil, nil, fmt.Errorf("%s: next reached", method) + } + if rw.Code != http.StatusOK { + return nil, nil, fmt.Errorf("%s: status = %d, want 200 (body %q)", method, rw.Code, rw.Body.String()) + } + var body map[string]interface{} + if err := json.Unmarshal(rw.Body.Bytes(), &body); err != nil { + return nil, nil, fmt.Errorf("%s: body is not JSON: %v", method, err) + } + return body, rw.Result().Cookies(), nil + } + + body, _, err := call("GET", cookies) + if err != nil { + return "", err + } + if body["access_token"] != accessTok || body["user_identifier"] != "user@example.com" { + return "", fmt.Errorf("GET: unexpected identity/token in %v", body) + } + claims, _ := body["claims"].(map[string]interface{}) + if len(claims) != 1 || claims["email"] != "user@example.com" { + return "", fmt.Errorf("GET: claims = %v, want only the configured email", body["claims"]) + } + groups, _ := body["groups"].([]interface{}) + if len(groups) != 1 || groups[0] != "admins" { + return "", fmt.Errorf("GET: groups = %v, want [admins]", body["groups"]) + } + left := body["expires_at"].(float64) - float64(time.Now().Unix()) + if left < 3000 || left > 3700 { + return "", fmt.Errorf("GET: expires_at = %v, want about an hour from now", body["expires_at"]) + } + if _, found := body["expires_in"]; found { + return "", fmt.Errorf("GET: expires_in must not be returned") + } + for _, k := range []string{"refresh_token", "id_token"} { + if _, found := body[k]; found { + return "", fmt.Errorf("GET: %s must never be returned", k) + } + } + + body, rotated, err := call("POST", cookies) + if err != nil { + return "", err + } + if body["access_token"] != newAccessTok { + return "", fmt.Errorf("POST: access_token was not the refreshed one") + } + body, _, err = call("GET", append(append([]*http.Cookie{}, cookies...), rotated...)) + if err != nil { + return "", err + } + if body["access_token"] != newAccessTok { + return "", fmt.Errorf("GET after POST: refreshed token was not persisted in the session") + } + return "", nil +} + // checkErrAbortHandlerAbortsUnderYaegi guards the re-review finding on // ServeHTTP's ErrAbortHandler branch (middleware.go): under yaegi v0.16.1, // `r == http.ErrAbortHandler` only ever matches a panic raised by COMPILED diff --git a/config_marshalling.go b/config_marshalling.go index 6c7b1bb..411d0b8 100644 --- a/config_marshalling.go +++ b/config_marshalling.go @@ -82,6 +82,8 @@ func (c Config) configToMap() map[string]interface{} { result["cookiePath"] = c.CookiePath result["enableBackchannelLogout"] = c.EnableBackchannelLogout result["enableFrontchannelLogout"] = c.EnableFrontchannelLogout + result["tmbSessionURL"] = c.TMBSessionURL + result["tmbClaims"] = c.TMBClaims result["backchannelLogoutURL"] = c.BackchannelLogoutURL result["frontchannelLogoutURL"] = c.FrontchannelLogoutURL result["caCertPath"] = c.CACertPath diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3241e15..94bbf6d 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -195,12 +195,14 @@ clientSecret: your-client-secret | `clientAssertionKeyID` | string | none | `kid` header for `private_key_jwt` assertions. Required when `clientAuthMethod: private_key_jwt`. | | `clientAssertionAlg` | string | `RS256` | Signing algorithm for `private_key_jwt`. One of `RS256/384/512`, `PS256/384/512`, `ES256/384/512`. | | `extraAuthParams` | map | none | Extra query parameters appended to the authorization request (e.g. re-selective prompt). | -| `perSourceLoginRateLimit` | int | `0` (off) | Throttle OIDC auth events (callback + login initiation) per external client source, in auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources are never throttled. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. | +| `perSourceLoginRateLimit` | int | `0` (off) | Throttle OIDC auth events (callback, login initiation and forced refreshes at the `tmbSessionURL` endpoint) per external client source, in auth events per minute. Keys and classifies the source by RemoteAddr only, never `X-Forwarded-For`, so a client cannot spoof it. Internal/loopback sources are never throttled. RemoteAddr is the TCP peer. Behind a load balancer or CDN, the limiter keys on the proxy address: a private address is never throttled, and a public address puts every client in one shared bucket. | | `stripAuthCookies` | bool | `false` | Strip OIDC session cookies from the hop to the backend (mitigates HTTP 431). | | `enableBackchannelLogout` | bool | `false` | Enable OIDC back-channel logout (IdP-initiated, server-to-server). | | `backchannelLogoutURL` | string | derived | Back-channel logout endpoint path. | | `enableFrontchannelLogout` | bool | `false` | Enable OIDC front-channel logout (browser iframe logout). | | `frontchannelLogoutURL` | string | derived | Front-channel logout endpoint path. | +| `tmbSessionURL` | string | none | Path of the token-mediating-backend endpoint, authenticated by the session cookie. `GET` returns user identifier, groups, roles, expiry, the claims listed in `tmbClaims` and the access token; `POST` forces a token refresh and returns the same. Setting it enables the endpoint. See [TMB.md](TMB.md). | +| `tmbClaims` | []string | none | ID-token claim names returned in the endpoint's `claims` object. Empty by default: nothing extra is exposed. | | `caCertPath` / `caCertPEM` | string | none | Custom CA bundle for OIDC TLS verification (filesystem path, or inline PEM). Mutually exclusive with `insecureSkipVerify`. | | `insecureSkipVerify` | bool | `false` | Disable TLS verification for the OIDC client (load balancer / mTLS edge). Emits a loud warning at startup. | diff --git a/docs/TMB.md b/docs/TMB.md new file mode 100644 index 0000000..48577d3 --- /dev/null +++ b/docs/TMB.md @@ -0,0 +1,148 @@ +# Token-mediating backend endpoint + +Lets a single-page app obtain an access token from the plugin's session without +holding a refresh token or running its own OAuth client. This is the +"Token-Mediating Backend" pattern of +[draft-ietf-oauth-browser-based-apps](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps): +the plugin is the confidential client, keeps the refresh token server-side, and +hands the access token to the browser. It is not a BFF: requests to the +resource server do not pass through the plugin. + +The spec defines no paths or formats. The endpoint is modelled on session +endpoints such as Azure App Service's `/.auth/me`: `GET` reads, `POST` +refreshes. + +## Configuration + +The endpoint is off until its path is set. There is no separate enable flag. + +```yaml +tmbSessionURL: /auth/session +tmbClaims: # optional; default none + - email + - name +``` + +The path must be a plain absolute path (leading `/`, no leading `//`, no query, +fragment or backslash) and must not be a path another endpoint of the +middleware already serves: `callbackURL`, `logoutURL` (its default is +`callbackURL` + `/logout`) or the back- and front-channel logout URLs. It is +matched against the request path as configured. + +`tmbClaims` names the claims returned in `claims`, read from the ID token (from +the access token when the session has no ID token). It is empty by default, so +nothing beyond the fields below is exposed. + +## Authentication + +The endpoint is authenticated by the plugin's session cookie, the same one the +rest of the plugin uses. It never accepts `Authorization: Bearer` and never +redirects to the IdP: with no valid session it answers `401 invalid_session`. It +is served ahead of the bypasses (`excludedURLs`, `Accept: text/event-stream`, +WebSocket upgrades, unauthenticated preflight), so none of them can forward a +request on its path to the backend. + +A session must also pass the normal gates (`allowedUsers`, `allowedUserDomains`, +`allowedRolesAndGroups`, back/front-channel logout invalidation); failing +`allowedUsers`/`allowedRolesAndGroups` answers `403 access_denied`. + +If `cookiePath` is set, it must cover the configured path, or the browser will +not send the cookie to it. + +## Cross-origin protection + +- `GET` and `POST` only (`405` otherwise, with `Allow: GET, POST`). +- A request is rejected with `403` when `Sec-Fetch-Site` is `cross-site` or + `same-site`, or when `Origin` is present and does not match the request host. + A rejected request never triggers a refresh. +- The endpoint never emits CORS headers: `Access-Control-*` headers added by + `securityHeaders.corsEnabled` are removed from its responses. +- Responses carry `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` + and `Cross-Origin-Resource-Policy: same-origin`. +- No custom request header is required. + +The plugin removes only the CORS headers that it adds itself. It cannot remove +headers that another middleware adds to its responses, for example CORS headers +from a Traefik `headers` middleware. Do not add such a middleware to the router +that serves `tmbSessionURL`. + +## What scripts on the origin can read + +The endpoint gives the access token to every script that runs on the same +origin. Thus a cross-site scripting flaw or a compromised third-party script on +that origin can read the access token. Without this endpoint, the access token +stays on the server. Before you enable the endpoint, set a strict +`Content-Security-Policy` on the pages of that origin. Keep the access token +lifetime at the IdP short. + +## `GET`: read the session + +```json +{ + "authenticated": true, + "user_identifier": "user-1", + "claims": {"email": "u@example.com", "name": "U One"}, + "groups": ["admins"], + "access_token": "…", + "expires_at": 1767225600 +} +``` + +- `user_identifier` is the claim named by `userIdentifierClaim`. `groups` and + `roles` use `groupClaimName` / `roleClaimName` and are omitted when empty. +- `claims` holds exactly the claims listed in `tmbClaims`, with their values as + they appear in the token (arrays and objects included). A claim the token + lacks is omitted, and `claims` itself is omitted when nothing is listed. +- `access_token` is the session's access token. The refresh token and ID token + are never returned. +- `expires_at` (unix seconds) is when the access token expires, not the ID + token, which may expire at a different time. The plugin records it at login + and at every refresh, from the token response's `expires_in` and otherwise + from the token's own `exp` claim, so opaque access tokens are covered when the + IdP sends `expires_in`. A session that predates the record falls back to the + `exp` claim. The field is omitted when the expiry is unknown. +- A `GET` has no side effects on the session, except that the access token is + refreshed first when its expiry is within `refreshGracePeriod` or past. This + goes beyond the plugin's usual rule, which for an opaque access token follows + the ID token's expiry and could hand out a token that has already expired. + If an expired token cannot be refreshed, the endpoint does not return it: it + answers `401 invalid_session` when there is no refresh token to try or the IdP + rejected it, and `502 server_error` when the IdP could not be reached. A token + that is merely due keeps being served if its early refresh fails. Query + parameters are ignored. + +## `POST`: force a refresh + +Runs a refresh-token grant through the same path as the automatic refresh, +saves the new tokens and any rotated refresh token to the session, and returns +the same body as `GET` with the new token. Use it when the API rejected the +current token. The request body is ignored. The refresh runs only after the +user passed the authorization gates, which are applied again to the refreshed +token's claims. Each forced refresh is one IdP call, so it is subject to +`perSourceLoginRateLimit` when that is set (off by default). + +## Errors + +`application/json` with `error` and optional `error_description`: + +| Status | `error` | Cause | +|--------|---------|-------| +| 401 | `invalid_session` | No valid authenticated session (missing, expired or logged out); the IdP rejected the refresh token (the session is ended); or the access token has expired and there is no refresh token to renew it. No `WWW-Authenticate` header is sent: the session cookie has no HTTP auth scheme, as for the plugin's other `401`s. | +| 401 | `backend_not_ready` | `POST` but the session has no refresh token, so it cannot be refreshed and the user has to authenticate again. The session is left as is; `GET` keeps working until the access token expires. | +| 403 | `access_denied` | The user fails `allowedUsers` or `allowedRolesAndGroups`. | +| 403 | `invalid_request` | Cross-origin request. | +| 405 | `invalid_request` | Method other than `GET` or `POST`. | +| 429 | `rate_limited` | `POST` from an external source over `perSourceLoginRateLimit`; `Retry-After: 1` is set and no refresh is attempted. | +| 502 | `server_error` | The token endpoint was unreachable or failed on a `POST`, or on a `GET` whose access token had already expired; the session is kept. | + +## SPA flow + +Read the session once on load and keep the access token in memory. When the API +answers `401` or `expires_at` is near, `POST` to get a fresh one. The endpoint +never redirects: on any `401` from this endpoint (`invalid_session` or +`backend_not_ready`), navigate the page to a protected URL so the normal login +redirect runs. No page reload is needed otherwise. + +## Not supported + +`resource` and `scope` (token downscoping) are not supported in this version. diff --git a/helpers.go b/helpers.go index 35534a5..692498d 100644 --- a/helpers.go +++ b/helpers.go @@ -93,6 +93,34 @@ type TokenResponse struct { ExpiresIn int `json:"expires_in"` } +// jwtExpiry returns the exp claim of a JWT (unix seconds), or 0 when token is +// not a JWT or carries no numeric exp. +func jwtExpiry(token string) int64 { + parsed, err := parseJWT(token) + if err != nil { + return 0 + } + exp, ok := parsed.Claims["exp"].(float64) + if !ok { + return 0 + } + return int64(exp) +} + +// accessTokenExpiry returns when the access token in a token response expires +// (unix seconds): from the response's expires_in when the IdP sent one, +// otherwise from the token's own exp claim. It returns 0 when neither is known +// (an opaque token without expires_in). +func accessTokenExpiry(tr *TokenResponse, now time.Time) int64 { + if tr == nil { + return 0 + } + if tr.ExpiresIn > 0 { + return now.Unix() + int64(tr.ExpiresIn) + } + return jwtExpiry(tr.AccessToken) +} + // exchangeTokens performs OAuth 2.0 token exchange with the authorization server. // It supports both authorization code and refresh token grant types with PKCE support. // Parameters: diff --git a/main.go b/main.go index 93254eb..b76128f 100644 --- a/main.go +++ b/main.go @@ -355,6 +355,8 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name stripAuthCookies: config.StripAuthCookies, enableBackchannelLogout: config.EnableBackchannelLogout, enableFrontchannelLogout: config.EnableFrontchannelLogout, + tmbSessionURLPath: config.TMBSessionURL, + tmbClaims: config.TMBClaims, backchannelLogoutPath: normalizeLogoutPath(config.BackchannelLogoutURL), frontchannelLogoutPath: normalizeLogoutPath(config.FrontchannelLogoutURL), sessionInvalidationCache: cacheManager.GetSharedSessionInvalidationCache(), diff --git a/middleware.go b/middleware.go index 182234d..07d12ae 100644 --- a/middleware.go +++ b/middleware.go @@ -204,6 +204,12 @@ func isWebSocketUpgrade(req *http.Request) bool { // This must be called BEFORE waiting on t.initComplete so excluded, SSE and // WebSocket traffic is never blocked by a slow/broken provider. func (t *TraefikOidc) shouldBypassAuth(req *http.Request) (bool, string) { + // The token-mediating endpoint authenticates itself, so no bypass (excluded + // URL, SSE, WebSocket, preflight) may forward a request to the backend + // instead of answering it. + if t.isTMBPath(req.URL.Path) { + return false, "" + } if t.determineExcludedURL(req.URL.Path) { return true, bypassReasonExcluded } @@ -775,6 +781,14 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) { // Bypass checks already ran before the init wait; no need to repeat them. t.sessionManager.CleanupOldCookies(rw, req) + // Token-mediating endpoints (opt-in by path): session-cookie only, so + // they are handled before the bearer branch and never fall into the + // redirect flow below. + if t.isTMBPath(req.URL.Path) { + t.handleTMB(rw, req) + return + } + // Bearer-token auth (opt-in). Runs after init (we need issuer+JWKs+aud // available) and after bypass (excluded URLs always win). Cookie-vs- // bearer precedence is configurable; the safe default is cookie-wins. diff --git a/requeststate.go b/requeststate.go index 1d1068b..216f2e7 100644 --- a/requeststate.go +++ b/requeststate.go @@ -39,6 +39,10 @@ type requestState struct { userIdentifier string createdAtUnixSec int64 + // accessTokenExpiresAt is the recorded access-token expiry (unix); 0 when + // unknown. + accessTokenExpiresAt int64 + // Output: scheme/host/redirect path determined at top of ServeHTTP. scheme string host string @@ -66,6 +70,7 @@ func (rs *requestState) captureSession(sd *SessionData) *requestState { rs.refreshToken = sd.getRefreshTokenUnsafe() rs.userIdentifier = sd.getUserIdentifierUnsafe() rs.createdAtUnixSec = sd.getCreatedAtUnsafe() + rs.accessTokenExpiresAt = sd.getAccessTokenExpiresAtUnsafe() sd.sessionMutex.RUnlock() return rs } diff --git a/review_r154_regression_test.go b/review_r154_regression_test.go index fb30510..d8f25f7 100644 --- a/review_r154_regression_test.go +++ b/review_r154_regression_test.go @@ -2,8 +2,6 @@ package traefikoidc import ( "context" - "crypto/rand" - "encoding/base64" "net/http/httptest" "sync" "sync/atomic" @@ -13,17 +11,6 @@ import ( // R154 review-round regressions. -// incompressibleToken returns a base64 blob too large to fit a single -// cookie after compression, so Set*Token takes the chunked path. Random -// bytes are (nearly) incompressible, unlike repeated chars. -func incompressibleToken(size int) string { - buf := make([]byte, size) - if _, err := rand.Read(buf); err != nil { - panic(err) - } - return base64.RawStdEncoding.EncodeToString(buf) -} - // TestSetRefreshToken_AbortPreservesPrevious covers the commit-on-success // rewrite of SetRefreshToken (session.go). Setting a new chunked refresh // token on a session whose request is nil (so the chunk write aborts) diff --git a/session.go b/session.go index 4ed64e3..79b80c1 100644 --- a/session.go +++ b/session.go @@ -153,6 +153,7 @@ type combinedSessionPayload struct { Ip string `json:"ip,omitempty"` Ru string `json:"ru,omitempty"` // redirect_uri used at initiate; reused at callback so a per-request rebuild can't drift (R136) Ca int64 `json:"ca,omitempty"` + Ea int64 `json:"ea,omitempty"` // access-token expiry (unix); a dedicated field because JSON would turn an int64 in X into a float64 Rc int `json:"rc,omitempty"` Au bool `json:"au,omitempty"` } @@ -172,8 +173,15 @@ var knownSessionKeys = map[string]bool{ "redirect_url": true, "created_at": true, "redirect_count": true, + + "access_token_expires_at": true, } +// accessTokenExpiresAtKey holds the access token's expiry (unix seconds) in +// mainSession.Values. It describes the stored access token only and is dropped +// whenever that token changes (see SetAccessToken). +const accessTokenExpiresAtKey = "access_token_expires_at" + // compressCombinedPayload compresses the combined session payload using gzip. // It serializes the payload to JSON, compresses it, and returns base64-encoded data. // Returns the compressed string and any error encountered. @@ -1305,6 +1313,9 @@ func (sm *SessionManager) loadFromCombinedCookies(r *http.Request, sessionData * sessionData.mainSession.Values["redirect_url"] = payload.Ru sessionData.mainSession.Values["created_at"] = payload.Ca sessionData.mainSession.Values["redirect_count"] = payload.Rc + if payload.Ea > 0 { + sessionData.mainSession.Values[accessTokenExpiresAtKey] = payload.Ea + } // Restore extra custom session values for key, val := range payload.X { @@ -1519,6 +1530,7 @@ func (sd *SessionData) saveCombined(r *http.Request, w http.ResponseWriter, opti Ip: sd.getIncomingPathUnsafe(), Ru: sd.getRedirectURLUnsafe(), Ca: sd.getCreatedAtUnsafe(), + Ea: sd.getAccessTokenExpiresAtUnsafe(), Rc: sd.getRedirectCountUnsafe(), } // Persist the refresh token's issued_at so maxRefreshTokenAge keeps @@ -2234,6 +2246,7 @@ func (sd *SessionData) SetAccessToken(token string) { sd.accessSession.Values["compressed"] = false } sd.clearAccessTokenChunks() + sd.clearAccessTokenExpiryUnsafe() return } @@ -2263,6 +2276,7 @@ func (sd *SessionData) SetAccessToken(token string) { if len(compressed) <= maxCookieSize { sd.clearAccessTokenChunks() + sd.clearAccessTokenExpiryUnsafe() if sd.accessSession != nil { sd.accessSession.Values["token"] = compressed sd.accessSession.Values["compressed"] = (compressed != token) @@ -2312,6 +2326,7 @@ func (sd *SessionData) SetAccessToken(token string) { // Validation passed: now it is safe to clear the existing token // before storing the new chunked one. sd.clearAccessTokenChunks() + sd.clearAccessTokenExpiryUnsafe() if sd.accessSession != nil { sd.accessSession.Values["token"] = "" sd.accessSession.Values["compressed"] = (compressed != token) @@ -3146,6 +3161,58 @@ func (sd *SessionData) getCreatedAtUnsafe() int64 { return createdAt } +// getAccessTokenExpiresAtUnsafe returns the stored access-token expiry (unix +// seconds), or 0 when none is known, without acquiring locks. +func (sd *SessionData) getAccessTokenExpiresAtUnsafe() int64 { + if sd.mainSession == nil { + return 0 + } + exp, _ := sd.mainSession.Values[accessTokenExpiresAtKey].(int64) + return exp +} + +// GetAccessTokenExpiresAt returns when the stored access token expires (unix +// seconds), as recorded from the token response or the token's own exp claim +// at login or refresh. It returns 0 when unknown, e.g. for sessions created +// before the expiry was recorded. +func (sd *SessionData) GetAccessTokenExpiresAt() int64 { + sd.sessionMutex.RLock() + defer sd.sessionMutex.RUnlock() + return sd.getAccessTokenExpiresAtUnsafe() +} + +// SetAccessTokenExpiresAt records when token expires (unix seconds), but only +// if token is the stored access token: when SetAccessToken could not store it, +// the previous token keeps its own expiry. A value <= 0 clears it. +func (sd *SessionData) SetAccessTokenExpiresAt(token string, expiresAt int64) { + sd.sessionMutex.Lock() + defer sd.sessionMutex.Unlock() + + if sd.mainSession == nil || sd.accessSession == nil || token == "" { + return + } + if !constantTimeStringCompare(sd.getAccessTokenUnsafe(), token) { + return + } + if sd.getAccessTokenExpiresAtUnsafe() == expiresAt { + return + } + sd.dirty = true + if expiresAt <= 0 { + sd.clearAccessTokenExpiryUnsafe() + return + } + sd.mainSession.Values[accessTokenExpiresAtKey] = expiresAt +} + +// clearAccessTokenExpiryUnsafe drops the recorded expiry, without acquiring +// locks. Call it whenever the stored access token is replaced or cleared. +func (sd *SessionData) clearAccessTokenExpiryUnsafe() { + if sd.mainSession != nil { + delete(sd.mainSession.Values, accessTokenExpiresAtKey) + } +} + // getRedirectCountUnsafe retrieves the redirect count without acquiring locks. func (sd *SessionData) getRedirectCountUnsafe() int { count, _ := sd.mainSession.Values["redirect_count"].(int) diff --git a/session_test_helpers_test.go b/session_test_helpers_test.go new file mode 100644 index 0000000..f620f40 --- /dev/null +++ b/session_test_helpers_test.go @@ -0,0 +1,17 @@ +package traefikoidc + +import ( + "crypto/rand" + "encoding/base64" +) + +// incompressibleToken returns a base64 blob too large to fit a single +// cookie after compression, so Set*Token takes the chunked path. Random +// bytes are (nearly) incompressible, unlike repeated chars. +func incompressibleToken(size int) string { + buf := make([]byte, size) + if _, err := rand.Read(buf); err != nil { + panic(err) + } + return base64.RawStdEncoding.EncodeToString(buf) +} diff --git a/settings.go b/settings.go index 7b3b20a..c47f21c 100644 --- a/settings.go +++ b/settings.go @@ -91,7 +91,8 @@ type Config struct { SessionMaxAge int `json:"sessionMaxAge"` RateLimit int `json:"rateLimit"` // PerSourceLoginRateLimit throttles OIDC authentication events - // (authorization-code callback + login initiation) per client source IP, + // (authorization-code callback, login initiation and forced refreshes at + // the token-mediating endpoint) per client source IP, // for external (non-internal) sources only. Internal / loopback / // link-local sources (reverse proxies, in-cluster callers) are trusted // and never throttled. Value = max auth events per minute per external @@ -132,6 +133,16 @@ type Config struct { EnableFrontchannelLogout bool `json:"enableFrontchannelLogout,omitempty"` BackchannelLogoutURL string `json:"backchannelLogoutURL,omitempty"` FrontchannelLogoutURL string `json:"frontchannelLogoutURL,omitempty"` + // TMBSessionURL is the path of the token-mediating backend endpoint + // (draft-ietf-oauth-browser-based-apps), authenticated by the session + // cookie: GET returns session information and the access token, POST + // forces a token refresh first. Setting it enables the endpoint; unset + // (default) leaves it off. See docs/TMB.md. + TMBSessionURL string `json:"tmbSessionURL,omitempty"` + // TMBClaims lists the ID-token claims the endpoint returns in `claims`. + // Default empty: nothing beyond user_identifier (userIdentifierClaim), + // groups and roles (groupClaimName, roleClaimName) and expires_at. + TMBClaims []string `json:"tmbClaims,omitempty"` // CACertPath is an optional filesystem path to a PEM-encoded CA bundle used // to verify the OIDC provider's TLS certificate. Use this when the provider // is signed by an internal/private CA that is not in the system trust store. @@ -517,6 +528,42 @@ func (c *Config) Validate() error { } } + for _, name := range c.TMBClaims { + if name == "" || len(name) > 128 { + return fmt.Errorf("tmbClaims entries must be non-empty claim names of at most 128 characters") + } + } + + // The token-mediating endpoint path is matched by exact request-path + // comparison, so it must be a bare absolute path and must not shadow + // another endpoint of this middleware. + if c.TMBSessionURL != "" { + if !strings.HasPrefix(c.TMBSessionURL, "/") { + return fmt.Errorf("tmbSessionURL must start with /") + } + if strings.ContainsAny(c.TMBSessionURL, "?#\\") || strings.HasPrefix(c.TMBSessionURL, "//") { + return fmt.Errorf("tmbSessionURL must be a plain absolute path: no query string, fragment, backslash or leading //") + } + // The logout, back-channel and front-channel handlers run before the + // TMB endpoint, so a path they own would silently never reach it. + // Compare against the effective logout path (its default derives + // from callbackURL) and the normalized channel paths. + logoutPath := c.LogoutURL + if logoutPath == "" { + logoutPath = c.CallbackURL + "/logout" + } + for _, owned := range []string{ + c.CallbackURL, + logoutPath, + normalizeLogoutPath(c.BackchannelLogoutURL), + normalizeLogoutPath(c.FrontchannelLogoutURL), + } { + if owned != "" && c.TMBSessionURL == owned { + return fmt.Errorf("tmbSessionURL %q is already used by the callback, logout, back-channel or front-channel logout endpoint", c.TMBSessionURL) + } + } + } + // Validate client credentials. With Dynamic Client Registration (RFC 7591) // enabled, clientID (and typically clientSecret) are not known at // construction time — the provider provisions them at registration. Skip diff --git a/tmb.go b/tmb.go new file mode 100644 index 0000000..2ca89a0 --- /dev/null +++ b/tmb.go @@ -0,0 +1,288 @@ +package traefikoidc + +import ( + "encoding/json" + "net/http" + "net/url" + "strings" + "time" + + "github.com/lukaszraczylo/traefikoidc/internal/utils" +) + +// Token-mediating backend endpoint (draft-ietf-oauth-browser-based-apps, +// "Token-Mediating Backend"). The spec defines no paths or formats, so the +// endpoint is served only at the path configured in tmbSessionURL, +// authenticated by the regular session cookie, and is never reachable by +// bearer auth. GET reads the session and its access token; POST forces a +// refresh first and returns the same body. + +// isTMBPath reports whether path is the configured token-mediating endpoint. +func (t *TraefikOidc) isTMBPath(path string) bool { + return t.tmbSessionURLPath != "" && path == t.tmbSessionURLPath +} + +func writeTMBJSON(rw http.ResponseWriter, status int, body map[string]interface{}) { + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(status) + _ = json.NewEncoder(rw).Encode(body) // Safe to ignore: response write +} + +func writeTMBError(rw http.ResponseWriter, status int, code, description string) { + body := map[string]interface{}{"error": code} + if description != "" { + body["error_description"] = description + } + writeTMBJSON(rw, status, body) +} + +// tmbCrossSite reports whether the request was issued from another origin. +// Browsers label cross-origin requests with Sec-Fetch-Site and Origin, and no +// CORS headers are ever emitted. Requests carrying neither header +// (non-browser clients) pass. +func tmbCrossSite(req *http.Request) bool { + switch strings.ToLower(req.Header.Get("Sec-Fetch-Site")) { + case "cross-site", "same-site": + return true + } + if origin := req.Header.Get("Origin"); origin != "" { + u, err := url.Parse(origin) + if err != nil || !strings.EqualFold(u.Host, utils.DetermineHost(req)) { + return true + } + } + return false +} + +// handleTMB serves the token-mediating endpoint. Callers must have verified +// isTMBPath. +func (t *TraefikOidc) handleTMB(rw http.ResponseWriter, req *http.Request) { + h := rw.Header() + h.Set("Cache-Control", "no-store") + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Cross-Origin-Resource-Policy", "same-origin") + // The endpoint is same-origin only. The middleware-wide security headers + // may already have added CORS headers (securityHeaders.corsEnabled); drop + // them so a cross-origin page can never be granted read access. + for name := range h { + if strings.HasPrefix(strings.ToLower(name), "access-control-") { + h.Del(name) + } + } + + if req.Method != http.MethodGet && req.Method != http.MethodPost { + h.Set("Allow", "GET, POST") + writeTMBError(rw, http.StatusMethodNotAllowed, "invalid_request", "only GET and POST are supported") + return + } + if tmbCrossSite(req) { + writeTMBError(rw, http.StatusForbidden, "invalid_request", "cross-origin requests are not allowed") + return + } + + session, err := t.sessionManager.GetSession(req) + if err != nil || session == nil { + t.logger.Errorf("Token-mediating endpoint: no usable session: %v", err) + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + return + } + gen := session.ownerGeneration() + defer session.returnToPoolIfOwner(gen) + + rs := (&requestState{metadata: t.metadataSnap()}).captureSession(session) + refreshed, ok := t.tmbEstablishSession(rw, req, session, rs) + if !ok { + return + } + + claims, groups, roles, ok := t.tmbAuthorize(rw, session) + if !ok { + return + } + + // POST forces a refresh, unless this request already refreshed. The + // refresh runs only after the user passed the authorization gates, and + // the gates are re-applied to the refreshed token's claims. + if req.Method == http.MethodPost && !refreshed { + // Each forced refresh is an IdP round trip, so it shares the optional + // per-source throttle of the other auth gates (perSourceLoginRateLimit). + if t.perSourceLimiter != nil && !t.perSourceLimiter.allow(req) { + rw.Header().Set("Retry-After", "1") + writeTMBError(rw, http.StatusTooManyRequests, "rate_limited", "too many refresh requests, try again shortly") + return + } + if !t.tmbForceRefresh(rw, req, session, rs) { + return + } + if claims, groups, roles, ok = t.tmbAuthorize(rw, session); !ok { + return + } + } + + t.writeTMBSession(rw, session, rs, claims, groups, roles) +} + +// tmbEstablishSession ensures the session holds a valid, authenticated token +// set, refreshing it when due, and updates rs to match. It reports whether a +// refresh happened. It answers invalid_session itself and returns ok=false +// when no valid session exists. It never redirects: this endpoint is for +// XHR/fetch. +// +// The plugin's own refresh decision follows the ID token when the access token +// is opaque, so it can hand out an access token that has already expired. This +// endpoint returns the access token, so it also refreshes when the recorded +// access-token expiry is inside refreshGracePeriod, and it never answers 200 +// with an access token known to be expired. +func (t *TraefikOidc) tmbEstablishSession(rw http.ResponseWriter, req *http.Request, session *SessionData, rs *requestState) (refreshed, ok bool) { + authenticated, needsRefresh, expired := t.isUserAuthenticatedRS(rs) + if expired { + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + return false, false + } + + now := time.Now() + exp := tmbAccessTokenExpiry(rs) + accessDue := exp > 0 && time.Unix(exp, 0).Sub(now) <= t.refreshGracePeriod + accessExpired := exp > 0 && exp <= now.Unix() + + attempted := false + if (needsRefresh || accessDue) && rs.refreshToken != "" && !t.isRefreshTokenExpired(session) && + !(authenticated && !accessDue && t.shouldSkipGraceRefresh(session)) { + attempted = true + if t.refreshToken(rw, req, session) { + rs.captureSession(session) + authenticated, refreshed = true, true + } + } + if !authenticated { + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + return false, false + } + if accessExpired && !refreshed { + switch { + case !attempted || !session.GetAuthenticated(): + // Nothing to renew it with, or the IdP rejected the refresh token. + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + default: + writeTMBError(rw, http.StatusBadGateway, "server_error", "access token expired and could not be refreshed") + } + return false, false + } + return refreshed, true +} + +// tmbForceRefresh runs a refresh-token grant through the existing refresh +// path and updates rs. It answers the error itself and returns false on +// failure. +func (t *TraefikOidc) tmbForceRefresh(rw http.ResponseWriter, req *http.Request, session *SessionData, rs *requestState) bool { + if rs.refreshToken == "" { + writeTMBError(rw, http.StatusUnauthorized, "backend_not_ready", "") + return false + } + if !t.refreshToken(rw, req, session) { + // A rejected refresh token clears the session; any other failure + // (IdP unreachable, 5xx) leaves it intact. + if !session.GetAuthenticated() { + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + } else { + writeTMBError(rw, http.StatusBadGateway, "server_error", "token refresh failed") + } + return false + } + rs.captureSession(session) + return true +} + +// tmbAuthorize applies the same post-authentication gates as the normal +// request path (identifier present, allowed user, IdP-initiated logout +// invalidation, allowed roles/groups) and returns the token claims. +func (t *TraefikOidc) tmbAuthorize(rw http.ResponseWriter, session *SessionData) (map[string]interface{}, []string, []string, bool) { + identifier := session.GetUserIdentifier() + if identifier == "" { + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + return nil, nil, nil, false + } + if !t.isAllowedUser(identifier) { + writeTMBError(rw, http.StatusForbidden, "access_denied", "") + return nil, nil, nil, false + } + idToken := session.GetIDToken() + if idToken != "" && (t.enableBackchannelLogout || t.enableFrontchannelLogout) { + sid, sub, createdAt := t.invalidationInputs(idToken, session) + if t.isSessionInvalidated(sid, sub, createdAt) { + writeTMBError(rw, http.StatusUnauthorized, "invalid_session", "") + return nil, nil, nil, false + } + } + + // A claims parse error leaves claims nil, which the roles/groups gate + // below rejects when it is configured. + claims, _ := t.bypassSessionClaims(session) + var groups, roles []string + if claims != nil { + var err error + groups, roles, err = t.extractGroupsAndRolesFromClaims(claims) + if err != nil && len(t.allowedRolesAndGroups) > 0 { + writeTMBError(rw, http.StatusForbidden, "access_denied", "") + return nil, nil, nil, false + } + } + if len(t.allowedRolesAndGroups) > 0 { + allowed := false + for _, g := range append(append([]string{}, groups...), roles...) { + if _, ok := t.allowedRolesAndGroups[g]; ok { + allowed = true + break + } + } + if !allowed { + writeTMBError(rw, http.StatusForbidden, "access_denied", "") + return nil, nil, nil, false + } + } + return claims, groups, roles, true +} + +// tmbAccessTokenExpiry returns when the session's access token expires (unix +// seconds): the expiry recorded at login or refresh (from the token response), +// else the token's own exp claim for sessions that predate the record. It +// returns 0 when unknown (an opaque token with no recorded expiry). +func tmbAccessTokenExpiry(rs *requestState) int64 { + if rs.accessTokenExpiresAt > 0 { + return rs.accessTokenExpiresAt + } + return jwtExpiry(rs.accessToken) +} + +// writeTMBSession answers 200 with the session information and the access +// token. +func (t *TraefikOidc) writeTMBSession(rw http.ResponseWriter, session *SessionData, rs *requestState, claims map[string]interface{}, groups, roles []string) { + out := map[string]interface{}{ + "authenticated": true, + "user_identifier": session.GetUserIdentifier(), + } + // Only the claims the operator listed in tmbClaims, as they appear in the + // token; absent or null claims are left out. + shown := map[string]interface{}{} + for _, name := range t.tmbClaims { + if v, ok := claims[name]; ok && v != nil { + shown[name] = v + } + } + if len(shown) > 0 { + out["claims"] = shown + } + if len(groups) > 0 { + out["groups"] = groups + } + if len(roles) > 0 { + out["roles"] = roles + } + if rs.accessToken != "" { + out["access_token"] = rs.accessToken + if exp := tmbAccessTokenExpiry(rs); exp > 0 { + out["expires_at"] = exp + } + } + writeTMBJSON(rw, http.StatusOK, out) +} diff --git a/tmb_test.go b/tmb_test.go new file mode 100644 index 0000000..f1cc208 --- /dev/null +++ b/tmb_test.go @@ -0,0 +1,683 @@ +package traefikoidc + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Example path used as the configured value in these tests. +const tmbPath = "/auth/session" + +const ( + tmbTestRefresh = "tmb-refresh-token-0123456789abcdefghijklmnopqrstuvwxyz" + tmbTestRotated = "tmb-rotated-token-0123456789abcdefghijklmnopqrstuvwxyz" +) + +// tmbIdP is a fake token endpoint recording each form it receives. +type tmbIdP struct { + mu sync.Mutex + forms []url.Values + status int + body string +} + +func (p *tmbIdP) ServeHTTP(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + p.mu.Lock() + p.forms = append(p.forms, r.PostForm) + status, body := p.status, p.body + p.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(body)) +} + +func (p *tmbIdP) calls() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.forms) +} + +func (p *tmbIdP) last(t *testing.T) url.Values { + t.Helper() + p.mu.Lock() + defer p.mu.Unlock() + require.NotEmpty(t, p.forms, "token endpoint was not called") + return p.forms[len(p.forms)-1] +} + +type tmbEnv struct { + oidc *TraefikOidc + idp *tmbIdP + cookies []*http.Cookie + access string // the session's access token + newAccess string // what a refresh grant returns + newID string // the ID token a refresh grant returns +} + +func newTMBEnv(t *testing.T, opts ...func(*TraefikOidc)) *tmbEnv { + t.Helper() + + claims := map[string]interface{}{ + "sub": "user-1", "email": "u@example.com", "name": "U One", + "groups": []interface{}{"admins"}, + "exp": float64(time.Now().Add(time.Hour).Unix()), + "iat": float64(time.Now().Unix()), + } + newClaims := map[string]interface{}{ + "sub": "user-1", "email": "u@example.com", "name": "U One", + "groups": []interface{}{"admins"}, + "exp": float64(time.Now().Add(2 * time.Hour).Unix()), + "iat": float64(time.Now().Unix()), + } + access := tokenWithGroups(t, claims) + id := tokenWithGroups(t, claims) + newAccess := tokenWithGroups(t, newClaims) + newID := tokenWithGroups(t, newClaims) + + refreshBody, err := json.Marshal(map[string]interface{}{ + "access_token": newAccess, + "id_token": newID, + "refresh_token": tmbTestRotated, + "expires_in": 7200, + }) + require.NoError(t, err) + idp := &tmbIdP{status: http.StatusOK, body: string(refreshBody)} + srv := httptest.NewServer(idp) + t.Cleanup(srv.Close) + + oidc := newTestOIDC(t, func(o *TraefikOidc) { + o.tmbSessionURLPath = tmbPath + o.tmbClaims = []string{"email", "name"} + o.tokenCache = NewTokenCache() + o.tokenVerifier = o // real VerifyToken; the seeded cache short-circuits it + o.tokenExchanger = o + o.extractClaimsFunc = extractClaims + o.tokenURL = srv.URL + "/token" + o.clientSecret = "secret" + o.tokenHTTPClient = srv.Client() + o.userIdentifierClaim = "sub" + o.groupClaimName, o.roleClaimName = "groups", "roles" + o.refreshGracePeriod = time.Minute + o.allowedRolesAndGroups = map[string]struct{}{} + o.next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("token-mediating request must not reach the backend") + }) + }) + for _, opt := range opts { + opt(oidc) + } + seedVerified(t, oidc, access, claims) + seedVerified(t, oidc, id, claims) + seedVerified(t, oidc, newAccess, newClaims) + seedVerified(t, oidc, newID, newClaims) + + base := httptest.NewRequest(http.MethodGet, "https://app.example.com/", nil) + rec := httptest.NewRecorder() + session, err := oidc.sessionManager.GetSession(base) + require.NoError(t, err) + require.NoError(t, session.SetAuthenticated(true)) + session.SetAccessToken(access) + session.SetIDToken(id) + session.SetRefreshToken(tmbTestRefresh) + session.SetUserIdentifier("user-1") + require.NoError(t, session.Save(base, rec)) + + return &tmbEnv{oidc: oidc, idp: idp, cookies: rec.Result().Cookies(), access: access, newAccess: newAccess, newID: newID} +} + +func requestWithCookies(cs []*http.Cookie) *http.Request { + r := httptest.NewRequest(http.MethodGet, "https://app.example.com/", nil) + for _, c := range cs { + r.AddCookie(c) + } + return r +} + +func (e *tmbEnv) do(method, path string, mutate func(*http.Request)) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, "https://app.example.com"+path, nil) + for _, c := range e.cookies { + req.AddCookie(c) + } + if mutate != nil { + mutate(req) + } + rec := httptest.NewRecorder() + e.oidc.ServeHTTP(rec, req) + return rec +} + +func (e *tmbEnv) get(path string, mutate func(*http.Request)) *httptest.ResponseRecorder { + return e.do(http.MethodGet, path, mutate) +} + +func (e *tmbEnv) post(path string, mutate func(*http.Request)) *httptest.ResponseRecorder { + return e.do(http.MethodPost, path, mutate) +} + +func decodeTMB(t *testing.T, rec *httptest.ResponseRecorder) map[string]interface{} { + t.Helper() + var m map[string]interface{} + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &m), "body: %s", rec.Body.String()) + return m +} + +func TestTMBGet_ReturnsSessionAndAccessToken(t *testing.T) { + e := newTMBEnv(t) + rec := e.get(tmbPath, nil) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + body := decodeTMB(t, rec) + assert.Equal(t, true, body["authenticated"]) + assert.Equal(t, "user-1", body["user_identifier"]) + assert.Equal(t, []interface{}{"admins"}, body["groups"]) + assert.Equal(t, map[string]interface{}{"email": "u@example.com", "name": "U One"}, body["claims"]) + assert.Contains(t, body, "expires_at") + assert.Equal(t, e.access, body["access_token"]) + assert.InDelta(t, time.Now().Add(time.Hour).Unix(), body["expires_at"], 5, "the access token's expiry") + assert.NotContains(t, body, "expires_in", "expiry is reported once, as an absolute time") + assert.NotContains(t, rec.Body.String(), tmbTestRefresh, "the refresh token must never be returned") + + h := rec.Header() + assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, "no-store", h.Get("Cache-Control")) + assert.Equal(t, "nosniff", h.Get("X-Content-Type-Options")) + assert.Equal(t, "same-origin", h.Get("Cross-Origin-Resource-Policy")) + assert.Empty(t, h.Get("Access-Control-Allow-Origin")) + assert.Zero(t, e.idp.calls(), "GET does not call the IdP while the token is fresh") +} + +// setRefreshResponse makes the fake token endpoint answer the next grants with +// the given access token and expires_in (the refreshed ID token is valid). +func (e *tmbEnv) setRefreshResponse(t *testing.T, accessToken string, expiresIn int) { + t.Helper() + body, err := json.Marshal(map[string]interface{}{ + "access_token": accessToken, + "id_token": e.newID, + "refresh_token": tmbTestRotated, + "expires_in": expiresIn, + }) + require.NoError(t, err) + e.idp.mu.Lock() + e.idp.body = string(body) + e.idp.mu.Unlock() +} + +func TestTMB_ReportsTheAccessTokenExpiry(t *testing.T) { + t.Run("a session without a recorded expiry falls back to the token's exp claim", func(t *testing.T) { + e := newTMBEnv(t) + body := decodeTMB(t, e.get(tmbPath, nil)) + assert.InDelta(t, time.Now().Add(time.Hour).Unix(), body["expires_at"], 5) + }) + t.Run("a recorded expiry wins over the token's exp claim", func(t *testing.T) { + e := newTMBEnv(t) + want := time.Now().Add(2 * time.Minute).Unix() + session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies)) + require.NoError(t, err) + session.SetAccessTokenExpiresAt(session.GetAccessToken(), want) + saved := httptest.NewRecorder() + require.NoError(t, session.Save(requestWithCookies(e.cookies), saved)) + e.cookies = saved.Result().Cookies() + + body := decodeTMB(t, e.get(tmbPath, nil)) + assert.EqualValues(t, want, body["expires_at"], "the ID token and the JWT expire in an hour; the recorded value is used") + }) + t.Run("POST reports the token response's expires_in and the next GET keeps it", func(t *testing.T) { + e := newTMBEnv(t) + e.setRefreshResponse(t, e.newAccess, 1800) // the refreshed JWT itself is good for 2 h + rec := e.post(tmbPath, nil) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + body := decodeTMB(t, rec) + assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), body["expires_at"], 5) + + next := requestWithCookies(e.cookies) + for _, c := range rec.Result().Cookies() { + next.AddCookie(c) + } + session, err := e.oidc.sessionManager.GetSession(next) + require.NoError(t, err) + assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), session.GetAccessTokenExpiresAt(), 5) + }) + t.Run("an opaque access token gets its expiry from expires_in", func(t *testing.T) { + e := newTMBEnv(t) + e.setRefreshResponse(t, "opaque-access-token-0123456789abcdef", 1800) + body := decodeTMB(t, e.post(tmbPath, nil)) + assert.Equal(t, "opaque-access-token-0123456789abcdef", body["access_token"]) + assert.InDelta(t, time.Now().Add(30*time.Minute).Unix(), body["expires_at"], 5) + }) + t.Run("an opaque token with no expiry information reports none", func(t *testing.T) { + e := newTMBEnv(t) + e.setRefreshResponse(t, "opaque-access-token-0123456789abcdef", 0) + body := decodeTMB(t, e.post(tmbPath, nil)) + assert.Equal(t, "opaque-access-token-0123456789abcdef", body["access_token"]) + assert.NotContains(t, body, "expires_at") + }) +} + +// mutateSession rewrites the session behind the env's cookies. +func (e *tmbEnv) mutateSession(t *testing.T, fn func(*SessionData)) { + t.Helper() + session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies)) + require.NoError(t, err) + fn(session) + saved := httptest.NewRecorder() + require.NoError(t, session.Save(requestWithCookies(e.cookies), saved)) + e.cookies = saved.Result().Cookies() +} + +// An opaque access token is judged by the ID token (valid for an hour here), so +// the plugin's own refresh logic keeps serving it; the endpoint hands out the +// access token and must look at the access token's own expiry. +func TestTMB_RefreshesAnAccessTokenThatIsDue(t *testing.T) { + const opaque = "opaque-access-token-0123456789abcdef" + setup := func(t *testing.T, remaining time.Duration, opts ...func(*SessionData)) *tmbEnv { + e := newTMBEnv(t) + e.mutateSession(t, func(sd *SessionData) { + sd.SetAccessToken(opaque) + sd.SetAccessTokenExpiresAt(opaque, time.Now().Add(remaining).Unix()) + for _, opt := range opts { + opt(sd) + } + }) + return e + } + + t.Run("a token with plenty of life left is served as is", func(t *testing.T) { + e := setup(t, 30*time.Minute) + rec := e.get(tmbPath, nil) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, opaque, decodeTMB(t, rec)["access_token"]) + assert.Zero(t, e.idp.calls()) + }) + t.Run("one inside the grace window is refreshed before being returned", func(t *testing.T) { + e := setup(t, 20*time.Second) // the env's grace period is one minute + rec := e.get(tmbPath, nil) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, e.newAccess, decodeTMB(t, rec)["access_token"]) + assert.Equal(t, 1, e.idp.calls()) + assert.Equal(t, "refresh_token", e.idp.last(t).Get("grant_type")) + }) + t.Run("one that has already expired is refreshed too", func(t *testing.T) { + e := setup(t, -10*time.Second) + rec := e.get(tmbPath, nil) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, e.newAccess, decodeTMB(t, rec)["access_token"]) + }) + t.Run("an expired token the IdP cannot refresh right now is never served", func(t *testing.T) { + e := setup(t, -10*time.Second) + e.idp.status, e.idp.body = http.StatusInternalServerError, `oops` + rec := e.get(tmbPath, nil) + assert.Equal(t, http.StatusBadGateway, rec.Code) + assert.Equal(t, "server_error", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + }) + t.Run("an expired token with no refresh token means logging in again", func(t *testing.T) { + e := setup(t, -10*time.Second, func(sd *SessionData) { sd.SetRefreshToken("") }) + rec := e.get(tmbPath, nil) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + assert.Zero(t, e.idp.calls()) + }) + t.Run("an expired token whose refresh token is rejected ends the session", func(t *testing.T) { + e := setup(t, -10*time.Second) + e.idp.status, e.idp.body = http.StatusBadRequest, `{"error":"invalid_grant"}` + rec := e.get(tmbPath, nil) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + }) + t.Run("a token due inside the grace window is still served if the refresh fails", func(t *testing.T) { + e := setup(t, 20*time.Second) + e.idp.status, e.idp.body = http.StatusInternalServerError, `oops` + rec := e.get(tmbPath, nil) + require.Equal(t, http.StatusOK, rec.Code, "the token is still valid, so the failed early refresh is not fatal") + assert.Equal(t, opaque, decodeTMB(t, rec)["access_token"]) + }) +} + +func TestTMB_ClaimsAreOptIn(t *testing.T) { + t.Run("nothing is returned by default", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbClaims = nil }) + body := decodeTMB(t, e.get(tmbPath, nil)) + assert.NotContains(t, body, "claims") + assert.Equal(t, "user-1", body["user_identifier"], "identity comes from userIdentifierClaim, not tmbClaims") + assert.Equal(t, []interface{}{"admins"}, body["groups"], "groups come from groupClaimName, not tmbClaims") + }) + t.Run("only listed claims, as they appear in the token", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbClaims = []string{"groups", "email", "absent"} }) + body := decodeTMB(t, e.get(tmbPath, nil)) + assert.Equal(t, map[string]interface{}{ + "groups": []interface{}{"admins"}, + "email": "u@example.com", + }, body["claims"], "a non-scalar claim passes through; an absent claim is omitted; unlisted ones are not leaked") + }) + t.Run("claims of a refreshed token are returned after POST", func(t *testing.T) { + e := newTMBEnv(t) + body := decodeTMB(t, e.post(tmbPath, nil)) + assert.Equal(t, map[string]interface{}{"email": "u@example.com", "name": "U One"}, body["claims"]) + }) +} + +func TestTMBGet_IgnoresParametersAndNeverForcesRefresh(t *testing.T) { + e := newTMBEnv(t) + rec := e.get(tmbPath+"?refresh=true&scope=read&resource="+url.QueryEscape("https://api.example.com"), nil) + + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"]) + assert.Zero(t, e.idp.calls(), "a GET must have no side effect on the session") +} + +func TestTMBPost_ForcesRefresh(t *testing.T) { + e := newTMBEnv(t) + rec := e.post(tmbPath, nil) + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + body := decodeTMB(t, rec) + assert.Equal(t, e.newAccess, body["access_token"]) + assert.InDelta(t, time.Now().Add(2*time.Hour).Unix(), body["expires_at"], 5) + assert.Equal(t, "user-1", body["user_identifier"], "POST returns the same body shape as GET") + assert.Equal(t, []interface{}{"admins"}, body["groups"]) + + require.Equal(t, 1, e.idp.calls()) + form := e.idp.last(t) + assert.Equal(t, "refresh_token", form.Get("grant_type")) + assert.Equal(t, tmbTestRefresh, form.Get("refresh_token")) + assert.Empty(t, form.Get("scope")) + + // The refreshed tokens are persisted for later requests. + next := requestWithCookies(e.cookies) + for _, c := range rec.Result().Cookies() { + next.AddCookie(c) + } + session, err := e.oidc.sessionManager.GetSession(next) + require.NoError(t, err) + assert.Equal(t, e.newAccess, session.GetAccessToken()) + assert.Equal(t, tmbTestRotated, session.GetRefreshToken()) +} + +func TestTMBPost_ErrorsAnswerWithoutLeakingTokens(t *testing.T) { + t.Run("rejected refresh token ends the session", func(t *testing.T) { + e := newTMBEnv(t) + e.idp.status, e.idp.body = http.StatusBadRequest, `{"error":"invalid_grant"}` + rec := e.post(tmbPath, nil) + + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + }) + t.Run("idp failure keeps the session and answers 502", func(t *testing.T) { + e := newTMBEnv(t) + e.idp.status, e.idp.body = http.StatusInternalServerError, `oops` + rec := e.post(tmbPath, nil) + + assert.Equal(t, http.StatusBadGateway, rec.Code) + assert.Equal(t, "server_error", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code, "the session still works") + }) + t.Run("no refresh token is backend_not_ready", func(t *testing.T) { + e := newTMBEnv(t) + session, err := e.oidc.sessionManager.GetSession(requestWithCookies(e.cookies)) + require.NoError(t, err) + session.SetRefreshToken("") + rec0 := httptest.NewRecorder() + require.NoError(t, session.Save(requestWithCookies(e.cookies), rec0)) + e.cookies = rec0.Result().Cookies() + + rec := e.post(tmbPath, nil) + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, "backend_not_ready", decodeTMB(t, rec)["error"]) + assert.Zero(t, e.idp.calls()) + }) +} + +func TestTMB_NoSessionIsInvalidSession(t *testing.T) { + for _, method := range []string{http.MethodGet, http.MethodPost} { + e := newTMBEnv(t) + e.cookies = nil + rec := e.do(method, tmbPath, nil) + + assert.Equal(t, http.StatusUnauthorized, rec.Code, method) + assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"], method) + assert.Empty(t, rec.Header().Get("Location"), "must not redirect") + assert.Zero(t, e.idp.calls()) + } +} + +func TestTMB_RejectsOtherMethods(t *testing.T) { + e := newTMBEnv(t) + for _, m := range []string{http.MethodPut, http.MethodDelete, http.MethodPatch, http.MethodOptions, http.MethodHead} { + rec := e.do(m, tmbPath, nil) + assert.Equal(t, http.StatusMethodNotAllowed, rec.Code, m) + assert.Equal(t, "GET, POST", rec.Header().Get("Allow"), m) + } + assert.Zero(t, e.idp.calls()) +} + +func TestTMB_CrossOriginRequestsRejected(t *testing.T) { + e := newTMBEnv(t) + cases := map[string]func(*http.Request){ + "sec-fetch cross-site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "cross-site") }, + "sec-fetch same-site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-site") }, + "foreign origin": func(r *http.Request) { r.Header.Set("Origin", "https://evil.example") }, + "null origin": func(r *http.Request) { r.Header.Set("Origin", "null") }, + } + for name, mutate := range cases { + for _, method := range []string{http.MethodGet, http.MethodPost} { + rec := e.do(method, tmbPath, mutate) + assert.Equal(t, http.StatusForbidden, rec.Code, name+" "+method) + } + } + assert.Zero(t, e.idp.calls(), "a cross-origin request must not trigger a refresh") + for name, mutate := range map[string]func(*http.Request){ + "same-origin fetch": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") }, + "same origin header": func(r *http.Request) { r.Header.Set("Origin", "https://app.example.com") }, + "address bar": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "none") }, + } { + assert.Equal(t, http.StatusOK, e.get(tmbPath, mutate).Code, name) + } +} + +func TestTMB_ConfiguredPathEnablesEndpoint(t *testing.T) { + t.Run("unset path leaves the endpoint off", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbSessionURLPath = "" }) + for _, p := range []string{tmbPath, ""} { + assert.False(t, e.oidc.isTMBPath(p), p) + } + }) + t.Run("custom path is served and others are not", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.tmbSessionURLPath = "/api/me" }) + rec := e.get("/api/me", nil) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"]) + assert.False(t, e.oidc.isTMBPath(tmbPath)) + }) +} + +func TestConfigValidate_TMBPath(t *testing.T) { + valid := func() *Config { + c := CreateConfig() + c.ProviderURL = "https://provider.example.com" + c.ClientID = "id" + c.ClientSecret = "secret" + c.CallbackURL = "/callback" + c.SessionEncryptionKey = "0123456789abcdef0123456789abcdef" + return c + } + require.NoError(t, valid().Validate()) + + ok := valid() + ok.TMBSessionURL = tmbPath + require.NoError(t, ok.Validate()) + + cases := map[string]func(*Config){ + "no leading slash": func(c *Config) { c.TMBSessionURL = "session" }, + "query": func(c *Config) { c.TMBSessionURL = "/s?x=1" }, + "fragment": func(c *Config) { c.TMBSessionURL = "/s#x" }, + "equals callback": func(c *Config) { c.TMBSessionURL = "/callback" }, + "equals logout": func(c *Config) { c.LogoutURL = "/out"; c.TMBSessionURL = "/out" }, + "empty claim name": func(c *Config) { c.TMBClaims = []string{"email", ""} }, + "equals the derived default logout path": func(c *Config) { c.TMBSessionURL = "/callback/logout" }, + "equals back-channel path, written without a slash": func(c *Config) { + c.BackchannelLogoutURL, c.TMBSessionURL = "bc/logout", "/bc/logout" + }, + "equals front-channel path": func(c *Config) { + c.FrontchannelLogoutURL, c.TMBSessionURL = "/fc/logout", "/fc/logout" + }, + "leading //": func(c *Config) { c.TMBSessionURL = "//auth/session" }, + "backslash": func(c *Config) { c.TMBSessionURL = "/auth\\session" }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + c := valid() + mutate(c) + assert.Error(t, c.Validate()) + }) + } +} + +// The endpoint authenticates itself, so none of the bypasses may forward a +// request on its path to the backend (newTMBEnv's next fails the test). +func TestTMB_NoBypassForwardsToBackend(t *testing.T) { + cases := map[string]struct { + opt func(*TraefikOidc) + mutate func(*http.Request) + method string + }{ + "excluded URL": { + opt: func(o *TraefikOidc) { o.excludedURLs = map[string]struct{}{tmbPath: {}} }, + method: http.MethodGet, + }, + "SSE accept header": { + mutate: func(r *http.Request) { r.Header.Set("Accept", "text/event-stream") }, + method: http.MethodGet, + }, + "WebSocket upgrade": { + mutate: func(r *http.Request) { + r.Header.Set("Upgrade", "websocket") + r.Header.Set("Connection", "Upgrade") + }, + method: http.MethodGet, + }, + "unauthenticated preflight allowed": { + opt: func(o *TraefikOidc) { o.allowUnauthenticatedPreflight = true }, + mutate: func(r *http.Request) { + r.Header.Set("Origin", "https://app.example.com") + r.Header.Set("Access-Control-Request-Method", "POST") + }, + method: http.MethodOptions, + }, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + var opts []func(*TraefikOidc) + if c.opt != nil { + opts = append(opts, c.opt) + } + e := newTMBEnv(t, opts...) + rec := e.do(c.method, tmbPath, c.mutate) + if c.method == http.MethodOptions { + assert.Equal(t, http.StatusMethodNotAllowed, rec.Code) + return + } + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Equal(t, e.access, decodeTMB(t, rec)["access_token"]) + }) + } +} + +func TestTMBPost_SharesThePerSourceThrottle(t *testing.T) { + t.Run("forced refreshes are limited, reads are not", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.perSourceLimiter = newPerSourceAuthLimiter(2) }) + assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code) + assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code) + callsBefore := e.idp.calls() + + rec := e.post(tmbPath, nil) + assert.Equal(t, http.StatusTooManyRequests, rec.Code) + assert.Equal(t, "rate_limited", decodeTMB(t, rec)["error"]) + assert.Equal(t, "1", rec.Header().Get("Retry-After")) + assert.NotContains(t, rec.Body.String(), "access_token") + assert.Equal(t, callsBefore, e.idp.calls(), "a throttled POST must not reach the IdP") + + assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code, "GET stays available while throttled") + }) + t.Run("no limiter configured means no throttling", func(t *testing.T) { + e := newTMBEnv(t) + for i := 0; i < 5; i++ { + assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code) + } + }) + t.Run("internal sources are never throttled", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.perSourceLimiter = newPerSourceAuthLimiter(1) }) + for i := 0; i < 3; i++ { + rec := e.post(tmbPath, func(r *http.Request) { r.RemoteAddr = "10.1.2.3:4567" }) + assert.Equal(t, http.StatusOK, rec.Code) + } + }) +} + +func TestTMB_NeverEmitsCORSHeaders(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { + // What securityHeaders.corsEnabled does at the top of ServeHTTP. + o.securityHeadersApplier = func(rw http.ResponseWriter, _ *http.Request) { + rw.Header().Set("Access-Control-Allow-Origin", "https://evil.example") + rw.Header().Set("Access-Control-Allow-Credentials", "true") + rw.Header().Set("access-control-allow-headers", "x-anything") + rw.Header().Set("X-Frame-Options", "DENY") + } + }) + for _, rec := range []*httptest.ResponseRecorder{ + e.get(tmbPath, nil), + e.post(tmbPath, nil), + e.get(tmbPath, func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "cross-site") }), + e.do(http.MethodPut, tmbPath, nil), + } { + for name := range rec.Header() { + assert.NotContains(t, name, "Access-Control", "response %d", rec.Code) + } + assert.Equal(t, "DENY", rec.Header().Get("X-Frame-Options"), "unrelated security headers are kept") + } +} + +func TestTMB_AuthorizationGates(t *testing.T) { + t.Run("user not in allowlist", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedUsers = map[string]struct{}{"someone-else": {}} }) + for _, method := range []string{http.MethodGet, http.MethodPost} { + rec := e.do(method, tmbPath, nil) + assert.Equal(t, http.StatusForbidden, rec.Code, method) + assert.Equal(t, "access_denied", decodeTMB(t, rec)["error"]) + assert.NotContains(t, rec.Body.String(), "access_token") + } + assert.Zero(t, e.idp.calls(), "an unauthorized user must not trigger a refresh") + }) + t.Run("missing required group", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedRolesAndGroups = map[string]struct{}{"staff": {}} }) + assert.Equal(t, http.StatusForbidden, e.get(tmbPath, nil).Code) + assert.Equal(t, http.StatusForbidden, e.post(tmbPath, nil).Code) + assert.Zero(t, e.idp.calls(), "an unauthorized user must not trigger a refresh") + }) + t.Run("required group present", func(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.allowedRolesAndGroups = map[string]struct{}{"admins": {}} }) + assert.Equal(t, http.StatusOK, e.get(tmbPath, nil).Code) + assert.Equal(t, http.StatusOK, e.post(tmbPath, nil).Code) + }) +} + +func TestTMB_BearerHeaderDoesNotBypassSessionCheck(t *testing.T) { + e := newTMBEnv(t, func(o *TraefikOidc) { o.enableBearerAuth = true }) + e.cookies = nil + rec := e.get(tmbPath, func(r *http.Request) { r.Header.Set("Authorization", "Bearer a.b.c") }) + + assert.Equal(t, http.StatusUnauthorized, rec.Code) + assert.Equal(t, "invalid_session", decodeTMB(t, rec)["error"]) +} diff --git a/token_manager.go b/token_manager.go index 0a3cd40..99d1b51 100644 --- a/token_manager.go +++ b/token_manager.go @@ -622,6 +622,7 @@ func (t *TraefikOidc) refreshToken(rw http.ResponseWriter, req *http.Request, se session.SetIDToken(newToken.IDToken) session.SetAccessToken(newToken.AccessToken) + session.SetAccessTokenExpiresAt(newToken.AccessToken, accessTokenExpiry(newToken, time.Now())) if newToken.RefreshToken != "" { t.logger.Debug("Received new refresh token from provider") diff --git a/types.go b/types.go index 6be0651..09484d0 100644 --- a/types.go +++ b/types.go @@ -233,6 +233,8 @@ type TraefikOidc struct { stripAuthCookies bool enableBackchannelLogout bool enableFrontchannelLogout bool + tmbSessionURLPath string + tmbClaims []string requireTokenIntrospection bool allowPrivateIPAddresses bool // allowUnauthenticatedPreflight mirrors Config.AllowUnauthenticatedPreflight