authn: use a single principal model instead of splitting users and clients by grant_type

Abierto
#291 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@mushrafmim ya está trabajando en esto.

Desde el 12/10/2026.

  • #301 de @mushrafmim — abierto

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

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

Type/Improvement
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 / ClientPrincipal
  • UserContext / ClientContext on AuthContext
  • Config.UserClaims / Config.ClientClaims, WithUserClaims / WithClientClaims
  • PrincipalType and AuthContext.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 authn branches on the principal type. Within authn the only behavioural difference is that UserProfileService.GetOrCreateUser runs for user principals only (authn/middleware.go:74). Everything else is the same data (subject/ID, roles, scopes, extra claims) written out twice. AuthContext then flattens it again through Subject() / 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_type is not a standard access-token claim (it's not in RFC 9068). IdPs that don't emit it have every token rejected as unsupported grant type.
  • The claim declarations are split for no reason. You declare the same Required/Optional claims 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, aud and exp check out. Drop grant_type-based dispatch and the unsupported grant type rejection.

  • Claims: replace UserClaims / ClientClaims (and WithUserClaims / WithClientClaims, and the ClaimSpec two-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_name
    
    type 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 Optional and Required" state (currently resolved silently as required) can't exist.
    • required is a boolean, defaulting to false (optional).
    • Duplicate names are rejected. Validate errors on a name declared twice, and so do repeated WithClaims calls; there is no "required wins" merge.
    • Extensible. Future per-claim settings (e.g. a nested path, an expected type) become fields on Claim instead of more parallel lists.
    • Applies to every token. A required claim missing from any token rejects it. Requirements that only make sense for some callers (e.g. "a human must have email") 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 ExtraClaims accessors are unchanged.
    • Reserved names: grant_type is no longer reserved, since nothing dispatches on it. client_id (and azp), scope, the roles claim, and the JWT registered claims stay reserved.
  • Principal: a single Principal with Subject (sub), ClientID (client_id, falling back to azp), Roles, Scopes, ExtraClaims.

  • AuthContext: a single shape carrying the principal's fields. Remove PrincipalType, Type(), and the User / Client branches.

  • Remove UserProfileService entirely, 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 plain func(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 authn already 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 GetOrCreateUser errors are logged and the request proceeds with a half-populated context).
    • No extra public API to document and keep stable, and authn stops knowing about users at all. AuthContext no longer carries a persisted user ID field.

    Document the provisioning middleware and the sub-mux wiring in authn/README.md as the migration path.

  • Update authn/README.md and 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

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de OpenNSW/core

Todos los issues de OpenNSW/core

Issues similares

Más issues de Go

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.