feat(identity): 实现统一认证运行时热切换
从 Active Revision 构造并验证 OIDC、BFF Session、Introspection 与 SSF Runtime,在数据库激活成功后原子替换内存引用。请求链路使用不可变快照,失败保留当前运行时,本地管理登录不受影响。\n\n验证:go test ./apps/api/...;go vet ./apps/api/...
This commit is contained in:
@@ -73,16 +73,19 @@ func NewRequestAuthError(status int, code, message string) error {
|
||||
}
|
||||
|
||||
type Authenticator struct {
|
||||
JWTSecret string
|
||||
ServerMainBaseURL string
|
||||
ServerMainInternalToken string
|
||||
ServerMainInternalKey string
|
||||
ServerMainInternalSecret string
|
||||
HTTPClient *http.Client
|
||||
LocalAPIKeyVerifier func(ctx context.Context, apiKey string) (*User, error)
|
||||
OIDCVerifier *OIDCVerifier
|
||||
OIDCSessionResolver func(ctx context.Context, sessionID string) (*User, error)
|
||||
LegacyJWTEnabled bool
|
||||
JWTSecret string
|
||||
ServerMainBaseURL string
|
||||
ServerMainInternalToken string
|
||||
ServerMainInternalKey string
|
||||
ServerMainInternalSecret string
|
||||
HTTPClient *http.Client
|
||||
LocalAPIKeyVerifier func(ctx context.Context, apiKey string) (*User, error)
|
||||
OIDCVerifier *OIDCVerifier
|
||||
OIDCVerifierProvider func() *OIDCVerifier
|
||||
OIDCSessionResolver func(ctx context.Context, sessionID string) (*User, error)
|
||||
OIDCSessionResolverProvider func(ctx context.Context, sessionID string) (*User, error)
|
||||
LegacyJWTEnabled bool
|
||||
LegacyJWTEnabledProvider func() bool
|
||||
}
|
||||
|
||||
func New(jwtSecret string, serverMainBaseURL string, internalToken string) *Authenticator {
|
||||
@@ -152,10 +155,14 @@ func (a *Authenticator) Authenticate(r *http.Request) (*User, error) {
|
||||
if token == "" {
|
||||
if cookie, err := r.Cookie(OIDCSessionCookieName); err == nil {
|
||||
sessionID := strings.TrimSpace(cookie.Value)
|
||||
if sessionID == "" || a.OIDCSessionResolver == nil {
|
||||
resolver := a.OIDCSessionResolver
|
||||
if a.OIDCSessionResolverProvider != nil {
|
||||
resolver = a.OIDCSessionResolverProvider
|
||||
}
|
||||
if sessionID == "" || resolver == nil {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return a.OIDCSessionResolver(r.Context(), sessionID)
|
||||
return resolver(r.Context(), sessionID)
|
||||
}
|
||||
}
|
||||
if token == "" {
|
||||
@@ -168,7 +175,7 @@ func (a *Authenticator) Authenticate(r *http.Request) (*User, error) {
|
||||
if algorithm == "RS256" || algorithm == "ES256" {
|
||||
return a.AuthenticateOIDCAccessToken(r.Context(), token)
|
||||
}
|
||||
if !a.LegacyJWTEnabled {
|
||||
if !a.legacyJWTEnabled() {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return a.verifyJWT(token)
|
||||
@@ -176,10 +183,21 @@ func (a *Authenticator) Authenticate(r *http.Request) (*User, error) {
|
||||
|
||||
func (a *Authenticator) AuthenticateOIDCAccessToken(ctx context.Context, token string) (*User, error) {
|
||||
algorithm := jwtAlgorithm(token)
|
||||
if a.OIDCVerifier == nil || algorithm != "RS256" && algorithm != "ES256" {
|
||||
verifier := a.OIDCVerifier
|
||||
if a.OIDCVerifierProvider != nil {
|
||||
verifier = a.OIDCVerifierProvider()
|
||||
}
|
||||
if verifier == nil || algorithm != "RS256" && algorithm != "ES256" {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
return a.OIDCVerifier.Verify(ctx, token)
|
||||
return verifier.Verify(ctx, token)
|
||||
}
|
||||
|
||||
func (a *Authenticator) legacyJWTEnabled() bool {
|
||||
if a.LegacyJWTEnabledProvider != nil {
|
||||
return a.LegacyJWTEnabledProvider()
|
||||
}
|
||||
return a.LegacyJWTEnabled
|
||||
}
|
||||
|
||||
func (a *Authenticator) verifyJWT(tokenString string) (*User, error) {
|
||||
|
||||
@@ -112,6 +112,20 @@ func NewOIDCVerifier(config OIDCConfig) (*OIDCVerifier, error) {
|
||||
return &OIDCVerifier{config: config, client: client, keys: map[string]any{}}, nil
|
||||
}
|
||||
|
||||
// ValidateConfiguration eagerly validates Discovery, JWKS and, when enabled,
|
||||
// the RFC 7662 endpoint and machine credential before a runtime is activated.
|
||||
func (v *OIDCVerifier) ValidateConfiguration(ctx context.Context) error {
|
||||
if err := v.refresh(ctx, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if v.config.IntrospectionEnabled || v.config.SecurityEventEvaluator != nil {
|
||||
if _, err := v.introspect(ctx, "identity-configuration-probe"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *OIDCVerifier) Verify(ctx context.Context, raw string) (*User, error) {
|
||||
parser := jwt.NewParser(jwt.WithValidMethods([]string{"RS256", "ES256"}))
|
||||
unverified, _, err := parser.ParseUnverified(raw, jwt.MapClaims{})
|
||||
|
||||
@@ -70,6 +70,12 @@ func NewOIDCPublicClient(config OIDCPublicClientConfig) (*OIDCPublicClient, erro
|
||||
return &OIDCPublicClient{config: config, client: newOIDCHTTPClient(config.HTTPClient)}, nil
|
||||
}
|
||||
|
||||
// ValidateConfiguration eagerly checks public-client Discovery metadata.
|
||||
func (c *OIDCPublicClient) ValidateConfiguration(ctx context.Context) error {
|
||||
_, _, err := c.configuration(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *OIDCPublicClient) AuthorizationURL(ctx context.Context, state, nonce, pkceVerifier string) (string, error) {
|
||||
if strings.TrimSpace(state) == "" || strings.TrimSpace(nonce) == "" || !validPKCEVerifier(pkceVerifier) {
|
||||
return "", errors.New("state, nonce and PKCE verifier are required")
|
||||
|
||||
@@ -63,6 +63,9 @@ func TestOIDCPublicClientUsesAuthorizationCodePKCES256WithoutSecret(t *testing.T
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.ValidateConfiguration(context.Background()); err != nil {
|
||||
t.Fatalf("ValidateConfiguration() error = %v", err)
|
||||
}
|
||||
authorizationURL, err := client.AuthorizationURL(context.Background(), "state", "nonce", pkceVerifier)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -58,6 +58,29 @@ func TestAuthenticateRejectsInvalidOIDCSessionCookie(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticatorReadsOIDCSessionResolverAndLegacyPolicyDynamically(t *testing.T) {
|
||||
authenticator := New("local-jwt-secret", "", "")
|
||||
currentUser := &User{ID: "first", Roles: []string{"manager"}}
|
||||
authenticator.OIDCSessionResolverProvider = func(ctx context.Context, sessionID string) (*User, error) {
|
||||
return currentUser, nil
|
||||
}
|
||||
authenticator.LegacyJWTEnabledProvider = func() bool { return false }
|
||||
request := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
request.AddCookie(&http.Cookie{Name: OIDCSessionCookieName, Value: "opaque-session-id"})
|
||||
user, err := authenticator.Authenticate(request)
|
||||
if err != nil || user.ID != "first" {
|
||||
t.Fatalf("first runtime session resolution failed: user=%#v err=%v", user, err)
|
||||
}
|
||||
currentUser = &User{ID: "second", Roles: []string{"manager"}}
|
||||
user, err = authenticator.Authenticate(request)
|
||||
if err != nil || user.ID != "second" {
|
||||
t.Fatalf("swapped runtime session resolution failed: user=%#v err=%v", user, err)
|
||||
}
|
||||
if authenticator.legacyJWTEnabled() {
|
||||
t.Fatal("dynamic legacy JWT policy was ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicRouteIgnoresExpiredOptionalOIDCSession(t *testing.T) {
|
||||
authenticator := New("local-jwt-secret", "", "")
|
||||
authenticator.OIDCSessionResolver = func(context.Context, string) (*User, error) {
|
||||
|
||||
@@ -49,6 +49,9 @@ func TestOIDCVerifierAcceptsRS256AndES256StableClaims(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifier.ValidateConfiguration(context.Background()); err != nil {
|
||||
t.Fatalf("ValidateConfiguration() error = %v", err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
kid string
|
||||
|
||||
Reference in New Issue
Block a user