Skip to content

rpuser: extract the duplicated claims -> local-user sync into an audited helper #10

Closed

Description

@matthewjhunter

Summary

Every RP site on the infodancer stack re-implements the same post-login glue: take the verified claims oidclient produced, upsert a local users row keyed by subject, and put the local user ID in the session. Two sites carry near-identical copies today:

  • OSG: server/internal/web/users.go (165 lines) + the sync half of auth.go
  • SF: internal/web/auth.go (202 lines)

SF's 006_users.sql is a near-verbatim copy of OSG's 002_users.sql (same oidc_sub key, same email/name/roles/email_verified columns). A third site will copy it again. This is security-sensitive policy code; it should be written once and audited once.

Companion to infodancer/web#52 (web/profile), which deliberately excludes this -- profile keys on an opaque host user key and works with or without this extraction.

What the shared part actually is

Not the table -- the policy:

  • Key strictly on (issuer, subject). Never match or merge accounts by email: an upstream that recycles or reassigns an email must not grant access to an existing local account.
  • On each login, refresh mutable claims (email, display name, email_verified) on the existing row; never create a second row for a known subject.
  • Record email_verified and expose it so hosts can gate features on it (OSG's require_verified pattern).
  • Map role claims into host roles in one place.
  • The session carries the local user key, not raw claims.

What stays host-owned

The users table. Both sites FK their schemas into users.id (OSG: campaigns, characters, memberships; SF: authors.claimed_by) -- it is the host's FK hub, and each host has host-specific columns. So the extraction is interface-shaped, not table-shaped, and oidclient stays free of database dependencies:

// Identity is the normalized result of a completed login.
type Identity struct {
    Issuer        string
    Subject       string
    Email         string
    EmailVerified bool
    DisplayName   string
    Roles         []string
}

// UserStore is implemented by the host over its own users table.
type UserStore interface {
    // UpsertBySubject creates or updates the host's user row for this
    // identity, keyed on (Issuer, Subject) only, and returns the host's
    // stable user key.
    UpsertBySubject(ctx context.Context, id Identity) (string, error)
}

oidclient gains a callback helper (or middleware) that runs code exchange -> claim validation -> Identity -> store.UpsertBySubject -> session, so hosts keep their schema and sqlc and delete the policy code. The returned user key is also exactly what web/profile wants as its user_key.

Placement

Subpackage (e.g. oidclient/rpuser) unless the API folds cleanly into the root package. Either way: no pgx, no goose -- the host owns storage.

Non-goals

Consumers

OSG and SF delete their duplicated sync code; any new site starts from the audited path instead of copying users.go a third time.

Activity

  1. added
    enhancement
    on Jun 9, 2026
  2. matthewjhunter commented on Jul 18, 2026

    @matthewjhunter
    ContributorAuthor

    Re-verified this against current OSG and SF code (2026-07-18). The core premise still holds -- posting a correction on two points before anyone implements against it.

    Still accurate

    • The duplication is real and current: OSG's getOrProvisionUser (server/internal/web/auth.go:393-457) and SF's (internal/web/auth.go:282-313) are structurally identical -- same GetByOIDCSub -> sync email/email_verified on hit -> name := claims.Name; if name == "" { name = claims.Email } fallback -> CreateUser on miss.
    • The schemas are still near-verbatim: OSG's 002_users.sql and SF's 006_users.sql diff to identical columns (id, oidc_sub unique, email, name, roles text[], created_at, updated_at) -- SF just split email_verified into a follow-up migration (007_user_email_verified.sql) instead of the initial one.
    • Nothing has been built against this yet -- no rpuser package, no Identity/UserStore types in oidclient.
    • The companion (infodancer/web#52, profile) shipped 2026-06-09, so the opaque host user key this doesn't block on already exists.

    Needs correction

    "Map role claims into host roles in one place" isn't something either site actually does. oidclient.Claims does carry a Roles []string field, but neither OSG nor SF ever reads claims.Roles. Both sites' Roles come from the persisted users.roles DB column, set out-of-band (admin action), not from the ID token. OSG went further and moved role resolution to a separate authz grants service on 2026-05-19 -- three weeks before this issue was filed -- with a comment in auth.go explicitly calling users.roles "legacy." This bullet should be dropped from the shared-policy list, or the Identity struct should drop Roles (or keep it but document that hosts are free to ignore it, since real role authority already lives elsewhere).

    Identity.Issuer can't be populated from oidclient.Claims as currently shaped. Claims has no iss field. OSG's notifyActor has to work around this today by injecting s.config.OIDCIssuerURL from its own config rather than the claims (see the comment at auth.go:462-464: "since oidclient.Claims does not surface iss"). Whatever consumes the proposed UserStore.UpsertBySubject(ctx, id Identity) needs a documented answer for where Issuer comes from -- host config, not Claims -- or oidclient.Claims needs an Issuer field added alongside this work.

    Everything else in the issue (the Identity/UserStore shape, the rpuser subpackage placement, the non-goals, "what stays host-owned") still reads correctly against current code.

  3. matthewjhunter commented on Jul 18, 2026

    @matthewjhunter
    ContributorAuthor

    Design review against the full auth stack (2026-07-18), including infodancer/authz, which the original issue predates in deployment (both sites now run it). The premise holds -- extract once, audit once -- but the spec needs revision on five points before implementation. This supersedes the bullet-level corrections in my previous comment by folding them into a coherent revision.

    1. authz.Identity already exists and is the shape this issue wants

    The proposed rpuser.Identity reinvents authz.Identity (Issuer, Subject, DisplayName, Email, EmailVerified) almost field-for-field. That type is deployed in both OSG and SF today via each site's authzsrc.go -- two files that are byte-identical except for the repo name in a comment, i.e. yet another copy of the same glue this issue exists to kill.

    The revision: rpuser's identity type should mirror authz.Identity's field names and semantics exactly (DisplayName, not Name), so the host's conversion between the two is mechanical. Keep the libraries decoupled -- oidclient should not import authz; identical shape without the dependency is enough.

    2. Drop Roles from the struct -- it contradicts the authz design, not just current practice

    My earlier comment noted neither site reads claims.Roles. It is stronger than that: authz's DESIGN.md makes "claims never carry roles" a trust-model invariant and lists JIT seeding from JWT claims as an explicit non-goal ("a federation footgun"). Both sites resolve roles through authz's (issuer, subject, module, role) store, granted out-of-band. A Roles field on the extracted identity type would invite exactly the pattern the authorization layer was built to forbid. Remove it; the "map role claims into host roles in one place" bullet goes with it.

    3. The Issuer question is already answered -- twice, identically

    Both authzsrc.go copies carry the same comment: the issuer is the host-configured OIDC issuer URL, not a token claim, because oidclient.Claims doesn't surface iss and oidclient validates the token's iss against the configured issuer during verification anyway. So the configured value is the authoritative one, and authz grants are keyed on that same string.

    The clean implementation follows directly: the rpuser helper fills Identity.Issuer from the client's own verified IssuerURL config. (Surfacing iss in Claims remains a reasonable independent improvement, but nothing here blocks on it.)

    4. Keying: the users tables and the authz store disagree today

    The issue says "key strictly on (issuer, subject)" -- but both sites' users tables key on oidc_sub alone (no issuer column), while authz already keys grants on the composite. That skew is currently harmless only because each site has exactly one upstream fixed by config. It means the extraction has a real migration decision, not a doc note:

    • Align now: add issuer to the users tables and widen the unique constraint as part of adopting rpuser. Matches authz, closes the multi-issuer gap for good.
    • Defer: keep sub-only keying for single-issuer hosts, with the interface contract stating the host key MUST incorporate issuer before any second upstream is configured.

    Either is defensible; the spec should pick one explicitly. My lean is align-now: the migration is small while there are two consumers, and it makes the user store and the role store agree on what identifies a person.

    5. Scope: the callback half is only half the duplication

    The issue extracts login-time provisioning, but the per-request half is duplicated just as verbatim: both sites' optionalAuth middleware run sessions.Authenticate -> resolve/provision the local user -> stash user + claims in context, and both authzsrc.go files feed authz from those stashed claims. Two consequences:

    • The "session carries the local user key, not raw claims" bullet doesn't match the session model oidclient already ships. The session subpackage deliberately keeps tokens server-side and returns claims per request, because renewal happens per request and refreshed tokens carry refreshed claims. The local user is re-derived each request from those claims. Storing the user key at callback time and stopping there would fight that design. Drop the bullet; the extraction should standardize the per-request resolve path instead.
    • The two sites quietly diverge on sync timing: OSG syncs mutable claims (email, name, email_verified) only at login; SF re-runs the upsert on every authenticated request, so upstream changes propagate at token refresh rather than next login. Decision: the audited policy is OSG's login-only sync. Per-request becomes a read-only lookup; staleness is bounded by the session's absolute TTL, and there is no write amplification on every authenticated request. SF migrates off its per-request upsert when it adopts rpuser.

    Revised sketch

    // Identity mirrors authz.Identity: the normalized, verified result of a
    // completed login. Issuer is the client's configured (and token-verified)
    // issuer URL. No Roles -- authorization is authz's job.
    type Identity struct {
        Issuer        string
        Subject       string
        DisplayName   string // Name claim, falling back to Email
        Email         string
        EmailVerified bool
    }
    
    // UserStore is implemented by the host over its own users table.
    type UserStore interface {
        // UpsertBySubject creates or updates the host's user row for this
        // identity, keyed on (Issuer, Subject) only -- never matched or
        // merged by email -- and returns the host's stable user key.
        // Called at login only (the audited sync point).
        UpsertBySubject(ctx context.Context, id Identity) (string, error)
    
        // LookupBySubject returns the host's stable user key for a known
        // (issuer, subject), or a not-found sentinel. Called per request;
        // never creates or mutates rows.
        LookupBySubject(ctx context.Context, issuer, subject string) (string, error)
    }

    plus two integration points instead of one:

    1. Login: a CallbackOptions.OnAuthenticated adapter (or wrapper) that builds Identity from claims + configured issuer and calls UpsertBySubject. The name-fallback policy (DisplayName = Name, else Email) lives here, once, instead of in four places across two repos.
    2. Per-request: a middleware helper over session.Manager.Authenticate that resolves claims -> Identity -> host user via LookupBySubject (read-only, per the sync decision above), and stashes both in context -- replacing each site's hand-rolled optionalAuth + authzsrc.go pair. authz's IdentitySource can then be implemented once against the stashed identity.

    Non-goals unchanged: no table ownership, no pgx/goose, hosts keep their schema and sqlc. Consumers unchanged: OSG and SF delete their copies; site three starts from the audited path.

  4. matthewjhunter commented on Jul 18, 2026

    @matthewjhunter
    ContributorAuthor

    Decision on point 4: align now. Both OSG and SF migrate their users tables to key on (issuer, subject) -- add the issuer column, widen the unique constraint -- as part of adopting rpuser, so the user store and the authz grant store agree on what identifies a person. No deferred single-issuer carve-out. All five points are now settled; the revised sketch in the previous comment is the implementation spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions