authn: use a single principal model instead of splitting users and clients by grant_type
Los mantenedores suelen responder en 1 día
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 15/100
- Tipo de issue
- Refactorización
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- go
- Área
- authentication
Línea de trabajo
Start with the grant_type dispatch in authn/token_parser.go (around line 262) and the user/client split in the principal, AuthContext and Config types. Then check the GetOrCreateUser call in authn/middleware.go (around line 74) and the UserProfileService parameter. Done means one Principal type, one per-claim list that applies to every token, UserProfileService removed, authn/README.md updated with the provisioning-middleware pattern, and the tests passing. This is a breaking API change that needs maintainer agreement on the design first.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Current Limitation
authn splits every authenticated caller into a user or a client principal based on the token's grant_type claim (authn/token_parser.go:262): authorization_code gives a user, client_credentials gives a client, and anything else is rejected. That one decision is copied across the whole package:
UserPrincipal/ClientPrincipalUserContext/ClientContextonAuthContextConfig.UserClaims/Config.ClientClaims,WithUserClaims/WithClientClaimsPrincipalTypeandAuthContext.Type()
Problems with this:
- Permissions shouldn't depend on how the token was obtained. A system integrating directly via client credentials should be able to do exactly what a person can do, as long as it holds the same roles and scopes. Treating them as different kinds of principal invites authorization logic that branches on token type instead of on permissions.
- It adds no value. Nothing outside
authnbranches on the principal type. Withinauthnthe only behavioural difference is thatUserProfileService.GetOrCreateUserruns for user principals only (authn/middleware.go:74). Everything else is the same data (subject/ID, roles, scopes, extra claims) written out twice.AuthContextthen flattens it again throughSubject()/Roles()/Scopes()/ExtraClaims(), whose own doc comment says authz should use them "rather than … branching on principal type". - It ties the library to one vendor.
grant_typeis not a standard access-token claim (it's not in RFC 9068). IdPs that don't emit it have every token rejected asunsupported grant type. - The claim declarations are split for no reason. You declare the same
Required/Optionalclaims once per principal kind, and validate them twice.
Suggested Improvement
Have one principal model, and one claim declaration that applies to every token.
-
Validation: a token is accepted when its signature,
iss,audandexpcheck out. Dropgrant_type-based dispatch and theunsupported grant typerejection. -
Claims: replace
UserClaims/ClientClaims(andWithUserClaims/WithClientClaims, and theClaimSpectwo-list shape) with a single list of per-claim declarations that applies to every token:claims: - name: email required: true - name: ouId # required defaults to false - name: given_nametype Claim struct { Name string `yaml:"name"` Required bool `yaml:"required"` } type Config struct { // ... Claims []Claim `yaml:"claims"` } func WithClaims(claims ...Claim) Option- One entry per claim. Everything about a claim is declared in one place, and the contradictory "listed in both
OptionalandRequired" state (currently resolved silently as required) can't exist. requiredis a boolean, defaulting tofalse(optional).- Duplicate names are rejected.
Validateerrors on a name declared twice, and so do repeatedWithClaimscalls; there is no "required wins" merge. - Extensible. Future per-claim settings (e.g. a nested path, an expected type) become fields on
Claiminstead of more parallel lists. - Applies to every token. A
requiredclaim missing from any token rejects it. Requirements that only make sense for some callers (e.g. "a human must haveemail") should be declared optional and enforced in the handler or authz. - Declared claims are extracted from every token that carries them; previously a name declared only for one principal type was never extracted from the other.
- Required/optional value semantics, exact (non-nested) name matching, and the
ExtraClaimsaccessors are unchanged. - Reserved names:
grant_typeis no longer reserved, since nothing dispatches on it.client_id(andazp),scope, the roles claim, and the JWT registered claims stay reserved.
- One entry per claim. Everything about a claim is declared in one place, and the contradictory "listed in both
-
Principal: a single
PrincipalwithSubject(sub),ClientID(client_id, falling back toazp),Roles,Scopes,ExtraClaims. -
AuthContext: a single shape carrying the principal's fields. Remove
PrincipalType,Type(), and theUser/Clientbranches. -
Remove
UserProfileServiceentirely, with no replacement hook. User provisioning is the only behaviour that currently depends on "is this a human?", and it isn't authentication.RequireAuth()already returns a plainfunc(http.Handler) http.Handler, so an application that wants to provision users (or do anything else with the validated principal) chains its own middleware after it:// in the application, not in authn func ProvisionUser(users *user.Service) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := authn.GetAuthContext(r.Context()) u, err := users.GetOrCreate(r.Context(), p.Subject(), p.ExtraClaims()) if err != nil { http.Error(w, "user provisioning failed", http.StatusInternalServerError) return } next.ServeHTTP(w, r.WithContext(user.NewContext(r.Context(), u))) }) } } // wrap all protected routes once, not per route api := http.NewServeMux() api.HandleFunc("POST /api/x", handlerX) root := http.NewServeMux() root.Handle("/api/", authManager.RequireAuth()(ProvisionUser(users)(api)))Why not a library-provided hook instead:
- Middleware is the standard Go extension point, and
authnalready produces one. A hook would be a second, library-specific way to do the same thing. - The application owns the policy: who gets a record, what to attach to the context, and whether a failure rejects the request (today
GetOrCreateUsererrors are logged and the request proceeds with a half-populated context). - No extra public API to document and keep stable, and
authnstops knowing about users at all.AuthContextno longer carries a persisted user ID field.
Document the provisioning middleware and the sub-mux wiring in
authn/README.mdas the migration path. - Middleware is the standard Go extension point, and
-
Update
authn/README.mdand the tests.
This is a breaking change to Config, the extractor options, Principal, AuthContext, and NewManager / Middleware / RequireAuth (the UserProfileService parameter and interface are removed).
Version
9668a52
Additional Context
Related: #289 (remove the ClientIDs allowlist). The two can be done independently. Together they bring authn down to standard JWT access-token validation (signature, issuer, audience, expiry) plus extraction of the claims the consumer declares, and leave authorization decisions to authz.
- Lenguaje dominante
- Go
- Estrellas
- 6
- Forks
- 8
- Merge medio
- 21 h 36 min
- PR fusionados (30 d)
- 42
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de OpenNSW/core
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
Los mantenedores suelen responder en 1 día
-
payment: test fixtures hardcode real gateway names (govpay/lankapay) instead of generic placeholdersAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 1 día
-
nsw-sl cleanup Type/Improvement
Dificultad 3/5 1-2 días Aptitud para principiantes 48/100
Los mantenedores suelen responder en 1 día
-
remote: let the host inject a logger, and log with one consistent policyPosiblemente ocupada @mushrafmim la tomó hace 5 días. AbiertoType/Improvement
Dificultad 4/5 3-5 días Aptitud para principiantes 22/100
Los mantenedores suelen responder en 1 día
Todos los issues de OpenNSW/core
Issues similares
-
agent-research-finding chore
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
jordansmall/spindrift#7370 ·
Los mantenedores suelen responder en 1 día
-
☢️ Bug v3
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 1 día
-
The repo's gates check is clean and runs need no swapsPosiblemente ocupada @turbot-agent-fleet la tomó hoy. Abiertoagent:ready
Dificultad 2/5 1-3 horas Aptitud para principiantes 64/100
turbot/tailpipe#677 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
-
needs-kind needs-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
Los mantenedores suelen responder en 2 días
-
enhancement
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
crossplane-contrib/provider-keycloak#806 ·
Los mantenedores suelen responder en 1 día