mirror of
https://github.com/lukaszraczylo/traefikoidc.git
synced 2026-11-24 11:05:53 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
169a9f66f9 | ||
|
|
f7b96344e4 | ||
|
|
a8ae9fa49b | ||
|
|
2ceea0f617 | ||
|
|
972993980e |
@@ -8,6 +8,12 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|||||||
|
|
||||||
### Added
|
### 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`
|
- **`allowUnauthenticatedPreflight` (default `false`).** Every `OPTIONS`
|
||||||
request needs authentication by default, as in the last release. Set the
|
request needs authentication by default, as in the last release. Set the
|
||||||
option to `true` to let a genuine CORS preflight reach the backend
|
option to `true` to let a genuine CORS preflight reach the backend
|
||||||
@@ -121,6 +127,19 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **Provider metadata now recovers without a request (#147).** A discovery
|
||||||
|
response of `404`, `429` or `5xx` is now retried during startup. Traefik
|
||||||
|
answers `404` while the router of an IdP behind the same Traefik is not
|
||||||
|
loaded yet. During these retries, requests wait up to 30 s for
|
||||||
|
initialization, as they already do when the provider cannot be reached.
|
||||||
|
If startup discovery still fails, each middleware instance
|
||||||
|
retries in the background (5 s, doubling up to 60 s) until the provider
|
||||||
|
answers or the instance closes. Before this change, an instance stayed
|
||||||
|
broken until a request reached it. Background attempts log at ERROR for
|
||||||
|
the first three and then for every tenth, and at DEBUG otherwise. The
|
||||||
|
`503` served while metadata is unavailable or initialization times out
|
||||||
|
now carries `Retry-After: 10`. The startup error log names the
|
||||||
|
middleware.
|
||||||
- SSE and WebSocket requests now get the configured `headers`, as normal
|
- SSE and WebSocket requests now get the configured `headers`, as normal
|
||||||
requests do. The last release sent only `X-Forwarded-User` on these
|
requests do. The last release sent only `X-Forwarded-User` on these
|
||||||
requests, so a backend that checks a shared-secret header answered `401`
|
requests, so a backend that checks a shared-secret header answered `401`
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ Full reference in [docs/CONFIGURATION.md](docs/CONFIGURATION.md).
|
|||||||
| `refreshGracePeriodSeconds` | `60` | Proactively refresh tokens this many seconds before expiry. |
|
| `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. |
|
| `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`. |
|
| `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`. |
|
| `logLevel` | `info` | `debug`, `info`, `error`. |
|
||||||
| `audience` | `clientID`, or `resource` if set | Custom access-token audience (Auth0 custom APIs). |
|
| `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)). |
|
| `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`. |
|
| `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). |
|
| `enableBackchannelLogout` / `backchannelLogoutURL` | `false` / none | OIDC Back-Channel Logout (server-to-server). |
|
||||||
| `enableFrontchannelLogout` / `frontchannelLogoutURL` | `false` / none | OIDC Front-Channel Logout (iframe). |
|
| `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). |
|
| `redis` | disabled | See [docs/REDIS.md](docs/REDIS.md). |
|
||||||
| `dynamicClientRegistration` | disabled | See [docs/DCR.md](docs/DCR.md). |
|
| `dynamicClientRegistration` | disabled | See [docs/DCR.md](docs/DCR.md). |
|
||||||
|
|
||||||
|
|||||||
@@ -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())
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -444,6 +444,7 @@ func (t *TraefikOidc) handleCallback(rw http.ResponseWriter, req *http.Request,
|
|||||||
session.SetUserIdentifier(userIdentifier)
|
session.SetUserIdentifier(userIdentifier)
|
||||||
session.SetIDToken(tokenResponse.IDToken)
|
session.SetIDToken(tokenResponse.IDToken)
|
||||||
session.SetAccessToken(tokenResponse.AccessToken)
|
session.SetAccessToken(tokenResponse.AccessToken)
|
||||||
|
session.SetAccessTokenExpiresAt(tokenResponse.AccessToken, accessTokenExpiry(tokenResponse, time.Now()))
|
||||||
session.SetRefreshToken(tokenResponse.RefreshToken)
|
session.SetRefreshToken(tokenResponse.RefreshToken)
|
||||||
|
|
||||||
session.SetCSRF("")
|
session.SetCSRF("")
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
"net/url"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/stretchr/testify/suite"
|
"github.com/stretchr/testify/suite"
|
||||||
)
|
)
|
||||||
@@ -685,6 +686,60 @@ func (s *AuthFlowBehaviourSuite) TestHandleCallback_SuccessfulAuthentication() {
|
|||||||
mockVerifier.AssertVerifyTokenCalled(s.T())
|
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": "[email protected]", "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
|
// TestHandleExpiredToken tests expired token handling
|
||||||
func (s *AuthFlowBehaviourSuite) TestHandleExpiredToken() {
|
func (s *AuthFlowBehaviourSuite) TestHandleExpiredToken() {
|
||||||
sessionManager, err := NewSessionManager(
|
sessionManager, err := NewSessionManager(
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -39,6 +40,7 @@ import (
|
|||||||
|
|
||||||
oidc "github.com/lukaszraczylo/traefikoidc"
|
oidc "github.com/lukaszraczylo/traefikoidc"
|
||||||
recovery "github.com/lukaszraczylo/traefikoidc/internal/recovery"
|
recovery "github.com/lukaszraczylo/traefikoidc/internal/recovery"
|
||||||
|
fixtures "github.com/lukaszraczylo/traefikoidc/internal/testutil/fixtures"
|
||||||
servers "github.com/lukaszraczylo/traefikoidc/internal/testutil/servers"
|
servers "github.com/lukaszraczylo/traefikoidc/internal/testutil/servers"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -128,6 +130,7 @@ func main() {
|
|||||||
// reachable errors.As-replacement site directly under the interpreter.
|
// reachable errors.As-replacement site directly under the interpreter.
|
||||||
runCheck("new01-retryexecutor-500-retried", checkNew01RetryExecutorHTTPError500Retried)
|
runCheck("new01-retryexecutor-500-retried", checkNew01RetryExecutorHTTPError500Retried)
|
||||||
runCheck("new01-retryexecutor-400-not-retried", checkNew01RetryExecutorHTTPError400NotRetried)
|
runCheck("new01-retryexecutor-400-not-retried", checkNew01RetryExecutorHTTPError400NotRetried)
|
||||||
|
runCheck("issue147-discovery-status-retried", checkIssue147DiscoveryStatusRetried)
|
||||||
runCheck("new01-retryexecutor-plain-error-no-panic", checkNew01RetryExecutorPlainErrorNoPanic)
|
runCheck("new01-retryexecutor-plain-error-no-panic", checkNew01RetryExecutorPlainErrorNoPanic)
|
||||||
runCheck("new01-internal-recovery-httperror-classification", checkNew01InternalRecoveryHTTPErrorClassification)
|
runCheck("new01-internal-recovery-httperror-classification", checkNew01InternalRecoveryHTTPErrorClassification)
|
||||||
runCheck("new01-internal-recovery-oidcerror-classification", checkNew01InternalRecoveryOIDCErrorClassification)
|
runCheck("new01-internal-recovery-oidcerror-classification", checkNew01InternalRecoveryOIDCErrorClassification)
|
||||||
@@ -141,6 +144,8 @@ func main() {
|
|||||||
runCheck("issue162-websocket-forwards-header-templates", checkIssue162WebSocketHeaderTemplates)
|
runCheck("issue162-websocket-forwards-header-templates", checkIssue162WebSocketHeaderTemplates)
|
||||||
runCheck("tojson-header-template", checkToJsonHeaderTemplate)
|
runCheck("tojson-header-template", checkToJsonHeaderTemplate)
|
||||||
runCheck("streaming-refresh-revoked-grant-rejected", checkStreamingRefreshRevokedGrant)
|
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")
|
fmt.Println("OK: all yaegi regression checks passed")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -390,6 +395,60 @@ func checkNew01RetryExecutorHTTPError400NotRetried() (string, error) {
|
|||||||
return fmt.Sprintf(" calls=%d", calls), nil
|
return fmt.Sprintf(" calls=%d", calls), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkIssue147DiscoveryStatusRetried pins #147 under the interpreter: a
|
||||||
|
// discovery 404 and 502 come back from GetProviderMetadata as *HTTPError, and
|
||||||
|
// MetadataFetchRetryConfig retries both (RetryableStatusCodes for the 404,
|
||||||
|
// the 5xx rule for the 502) until the document is served.
|
||||||
|
func checkIssue147DiscoveryStatusRetried() (string, error) {
|
||||||
|
var hits int32
|
||||||
|
var srv *httptest.Server
|
||||||
|
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch atomic.AddInt32(&hits, 1) {
|
||||||
|
case 1:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
case 2:
|
||||||
|
w.WriteHeader(http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(oidc.ProviderMetadata{
|
||||||
|
Issuer: srv.URL,
|
||||||
|
AuthURL: srv.URL + "/auth",
|
||||||
|
TokenURL: srv.URL + "/token",
|
||||||
|
JWKSURL: srv.URL + "/jwks",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
cfg := oidc.MetadataFetchRetryConfig()
|
||||||
|
cfg.MaxAttempts = 4
|
||||||
|
cfg.InitialDelay = time.Millisecond
|
||||||
|
cfg.MaxDelay = time.Millisecond
|
||||||
|
re := oidc.NewRetryExecutor(cfg, oidc.NewLogger("error"))
|
||||||
|
mc := oidc.NewMetadataCacheWithLogger(nil, oidc.NewLogger("error"))
|
||||||
|
|
||||||
|
var issuer string
|
||||||
|
err := re.ExecuteWithContext(context.Background(), func() error {
|
||||||
|
metadata, fetchErr := mc.GetProviderMetadata(context.Background(), srv.URL, srv.Client())
|
||||||
|
if fetchErr != nil {
|
||||||
|
return fetchErr
|
||||||
|
}
|
||||||
|
issuer = metadata.Issuer
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("discovery 404/502 were not retried to success: %v (requests=%d)", err, atomic.LoadInt32(&hits))
|
||||||
|
}
|
||||||
|
if issuer != srv.URL {
|
||||||
|
return "", fmt.Errorf("issuer = %q, want %q", issuer, srv.URL)
|
||||||
|
}
|
||||||
|
if got := atomic.LoadInt32(&hits); got != 3 {
|
||||||
|
return "", fmt.Errorf("requests = %d, want 3 (404, 502, 200)", got)
|
||||||
|
}
|
||||||
|
return " requests=3", nil
|
||||||
|
}
|
||||||
|
|
||||||
// checkNew01RetryExecutorPlainErrorNoPanic pins that a plain (non-HTTPError)
|
// checkNew01RetryExecutorPlainErrorNoPanic pins that a plain (non-HTTPError)
|
||||||
// error reaching isRetryableError's asHTTPError check never panics under
|
// error reaching isRetryableError's asHTTPError check never panics under
|
||||||
// yaegi -- the exact call shape that panicked pre-fix regardless of err's
|
// yaegi -- the exact call shape that panicked pre-fix regardless of err's
|
||||||
@@ -982,6 +1041,268 @@ func checkStreamingRefreshRevokedGrant() (string, error) {
|
|||||||
return "", nil
|
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("[email protected]")
|
||||||
|
// 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":"[email protected]","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": "[email protected]",
|
||||||
|
"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("[email protected]")
|
||||||
|
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"] != "[email protected]" {
|
||||||
|
return "", fmt.Errorf("GET: unexpected identity/token in %v", body)
|
||||||
|
}
|
||||||
|
claims, _ := body["claims"].(map[string]interface{})
|
||||||
|
if len(claims) != 1 || claims["email"] != "[email protected]" {
|
||||||
|
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
|
// checkErrAbortHandlerAbortsUnderYaegi guards the re-review finding on
|
||||||
// ServeHTTP's ErrAbortHandler branch (middleware.go): under yaegi v0.16.1,
|
// ServeHTTP's ErrAbortHandler branch (middleware.go): under yaegi v0.16.1,
|
||||||
// `r == http.ErrAbortHandler` only ever matches a panic raised by COMPILED
|
// `r == http.ErrAbortHandler` only ever matches a panic raised by COMPILED
|
||||||
|
|||||||
@@ -82,6 +82,8 @@ func (c Config) configToMap() map[string]interface{} {
|
|||||||
result["cookiePath"] = c.CookiePath
|
result["cookiePath"] = c.CookiePath
|
||||||
result["enableBackchannelLogout"] = c.EnableBackchannelLogout
|
result["enableBackchannelLogout"] = c.EnableBackchannelLogout
|
||||||
result["enableFrontchannelLogout"] = c.EnableFrontchannelLogout
|
result["enableFrontchannelLogout"] = c.EnableFrontchannelLogout
|
||||||
|
result["tmbSessionURL"] = c.TMBSessionURL
|
||||||
|
result["tmbClaims"] = c.TMBClaims
|
||||||
result["backchannelLogoutURL"] = c.BackchannelLogoutURL
|
result["backchannelLogoutURL"] = c.BackchannelLogoutURL
|
||||||
result["frontchannelLogoutURL"] = c.FrontchannelLogoutURL
|
result["frontchannelLogoutURL"] = c.FrontchannelLogoutURL
|
||||||
result["caCertPath"] = c.CACertPath
|
result["caCertPath"] = c.CACertPath
|
||||||
|
|||||||
@@ -921,82 +921,6 @@ func TestMemoryTestOrchestrator_StopLeakDetection_CoverageBoost(t *testing.T) {
|
|||||||
// CHUNK MANAGER TESTS
|
// CHUNK MANAGER TESTS
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
||||||
func TestChunkManager_GetSessionCount_CoverageBoost(t *testing.T) {
|
|
||||||
logger := NewLogger("debug")
|
|
||||||
cm := NewChunkManager(logger)
|
|
||||||
if cm == nil {
|
|
||||||
t.Fatal("Expected non-nil ChunkManager")
|
|
||||||
}
|
|
||||||
defer cm.Shutdown()
|
|
||||||
|
|
||||||
// Test GetSessionCount
|
|
||||||
count := cm.GetSessionCount()
|
|
||||||
if count != 0 {
|
|
||||||
t.Errorf("Expected 0 sessions, got %d", count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChunkManager_GetMemoryStats_CoverageBoost(t *testing.T) {
|
|
||||||
logger := NewLogger("debug")
|
|
||||||
cm := NewChunkManager(logger)
|
|
||||||
if cm == nil {
|
|
||||||
t.Fatal("Expected non-nil ChunkManager")
|
|
||||||
}
|
|
||||||
defer cm.Shutdown()
|
|
||||||
|
|
||||||
// Test GetMemoryStats
|
|
||||||
stats := cm.GetMemoryStats()
|
|
||||||
if stats == nil {
|
|
||||||
t.Fatal("Expected non-nil stats")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify expected keys exist
|
|
||||||
if _, ok := stats["active_sessions"]; !ok {
|
|
||||||
t.Error("Expected active_sessions key in stats")
|
|
||||||
}
|
|
||||||
if _, ok := stats["max_sessions"]; !ok {
|
|
||||||
t.Error("Expected max_sessions key in stats")
|
|
||||||
}
|
|
||||||
if _, ok := stats["bytes_allocated"]; !ok {
|
|
||||||
t.Error("Expected bytes_allocated key in stats")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChunkManager_CanCreateSession_CoverageBoost(t *testing.T) {
|
|
||||||
logger := NewLogger("debug")
|
|
||||||
cm := NewChunkManager(logger)
|
|
||||||
if cm == nil {
|
|
||||||
t.Fatal("Expected non-nil ChunkManager")
|
|
||||||
}
|
|
||||||
defer cm.Shutdown()
|
|
||||||
|
|
||||||
// Test CanCreateSession - should be true initially
|
|
||||||
canCreate, err := cm.CanCreateSession()
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if !canCreate {
|
|
||||||
t.Error("Expected CanCreateSession to return true when empty")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChunkManager_EmergencyCleanup_CoverageBoost(t *testing.T) {
|
|
||||||
logger := NewLogger("debug")
|
|
||||||
cm := NewChunkManager(logger)
|
|
||||||
if cm == nil {
|
|
||||||
t.Fatal("Expected non-nil ChunkManager")
|
|
||||||
}
|
|
||||||
defer cm.Shutdown()
|
|
||||||
|
|
||||||
// Test EmergencyCleanup - should not panic on empty session map
|
|
||||||
cm.EmergencyCleanup()
|
|
||||||
|
|
||||||
// Verify no sessions exist
|
|
||||||
if cm.GetSessionCount() != 0 {
|
|
||||||
t.Error("Expected 0 sessions after cleanup")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChunkManager_CleanupExpiredSessions_CoverageBoost(t *testing.T) {
|
func TestChunkManager_CleanupExpiredSessions_CoverageBoost(t *testing.T) {
|
||||||
logger := NewLogger("debug")
|
logger := NewLogger("debug")
|
||||||
cm := NewChunkManager(logger)
|
cm := NewChunkManager(logger)
|
||||||
@@ -1008,8 +932,7 @@ func TestChunkManager_CleanupExpiredSessions_CoverageBoost(t *testing.T) {
|
|||||||
// Test CleanupExpiredSessions - should not panic on empty session map
|
// Test CleanupExpiredSessions - should not panic on empty session map
|
||||||
cm.CleanupExpiredSessions()
|
cm.CleanupExpiredSessions()
|
||||||
|
|
||||||
// Verify no sessions exist
|
if len(cm.sessionMap) != 0 {
|
||||||
if cm.GetSessionCount() != 0 {
|
|
||||||
t.Error("Expected 0 sessions after cleanup")
|
t.Error("Expected 0 sessions after cleanup")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,12 +195,14 @@ clientSecret: your-client-secret
|
|||||||
| `clientAssertionKeyID` | string | none | `kid` header for `private_key_jwt` assertions. Required when `clientAuthMethod: private_key_jwt`. |
|
| `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`. |
|
| `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). |
|
| `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). |
|
| `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). |
|
| `enableBackchannelLogout` | bool | `false` | Enable OIDC back-channel logout (IdP-initiated, server-to-server). |
|
||||||
| `backchannelLogoutURL` | string | derived | Back-channel logout endpoint path. |
|
| `backchannelLogoutURL` | string | derived | Back-channel logout endpoint path. |
|
||||||
| `enableFrontchannelLogout` | bool | `false` | Enable OIDC front-channel logout (browser iframe logout). |
|
| `enableFrontchannelLogout` | bool | `false` | Enable OIDC front-channel logout (browser iframe logout). |
|
||||||
| `frontchannelLogoutURL` | string | derived | Front-channel logout endpoint path. |
|
| `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`. |
|
| `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. |
|
| `insecureSkipVerify` | bool | `false` | Disable TLS verification for the OIDC client (load balancer / mTLS edge). Emits a loud warning at startup. |
|
||||||
|
|
||||||
|
|||||||
+148
@@ -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.
|
||||||
+16
-2
@@ -9,6 +9,7 @@ import (
|
|||||||
"math"
|
"math"
|
||||||
"math/rand/v2"
|
"math/rand/v2"
|
||||||
"net"
|
"net"
|
||||||
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -476,6 +477,9 @@ func (cb *CircuitBreaker) GetMetrics() map[string]interface{} {
|
|||||||
type RetryConfig struct {
|
type RetryConfig struct {
|
||||||
// RetryableErrors defines error patterns that should trigger retries
|
// RetryableErrors defines error patterns that should trigger retries
|
||||||
RetryableErrors []string `json:"retryable_errors"`
|
RetryableErrors []string `json:"retryable_errors"`
|
||||||
|
// RetryableStatusCodes lists HTTP statuses retried even though they are
|
||||||
|
// below 500 and not 429
|
||||||
|
RetryableStatusCodes []int `json:"retryable_status_codes"`
|
||||||
// MaxAttempts is the maximum number of retry attempts
|
// MaxAttempts is the maximum number of retry attempts
|
||||||
MaxAttempts int `json:"max_attempts"`
|
MaxAttempts int `json:"max_attempts"`
|
||||||
// InitialDelay is the delay before the first retry
|
// InitialDelay is the delay before the first retry
|
||||||
@@ -528,6 +532,9 @@ func MetadataFetchRetryConfig() RetryConfig {
|
|||||||
"x509",
|
"x509",
|
||||||
"tls",
|
"tls",
|
||||||
},
|
},
|
||||||
|
// Traefik answers 404 for a provider router that is not loaded yet
|
||||||
|
// (IdP behind the same Traefik, #147).
|
||||||
|
RetryableStatusCodes: []int{http.StatusNotFound},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -766,8 +773,15 @@ func (re *RetryExecutor) isRetryableError(err error) bool {
|
|||||||
// "EOF" (isEOFError), or a generic "timeout" — would be reclassified
|
// "EOF" (isEOFError), or a generic "timeout" — would be reclassified
|
||||||
// retryable and retried to MaxAttempts on a permanent error, repeating
|
// retryable and retried to MaxAttempts on a permanent error, repeating
|
||||||
// the failing request (R123, R157).
|
// the failing request (R123, R157).
|
||||||
if statusHTTP, ok := asHTTPError(err); ok && statusHTTP.StatusCode != 0 && statusHTTP.StatusCode < 500 && statusHTTP.StatusCode != 429 {
|
if statusHTTP, ok := asHTTPError(err); ok && statusHTTP.StatusCode != 0 {
|
||||||
return false
|
for _, code := range re.config.RetryableStatusCodes {
|
||||||
|
if statusHTTP.StatusCode == code {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if statusHTTP.StatusCode < 500 && statusHTTP.StatusCode != 429 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for Traefik default certificate error (startup race condition)
|
// Check for Traefik default certificate error (startup race condition)
|
||||||
|
|||||||
+28
@@ -93,6 +93,34 @@ type TokenResponse struct {
|
|||||||
ExpiresIn int `json:"expires_in"`
|
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.
|
// exchangeTokens performs OAuth 2.0 token exchange with the authorization server.
|
||||||
// It supports both authorization code and refresh token grant types with PKCE support.
|
// It supports both authorization code and refresh token grant types with PKCE support.
|
||||||
// Parameters:
|
// Parameters:
|
||||||
|
|||||||
@@ -336,7 +336,9 @@ func TestIssue152NewWithContextWiring(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("discovery fails outright, cold-start seed holds", func(t *testing.T) {
|
t.Run("discovery fails outright, cold-start seed holds", func(t *testing.T) {
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
// A status startup discovery does not retry (#147 retries 404,
|
||||||
|
// 429 and 5xx), so discovery fails at once.
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
}))
|
}))
|
||||||
defer srv.Close()
|
defer srv.Close()
|
||||||
|
|
||||||
|
|||||||
@@ -355,6 +355,8 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
|
|||||||
stripAuthCookies: config.StripAuthCookies,
|
stripAuthCookies: config.StripAuthCookies,
|
||||||
enableBackchannelLogout: config.EnableBackchannelLogout,
|
enableBackchannelLogout: config.EnableBackchannelLogout,
|
||||||
enableFrontchannelLogout: config.EnableFrontchannelLogout,
|
enableFrontchannelLogout: config.EnableFrontchannelLogout,
|
||||||
|
tmbSessionURLPath: config.TMBSessionURL,
|
||||||
|
tmbClaims: config.TMBClaims,
|
||||||
backchannelLogoutPath: normalizeLogoutPath(config.BackchannelLogoutURL),
|
backchannelLogoutPath: normalizeLogoutPath(config.BackchannelLogoutURL),
|
||||||
frontchannelLogoutPath: normalizeLogoutPath(config.FrontchannelLogoutURL),
|
frontchannelLogoutPath: normalizeLogoutPath(config.FrontchannelLogoutURL),
|
||||||
sessionInvalidationCache: cacheManager.GetSharedSessionInvalidationCache(),
|
sessionInvalidationCache: cacheManager.GetSharedSessionInvalidationCache(),
|
||||||
@@ -572,7 +574,7 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
|
|||||||
t.safeLogErrorf("Initialize metadata goroutine panic recovered: %v", r)
|
t.safeLogErrorf("Initialize metadata goroutine panic recovered: %v", r)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
t.initializeMetadata(config.ProviderURL)
|
t.runMetadataInit(config.ProviderURL, metadataRecoveryBackoff())
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Setup cleanup hook for when context is canceled
|
// Setup cleanup hook for when context is canceled
|
||||||
@@ -587,12 +589,97 @@ func NewWithContext(ctx context.Context, config *Config, next http.Handler, name
|
|||||||
return t, nil
|
return t, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// metadataRecoveryFetchTimeout bounds one background discovery request.
|
||||||
|
const metadataRecoveryFetchTimeout = 15 * time.Second
|
||||||
|
|
||||||
|
// metadataRecoveryBackoff paces background discovery after startup discovery
|
||||||
|
// fails: 5s, doubling up to 60s, with jitter.
|
||||||
|
func metadataRecoveryBackoff() RetryConfig {
|
||||||
|
return RetryConfig{
|
||||||
|
InitialDelay: 5 * time.Second,
|
||||||
|
MaxDelay: 60 * time.Second,
|
||||||
|
BackoffFactor: 2,
|
||||||
|
EnableJitter: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runMetadataInit runs startup discovery and, if it fails, keeps retrying in
|
||||||
|
// the background, so an instance recovers once the provider answers without
|
||||||
|
// waiting for a request to trigger recovery (#147).
|
||||||
|
func (t *TraefikOidc) runMetadataInit(providerURL string, backoff RetryConfig) {
|
||||||
|
if t.initializeMetadata(providerURL) || providerURL == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.recoverMetadataInBackground(providerURL, backoff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// recoverMetadataInBackground retries discovery with backoff until it
|
||||||
|
// succeeds, another path has adopted metadata, or the instance closes.
|
||||||
|
// Instances that share providerURL also share the metadata cache, so after the
|
||||||
|
// first success the others adopt the cached document without a fetch.
|
||||||
|
func (t *TraefikOidc) recoverMetadataInBackground(providerURL string, backoff RetryConfig) {
|
||||||
|
if t.metadataCache == nil || t.httpClient == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx := t.lifecycleCtx()
|
||||||
|
pacer := NewRetryExecutor(backoff, t.logger)
|
||||||
|
for attempt := 1; ; attempt++ {
|
||||||
|
timer := time.NewTimer(pacer.calculateDelay(attempt))
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
timer.Stop()
|
||||||
|
return
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
if t.metadataReady() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchCtx, cancel := context.WithTimeout(ctx, metadataRecoveryFetchTimeout)
|
||||||
|
metadata, err := t.metadataCache.GetProviderMetadata(fetchCtx, providerURL, t.httpClient)
|
||||||
|
cancel()
|
||||||
|
if err != nil || metadata == nil {
|
||||||
|
t.logMetadataRecoveryFailure(attempt, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t.updateMetadataEndpoints(metadata)
|
||||||
|
if !t.metadataReady() {
|
||||||
|
t.logMetadataRecoveryFailure(attempt, fmt.Errorf("discovery document has no usable issuer"))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t.safeLogInfo(fmt.Sprintf("Recovered OIDC provider metadata for middleware %q in the background", t.name))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Background recovery logs the first metadataRecoveryLoudAttempts failures and
|
||||||
|
// then every metadataRecoveryLogEvery-th at ERROR, the rest at DEBUG, so a
|
||||||
|
// permanently wrong providerURL does not flood the log.
|
||||||
|
const (
|
||||||
|
metadataRecoveryLoudAttempts = 3
|
||||||
|
metadataRecoveryLogEvery = 10
|
||||||
|
)
|
||||||
|
|
||||||
|
// metadataRecoveryLogLoud reports whether a failed background attempt logs at ERROR.
|
||||||
|
func metadataRecoveryLogLoud(attempt int) bool {
|
||||||
|
return attempt <= metadataRecoveryLoudAttempts || attempt%metadataRecoveryLogEvery == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TraefikOidc) logMetadataRecoveryFailure(attempt int, err error) {
|
||||||
|
if metadataRecoveryLogLoud(attempt) {
|
||||||
|
t.safeLogErrorf("Provider metadata for middleware %q still unavailable (background attempt %d): %v", t.name, attempt, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.safeLogDebugf("Provider metadata for middleware %q still unavailable (background attempt %d): %v", t.name, attempt, err)
|
||||||
|
}
|
||||||
|
|
||||||
// initializeMetadata initializes OIDC provider metadata by fetching configuration.
|
// initializeMetadata initializes OIDC provider metadata by fetching configuration.
|
||||||
// It retrieves the provider's .well-known/openid-configuration and updates
|
// It retrieves the provider's .well-known/openid-configuration and updates
|
||||||
// internal endpoint URLs. Uses error recovery if available for resilient fetching.
|
// internal endpoint URLs. Uses error recovery if available for resilient fetching.
|
||||||
|
// It reports whether metadata was adopted.
|
||||||
// Parameters:
|
// Parameters:
|
||||||
// - providerURL: The base URL of the OIDC provider.
|
// - providerURL: The base URL of the OIDC provider.
|
||||||
func (t *TraefikOidc) initializeMetadata(providerURL string) {
|
func (t *TraefikOidc) initializeMetadata(providerURL string) bool {
|
||||||
t.safeLogDebug("Starting provider metadata discovery")
|
t.safeLogDebug("Starting provider metadata discovery")
|
||||||
|
|
||||||
// Ensure initComplete is always closed, even on failure
|
// Ensure initComplete is always closed, even on failure
|
||||||
@@ -609,22 +696,27 @@ func (t *TraefikOidc) initializeMetadata(providerURL string) {
|
|||||||
var metadata *ProviderMetadata
|
var metadata *ProviderMetadata
|
||||||
var err error
|
var err error
|
||||||
if t.errorRecoveryManager != nil {
|
if t.errorRecoveryManager != nil {
|
||||||
metadata, err = t.metadataCache.GetMetadataWithRecovery(providerURL, t.httpClient, t.logger, t.errorRecoveryManager)
|
metadata, err = t.metadataCache.GetMetadataWithRecovery(t.lifecycleCtx(), providerURL, t.httpClient, t.logger, t.errorRecoveryManager)
|
||||||
} else {
|
} else {
|
||||||
metadata, err = t.metadataCache.GetMetadata(providerURL, t.httpClient, t.logger)
|
metadata, err = t.metadataCache.GetMetadata(providerURL, t.httpClient, t.logger)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.safeLogErrorf("Failed to get provider metadata: %v", err)
|
if t.lifecycleCtx().Err() != nil {
|
||||||
return
|
t.safeLogDebugf("Provider metadata discovery for middleware %q stopped: instance closed", t.name)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
t.safeLogErrorf("Failed to get provider metadata for middleware %q: %v", t.name, err)
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata != nil {
|
if metadata != nil {
|
||||||
t.safeLogDebug("Successfully initialized provider metadata")
|
t.safeLogDebug("Successfully initialized provider metadata")
|
||||||
t.updateMetadataEndpoints(metadata)
|
t.updateMetadataEndpoints(metadata)
|
||||||
return
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
t.safeLogError("Received nil metadata during initialization")
|
t.safeLogError("Received nil metadata during initialization")
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Discovered-endpoint names. jwks_uri, authorization and token have no
|
// Discovered-endpoint names. jwks_uri, authorization and token have no
|
||||||
|
|||||||
+4
-1
@@ -2647,7 +2647,10 @@ func TestMetadataRecoveryOnProviderFailure(t *testing.T) {
|
|||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
|
|
||||||
if !available {
|
if !available {
|
||||||
w.WriteHeader(http.StatusServiceUnavailable)
|
// A status startup discovery does not retry, so init fails at
|
||||||
|
// once and the test can drive request-path recovery (#147
|
||||||
|
// retries 404, 429 and 5xx at startup).
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-8
@@ -138,7 +138,8 @@ func (mc *MetadataCache) GetProviderMetadata(ctx context.Context, providerURL st
|
|||||||
defer func() { _ = resp.Body.Close() }() // Safe to ignore: closing body on defer
|
defer func() { _ = resp.Body.Close() }() // Safe to ignore: closing body on defer
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return nil, fmt.Errorf("metadata fetch returned status %d", resp.StatusCode)
|
// Typed so the retry classification can read the status.
|
||||||
|
return nil, &HTTPError{StatusCode: resp.StatusCode, Message: "metadata fetch failed"}
|
||||||
}
|
}
|
||||||
|
|
||||||
var metadata ProviderMetadata
|
var metadata ProviderMetadata
|
||||||
@@ -212,10 +213,11 @@ func (mc *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client
|
|||||||
// GetMetadataWithRecovery fetches metadata with retry support for startup scenarios.
|
// GetMetadataWithRecovery fetches metadata with retry support for startup scenarios.
|
||||||
// This handles the race condition where Traefik initializes the plugin before the
|
// This handles the race condition where Traefik initializes the plugin before the
|
||||||
// OIDC provider routes are fully established, or before TLS certificates are loaded.
|
// OIDC provider routes are fully established, or before TLS certificates are loaded.
|
||||||
// Uses aggressive retry settings (10 attempts, 1s intervals) to give the infrastructure
|
// It makes up to 10 attempts with backoff from 1s, x1.5, capped at 10s (about 51s
|
||||||
// time to stabilize during cold starts.
|
// of delay), so the infrastructure has time to stabilize during cold starts.
|
||||||
|
// The retries stop when ctx ends.
|
||||||
// See: https://github.com/lukaszraczylo/traefikoidc/issues/90
|
// See: https://github.com/lukaszraczylo/traefikoidc/issues/90
|
||||||
func (mc *MetadataCache) GetMetadataWithRecovery(providerURL string, httpClient *http.Client, logger *Logger, errorRecoveryManager *ErrorRecoveryManager) (*ProviderMetadata, error) {
|
func (mc *MetadataCache) GetMetadataWithRecovery(ctx context.Context, providerURL string, httpClient *http.Client, logger *Logger, errorRecoveryManager *ErrorRecoveryManager) (*ProviderMetadata, error) {
|
||||||
// Check cache first - if we have valid cached metadata, use it
|
// Check cache first - if we have valid cached metadata, use it
|
||||||
if metadata, exists := mc.Get(providerURL); exists {
|
if metadata, exists := mc.Get(providerURL); exists {
|
||||||
return metadata, nil
|
return metadata, nil
|
||||||
@@ -229,13 +231,13 @@ func (mc *MetadataCache) GetMetadataWithRecovery(providerURL string, httpClient
|
|||||||
var lastErr error
|
var lastErr error
|
||||||
|
|
||||||
// Use context with overall timeout for the entire retry sequence
|
// Use context with overall timeout for the entire retry sequence
|
||||||
// 10 attempts * ~10s max delay = ~100s worst case, so use 2 minute timeout
|
// About 51s of delay plus up to 15s per attempt, so use a 2 minute timeout
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
retryCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
err := retryExecutor.ExecuteWithContext(ctx, func() error {
|
err := retryExecutor.ExecuteWithContext(retryCtx, func() error {
|
||||||
// Create per-attempt context with shorter timeout
|
// Create per-attempt context with shorter timeout
|
||||||
attemptCtx, attemptCancel := context.WithTimeout(ctx, 15*time.Second)
|
attemptCtx, attemptCancel := context.WithTimeout(retryCtx, 15*time.Second)
|
||||||
defer attemptCancel()
|
defer attemptCancel()
|
||||||
|
|
||||||
var fetchErr error
|
var fetchErr error
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package traefikoidc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newFlakyDiscovery serves failStatus for the first failures discovery
|
||||||
|
// requests, then a valid document whose endpoints share the server's host.
|
||||||
|
// The returned provider URL is unique to the test, so the process-wide
|
||||||
|
// metadata cache never answers with another test's document.
|
||||||
|
func newFlakyDiscovery(t *testing.T, failStatus int, failures int32) (*httptest.Server, string, *atomic.Int32) {
|
||||||
|
t.Helper()
|
||||||
|
hits := &atomic.Int32{}
|
||||||
|
var srv *httptest.Server
|
||||||
|
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if hits.Add(1) <= failures {
|
||||||
|
w.WriteHeader(failStatus)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(ProviderMetadata{
|
||||||
|
Issuer: srv.URL,
|
||||||
|
AuthURL: srv.URL + "/auth",
|
||||||
|
TokenURL: srv.URL + "/token",
|
||||||
|
JWKSURL: srv.URL + "/jwks",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
return srv, srv.URL + "/" + strings.ReplaceAll(t.Name(), "/", "_"), hits
|
||||||
|
}
|
||||||
|
|
||||||
|
// fastRetry shrinks a retry config's delays so a test runs in milliseconds.
|
||||||
|
func fastRetry(cfg RetryConfig, attempts int) RetryConfig {
|
||||||
|
cfg.MaxAttempts = attempts
|
||||||
|
cfg.InitialDelay = time.Millisecond
|
||||||
|
cfg.MaxDelay = time.Millisecond
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRecoveryTestOIDC builds an instance whose provider metadata is not yet
|
||||||
|
// known and whose startup gate is still open, as New leaves it before init.
|
||||||
|
func newRecoveryTestOIDC(t *testing.T, srv *httptest.Server, providerURL string) *TraefikOidc {
|
||||||
|
t.Helper()
|
||||||
|
return newTestOIDC(t, func(o *TraefikOidc) {
|
||||||
|
o.issuerURL = ""
|
||||||
|
o.initComplete = make(chan struct{})
|
||||||
|
o.providerURL = providerURL
|
||||||
|
o.httpClient = srv.Client()
|
||||||
|
o.metadataCache = NewMetadataCacheWithLogger(nil, NewLogger("error"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataDiscovery_StatusRetryClassification(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
cfg RetryConfig
|
||||||
|
status int
|
||||||
|
wantCalls int32
|
||||||
|
}{
|
||||||
|
{"discovery 404 is a routing race and is retried", MetadataFetchRetryConfig(), http.StatusNotFound, 3},
|
||||||
|
{"discovery 502 is retried", MetadataFetchRetryConfig(), http.StatusBadGateway, 3},
|
||||||
|
{"discovery 503 is retried", MetadataFetchRetryConfig(), http.StatusServiceUnavailable, 3},
|
||||||
|
{"discovery 429 is retried", MetadataFetchRetryConfig(), http.StatusTooManyRequests, 3},
|
||||||
|
{"discovery 400 is terminal", MetadataFetchRetryConfig(), http.StatusBadRequest, 1},
|
||||||
|
{"discovery 401 is terminal", MetadataFetchRetryConfig(), http.StatusUnauthorized, 1},
|
||||||
|
{"discovery 403 is terminal", MetadataFetchRetryConfig(), http.StatusForbidden, 1},
|
||||||
|
{"other configs keep 404 terminal", DefaultRetryConfig(), http.StatusNotFound, 1},
|
||||||
|
{"other configs retry 502", DefaultRetryConfig(), http.StatusBadGateway, 3},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, c.status, 1<<20)
|
||||||
|
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
|
||||||
|
re := NewRetryExecutor(fastRetry(c.cfg, 3), NewLogger("error"))
|
||||||
|
|
||||||
|
err := re.ExecuteWithContext(context.Background(), func() error {
|
||||||
|
_, fetchErr := mc.GetProviderMetadata(context.Background(), providerURL, srv.Client())
|
||||||
|
return fetchErr
|
||||||
|
})
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Equal(t, c.wantCalls, hits.Load())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetProviderMetadata_NonOKStatusIsHTTPError(t *testing.T) {
|
||||||
|
srv, providerURL, _ := newFlakyDiscovery(t, http.StatusBadGateway, 1)
|
||||||
|
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
|
||||||
|
|
||||||
|
_, err := mc.GetProviderMetadata(context.Background(), providerURL, srv.Client())
|
||||||
|
require.Error(t, err)
|
||||||
|
httpErr, ok := asHTTPError(err)
|
||||||
|
require.True(t, ok, "a non-200 discovery response must carry its status: %v", err)
|
||||||
|
assert.Equal(t, http.StatusBadGateway, httpErr.StatusCode)
|
||||||
|
assert.Contains(t, err.Error(), "HTTP 502")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataWithRecovery_RetriesStartupNotFound(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 2)
|
||||||
|
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
|
||||||
|
|
||||||
|
metadata, err := mc.GetMetadataWithRecovery(context.Background(), providerURL, srv.Client(), NewLogger("error"), nil)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, srv.URL, metadata.Issuer)
|
||||||
|
assert.Equal(t, int32(3), hits.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataWithRecovery_StopsWhenContextEnds(t *testing.T) {
|
||||||
|
srv, providerURL, _ := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
|
||||||
|
mc := NewMetadataCacheWithLogger(nil, NewLogger("error"))
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
_, err := mc.GetMetadataWithRecovery(ctx, providerURL, srv.Client(), NewLogger("error"), nil)
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Less(t, time.Since(start), 5*time.Second, "a canceled context must end the startup retries")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunMetadataInit_RecoversInBackgroundWithoutRequest(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 3)
|
||||||
|
oidc := newRecoveryTestOIDC(t, srv, providerURL)
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
oidc.runMetadataInit(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("background recovery did not finish")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-oidc.initComplete:
|
||||||
|
default:
|
||||||
|
t.Fatal("initComplete must be closed after the first failed attempt")
|
||||||
|
}
|
||||||
|
assert.True(t, oidc.metadataReady())
|
||||||
|
assert.Equal(t, srv.URL, oidc.issuerURL)
|
||||||
|
assert.Equal(t, int32(4), hits.Load(), "one startup attempt, two failed background attempts, one success")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunMetadataInit_OpensTheGateBeforeBackgroundRetries(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
|
||||||
|
oidc := newRecoveryTestOIDC(t, srv, providerURL)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
oidc.ctx = ctx
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
oidc.runMetadataInit(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-oidc.initComplete:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("requests must not wait on initComplete while recovery retries")
|
||||||
|
}
|
||||||
|
require.Eventually(t, func() bool { return hits.Load() >= 3 }, 5*time.Second, 5*time.Millisecond)
|
||||||
|
assert.False(t, oidc.metadataReady())
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("background recovery must stop when the instance context ends")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecoverMetadataInBackground_StopsOnCancelDuringDelay(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
|
||||||
|
oidc := newRecoveryTestOIDC(t, srv, providerURL)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
oidc.ctx = ctx
|
||||||
|
|
||||||
|
backoff := metadataRecoveryBackoff()
|
||||||
|
backoff.InitialDelay = time.Hour
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
oidc.recoverMetadataInBackground(providerURL, backoff)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("background recovery must stop when the instance context ends")
|
||||||
|
}
|
||||||
|
assert.Zero(t, hits.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecoverMetadataInBackground_SkipsWhenAlreadyRecovered(t *testing.T) {
|
||||||
|
srv, providerURL, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
|
||||||
|
oidc := newRecoveryTestOIDC(t, srv, providerURL)
|
||||||
|
oidc.issuerURL = srv.URL // the request path recovered it first
|
||||||
|
|
||||||
|
oidc.recoverMetadataInBackground(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
|
||||||
|
assert.Zero(t, hits.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServeHTTP_MetadataUnavailableSetsRetryAfter(t *testing.T) {
|
||||||
|
oidc := newTestOIDC(t, func(o *TraefikOidc) { o.issuerURL = "" })
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/app", nil)
|
||||||
|
req.Header.Set("Accept", "text/html")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
|
||||||
|
oidc.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
|
||||||
|
assert.Equal(t, metadataUnavailableRetryAfter, rec.Header().Get("Retry-After"))
|
||||||
|
assert.True(t, strings.Contains(rec.Body.String(), "metadata"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetadataRecoveryLogLoud(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
attempt int
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{1, true}, {3, true}, {4, false}, {9, false}, {10, true}, {11, false}, {20, true},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
assert.Equal(t, c.want, metadataRecoveryLogLoud(c.attempt), "attempt %d", c.attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecoverMetadataInBackground_KeepsRetryingWithoutIssuer(t *testing.T) {
|
||||||
|
hits := &atomic.Int32{}
|
||||||
|
var srv *httptest.Server
|
||||||
|
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hits.Add(1)
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(ProviderMetadata{
|
||||||
|
AuthURL: srv.URL + "/auth",
|
||||||
|
TokenURL: srv.URL + "/token",
|
||||||
|
JWKSURL: srv.URL + "/jwks",
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
providerURL := srv.URL + "/" + t.Name()
|
||||||
|
oidc := newRecoveryTestOIDC(t, srv, providerURL)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
oidc.ctx = ctx
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
oidc.recoverMetadataInBackground(providerURL, fastRetry(metadataRecoveryBackoff(), 0))
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
require.Eventually(t, func() bool { return hits.Load() >= 1 }, 5*time.Second, time.Millisecond)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
t.Fatal("a document without an issuer must not end recovery")
|
||||||
|
case <-time.After(100 * time.Millisecond):
|
||||||
|
}
|
||||||
|
assert.False(t, oidc.metadataReady())
|
||||||
|
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("background recovery must stop when the instance context ends")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNew_CloseStopsStartupRetries(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip("drives New through the real startup retry delays")
|
||||||
|
}
|
||||||
|
srv, _, hits := newFlakyDiscovery(t, http.StatusNotFound, 1<<20)
|
||||||
|
config := &Config{
|
||||||
|
ProviderURL: srv.URL,
|
||||||
|
ClientID: "test-client",
|
||||||
|
ClientSecret: "test-secret",
|
||||||
|
CallbackURL: "/callback",
|
||||||
|
SessionEncryptionKey: "test-encryption-key-thats-long-enough",
|
||||||
|
RateLimit: 100,
|
||||||
|
}
|
||||||
|
handler, err := New(context.Background(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}), config, "issue147-close")
|
||||||
|
require.NoError(t, err)
|
||||||
|
m, ok := handler.(*TraefikOidc)
|
||||||
|
require.True(t, ok)
|
||||||
|
|
||||||
|
// The first retry delay is 1s, so a second request proves the retries run.
|
||||||
|
require.Eventually(t, func() bool { return hits.Load() >= 2 }, 10*time.Second, 10*time.Millisecond)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
require.NoError(t, m.Close())
|
||||||
|
assert.Less(t, time.Since(start), 5*time.Second, "Close must not wait for the startup retries")
|
||||||
|
|
||||||
|
stopped := hits.Load()
|
||||||
|
time.Sleep(2 * time.Second)
|
||||||
|
assert.Equal(t, stopped, hits.Load(), "no discovery request may follow Close")
|
||||||
|
}
|
||||||
@@ -204,6 +204,12 @@ func isWebSocketUpgrade(req *http.Request) bool {
|
|||||||
// This must be called BEFORE waiting on t.initComplete so excluded, SSE and
|
// This must be called BEFORE waiting on t.initComplete so excluded, SSE and
|
||||||
// WebSocket traffic is never blocked by a slow/broken provider.
|
// WebSocket traffic is never blocked by a slow/broken provider.
|
||||||
func (t *TraefikOidc) shouldBypassAuth(req *http.Request) (bool, string) {
|
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) {
|
if t.determineExcludedURL(req.URL.Path) {
|
||||||
return true, bypassReasonExcluded
|
return true, bypassReasonExcluded
|
||||||
}
|
}
|
||||||
@@ -460,6 +466,11 @@ func (t *TraefikOidc) bypassSessionClaims(session *SessionData) (map[string]inte
|
|||||||
return claims, err
|
return claims, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// metadataUnavailableRetryAfter is the Retry-After value (seconds) of the 503
|
||||||
|
// served while provider metadata is unavailable or initialization times out.
|
||||||
|
// Background recovery retries every 5 to 60 seconds.
|
||||||
|
const metadataUnavailableRetryAfter = "10"
|
||||||
|
|
||||||
// ServeHTTP implements the main middleware logic for processing HTTP requests.
|
// ServeHTTP implements the main middleware logic for processing HTTP requests.
|
||||||
// It handles the complete OIDC authentication flow including:
|
// It handles the complete OIDC authentication flow including:
|
||||||
// - Excluded URL bypass
|
// - Excluded URL bypass
|
||||||
@@ -757,6 +768,7 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
t.logger.Error("OIDC provider metadata initialization failed or incomplete")
|
t.logger.Error("OIDC provider metadata initialization failed or incomplete")
|
||||||
|
rw.Header().Set("Retry-After", metadataUnavailableRetryAfter)
|
||||||
t.sendErrorResponse(rw, req, "OIDC provider metadata initialization failed - please check provider availability and configuration", http.StatusServiceUnavailable)
|
t.sendErrorResponse(rw, req, "OIDC provider metadata initialization failed - please check provider availability and configuration", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -768,6 +780,7 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||||||
case <-initTimer.C:
|
case <-initTimer.C:
|
||||||
atomic.AddInt32(&t.initWaiters, -1)
|
atomic.AddInt32(&t.initWaiters, -1)
|
||||||
t.logger.Error("Timeout waiting for OIDC initialization")
|
t.logger.Error("Timeout waiting for OIDC initialization")
|
||||||
|
rw.Header().Set("Retry-After", metadataUnavailableRetryAfter)
|
||||||
t.sendErrorResponse(rw, req, "Timeout waiting for OIDC provider initialization - please try again later", http.StatusServiceUnavailable)
|
t.sendErrorResponse(rw, req, "Timeout waiting for OIDC provider initialization - please try again later", http.StatusServiceUnavailable)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -775,6 +788,14 @@ func (t *TraefikOidc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|||||||
// Bypass checks already ran before the init wait; no need to repeat them.
|
// Bypass checks already ran before the init wait; no need to repeat them.
|
||||||
t.sessionManager.CleanupOldCookies(rw, req)
|
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
|
// Bearer-token auth (opt-in). Runs after init (we need issuer+JWKs+aud
|
||||||
// available) and after bypass (excluded URLs always win). Cookie-vs-
|
// available) and after bypass (excluded URLs always win). Cookie-vs-
|
||||||
// bearer precedence is configurable; the safe default is cookie-wins.
|
// bearer precedence is configurable; the safe default is cookie-wins.
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package traefikoidc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entra ID refresh tokens start with "1." and contain two dots, but are not JWTs.
|
||||||
|
func TestRefreshTokenWithDotsIsOpaque(t *testing.T) {
|
||||||
|
cm := NewChunkManager(NewLogger(""))
|
||||||
|
entra := "1.AXwAbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-" +
|
||||||
|
"." + strings.Repeat("Ab9_-xYz+/", 40) +
|
||||||
|
"." + strings.Repeat("Qw3rTy7u!~", 40)
|
||||||
|
|
||||||
|
t.Run("refresh config accepts dotted opaque token", func(t *testing.T) {
|
||||||
|
if res := cm.validateToken(entra, RefreshTokenConfig); res.Error != nil {
|
||||||
|
t.Fatalf("refresh token rejected: %v", res.Error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("access config still validates dotted token as JWT", func(t *testing.T) {
|
||||||
|
res := cm.validateToken(entra, AccessTokenConfig)
|
||||||
|
if res.Error == nil {
|
||||||
|
t.Fatal("malformed JWT-shaped access token was accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("refresh config still rejects control characters", func(t *testing.T) {
|
||||||
|
bad := strings.Replace(entra, "AXwA", "AX\x01A", 1)
|
||||||
|
if res := cm.validateToken(bad, RefreshTokenConfig); res.Error == nil {
|
||||||
|
t.Fatal("refresh token with control character was accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("valid JWT refresh token keeps JWT validation", func(t *testing.T) {
|
||||||
|
future := time.Now().Add(time.Hour).Unix()
|
||||||
|
jwt := tokenWithGroups(t, map[string]interface{}{"sub": "a", "exp": float64(future + 3600), "iat": float64(future)})
|
||||||
|
res := cm.validateToken(jwt, RefreshTokenConfig)
|
||||||
|
if res.Error == nil || !strings.Contains(res.Error.Error(), "issued in future") {
|
||||||
|
t.Fatalf("error = %v, want issued-in-future from the JWT path", res.Error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("malformed JWT refresh token stays rejected", func(t *testing.T) {
|
||||||
|
future := time.Now().Add(time.Hour).Unix()
|
||||||
|
jwt := tokenWithGroups(t, map[string]interface{}{"sub": "a", "exp": float64(future + 3600), "iat": float64(time.Now().Unix())})
|
||||||
|
parts := strings.Split(jwt, ".")
|
||||||
|
corrupt := parts[0] + "." + parts[1] + ".!!!not-base64!!!"
|
||||||
|
if res := cm.validateToken(corrupt, RefreshTokenConfig); res.Error == nil {
|
||||||
|
t.Fatal("JWT with a corrupt signature was accepted as opaque")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -39,6 +39,10 @@ type requestState struct {
|
|||||||
userIdentifier string
|
userIdentifier string
|
||||||
createdAtUnixSec int64
|
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.
|
// Output: scheme/host/redirect path determined at top of ServeHTTP.
|
||||||
scheme string
|
scheme string
|
||||||
host string
|
host string
|
||||||
@@ -66,6 +70,7 @@ func (rs *requestState) captureSession(sd *SessionData) *requestState {
|
|||||||
rs.refreshToken = sd.getRefreshTokenUnsafe()
|
rs.refreshToken = sd.getRefreshTokenUnsafe()
|
||||||
rs.userIdentifier = sd.getUserIdentifierUnsafe()
|
rs.userIdentifier = sd.getUserIdentifierUnsafe()
|
||||||
rs.createdAtUnixSec = sd.getCreatedAtUnsafe()
|
rs.createdAtUnixSec = sd.getCreatedAtUnsafe()
|
||||||
|
rs.accessTokenExpiresAt = sd.getAccessTokenExpiresAtUnsafe()
|
||||||
sd.sessionMutex.RUnlock()
|
sd.sessionMutex.RUnlock()
|
||||||
return rs
|
return rs
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package traefikoidc
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
@@ -13,17 +11,6 @@ import (
|
|||||||
|
|
||||||
// R154 review-round regressions.
|
// 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
|
// TestSetRefreshToken_AbortPreservesPrevious covers the commit-on-success
|
||||||
// rewrite of SetRefreshToken (session.go). Setting a new chunked refresh
|
// rewrite of SetRefreshToken (session.go). Setting a new chunked refresh
|
||||||
// token on a session whose request is nil (so the chunk write aborts)
|
// token on a session whose request is nil (so the chunk write aborts)
|
||||||
|
|||||||
+67
@@ -153,6 +153,7 @@ type combinedSessionPayload struct {
|
|||||||
Ip string `json:"ip,omitempty"`
|
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)
|
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"`
|
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"`
|
Rc int `json:"rc,omitempty"`
|
||||||
Au bool `json:"au,omitempty"`
|
Au bool `json:"au,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -172,8 +173,15 @@ var knownSessionKeys = map[string]bool{
|
|||||||
"redirect_url": true,
|
"redirect_url": true,
|
||||||
"created_at": true,
|
"created_at": true,
|
||||||
"redirect_count": 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.
|
// compressCombinedPayload compresses the combined session payload using gzip.
|
||||||
// It serializes the payload to JSON, compresses it, and returns base64-encoded data.
|
// It serializes the payload to JSON, compresses it, and returns base64-encoded data.
|
||||||
// Returns the compressed string and any error encountered.
|
// 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["redirect_url"] = payload.Ru
|
||||||
sessionData.mainSession.Values["created_at"] = payload.Ca
|
sessionData.mainSession.Values["created_at"] = payload.Ca
|
||||||
sessionData.mainSession.Values["redirect_count"] = payload.Rc
|
sessionData.mainSession.Values["redirect_count"] = payload.Rc
|
||||||
|
if payload.Ea > 0 {
|
||||||
|
sessionData.mainSession.Values[accessTokenExpiresAtKey] = payload.Ea
|
||||||
|
}
|
||||||
|
|
||||||
// Restore extra custom session values
|
// Restore extra custom session values
|
||||||
for key, val := range payload.X {
|
for key, val := range payload.X {
|
||||||
@@ -1519,6 +1530,7 @@ func (sd *SessionData) saveCombined(r *http.Request, w http.ResponseWriter, opti
|
|||||||
Ip: sd.getIncomingPathUnsafe(),
|
Ip: sd.getIncomingPathUnsafe(),
|
||||||
Ru: sd.getRedirectURLUnsafe(),
|
Ru: sd.getRedirectURLUnsafe(),
|
||||||
Ca: sd.getCreatedAtUnsafe(),
|
Ca: sd.getCreatedAtUnsafe(),
|
||||||
|
Ea: sd.getAccessTokenExpiresAtUnsafe(),
|
||||||
Rc: sd.getRedirectCountUnsafe(),
|
Rc: sd.getRedirectCountUnsafe(),
|
||||||
}
|
}
|
||||||
// Persist the refresh token's issued_at so maxRefreshTokenAge keeps
|
// 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.accessSession.Values["compressed"] = false
|
||||||
}
|
}
|
||||||
sd.clearAccessTokenChunks()
|
sd.clearAccessTokenChunks()
|
||||||
|
sd.clearAccessTokenExpiryUnsafe()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2263,6 +2276,7 @@ func (sd *SessionData) SetAccessToken(token string) {
|
|||||||
|
|
||||||
if len(compressed) <= maxCookieSize {
|
if len(compressed) <= maxCookieSize {
|
||||||
sd.clearAccessTokenChunks()
|
sd.clearAccessTokenChunks()
|
||||||
|
sd.clearAccessTokenExpiryUnsafe()
|
||||||
if sd.accessSession != nil {
|
if sd.accessSession != nil {
|
||||||
sd.accessSession.Values["token"] = compressed
|
sd.accessSession.Values["token"] = compressed
|
||||||
sd.accessSession.Values["compressed"] = (compressed != token)
|
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
|
// Validation passed: now it is safe to clear the existing token
|
||||||
// before storing the new chunked one.
|
// before storing the new chunked one.
|
||||||
sd.clearAccessTokenChunks()
|
sd.clearAccessTokenChunks()
|
||||||
|
sd.clearAccessTokenExpiryUnsafe()
|
||||||
if sd.accessSession != nil {
|
if sd.accessSession != nil {
|
||||||
sd.accessSession.Values["token"] = ""
|
sd.accessSession.Values["token"] = ""
|
||||||
sd.accessSession.Values["compressed"] = (compressed != token)
|
sd.accessSession.Values["compressed"] = (compressed != token)
|
||||||
@@ -3146,6 +3161,58 @@ func (sd *SessionData) getCreatedAtUnsafe() int64 {
|
|||||||
return createdAt
|
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.
|
// getRedirectCountUnsafe retrieves the redirect count without acquiring locks.
|
||||||
func (sd *SessionData) getRedirectCountUnsafe() int {
|
func (sd *SessionData) getRedirectCountUnsafe() int {
|
||||||
count, _ := sd.mainSession.Values["redirect_count"].(int)
|
count, _ := sd.mainSession.Values["redirect_count"].(int)
|
||||||
|
|||||||
+45
-230
@@ -5,6 +5,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -27,12 +28,43 @@ type TokenConfig struct {
|
|||||||
MaxChunkSize int
|
MaxChunkSize int
|
||||||
AllowOpaqueTokens bool
|
AllowOpaqueTokens bool
|
||||||
RequireJWTFormat bool
|
RequireJWTFormat bool
|
||||||
|
// AlwaysOpaque skips JWT checks even when the value contains dots.
|
||||||
|
AlwaysOpaque bool
|
||||||
|
// FallbackToOpaque validates a dotted token as opaque when it fails JWT
|
||||||
|
// validation. Entra ID refresh tokens have two dots but are not JWTs.
|
||||||
|
FallbackToOpaque bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// claimsJWT reports whether the first segment decodes to a JSON header with an
|
||||||
|
// "alg" member. A token that does so claims to be a JWT, so a malformed one
|
||||||
|
// must stay rejected rather than fall back to opaque validation.
|
||||||
|
func claimsJWT(token string) bool {
|
||||||
|
seg, _, _ := strings.Cut(token, ".")
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(seg, "="))
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var header map[string]any
|
||||||
|
if json.Unmarshal(raw, &header) != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
_, ok := header["alg"]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// jwtShaped reports whether token must pass JWT validation.
|
||||||
|
func (c TokenConfig) jwtShaped(token string) bool {
|
||||||
|
return c.RequireJWTFormat || (c.AllowOpaqueTokens && !c.AlwaysOpaque && strings.Contains(token, "."))
|
||||||
|
}
|
||||||
|
|
||||||
|
// opaqueShaped reports whether token must pass opaque-token validation.
|
||||||
|
func (c TokenConfig) opaqueShaped(token string) bool {
|
||||||
|
return c.AllowOpaqueTokens && (c.AlwaysOpaque || !strings.Contains(token, "."))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Global session tracking to prevent memory leaks across all instances
|
// Global session tracking to prevent memory leaks across all instances
|
||||||
var (
|
var (
|
||||||
globalSessionCount int64 = 0
|
globalSessionCount int64 = 0
|
||||||
globalMaxSessions int64 = 5000 // CRITICAL FIX: Global limit of 5000 total sessions
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ResetGlobalSessionCounters resets global session tracking for testing
|
// ResetGlobalSessionCounters resets global session tracking for testing
|
||||||
@@ -64,6 +96,7 @@ var (
|
|||||||
MaxChunkSize: maxCookieSize,
|
MaxChunkSize: maxCookieSize,
|
||||||
AllowOpaqueTokens: true,
|
AllowOpaqueTokens: true,
|
||||||
RequireJWTFormat: false,
|
RequireJWTFormat: false,
|
||||||
|
FallbackToOpaque: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
IDTokenConfig = TokenConfig{
|
IDTokenConfig = TokenConfig{
|
||||||
@@ -300,6 +333,9 @@ func (cm *ChunkManager) processSingleToken(token string, compressed bool, config
|
|||||||
// Returns:
|
// Returns:
|
||||||
// - TokenRetrievalResult with the validated token or validation error.
|
// - TokenRetrievalResult with the validated token or validation error.
|
||||||
func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRetrievalResult {
|
func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRetrievalResult {
|
||||||
|
if config.FallbackToOpaque && strings.Contains(token, ".") && !claimsJWT(token) {
|
||||||
|
config.AlwaysOpaque = true
|
||||||
|
}
|
||||||
// Content-only checks depend on the token string alone, so a token that
|
// Content-only checks depend on the token string alone, so a token that
|
||||||
// passed them once skips them. Expiry and freshness always run.
|
// passed them once skips them. Expiry and freshness always run.
|
||||||
key := contentValidKey(token, config)
|
key := contentValidKey(token, config)
|
||||||
@@ -315,7 +351,9 @@ func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRet
|
|||||||
if contentErr := cm.validateTokenContent(token, config); contentErr != nil {
|
if contentErr := cm.validateTokenContent(token, config); contentErr != nil {
|
||||||
return TokenRetrievalResult{Token: "", Error: contentErr}
|
return TokenRetrievalResult{Token: "", Error: contentErr}
|
||||||
}
|
}
|
||||||
times = cm.tokenTimesOf(token)
|
if !config.AlwaysOpaque {
|
||||||
|
times = cm.tokenTimesOf(token)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if expErr := cm.validateTokenExpiration(times, config); expErr != nil {
|
if expErr := cm.validateTokenExpiration(times, config); expErr != nil {
|
||||||
@@ -332,8 +370,7 @@ func (cm *ChunkManager) validateToken(token string, config TokenConfig) TokenRet
|
|||||||
return TokenRetrievalResult{Token: token, Error: nil}
|
return TokenRetrievalResult{Token: token, Error: nil}
|
||||||
}
|
}
|
||||||
|
|
||||||
dotCount := strings.Count(token, ".")
|
isJWT := strings.Count(token, ".") == 2 && !config.AlwaysOpaque
|
||||||
isJWT := dotCount == 2
|
|
||||||
|
|
||||||
if config.RequireJWTFormat && !config.AllowOpaqueTokens {
|
if config.RequireJWTFormat && !config.AllowOpaqueTokens {
|
||||||
// Only accept JWT format tokens
|
// Only accept JWT format tokens
|
||||||
@@ -685,7 +722,7 @@ func (cm *ChunkManager) validateTokenSize(token string, config TokenConfig) erro
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.RequireJWTFormat || (config.AllowOpaqueTokens && strings.Contains(token, ".")) {
|
if config.jwtShaped(token) {
|
||||||
parts := strings.Split(token, ".")
|
parts := strings.Split(token, ".")
|
||||||
if len(parts) == 3 {
|
if len(parts) == 3 {
|
||||||
headerLen := len(parts[0])
|
headerLen := len(parts[0])
|
||||||
@@ -709,7 +746,7 @@ func (cm *ChunkManager) validateTokenSize(token string, config TokenConfig) erro
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.AllowOpaqueTokens && !strings.Contains(token, ".") {
|
if config.opaqueShaped(token) {
|
||||||
if tokenLen > config.MaxLength {
|
if tokenLen > config.MaxLength {
|
||||||
err := fmt.Errorf("%s opaque token unusually large (%d bytes)", config.Type, tokenLen)
|
err := fmt.Errorf("%s opaque token unusually large (%d bytes)", config.Type, tokenLen)
|
||||||
return err
|
return err
|
||||||
@@ -752,13 +789,13 @@ func (cm *ChunkManager) validateTokenContent(token string, config TokenConfig) e
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.RequireJWTFormat || (config.AllowOpaqueTokens && strings.Contains(token, ".")) {
|
if config.jwtShaped(token) {
|
||||||
if err := cm.validateJWTContent(token, config); err != nil {
|
if err := cm.validateJWTContent(token, config); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.AllowOpaqueTokens && !strings.Contains(token, ".") {
|
if config.opaqueShaped(token) {
|
||||||
if err := cm.validateOpaqueTokenContent(token, config); err != nil {
|
if err := cm.validateOpaqueTokenContent(token, config); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -1243,226 +1280,4 @@ func (cm *ChunkManager) CleanupExpiredSessions(force ...bool) {
|
|||||||
cm.logger.Debugf("Cleaned up %d expired sessions, freed %d bytes",
|
cm.logger.Debugf("Cleaned up %d expired sessions, freed %d bytes",
|
||||||
len(expiredKeys), totalBytesFreed)
|
len(expiredKeys), totalBytesFreed)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enforce max sessions limit
|
|
||||||
if len(cm.sessionMap) > cm.maxSessions {
|
|
||||||
cm.enforceSessionLimit()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// enforceSessionLimit removes oldest sessions when limit is exceeded
|
|
||||||
// Uses partial sort (O(n) for finding k smallest) instead of full sort (O(n log n))
|
|
||||||
func (cm *ChunkManager) enforceSessionLimit() {
|
|
||||||
currentLocal := len(cm.sessionMap)
|
|
||||||
currentGlobal := atomic.LoadInt64(&globalSessionCount)
|
|
||||||
|
|
||||||
// CRITICAL FIX: Aggressive eviction when approaching limits
|
|
||||||
shouldEvict := false
|
|
||||||
targetCapacity := cm.maxSessions
|
|
||||||
|
|
||||||
// Check global limit first (more critical)
|
|
||||||
if currentGlobal >= globalMaxSessions {
|
|
||||||
shouldEvict = true
|
|
||||||
targetCapacity = cm.maxSessions / 4 // Aggressive reduction to 25%
|
|
||||||
} else if currentGlobal >= globalMaxSessions*8/10 { // 80% of global
|
|
||||||
shouldEvict = true
|
|
||||||
targetCapacity = cm.maxSessions / 2 // Reduce to 50%
|
|
||||||
} else if currentLocal >= cm.maxSessions {
|
|
||||||
shouldEvict = true
|
|
||||||
targetCapacity = cm.maxSessions * 3 / 4 // Reduce to 75%
|
|
||||||
}
|
|
||||||
|
|
||||||
if !shouldEvict {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate how many sessions to remove
|
|
||||||
excessCount := currentLocal - targetCapacity
|
|
||||||
if excessCount <= 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use partial selection instead of full sort for better performance
|
|
||||||
// For finding k oldest sessions, we only need O(n) operations
|
|
||||||
keysToRemove := cm.findOldestSessions(excessCount)
|
|
||||||
|
|
||||||
totalBytesFreed := int64(0)
|
|
||||||
removedCount := int64(0)
|
|
||||||
|
|
||||||
for _, key := range keysToRemove {
|
|
||||||
if entry, exists := cm.sessionMap[key]; exists {
|
|
||||||
totalBytesFreed += entry.SizeEstimate
|
|
||||||
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
|
|
||||||
removedCount++
|
|
||||||
}
|
|
||||||
delete(cm.sessionMap, key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update global count
|
|
||||||
if removedCount > 0 {
|
|
||||||
atomic.AddInt64(&globalSessionCount, -removedCount)
|
|
||||||
}
|
|
||||||
|
|
||||||
cm.logger.Infof("Enforced session limit: removed %d excess sessions, freed %d bytes",
|
|
||||||
len(keysToRemove), totalBytesFreed)
|
|
||||||
}
|
|
||||||
|
|
||||||
// findOldestSessions returns keys of the k oldest sessions efficiently
|
|
||||||
// Uses a simple approach: find the kth oldest timestamp, then collect all older entries
|
|
||||||
func (cm *ChunkManager) findOldestSessions(k int) []string {
|
|
||||||
if k <= 0 || len(cm.sessionMap) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if k >= len(cm.sessionMap) {
|
|
||||||
// Remove all sessions
|
|
||||||
keys := make([]string, 0, len(cm.sessionMap))
|
|
||||||
for key := range cm.sessionMap {
|
|
||||||
keys = append(keys, key)
|
|
||||||
}
|
|
||||||
return keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// Collect all timestamps with keys
|
|
||||||
type sessionAge struct {
|
|
||||||
lastUsed time.Time
|
|
||||||
key string
|
|
||||||
}
|
|
||||||
|
|
||||||
sessions := make([]sessionAge, 0, len(cm.sessionMap))
|
|
||||||
for key, entry := range cm.sessionMap {
|
|
||||||
sessions = append(sessions, sessionAge{key: key, lastUsed: entry.LastUsed})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Partial sort: get the k smallest elements using selection
|
|
||||||
// This is O(n*k) which is better than O(n log n) when k << n
|
|
||||||
for i := 0; i < k; i++ {
|
|
||||||
minIdx := i
|
|
||||||
for j := i + 1; j < len(sessions); j++ {
|
|
||||||
if sessions[j].lastUsed.Before(sessions[minIdx].lastUsed) {
|
|
||||||
minIdx = j
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if minIdx != i {
|
|
||||||
sessions[i], sessions[minIdx] = sessions[minIdx], sessions[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the k oldest
|
|
||||||
result := make([]string, k)
|
|
||||||
for i := 0; i < k; i++ {
|
|
||||||
result[i] = sessions[i].key
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
// CanCreateSession checks if a new session can be created within limits
|
|
||||||
func (cm *ChunkManager) CanCreateSession() (bool, error) {
|
|
||||||
cm.mutex.RLock()
|
|
||||||
currentCount := len(cm.sessionMap)
|
|
||||||
cm.mutex.RUnlock()
|
|
||||||
|
|
||||||
// Hard limit check - never exceed maxSessions
|
|
||||||
if currentCount >= cm.maxSessions {
|
|
||||||
cm.logger.Error("Cannot create session: at maximum limit (%d)", cm.maxSessions)
|
|
||||||
return false, fmt.Errorf("session storage at maximum capacity (%d sessions)", cm.maxSessions)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emergency cleanup at 90% capacity
|
|
||||||
emergencyThreshold := int(float64(cm.maxSessions) * 0.9)
|
|
||||||
if currentCount >= emergencyThreshold {
|
|
||||||
cm.logger.Info("Session storage at %d%% capacity, triggering emergency cleanup",
|
|
||||||
(currentCount*100)/cm.maxSessions)
|
|
||||||
cm.EmergencyCleanup()
|
|
||||||
|
|
||||||
// Recheck after cleanup
|
|
||||||
cm.mutex.RLock()
|
|
||||||
newCount := len(cm.sessionMap)
|
|
||||||
cm.mutex.RUnlock()
|
|
||||||
|
|
||||||
if newCount >= cm.maxSessions {
|
|
||||||
return false, fmt.Errorf("session storage full even after emergency cleanup (%d sessions)", newCount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EmergencyCleanup performs aggressive session cleanup when approaching limits
|
|
||||||
func (cm *ChunkManager) EmergencyCleanup() {
|
|
||||||
cm.mutex.Lock()
|
|
||||||
defer cm.mutex.Unlock()
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
removed := 0
|
|
||||||
|
|
||||||
// Remove any expired sessions first
|
|
||||||
expiredKeys := make([]string, 0)
|
|
||||||
for key, entry := range cm.sessionMap {
|
|
||||||
if now.After(entry.ExpiresAt) || now.Sub(entry.LastUsed) > cm.sessionTTL {
|
|
||||||
expiredKeys = append(expiredKeys, key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, key := range expiredKeys {
|
|
||||||
if entry, exists := cm.sessionMap[key]; exists {
|
|
||||||
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
|
|
||||||
}
|
|
||||||
delete(cm.sessionMap, key)
|
|
||||||
removed++
|
|
||||||
}
|
|
||||||
|
|
||||||
// If still over 80% capacity, remove oldest sessions more aggressively
|
|
||||||
targetCapacity := int(float64(cm.maxSessions) * 0.8)
|
|
||||||
if len(cm.sessionMap) > targetCapacity {
|
|
||||||
excessCount := len(cm.sessionMap) - targetCapacity
|
|
||||||
|
|
||||||
// Use efficient partial sort to find oldest sessions
|
|
||||||
keysToRemove := cm.findOldestSessions(excessCount)
|
|
||||||
|
|
||||||
for _, key := range keysToRemove {
|
|
||||||
if entry, exists := cm.sessionMap[key]; exists {
|
|
||||||
atomic.AddInt64(&cm.bytesAllocated, -entry.SizeEstimate)
|
|
||||||
}
|
|
||||||
delete(cm.sessionMap, key)
|
|
||||||
removed++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cm.lastCleanup = now
|
|
||||||
cm.logger.Infof("Emergency cleanup completed: removed %d sessions, %d remaining",
|
|
||||||
removed, len(cm.sessionMap))
|
|
||||||
|
|
||||||
// Log memory stats after emergency cleanup (read only, no forced GC)
|
|
||||||
cm.logger.Infof("Sessions after emergency cleanup: %d, Tracked bytes: %d",
|
|
||||||
len(cm.sessionMap), atomic.LoadInt64(&cm.bytesAllocated))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSessionCount returns the current number of active sessions (for monitoring)
|
|
||||||
func (cm *ChunkManager) GetSessionCount() int {
|
|
||||||
cm.mutex.RLock()
|
|
||||||
defer cm.mutex.RUnlock()
|
|
||||||
return len(cm.sessionMap)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMemoryStats returns memory usage statistics for monitoring
|
|
||||||
func (cm *ChunkManager) GetMemoryStats() map[string]interface{} {
|
|
||||||
cm.mutex.RLock()
|
|
||||||
sessionCount := len(cm.sessionMap)
|
|
||||||
cm.mutex.RUnlock()
|
|
||||||
|
|
||||||
stats := make(map[string]interface{})
|
|
||||||
stats["active_sessions"] = sessionCount
|
|
||||||
stats["max_sessions"] = cm.maxSessions
|
|
||||||
stats["bytes_allocated"] = atomic.LoadInt64(&cm.bytesAllocated)
|
|
||||||
stats["peak_sessions"] = atomic.LoadInt64(&cm.peakSessions)
|
|
||||||
stats["cleanup_count"] = atomic.LoadInt64(&cm.cleanupCount)
|
|
||||||
stats["session_ttl_hours"] = cm.sessionTTL.Hours()
|
|
||||||
|
|
||||||
// Update peak sessions
|
|
||||||
if int64(sessionCount) > atomic.LoadInt64(&cm.peakSessions) {
|
|
||||||
atomic.StoreInt64(&cm.peakSessions, int64(sessionCount))
|
|
||||||
}
|
|
||||||
|
|
||||||
return stats
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
+48
-1
@@ -91,7 +91,8 @@ type Config struct {
|
|||||||
SessionMaxAge int `json:"sessionMaxAge"`
|
SessionMaxAge int `json:"sessionMaxAge"`
|
||||||
RateLimit int `json:"rateLimit"`
|
RateLimit int `json:"rateLimit"`
|
||||||
// PerSourceLoginRateLimit throttles OIDC authentication events
|
// 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 /
|
// for external (non-internal) sources only. Internal / loopback /
|
||||||
// link-local sources (reverse proxies, in-cluster callers) are trusted
|
// link-local sources (reverse proxies, in-cluster callers) are trusted
|
||||||
// and never throttled. Value = max auth events per minute per external
|
// and never throttled. Value = max auth events per minute per external
|
||||||
@@ -132,6 +133,16 @@ type Config struct {
|
|||||||
EnableFrontchannelLogout bool `json:"enableFrontchannelLogout,omitempty"`
|
EnableFrontchannelLogout bool `json:"enableFrontchannelLogout,omitempty"`
|
||||||
BackchannelLogoutURL string `json:"backchannelLogoutURL,omitempty"`
|
BackchannelLogoutURL string `json:"backchannelLogoutURL,omitempty"`
|
||||||
FrontchannelLogoutURL string `json:"frontchannelLogoutURL,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
|
// 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
|
// 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.
|
// 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)
|
// Validate client credentials. With Dynamic Client Registration (RFC 7591)
|
||||||
// enabled, clientID (and typically clientSecret) are not known at
|
// enabled, clientID (and typically clientSecret) are not known at
|
||||||
// construction time — the provider provisions them at registration. Skip
|
// construction time — the provider provisions them at registration. Skip
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
+683
@@ -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": "[email protected]", "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": "[email protected]", "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": "[email protected]", "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": "[email protected]",
|
||||||
|
}, 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": "[email protected]", "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"])
|
||||||
|
}
|
||||||
@@ -622,6 +622,7 @@ func (t *TraefikOidc) refreshToken(rw http.ResponseWriter, req *http.Request, se
|
|||||||
|
|
||||||
session.SetIDToken(newToken.IDToken)
|
session.SetIDToken(newToken.IDToken)
|
||||||
session.SetAccessToken(newToken.AccessToken)
|
session.SetAccessToken(newToken.AccessToken)
|
||||||
|
session.SetAccessTokenExpiresAt(newToken.AccessToken, accessTokenExpiry(newToken, time.Now()))
|
||||||
|
|
||||||
if newToken.RefreshToken != "" {
|
if newToken.RefreshToken != "" {
|
||||||
t.logger.Debug("Received new refresh token from provider")
|
t.logger.Debug("Received new refresh token from provider")
|
||||||
|
|||||||
@@ -233,6 +233,8 @@ type TraefikOidc struct {
|
|||||||
stripAuthCookies bool
|
stripAuthCookies bool
|
||||||
enableBackchannelLogout bool
|
enableBackchannelLogout bool
|
||||||
enableFrontchannelLogout bool
|
enableFrontchannelLogout bool
|
||||||
|
tmbSessionURLPath string
|
||||||
|
tmbClaims []string
|
||||||
requireTokenIntrospection bool
|
requireTokenIntrospection bool
|
||||||
allowPrivateIPAddresses bool
|
allowPrivateIPAddresses bool
|
||||||
// allowUnauthenticatedPreflight mirrors Config.AllowUnauthenticatedPreflight
|
// allowUnauthenticatedPreflight mirrors Config.AllowUnauthenticatedPreflight
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package traefikoidc
|
package traefikoidc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@@ -28,6 +29,26 @@ func (t *TraefikOidc) metadataSnap() *MetadataSnapshot {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// metadataReady reports whether provider metadata has been adopted, read the
|
||||||
|
// same way ServeHTTP reads it: the snapshot, else issuerURL under metadataMu.
|
||||||
|
func (t *TraefikOidc) metadataReady() bool {
|
||||||
|
if snap := t.metadataSnap(); snap != nil {
|
||||||
|
return snap.IssuerURL != ""
|
||||||
|
}
|
||||||
|
t.metadataMu.RLock()
|
||||||
|
defer t.metadataMu.RUnlock()
|
||||||
|
return t.issuerURL != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// lifecycleCtx returns the instance context, which Close cancels, or
|
||||||
|
// context.Background for instances built without New.
|
||||||
|
func (t *TraefikOidc) lifecycleCtx() context.Context {
|
||||||
|
if t.ctx != nil {
|
||||||
|
return t.ctx
|
||||||
|
}
|
||||||
|
return context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
// safeLogDebug provides nil-safe logging for debug messages
|
// safeLogDebug provides nil-safe logging for debug messages
|
||||||
func (t *TraefikOidc) safeLogDebug(msg string) {
|
func (t *TraefikOidc) safeLogDebug(msg string) {
|
||||||
if t.logger != nil {
|
if t.logger != nil {
|
||||||
|
|||||||
+1
-1
@@ -14,4 +14,4 @@ const devPluginVersion = "0.0.0-dev"
|
|||||||
// from build info at runtime (debug.ReadBuildInfo sees Traefik's build graph,
|
// from build info at runtime (debug.ReadBuildInfo sees Traefik's build graph,
|
||||||
// not the interpreted plugin). This build-stamped constant is therefore the
|
// not the interpreted plugin). This build-stamped constant is therefore the
|
||||||
// single source of truth for the version reported by anonymous usage telemetry.
|
// single source of truth for the version reported by anonymous usage telemetry.
|
||||||
const traefikoidcPluginVersion = "0.0.0-dev"
|
const traefikoidcPluginVersion = "1.0.66"
|
||||||
|
|||||||
Reference in New Issue
Block a user