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

Đang mở
#291 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

@mushrafmim đang làm issue này rồi.

Từ ngày 12/10/2026.

  • #301 của @mushrafmim — đang mở

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
15/100
Loại issue
Tái cấu trúc
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
go
Lĩnh vực
authentication

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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.

Ngôn ngữ chính
Go
Star
6
Fork
8
Merge trung bình
21 giờ 36 phút
Pull request đã merge (30 ngày)
42

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của OpenNSW/core

Tất cả issue của OpenNSW/core

Issue tương tự

Thêm issue về Go

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.