docs(19.4): create phase plan
This commit is contained in:
@@ -1289,20 +1289,30 @@ Plans:
|
||||
**Goal:** `wristband` is a full OpenID Connect provider that existing relying parties can switch to without noticing: discovery, JWKS with asymmetric signing and key rotation, `id_token`, userinfo, resumable authorization with account switching, a consent store and pairwise subjects. The existing issuer, signing keys and client secrets carry over.
|
||||
**Mode:** mvp
|
||||
**Depends on:** Phase 8, Phase 19.3
|
||||
**Repos:** `summercms.go`
|
||||
**Repos:** `summercms.go`, `sm-oauthserver-plugin` (new)
|
||||
**Requirements**: TBD
|
||||
**Success Criteria** (what must be TRUE):
|
||||
|
||||
1. A decision note settles whether the full OIDC provider extends the hand-written `wristband` server or puts zitadel/oidc v3 behind it, before code lands.
|
||||
1. A decision note settles whether the full OIDC provider extends the hand-written `wristband` server or puts zitadel/oidc v3 behind it, and names the JOSE/JWT dependency, before code lands.
|
||||
2. `/.well-known/openid-configuration`, the JWKS endpoint, userinfo and `id_token` in the token response work with RS256 or ES256 keys. Rotation publishes the old and the new key together.
|
||||
3. The authorization flow supports resuming a request, switching account, the consent list and revocation, and pairwise and public subjects. A scheduled prune job removes expired codes, tokens and requests.
|
||||
4. An existing issuer, its signing keys and client secrets can be imported so that relying parties keep working. The phase gets a security review.
|
||||
5. The `wristband` README and `docs/` pages are updated. The new code has unit tests, delivered in the phase's last plan.
|
||||
|
||||
**Plans:** 0 plans
|
||||
**Plans:** 4 plans
|
||||
|
||||
Plans:
|
||||
- [ ] TBD (run /msd-plan-phase 19.4 to break down)
|
||||
**Wave 1**
|
||||
- [ ] 19.4-01-PLAN.md — Decision note (golang-jwt v5, zitadel rejected), then the wristband OIDC flavour: discovery, JWKS, resumable authorize with consent and switch account, token with id_token, userinfo, pairwise subjects, kinds, opt-in refresh; neutral Resource default; README and docs (wave 1)
|
||||
|
||||
**Wave 2** *(blocked on Wave 1 completion)*
|
||||
- [ ] 19.4-02-PLAN.md — New repo sm-oauthserver-plugin: migrations, GORM stores for OIDC and MCP, DB key ring, PHP-path routes and throttles, branded consent and error pages, authorizations JSON, user cascade, additive sm-user-plugin exports, go-oidc interop test (wave 2)
|
||||
|
||||
**Wave 3** *(blocked on Wave 2 completion)*
|
||||
- [ ] 19.4-03-PLAN.md — Winter import with original kids, cabana Clients and Branding screens, rotate-keys, prune and schedule, tide parity against the PHP plugin, security review (wave 3)
|
||||
|
||||
**Wave 4** *(blocked on Wave 3 completion)*
|
||||
- [ ] 19.4-04-PLAN.md — Unit tests: PHP test map port plus Go-only cases, scripts/check-phase19.4.sh (wave 4)
|
||||
|
||||
### Phase 19.5: Social login in sm-user-plugin (INSERTED)
|
||||
|
||||
@@ -1458,7 +1468,7 @@ Phases execute in numeric order: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 →
|
||||
| 19. Chat and ChatChannels | 7/7 | Complete | 2026-10-17 |
|
||||
| 19.1. Chat satellites | 6/6 | Complete | 2026-10-18 |
|
||||
| 19.3. Framework transport and infrastructure for WavePath | 6/6 | In Progress| |
|
||||
| 19.4. OIDC provider on wristband | 0/TBD | Not started | - |
|
||||
| 19.4. OIDC provider on wristband | 0/4 | Planned | - |
|
||||
| 19.5. Social login in sm-user-plugin | 0/TBD | Not started | - |
|
||||
| 19.6. Two-factor auth and device flow in sm-user-plugin | 0/TBD | Not started | - |
|
||||
| 19.7. Generic MCP module | 0/TBD | Not started | - |
|
||||
|
||||
@@ -3,16 +3,16 @@ msd_state_version: "1.0"
|
||||
milestone: v1.0
|
||||
current_phase: "19.4"
|
||||
current_phase_name: OIDC provider on wristband
|
||||
status: planning
|
||||
status: executing
|
||||
stopped_at: Roadmap reordered 2026-10-18; ready to plan Phase 19.4
|
||||
last_updated: "2026-10-19T10:54:33.888Z"
|
||||
last_updated: "2026-10-19T15:59:56.673Z"
|
||||
last_activity: 2026-10-19
|
||||
last_activity_desc: "Completed quick task 261019-hgw: Translate hook ValidationError phrase keys in the request locale"
|
||||
state_head: ce8d7efb675a15840b5ee274d11625d920827147
|
||||
state_head: df0d8c1d55a88d3dd07fabf1c04cf9e5611621ca
|
||||
progress:
|
||||
total_phases: 42
|
||||
completed_phases: 34
|
||||
total_plans: 204
|
||||
total_plans: 208
|
||||
completed_plans: 204
|
||||
gsd_state_version: "1.0"
|
||||
milestone_name: milestone
|
||||
@@ -29,9 +29,9 @@ See: .planning/PROJECT.md (updated 2026-10-12)
|
||||
|
||||
## Current Position
|
||||
|
||||
Phase: 19.4 — OIDC provider on wristband
|
||||
Phase: 19.4 (OIDC provider on wristband) — READY TO EXECUTE
|
||||
Plan: Not started
|
||||
Status: Ready to plan
|
||||
Status: Ready to execute
|
||||
Last activity: 2026-10-19 - Completed quick task 261019-hgw: Translate hook ValidationError phrase keys in the request locale
|
||||
|
||||
Progress: [████████░░] 83%
|
||||
|
||||
373
.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-PLAN.md
Normal file
373
.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-PLAN.md
Normal file
@@ -0,0 +1,373 @@
|
||||
---
|
||||
phase: 19.4-oidc-provider-on-wristband
|
||||
plan: 01
|
||||
type: execute
|
||||
wave: 1
|
||||
depends_on: []
|
||||
files_modified:
|
||||
- .planning/ROADMAP.md
|
||||
- .planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md
|
||||
- .planning/research/STACK.md
|
||||
- .planning/todos/pending/wristband-neutral-resource-default.md
|
||||
- .planning/todos/done/wristband-neutral-resource-default.md
|
||||
- modules/wristband/server.go
|
||||
- modules/wristband/stores.go
|
||||
- modules/wristband/client_issue.go
|
||||
- modules/wristband/authorize.go
|
||||
- modules/wristband/token.go
|
||||
- modules/wristband/register.go
|
||||
- modules/wristband/oidc_options.go
|
||||
- modules/wristband/oidc_stores.go
|
||||
- modules/wristband/oidc_discovery.go
|
||||
- modules/wristband/oidc_keys.go
|
||||
- modules/wristband/oidc_authorize.go
|
||||
- modules/wristband/oidc_consent.go
|
||||
- modules/wristband/oidc_token.go
|
||||
- modules/wristband/oidc_userinfo.go
|
||||
- modules/wristband/oidc_redirect.go
|
||||
- modules/wristband/oidc_subject.go
|
||||
- modules/wristband/oidc_fakes_test.go
|
||||
- modules/wristband/oidc_tracer_test.go
|
||||
- modules/wristband/oidc_authorize_smoke_test.go
|
||||
- modules/wristband/oidc_token_smoke_test.go
|
||||
- modules/wristband/example_test.go
|
||||
- modules/wristband/authorize_test.go
|
||||
- modules/wristband/token_test.go
|
||||
- modules/wristband/server_test.go
|
||||
- modules/wristband/README.md
|
||||
- README.md
|
||||
- docs/services/oauth-server.md
|
||||
- ../fonoteka.go/plugins/golem15/fonoteka/plugin.go
|
||||
- ../fonoteka.go/plugins/golem15/fonoteka/oauth_resource_test.go
|
||||
autonomous: true
|
||||
requirements: [SC-1, SC-2, SC-3, SC-5, D-01, D-04, D-06, D-07, D-08, D-09, D-12, D-14, D-15, D-16, D-17]
|
||||
estimate:
|
||||
tokens: 230000
|
||||
raw_tokens: 230000
|
||||
tasks: 4
|
||||
confidence: low
|
||||
must_haves:
|
||||
truths:
|
||||
- "SC-1, D-16: a decision note under .planning/notes/ names github.com/golang-jwt/jwt/v5 v5.3.1 (already in go.mod) as the JOSE/JWT library for id_token signing, a standard-library JWK encoder, github.com/coreos/go-oidc/v3 v3.21.0 and golang.org/x/oauth2 v0.37.0 as test-only modules of the plugin repo installed after a blocking human check, and rejects zitadel/oidc v3 because it breaks D-06, D-09 and D-14; its commit is an ancestor of the first commit that adds modules/wristband/oidc_keys.go; STACK.md marks its zitadel/oidc row superseded."
|
||||
- "D-01, D-06: one wristband package serves both flavours. wristband.NewServer builds the MCP flavour exactly as before; wristband.NewOIDCServer builds a second *wristband.Server with the OIDC flavour; both reuse crypto.go, writeRedirectHTML and writeExactJSON; wristband imports no ORM and no application package."
|
||||
- "D-09: the existing wristband.Backend, wristband.Tx and every MCP signature stay source-compatible: fonoteka's adapter compiles and its tests pass unchanged except that fonoteka now sets Options.Resource explicitly; OIDC storage arrives only through the new wristband.OIDCBackend, wristband.OIDCTx and wristband.KeyStore, checked by SetOIDCBackend, which returns an error on an MCP server or for a nil argument."
|
||||
- "SC-2, D-12, D-14: on an OIDC server, Discovery serves the PHP field set in PHP order with Cache-Control max-age=3600, public; subject_types_supported is public and pairwise; id_token_signing_alg_values_supported lists the algorithms the published key ring holds (RS256, ES256 or both); JWKS serves the active key plus retired keys inside the grace window as RSA or EC JWKs with use sig, alg and kid."
|
||||
- "SC-2: the token endpoint answers {access_token, token_type Bearer, expires_in, id_token, scope} with no-store, private and Pragma no-cache; the id_token is signed by the active key with header alg and kid and carries iss, sub, aud as a string, exp, iat, nonce only when sent, at_hash as base64url of the left 16 bytes of SHA-256 of the access token, and only allowlisted identity claims that can never overwrite a protocol claim; no auth_time and no azp."
|
||||
- "SC-3, D-04: authorize start validates in PHP order and renders (never redirects) unknown_client, redirect_mismatch and inactive_client through the host; a valid request parks an auth request with a UUIDv4 id and redirects a signed-in user to the relative /oauth/authorize/resume/{request} path and an anonymous one to the login URL with only redirect={urlencoded resume path}; resume is silent when consent already covers the scopes, otherwise the host renders a consent view listing only the missing scopes with a one-shot consent token whose SHA-256(token|userID) digest is stored; decide and switch-account burn that token; switch-account ends the session through the host and returns to the resume path without consuming the request."
|
||||
- "D-14: OIDC redirects are encoded like PHP http_build_query (space as +, tilde as %7E, error_description dropped when empty, state dropped when absent or empty, no iss parameter); the MCP redirects keep RFC 3986 encoding and iss byte for byte."
|
||||
- "D-07, D-08: an MCP server treats a client whose Kind is oidc as unknown at authorize and invalid_client at token, and still rejects the openid scope with invalid_scope; an OIDC server accepts only clients of kind oidc at authorize, token and userinfo, so a dynamically registered client never receives identity scopes or an id_token."
|
||||
- "D-15: the subject is a random UUIDv4 allocated lazily per (user, sector) through OIDCTx.SubjectFor and never derived from an account attribute; public clients use the empty sector; a pairwise client uses its SectorIdentifier or the single host of its redirect URIs, and wristband.SubjectSector reports wristband.ErrSectorRequired when the hosts differ and no sector identifier is set; userinfo returns the same sub as the id_token for that client."
|
||||
- "D-17: with OIDCOptions.RefreshEnabled false the refresh_token grant answers unsupported_grant_type exactly as PHP; with it true, only a client with OfflineAccess that was granted offline_access receives a rotating refresh token, a refresh returns a fresh id_token without nonce, and replay of a rotated refresh token revokes the lineage and its access tokens."
|
||||
- "Folded todo: wristband.DefaultOptions().Resource is empty, no non-test wristband file names a consuming application, and fonoteka sets its resource explicitly so its MCP behaviour is unchanged."
|
||||
- "SC-5: the wristband README (summary sentence, Features, Usage, API reference, Dependencies) and docs/services/oauth-server.md describe the OIDC flavour; every identifier they name exists (TestDocsTree and summer docs:build --check green)."
|
||||
artifacts:
|
||||
- path: ".planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md"
|
||||
provides: "SC-1 decision note naming golang-jwt v5 and the test-only RP modules, rejecting zitadel/oidc"
|
||||
contains: "golang-jwt/jwt/v5"
|
||||
- path: "modules/wristband/oidc_options.go"
|
||||
provides: "OIDCOptions, DefaultOIDCOptions, NewOIDCServer, SetOIDCBackend, OIDCHost, ConsentView"
|
||||
contains: "func NewOIDCServer"
|
||||
- path: "modules/wristband/oidc_stores.go"
|
||||
provides: "OIDCBackend, OIDCTx and the OIDC record types"
|
||||
contains: "type OIDCTx interface"
|
||||
- path: "modules/wristband/oidc_keys.go"
|
||||
provides: "KeyStore, SigningKey, PublicKey, JWK encoding, id_token signing, key generation and PEM parsing"
|
||||
contains: "jwt.MapClaims"
|
||||
- path: "modules/wristband/oidc_authorize.go"
|
||||
provides: "OIDC start, Resume, SwitchAccount and decide"
|
||||
contains: "func (s *Server) Resume"
|
||||
- path: "modules/wristband/oidc_token.go"
|
||||
provides: "OIDC token endpoint with burn-then-check codes and opt-in refresh"
|
||||
contains: "unsupported_grant_type"
|
||||
- path: "modules/wristband/oidc_tracer_test.go"
|
||||
provides: "TestOIDCTracerSmoke: discovery to userinfo over memory fakes, id_token verified with golang-jwt against the served JWKS"
|
||||
contains: "TestOIDCTracerSmoke"
|
||||
key_links:
|
||||
- from: "modules/wristband/authorize.go"
|
||||
to: "modules/wristband/oidc_authorize.go"
|
||||
via: "Authorize dispatches to the OIDC flavour before any MCP code runs"
|
||||
pattern: "flavourOIDC"
|
||||
- from: "modules/wristband/oidc_token.go"
|
||||
to: "modules/wristband/oidc_keys.go"
|
||||
via: "the token response signs the id_token with KeyStore.ActiveSigningKey"
|
||||
pattern: "ActiveSigningKey"
|
||||
- from: "modules/wristband/oidc_discovery.go"
|
||||
to: "modules/wristband/oidc_keys.go"
|
||||
via: "Discovery and JWKS read KeyStore.PublishedKeys"
|
||||
pattern: "PublishedKeys"
|
||||
- from: "../fonoteka.go/plugins/golem15/fonoteka/plugin.go"
|
||||
to: "modules/wristband/server.go"
|
||||
via: "fonoteka sets oauthOpts.Resource explicitly before its config overrides"
|
||||
pattern: "oauthOpts.Resource ="
|
||||
prohibitions:
|
||||
- statement: "wristband imports no ORM, no framework module and no application package; no non-test wristband file, README or docs page names a consuming application."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "MCP wire bytes do not change: the existing wristband tests and fonoteka's OAuth tests pass without edits other than setting an explicit resource where they relied on the old default."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "Private key material, codes, tokens and secrets are never logged and never appear in an error string."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
---
|
||||
|
||||
## Phase Goal
|
||||
|
||||
ROADMAP Goal (not in user-story format; MVP mode would take a story from `/msd mvp-phase 19.4`, which was not run, so no story is invented here): `wristband` is a full OpenID Connect provider that existing relying parties can switch to without noticing: discovery, JWKS with asymmetric signing and key rotation, `id_token`, userinfo, resumable authorization with account switching, a consent store and pairwise subjects. The existing issuer, signing keys and client secrets carry over.
|
||||
|
||||
This plan's slice (plan 1 of 4, wave 1): the protocol half of D-01. The SC-1 decision note lands first, then the OIDC flavour of `wristband` is proven end to end over in-memory fakes (the tracer), then widened to the PHP contract: authorize, resume, consent, switch account, token, userinfo, keys, subjects, kinds and opt-in refresh. Plan 02 builds the `sm-oauthserver-plugin` stores, pages and routes on these interfaces.
|
||||
|
||||
## Spec-less probe fallback
|
||||
|
||||
No SPEC.md and no REQUIREMENTS IDs exist for this phase (ROADMAP "Requirements: TBD"); the spec-less probe fallback was skipped as a visible, recorded choice. `must_haves` derive from the ROADMAP success criteria SC-1..SC-5 and the CONTEXT decisions D-01..D-19; `requirements` lists those IDs for traceability.
|
||||
|
||||
## Decisions taken in this plan (recorded assumptions and Claude's discretion)
|
||||
|
||||
- D-16 (research recommendation, user-confirmed at plan time): extend the hand-written engine; sign with golang-jwt v5 (`jwt.MapClaims`, so `aud` stays a string); encode JWKs with the standard library (RSA `N`/`E`, EC `PublicKey.Bytes()`); reject zitadel/oidc v3. The interop oracle (go-oidc) is test-only in the plugin repo (plan 02), so the framework go.mod gains nothing.
|
||||
- One engine, two flavours (D-06): `NewOIDCServer` returns a `*wristband.Server` whose `flavour` field selects separate orchestration functions; shared primitives stay shared. MCP-only handlers (`Metadata`, `Register`) answer 404 on an OIDC server; OIDC-only handlers (`Discovery`, `JWKS`, `UserInfo`, `Resume`, `SwitchAccount`) answer 404 on an MCP server.
|
||||
- Rendering seam: the engine owns validation, redirects, headers and CSRF; HTML belongs to the host through `wristband.OIDCHost` (`SignedInUser`, `RenderAuthorizeError`, `RenderConsent`, `EndSession`). The engine sets `X-Frame-Options: DENY`, `Content-Security-Policy: frame-ancestors 'none'`, `Cache-Control: no-store, private` and `Referrer-Policy: no-referrer` before it calls a render method; the host writes the status and body.
|
||||
- JSON consent mode (D-03 redirect option): exported operations `ConsentRequest` and `DecideConsent` give the host's SPA endpoints the same logic as the HTML path.
|
||||
- Repeated query parameters: last value wins (PHP `parse_str`), array-style parameters (`state[]=`) count as absent (Pitfall 13). Recorded here; tested in plan 04.
|
||||
- Pairwise subjects are stored random UUIDv4 values per (user, sector), not HMAC-derived; the sector is the client's `SectorIdentifier` or the single host of its redirect URIs, with no remote `sector_identifier_uri` fetch (RESEARCH OQ5, A10).
|
||||
- OIDC refresh (D-17, RESEARCH OQ4): server switch `OIDCOptions.RefreshEnabled` (default false). Off: byte-identical to PHP. On: discovery adds `refresh_token` and `offline_access`; a client without `OfflineAccess` asking for the grant gets `unauthorized_client`; a `scope` parameter on refresh must be a subset of the original grant (else `invalid_scope`); refresh tokens use the prefix `oas_rt_`.
|
||||
- Signing keys come from `KeyStore`; the engine generates and parses keys through exported helpers (`GenerateSigningKey`, `ParsePrivateKeyPEM`, `ParsePublicKeyPEM`) so key crypto stays in the reviewed package. New kids are 16 lowercase hex characters (PHP `bin2hex(random_bytes(8))`).
|
||||
|
||||
<assumption_delta_decision>
|
||||
add-alongside: the authorization server pluralizes from one flavour (MCP) to two (MCP and OIDC). The MCP flavour and its interfaces stay as they are; the OIDC flavour is added next to them behind new constructors and interfaces. Nothing changes for an application that only calls NewServer, except that DefaultOptions no longer carries a resource URL.
|
||||
</assumption_delta_decision>
|
||||
|
||||
## Artifacts this phase produces (this plan)
|
||||
|
||||
- Decision note `.planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md`; STACK.md zitadel/oidc row marked superseded for OIDC; ROADMAP corrections (Repos line, SC-1 wording) verified; folded todo moved to `.planning/todos/done/`.
|
||||
- Constructors and handlers: `wristband.NewOIDCServer(opts Options, oidc OIDCOptions) *Server`, `(*Server).SetOIDCBackend(b OIDCBackend, keys KeyStore, host OIDCHost) error`, handlers `(*Server).Discovery`, `(*Server).JWKS`, `(*Server).Resume`, `(*Server).SwitchAccount`, `(*Server).UserInfo`; `(*Server).Authorize` (GET start, POST decide) and `(*Server).Token` dispatch by flavour; operations `(*Server).ConsentRequest(ctx, requestID string, userID uint) (ConsentView, error)` and `(*Server).DecideConsent(ctx, requestID string, userID uint, consentToken string, allow bool) (string, error)`.
|
||||
- Options: `wristband.OIDCOptions` (fields `LoginURL`, `IDTokenTTL`, `AccessTokenTTL`, `CodeTTL`, `AuthRequestTTL`, `RefreshEnabled`, `RefreshTokenTTL`, `ScopesSupported`, `ClaimsSupported`, `IdentityClaims`, `SubjectTypesSupported`, `ClientIDPrefix`, `ClientSecretPrefix`, `CodePrefix`, `AccessTokenPrefix`, `RefreshTokenPrefix`), `wristband.DefaultOIDCOptions()`.
|
||||
- Host seam: `wristband.OIDCHost` (methods `SignedInUser(r *http.Request) (uint, bool, error)`, `RenderAuthorizeError(w http.ResponseWriter, r *http.Request, code string)`, `RenderConsent(w http.ResponseWriter, r *http.Request, view ConsentView)`, `EndSession(w http.ResponseWriter, r *http.Request) error`), `wristband.ConsentView` (fields `RequestID`, `ConsentToken`, `ClientID`, `ClientName`, `Scopes`, `UserID`), constants `wristband.AuthorizeErrorUnknownClient` (`unknown_client`), `wristband.AuthorizeErrorRedirectMismatch` (`redirect_mismatch`), `wristband.AuthorizeErrorInactiveClient` (`inactive_client`), `wristband.AuthorizeErrorExpiredRequest` (`expired_request`), error `wristband.ErrAuthRequestExpired`.
|
||||
- Storage seam: `wristband.OIDCBackend` (`WithinOIDCTx`), `wristband.OIDCTx` composed of `wristband.OIDCClientStore` (`OIDCClientByClientID`), `wristband.AuthRequestStore` (`CreateAuthRequest`, `AuthRequestByRequestID`, `AuthRequestByRequestIDForUpdate`, `ConsumeAuthRequest`, `SetConsentTokenHash`), `wristband.OIDCCodeStore` (`CreateCode`, `ConsumeCode`, `CodeByHash`), `wristband.OIDCAccessTokenStore` (`CreateAccessToken`, `AccessTokenByHash`, `TouchAccessToken`, `RevokeAccessTokensForCode`), `wristband.ConsentStore` (`ConsentFor`, `SaveConsent`, `TouchConsent`), `wristband.SubjectStore` (`SubjectFor`), `wristband.IdentityStore` (`IdentityClaims`), `wristband.OIDCRefreshTokenStore` (`CreateRefreshToken`, `RefreshTokenByHashForUpdate`, `MarkRefreshRotated`, `RevokeRefreshLineage`); records `wristband.OIDCClientRecord`, `wristband.AuthRequestRecord`, `wristband.OIDCCodeRecord`, `wristband.OIDCAccessTokenRecord`, `wristband.OIDCRefreshTokenRecord`, `wristband.ConsentRecord`.
|
||||
- Keys: `wristband.KeyStore` (`ActiveSigningKey(ctx) (SigningKey, error)`, `PublishedKeys(ctx, now time.Time) ([]PublicKey, error)`), `wristband.SigningKey` (`Kid`, `Alg`, `Signer crypto.Signer`), `wristband.PublicKey` (`Kid`, `Alg`, `Key crypto.PublicKey`), `wristband.AlgRS256`, `wristband.AlgES256`, `wristband.GenerateSigningKey(alg string) (kid string, privatePEM, publicPEM []byte, err error)`, `wristband.ParsePrivateKeyPEM([]byte) (crypto.Signer, error)`, `wristband.ParsePublicKeyPEM([]byte) (crypto.PublicKey, error)`.
|
||||
- Kinds and subjects: `wristband.ClientRecord.Kind` (new field, `""` means MCP), `wristband.ClientKindMCP` (`mcp`), `wristband.ClientKindOIDC` (`oidc`), `wristband.SubjectSector(c *OIDCClientRecord) (string, error)`, `wristband.ErrSectorRequired`, `wristband.IssueOIDCClientCredentials(o OIDCOptions) (clientID, secret, secretHash string, err error)` (client id `oas_` + 24 hex characters, secret `oas_cs_` + base64url of 32 random bytes, PHP `Client::issue`).
|
||||
- Unexported: `flavourMCP`, `flavourOIDC`, `phpURLEncode`, `appendPHPQuery`, `matchOIDCRedirectURI`, `jwkFor`, `signIDToken`, `atHash`.
|
||||
- Tests (smoke; full coverage is plan 04): `TestOIDCTracerSmoke` (oidc_tracer_test.go), `TestOIDCAuthorizeStartSmoke`, `TestOIDCResumeDecideSwitchSmoke`, `TestKindIsolationSmoke`, `TestPHPRedirectEncodingSmoke` (oidc_authorize_smoke_test.go), `TestOIDCTokenErrorsSmoke`, `TestOIDCReplayRevokesSmoke`, `TestOIDCUserInfoSmoke`, `TestMixedKeyRingSmoke`, `TestPairwiseSubjectSmoke`, `TestOIDCRefreshOptInSmoke` (oidc_token_smoke_test.go); fakes `memoryOIDCBackend`, `memoryKeyStore`, `fakeOIDCHost` in oidc_fakes_test.go; fonoteka `TestOAuthResourceExplicit` (oauth_resource_test.go).
|
||||
|
||||
<objective>
|
||||
Settle the library question in a decision note, then give wristband an OIDC flavour that a relying party can use end to end (discovery, JWKS, authorize with resume and consent, token with a signed id_token, userinfo), widen it to the PHP plugin's contract, and neutralise the framework's default resource URL, all documented in the same commits.
|
||||
|
||||
Purpose: SC-1, SC-2, SC-3 (protocol side), SC-5 (README and docs); D-01, D-04, D-06..D-09, D-12, D-14..D-17; the folded todo. Plan 02 implements OIDCBackend, KeyStore and OIDCHost in the plugin.
|
||||
Output: two planning-doc commits (roadmap corrections only if still missing, the decision note), then code commits in summercms.go with README and docs, one commit in fonoteka.go, and one planning-doc commit closing the todo.
|
||||
</objective>
|
||||
|
||||
<execution_context>
|
||||
@~/.claude/msd-core/workflows/execute-plan.md
|
||||
@~/.claude/msd-core/templates/summary.md
|
||||
</execution_context>
|
||||
|
||||
<context>
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-CONTEXT.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-RESEARCH.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-PATTERNS.md
|
||||
@modules/wristband/README.md
|
||||
|
||||
Repos and concurrency: this plan writes in summercms.go and, for one file and one test, in ../fonoteka.go (its plugin `plugins/golem15/fonoteka` is in-repo). fonoteka.go has another session's uncommitted submodule pointer changes (plugins/golem15/feedback, golem, user): never stage, stash or reset them; stage only this plan's paths. Before Task 1 run `git status --porcelain -- modules/wristband README.md docs/services .planning/notes .planning/research/STACK.md` here and `git -C ../fonoteka.go status --porcelain -- plugins/golem15/fonoteka`; if a file this plan touches is modified by someone else, stop and report. No co-author tags; planning docs and code in separate commits; a README and the docs change in the same commit as the API they describe. Keep `go vet ./...` and `go test -short ./...` green at every commit. Nothing is pushed or tagged.
|
||||
|
||||
PHP source of truth (read-only): /media/nvme/dev/jz/wavepath.org/plugins/golem15/oauthserver/ — controllers/oidc/{AuthorizeController,TokenController,UserInfoController,DiscoveryController,JwksController}.php, classes/{AuthorizeRequestValidator,RedirectUriMatcher,PkceVerifier,ConsentCsrf,TokenIssuer,ClaimBuilder,DiscoveryDocument,KeyRing,ScopeCatalog}.php, models/{Client,AuthCode,AccessToken,AuthRequest}.php, tests/. RESEARCH "Pattern 2: PHP contract map" quotes every message, order and header; treat it as the spec and the PHP files as the tie-breaker.
|
||||
|
||||
<interfaces>
|
||||
Existing seams (extend, do not fork):
|
||||
|
||||
- modules/wristband/server.go: `Options` (Issuer, ServiceDocumentationPath, ScopesSupported, TokenEndpointAuthMethodsSupported, AuthorizationResponseIssParameterSupported, DCRClientCap, DCRUnconsentedSweepAge, RegisterMaxBodyBytes, Resource, PendingRequestTTL, CodeTTL, AccessTokenTTL, RefreshTokenTTL), `DefaultOptions()` (line ~91, Resource default at ~100), `Server{opts, backend, now, randomBytes}`, `NewServer(opts) *Server`, `SetBackend(b Backend)` (no return value; fonoteka calls it bare: keep), `metadataDocument` + `Metadata`, `writeExactJSON(w, status, v, extraHeaders)` (SetEscapeHTML false = PHP JSON_UNESCAPED_SLASHES).
|
||||
- modules/wristband/stores.go: `ClientRecord{ID, ClientID, ClientSecretHash *string, ClientName, RedirectURIs, GrantTypes, TokenEndpointAuthMethod, RegistrationIP *string, ConsentedAt, RevokedAt *time.Time, ScopeCeiling, CreatedAt}`, interfaces ClientStore, AuthCodeStore, RefreshTokenStore, AccessTokenIssuer, `Tx`, `Backend{WithinTx}`; not-found convention: `(nil, nil)`.
|
||||
- modules/wristband/crypto.go: `randomBase64URL(n)`, `sha256Hex(raw)`, `constantEqual(a, b)`, `s256Challenge(verifier)` (unchanged, shared).
|
||||
- modules/wristband/authorize.go: `Authorize` (:31), `authorizeAllowedScopes` (:22, read/write/ai/offline_access: openid is already refused), `writeAuthorizeLocalError` (:178), `authorizeErrorRedirect` (:188, adds iss, RFC 3986), `rfc3986Escape`/`buildOrderedQuery`/`appendOrderedQuery` (:234-272; do not edit).
|
||||
- modules/wristband/token.go: `Token` (:63), `authenticateClient` (:156, `Basic realm="OAuth"`), `verifyPkce` (:206), `writeTokenError` (:411).
|
||||
- modules/wristband/redirect_html.go: `writeRedirectHTML(w, status, target)` (Symfony redirect body, reused for every OIDC 302).
|
||||
- modules/flare/vapid.go:100-117: golang-jwt `jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{...})` + `SignedString(signer)`.
|
||||
- ../fonoteka.go/plugins/golem15/fonoteka/plugin.go:143-175 builds `wristband.DefaultOptions()` and layers `golem15.fonoteka.oauth.*` overrides (resource at :166); ../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go uses keyed ClientRecord literals (a new field is source-compatible).
|
||||
- RESEARCH Code Examples: "JWK encoding (stdlib)", "id_token signing (golang-jwt v5)", "Folded todo: empty Resource".
|
||||
</interfaces>
|
||||
</context>
|
||||
|
||||
<tasks>
|
||||
|
||||
<task type="tracer">
|
||||
<name>Task 1: Tracer: decision note first, then a relying party reads discovery and JWKS, signs a user in through authorize, resume and consent, exchanges the code and verifies the id_token against the served JWKS (memory fakes)</name>
|
||||
<reversibility rating="costly">D-16 and D-09: the OIDCBackend, OIDCTx, KeyStore and OIDCHost shapes become the published wristband API that the plugin (plan 02) and later the MCP module (19.7) implement.</reversibility>
|
||||
<files>.planning/ROADMAP.md, .planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md, .planning/research/STACK.md, modules/wristband/server.go, modules/wristband/authorize.go, modules/wristband/token.go, modules/wristband/register.go, modules/wristband/oidc_options.go, modules/wristband/oidc_stores.go, modules/wristband/oidc_discovery.go, modules/wristband/oidc_keys.go, modules/wristband/oidc_authorize.go, modules/wristband/oidc_consent.go, modules/wristband/oidc_token.go, modules/wristband/oidc_userinfo.go, modules/wristband/oidc_subject.go, modules/wristband/oidc_fakes_test.go, modules/wristband/oidc_tracer_test.go, modules/wristband/README.md</files>
|
||||
<read_first>.planning/notes/2026-10-15-cooler-go-redis-otter.md (decision-note structure), .planning/notes/oauth2-wristband-direct-port.md, .planning/research/STACK.md (zitadel/oidc row near line 21), .planning/ROADMAP.md (Phase 19.4 section), 19.4-RESEARCH.md (D-16 decision, Standard Stack, Package Legitimacy Audit, Pattern 1, Pattern 2 Discovery/JWKS/id_token/Token/UserInfo rows, Code Examples), modules/wristband/server.go, modules/wristband/stores.go, modules/wristband/crypto.go, modules/wristband/authorize.go, modules/wristband/consent.go, modules/wristband/token.go, modules/wristband/redirect_html.go, modules/wristband/registration_test.go (memoryBackend style), modules/wristband/server_test.go (exact-bytes assertions), modules/flare/vapid.go, PHP classes/DiscoveryDocument.php, classes/TokenIssuer.php, controllers/oidc/DiscoveryController.php, controllers/oidc/JwksController.php</read_first>
|
||||
<action>Planning docs first (SC-1, D-16). (a) Roadmap corrections: check the Phase 19.4 section of .planning/ROADMAP.md; the Repos line must read `summercms.go`, `sm-oauthserver-plugin` (new) and SC-1 must say the note "names the JOSE/JWT dependency". The plan-creation commit already carries both; only if either is missing, edit it and commit alone (`docs(19.4): roadmap corrections`). (b) Write `.planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md` in the structure of the cooler note (Decision, Date, Status Accepted, Context Phase 19.4 RESEARCH, Decision bullets, "zitadel/oidc v3 was rejected" paragraph, Related dependencies, Consequences): the OIDC provider extends the hand-written wristband with an OIDC flavour (D-06 one engine, D-09 additive interfaces); `github.com/golang-jwt/jwt/v5` v5.3.1 (already required in go.mod, used by bouncer and flare) signs id_tokens (RS256, ES256) through map claims so `aud` stays a string; JWKs are encoded with the standard library (RSA modulus and exponent, EC `PublicKey.Bytes()`), go-jose rejected at runtime to keep one JOSE library (RESEARCH A2); `github.com/coreos/go-oidc/v3` v3.21.0 and `golang.org/x/oauth2` v0.37.0 are test-only modules of the sm-oauthserver-plugin repo (the D-16 interop test, the equivalent of PHP JumbojettInteropTest), installed in plan 02 only after a blocking human package check; zitadel/oidc v3.51.16 rejected (second engine next to MCP, 25-method Storage contract, discovery and error bytes it owns: cite RESEARCH's comparison table); the note supersedes STACK.md's zitadel/oidc row for OIDC as the Phase 8 note did for MCP; consequences: framework go.mod gains no module, the user's "maintained library for protocol and security code" preference is honoured for the cryptography and for the test oracle. In .planning/research/STACK.md add to the zitadel/oidc row's Why cell: "Superseded: MCP by .planning/notes/oauth2-wristband-direct-port.md, OIDC by .planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md". Commit note and STACK.md together, alone (`docs(19.4): decide OIDC on wristband with golang-jwt`), before any code.
|
||||
|
||||
Then the tracer (D-01, D-06, D-09, SC-2), RS256 only, public subjects only, one happy path; every piece is production code that later tasks widen, not replace:
|
||||
- server.go: unexported `flavour` type with `flavourMCP` (zero value) and `flavourOIDC`; Server gains `flavour`, `oidc OIDCOptions`, `oidcBackend OIDCBackend`, `keys KeyStore`, `host OIDCHost`. `Metadata` and register.go `Register` answer 404 with an empty body on an OIDC server. authorize.go `Authorize` and token.go `Token` start with a flavour dispatch to `s.oidcAuthorize` / `s.oidcToken`; no other MCP line changes in this task.
|
||||
- oidc_options.go: `OIDCOptions` with every field listed in this plan's Artifacts and `DefaultOIDCOptions()` (PHP defaults: LoginURL `/login`, IDTokenTTL 3600 s, AccessTokenTTL 3600 s, CodeTTL 60 s, AuthRequestTTL 600 s, RefreshEnabled false, RefreshTokenTTL 30 days, ScopesSupported openid/profile/email, ClaimsSupported the PHP list sub, name, picture, groups, communities, email, email_verified, iss, aud, exp, iat, nonce, IdentityClaims the ClaimBuilder ALLOWED list sub, name, picture, groups, communities, email, email_verified, SubjectTypesSupported public/pairwise, prefixes `oas_`, `oas_cs_`, `oas_ac_`, `oas_at_`, `oas_rt_`); `NewOIDCServer(opts Options, oidc OIDCOptions) *Server` (shares now/randomBytes seams); `SetOIDCBackend(b OIDCBackend, keys KeyStore, host OIDCHost) error` (error on an MCP server or any nil argument, errors prefixed `wristband:`); `OIDCHost` and `ConsentView` with the method set and fields in Artifacts, doc comments stating the render contract (engine sets the four security headers, host writes status and body; RenderAuthorizeError must write 400, RenderConsent writes the page or, in a host's redirect mode, its own redirect); the four `AuthorizeError*` constants and `ErrAuthRequestExpired`.
|
||||
- oidc_stores.go: `OIDCBackend`, `OIDCTx` and its eight component interfaces with exactly the method names in Artifacts, plus the record structs: `OIDCClientRecord{ID uint; ClientID, Name, Kind string; SecretHash *string; RedirectURIs, Scopes []string; IsActive, IsDev, OfflineAccess bool; SubjectType, SectorIdentifier string}`, `AuthRequestRecord{ID uint; RequestID, ClientID, RedirectURI string; Scopes []string; State, Nonce *string; CodeChallenge, CodeChallengeMethod string; ConsentTokenHash *string; ExpiresAt time.Time; ConsumedAt *time.Time}`, `OIDCCodeRecord{ID uint; CodeHash, ClientID string; UserID uint; RedirectURI string; Scopes []string; CodeChallenge, CodeChallengeMethod string; Nonce *string; ExpiresAt time.Time; ConsumedAt *time.Time}`, `OIDCAccessTokenRecord{ID uint; TokenHash, ClientID string; UserID uint; AuthCodeID *uint; Scopes []string; ExpiresAt time.Time; RevokedAt, LastUsedAt *time.Time}`, `OIDCRefreshTokenRecord{ID uint; TokenHash, ClientID string; UserID uint; AccessTokenID *uint; Scopes []string; ExpiresAt time.Time; RevokedAt *time.Time; RotatedToID *uint}`, `ConsentRecord{ID, UserID uint; ClientID string; Scopes []string; CreatedAt time.Time; LastUsedAt *time.Time}`. Signatures: `ConsumeAuthRequest(ctx, id uint, now time.Time) (bool, error)` and `ConsumeCode(ctx, codeHash string, now time.Time) (*OIDCCodeRecord, error)` are atomic (UPDATE ... WHERE consumed_at IS NULL AND expires_at > now, exactly one row); `SaveConsent(ctx, userID uint, clientID string, scopes []string, now time.Time) error` merges into one row per pair; `SubjectFor(ctx, userID uint, sector, candidate string) (string, error)` returns the stored sub, inserting candidate only when none exists; `IdentityClaims(ctx, userID uint, scopes []string) (map[string]any, bool, error)` returns false when the user is gone; not-found reads return `(nil, nil)`. Doc comments cite T-19.4 IDs from this plan's threat model, never an application.
|
||||
- oidc_keys.go: `KeyStore`, `SigningKey`, `PublicKey`, `AlgRS256`, `AlgES256`; `jwkFor` emitting an ordered struct (kty, use, alg, kid, n, e for RSA) per RESEARCH Code Examples; `signIDToken` with golang-jwt `jwt.NewWithClaims` and map claims (iss, sub, aud string, exp, iat as int64, nonce when non-empty, at_hash when the access token is non-empty, identity claims filtered by OIDCOptions.IdentityClaims, then sub forced again; header kid set); `GenerateSigningKey("RS256")` (RSA 2048 via crypto/rand, PKCS#8 private PEM, PKIX public PEM, kid of 8 random bytes as hex) and `ParsePrivateKeyPEM` / `ParsePublicKeyPEM` (PKCS#8 first; ES256 lands in Task 3).
|
||||
- oidc_discovery.go: `Discovery` writes the PHP field set in PHP order (issuer, authorization_endpoint, token_endpoint, userinfo_endpoint, jwks_uri, response_types_supported, grant_types_supported, subject_types_supported, id_token_signing_alg_values_supported, scopes_supported, claims_supported, code_challenge_methods_supported, token_endpoint_auth_methods_supported, response_modes_supported) through an ordered struct and writeExactJSON with `Cache-Control: max-age=3600, public`; endpoints are issuer + /oauth/authorize, /oauth/token, /oauth/userinfo, /oauth/jwks; an empty issuer answers 500 with the PHP message "The OpenID Connect issuer is not configured." (body shape per DiscoveryController.php). `JWKS` calls ActiveSigningKey once (lazy first key), then PublishedKeys, and writes {"keys":[...]} with the same Cache-Control; a key-store error answers 500 "Signing keys are unavailable." without the error text. id_token_signing_alg_values_supported comes from the published ring.
|
||||
- oidc_authorize.go and oidc_consent.go (happy path): start with client lookup, byte-exact redirect match, is_active, response_type code, S256 challenge, scope openid; park the AuthRequestRecord (request_id from stdlib `uuid.NewV4()`, scopes intersected with the client's, TTL AuthRequestTTL); signed in (host.SignedInUser) gives a 302 to the relative `/oauth/authorize/resume/{request}` path through writeRedirectHTML. `Resume` reads `r.PathValue("request")`, loads the usable request, allocates the subject through `SubjectFor` (sector from oidc_subject.go, public only here), mints a consent token (base64url of 32 random bytes), stores `sha256Hex(token + "|" + userID)` with SetConsentTokenHash and calls host.RenderConsent with the missing scopes (openid never listed). POST `Authorize` (decide) verifies the digest in constant time and clears it, consumes the request, saves consent, creates the code (`oas_ac_` + base64url of 32 bytes, stored hashed, TTL CodeTTL, nonce carried) and redirects to redirect_uri with code and state.
|
||||
- oidc_token.go (happy path): authorization_code grant, client_secret_basic and client_secret_post, ConsumeCode, PKCE through the shared s256Challenge, mint `oas_at_` + base64url of 32 bytes stored hashed with AuthCodeID, subject, sign the id_token, answer the ordered body access_token, token_type, expires_in, id_token, scope with `Cache-Control: no-store, private` and `Pragma: no-cache`.
|
||||
- oidc_userinfo.go (happy path): Bearer token, prefix gate, AccessTokenByHash, IdentityClaims for the token's scopes plus sub, TouchAccessToken, JSON answer.
|
||||
- oidc_subject.go: `SubjectSector` (public returns "") used by resume, token and userinfo.
|
||||
|
||||
Tests: oidc_fakes_test.go `memoryOIDCBackend` (mutex, slices, implements every OIDCTx method with the atomic semantics above), `memoryKeyStore` (keys from GenerateSigningKey, active plus retired-with-time), `fakeOIDCHost` (settable signed-in user, captures RenderConsent views and RenderAuthorizeError codes, EndSession counter). oidc_tracer_test.go `TestOIDCTracerSmoke`: an httptest server with a ServeMux using method patterns (GET /.well-known/openid-configuration, GET /oauth/jwks, GET and POST /oauth/authorize, GET /oauth/authorize/resume/{request}, POST /oauth/token, GET /oauth/userinfo) and issuer = server URL; read the discovery document and use only its URLs; start authorize as a signed-in user with state, nonce and an S256 challenge; follow the resume Location; read the consent token from the captured view; POST allow; read the code from the redirect; exchange with client_secret_basic; build the RSA public key from the served JWKS n and e with math/big and the standard library; parse the id_token with golang-jwt using a keyfunc that picks the key by kid and allows only RS256; assert iss, aud (a JSON string equal to the client id), sub equal to the subject the fake allocated, nonce, at_hash equal to base64url of the left 16 bytes of SHA-256 of the access token, and that userinfo's sub matches. Test values use neutral names (issuer from httptest, client `oas_...`, redirect https://rp.example.test/callback).
|
||||
|
||||
README in the same code commit: Features gains an OIDC bullet and the API reference gains rows for every exported identifier this task adds (the docs checker enforces that each exists); Dependencies third-party line names github.com/golang-jwt/jwt/v5. Do not change the summary sentence yet (Task 4 does it with the root README row).</action>
|
||||
<verify>
|
||||
<automated>go vet ./... && go test -count=1 -short ./modules/wristband/... && go test -count=1 -short -run '^TestOIDCTracerSmoke$' -v ./modules/wristband 2>&1 | grep -q -- '^--- PASS: TestOIDCTracerSmoke' && go test -count=1 -run '^TestDocsTree$' ./cmd/summer && go run ./cmd/summer docs:build --check</automated>
|
||||
<fails_when>Non-zero exit: vet or the wristband suite is red (an MCP regression or an OIDC failure), no "--- PASS: TestOIDCTracerSmoke" line (the tracer failed or was not found), or the docs checker reports an identifier in the README that does not exist.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `N=$(git log --format=%H --diff-filter=A -- .planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md) && C=$(git log --format=%H --diff-filter=A -- modules/wristband/oidc_keys.go) && test -n "$N" && test -n "$C" && git merge-base --is-ancestor "$N" "$C"` exits 0 (note committed before the first OIDC code).
|
||||
- `grep -c 'golang-jwt/jwt/v5' .planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md` prints at least 1, and the same file matches `coreos/go-oidc/v3`, `v3.21.0`, `golang.org/x/oauth2`, `v0.37.0` and `zitadel`.
|
||||
- `grep -n 'zitadel/oidc' .planning/research/STACK.md | grep -c 'Superseded'` prints at least 1.
|
||||
- `grep -c 'sm-oauthserver-plugin. (new)' .planning/ROADMAP.md` prints at least 1 and `grep -c 'names the JOSE/JWT dependency' .planning/ROADMAP.md` prints 1.
|
||||
- `grep -cE 'zitadel|go-jose|coreos' go.mod` prints 0 (no new framework module).
|
||||
- `go list -deps ./modules/wristband | grep -vx 'git.golem15.com/golem15/summercms/modules/wristband' | grep -cE 'gorm.io|summercms/modules/'` prints 0 (no ORM, no framework module; the package itself is filtered out because `go list -deps` always lists it).
|
||||
- `grep -c 'wristband.NewOIDCServer\|wristband.OIDCTx\|wristband.KeyStore\|wristband.OIDCHost' modules/wristband/README.md` prints at least 4.
|
||||
</acceptance_criteria>
|
||||
<done>A relying party discovers the OIDC endpoints, signs a user in through resume and consent, and verifies a signed id_token against the served JWKS; the library decision is on record before the code.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 2: Authorize, resume, consent and switch account behave like the PHP plugin: validation order and messages, rendered local errors, login handoff, silent and incremental consent, deny, one-shot CSRF, PHP query encoding, is_dev loopback ports, kind isolation in both flavours</name>
|
||||
<reversibility rating="costly">D-08: the Kind field on ClientRecord and the oidc/mcp values become the contract the plugin's clients table and fonoteka's adapter rely on.</reversibility>
|
||||
<files>modules/wristband/stores.go, modules/wristband/authorize.go, modules/wristband/token.go, modules/wristband/oidc_authorize.go, modules/wristband/oidc_consent.go, modules/wristband/oidc_redirect.go, modules/wristband/oidc_authorize_smoke_test.go, modules/wristband/oidc_fakes_test.go, modules/wristband/README.md</files>
|
||||
<read_first>modules/wristband/oidc_authorize.go, modules/wristband/oidc_consent.go and modules/wristband/oidc_fakes_test.go (Task 1), modules/wristband/authorize.go (rfc3986Escape, appendOrderedQuery: models only, never edit them), modules/wristband/token.go (authenticateClient), 19.4-RESEARCH.md (Pattern 2 rows Authorize start, Redirect query encoding, Rendered pages, Resume / decide / switch; Pitfalls 1, 2, 13), PHP controllers/oidc/AuthorizeController.php, classes/AuthorizeRequestValidator.php, classes/RedirectUriMatcher.php, classes/ConsentCsrf.php, tests/feature/AuthorizeStartTest.php, tests/feature/ConsentOnceTest.php, tests/feature/IncrementalConsentTest.php, tests/security/ConsentCsrfTest.php, tests/security/RedirectUriMatchTest.php, ../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go (keyed ClientRecord literals)</read_first>
|
||||
<action>Per D-04, D-07, D-08, D-14.
|
||||
|
||||
Kinds (D-08, D-07): stores.go `ClientRecord` gains `Kind string` (doc: "" or `ClientKindMCP` is an MCP client, `ClientKindOIDC` an admin-registered OIDC client) and the constants `ClientKindMCP`, `ClientKindOIDC`; register.go sets `Kind: ClientKindMCP` on records it creates. MCP authorize treats a client whose Kind is ClientKindOIDC exactly like an unknown client (the existing local "Unknown client." 400) and MCP authenticateClient returns errInvalidClient for it; these are the only MCP lines this task changes. The MCP scope allowlist already refuses openid (D-07): no change, pinned by a test. The OIDC flavour reads clients only through OIDCClientByClientID and refuses any record whose Kind is not ClientKindOIDC.
|
||||
|
||||
oidc_redirect.go (Pitfall 2): `phpURLEncode` (bytes in A-Z a-z 0-9 . _ - pass, space becomes +, every other byte %XX uppercase, so tilde becomes %7E); `appendPHPQuery(uri string, pairs [][2]string) string` (separator ? or & when the URI already has ?, pairs in the given order, http_build_query semantics); `matchOIDCRedirectURI(registered []string, presented string, isDev bool) bool` porting RedirectUriMatcher: byte-exact match against any registered URI; only for is_dev clients, an http URI whose host is localhost, 127.0.0.1 or [::1] matches a registered URI that differs only in the port (scheme, user info, host, path, raw query and fragment identical); no registered URIs match nothing; scheme-relative, https-vs-http, trailing-slash and lookalike-host variants never match.
|
||||
|
||||
Start (`oidcAuthorize` GET) in PHP order with PHP messages: query parameters last-wins, array-style keys absent; client by client_id, missing or unknown gives RenderAuthorizeError(unknown_client); redirect mismatch gives redirect_mismatch; inactive gives inactive_client (all rendered with the four security headers, never redirected); response_type not code gives unsupported_response_type "This provider only supports the authorization code response type."; code_challenge not matching ^[A-Za-z0-9_-]{43,128}$ gives invalid_request "A PKCE code challenge is required and must be a base64url-encoded SHA-256 digest."; method not S256 gives invalid_request "The code challenge method is required and must be S256."; state or nonce over 255 characters gives invalid_request "The state and nonce parameters must be strings of at most 255 characters."; scope missing or over 255 gives invalid_scope "A scope parameter is required."; no openid gives "The scope parameter must include openid."; a scope outside OIDCOptions.ScopesSupported (plus offline_access when RefreshEnabled) gives "One or more requested scopes are not supported."; a scope outside the client's Scopes (offline_access additionally needs OfflineAccess) gives "One or more requested scopes are not allowed for this client.". Error redirects go through appendPHPQuery with error, error_description (dropped when empty) and state (dropped when absent or empty), no iss, Cache-Control no-store, private, written by writeRedirectHTML. resource, prompt, max_age and login_hint are ignored. A valid request parks the AuthRequestRecord; signed in gives the relative resume path; anonymous gives rtrim(LoginURL, "/") + (? or &) + "redirect=" + phpURLEncode(resume path).
|
||||
|
||||
Resume (`Resume`): request missing, expired or consumed gives expired_request (rendered); no signed-in user gives the login handoff again; client gone or inactive gives the rendered unknown_client or inactive_client; subject allocated lazily; when the user's consent covers every requested scope the path is silent: ConsumeAuthRequest (false gives expired_request), TouchConsent, CreateCode, 302 with code and state, no HTML; otherwise a new consent token replaces any stored digest and the host renders the missing scopes.
|
||||
|
||||
Decide (POST `Authorize`) and the JSON operations: `ConsentRequest(ctx, requestID, userID)` and `DecideConsent(ctx, requestID, userID, consentToken, allow)` hold the logic, the HTML handlers read request_id, consent_token and decision from the form (decision exactly "allow" allows; anything else denies) and the signed-in user from the host. Every CSRF failure (no user, missing or forged token, token minted for another user, reused token) answers expired_request; verification reads the row with AuthRequestByRequestIDForUpdate, compares digests in constant time and clears the digest (one-shot). Deny consumes the request and redirects with access_denied (no error_description) and state. Allow computes granted = stored scopes intersected with the client's current scopes, consumes the request first (a lost race gives expired_request), merges consent, creates the code and redirects, all in one OIDC transaction.
|
||||
|
||||
`SwitchAccount` (POST): verify and burn the consent token for the signed-in user (failure gives expired_request), call host.EndSession(w, r), then 302 to the resume path; the request is not consumed.
|
||||
|
||||
Smoke tests in oidc_authorize_smoke_test.go using the Task 1 fakes: `TestOIDCAuthorizeStartSmoke` (unknown client and redirect mismatch render 400 with X-Frame-Options DENY and never set Location; missing PKCE redirects with invalid_request and the state; anonymous user gets the login URL carrying only redirect=%2Foauth%2Fauthorize%2Fresume%2F...), `TestOIDCResumeDecideSwitchSmoke` (silent second run; incremental consent lists only the added scope; a reused consent token gives expired_request; switch account calls EndSession, returns to the resume path and the request is still answerable), `TestKindIsolationSmoke` (an oidc-kind client is unknown at MCP authorize and invalid_client at MCP token; an mcp-kind client is unknown_client at OIDC authorize; MCP authorize with scope openid answers invalid_scope), `TestPHPRedirectEncodingSmoke` (a state of "a b~c+d/é" encodes as a+b%7Ec%2Bd%2F%C3%A9; access_denied carries no error_description; no iss parameter). README: rows for the identifiers this task adds (ClientRecord Kind, the kind constants, ConsentRequest, DecideConsent) and the Features text for kinds and consent.</action>
|
||||
<verify>
|
||||
<automated>go vet ./... && go test -count=1 -short ./modules/wristband/... && go test -count=1 -short -run '^(TestOIDCAuthorizeStartSmoke|TestOIDCResumeDecideSwitchSmoke|TestKindIsolationSmoke|TestPHPRedirectEncodingSmoke)$' -v ./modules/wristband 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 4 && go -C ../fonoteka.go vet ./... ./plugins/golem15/fonoteka/... && go test -count=1 -run '^TestDocsTree$' ./cmd/summer</automated>
|
||||
<fails_when>Non-zero exit: vet or the wristband suite red (an MCP test regressed), fewer than four "--- PASS" lines for the authorize smokes, fonoteka no longer compiles against the changed ClientRecord (D-09 broken), or the docs checker fails.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `D=$(git diff df0d8c1 -- modules/wristband/authorize.go) && printf '%s\n' "$D" | grep -cE '^-.*(rfc3986|OrderedQuery|isRFC3986Unreserved)'` prints 0 (no line of the MCP encoders was removed or changed since the phase base commit).
|
||||
- `grep -c 'Kind' ../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go` is unchanged by this plan (`git -C ../fonoteka.go diff --stat -- plugins/golem15/fonoteka/classes` prints nothing).
|
||||
- `grep -n 'The scope parameter must include openid.' modules/wristband/oidc_authorize.go` prints one line.
|
||||
- `grep -c 'frame-ancestors' modules/wristband/oidc_authorize.go modules/wristband/oidc_consent.go | awk -F: '{s+=$2} END {print s}'` prints at least 1.
|
||||
- `go test -count=1 -short -run '^TestOIDCResumeDecideSwitchSmoke$' -v ./modules/wristband 2>&1 | grep -c -- '--- PASS'` prints 1.
|
||||
</acceptance_criteria>
|
||||
<done>The OIDC authorize flow answers every PHP case with PHP's order, messages and encoding, consent is silent or incremental with a one-shot token, account switching works, and an MCP client can never enter the OIDC flow or the reverse.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 3: Token, userinfo, keys and subjects match the PHP contract and go beyond it where the roadmap asks: client authentication rules, burn-then-check codes with replay revocation, uniform userinfo 401, ES256 and mixed key rings, pairwise subjects, opt-in refresh</name>
|
||||
<reversibility rating="costly">D-12, D-15, D-17: the JWK shapes, the pairwise sector rule and the refresh-token prefix become relying-party-visible contracts once a client uses them.</reversibility>
|
||||
<files>modules/wristband/oidc_token.go, modules/wristband/oidc_userinfo.go, modules/wristband/oidc_keys.go, modules/wristband/oidc_discovery.go, modules/wristband/oidc_subject.go, modules/wristband/oidc_options.go, modules/wristband/oidc_token_smoke_test.go, modules/wristband/oidc_fakes_test.go, modules/wristband/README.md</files>
|
||||
<read_first>modules/wristband/oidc_token.go, oidc_userinfo.go, oidc_keys.go, oidc_subject.go (Tasks 1-2), modules/wristband/token.go (rotateRefreshToken lineage logic to mirror, writeTokenError), 19.4-RESEARCH.md (Pattern 2 Token, UserInfo, JWKS, id_token rows; Pattern 3; Pattern 5; Pitfalls 3, 5; Code Examples), PHP controllers/oidc/TokenController.php, controllers/oidc/UserInfoController.php, classes/TokenIssuer.php, classes/PkceVerifier.php, models/Client.php (issue, verifySecret), models/AuthCode.php, models/AccessToken.php, tests/feature/TokenEndpointTest.php, tests/security/PkceAndReplayTest.php, tests/feature/UserInfoEndpointTest.php, tests/unit/TokenIssuerTest.php, go doc github.com/golang-jwt/jwt/v5 SigningMethodES256</read_first>
|
||||
<action>Per D-12, D-14, D-15, D-17, SC-2.
|
||||
|
||||
Token (`oidcToken`), PHP order, every response with Cache-Control no-store, private and Pragma no-cache, error bodies as an ordered {error, error_description}: grant_type other than authorization_code (or refresh_token when RefreshEnabled) gives 400 unsupported_grant_type "Only the authorization_code grant is supported." (when RefreshEnabled the message names both grants); client credentials from an Authorization header whose scheme matches "basic" case-insensitively (strict base64, split on the first colon, url.QueryUnescape both halves, an empty id falls back to the form) else client_id and client_secret form fields; an unknown client still runs one constant-time comparison against a fixed dummy hash; unknown, inactive, non-oidc, a secret without OIDCOptions.ClientSecretPrefix or a wrong secret all give 401 invalid_client "Client authentication failed." with `WWW-Authenticate: Basic realm="oauth"` (lowercase, unlike MCP); missing code, redirect_uri or code_verifier gives 400 invalid_request "code, redirect_uri and code_verifier are required."; then in one OIDC transaction (Pitfall 3, burn then check): a code without the CodePrefix is invalid; ConsumeCode first; when it returns nil and CodeByHash finds an already consumed code, RevokeAccessTokensForCode and return invalid_grant without rolling the revocation back; then client match, redirect match, PKCE (verifier 43-128 characters of A-Z a-z 0-9 - . _ ~, S256 only, constant time), user present (IdentityClaims ok) else 400 invalid_grant "The authorization code is invalid, expired, already used, or does not match this request.". Failures log client_id, client IP and a fixed reason through log/slog only, never codes, tokens or secrets.
|
||||
|
||||
UserInfo (`UserInfo`): a missing bearer, no AccessTokenPrefix, unknown, expired, revoked, a non-oidc or inactive client, or a gone user all give 401 with an empty body, `WWW-Authenticate: Bearer error="invalid_token"` and Cache-Control no-store, private; success answers sub (same sector rule as the id_token for the token's client) plus the IdentityClaims for the token's stored scopes filtered by IdentityClaims allowlist, touching LastUsedAt.
|
||||
|
||||
Keys (D-12): GenerateSigningKey accepts ES256 (P-256, PKCS#8) besides RS256 and refuses other algorithms; ParsePrivateKeyPEM accepts PKCS#8, then PKCS#1 RSA, then SEC1 EC; ParsePublicKeyPEM accepts PKIX; jwkFor emits EC JWKs ordered kty, use, alg, kid, crv P-256, x, y from `ecdsa.PublicKey.Bytes()` (65-byte uncompressed point) and refuses other curves; signIDToken picks SigningMethodRS256 or SigningMethodES256 from the key's Alg and refuses a mismatch between Alg and key type; discovery's id_token_signing_alg_values_supported lists the published algorithms in the order RS256, ES256 without duplicates.
|
||||
|
||||
Subjects (D-15): `SubjectSector` returns "" for public; for pairwise returns the trimmed SectorIdentifier when set, else the host of the redirect URIs when they all share one host, else `ErrSectorRequired`; resume, token and userinfo call SubjectFor(user, sector, uuid.NewV4().String()).
|
||||
|
||||
Refresh (D-17): when RefreshEnabled and the granted scopes include offline_access and the client has OfflineAccess, the code exchange also creates an `oas_rt_` refresh token (stored hashed, TTL RefreshTokenTTL, linked to the access token) and returns refresh_token between id_token and scope; the refresh_token grant authenticates the client like the code grant, a client without OfflineAccess gets 400 unauthorized_client, RefreshTokenByHashForUpdate then: unknown, expired or revoked gives invalid_grant; an already rotated token revokes the whole lineage (RevokeRefreshLineage also revokes linked access tokens) and gives invalid_grant; otherwise a new access token, a new refresh token, MarkRefreshRotated, and a fresh id_token without nonce; a scope parameter must be a subset of the stored scopes or invalid_scope. Discovery adds refresh_token to grant_types_supported and offline_access to scopes_supported only when RefreshEnabled.
|
||||
|
||||
`IssueOIDCClientCredentials(o OIDCOptions)` in oidc_options.go: client id ClientIDPrefix + hex of 12 random bytes, secret ClientSecretPrefix + base64url of 32 random bytes, secretHash sha256Hex(secret).
|
||||
|
||||
Smoke tests in oidc_token_smoke_test.go: `TestOIDCTokenErrorsSmoke` (wrong secret gives 401 with the lowercase realm; unsupported grant 400 with no-store, private and Pragma; Basic credentials with percent-encoded characters authenticate), `TestOIDCReplayRevokesSmoke` (second exchange of a code gives invalid_grant and the first access token is revoked at userinfo), `TestOIDCUserInfoSmoke` (missing, revoked and expired tokens give 401 with an empty body; email claims absent without the email scope), `TestMixedKeyRingSmoke` (an ES256 active key and an RS256 retired key: JWKS has both JWK kinds, discovery lists RS256 and ES256, a token signed before rotation still verifies against the JWKS), `TestPairwiseSubjectSmoke` (two pairwise clients on different sectors get different subs for one user, the same client gets the same sub twice, userinfo sub equals id_token sub, mixed redirect hosts without a sector give ErrSectorRequired), `TestOIDCRefreshOptInSmoke` (disabled server: unsupported_grant_type; enabled: a client without OfflineAccess gets no refresh token; rotation works; replaying a rotated token revokes the lineage). README rows for every identifier this task adds and the dependency line for golang-jwt.</action>
|
||||
<verify>
|
||||
<automated>go vet ./... && go test -count=1 -short ./modules/wristband/... && go test -count=1 -short -run '^(TestOIDCTokenErrorsSmoke|TestOIDCReplayRevokesSmoke|TestOIDCUserInfoSmoke|TestMixedKeyRingSmoke|TestPairwiseSubjectSmoke|TestOIDCRefreshOptInSmoke)$' -v ./modules/wristband 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 6 && go test -count=1 -run '^TestDocsTree$' ./cmd/summer</automated>
|
||||
<fails_when>Non-zero exit: vet or the wristband suite red, fewer than six "--- PASS" lines for the token, userinfo, key, subject and refresh smokes, or the docs checker fails.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c 'MarshalSingleStringAsArray' modules/wristband/*.go` prints 0 for every file (the golang-jwt package global is never touched).
|
||||
- `grep -nE 'Basic realm=\\?"oauth\\?"' modules/wristband/oidc_token.go` prints at least one line and `grep -nE 'Basic realm=\\?"OAuth\\?"' modules/wristband/token.go` still prints at least one line (MCP keeps its capitalised realm).
|
||||
- `grep -n 'ES256' modules/wristband/oidc_keys.go | wc -l` prints at least 2.
|
||||
- `grep -n 'ErrSectorRequired' modules/wristband/oidc_subject.go modules/wristband/README.md | wc -l` prints at least 2.
|
||||
- `go test -count=1 -short -run '^TestOIDCReplayRevokesSmoke$' -v ./modules/wristband 2>&1 | grep -c -- '--- PASS'` prints 1.
|
||||
</acceptance_criteria>
|
||||
<done>The token and userinfo endpoints answer every PHP case with PHP's bytes and headers, RS256 and ES256 rings rotate visibly in JWKS and discovery, pairwise and public subjects are stable, and refresh is available only to clients that opt in.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 4: The framework default names no application, fonoteka keeps its resource, and the README and the OAuth server page document the OIDC provider (folded todo closed)</name>
|
||||
<files>modules/wristband/server.go, modules/wristband/stores.go, modules/wristband/client_issue.go, modules/wristband/authorize_test.go, modules/wristband/token_test.go, modules/wristband/server_test.go, modules/wristband/example_test.go, modules/wristband/README.md, README.md, docs/services/oauth-server.md, ../fonoteka.go/plugins/golem15/fonoteka/plugin.go, ../fonoteka.go/plugins/golem15/fonoteka/oauth_resource_test.go, .planning/todos/pending/wristband-neutral-resource-default.md, .planning/todos/done/wristband-neutral-resource-default.md</files>
|
||||
<read_first>.planning/todos/pending/wristband-neutral-resource-default.md, 19.4-RESEARCH.md (Code Examples "Folded todo: empty Resource"), modules/wristband/server.go (package comment :1-11, Resource field :61-65, DefaultOptions :91-106), modules/wristband/stores.go (comments naming the host app), modules/wristband/client_issue.go (:1-7), modules/wristband/example_test.go (newServer region used by docs src=), modules/wristband/README.md, README.md (module table wristband row), docs/services/oauth-server.md, ../fonoteka.go/plugins/golem15/fonoteka/plugin.go (:143-175), ../fonoteka.go/plugins/golem15/fonoteka/config/config.yaml (oauth.resource), ../fonoteka.go/plugins/golem15/fonoteka/oauth_authorize_test.go (assembled-app harness, resource cases :107-250), .planning/G15OFFICE.md</read_first>
|
||||
<action>Folded todo (CONTEXT Folded Todos): `DefaultOptions().Resource` becomes "" (authorize compares only when the client sends resource, authorize.go:119-126, so an empty default refuses a sent resource and leaves clients that omit it unaffected); reword the package comment, the Resource field comment (no PHP config key that names an application, no default URL), the stores.go and client_issue.go comments to "the host application" and its adapter or operator command. Wristband tests that relied on the old default set `opts.Resource` to the neutral `https://resource.example.test/mcp` explicitly (and assert the same bytes otherwise); while touching those test files replace other application names in their literals with neutral ones. The README defaults table states that Resource has no default and must be set. Add `TestDefaultOptionsResourceEmpty` to server_test.go (DefaultOptions().Resource is "" and every other default is unchanged).
|
||||
|
||||
fonoteka (D-09, folded todo): in plugins/golem15/fonoteka/plugin.go set `oauthOpts.Resource = "https://mcp.plytarium.com/mcp"` right after DefaultOptions (the host names itself; the config override stays); new oauth_resource_test.go `TestOAuthResourceExplicit` boots the assembled app the way oauth_authorize_test.go does with the golem15.fonoteka.oauth.resource key blanked and asserts that authorize accepts the plugin's own resource and refuses https://wrong.example.test/mcp with invalid_target. Commit in fonoteka.go with only these two paths staged (`fix(fonoteka): set the OAuth resource explicitly`).
|
||||
|
||||
Docs (SC-5), in the summercms.go code commit: wristband README summary sentence becomes "An OAuth authorization server and OpenID Connect provider: RFC 8414 metadata, dynamic client registration, discovery, JWKS, id_token, userinfo, resumable consent and refresh-token rotation over application-supplied storage." (and the root README.md wristband row's purpose cell equals it); Overview and Role describe the two flavours sharing one engine and the OIDCHost seam; Usage gains an OIDC example; the API reference lists every exported identifier of this plan (check against this plan's Artifacts); Dependencies lists github.com/golang-jwt/jwt/v5 and the new standard library packages (crypto, crypto/ecdsa, crypto/elliptic, crypto/rsa, crypto/x509, encoding/pem, log/slog, math/big, uuid, slices); Testing mentions the OIDC smokes. example_test.go gains an `ExampleNewOIDCServer` region (neutral issuer https://id.example.com) for docs src= use. docs/services/oauth-server.md gains a section "OpenID Connect provider": what the OIDC flavour implements (the PHP-compatible discovery, JWKS, authorize with resume, consent and switch account, token with id_token, userinfo, public and pairwise subjects, RS256 and ES256 rotation, opt-in refresh), the OIDCHost contract, the storage and key interfaces, kinds, and a pointer that a shared plugin supplies storage, pages and routes; update the existing "Configuring the server" text so Resource is described as required and its default as empty; run `go run ./cmd/summer docs:sync` after the example change. No application, client or relying party is named.
|
||||
|
||||
Close the todo: `git mv .planning/todos/pending/wristband-neutral-resource-default.md .planning/todos/done/` with a one-line resolution note at the end of the file, committed alone (`docs(19.4): close neutral wristband resource todo`). Move g15office task iarcg5dk to Live with a one-line comment naming plan 19.4-01 (G15OFFICE.md); if the g15office tool is unavailable in this session, record that in the SUMMARY for the orchestrator.</action>
|
||||
<verify>
|
||||
<automated>go vet ./... && go test -count=1 -short ./... && go -C ../fonoteka.go vet ./... ./plugins/golem15/fonoteka/... && go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/fonoteka/... && go -C ../fonoteka.go test -count=1 -run '^TestOAuthResourceExplicit$' -v ./plugins/golem15/fonoteka 2>&1 | grep -q -- '^--- PASS: TestOAuthResourceExplicit' && go test -count=1 -run '^TestDocsTree$' ./cmd/summer && go run ./cmd/summer docs:build --check</automated>
|
||||
<fails_when>Non-zero exit: vet or the short framework suite red, fonoteka fails to compile or a fonoteka plugin test fails (D-09 broken), TestOAuthResourceExplicit did not print "--- PASS" (it skips without Docker; run on a Docker host, through sudo -u golem if the socket is denied), or the docs checker or docs:build --check reports a problem.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -rniE 'plytarium|płytarium|fonoteka|wavepath' modules/wristband --include='*.go' --include='*.md' | grep -v '_test.go:'` prints nothing.
|
||||
- `go test -count=1 -short -run '^TestDefaultOptionsResourceEmpty$' -v ./modules/wristband 2>&1 | grep -c -- '--- PASS'` prints 1.
|
||||
- `test -f .planning/todos/done/wristband-neutral-resource-default.md && test ! -f .planning/todos/pending/wristband-neutral-resource-default.md` exits 0.
|
||||
- The wristband row's purpose cell in README.md equals the second non-empty line of modules/wristband/README.md (`diff <(grep '^| \[wristband\]' README.md | awk -F'|' '{gsub(/^ +| +$/,"",$3); print $3}') <(awk 'NF' modules/wristband/README.md | sed -n 2p)` prints nothing).
|
||||
- `grep -c 'OpenID Connect provider' docs/services/oauth-server.md` prints at least 1.
|
||||
- `F=$(git -C ../fonoteka.go log -1 --name-only --format=) && printf '%s\n' "$F" | sort | tr '\n' ' '` lists exactly plugins/golem15/fonoteka/oauth_resource_test.go and plugins/golem15/fonoteka/plugin.go (the fonoteka commit staged nothing else).
|
||||
</acceptance_criteria>
|
||||
<done>The framework default is neutral, fonoteka behaves exactly as before, and a reader of the README and the OAuth server page can build an OIDC provider on wristband.</done>
|
||||
</task>
|
||||
|
||||
</tasks>
|
||||
|
||||
<threat_model>
|
||||
## Trust Boundaries
|
||||
|
||||
| Boundary | Description |
|
||||
|----------|-------------|
|
||||
| browser to authorize, resume, decide, switch-account | untrusted query and form input, a session cookie that may be stale or someone else's |
|
||||
| relying party to token endpoint | client credentials, codes and verifiers from a server on the internet |
|
||||
| bearer holder to userinfo | any presented token string |
|
||||
| engine to host (OIDCHost) and storage (OIDCBackend, KeyStore) | the host renders HTML and resolves the user; storage returns rows the engine trusts |
|
||||
| engine to relying party | signed id_tokens and JWKS the relying party trusts for identity |
|
||||
|
||||
## STRIDE Threat Register
|
||||
|
||||
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|
||||
|-----------|----------|-----------|----------|-------------|-----------------|
|
||||
| T-19.4-01 | Spoofing | oidcAuthorize, matchOIDCRedirectURI | high | mitigate | unknown client and redirect mismatch are rendered through RenderAuthorizeError, never redirected; byte-exact matching; the loopback port exception only for is_dev clients and only for localhost, 127.0.0.1 and [::1]; TestOIDCAuthorizeStartSmoke |
|
||||
| T-19.4-02 | Spoofing | authorize and token PKCE | high | mitigate | S256 only, challenge regex 43-128 base64url, verifier charset and length, constant-time compare; code bound to client and redirect, 60 s TTL, single use |
|
||||
| T-19.4-03 | Tampering | oidcToken code redemption | high | mitigate | ConsumeCode before any other check (burn then check); a replay revokes every access token issued from the code and the revocation commits although the answer is an error; TestOIDCReplayRevokesSmoke |
|
||||
| T-19.4-04 | Spoofing | decide, switch-account, ConsentRequest, DecideConsent | high | mitigate | one-shot consent token, digest SHA-256(token pipe userID) on the request row, read under row lock, constant-time compare, cleared on use; the request row has no user column; any failure is expired_request |
|
||||
| T-19.4-05 | Elevation of privilege | kind checks in both flavours | high | mitigate | MCP flavour refuses Kind oidc at authorize and token; OIDC flavour accepts only Kind oidc at authorize, token and userinfo; openid stays outside the MCP scope allowlist; TestKindIsolationSmoke |
|
||||
| T-19.4-06 | Spoofing | client authentication | medium | mitigate | secret prefix gate, SHA-256 hex compared in constant time, a dummy comparison for unknown clients, one uniform invalid_client answer; the plugin adds the per-client_id throttle (plan 02) |
|
||||
| T-19.4-07 | Spoofing | id_token claims | high | mitigate | aud is the client id as a string, nonce echoed when sent, at_hash over the issued access token, exp from IDTokenTTL; relying parties verify against the JWKS (go-oidc interop in plan 02) |
|
||||
| T-19.4-08 | Tampering | signIDToken, jwkFor, Discovery | medium | mitigate | the server only signs, with the method derived from the key type (RS256 or ES256), and refuses an Alg and key mismatch; discovery advertises exactly the algorithms in the ring; every JWK carries alg and use sig |
|
||||
| T-19.4-09 | Information disclosure | logs and errors in oidc_*.go | high | mitigate | logs carry client_id, client IP and a fixed reason only; key material reaches the engine only as crypto.Signer; key-store and backend errors become fixed messages (Signing keys are unavailable.) |
|
||||
| T-19.4-10 | Information disclosure | UserInfo | medium | mitigate | one uniform 401 with an empty body and Bearer error="invalid_token" for missing, malformed, unknown, expired, revoked, wrong-kind and gone-user cases; no-store, private |
|
||||
| T-19.4-11 | Tampering | identity claim merge | medium | mitigate | identity claims filtered by the IdentityClaims allowlist; protocol claims (iss, aud, exp, iat, nonce, at_hash) are written after and sub is forced last, so a user attribute can never overwrite them |
|
||||
| T-19.4-12 | Spoofing | refresh grant | medium | mitigate | off by default; only OfflineAccess clients granted offline_access; rotation on every use; a replayed rotated token revokes the lineage and its access tokens; TestOIDCRefreshOptInSmoke |
|
||||
| T-19.4-13 | Information disclosure | subjects | low | mitigate | sub is a random UUIDv4 per (user, sector), never derived from id, email or name; pairwise clients get per-sector subs so relying parties cannot correlate users across sectors |
|
||||
| T-19.4-14 | Tampering | MCP regression through shared code (D-09) | medium | mitigate | flavour dispatch at the top of Authorize and Token, MCP encoders untouched, existing wristband suite and fonoteka compile and tests in the verify commands |
|
||||
| T-19.4-SC | Tampering | Go module installs | high | mitigate | no module is installed in this plan (golang-jwt v5.3.1 is already required); go-oidc and x/oauth2 wait for plan 02's blocking human package check; acceptance criterion greps go.mod |
|
||||
</threat_model>
|
||||
|
||||
<verification>
|
||||
- Task 1: the note precedes the first OIDC code; the wristband suite and TestOIDCTracerSmoke; docs checker and docs:build --check.
|
||||
- Task 2: four authorize smokes; fonoteka compiles against the new ClientRecord field.
|
||||
- Task 3: six token, userinfo, key, subject and refresh smokes.
|
||||
- Task 4: the whole short framework suite, fonoteka plugin tests and TestOAuthResourceExplicit, docs checker, the no-application-name grep.
|
||||
- Feedback sampling (19.4-VALIDATION.md): after each commit `go vet ./... && go test -short ./modules/wristband/...`.
|
||||
</verification>
|
||||
|
||||
<success_criteria>
|
||||
- SC-1: the decision note, naming golang-jwt v5 and the test-only RP modules, landed before the code.
|
||||
- SC-2 (engine): discovery, JWKS, token with id_token and userinfo work with RS256 and ES256 keys; a retired key stays published.
|
||||
- SC-3 (engine): resume, switch account, consent and public plus pairwise subjects work over the new interfaces.
|
||||
- SC-5: wristband README and docs/services/oauth-server.md updated; the docs checker is green.
|
||||
- D-09: fonoteka compiles and passes with only the explicit resource change.
|
||||
</success_criteria>
|
||||
|
||||
<output>
|
||||
Create `.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-SUMMARY.md` when done, with the commits in order (planning docs first), the final exported identifiers (plan 02 reads them from here), the fonoteka commit hash, which Docker-backed tests ran or were NOT RUN, the g15office update, and any deviation from this plan's names.
|
||||
</output>
|
||||
381
.planning/phases/19.4-oidc-provider-on-wristband/19.4-02-PLAN.md
Normal file
381
.planning/phases/19.4-oidc-provider-on-wristband/19.4-02-PLAN.md
Normal file
@@ -0,0 +1,381 @@
|
||||
---
|
||||
phase: 19.4-oidc-provider-on-wristband
|
||||
plan: 02
|
||||
type: execute
|
||||
wave: 2
|
||||
depends_on: ["19.4-01"]
|
||||
files_modified:
|
||||
- ../fonoteka.go/plugins/golem15/user/classes/session_user.go
|
||||
- ../fonoteka.go/plugins/golem15/user/classes/avatar.go
|
||||
- ../fonoteka.go/plugins/golem15/user/classes/events.go
|
||||
- ../fonoteka.go/plugins/golem15/user/controllers/api_controller.go
|
||||
- ../fonoteka.go/plugins/golem15/user/controllers/registration.go
|
||||
- ../fonoteka.go/plugins/golem15/user/controllers/users_admin_controller.go
|
||||
- ../fonoteka.go/plugins/golem15/user/README.md
|
||||
- ../sm-oauthserver-plugin/.gitignore
|
||||
- ../sm-oauthserver-plugin/go.mod
|
||||
- ../sm-oauthserver-plugin/go.sum
|
||||
- ../sm-oauthserver-plugin/go.work
|
||||
- ../sm-oauthserver-plugin/README.md
|
||||
- ../sm-oauthserver-plugin/plugin.go
|
||||
- ../sm-oauthserver-plugin/servers.go
|
||||
- ../sm-oauthserver-plugin/routes.go
|
||||
- ../sm-oauthserver-plugin/buckets.go
|
||||
- ../sm-oauthserver-plugin/config/config.yaml
|
||||
- ../sm-oauthserver-plugin/lang/en/lang.yaml
|
||||
- ../sm-oauthserver-plugin/lang/pl/lang.yaml
|
||||
- ../sm-oauthserver-plugin/models/registry.go
|
||||
- ../sm-oauthserver-plugin/models/client.go
|
||||
- ../sm-oauthserver-plugin/models/auth_request.go
|
||||
- ../sm-oauthserver-plugin/models/auth_code.go
|
||||
- ../sm-oauthserver-plugin/models/access_token.go
|
||||
- ../sm-oauthserver-plugin/models/refresh_token.go
|
||||
- ../sm-oauthserver-plugin/models/consent.go
|
||||
- ../sm-oauthserver-plugin/models/subject.go
|
||||
- ../sm-oauthserver-plugin/models/signing_key.go
|
||||
- ../sm-oauthserver-plugin/models/mcp_code.go
|
||||
- ../sm-oauthserver-plugin/models/settings.go
|
||||
- ../sm-oauthserver-plugin/updates/registry.go
|
||||
- ../sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go
|
||||
- ../sm-oauthserver-plugin/updates/202610190002_create_golem15_oauthserver_settings.go
|
||||
- ../sm-oauthserver-plugin/updates/202610190003_create_golem15_oauthserver_mcp_codes.go
|
||||
- ../sm-oauthserver-plugin/classes/lazy.go
|
||||
- ../sm-oauthserver-plugin/classes/oidc_store.go
|
||||
- ../sm-oauthserver-plugin/classes/mcp_store.go
|
||||
- ../sm-oauthserver-plugin/classes/keyring.go
|
||||
- ../sm-oauthserver-plugin/classes/claims.go
|
||||
- ../sm-oauthserver-plugin/classes/host.go
|
||||
- ../sm-oauthserver-plugin/classes/branding.go
|
||||
- ../sm-oauthserver-plugin/classes/cascade.go
|
||||
- ../sm-oauthserver-plugin/controllers/authorizations.go
|
||||
- ../sm-oauthserver-plugin/controllers/consent_api.go
|
||||
- ../sm-oauthserver-plugin/views/consent.html.tmpl
|
||||
- ../sm-oauthserver-plugin/views/error.html.tmpl
|
||||
- ../sm-oauthserver-plugin/testmain_test.go
|
||||
- ../sm-oauthserver-plugin/harness_test.go
|
||||
- ../sm-oauthserver-plugin/oidc_flow_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/pages_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/authorizations_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/mcp_store_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/interop_test.go
|
||||
autonomous: false
|
||||
requirements: [SC-2, SC-3, D-01, D-02, D-03, D-04, D-05, D-06, D-08, D-10, D-12, D-15, D-16, D-17, D-18, D-19]
|
||||
estimate:
|
||||
tokens: 280000
|
||||
raw_tokens: 280000
|
||||
tasks: 5
|
||||
confidence: low
|
||||
must_haves:
|
||||
truths:
|
||||
- "D-01, D-02: a new repository ../sm-oauthserver-plugin (module git.golem15.com/golem15/sm-oauthserver-plugin, plugin ID golem15.oauthserver, Requires golem15.user) holds the GORM stores for both flows: classes.Store implements wristband.OIDCBackend and classes.MCPStore implements wristband.Backend over the same golem15_oauthserver_* tables, filtering clients by kind in SQL."
|
||||
- "D-06: the plugin builds one MCP *wristband.Server and one OIDC *wristband.Server from the same issuer and publishes them through one wrapper type (*oauthserver.Servers), never two *wristband.Server values; the MCP routes and RFC 8414 metadata are mounted only when golem15.oauthserver.mcp.enabled is true (default false); MCP access-token verification is Phase 19.7's."
|
||||
- "D-10, D-12: signing keys live in golem15_oauthserver_keys (kid unique, alg, public PEM, private PEM as lagoon.Encrypted, created_at, retired_at, active with a partial unique index WHERE active); the first key is generated lazily (RS256 by default, ES256 when key_algorithm is ES256) and two instances racing the first key end with exactly one active key; the private PEM is never serialised, logged or exposed."
|
||||
- "SC-2, D-16: a stock relying party (go-oidc v3.21.0 + x/oauth2 v0.37.0, test-only, installed after a blocking human package check) discovers the provider, completes authorize with PKCE and nonce, exchanges the code, verifies the id_token and at_hash and reads userinfo with the same sub, against an RS256 ring and an ES256 ring on Postgres."
|
||||
- "D-03: the consent and error pages are server-rendered html/template pages with the branding settings (site name, logo, colours, font CSS URL and family, custom CSS) passed through ported PHP sanitisers, a client name containing markup is escaped, and the consent form carries the one-shot consent token; with consent_mode redirect the browser goes to consent_url?request={id} and JSON endpoints serve and decide the same consent."
|
||||
- "D-04, D-05: an anonymous browser at /oauth/authorize goes to the configured login_url with only redirect=/oauth/authorize/resume/{request}; the signed-in user comes from sm-user-plugin's token JWT cookie (classes.RequestUser); switch-account blacklists that JWT's jti and forgets the cookie with the 19.3 cookie attributes (classes.EndRequestSession); claims name, picture, groups, communities, email and email_verified come from sm-user-plugin data with PHP's rules."
|
||||
- "D-05: sm-user-plugin changes are additive only (new exported functions, a new user.Deactivating event fired by the deactivate bulk action, applyAvatar delegating to the new AvatarURL with unchanged output); its own tests and fonoteka still pass; the user plugin is committed in its own repository before the oauthserver plugin uses it."
|
||||
- "SC-3: GET /oauth/authorizations lists the caller's authorizations newest first in PHP's shape and DELETE /oauth/authorizations/{client_id} removes the consent, codes, access and refresh tokens of that pair; another user's or an unknown client id answers 404 {\"error\":\"not_found\"}."
|
||||
- "D-05 cascade: user.Deleting removes the user's subjects, consents, codes, access, refresh and MCP code rows in the event's transaction; user.Deactivating removes the same rows except subjects, so a restored user keeps the same sub."
|
||||
- "D-18: named surf buckets oauth-authorize (30/min, user id from the token cookie else IP), oauth-token (20/min, form client_id else IP, Basic header not consulted, as PHP), oauth-userinfo (60/min, SHA-256 of the bearer else IP) and oauth-authorizations (120/min, user else IP) guard their routes; discovery and JWKS stay unthrottled with Cache-Control max-age=3600, public."
|
||||
- "D-15, D-17, D-19: clients carry kind, subject_type, sector_identifier and offline_access columns (imported PHP rows default to oidc, public, no offline_access); subjects are unique per (user_id, sector) with public as the empty sector; the issuer comes from golem15.oauthserver.issuer, falling back to app.url, trailing slash trimmed."
|
||||
artifacts:
|
||||
- path: "../sm-oauthserver-plugin/plugin.go"
|
||||
provides: "the golem15.oauthserver plugin: config, servers, routes, buckets, migrations, models, listeners"
|
||||
contains: "golem15.oauthserver"
|
||||
- path: "../sm-oauthserver-plugin/classes/oidc_store.go"
|
||||
provides: "GORM implementation of wristband.OIDCBackend and wristband.OIDCTx"
|
||||
contains: "WithinOIDCTx"
|
||||
- path: "../sm-oauthserver-plugin/classes/keyring.go"
|
||||
provides: "database key ring implementing wristband.KeyStore with lazy first key and grace window"
|
||||
contains: "PublishedKeys"
|
||||
- path: "../sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go"
|
||||
provides: "raw SQL migration for clients, auth_requests, auth_codes, access_tokens, refresh_tokens, consents, subjects, keys"
|
||||
contains: "WHERE active"
|
||||
- path: "../sm-oauthserver-plugin/views/consent.html.tmpl"
|
||||
provides: "server-rendered branded consent page"
|
||||
contains: "consent_token"
|
||||
- path: "../sm-oauthserver-plugin/interop_test.go"
|
||||
provides: "TestRelyingPartyInterop with go-oidc and x/oauth2"
|
||||
contains: "TestRelyingPartyInterop"
|
||||
key_links:
|
||||
- from: "../sm-oauthserver-plugin/plugin.go"
|
||||
to: "modules/wristband/oidc_options.go"
|
||||
via: "Boot builds NewOIDCServer and calls SetOIDCBackend(store, keyring, host)"
|
||||
pattern: "SetOIDCBackend"
|
||||
- from: "../sm-oauthserver-plugin/classes/host.go"
|
||||
to: "../fonoteka.go/plugins/golem15/user/classes/session_user.go"
|
||||
via: "SignedInUser and EndSession call classes.RequestUser and classes.EndRequestSession"
|
||||
pattern: "RequestUser"
|
||||
- from: "../sm-oauthserver-plugin/classes/cascade.go"
|
||||
to: "../fonoteka.go/plugins/golem15/user/classes/events.go"
|
||||
via: "listeners on DeletingEvent and DeactivatingEvent"
|
||||
pattern: "DeactivatingEvent"
|
||||
- from: "../sm-oauthserver-plugin/routes.go"
|
||||
to: "../sm-oauthserver-plugin/buckets.go"
|
||||
via: "throttle:oauth-* middleware names on the route groups"
|
||||
pattern: "throttle:oauth-token"
|
||||
prohibitions:
|
||||
- statement: "No existing sm-user-plugin exported signature changes; DeactivateUsers keeps its signature."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "The signing-key model is never registered in any cabana form or list and its private PEM never leaves the key ring."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "Nothing is pushed, tagged or deployed; no app's submodule pointer is bumped in this plan."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
---
|
||||
|
||||
## Phase Goal
|
||||
|
||||
ROADMAP Goal (not in user-story format; no story invented, see plan 01): `wristband` is a full OpenID Connect provider that existing relying parties can switch to without noticing: discovery, JWKS with asymmetric signing and key rotation, `id_token`, userinfo, resumable authorization with account switching, a consent store and pairwise subjects. The existing issuer, signing keys and client secrets carry over.
|
||||
|
||||
This plan's slice (plan 2 of 4, wave 2): the plugin half of D-01. A new shared plugin `sm-oauthserver-plugin` gives an application everything the PHP `Golem15.OAuthServer` plugin served: the tables, the stores for OIDC and MCP, the database key ring, the routes at the PHP paths with the PHP throttles, branded consent and error pages, the authorized-apps JSON, and the user cascade, proven first with a Postgres end-to-end flow and finally with a stock relying-party library.
|
||||
|
||||
## Decisions taken in this plan (recorded assumptions and Claude's discretion)
|
||||
|
||||
- Tables keep the PHP names `golem15_oauthserver_*` so the import (plan 03) is a straight copy (CONTEXT discretion). New: `_keys`, `_refresh_tokens` (OIDC opt-in refresh and MCP lineage), `_mcp_codes` (MCP pending rows have no user and no code hash, so they cannot share `_auth_codes`), `_settings` (branding singleton). Raw SQL migrations, never AutoMigrate.
|
||||
- Signed-in user seam (RESEARCH OQ7, researcher's pattern-map recommendation): sm-user-plugin exports `classes.RequestUser` and `classes.EndRequestSession` built on its own JWT guard configuration; no bouncer API change.
|
||||
- `communities` claim (RESEARCH OQ2, A9): read-only SQL on `golem15_userfriends_group_members` joined to `golem15_userfriends_groups` (deleted_at IS NULL) when both tables exist (`Migrator().HasTable`), else `[]`; no import of sm-userfriends-plugin.
|
||||
- Soft delete (user decision): sm-user-plugin fires a new `user.Deactivating` event from the deactivate bulk action through `controllers.FireDeactivatingEvent`, modelled on `FireDeletingEvent`; `DeactivateUsers` keeps its signature.
|
||||
- Key ring: the active kid is read from the database on every `ActiveSigningKey` call (one indexed SELECT) so a rotation on one instance reaches every instance at once; parsed signers are cached per kid in process; JWKS is read per request (Cache-Control does the caching, as PHP).
|
||||
- Config keys under `golem15.oauthserver.*` (environment `SUMMER_GOLEM15__OAUTHSERVER__*`): `issuer` (PHP OAUTHSERVER_ISSUER; empty falls back to app.url), `login_url` (`/login`), `rotation_grace_hours` (24), `ttl.id_token` (3600), `ttl.access_token` (3600), `ttl.auth_code` (60), `ttl.auth_request` (600), `ttl.refresh_token` (2592000), `picture_size` (128), `consent_mode` (`page` or `redirect`, default `page`), `consent_url` (required with redirect), `key_algorithm` (`RS256` or `ES256`, default RS256), `rotation_interval` (plan 03, default empty = off), `refresh.enabled` (false), `cors_profile` (empty = no CORS middleware on the SPA routes), `mcp.enabled` (false), `mcp.resource` (empty), `token_body_limit` (65536).
|
||||
- JSON consent endpoints for redirect mode: `GET /oauth/authorize/requests/{request}` answers {request_id, consent_token, client {client_id, name, logo_url}, scopes [missing scope keys]}; `POST /oauth/authorize/requests/{request}` with JSON {consent_token, decision} answers {redirect_uri}; both behind `jwt.auth` and the oauth-authorize bucket.
|
||||
- The token bucket reads `client_id` from the form only, so a client_secret_basic relying party is limited per IP: that is PHP's key (D-18 "same keys") and is ported on purpose, with a comment.
|
||||
- Without a configured `cors_profile`, `OPTIONS /oauth/authorizations` is not routed (pact.Router has no OPTIONS verb); PHP answered 204. Recorded as an accepted parity deviation for plan 03.
|
||||
- sm-user-plugin's local master is ahead 3 and behind 1 of its origin (RESEARCH Pitfall 10). This plan fetches and records the divergence but neither merges nor pushes: reconciling belongs to the push step, which waits for the user.
|
||||
- Context budget (estimate 280k, 5 tasks; size accepted with the four-plan decision): the Task 4 legitimacy checkpoint splits execution in two, since the executor resumes in a fresh continuation agent. Tasks 1-3 run in the first context; Task 5 (interop) runs in the continuation agent and reads plan 01's SUMMARY, the harness and the Task 1-3 commits from disk.
|
||||
|
||||
## Artifacts this phase produces (this plan)
|
||||
|
||||
- sm-user-plugin (additive): `classes.RequestUser(ctx context.Context, app *backpack.App, r *http.Request) (*models.User, error)`, `classes.EndRequestSession(ctx context.Context, app *backpack.App, w http.ResponseWriter, r *http.Request) error`, `classes.AvatarURL(ctx context.Context, app *backpack.App, user *models.User, size int) (string, error)`, `classes.DeactivatingEventName` (`user.Deactivating`), `classes.DeactivatingEvent{User *models.User; Tx *gorm.DB}`, `controllers.FireDeactivatingEvent(ctx, app, user, tx) error`.
|
||||
- Plugin package `oauthserver`: `PluginID` (`golem15.oauthserver`), `Plugin` (ID, Requires, Register, Boot, ConfigFS, LangFS, Migrations, Models, Routes, Buckets), `Servers{MCP, OIDC *wristband.Server}`, bucket names `BucketAuthorize` (`oauth-authorize`), `BucketToken` (`oauth-token`), `BucketUserInfo` (`oauth-userinfo`), `BucketAuthorizations` (`oauth-authorizations`), `BucketMCPRegister` (`oauth-mcp-register`), `BucketMCPToken` (`oauth-mcp-token`).
|
||||
- `models`: `LangPrefix`, `Client`, `AuthRequest`, `AuthCode`, `AccessToken`, `RefreshToken`, `Consent`, `Subject`, `SigningKey`, `MCPCode`, `Settings`, `Register`, `All`.
|
||||
- `updates`: `Register`, `All`, migrations `202610190001_create_golem15_oauthserver_tables`, `202610190002_create_golem15_oauthserver_settings`, `202610190003_create_golem15_oauthserver_mcp_codes`.
|
||||
- `classes`: `Store` (`NewStore(db *gorm.DB) *Store`, `WithinOIDCTx`), `MCPStore` (`NewMCPStore(db *gorm.DB) *MCPStore`, `WithinTx`), `LazyStore`, `LazyMCPStore`, `KeyRing` (`NewKeyRing(app *backpack.App, cfg KeyRingConfig) *KeyRing`, `ActiveSigningKey`, `PublishedKeys`, `Rotate`, `Prune`), `KeyRingConfig` (`Algorithm`, `Grace`), `Claims` (`IdentityClaims` used by the store), `Host` (implements wristband.OIDCHost), `Branding` (`LoadBranding`, `BrandingCSS`, `SanitizeColor`, `SanitizeFontFamily`, `SanitizeCSSURL`, `SanitizeCustomCSS`, `DangerColor`, `MaxCustomCSS`), `Cascade` (`OnUserDeleting`, `OnUserDeactivating`).
|
||||
- `controllers`: `AuthorizationsIndex(app) http.HandlerFunc`, `AuthorizationsDestroy(app) http.HandlerFunc`, `ConsentShow(app, srv) http.HandlerFunc`, `ConsentDecide(app, srv) http.HandlerFunc`.
|
||||
- Views `views/consent.html.tmpl`, `views/error.html.tmpl`; lang keys under `golem15.oauthserver::lang.*` (en, pl).
|
||||
- Smoke tests: `TestOIDCFlowSmoke`, `TestKeyRingFirstKeyRaceSmoke` (oidc_flow_smoke_test.go), `TestConsentPageBrandingSmoke`, `TestLoginHandoffAndSwitchSmoke`, `TestBucketKeysSmoke`, `TestRouteGuardSmoke` (pages_smoke_test.go), `TestAuthorizationsSmoke`, `TestUserCascadeSmoke` (authorizations_smoke_test.go), `TestMCPStoreSmoke` (mcp_store_smoke_test.go), `TestRelyingPartyInterop` (interop_test.go); harness `bootOAuth` (harness_test.go); full coverage in plan 04.
|
||||
|
||||
<objective>
|
||||
Create the shared plugin that turns wristband's OIDC flavour into a working provider for any SummerCMS application, at the PHP plugin's paths, with its storage, keys, pages, throttles, authorized-apps API and user cascade, and prove it against a stock relying-party library.
|
||||
|
||||
Purpose: SC-2 and SC-3 (plugin side), D-01..D-06, D-08, D-10, D-12, D-15..D-19. Plan 03 adds the admin screens, commands, the Winter import, tide parity and the security review on top.
|
||||
Output: commits in sm-user-plugin first, then in the new sm-oauthserver-plugin repository; nothing pushed.
|
||||
</objective>
|
||||
|
||||
<execution_context>
|
||||
@~/.claude/msd-core/workflows/execute-plan.md
|
||||
@~/.claude/msd-core/templates/summary.md
|
||||
</execution_context>
|
||||
|
||||
<context>
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-CONTEXT.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-RESEARCH.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-PATTERNS.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-SUMMARY.md
|
||||
|
||||
Repos: three repositories. (1) sm-user-plugin, edited in its newest checkout `../fonoteka.go/plugins/golem15/user` (its own git repository, a submodule of fonoteka.go): commit there with explicit paths, never touch fonoteka.go's superproject pointer (another session has it modified). (2) The new `../sm-oauthserver-plugin` (git init -b master, origin git@git.golem15.com:golem15/sm-oauthserver-plugin.git added but never pushed). (3) summercms.go is read-only in this plan. Commit sm-user-plugin before the plugin code that uses it. No co-author tags; stage files by path; README updated in the same commit as the API it describes. Docker-backed tests skip under -short; run them on a Docker host (through `sudo -u golem` if the socket is denied although the user is in the docker group) and record NOT RUN in the SUMMARY when no daemon answers.
|
||||
|
||||
Plan 01's SUMMARY lists the final wristband identifiers; where it deviates from the names below, follow the SUMMARY.
|
||||
|
||||
PHP source of truth (read-only): /media/nvme/dev/jz/wavepath.org/plugins/golem15/oauthserver/ — routes.php, Plugin.php, config/oauthserver.php, updates/*.php (columns, indexes), models/*.php, classes/{KeyRing,ClaimBuilder,ConsentCsrf,UserCascade,ScopeCatalog}.php, models/Settings.php (branding, brandingCss, sanitisers :96-300), views/consent.htm, views/error.htm, controllers/oidc/AuthorizationsController.php, lang/.
|
||||
|
||||
<interfaces>
|
||||
From plan 01 (summercms.go/modules/wristband, see 19.4-01-SUMMARY.md): NewOIDCServer, DefaultOIDCOptions, OIDCOptions, SetOIDCBackend(b OIDCBackend, keys KeyStore, host OIDCHost) error, handlers Discovery, JWKS, Authorize, Resume, SwitchAccount, Token, UserInfo, operations ConsentRequest and DecideConsent, OIDCHost{SignedInUser, RenderAuthorizeError, RenderConsent, EndSession}, ConsentView, OIDCBackend/OIDCTx and the record types, KeyStore/SigningKey/PublicKey, GenerateSigningKey, ParsePrivateKeyPEM, ParsePublicKeyPEM, SubjectSector, ErrSectorRequired, IssueOIDCClientCredentials, ClientKindMCP, ClientKindOIDC; MCP: NewServer, SetBackend, Backend/Tx (ClientStore, AuthCodeStore, RefreshTokenStore, AccessTokenIssuer), Metadata, Authorize, Register, Token, PendingRequest, IssueCode, DenyPending.
|
||||
|
||||
Analogs (copy shapes, not names):
|
||||
- ../sm-pgstripe-plugin/{go.mod, go.work, plugin.go, testmain_test.go, models/settings.go (lagoon.Encrypted column with json:"-"), updates/registry.go, updates/202610130001_create_golem15_pgstripe_settings.go}.
|
||||
- ../sm-faq-plugin/{plugin.go Buckets :59-77, routes.go, models/registry.go}; ../sm-chat-plugin/routes.go:28 (jwt.auth + throttle group).
|
||||
- ../sm-userfriends-plugin/{go.work (sm-user-plugin replace to the fonoteka checkout), boot.go:74-89 (Events.Listen on DeletingEvent), harness_test.go (party.Activate + lagoon.Migrate + users), http_tracer_test.go, user_deleting_test.go}.
|
||||
- ../fonoteka.go/plugins/golem15/fonoteka/{plugin.go:143-175 config layering and :255-273 lazyOAuthBackend, routes.go:374-383 GroupRaw for OAuth, classes/auth/oauth_store.go (wristband.Backend over GORM, converters)}.
|
||||
- sm-user-plugin: plugin.go:65-110 (JWTSecret, bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, bl, "token", "auth_token"), published bouncer.BlacklistStore), controllers/api_controller.go Logout (:130-160, bouncer.VerifyClaims + bl.Add) and applyAvatar/gravatarURL (:1247-1297), classes/events.go, classes/admin_actions.go DeactivateUsers (:94-113), controllers/registration.go FireDeletingEvent (:116), controllers/users_admin_controller.go AdminBulkActions (:566-600), classes/user_groups.go UserGroupCodes.
|
||||
- summercms.go: modules/lagoon/encrypted.go (Encrypted, NewEncrypted, Reveal), modules/surf/limiter.go (Bucket, BucketProvider), modules/surf/clientip.go (ClientIP, TrustedProxies), modules/bouncer/cookie.go (LoadCookieConfig, ForgetTokenCookie), modules/bouncer/context.go (User), modules/pact/capabilities.go (Router, HasRoutes).
|
||||
</interfaces>
|
||||
</context>
|
||||
|
||||
<tasks>
|
||||
|
||||
<task type="tracer">
|
||||
<name>Task 1: Tracer: a signed-in user of an application with sm-oauthserver-plugin installed authorizes a relying party at the PHP paths on Postgres, and the relying party verifies the id_token against the database key ring and reads userinfo</name>
|
||||
<reversibility rating="costly">D-01, D-10: the table layout and the encrypted key column are what the Winter import (plan 03) and every installing application migrate into; changing them later means a data migration.</reversibility>
|
||||
<files>../fonoteka.go/plugins/golem15/user/classes/session_user.go, ../fonoteka.go/plugins/golem15/user/README.md, ../sm-oauthserver-plugin/.gitignore, ../sm-oauthserver-plugin/go.mod, ../sm-oauthserver-plugin/go.sum, ../sm-oauthserver-plugin/go.work, ../sm-oauthserver-plugin/README.md, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/servers.go, ../sm-oauthserver-plugin/routes.go, ../sm-oauthserver-plugin/config/config.yaml, ../sm-oauthserver-plugin/lang/en/lang.yaml, ../sm-oauthserver-plugin/lang/pl/lang.yaml, ../sm-oauthserver-plugin/models/registry.go, ../sm-oauthserver-plugin/models/client.go, ../sm-oauthserver-plugin/models/auth_request.go, ../sm-oauthserver-plugin/models/auth_code.go, ../sm-oauthserver-plugin/models/access_token.go, ../sm-oauthserver-plugin/models/refresh_token.go, ../sm-oauthserver-plugin/models/consent.go, ../sm-oauthserver-plugin/models/subject.go, ../sm-oauthserver-plugin/models/signing_key.go, ../sm-oauthserver-plugin/updates/registry.go, ../sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go, ../sm-oauthserver-plugin/classes/lazy.go, ../sm-oauthserver-plugin/classes/oidc_store.go, ../sm-oauthserver-plugin/classes/keyring.go, ../sm-oauthserver-plugin/classes/claims.go, ../sm-oauthserver-plugin/classes/host.go, ../sm-oauthserver-plugin/views/consent.html.tmpl, ../sm-oauthserver-plugin/views/error.html.tmpl, ../sm-oauthserver-plugin/testmain_test.go, ../sm-oauthserver-plugin/harness_test.go, ../sm-oauthserver-plugin/oidc_flow_smoke_test.go</files>
|
||||
<read_first>.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-SUMMARY.md, modules/wristband/oidc_options.go, modules/wristband/oidc_stores.go, modules/wristband/oidc_keys.go (plan 01), 19.4-PATTERNS.md (plugin rows, store adapter, migration, testmain), 19.4-RESEARCH.md (Pattern 3, Pattern 4, Pattern 5, Pitfalls 6, 7, 10), ../sm-pgstripe-plugin/go.mod, ../sm-pgstripe-plugin/plugin.go, ../sm-pgstripe-plugin/testmain_test.go, ../sm-pgstripe-plugin/updates/registry.go, ../sm-pgstripe-plugin/models/settings.go, ../sm-userfriends-plugin/go.work, ../sm-userfriends-plugin/harness_test.go, ../sm-userfriends-plugin/http_tracer_test.go, ../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go, ../fonoteka.go/plugins/golem15/fonoteka/plugin.go (:143-175, :255-273), ../fonoteka.go/plugins/golem15/user/plugin.go, ../fonoteka.go/plugins/golem15/user/controllers/api_controller.go (Logout :130-160), ../fonoteka.go/plugins/golem15/user/classes/user_lookup.go, modules/lagoon/encrypted.go, PHP updates/*.php, models/Client.php, classes/KeyRing.php, classes/ClaimBuilder.php, views/consent.htm, views/error.htm</read_first>
|
||||
<action>Per D-01, D-02, D-04, D-05, D-06, D-10, D-12, D-15, D-19.
|
||||
|
||||
sm-user-plugin first. `git -C ../fonoteka.go/plugins/golem15/user fetch origin` and record `git status -sb` (ahead/behind) in the SUMMARY; do not merge, rebase or push. Add classes/session_user.go: `RequestUser(ctx, app, r)` authenticates the request exactly like the plugin's "jwt" guard (JWTSecret, GormUsers, the published bouncer.BlacklistStore when present, cookies token and auth_token, the Authorization bearer header as the guard reads it) and returns the models.User for the principal's id (soft-deleted users are not returned); an anonymous, invalid, expired or blacklisted request returns (nil, nil), and only an infrastructure failure returns an error. `EndRequestSession(ctx, app, w, r)`: when the request carries a valid JWT, verify it with bouncer.VerifyClaims and add its jti to the published BlacklistStore until its expiry (the same call Logout makes); always write `bouncer.LoadCookieConfig(app.Config)`'s ForgetTokenCookie so Domain and Path match the 19.3 cookie; best effort as PHP (a blacklist failure is logged, never shown). README of the user plugin lists both. Commit in the user plugin repository alone (`feat: export RequestUser and EndRequestSession for OAuth providers`). Then `go -C ../fonoteka.go vet ./plugins/golem15/user/... && go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/user/...` must stay green.
|
||||
|
||||
New repository ../sm-oauthserver-plugin (`git init -b master`, `git remote add origin git@git.golem15.com:golem15/sm-oauthserver-plugin.git`): go.mod (module git.golem15.com/golem15/sm-oauthserver-plugin, go 1.27.0, requires summercms v0.2.4, sm-user-plugin v0.1.1, gorm, pgx, gormigrate, golang-jwt v5.3.1, testcontainers postgres as in pgstripe; `replace git.golem15.com/golem15/summercms => ../summercms.go`), go.work (use .; replace summercms => ../summercms.go; replace sm-user-plugin => ../fonoteka.go/plugins/golem15/user), .gitignore (go.work.sum, node_modules/).
|
||||
|
||||
Migration 202610190001 (raw SQL, run helper, Rollback drops in reverse order): `golem15_oauthserver_clients` (id serial, name, client_id unique, secret_hash varchar(64) null, redirect_uris text null (JSON array), scopes text null (JSON array), is_active bool default true, is_dev bool default false, kind varchar(8) not null default 'oidc' check in ('mcp','oidc'), subject_type varchar(16) not null default 'public' check in ('public','pairwise'), sector_identifier text null, offline_access bool not null default false, token_endpoint_auth_method varchar(32) not null default 'client_secret_basic', grant_types text null, registration_ip varchar(64) null, consented_at, revoked_at timestamptz null, created_at, updated_at); `_auth_requests`, `_auth_codes`, `_access_tokens`, `_consents` with PHP's columns and PHP's index names (oas_*), timestamptz for times, user_id foreign keys to users(id) ON DELETE CASCADE as PHP; `_subjects` (user_id, sector text not null default '', sub, unique (user_id, sector) and unique sub, FK cascade); `_refresh_tokens` (token_hash unique, client_id, user_id FK cascade, access_token_id null, scopes, collection_ids text null, expires_at, revoked_at, rotated_to_id, offline_access); `_keys` (id serial, kid varchar(64) unique, alg varchar(8) check in ('RS256','ES256'), public_pem text, private_pem text (lagoon.Encrypted ciphertext), active bool not null default false, created_at, retired_at null, and `CREATE UNIQUE INDEX oas_keys_one_active ON golem15_oauthserver_keys (active) WHERE active`). models/*.go: one GORM model per table with TableName, PHP MorphName for Client (Golem15\OAuthServer\Models\Client), JSON-array columns as a scanner/valuer type, `SigningKey.PrivatePEM lagoon.Encrypted` with json:"-" and `Client.SecretHash` with json:"-"; `LangPrefix = "golem15.oauthserver::lang."`.
|
||||
|
||||
classes/oidc_store.go: `Store` over *gorm.DB implementing wristband.OIDCBackend (WithinOIDCTx runs one db.Transaction) and every OIDCTx method with the semantics in plan 01: client reads `WHERE kind = 'oidc'`; ConsumeAuthRequest and ConsumeCode as single UPDATE statements checking RowsAffected == 1; AuthRequestByRequestIDForUpdate with a row lock; SaveConsent upserts one row per (user_id, client_id) merging scopes; SubjectFor inserts the candidate with ON CONFLICT (user_id, sector) DO NOTHING then selects; the four refresh methods over `_refresh_tokens`; not-found returns (nil, nil). IdentityClaims delegates to classes/claims.go (this task: name = trimmed Name else Email, omitted when empty; email and email_verified (bool of IsActivated) only when the email is non-empty and the email scope was granted; groups as sorted unique non-empty codes from sm-user classes.UserGroupCodes for profile; false when the user row is gone or soft-deleted). classes/lazy.go: `LazyStore` resolving *gorm.DB from the app at call time (fonoteka lazyOAuthBackend pattern, fail closed with an error).
|
||||
|
||||
classes/keyring.go: `KeyRing` implements wristband.KeyStore. ActiveSigningKey reads the active row (kid, alg) each call, returns a cached signer for that kid or parses `PrivatePEM.Reveal()` with wristband.ParsePrivateKeyPEM; when no active row exists it generates a key with wristband.GenerateSigningKey(cfg.Algorithm) and inserts it as active inside a transaction; on a unique violation of oas_keys_one_active it re-reads the winner. PublishedKeys returns the active key plus keys whose retired_at is within cfg.Grace of now (parsed from public_pem). `Rotate(ctx) (newKid, previousKid string, retiredAt *time.Time, err error)` generates a new active key and retires the previous one (retired_at now, active false) in one transaction; `Prune(ctx, now) (int, error)` deletes keys retired before now minus the grace and returns the count. Plan 03's commands call both. Errors never contain PEM text.
|
||||
|
||||
classes/host.go: `Host` implements wristband.OIDCHost: SignedInUser through classes.RequestUser; EndSession through classes.EndRequestSession; RenderAuthorizeError and RenderConsent execute the embedded views with html/template (status 400 for errors, 200 for consent, Content-Type text/html; charset=UTF-8), using default branding values in this task (PHP Settings DEFAULTS) and lang strings; the consent page shows the client name, the missing scope labels, the signed-in user's name, a form POSTing request_id, consent_token and decision to /oauth/authorize, and the switch-account form POSTing request_id and consent_token to /oauth/authorize/switch-account. views/*.html.tmpl follow the PHP layout and class names.
|
||||
|
||||
plugin.go and servers.go: PluginID, Requires {"golem15.user"}, ConfigFS, LangFS, Migrations, Models; Boot reads config (issuer from golem15.oauthserver.issuer else app.url, TrimSpace and TrimSuffix "/", TTLs and login_url layered over wristband.DefaultOIDCOptions as fonoteka layers its options), builds the OIDC server with wristband.NewOIDCServer and SetOIDCBackend(LazyStore, KeyRing, Host) (a returned error fails boot), builds the MCP server with wristband.NewServer (backend wired in Task 3), and publishes one `*Servers`. routes.go: GroupRaw (no envelope) groups mirroring PHP's auth models: public (GET /.well-known/openid-configuration, GET /oauth/jwks), server-to-server (POST /oauth/token, GET /oauth/userinfo), browser (GET and POST /oauth/authorize, GET /oauth/authorize/resume/{request}, POST /oauth/authorize/switch-account); throttles arrive in Task 2. config/config.yaml documents every key with its default and SUMMER_GOLEM15__OAUTHSERVER__ variable (keys of later tasks are added by them).
|
||||
|
||||
Tests: testmain_test.go copied from pgstripe (flag.Parse then testing.Short, one postgres:16-alpine container, freshDB per test, names renamed to oauthserver); harness_test.go `bootOAuth(t, overrides...)` modelled on sm-userfriends harness (app key, golem15.user and golem15.oauthserver activated, lagoon.Migrate, a helper creating a user and a session JWT through sm-user's controllers.IssueToken, a helper creating an OIDC client row with wristband.IssueOIDCClientCredentials returning the plaintext secret, an httptest server from surf's router). oidc_flow_smoke_test.go `TestOIDCFlowSmoke` (skips under -short): discovery from the issuer, GET /oauth/authorize with the token cookie (302 to the resume path), GET resume (200 HTML, parse the hidden consent_token), POST allow (302 with code and state), POST /oauth/token with client_secret_basic, verify the id_token with golang-jwt against keys built from GET /oauth/jwks, GET /oauth/userinfo returning the same sub, and a key row exists with active true and a private_pem column that does not start with -----BEGIN. `TestKeyRingFirstKeyRaceSmoke`: eight goroutines calling ActiveSigningKey on an empty ring end with exactly one active row and one kid. README.md in the standard plugin structure (pgstripe README): summary, plugin ID, Overview, Features, Installation, Configuration (every key, default, SUMMER_ variable, PHP env name), Routes, Security notes (app.key rotation must keep app.previous_keys or the ring becomes unreadable), Testing.</action>
|
||||
<verify>
|
||||
<automated>go -C ../fonoteka.go vet ./plugins/golem15/user/... && go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/user/... && go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestOIDCFlowSmoke|TestKeyRingFirstKeyRaceSmoke)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 2</automated>
|
||||
<fails_when>Non-zero exit: sm-user-plugin vet or tests red (an additive change broke it), the plugin does not vet or its short suite fails, or fewer than two "--- PASS" lines for the Postgres flow and key-race smokes (Docker unavailable or a broken flow).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `git -C ../sm-oauthserver-plugin rev-list --count HEAD` prints at least 1 and `git -C ../sm-oauthserver-plugin remote get-url origin` prints git@git.golem15.com:golem15/sm-oauthserver-plugin.git.
|
||||
- `U=$(git -C ../fonoteka.go/plugins/golem15/user log -1 --format=%ct -- classes/session_user.go) && R=$(git -C ../sm-oauthserver-plugin rev-list --max-parents=0 HEAD) && P=$(git -C ../sm-oauthserver-plugin show -s --format=%ct "$R") && test -n "$U" && test "$U" -le "$P"` exits 0 (user plugin committed before the plugin's first commit).
|
||||
- `grep -c 'WHERE active' ../sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go` prints at least 1.
|
||||
- `grep -n 'lagoon.Encrypted' ../sm-oauthserver-plugin/models/signing_key.go | grep -c 'json:"-"'` prints 1.
|
||||
- `grep -c "kind = 'oidc'\|kind = ?" ../sm-oauthserver-plugin/classes/oidc_store.go` prints at least 1.
|
||||
- `grep -rc 'AutoMigrate' ../sm-oauthserver-plugin --include='*.go' | grep -v ':0' | grep -v '_test.go'` prints nothing.
|
||||
- `grep -rniE 'wavepath|plytarium|płytarium|fonoteka' ../sm-oauthserver-plugin --include='*.go' --include='*.md' --include='*.yaml' --include='*.tmpl'` prints nothing (go.work's replace path is the only allowed mention and is not matched by these globs).
|
||||
</acceptance_criteria>
|
||||
<done>An application that installs the plugin signs a user in to a relying party with a database-backed, encrypted RS256 key, at the PHP paths, end to end on Postgres.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 2: Users see branded consent and error pages, anonymous users go through the login handoff, switching account works, the SPA consent mode is available, claims match PHP, and the PHP throttles hold</name>
|
||||
<files>../fonoteka.go/plugins/golem15/user/classes/avatar.go, ../fonoteka.go/plugins/golem15/user/controllers/api_controller.go, ../fonoteka.go/plugins/golem15/user/README.md, ../sm-oauthserver-plugin/updates/202610190002_create_golem15_oauthserver_settings.go, ../sm-oauthserver-plugin/models/settings.go, ../sm-oauthserver-plugin/models/registry.go, ../sm-oauthserver-plugin/classes/branding.go, ../sm-oauthserver-plugin/classes/host.go, ../sm-oauthserver-plugin/classes/claims.go, ../sm-oauthserver-plugin/controllers/consent_api.go, ../sm-oauthserver-plugin/views/consent.html.tmpl, ../sm-oauthserver-plugin/views/error.html.tmpl, ../sm-oauthserver-plugin/buckets.go, ../sm-oauthserver-plugin/routes.go, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/config/config.yaml, ../sm-oauthserver-plugin/lang/en/lang.yaml, ../sm-oauthserver-plugin/lang/pl/lang.yaml, ../sm-oauthserver-plugin/pages_smoke_test.go, ../sm-oauthserver-plugin/README.md</files>
|
||||
<read_first>../sm-oauthserver-plugin/classes/host.go, classes/claims.go, routes.go, plugin.go (Task 1), PHP models/Settings.php (DEFAULTS, DANGER_COLOR, MAX_CUSTOM_CSS, branding(), brandingCss() and the sanitisers :96-300), models/settings/fields.yaml, views/consent.htm, views/error.htm, classes/ScopeCatalog.php, classes/ClaimBuilder.php, routes.php (header comment, throttle definitions), lang/en, lang/pl, tests/security/ConsentCsrfTest.php, tests/security/RouteGuardTest.php, tests/unit/ClaimBuilderTest.php, 19.4-RESEARCH.md (Pattern 2 Routes, Identity claims, Rendered pages; Pattern 6; Pitfalls 11, 12), ../sm-faq-plugin/plugin.go (Buckets :59-77), ../sm-chat-plugin/routes.go, ../fonoteka.go/plugins/golem15/user/controllers/api_controller.go (applyAvatar, gravatarURL :1247-1297), ../sm-userfriends-plugin/models/group.go and models/group_member.go</read_first>
|
||||
<action>Per D-03, D-04, D-05, D-15, D-18.
|
||||
|
||||
sm-user-plugin (additive, own commit first): classes/avatar.go `AvatarURL(ctx, app, user, size)` returns the user's avatar file thumbnail URL (size by size, mode auto) when an avatar attachment exists, else the gravatar URL `//www.gravatar.com/avatar/{md5}?s={size}&d=mm` (the logic of applyAvatar and gravatarURL); applyAvatar in controllers/api_controller.go calls it so its payload stays byte-identical (avatar_url, has_avatar, avatar keys unchanged; the existing avatar tests stay green). README row. Commit in the user plugin repository.
|
||||
|
||||
Branding (D-03): migration 202610190002 creates `golem15_oauthserver_settings` (id integer primary key, site_name, page_background, surface_color, text_color, muted_text_color, border_color, accent_color, accent_text_color, font_css_url, font_family, custom_css, created_at, updated_at) and inserts row 1 with the PHP DEFAULTS; models.Settings with Fillable and Rules (colour fields validated by the sanitiser rules, custom_css max 20000) and an attachOne `logo` relation (MorphName Golem15\OAuthServer\Models\Settings). classes/branding.go ports Settings::branding and brandingCss: SanitizeColor (hex 3 to 8 digits or a 3-24 letter name, else the default), SanitizeFontFamily (letters, digits, space, comma, quotes, dot, underscore, dash, 1-200 characters, else the default), SanitizeCSSURL (https only, else empty), SanitizeCustomCSS (removes every < that starts a tag, capped at MaxCustomCSS = 20000), DangerColor #B91C1C for the error heading, LoadBranding reading row 1 and the logo URL; the CSS block is built from sanitised values only and passed to the template as template.CSS after sanitising. Views: the full PHP layout, copy and scope labels from lang (en, pl ported from PHP lang files and ScopeCatalog), client logo (attachOne logo on Client, MorphName Golem15\OAuthServer\Models\Client) or the initial, the user's picture, the reassurance line, the switch-account form; every value escaped by html/template; the error page for unknown_client, redirect_mismatch, inactive_client and expired_request.
|
||||
|
||||
Consent mode: when golem15.oauthserver.consent_mode is redirect (boot fails when consent_url is empty), Host.RenderConsent answers 302 to consent_url with ?request={id} (or &request= when the URL has a query) through the same headers; controllers/consent_api.go `ConsentShow` (GET /oauth/authorize/requests/{request}) and `ConsentDecide` (POST, JSON body {consent_token, decision}) call the OIDC server's ConsentRequest and DecideConsent with the jwt.auth user; ErrAuthRequestExpired answers 410 {"error":"expired_request"}; success answers the shapes in this plan's Decisions. In page mode these routes are not mounted.
|
||||
|
||||
Claims (D-05) completed in classes/claims.go: picture for profile from sm-user classes.AvatarURL with picture_size, made absolute (`//x` becomes `https://x`, a relative path is joined to app.url), omitted when empty; communities for profile: when both golem15_userfriends tables exist, read-only SQL for the user's memberships in groups with deleted_at null as [{id, name, role}] sorted by name then id, else []; groups always present for profile (sorted unique non-empty codes); the claim set never leaves the allowlist.
|
||||
|
||||
Throttles (D-18) in buckets.go (`Buckets()` on the plugin, trusted proxies from surf.TrustedProxies(app.Config)): `oauth-authorize` 30 per minute keyed "oauth-authorize:" + the user id from the token cookie verified with bouncer.VerifyClaims and the sm-user JWT secret (no DB lookup) else "oauth-authorize-ip:" + client IP; `oauth-token` 20 per minute keyed "oac:" + r.FormValue("client_id") else "oac-ip:" + IP (comment: PHP reads the input only, so Basic clients share the IP bucket, D-18 same keys); `oauth-userinfo` 60 per minute keyed "oau:" + SHA-256 hex of the bearer else "oau-ip:" + IP; `oauth-authorizations` 120 per minute keyed by user else IP. routes.go attaches throttle:oauth-authorize to the browser group and the consent JSON routes, throttle:oauth-token plus body.limit from token_body_limit to POST /oauth/token, throttle:oauth-userinfo to userinfo; discovery and JWKS carry none.
|
||||
|
||||
Smoke tests in pages_smoke_test.go (Postgres, skip under -short): `TestConsentPageBrandingSmoke` (settings row with a custom accent colour and site name appear in the rendered page; a colour value carrying markup or a closing style tag cannot leave the style block; a client named with a script tag is escaped; X-Frame-Options DENY and frame-ancestors 'none'), `TestLoginHandoffAndSwitchSmoke` (no cookie: 302 to /login?redirect=%2Foauth%2Fauthorize%2Fresume%2F{id} only; switch-account: the old jti is blacklisted, the response forgets the token cookie and redirects to the resume path; the request still resumes for another signed-in user; consent_mode redirect sends the browser to consent_url and the JSON endpoints complete the flow), `TestBucketKeysSmoke` (the four key functions produce the documented prefixes, the userinfo key never contains the bearer), `TestRouteGuardSmoke` (with test routes GET /oauth/{provider} and GET /oauth/{provider}/callback registered by a fixture plugin, every OIDC path still reaches the oauthserver handlers, and /oauth/google still reaches the fixture). README: configuration keys consent_mode, consent_url, token_body_limit, the bucket table, the branding description. Add `<human-check>` below for the visual comparison.</action>
|
||||
<verify>
|
||||
<automated>go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/user/... && go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestConsentPageBrandingSmoke|TestLoginHandoffAndSwitchSmoke|TestBucketKeysSmoke|TestRouteGuardSmoke|TestOIDCFlowSmoke)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 5</automated>
|
||||
<fails_when>Non-zero exit: the user plugin's tests red (applyAvatar output changed), the plugin fails vet or its short suite, or fewer than five "--- PASS" lines for the page, handoff, bucket, route-guard and flow smokes.</fails_when>
|
||||
<human-check>With the plugin running in a local application (or the test harness server kept alive), set a site name, a logo and an accent colour in row 1 of golem15_oauthserver_settings, open an authorize URL for a test client and compare the consent page and the inactive-client error page side by side with the PHP pages in a browser: same structure and copy, branding applied, error heading in the fixed danger colour.</human-check>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c 'oac:\|oac-ip:\|oau:\|oau-ip:' ../sm-oauthserver-plugin/buckets.go` prints at least 4.
|
||||
- `grep -n 'template.CSS' ../sm-oauthserver-plugin/classes/branding.go ../sm-oauthserver-plugin/classes/host.go | wc -l` prints at least 1 and `grep -n 'MaxCustomCSS = 20000' ../sm-oauthserver-plugin/classes/branding.go` prints one line.
|
||||
- `grep -n 'throttle:oauth-token' ../sm-oauthserver-plugin/routes.go | grep -c 'body.limit'` prints 1.
|
||||
- `grep -n '"/.well-known/openid-configuration"' ../sm-oauthserver-plugin/routes.go | grep -c throttle` prints 0.
|
||||
- `go -C ../fonoteka.go test -count=1 -run 'Avatar' ./plugins/golem15/user/...` exits 0.
|
||||
</acceptance_criteria>
|
||||
<done>The provider's pages look like the application's, anonymous and switching users move through login exactly as in PHP, an SPA can own consent instead, claims carry the same data as PHP, and the PHP rate limits apply per instance group through the shared store.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 3: Users list and revoke their authorized apps, deleting or deactivating a user removes their grants, and an application can serve MCP clients from the same stores behind a switch</name>
|
||||
<files>../fonoteka.go/plugins/golem15/user/classes/events.go, ../fonoteka.go/plugins/golem15/user/controllers/registration.go, ../fonoteka.go/plugins/golem15/user/controllers/users_admin_controller.go, ../fonoteka.go/plugins/golem15/user/README.md, ../sm-oauthserver-plugin/controllers/authorizations.go, ../sm-oauthserver-plugin/classes/cascade.go, ../sm-oauthserver-plugin/classes/mcp_store.go, ../sm-oauthserver-plugin/classes/lazy.go, ../sm-oauthserver-plugin/models/mcp_code.go, ../sm-oauthserver-plugin/models/registry.go, ../sm-oauthserver-plugin/updates/202610190003_create_golem15_oauthserver_mcp_codes.go, ../sm-oauthserver-plugin/routes.go, ../sm-oauthserver-plugin/buckets.go, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/config/config.yaml, ../sm-oauthserver-plugin/authorizations_smoke_test.go, ../sm-oauthserver-plugin/mcp_store_smoke_test.go, ../sm-oauthserver-plugin/README.md</files>
|
||||
<read_first>PHP controllers/oidc/AuthorizationsController.php, classes/UserCascade.php, routes.php (authorizations group, OPTIONS), tests/feature/RevokeAuthorizationTest.php, tests/security/UserDeleteCascadeTest.php, ../sm-userfriends-plugin/boot.go (:74-89), ../sm-userfriends-plugin/user_deleting_test.go, ../fonoteka.go/plugins/golem15/user/classes/events.go, controllers/registration.go (FireDeletingEvent :116), controllers/users_admin_controller.go (AdminBulkActions :566-600), classes/admin_actions.go (DeactivateUsers :94-113), ../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go (wristband.Tx over GORM: converters, CreateWithCap, MarkIssued, RevokeLineage), modules/wristband/stores.go, ../sm-chat-plugin/routes.go:28, modules/surf README (cors:{profile})</read_first>
|
||||
<action>Per D-02, D-05, D-06, D-08, SC-3.
|
||||
|
||||
sm-user-plugin (additive, own commit first): classes/events.go adds `DeactivatingEventName = "user.Deactivating"` and `DeactivatingEvent{User *models.User; Tx *gorm.DB}` (doc: fires after a soft delete inside the same transaction); controllers/registration.go adds `FireDeactivatingEvent(ctx, app, user, tx) error` modelled on FireDeletingEvent; users_admin_controller.go's deactivate bulk action wraps classes.DeactivateUsers: it remembers which selected users were not deactivated yet, calls DeactivateUsers unchanged, then fires the event for each of them with the action's transaction (an error rolls the action back). DeactivateUsers' signature does not change. README row. Commit in the user plugin repository; its tests and `go -C ../fonoteka.go vet ./plugins/golem15/user/...` stay green.
|
||||
|
||||
Cascade (classes/cascade.go, registered in Boot with app.Events.Listen as sm-userfriends does): `OnUserDeleting` deletes, in ev.Tx, the user's access tokens, refresh tokens, auth codes, MCP codes, consents and subjects; `OnUserDeactivating` deletes the same except subjects (PHP UserCascade: a soft delete keeps the sub stable across a restore). Other users' rows are untouched.
|
||||
|
||||
Authorizations (SC-3) in controllers/authorizations.go behind `jwt.auth` and throttle:oauth-authorizations, plus `cors:{profile}` when golem15.oauthserver.cors_profile is set: `AuthorizationsIndex` answers {"authorizations":[{client_id, name, logo_url, scopes, first_authorized_at, last_used_at}]} for the bouncer.User principal, newest consent first, rows whose client no longer exists skipped, times ISO 8601 with offset as PHP's toIso8601String, last_used_at null when never used, logo_url null without a logo; `AuthorizationsDestroy` (DELETE /oauth/authorizations/{client_id}) runs one transaction that locks the caller's consent row for that client (none gives 404 {"error":"not_found"}), deletes it and the pair's auth codes, access tokens and refresh tokens, and answers {"revoked":true}.
|
||||
|
||||
MCP stores (D-02, D-06, D-08): migration 202610190003 creates `golem15_oauthserver_mcp_codes` (the wristband.AuthCodeRecord columns: request_id unique null, code_hash unique null, client_id, user_id null FK cascade, redirect_uri, scopes, collection_ids, code_challenge, code_challenge_method, resource, state, expires_at, used_at, offline_access); classes/mcp_store.go `MCPStore` implements wristband.Backend and wristband.Tx in the shape of fonoteka's adapter: clients filtered `kind = 'mcp'` and created with kind mcp, CreateWithCap counting unrevoked mcp clients in the same transaction, SweepUnconsented and MarkConsented, the AuthCodeStore over mcp_codes, the RefreshTokenStore over refresh_tokens, and AccessTokenIssuer minting `oas_at_` + base64url of 32 random bytes into access_tokens (hashed, client id stamped; collection ids accepted and ignored). `LazyMCPStore` in lazy.go. Boot calls the MCP server's SetBackend(LazyMCPStore) and reads mcp.* options (resource from golem15.oauthserver.mcp.resource). routes.go mounts GET /.well-known/oauth-authorization-server, GET /oauth/mcp/authorize, POST /oauth/mcp/register (throttle:oauth-mcp-register, 10 per minute per IP) and POST /oauth/mcp/token (throttle:oauth-mcp-token, 20 per minute per client_id else IP) only when golem15.oauthserver.mcp.enabled is true. README: the MCP switch is off by default, an application that already serves its own MCP authorization server must leave it off (the paths would collide at boot), the MCP consent page is the host's (wristband's PendingRequest/IssueCode/DenyPending) and MCP access-token verification arrives with the MCP module (Phase 19.7).
|
||||
|
||||
Smoke tests (Postgres, skip under -short): authorizations_smoke_test.go `TestAuthorizationsSmoke` (list shape and order; revoke returns revoked true and the old access token answers 401 at userinfo and the next authorize shows consent again; another user's client_id and an unknown one give 404 and leave rows intact; unauthenticated list gives the jwt.auth 401) and `TestUserCascadeSmoke` (firing DeletingEvent removes every row including the subject; firing DeactivatingEvent through the bulk action path keeps the subject and removes the rest; another user's rows survive); mcp_store_smoke_test.go `TestMCPStoreSmoke` (with mcp.enabled: register a client over HTTP, authorize to a pending row, IssueCode through the server's Go method, exchange at /oauth/mcp/token, rotate the refresh token, replay the old one and see the lineage revoked; the registered client is kind mcp and gets unknown_client at /oauth/authorize; with mcp.enabled false the four MCP paths answer 404).</action>
|
||||
<verify>
|
||||
<automated>go -C ../fonoteka.go vet ./... ./plugins/golem15/fonoteka/... ./plugins/golem15/user/... && go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/user/... && go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestAuthorizationsSmoke|TestUserCascadeSmoke|TestMCPStoreSmoke)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 3</automated>
|
||||
<fails_when>Non-zero exit: fonoteka or the user plugin fails vet or tests (an sm-user change was not additive), the plugin fails vet or its short suite, or fewer than three "--- PASS" lines for the authorizations, cascade and MCP smokes.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `D=$(git -C ../fonoteka.go/plugins/golem15/user diff c077029 -- classes/admin_actions.go) && printf '%s\n' "$D" | grep -c '^[-+]func DeactivateUsers'` prints 0 (signature unchanged since the phase's starting commit of the user plugin).
|
||||
- `grep -n 'DeactivatingEventName = "user.Deactivating"' ../fonoteka.go/plugins/golem15/user/classes/events.go` prints one line.
|
||||
- `grep -c '{"error":"not_found"}\|"not_found"' ../sm-oauthserver-plugin/controllers/authorizations.go` prints at least 1.
|
||||
- `grep -n 'mcp.enabled' ../sm-oauthserver-plugin/routes.go ../sm-oauthserver-plugin/plugin.go | wc -l` prints at least 1 and `grep -n 'enabled: false' ../sm-oauthserver-plugin/config/config.yaml | wc -l` prints at least 1.
|
||||
- `grep -c "kind = 'mcp'\|kind = ?" ../sm-oauthserver-plugin/classes/mcp_store.go` prints at least 1.
|
||||
</acceptance_criteria>
|
||||
<done>A user manages the apps they authorized, a deleted or deactivated user leaves no live grant behind, and an application can switch on MCP sign-in from the same plugin.</done>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-verify" gate="blocking-human">
|
||||
<name>Task 4: Package legitimacy check before installing github.com/coreos/go-oidc/v3 v3.21.0 and golang.org/x/oauth2 v0.37.0 (test-only, plugin repository)</name>
|
||||
<read_first>.planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md (Related dependencies), 19.4-RESEARCH.md (Package Legitimacy Audit, Supporting stack, assumption A3)</read_first>
|
||||
<acceptance_criteria>
|
||||
- The SUMMARY records the human's reply verbatim ("approved" or "hand-rolled-rp") before any go.mod change in Task 5.
|
||||
- Until the reply, `grep -cE 'coreos/go-oidc|golang.org/x/oauth2' ../sm-oauthserver-plugin/go.mod` prints 0.
|
||||
</acceptance_criteria>
|
||||
<what-built>Nothing installed yet. Tasks 1-3 are committed and green on Postgres with a golang-jwt based relying party in the smokes. RESEARCH verified both modules on proxy.golang.org (go-oidc v3.21.0 published 2026-09-01, origin github.com/coreos/go-oidc, requires go-jose v4.1.4 and x/oauth2 v0.36.0; x/oauth2 v0.37.0 published 2026-08-25, origin go.googlesource.com/oauth2) but the package seam cannot check Go modules, so they carry [ASSUMED]. The decision note names them as test-only modules of this plugin repository; the framework go.mod is not touched. Never auto-approved.</what-built>
|
||||
<how-to-verify>
|
||||
1. Open https://pkg.go.dev/github.com/coreos/go-oidc/v3 and https://github.com/coreos/go-oidc: confirm the repository, the maintainers, the Apache-2.0 licence and that v3.21.0 is a tagged release.
|
||||
2. Open https://pkg.go.dev/golang.org/x/oauth2: confirm it is the Go project's module and v0.37.0 is published.
|
||||
3. In a scratch directory run `go list -m -json github.com/coreos/go-oidc/v3@v3.21.0 golang.org/x/oauth2@v0.37.0` and confirm Origin.URL for each.
|
||||
4. Confirm both are acceptable as test-only requirements of ../sm-oauthserver-plugin (they land in its go.mod and go.sum; no production file imports them).
|
||||
</how-to-verify>
|
||||
<resume-signal>Reply "approved" to install both in Task 5, or "hand-rolled-rp" to keep the relying party in tests on golang-jwt and the standard library only (Task 5 then writes the interop test without go-oidc and records the deviation from D-16's "real RP library" in the SUMMARY for the user).</resume-signal>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 5: A stock relying-party library signs in against the plugin with an RS256 ring and with an ES256 ring (D-16 interop)</name>
|
||||
<files>../sm-oauthserver-plugin/go.mod, ../sm-oauthserver-plugin/go.sum, ../sm-oauthserver-plugin/interop_test.go, ../sm-oauthserver-plugin/README.md</files>
|
||||
<read_first>../sm-oauthserver-plugin/harness_test.go and oidc_flow_smoke_test.go (Tasks 1-3), 19.4-RESEARCH.md (Code Examples "Interop tracer"), PHP tests/feature/JumbojettInteropTest.php, tests/fixtures/JumbojettTestClient.php, go doc github.com/coreos/go-oidc/v3/oidc (after install), go doc golang.org/x/oauth2</read_first>
|
||||
<action>Per D-16, SC-2. With "approved": `go -C ../sm-oauthserver-plugin get github.com/coreos/go-oidc/v3@v3.21.0 golang.org/x/oauth2@v0.37.0` and tidy; only interop_test.go imports them. `TestRelyingPartyInterop` (Postgres, skips under -short) with subtests RS256 and ES256 (a fresh database each, key_algorithm set accordingly): oidc.ClientContext with the httptest client, oidc.NewProvider at the issuer (discovery fetched, issuer equal), an oauth2.Config from provider.Endpoint() with scopes openid, profile and email, a verifier from oauth2.GenerateVerifier, AuthCodeURL with oauth2.S256ChallengeOption and oidc.Nonce; drive authorize, resume and consent with the user's token cookie through the test's own client; Exchange with oauth2.VerifierOption (x/oauth2 sends client_secret_basic with query-escaped halves, which the engine must decode); provider.Verifier(&oidc.Config{ClientID}).Verify the id_token; assert the nonce explicitly (Verify does not), idToken.VerifyAccessToken on the access token (at_hash), the header alg equals the subtest's algorithm, provider.UserInfo returns the same Subject, and a second run for the same user is silent (no consent page). With "hand-rolled-rp": the same test drives the flow with net/http, verifies with golang-jwt and checks at_hash by hand, and the SUMMARY records the deviation. README Testing names the interop test and its test-only dependencies.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^TestRelyingPartyInterop$' -v ./... 2>&1 | grep -c -- '--- PASS: TestRelyingPartyInterop' | grep -qx 3</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red, or fewer than three PASS lines for TestRelyingPartyInterop and its RS256 and ES256 subtests (Docker unavailable, or the library rejected a token, the at_hash or the discovery document).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- With "approved": `grep -n 'github.com/coreos/go-oidc/v3 v3.21.0' ../sm-oauthserver-plugin/go.mod` and `grep -n 'golang.org/x/oauth2 v0.37.0' ../sm-oauthserver-plugin/go.mod` each print one line, and `grep -rln 'coreos/go-oidc' ../sm-oauthserver-plugin --include='*.go' | grep -v '_test.go'` prints nothing.
|
||||
- `grep -cE 'coreos/go-oidc|golang.org/x/oauth2' go.mod` in summercms.go prints 0.
|
||||
- `grep -c 'TestRelyingPartyInterop' ../sm-oauthserver-plugin/README.md` prints at least 1.
|
||||
</acceptance_criteria>
|
||||
<done>A relying party built on a maintained OIDC library signs users in against the plugin and verifies everything it receives, with either key algorithm.</done>
|
||||
</task>
|
||||
|
||||
</tasks>
|
||||
|
||||
<threat_model>
|
||||
## Trust Boundaries
|
||||
|
||||
| Boundary | Description |
|
||||
|----------|-------------|
|
||||
| browser to /oauth/authorize* and the consent JSON routes | session cookie, untrusted form and query input, cross-site requests |
|
||||
| SPA to /oauth/authorizations | JWT bearer or cookie, client_id path parameter chosen by the caller |
|
||||
| plugin to Postgres | encrypted private keys, hashed secrets and tokens, user-linked grant rows |
|
||||
| plugin to sm-user-plugin | user identity, session revocation, deletion events |
|
||||
| administrator-controlled branding to every visitor's browser | colours, fonts, CSS and logos rendered into the consent and error pages |
|
||||
|
||||
## STRIDE Threat Register
|
||||
|
||||
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|
||||
|-----------|----------|-----------|----------|-------------|-----------------|
|
||||
| T-19.4-15 | Information disclosure | models.SigningKey, classes.KeyRing | high | mitigate | private PEM stored as lagoon.Encrypted (AES-256-GCM, app key), json:"-", read only through Reveal inside the key ring, never in a cabana form, a log or an error string; README documents app.previous_keys for app.key rotation |
|
||||
| T-19.4-16 | Denial of service | KeyRing lazy first key across instances | medium | mitigate | partial unique index oas_keys_one_active, generation in a transaction, a unique violation re-reads the winner; TestKeyRingFirstKeyRaceSmoke |
|
||||
| T-19.4-17 | Tampering | consent and error pages (clickjacking) | medium | mitigate | the engine sets X-Frame-Options DENY, frame-ancestors 'none', no-store and no-referrer before the plugin renders; TestConsentPageBrandingSmoke asserts them |
|
||||
| T-19.4-18 | Tampering | branding CSS and client names in HTML | high | mitigate | html/template escaping everywhere; colours, font family, font URL (https only) and custom CSS pass ported PHP sanitisers before becoming template.CSS; custom CSS capped at 20000 and stripped of tag openers; danger colour fixed |
|
||||
| T-19.4-19 | Elevation of privilege | AuthorizationsDestroy | high | mitigate | consent row selected FOR UPDATE by the jwt.auth principal and the path client_id; another user's or an unknown client gives 404 and touches nothing; TestAuthorizationsSmoke |
|
||||
| T-19.4-20 | Denial of service | token, userinfo, authorize, authorizations | medium | mitigate | D-18 buckets on the shared surf store, body.limit on the token route; discovery and JWKS stay cacheable |
|
||||
| T-19.4-21 | Information disclosure | rate-limit keys | low | mitigate | the userinfo key uses SHA-256 of the bearer, never the bearer; TestBucketKeysSmoke |
|
||||
| T-19.4-22 | Spoofing | switch-account and stale sessions | medium | mitigate | EndRequestSession blacklists the JWT's jti until expiry and forgets the cookie with the 19.3 Domain and Path; the consent token is burned; the parked request carries no user |
|
||||
| T-19.4-23 | Information disclosure | grants of deleted or deactivated users | medium | mitigate | listeners on user.Deleting and the new user.Deactivating remove tokens, codes, consents (and subjects on hard delete) inside the user change's transaction; soft-deleted users are not returned by RequestUser or IdentityClaims |
|
||||
| T-19.4-24 | Elevation of privilege | MCP routes and dynamic registration | medium | mitigate | MCP routes mounted only with mcp.enabled (default false); DCR creates kind mcp clients that the OIDC flow refuses (plan 01 kind isolation, TestMCPStoreSmoke) |
|
||||
| T-19.4-25 | Spoofing | route shadowing under /oauth/ | low | mitigate | literal OIDC paths; TestRouteGuardSmoke registers /oauth/{provider} routes and proves both directions |
|
||||
| T-19.4-26 | Tampering | sm-user-plugin changes for five consuming applications | medium | mitigate | additive exports and a new event only; DeactivateUsers signature unchanged; the user plugin's suite and fonoteka vet in the verify commands; other apps pin older commits and are unaffected until they bump |
|
||||
| T-19.4-SC | Tampering | Go module installs (go-oidc v3.21.0, x/oauth2 v0.37.0) | high | mitigate | blocking human package check in Task 4 before any go.mod change; test-only in the plugin repository; framework go.mod untouched; versions pinned |
|
||||
</threat_model>
|
||||
|
||||
<verification>
|
||||
- Task 1: sm-user-plugin green; plugin vet and short suite; TestOIDCFlowSmoke and TestKeyRingFirstKeyRaceSmoke on Postgres.
|
||||
- Task 2: page, handoff, bucket and route-guard smokes; applyAvatar output unchanged; human-check of the pages against PHP (end of phase).
|
||||
- Task 3: authorizations, cascade and MCP smokes; fonoteka and the user plugin vet and test.
|
||||
- Task 5: TestRelyingPartyInterop with RS256 and ES256 subtests.
|
||||
- Feedback sampling: after each commit `go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -short ./...`.
|
||||
</verification>
|
||||
|
||||
<success_criteria>
|
||||
- SC-2: a stock relying party verifies id_tokens signed by the database key ring with RS256 and ES256.
|
||||
- SC-3 (plugin): resume, switch account, the consent list and revocation, public and pairwise subjects work at the PHP paths.
|
||||
- D-02, D-06: the stores serve OIDC and MCP; the MCP routes stay off unless enabled.
|
||||
- D-05: sm-user-plugin changes are additive and committed first; its consumers still build.
|
||||
</success_criteria>
|
||||
|
||||
<output>
|
||||
Create `.planning/phases/19.4-oidc-provider-on-wristband/19.4-02-SUMMARY.md` when done, with the commits per repository in order (user plugin first), the sm-user-plugin ahead/behind state, the human's legitimacy reply verbatim, which Docker-backed tests ran or were NOT RUN, the human-check item for the end-of-phase UAT, and any deviation from this plan's names.
|
||||
</output>
|
||||
385
.planning/phases/19.4-oidc-provider-on-wristband/19.4-03-PLAN.md
Normal file
385
.planning/phases/19.4-oidc-provider-on-wristband/19.4-03-PLAN.md
Normal file
@@ -0,0 +1,385 @@
|
||||
---
|
||||
phase: 19.4-oidc-provider-on-wristband
|
||||
plan: 03
|
||||
type: execute
|
||||
wave: 3
|
||||
depends_on: ["19.4-02"]
|
||||
files_modified:
|
||||
- ../sm-oauthserver-plugin/console/helpers.go
|
||||
- ../sm-oauthserver-plugin/console/import_winter.go
|
||||
- ../sm-oauthserver-plugin/console/import_keys.go
|
||||
- ../sm-oauthserver-plugin/console/import_settings.go
|
||||
- ../sm-oauthserver-plugin/console/rotate_keys.go
|
||||
- ../sm-oauthserver-plugin/console/prune.go
|
||||
- ../sm-oauthserver-plugin/scripts/winter-export.sql
|
||||
- ../sm-oauthserver-plugin/schedule.go
|
||||
- ../sm-oauthserver-plugin/plugin.go
|
||||
- ../sm-oauthserver-plugin/admin.go
|
||||
- ../sm-oauthserver-plugin/admin_permissions.go
|
||||
- ../sm-oauthserver-plugin/admin_navigation.go
|
||||
- ../sm-oauthserver-plugin/controllers/admin_registry.go
|
||||
- ../sm-oauthserver-plugin/controllers/clients.go
|
||||
- ../sm-oauthserver-plugin/controllers/branding.go
|
||||
- ../sm-oauthserver-plugin/controllers/clients/config_list.yaml
|
||||
- ../sm-oauthserver-plugin/controllers/clients/config_form.yaml
|
||||
- ../sm-oauthserver-plugin/controllers/clients/_secret_reveal.htm
|
||||
- ../sm-oauthserver-plugin/controllers/clients/_authorizations.htm
|
||||
- ../sm-oauthserver-plugin/controllers/branding/config_form.yaml
|
||||
- ../sm-oauthserver-plugin/models/client.go
|
||||
- ../sm-oauthserver-plugin/models/settings.go
|
||||
- ../sm-oauthserver-plugin/models/client/columns.yaml
|
||||
- ../sm-oauthserver-plugin/models/client/fields.yaml
|
||||
- ../sm-oauthserver-plugin/models/settings/fields.yaml
|
||||
- ../sm-oauthserver-plugin/classes/reveal.go
|
||||
- ../sm-oauthserver-plugin/config/config.yaml
|
||||
- ../sm-oauthserver-plugin/lang/en/lang.yaml
|
||||
- ../sm-oauthserver-plugin/lang/pl/lang.yaml
|
||||
- ../sm-oauthserver-plugin/README.md
|
||||
- ../sm-oauthserver-plugin/import_cutover_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/admin_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/commands_smoke_test.go
|
||||
- ../sm-oauthserver-plugin/parity_test.go
|
||||
- ../sm-oauthserver-plugin/testdata/parity/README.md
|
||||
- ../sm-oauthserver-plugin/testdata/parity/rules.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/deviations.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/seed.json
|
||||
- ../sm-oauthserver-plugin/testdata/parity/winter-export.jsonl
|
||||
- ../sm-oauthserver-plugin/testdata/parity/id_token_shape.json
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/discovery.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/jwks.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/authorize_errors.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/login_handoff.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/consent_allow.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/consent_silent.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/consent_deny.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/token_errors.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/userinfo_errors.yaml
|
||||
- ../sm-oauthserver-plugin/testdata/parity/flows/authorizations.yaml
|
||||
- .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md
|
||||
autonomous: false
|
||||
requirements: [SC-3, SC-4, D-03, D-08, D-10, D-11, D-13, D-14, D-15, D-17, D-19]
|
||||
estimate:
|
||||
tokens: 260000
|
||||
raw_tokens: 260000
|
||||
tasks: 7
|
||||
confidence: low
|
||||
must_haves:
|
||||
truths:
|
||||
- "SC-4, D-11, D-19: oauthserver:import-winter copies the six PHP tables (clients, auth_codes, access_tokens, auth_requests, consents, subjects) from the JSON-lines export keeping ids, hashes and timestamps, moves the id sequences, and with --key-dir inserts every key of keys.json with its original kid, its PEMs (private encrypted with the app key) and its retired state; after the import a pre-cutover access token works at /oauth/userinfo, a pre-cutover id_token verifies against the Go JWKS, the imported client authenticates with its old secret, and the next Go id_token carries the imported active kid."
|
||||
- "D-19: imported clients become kind oidc, public subjects, no offline_access (D-17); imported subjects get the empty (public) sector; the import refuses to write into non-empty tables without --force, reports without writing under --dry-run, and aborts naming the count when a referenced user does not exist in the application."
|
||||
- "D-13: oauthserver:rotate-keys promotes a new key (algorithm from key_algorithm) and retires the previous one, which stays in the JWKS for rotation_grace_hours (default 24); --prune also removes keys past the grace; the output lines match PHP and never contain key material; a scheduled rotation runs only when rotation_interval is set (off by default)."
|
||||
- "SC-3: oauthserver:prune runs daily through the framework scheduler and deletes codes, access tokens (expired or revoked), auth requests, refresh tokens and MCP codes older than one day past expiry, and keys past the grace window, printing one count per kind."
|
||||
- "D-03, D-08: administrators manage OIDC clients in cabana with stock field types: create generates an oas_ client id and an oas_cs_ secret that is shown exactly once, regenerate-secret is a danger action that invalidates the old secret, the secret hash never appears in a list, form or JSON, redirect URIs are edited one per line, pairwise clients need a resolvable sector, and the client form lists who authorized the client with each user's sub; branding is a singleton form linked from Settings with a logo upload."
|
||||
- statement: "D-14: tide fixtures recorded from the PHP plugin (discovery, JWKS, authorize errors and redirects, login handoff, resume, decide, deny, silent consent, token success and errors, userinfo success and 401, authorizations list, revoke and 404) replay against the Go plugin with no difference outside a documented deviations list; the PHP id_token's header members and claim set equal the Go id_token's. The only evidence is TestPHPParityReplay and TestIDTokenShapeParity passing with PHASE194_REQUIRE_PARITY=1 over committed recordings; a skip, the gate's NOT RUN parity line or the skip-parity reply is not evidence, so without recordings this truth stays unproven and the phase verdict is human_needed (or gaps_found), never passed."
|
||||
verification: backstop
|
||||
- "SC-4: a security review walks ASVS L1 across wristband's OIDC flavour, the plugin and the sm-user-plugin additions, verifies every T-19.4 mitigation in code and in a test, fixes any gap, and records the result in 19.4-SECURITY-REVIEW.md."
|
||||
artifacts:
|
||||
- path: "../sm-oauthserver-plugin/console/import_winter.go"
|
||||
provides: "oauthserver:import-winter for the six tables plus --key-dir, --settings and --uploads-dir"
|
||||
contains: "oauthserver:import-winter"
|
||||
- path: "../sm-oauthserver-plugin/console/import_keys.go"
|
||||
provides: "key_dir import keeping original kids and retired state"
|
||||
contains: "keys.json"
|
||||
- path: "../sm-oauthserver-plugin/console/rotate_keys.go"
|
||||
provides: "oauthserver:rotate-keys"
|
||||
contains: "oauthserver:rotate-keys"
|
||||
- path: "../sm-oauthserver-plugin/console/prune.go"
|
||||
provides: "oauthserver:prune"
|
||||
contains: "oauthserver:prune"
|
||||
- path: "../sm-oauthserver-plugin/controllers/clients.go"
|
||||
provides: "cabana Clients controller with one-time secret reveal and regenerate action"
|
||||
contains: "regenerate_secret"
|
||||
- path: "../sm-oauthserver-plugin/parity_test.go"
|
||||
provides: "TestPHPParityReplay and TestIDTokenShapeParity"
|
||||
contains: "ReplayFlow"
|
||||
- path: ".planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md"
|
||||
provides: "ASVS L1 security review with evidence per T-19.4 threat"
|
||||
contains: "T-19.4-SC"
|
||||
key_links:
|
||||
- from: "../sm-oauthserver-plugin/console/import_keys.go"
|
||||
to: "../sm-oauthserver-plugin/models/signing_key.go"
|
||||
via: "inserts SigningKey rows with lagoon.NewEncrypted private PEMs and the manifest's kids"
|
||||
pattern: "NewEncrypted"
|
||||
- from: "../sm-oauthserver-plugin/schedule.go"
|
||||
to: "../sm-oauthserver-plugin/console/prune.go"
|
||||
via: "pact.ScheduledCommand{Command: oauthserver:prune, Cadence: pact.Daily()}"
|
||||
pattern: "pact.Daily"
|
||||
- from: "../sm-oauthserver-plugin/controllers/clients.go"
|
||||
to: "modules/wristband/oidc_options.go"
|
||||
via: "client credentials from wristband.IssueOIDCClientCredentials"
|
||||
pattern: "IssueOIDCClientCredentials"
|
||||
prohibitions:
|
||||
- statement: "No private key, plaintext secret, session token or vars file is committed; parity fixtures hold variables, hashes and shapes only."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "The signing-key model never appears in a cabana controller, form or list."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "Nothing is pushed, tagged or deployed."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
---
|
||||
|
||||
## Phase Goal
|
||||
|
||||
ROADMAP Goal (not in user-story format; no story invented, see plan 01): `wristband` is a full OpenID Connect provider that existing relying parties can switch to without noticing: discovery, JWKS with asymmetric signing and key rotation, `id_token`, userinfo, resumable authorization with account switching, a consent store and pairwise subjects. The existing issuer, signing keys and client secrets carry over.
|
||||
|
||||
This plan's slice (plan 3 of 4, wave 3): the cutover and operations half. An operator moves a WinterCMS site's OIDC provider to the Go plugin (the import, proven end to end first), manages clients and branding in the admin, rotates and prunes keys on a schedule, the PHP contract is recorded with tide and replayed against Go, and the phase gets its security review.
|
||||
|
||||
## Decisions taken in this plan (recorded assumptions and Claude's discretion)
|
||||
|
||||
- Branding settings and logos (RESEARCH OQ8, researcher's recommendation): imported by optional flags `--settings` (the Winter `system_settings` item `golem15_oauthserver_settings`) and `--uploads-dir` (Winter storage path for `system_files` logo attachments of clients and settings).
|
||||
- cabana widgets (RESEARCH OQ9): stock field types only: `text` for colours (hex rule in Rules), `textarea` for custom CSS and redirect URIs, `switch` for flags, `dropdown` for subject type, `fileupload` for logos, and scopes as stock checkboxes or a fixed-option taglist, whichever cabana supports without new widgets (the executor records which). cabana settings forms refuse `fileupload`, so Branding is a `pact.AdminSingleton` controller linked from Settings (the sitemap plugin's pattern), not a singleton settings form.
|
||||
- The Clients list shows kind oidc only; dynamically registered MCP clients are not managed here (D-08: admin-registered clients are OIDC).
|
||||
- One-time secret reveal: the plaintext is parked in `cooler.FromApp`'s cache under `oauthserver:reveal:{admin id}:{record id}` for 5 minutes and forgotten on first read (PHP parks it in the session). Multi-instance deployments need `cache.driver: redis` for the reveal to survive a request landing on another instance; an administrator who misses it regenerates. Documented in the README.
|
||||
- Prune margin: one day past expiry or revocation as PHP; the Go-only tables (refresh tokens, MCP codes) follow the same rule and add two output lines after PHP's four.
|
||||
- Scheduled rotation (CONTEXT discretion): `rotation_interval` empty means off; the README suggests 2160h (90 days) when switched on; an unparseable or non-positive value fails boot naming the key.
|
||||
- Parity: the session JWT on both sides comes from a variable (`session_token`): recorded from a human's WavePath login, minted by the Go harness on replay; JWKS `n`, `e`, `x`, `y` and `kid` values, id_token and access token strings, codes and request ids are compared by shape or captured as variables; HTML bodies of rendered pages are not compared (D-14), their status and headers are.
|
||||
- D-11 is a one-way door already decided by the user in CONTEXT; it is rated here and not re-gated.
|
||||
- Parity skip (D-14): a "skip-parity" reply at Task 5 is an accepted way to finish this plan, never a way to prove D-14. The D-14 truth is a backstop truth whose only evidence is the replay passing with PHASE194_REQUIRE_PARITY=1; after a skip the phase verdict stays human_needed (or gaps_found) until the recording is made.
|
||||
- Context budget (estimate 260k, 7 tasks; size accepted with the four-plan decision): the Task 5 checkpoint splits execution in two, since the executor resumes in a fresh continuation agent. Tasks 1-4 run in the first context; Tasks 6-7 run in the continuation agent. Task 7 (security review) reads everything it needs from disk (the three plans' threat models, the plan 01 and 02 SUMMARYs, the code), so the executor may also give it a fresh agent of its own.
|
||||
|
||||
## Artifacts this phase produces (this plan)
|
||||
|
||||
- Commands: `oauthserver:import-winter` (flags `file`, `key-dir`, `settings`, `uploads-dir`, `force`, `dry-run`), `oauthserver:rotate-keys` (flag `prune`), `oauthserver:prune`; Go API `console.ImportWinter(app)`, `console.ImportWinterFile(ctx, db, opts WinterOptions, out bonfire.Output) (WinterReport, error)`, `console.ImportKeyDir(ctx, db, dir string, out bonfire.Output) (int, error)`, `console.ImportSettings(ctx, app, db, raw string, uploadsDir string, out bonfire.Output) error`, `console.RotateKeys(app)`, `console.Prune(app)`, `console.PruneExpired(ctx, db, ring *classes.KeyRing, now time.Time) (PruneReport, error)`, types `WinterOptions`, `WinterReport`, `PruneReport`.
|
||||
- Schedule: `oauthserver:prune` daily; `oauthserver:rotate-keys` every `rotation_interval` when set. Config key `golem15.oauthserver.rotation_interval`.
|
||||
- Admin: controllers `golem15.oauthserver.clients` (`controllers.ClientsControllerID`), `golem15.oauthserver.branding` (`controllers.BrandingControllerID`), permissions `golem15.oauthserver.manage_clients`, `golem15.oauthserver.manage_settings`, a Settings link item `oauthserver_branding`, navigation entry with a Clients side menu (PHP order 560), record action `regenerate_secret` (Danger), partials `_secret_reveal` and `_authorizations`, `classes.RevealStore` (`Park`, `Take`).
|
||||
- `scripts/winter-export.sql`; parity assets under `testdata/parity/` (README runbook, rules.yaml, deviations.yaml, seed.json, winter-export.jsonl, id_token_shape.json, flows/*.yaml).
|
||||
- Tests (smoke): `TestImportWinterCutoverSmoke` (import_cutover_smoke_test.go), `TestClientsAdminSmoke`, `TestBrandingAdminSmoke` (admin_smoke_test.go), `TestRotateAndPruneSmoke`, `TestScheduleSmoke` (commands_smoke_test.go), `TestPHPParityReplay`, `TestIDTokenShapeParity` (parity_test.go).
|
||||
- `.planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md`.
|
||||
|
||||
<objective>
|
||||
Let an operator move a WinterCMS site's OIDC provider to the Go plugin without relying parties noticing (import with original kids, secrets and live tokens), run it day to day (admin screens, key rotation, prune on a schedule), prove the relying-party-visible contract against recordings of the PHP plugin, and review the phase's security.
|
||||
|
||||
Purpose: SC-3 (scheduled prune), SC-4 (import and security review), D-03, D-08, D-11, D-13, D-14, D-19.
|
||||
Output: commits in ../sm-oauthserver-plugin, the security review document in summercms.go (planning doc commit), nothing pushed.
|
||||
</objective>
|
||||
|
||||
<execution_context>
|
||||
@~/.claude/msd-core/workflows/execute-plan.md
|
||||
@~/.claude/msd-core/templates/summary.md
|
||||
</execution_context>
|
||||
|
||||
<context>
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-CONTEXT.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-RESEARCH.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-PATTERNS.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-02-SUMMARY.md
|
||||
|
||||
Repos: ../sm-oauthserver-plugin (code), summercms.go (the review document only, planning doc commit), ../fonoteka.go/plugins/golem15/user only if the security review finds a gap there (additive fixes, own commit). No co-author tags, stage by path, README in the same commit as the commands and config it documents. Docker-backed tests skip under -short; run them on a Docker host (through sudo -u golem if the socket is denied) and record NOT RUN when no daemon answers. The WavePath application and its database are another project: read them, run only the commands the runbook names, never edit its code.
|
||||
|
||||
PHP source of truth (read-only): /media/nvme/dev/jz/wavepath.org/plugins/golem15/oauthserver/ — Plugin.php (permissions, navigation :92-115, settings :116-132, schedule :135), controllers/Clients.php and controllers/clients/*, models/client/{fields,columns}.yaml, models/settings/fields.yaml, models/Client.php (issue, regenerateSecret, redirect_uris_text), models/Settings.php, console/{RotateKeys,PruneExpired}.php, classes/KeyRing.php (keys.json manifest :20, :250-330), updates/*.php, tests/feature/ClientRegistryTest.php, tests/unit/{KeyRingTest,PruneExpiredTest}.php, tests/feature/RelyingPartyFlowTest.php.
|
||||
|
||||
<interfaces>
|
||||
From plan 02 (see 19.4-02-SUMMARY.md): models Client, AuthRequest, AuthCode, AccessToken, RefreshToken, Consent, Subject, SigningKey (PrivatePEM lagoon.Encrypted), MCPCode, Settings (row 1, attachOne logo); classes.KeyRing (ActiveSigningKey, PublishedKeys, Rotate(ctx) (newKid, previousKid string, retiredAt *time.Time, err error), Prune(ctx, now) (int, error)), classes.LoadBranding and the sanitisers, harness bootOAuth in harness_test.go, config keys in config/config.yaml.
|
||||
From plan 01: wristband.IssueOIDCClientCredentials, wristband.SubjectSector, wristband.ErrSectorRequired, wristband.ParsePrivateKeyPEM, wristband.ParsePublicKeyPEM.
|
||||
Existing wristband (before this phase, modules/wristband/client_issue.go:38): wristband.RejectRedirectURI.
|
||||
|
||||
Analogs:
|
||||
- ../sm-faq-plugin/console/{import_winter.go (WinterOptions, ImportWinterFile, refuse-unless-force, setval), helpers.go (flagValue, flagOn, lookupDB, readJSONLines)}, ../sm-faq-plugin/scripts/winter-export.sql (header, JSON_OBJECT per line).
|
||||
- ../sm-pgstripe-plugin/console/import_winter.go (settings item, secrets into lagoon.Encrypted, masked output), ../fonoteka.go/plugins/golem15/feedback/console/import_settings.go (Winter system_settings item import), ../sm-journal-plugin/console/import_posts.go (files through lagoon attach).
|
||||
- ../sm-paymentgateway-plugin/{schedule.go, plugin.go Commands and Schedule}, ../sm-paymentgateway-plugin/console/pg_*.go.
|
||||
- ../sm-faq-plugin/{admin.go, controllers/faqs.go, controllers/faqs/config_*.yaml, controllers/admin_registry.go}, ../sm-sitemap-plugin/{admin.go (Settings item with Controller), controllers/definitions.go (pact.AdminSingleton)}, ../sm-paymentgateway-plugin/models/order/fields.yaml (type partial) and its PartialData controller.
|
||||
- summercms.go: modules/pact/capabilities.go (ScheduledCommand, Daily, Every, AdminSingleton, AdminRecordAction with Danger, AdminPartialData, FormBeforeCreate, SettingsItem.Controller), modules/cooler/cooler.go (FromApp, Cache Get/Set/Forget), modules/tide/README.md (RecordFlow, Rules, Store, ScrubStep, ReplayFlow, Diff), cmd/summer/parity.go (parity:record, parity:replay).
|
||||
</interfaces>
|
||||
</context>
|
||||
|
||||
<tasks>
|
||||
|
||||
<task type="tracer">
|
||||
<name>Task 1: Tracer: an operator imports a WinterCMS site's OIDC tables and key_dir, and relying parties keep working: an old access token reads userinfo, an old id_token verifies against the new JWKS, the old client secret still authenticates</name>
|
||||
<reversibility rating="one-way">D-11 (decided in CONTEXT, not re-gated): kids are imported unchanged because a cutover with new kids breaks every relying party's verification until it refetches.</reversibility>
|
||||
<files>../sm-oauthserver-plugin/console/helpers.go, ../sm-oauthserver-plugin/console/import_winter.go, ../sm-oauthserver-plugin/console/import_keys.go, ../sm-oauthserver-plugin/scripts/winter-export.sql, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/README.md, ../sm-oauthserver-plugin/import_cutover_smoke_test.go</files>
|
||||
<read_first>../sm-faq-plugin/console/import_winter.go, ../sm-faq-plugin/console/helpers.go, ../sm-faq-plugin/scripts/winter-export.sql, ../sm-pgstripe-plugin/console/import_winter.go, ../sm-oauthserver-plugin/models/*.go, ../sm-oauthserver-plugin/updates/202610190001_create_golem15_oauthserver_tables.go, ../sm-oauthserver-plugin/classes/keyring.go, ../sm-oauthserver-plugin/harness_test.go, 19.4-RESEARCH.md (D-19 hash compatibility, Runtime State Inventory, Pattern 3 imported PEMs, Pitfalls 7, 8), PHP classes/KeyRing.php, updates/*.php, models/*.php ($jsonable columns)</read_first>
|
||||
<action>Per D-11, D-17, D-19, SC-4.
|
||||
|
||||
scripts/winter-export.sql (header in the faq style: read-only, `mysql -N -B --raw {database} < winter-export.sql > oauthserver.jsonl`, MySQL 5.7.8+/MariaDB 10.2.3+, "check the table names first"): one JSON_OBJECT per row with a "table" member naming the source (clients, auth_codes, access_tokens, auth_requests, consents, subjects) and every PHP column; then the system_settings row whose item is golem15_oauthserver_settings and the system_files rows whose attachment_type is Golem15\OAuthServer\Models\Client or Golem15\OAuthServer\Models\Settings and field logo (consumed in Task 2).
|
||||
|
||||
console/helpers.go copied from faq (flagValue, flagOn, lookupDB, readJSONLines). console/import_winter.go: `ImportWinter(app)` registers `oauthserver:import-winter` with flags file, key-dir, settings, uploads-dir, force, dry-run; `ImportWinterFile(ctx, db, opts, out)` reads the lines, groups by table, checks that every user_id referenced exists in users (abort with the count and the advice to import users first), refuses when any of the six target tables holds rows unless Force (Force deletes the six tables' rows inside the same transaction), reports per-table counts under DryRun, else copies all rows in one transaction keeping ids, hashes (secret_hash, code_hash, token_hash: SHA-256 hex identical to wristband's, verified in RESEARCH), JSON text columns and timestamps; clients get kind oidc, subject_type public, offline_access false, token_endpoint_auth_method client_secret_basic; subjects get sector ''; then `SELECT setval(pg_get_serial_sequence(...), COALESCE(MAX(id), 1), MAX(id) IS NOT NULL)` for each table. Output: one line per table with the count; never a hash, secret or token. Register the command in Commands() (plugin.go gains pact.HasCommands).
|
||||
|
||||
console/import_keys.go: `ImportKeyDir(ctx, db, dir, out)` reads keys.json ({"active": kid, "keys": {kid: {created_at, retired_at}}}), and for each kid reads {kid}.key and {kid}.pub, parses with wristband.ParsePrivateKeyPEM (PKCS#8, then PKCS#1) and wristband.ParsePublicKeyPEM, refuses a key whose public half does not Equal the .pub, derives alg from the key type, and inserts SigningKey rows with the original kid, public PEM, `lagoon.NewEncrypted` private PEM, created_at and retired_at from the manifest, active only for the manifest's active kid (one transaction; a kid that already exists is refused without --force). A missing directory, an unreadable file or a mismatch aborts with a message naming the kid and the file, never the PEM. Output: "Imported signing key {kid} (active|retired at {time})". ImportWinter calls it when --key-dir is set, after the tables, in the same command run.
|
||||
|
||||
README "Importing from WinterCMS": the export command, the import command, the env mapping (OAUTHSERVER_ISSUER to golem15.oauthserver.issuer and the rest), stop the PHP prune cron at cutover, keep the issuer identical, do not rotate keys within one hour of the cutover (relying parties cache JWKS for up to an hour), delete the PHP key_dir securely after verification, keep app.previous_keys when rotating app.key.
|
||||
|
||||
Test import_cutover_smoke_test.go `TestImportWinterCutoverSmoke` (Postgres, skips under -short): with bootOAuth and a user created with a known id, write a JSONL export in a temp dir (a client whose secret_hash is sha256 hex of a known oas_cs_ secret, a subject, a consent, an unexpired auth code with a known PKCE challenge and its oas_ac_ code hash, an unexpired access token whose hash is of a known oas_at_ value, an auth request) and a PHP-shaped key_dir (two RSA 2048 keys generated in the test, PKCS#8 .key files mode 0600, PKIX .pub files, keys.json with one active kid of 16 hex characters and one retired one hour ago); run ImportWinterFile and ImportKeyDir; assert GET /oauth/jwks lists both kids; an id_token signed in the test with the imported active private key (golang-jwt, RS256, kid header, the PHP claim set) verifies against the served JWKS; GET /oauth/userinfo with the old access token answers the imported sub; POST /oauth/token with the old client secret exchanges the imported code and the new id_token's kid is the imported active kid; a second import without --force is refused and changes nothing; creating a new client afterwards gets an id above the imported maximum.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^TestImportWinterCutoverSmoke$' -v ./... 2>&1 | grep -q -- '^--- PASS: TestImportWinterCutoverSmoke'</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red, or no "--- PASS: TestImportWinterCutoverSmoke" line (Docker missing, a hash not accepted, a kid not preserved, or an imported token rejected).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c "'table'" ../sm-oauthserver-plugin/scripts/winter-export.sql` prints at least 6.
|
||||
- `grep -n 'setval(pg_get_serial_sequence' ../sm-oauthserver-plugin/console/import_winter.go | wc -l` prints at least 1.
|
||||
- `grep -n 'NewEncrypted' ../sm-oauthserver-plugin/console/import_keys.go | wc -l` prints at least 1.
|
||||
- `grep -c 'oauthserver:import-winter' ../sm-oauthserver-plugin/README.md` prints at least 1.
|
||||
</acceptance_criteria>
|
||||
<done>A WinterCMS site's relying parties, tokens and keys keep working the moment its data and key_dir are imported into the Go plugin.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 2: Administrators create and manage OIDC clients and branding in the admin, with one-time secret reveal, secret regeneration and the list of users who authorized each client; the import also brings branding and logos</name>
|
||||
<files>../sm-oauthserver-plugin/admin.go, ../sm-oauthserver-plugin/admin_permissions.go, ../sm-oauthserver-plugin/admin_navigation.go, ../sm-oauthserver-plugin/controllers/admin_registry.go, ../sm-oauthserver-plugin/controllers/clients.go, ../sm-oauthserver-plugin/controllers/branding.go, ../sm-oauthserver-plugin/controllers/clients/config_list.yaml, ../sm-oauthserver-plugin/controllers/clients/config_form.yaml, ../sm-oauthserver-plugin/controllers/clients/_secret_reveal.htm, ../sm-oauthserver-plugin/controllers/clients/_authorizations.htm, ../sm-oauthserver-plugin/controllers/branding/config_form.yaml, ../sm-oauthserver-plugin/models/client.go, ../sm-oauthserver-plugin/models/settings.go, ../sm-oauthserver-plugin/models/client/columns.yaml, ../sm-oauthserver-plugin/models/client/fields.yaml, ../sm-oauthserver-plugin/models/settings/fields.yaml, ../sm-oauthserver-plugin/classes/reveal.go, ../sm-oauthserver-plugin/console/import_settings.go, ../sm-oauthserver-plugin/console/import_winter.go, ../sm-oauthserver-plugin/lang/en/lang.yaml, ../sm-oauthserver-plugin/lang/pl/lang.yaml, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/README.md, ../sm-oauthserver-plugin/admin_smoke_test.go</files>
|
||||
<read_first>PHP Plugin.php (:78-132), controllers/Clients.php, controllers/clients/{config_list.yaml, config_form.yaml, _secret_reveal.htm, _authorizations.htm}, models/client/{fields,columns}.yaml, models/settings/fields.yaml, models/Client.php, tests/feature/ClientRegistryTest.php, ../sm-faq-plugin/{admin.go, controllers/faqs.go, controllers/faqs/config_list.yaml, controllers/faqs/config_form.yaml, controllers/admin_registry.go}, ../sm-sitemap-plugin/{admin.go, controllers/definitions.go}, ../sm-paymentgateway-plugin/models/order/fields.yaml (type partial) and the controller's PartialData, modules/pact/capabilities.go (AdminSingleton, AdminRecordAction, AdminPartialData, FormBeforeCreate, SettingsItem), modules/cabana/form_schema.go (stock field types :24-30), modules/cabana/settings.go (:100-104 settings forms refuse fileupload), modules/cooler/cooler.go (FromApp), ../fonoteka.go/plugins/golem15/feedback/console/import_settings.go, ../sm-journal-plugin/console/import_posts.go</read_first>
|
||||
<action>Per D-03, D-08, D-15, D-17, D-19.
|
||||
|
||||
Permissions golem15.oauthserver.manage_clients and golem15.oauthserver.manage_settings (PHP labels via lang); navigation entry (PHP order 560) with a Clients side menu; AdminFS embedding the YAML and partials. Clients controller (ID golem15.oauthserver.clients, model Golem15\OAuthServer\Models\Client, permission manage_clients): ListExtendQuery and FormExtendQuery restrict to kind oidc; columns id, name, client_id, is_active, is_dev, subject_type, created_at; form fields name (required), client_id (read-only, shown after create), redirect_uris_text (textarea, one URI per line, mapped to the JSON redirect_uris column; each line validated with wristband.RejectRedirectURI, except that is_dev clients may also register http loopback URIs), scopes (openid always kept; profile, email, offline_access selectable with a stock type; offline_access saved only together with the offline_access switch), logo (fileupload image), is_active, is_dev and offline_access (switch; the offline_access comment says it takes effect only with refresh.enabled), subject_type (dropdown public or pairwise), sector_identifier (text; on save a pairwise client must resolve wristband.SubjectSector, else a field error naming the sector), secret (type partial `_secret_reveal`), authorizations (type partial `_authorizations`). FormBeforeCreate sets kind oidc, calls wristband.IssueOIDCClientCredentials and stores the client id and the hash, keeping the plaintext only on an unexported, never-persisted field of the model; FormAfterCreate (the record id now exists) parks it through classes.RevealStore (`Park(ctx, adminID, recordID, secret)` into cooler.FromApp under oauthserver:reveal:{admin}:{record} for 5 minutes; `Take` reads and forgets, so it reveals exactly once and never on another record or for another administrator). Record action `regenerate_secret` (Danger true, confirm phrase, permission manage_clients) replaces the hash with a new secret's, parks the plaintext and answers a message phrase; the old secret fails at /oauth/token afterwards. PartialData: `_secret_reveal` returns the taken secret or nothing; `_authorizations` returns a curated view model (user name, email, sub for the client's sector, scopes, first authorized, last used) from consents joined to users and subjects, never a GORM model, skipping rows whose user is gone. The secret hash is never a field, column or JSON member.
|
||||
|
||||
Branding: controllers/branding.go (ID golem15.oauthserver.branding, permission manage_settings) implements pact.AdminSingleton returning row 1 of golem15_oauthserver_settings; form models/settings/fields.yaml ports PHP's fields with stock types (text for site_name, the seven colours with Rules enforcing the hex pattern, font_css_url with an https rule, font_family, textarea custom_css max 20000, fileupload logo); a Settings link item (code oauthserver_branding, Controller set, PHP label and permission). Saving goes through the same sanitisers on render (plan 02), so an invalid stored value can never reach a page.
|
||||
|
||||
Import (D-19 optional parts): console/import_settings.go `ImportSettings` writes the Winter settings JSON into row 1 (keys PHP and Go share; unknown keys ignored and reported) when --settings names the export file (the system_settings line), and with --uploads-dir copies each exported logo system_files row's file from {uploads-dir}/{partition}/{disk_name} into the application's storage through lagoon attach as the client's or the settings' logo; ImportWinter calls them after the tables.
|
||||
|
||||
Tests admin_smoke_test.go (Postgres, skip under -short), through cabana's admin API as an administrator with the permissions: `TestClientsAdminSmoke` (create answers a client_id starting oas_ and the form's secret partial shows an oas_cs_ secret once, a second read shows nothing and another client's form never shows it; list and form JSON contain no secret_hash; regenerate makes the old secret fail and the new one pass at /oauth/token; redirect URIs round-trip one per line; a pairwise client with two redirect hosts and no sector is refused; an administrator without manage_clients gets 403; the authorizations partial lists a consenting user's sub), `TestBrandingAdminSmoke` (the Settings link opens the singleton form; a colour that is not hex is refused; a saved accent colour appears on the consent page; an uploaded logo's URL appears on the consent page). README: the admin screens, permissions, the reveal store and the multi-instance cache note, the import flags.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestClientsAdminSmoke|TestBrandingAdminSmoke)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 2</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red (cabana rejected a YAML schema at boot), or fewer than two "--- PASS" lines for the admin smokes.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -rn 'secret_hash' ../sm-oauthserver-plugin/models/client/fields.yaml ../sm-oauthserver-plugin/models/client/columns.yaml | wc -l` prints 0.
|
||||
- `grep -rln 'SigningKey' ../sm-oauthserver-plugin/controllers ../sm-oauthserver-plugin/admin.go` prints nothing.
|
||||
- `grep -n 'Danger: *true' ../sm-oauthserver-plugin/controllers/clients.go | wc -l` prints 1.
|
||||
- `grep -n 'SingletonRecord' ../sm-oauthserver-plugin/controllers/branding.go | wc -l` prints 1.
|
||||
- `grep -n 'type: fileupload' ../sm-oauthserver-plugin/models/client/fields.yaml ../sm-oauthserver-plugin/models/settings/fields.yaml | wc -l` prints 2.
|
||||
</acceptance_criteria>
|
||||
<done>An administrator registers relying parties, hands over their secret once, regenerates it when it leaks, sees who authorized each one, and brands the pages, all in the admin.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 3: Operators rotate signing keys with a grace window and the application prunes expired codes, tokens, requests and retired keys every day; scheduled rotation is available on request</name>
|
||||
<files>../sm-oauthserver-plugin/console/rotate_keys.go, ../sm-oauthserver-plugin/console/prune.go, ../sm-oauthserver-plugin/schedule.go, ../sm-oauthserver-plugin/plugin.go, ../sm-oauthserver-plugin/config/config.yaml, ../sm-oauthserver-plugin/README.md, ../sm-oauthserver-plugin/commands_smoke_test.go</files>
|
||||
<read_first>PHP console/RotateKeys.php, console/PruneExpired.php, Plugin.php registerSchedule (:135), tests/unit/KeyRingTest.php, tests/unit/PruneExpiredTest.php, tests/feature/RelyingPartyFlowTest.php (rotation within grace), ../sm-paymentgateway-plugin/schedule.go and plugin.go (Commands, Schedule), ../sm-paymentgateway-plugin/console/pg_*.go (command shape), ../sm-oauthserver-plugin/classes/keyring.go, modules/pact/capabilities.go (:120-175 Cadence, Daily, Every, ScheduledCommand, HasSchedule)</read_first>
|
||||
<action>Per D-13, SC-3.
|
||||
|
||||
console/rotate_keys.go `RotateKeys(app)`: `oauthserver:rotate-keys` with bare flag prune; calls KeyRing.Rotate; prints "New signing key: {kid}", then "Retired previous key {kid} at {time} (verifiable for {grace} more hours)." or "No previous key was active; this is the first signing key on this site.", then with --prune "Pruned {n} expired key(s)." else "Expired keys were not pruned. Run with --prune, or leave it to oauthserver:prune."; failures print only "Key rotation failed: the signing key could not be generated or written." (or PHP's prune-failure line) and exit non-zero, never an underlying error that could carry key material. The new key's algorithm comes from key_algorithm, so switching to ES256 is a config change plus a rotation, and the JWKS then holds both kinds until the grace ends (D-12).
|
||||
|
||||
console/prune.go `Prune(app)` and testable `PruneExpired(ctx, db, ring, now) (PruneReport, error)`: cutoff now minus 24 hours; deletes auth codes with expires_at before the cutoff, access tokens expired or revoked before the cutoff, auth requests expired before the cutoff, refresh tokens expired or revoked before the cutoff, MCP codes expired before the cutoff, and keys through KeyRing.Prune; prints PHP's four lines ("Authorization codes pruned: {n}", "Access tokens pruned: {n}", "Authorization requests pruned: {n}", "Signing keys pruned: {n}") followed by "Refresh tokens pruned: {n}" and "MCP codes pruned: {n}"; exits zero on an empty database.
|
||||
|
||||
schedule.go: `Schedule()` returns oauthserver:prune with pact.Daily(), plus oauthserver:rotate-keys with pact.Every(interval) only when golem15.oauthserver.rotation_interval parses (time.ParseDuration) to a positive value; an invalid or non-positive value fails boot naming the key. plugin.go gains pact.HasSchedule and registers both commands. config.yaml documents rotation_interval (empty, the 2160h suggestion in a comment) and rotation_grace_hours.
|
||||
|
||||
Tests commands_smoke_test.go (Postgres, skip under -short): `TestRotateAndPruneSmoke` (rotation makes a new kid active and keeps the old one in the JWKS; a token signed before the rotation verifies within the grace; with the clock past the grace prune removes the old key and keeps the new one; rows older than the margin are deleted and newer ones survive for every kind; output lines match the PHP text; the rotate failure path prints only the fixed message), `TestScheduleSmoke` (default schedule has only the daily prune; rotation_interval 2160h adds the rotation; "soon" and "-1h" fail boot naming golem15.oauthserver.rotation_interval). README: commands and schedule.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestRotateAndPruneSmoke|TestScheduleSmoke)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 2</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red, or fewer than two "--- PASS" lines for the rotation, prune and schedule smokes.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -n 'pact.Daily()' ../sm-oauthserver-plugin/schedule.go | wc -l` prints 1 and `grep -n 'pact.Every' ../sm-oauthserver-plugin/schedule.go | wc -l` prints 1.
|
||||
- `grep -c 'Authorization codes pruned: \|Access tokens pruned: \|Authorization requests pruned: \|Signing keys pruned: ' ../sm-oauthserver-plugin/console/prune.go` prints at least 4.
|
||||
- `grep -n 'Key rotation failed: the signing key could not be generated or written.' ../sm-oauthserver-plugin/console/rotate_keys.go | wc -l` prints 1.
|
||||
- `grep -c 'rotation_interval' ../sm-oauthserver-plugin/config/config.yaml ../sm-oauthserver-plugin/README.md | awk -F: '{s+=$2} END {print s}'` prints at least 2.
|
||||
</acceptance_criteria>
|
||||
<done>Keys rotate without breaking relying parties, expired grant data disappears daily, and periodic rotation is one config value away.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 4: The parity suite is ready to record the PHP plugin: spec flows for every relying-party-visible step, capture rules, the accepted-deviations list, the replay test and a runbook for starting WavePath locally</name>
|
||||
<files>../sm-oauthserver-plugin/testdata/parity/README.md, ../sm-oauthserver-plugin/testdata/parity/rules.yaml, ../sm-oauthserver-plugin/testdata/parity/deviations.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/discovery.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/jwks.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/authorize_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/login_handoff.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_allow.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_silent.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_deny.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/token_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/userinfo_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/authorizations.yaml, ../sm-oauthserver-plugin/parity_test.go</files>
|
||||
<read_first>modules/tide/README.md (flows, Rules, Store, ScrubStep, RecordFlow, ReplayFlow, Diff, compared headers), cmd/summer/parity.go (parity:record and parity:replay flags), modules/tide/diff.go (:30-60 compared headers), 19.4-RESEARCH.md (Pattern 2 "Wire headers that tide compares", planned deviations under Discovery), 19.4-VALIDATION.md (Manual-Only Verifications), PHP routes.php, tests/feature/RelyingPartyFlowTest.php, ../sm-oauthserver-plugin/harness_test.go, ../sm-oauthserver-plugin/console/import_winter.go</read_first>
|
||||
<action>Per D-14. Spec flows under testdata/parity/flows/ (requests only, variables in double braces), one file each: discovery.yaml; jwks.yaml; authorize_errors.yaml (unknown client, redirect mismatch: status and headers only; missing PKCE, plain method, unsupported response_type, scope without openid, scope outside the client: Location compared); login_handoff.yaml (anonymous start: Location); consent_allow.yaml (signed-in start, resume with the consent page's status and headers, decide allow with code and state, token success, userinfo success); consent_silent.yaml (second run without a page); consent_deny.yaml (access_denied Location); token_errors.yaml (wrong secret with WWW-Authenticate, unsupported grant, missing parameters, replayed code); userinfo_errors.yaml (missing and revoked tokens); authorizations.yaml (list, revoke, revoke unknown with the 404 JSON). rules.yaml captures volatile values into variables (request id and code from Location query strings, access_token and id_token from token JSON, consent_token from the consent form field) and keeps the headers tide compares. deviations.yaml lists each accepted difference with its JSON path or header and the reason: subject_types_supported adds pairwise (D-15); id_token_signing_alg_values_supported comes from the ring (D-12); JWKS key material and kid values (compared by shape: members, kty, alg, use, kid of 16 hex characters); token and id_token strings; OPTIONS on authorizations without a CORS profile; HTML bodies of rendered pages (D-14). parity_test.go: `TestPHPParityReplay` boots the plugin with bootOAuth, seeds the user from seed.json and imports testdata/parity/winter-export.jsonl with ImportWinterFile, mints the Go session JWT into the tide Store as session_token, replays every recorded fixture (flows/*.yaml with responses) with tide.ReplayFlow and fails on any Diff not matched by deviations.yaml; while the flows carry no recorded responses it skips with the message "no PHP recordings" unless PHASE194_REQUIRE_PARITY=1 is set, which turns the skip into a failure (plan 04's gate sets it, so the gate fails closed); this recordings check is the test's first statement, before the -short check and before bootOAuth, so the "no PHP recordings" skip never depends on Docker; `TestIDTokenShapeParity` compares id_token_shape.json (header member names and claim names with value types from the PHP recording) with a Go id_token from the same flow. testdata/parity/README.md is the runbook: start WavePath locally (its documented dev command), create the parity user and an OIDC client (redirect https://rp.example.test/callback, scopes openid profile email) in its backend, export with scripts/winter-export.sql, write base_url, client_id, client_secret and session_token into a vars file outside the repository (mode 0600, for example ~/.config/summercms/parity-oauthserver.vars), record with `go run ../summercms.go/cmd/summer parity:record` per flow, scrub, delete the parity client afterwards. Commit the flows, rules, deviations, runbook and test; the plugin suite stays green because the replay test skips until Task 6 commits the recordings.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 ./... && test -s ../sm-oauthserver-plugin/testdata/parity/rules.yaml && test -s ../sm-oauthserver-plugin/testdata/parity/deviations.yaml && for f in discovery jwks authorize_errors login_handoff consent_allow consent_silent consent_deny token_errors userinfo_errors authorizations; do test -s ../sm-oauthserver-plugin/testdata/parity/flows/$f.yaml || { echo "missing flow $f"; exit 1; }; done</automated>
|
||||
<fails_when>Non-zero exit or "missing flow" printed: vet or the full plugin suite red (the replay test must skip, not fail, before recordings exist), rules.yaml or deviations.yaml missing or empty, or a spec flow file missing.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c 'pairwise' ../sm-oauthserver-plugin/testdata/parity/deviations.yaml` prints at least 1.
|
||||
- `grep -c 'parity-oauthserver.vars\|mode 0600' ../sm-oauthserver-plugin/testdata/parity/README.md` prints at least 1.
|
||||
- `grep -n 'ReplayFlow' ../sm-oauthserver-plugin/parity_test.go | wc -l` prints at least 1.
|
||||
</acceptance_criteria>
|
||||
<done>Everything needed to record the PHP contract and hold Go to it is in place; only the running PHP application is missing.</done>
|
||||
</task>
|
||||
|
||||
<task type="checkpoint:human-action" gate="blocking">
|
||||
<name>Task 5: Start WavePath locally and prepare the parity user, client, export and vars file</name>
|
||||
<read_first>../sm-oauthserver-plugin/testdata/parity/README.md (Task 4 runbook)</read_first>
|
||||
<acceptance_criteria>
|
||||
- The vars file named in the reply exists outside both repositories with mode 0600 (`stat -c %a {file}` prints 600) and holds base_url, client_id, client_secret and session_token.
|
||||
- `curl -s -o /dev/null -w '%{http_code}' {base_url}/.well-known/openid-configuration` prints 200.
|
||||
</acceptance_criteria>
|
||||
<action>Start the local WavePath application with the Golem15.OAuthServer plugin enabled and prepare the parity data as the runbook describes.</action>
|
||||
<instructions>
|
||||
Claude has already written the spec flows, capture rules, deviations list, replay test and runbook (Task 4). The one thing that needs you: the WavePath application and its MariaDB are yours to start and to log in to.
|
||||
1. Start WavePath locally (its usual dev command) so that {base_url}/.well-known/openid-configuration answers 200.
|
||||
2. In its backend create a dedicated parity user (note its id, name, email, activation state) and an OIDC client named "Parity RP" with redirect URI https://rp.example.test/callback and scopes openid, profile and email; copy the one-time secret.
|
||||
3. Log in as the parity user in a browser and copy the token cookie value.
|
||||
4. Run the export from the runbook (`mysql -N -B --raw {database} < ../sm-oauthserver-plugin/scripts/winter-export.sql > ~/.config/summercms/parity-oauthserver.jsonl`).
|
||||
5. Write base_url, client_id, client_secret and session_token into ~/.config/summercms/parity-oauthserver.vars (chmod 600). Do not paste the secret or the token into the chat.
|
||||
</instructions>
|
||||
<verification>Claude checks the vars file mode, that discovery answers 200 at base_url, and that the export file holds lines for the parity client.</verification>
|
||||
<resume-signal>Reply "ready" with the vars file path and the parity user's id, name and email, or "skip-parity" if WavePath cannot be started now (Task 6 then runs its explicit skip check, commits nothing new and records D-14 parity as NOT RUN with a human verification item; D-14 stays unproven and the phase verdict stays human_needed until the recording is made, never passed).</resume-signal>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 6: The Go plugin answers relying parties exactly like the recorded PHP plugin (tide record and replay)</name>
|
||||
<files>../sm-oauthserver-plugin/testdata/parity/flows/discovery.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/jwks.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/authorize_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/login_handoff.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_allow.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_silent.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/consent_deny.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/token_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/userinfo_errors.yaml, ../sm-oauthserver-plugin/testdata/parity/flows/authorizations.yaml, ../sm-oauthserver-plugin/testdata/parity/seed.json, ../sm-oauthserver-plugin/testdata/parity/winter-export.jsonl, ../sm-oauthserver-plugin/testdata/parity/id_token_shape.json, ../sm-oauthserver-plugin/testdata/parity/deviations.yaml, ../sm-oauthserver-plugin/parity_test.go</files>
|
||||
<read_first>../sm-oauthserver-plugin/testdata/parity/README.md, rules.yaml, deviations.yaml, parity_test.go (Task 4), modules/tide/README.md (ScrubStep refusal of token-shaped values), the human's Task 5 reply</read_first>
|
||||
<action>Per D-14. With "ready": record every spec flow against base_url with `go run ../summercms.go/cmd/summer parity:record` (vars from the vars file, never echoed), let tide scrub the fixtures (a scrub refusal means a secret is still in a fixture: fix the rules, never commit it); decode the recorded PHP id_token locally and write id_token_shape.json (header member names, claim names and JSON value types only); write seed.json from the reply (user id, name, email, activation) and testdata/parity/winter-export.jsonl as the export lines for the parity client, the parity user's subject and consent only (hashes, no plaintext). Run TestPHPParityReplay: fix real differences in the plugin or in wristband (wristband fixes go into summercms.go with README updates in their own commits and re-run plan 01's suite), and add an entry to deviations.yaml only for a difference that a locked decision explains (cite the D-number). Ask the operator to delete the parity client in WavePath. With "skip-parity": commit nothing new, run the verify with `PARITY_REPLY=skip-parity` (the explicit skip branch: no flow file holds a recorded response, the replay test reports "no PHP recordings", and no secret is under testdata), and write into the SUMMARY a line `D-14 parity: NOT RUN (skip-parity)` plus a `## Human verification pending` section in the verifier's item format (Test: start WavePath, record every spec flow per testdata/parity/README.md, then run TestPHPParityReplay and TestIDTokenShapeParity with PHASE194_REQUIRE_PARITY=1; Expected: both pass with only decision-backed deviations; Why human: the PHP application and its database run only on the operator's machine). The D-14 truth is a backstop truth: a skip is not evidence, so the phase verdict stays human_needed (or gaps_found) until the recording is made; never describe the skip as passing parity.</action>
|
||||
<verify>
|
||||
<automated>if [ "${PARITY_REPLY:-ready}" = skip-parity ]; then test -z "$(grep -l 'response:' ../sm-oauthserver-plugin/testdata/parity/flows/*.yaml)" && go -C ../sm-oauthserver-plugin test -count=1 -short -run '^TestPHPParityReplay$' -v ./... 2>&1 | grep -q 'no PHP recordings'; else PHASE194_REQUIRE_PARITY=1 go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestPHPParityReplay|TestIDTokenShapeParity)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 2; fi && ! grep -rEl 'oas_cs_[A-Za-z0-9_-]{20,}|oas_at_[A-Za-z0-9_-]{20,}|BEGIN (RSA |EC )?PRIVATE KEY' ../sm-oauthserver-plugin/testdata</automated>
|
||||
<fails_when>Non-zero exit. Default (PARITY_REPLY unset or "ready", fail closed): fewer than two "--- PASS" lines for the replay and id_token shape tests (an unexplained difference, missing recordings, or Docker unavailable). PARITY_REPLY=skip-parity (set only when the human replied "skip-parity"): a flow file already holds a recorded response, or the replay test does not report "no PHP recordings". Either branch: a plaintext secret, access token or private key appears under testdata. Passing the skip branch completes the task but does not prove D-14.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- With "ready": all ten flow files exist and every flow file contains a recorded response (`grep -L 'response:' ../sm-oauthserver-plugin/testdata/parity/flows/*.yaml` prints nothing), and every entry in deviations.yaml carries a `reason:` that cites a D-number (`grep -c 'reason:' deviations.yaml` equals `grep -c 'reason:.*D-[0-9]' deviations.yaml`).
|
||||
- With "skip-parity": `grep -l 'response:' ../sm-oauthserver-plugin/testdata/parity/flows/*.yaml` prints nothing, and 19.4-03-SUMMARY.md contains `D-14 parity: NOT RUN (skip-parity)` and a `## Human verification pending` section naming TestPHPParityReplay (checked when the SUMMARY is written).
|
||||
- Either reply: `F=$(git -C ../sm-oauthserver-plugin ls-files testdata) && printf '%s\n' "$F" | grep -c '\.vars$'` prints 0.
|
||||
</acceptance_criteria>
|
||||
<done>With "ready": the relying-party-visible contract of the PHP plugin is recorded and the Go plugin reproduces it, with every difference explained by a decision. With "skip-parity": nothing is recorded, the skip is checked explicitly, and D-14 is carried to verification as an open human item that keeps the verdict at human_needed.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 7: Security review of the OIDC provider (ASVS L1): every T-19.4 mitigation is present in code and pinned by a test, and gaps are fixed</name>
|
||||
<files>.planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md</files>
|
||||
<read_first>19.4-RESEARCH.md (Security Domain: ASVS categories and known threat patterns), the threat_model blocks of 19.4-01-PLAN.md, 19.4-02-PLAN.md and this plan, ~/.claude/msd-core/references/security-asvs-levels.md, modules/wristband/oidc_*.go, ../sm-oauthserver-plugin/{classes,controllers,console}/*.go, ../sm-oauthserver-plugin/views/*.tmpl, ../fonoteka.go/plugins/golem15/user/classes/session_user.go, the SUMMARYs of plans 01 and 02</read_first>
|
||||
<action>Per SC-4. Walk the ASVS L1 categories (authentication, session management, access control, input validation, cryptography, errors and logging, data protection, API, configuration) across wristband's OIDC files, the plugin and the sm-user-plugin additions. For each threat T-19.4-01..T-19.4-34 and T-19.4-SC record in 19.4-SECURITY-REVIEW.md: the mitigation as built, the file and line that implements it, the test that pins it (name and repository), and a status (verified, fixed in commit {hash}, or accepted with the reason). Also check: no log or error path prints a code, token, secret, consent token or PEM (grep the three repositories for slog calls and fmt.Errorf near these values); every OIDC response that carries a credential has no-store; the consent POST cannot be replayed; the authorize, token and userinfo paths refuse mcp-kind clients; cabana never exposes secret_hash or SigningKey; branding cannot inject markup; the import never prints key material; parity fixtures hold no secrets. Fix every gap as a separate code commit in the repository it belongs to (with a test and README change when the API changes) and re-run that repository's suite; add new findings as T-19.4-36 onward. Commit the review document alone in summercms.go (`docs(19.4): security review`). Optionally note whether the OpenID Foundation conformance suite was run (RESEARCH A11, not required).</action>
|
||||
<verify>
|
||||
<automated>test -s .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md && for n in 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 SC; do grep -q "T-19.4-$n" .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md || { echo "missing T-19.4-$n"; exit 1; }; done && go vet ./... && go test -count=1 -short ./modules/wristband/... && go -C ../sm-oauthserver-plugin test -count=1 -short ./...</automated>
|
||||
<fails_when>Non-zero exit or "missing T-19.4-{n}" printed: the review document is absent or skips a threat, or a fix broke the wristband or plugin suites.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c '| verified |\|| fixed\|| accepted' .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md` prints at least 35.
|
||||
- `grep -ciE 'status: *open|\| open \|' .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md` prints 0 (no threat left open).
|
||||
- `R=$(git log -1 --format=%s -- .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md) && test "$R" = "docs(19.4): security review"` exits 0.
|
||||
</acceptance_criteria>
|
||||
<done>The phase's security claims are checked line by line against the code and tests, and nothing is left open.</done>
|
||||
</task>
|
||||
|
||||
</tasks>
|
||||
|
||||
<threat_model>
|
||||
## Trust Boundaries
|
||||
|
||||
| Boundary | Description |
|
||||
|----------|-------------|
|
||||
| Winter export and key_dir files to the import command | operator-supplied files carrying hashes, private keys and user links |
|
||||
| administrator to the cabana Clients and Branding screens | privileged input that becomes credentials and page content |
|
||||
| scheduler to the prune and rotate commands | unattended jobs on every instance |
|
||||
| PHP recordings to the repository | fixtures captured from a live application with real credentials |
|
||||
|
||||
## STRIDE Threat Register
|
||||
|
||||
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|
||||
|-----------|----------|-----------|----------|-------------|-----------------|
|
||||
| T-19.4-27 | Information disclosure | client secret display | high | mitigate | plaintext generated by IssueOIDCClientCredentials, stored only as SHA-256, parked 5 minutes per administrator and record and forgotten on first read; secret_hash never a field, column or JSON member; TestClientsAdminSmoke |
|
||||
| T-19.4-28 | Information disclosure | import of key_dir | high | mitigate | PEMs read from the operator's directory, public half checked against .pub, private PEM written only through lagoon.NewEncrypted; output names kid and state only; errors name the kid and file, never content |
|
||||
| T-19.4-29 | Tampering | import overwriting live data | medium | mitigate | refuses non-empty tables without --force, --dry-run reports only, one transaction, users must exist (abort with a count) |
|
||||
| T-19.4-30 | Denial of service | key rotation and relying-party caches | medium | mitigate | retired key published for rotation_grace_hours; prune removes it only after; README forbids rotation within an hour of cutover; scheduled rotation off by default |
|
||||
| T-19.4-31 | Information disclosure | parity fixtures | high | mitigate | tide scrub refuses token-shaped values; vars file outside the repositories with mode 0600; the verify command greps testdata for secret, token and key patterns; the parity client is deleted after recording |
|
||||
| T-19.4-32 | Elevation of privilege | admin screens | medium | mitigate | manage_clients and manage_settings permissions on the controllers and the Settings link; kind oidc scope on the Clients queries; SigningKey never registered in cabana |
|
||||
| T-19.4-33 | Repudiation | scheduled jobs on several instances | low | accept | conga's leader-elected scheduler runs each job once; prune and rotate are idempotent within a run, so a duplicate run would only repeat deletions or create one extra retired key |
|
||||
| T-19.4-34 | Denial of service | app.key rotation | low | accept | lagoon.Encrypted decrypts with app.previous_keys; the README requires keeping the previous key; rotating signing keys afterwards re-encrypts new keys with the new app key |
|
||||
| T-19.4-SC | Tampering | Go module installs | high | mitigate | no module is installed in this plan |
|
||||
</threat_model>
|
||||
|
||||
<verification>
|
||||
- Task 1: TestImportWinterCutoverSmoke (old token, old id_token, old secret, original kids).
|
||||
- Task 2: TestClientsAdminSmoke and TestBrandingAdminSmoke.
|
||||
- Task 3: TestRotateAndPruneSmoke and TestScheduleSmoke.
|
||||
- Task 4 to 6: the parity suite prepared, the PHP plugin recorded after the human starts it, the replay and id_token shape tests green, no secrets under testdata. After a skip-parity reply only the explicit skip branch passes; D-14 stays unproven and goes to verification as a human item.
|
||||
- Task 7: the security review document covers every threat; suites green after fixes.
|
||||
</verification>
|
||||
|
||||
<success_criteria>
|
||||
- SC-3: the daily prune is scheduled and removes expired codes, tokens, requests and keys.
|
||||
- SC-4: an existing issuer, its keys (original kids) and client secrets import so relying parties keep working; the phase has a security review with no open threat.
|
||||
- D-14: the Go plugin replays the PHP recordings with only decision-backed deviations. Unmet after skip-parity: the phase verdict is then human_needed (or gaps_found), not passed.
|
||||
</success_criteria>
|
||||
|
||||
<output>
|
||||
Create `.planning/phases/19.4-oidc-provider-on-wristband/19.4-03-SUMMARY.md` when done, with the commits per repository, the human's Task 5 reply (without secrets), the parity result or `D-14 parity: NOT RUN (skip-parity)` with the `## Human verification pending` section from Task 6, the review's fixed and accepted items, which Docker-backed tests ran, and any deviation from this plan's names.
|
||||
</output>
|
||||
264
.planning/phases/19.4-oidc-provider-on-wristband/19.4-04-PLAN.md
Normal file
264
.planning/phases/19.4-oidc-provider-on-wristband/19.4-04-PLAN.md
Normal file
@@ -0,0 +1,264 @@
|
||||
---
|
||||
phase: 19.4-oidc-provider-on-wristband
|
||||
plan: 04
|
||||
type: execute
|
||||
wave: 4
|
||||
depends_on: ["19.4-01", "19.4-02", "19.4-03"]
|
||||
files_modified:
|
||||
- scripts/check-phase19.4.sh
|
||||
- modules/wristband/oidc_discovery_test.go
|
||||
- modules/wristband/oidc_keys_test.go
|
||||
- modules/wristband/oidc_authorize_test.go
|
||||
- modules/wristband/oidc_consent_test.go
|
||||
- modules/wristband/oidc_token_test.go
|
||||
- modules/wristband/oidc_userinfo_test.go
|
||||
- modules/wristband/oidc_subject_test.go
|
||||
- modules/wristband/oidc_redirect_test.go
|
||||
- modules/wristband/oidc_refresh_test.go
|
||||
- modules/wristband/oidc_flavour_test.go
|
||||
- ../sm-oauthserver-plugin/testdata/PHP_METHOD_MAP.md
|
||||
- ../sm-oauthserver-plugin/testdata/php_methods.txt
|
||||
- ../sm-oauthserver-plugin/php_method_map_test.go
|
||||
- ../sm-oauthserver-plugin/authorize_test.go
|
||||
- ../sm-oauthserver-plugin/consent_test.go
|
||||
- ../sm-oauthserver-plugin/token_test.go
|
||||
- ../sm-oauthserver-plugin/userinfo_test.go
|
||||
- ../sm-oauthserver-plugin/discovery_test.go
|
||||
- ../sm-oauthserver-plugin/authorizations_test.go
|
||||
- ../sm-oauthserver-plugin/route_guard_test.go
|
||||
- ../sm-oauthserver-plugin/cascade_test.go
|
||||
- ../sm-oauthserver-plugin/clients_admin_test.go
|
||||
- ../sm-oauthserver-plugin/claims_test.go
|
||||
- ../sm-oauthserver-plugin/keyring_test.go
|
||||
- ../sm-oauthserver-plugin/prune_test.go
|
||||
- ../sm-oauthserver-plugin/subject_test.go
|
||||
- ../sm-oauthserver-plugin/branding_test.go
|
||||
- ../sm-oauthserver-plugin/buckets_test.go
|
||||
- ../sm-oauthserver-plugin/mcp_store_test.go
|
||||
- ../sm-oauthserver-plugin/console/import_winter_test.go
|
||||
- ../sm-oauthserver-plugin/console/commands_test.go
|
||||
- ../sm-oauthserver-plugin/zero_edit_test.go
|
||||
- ../fonoteka.go/plugins/golem15/user/classes/session_user_test.go
|
||||
- ../fonoteka.go/plugins/golem15/user/classes/avatar_url_test.go
|
||||
- ../fonoteka.go/plugins/golem15/user/deactivating_event_test.go
|
||||
- .planning/phases/19.4-oidc-provider-on-wristband/19.4-VALIDATION.md
|
||||
autonomous: true
|
||||
requirements: [SC-1, SC-2, SC-3, SC-4, SC-5, D-02, D-03, D-05, D-07, D-08, D-09, D-10, D-11, D-12, D-13, D-14, D-15, D-17, D-18, D-19]
|
||||
estimate:
|
||||
tokens: 250000
|
||||
raw_tokens: 250000
|
||||
tasks: 5
|
||||
confidence: low
|
||||
must_haves:
|
||||
truths:
|
||||
- "SC-5: the phase's new code has unit tests delivered in this, the last plan: wristband's OIDC flavour over memory fakes, the plugin on Postgres, and the sm-user-plugin additions."
|
||||
- "D-14: every one of the PHP plugin's test methods (25 files under plugins/golem15/oauthserver/tests) appears in testdata/PHP_METHOD_MAP.md with the Go test that ports it (top-level name or name/subtest), or not-applicable with a reason; TestPHPMethodMap fails on a missing, unknown or extra method and on a Go test name that does not exist in either repository."
|
||||
- "Go-only behaviour has its own tests: ES256 and mixed key rings, pairwise subjects, kind isolation in both flavours, opt-in refresh, PHP query encoding and repeated parameters, PEM parsing, the database key ring race, decryption with app.previous_keys, MCP stores, the consent redirect mode, the Winter import with key_dir errors, rotation, prune and schedule."
|
||||
- "D-07, D-09: wristband's existing MCP tests, fonoteka's OAuth tests and the sm-user-plugin suite pass unchanged; an MCP server refuses openid and never emits an id_token."
|
||||
- "scripts/check-phase19.4.sh fails closed: a required test that fails, skips or does not run fails its stage; --self-test proves the detectors on planted output; --all runs every stage and prints NOT RUN for the docker stage without a daemon and for the parity stage without recordings, failing instead when PHASE194_REQUIRE_DOCKER=1 or PHASE194_REQUIRE_PARITY=1; the parity NOT RUN line states that D-14 parity is unproven, and a gate that exits 0 with parity NOT RUN is never evidence for D-14 (the phase verdict stays human_needed)."
|
||||
- "SC-1, SC-5: the gate's docs stage checks the decision note's dependency names, TestDocsTree, summer docs:build --check, and that no wristband source, docs page or plugin file names a consuming application; its userplugin stage proves sm-user-plugin removed no exported function or type since the phase began (D-05)."
|
||||
artifacts:
|
||||
- path: "scripts/check-phase19.4.sh"
|
||||
provides: "fail-closed phase gate across summercms.go, sm-oauthserver-plugin, sm-user-plugin and fonoteka.go"
|
||||
contains: "PHASE194_REQUIRE_DOCKER"
|
||||
- path: "../sm-oauthserver-plugin/testdata/PHP_METHOD_MAP.md"
|
||||
provides: "case-by-case map of the PHP test suite to Go tests"
|
||||
contains: "test_replayed_code_revokes_the_token_previously_issued_from_it"
|
||||
- path: "../sm-oauthserver-plugin/php_method_map_test.go"
|
||||
provides: "TestPHPMethodMap"
|
||||
contains: "TestPHPMethodMap"
|
||||
- path: "modules/wristband/oidc_token_test.go"
|
||||
provides: "TestTokenIssuer, TestPKCEAndReplay, TestPKCEVerifier"
|
||||
contains: "TestPKCEAndReplay"
|
||||
key_links:
|
||||
- from: "scripts/check-phase19.4.sh"
|
||||
to: "../sm-oauthserver-plugin/php_method_map_test.go"
|
||||
via: "the plugin stage requires TestPHPMethodMap by name"
|
||||
pattern: "TestPHPMethodMap"
|
||||
- from: "../sm-oauthserver-plugin/php_method_map_test.go"
|
||||
to: "modules/wristband/oidc_token_test.go"
|
||||
via: "map entries naming wristband tests are checked against the framework's test sources"
|
||||
pattern: "summercms.go/modules/wristband"
|
||||
prohibitions:
|
||||
- statement: "No production behaviour changes in this plan except fixes for defects a new test exposes, each in its own commit with the README change it needs."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
- statement: "Nothing is pushed, tagged or deployed; the release (framework tag, plugin and app pointer bumps, changelog post) waits for the user's go-ahead after verification."
|
||||
status: unresolved
|
||||
verification: judgment
|
||||
---
|
||||
|
||||
## Phase Goal
|
||||
|
||||
ROADMAP Goal (not in user-story format; no story invented, see plan 01): `wristband` is a full OpenID Connect provider that existing relying parties can switch to without noticing: discovery, JWKS with asymmetric signing and key rotation, `id_token`, userinfo, resumable authorization with account switching, a consent store and pairwise subjects. The existing issuer, signing keys and client secrets carry over.
|
||||
|
||||
This plan's slice (plan 4 of 4, wave 4, the project's "unit tests are the last plan" rule): every new piece of the phase gets unit tests, the PHP plugin's test suite is mapped case by case, and one fail-closed gate proves it across the four repositories.
|
||||
|
||||
## Decisions taken in this plan
|
||||
|
||||
- One Go test function per PHP test file, with one subtest per PHP method (subtest names are the PHP method names without the `test_` prefix), so the map stays one line per PHP method and the gate requires about thirty top-level names instead of 166.
|
||||
- Protocol-level PHP cases (PKCE, redirect matching, token issuance, code lifecycle, replay, consent CSRF) run in wristband over memory fakes; cases that need the database, the pages, the admin, the user plugin or config run in the plugin on Postgres. The map says where.
|
||||
- `test_private_key_file_is_not_world_readable` becomes "the private PEM is encrypted at rest and never serialised"; `test_sub_is_public_not_pairwise` becomes "public by default, pairwise only on opt-in"; `test_shared_plugins_are_unedited` becomes the gate's additive check on sm-user-plugin; `test_the_gdpr_scheduled_deletion_path_cascades` maps to the Go user plugin's deletion path if one exists, else not-applicable with that reason; `test_command_exits_zero_and_prints_four_counts_on_an_empty_database` asserts PHP's four lines first and the two Go lines after.
|
||||
- The parity stage of the gate counts as NOT RUN (not failed) when plan 03 recorded no PHP fixtures, unless PHASE194_REQUIRE_PARITY=1, so this plan can finish after a skip-parity reply. NOT RUN only lets the gate exit 0; it does not prove D-14. Plan 03's D-14 truth is a backstop truth whose only evidence is the replay passing with PHASE194_REQUIRE_PARITY=1, so with parity NOT RUN the phase verdict is human_needed (or gaps_found), never passed. The open item stays visible in the gate output and in this plan's SUMMARY as a human verification item.
|
||||
|
||||
## Artifacts this phase produces (this plan)
|
||||
|
||||
- `scripts/check-phase19.4.sh` with stages `go`, `plugin`, `userplugin`, `fonoteka`, `docker`, `parity`, `docs`, `--self-test`, `--all`; environment `PHASE194_ROOT`, `OAUTHSERVER_PLUGIN`, `USER_PLUGIN`, `FONOTEKA`, `PHASE194_REQUIRE_DOCKER`, `PHASE194_REQUIRE_PARITY`.
|
||||
- wristband tests: `TestPKCEVerifier`, `TestRedirectURIMatch`, `TestTokenIssuer`, `TestAuthCodeLifecycle`, `TestPKCEAndReplay`, `TestConsentCSRF`, `TestDiscoveryFields`, `TestJWKSShapes`, `TestKeyPEMParsing`, `TestES256Ring`, `TestMixedRingJWKS`, `TestAuthorizeValidationOrder`, `TestRepeatedQueryParams`, `TestPHPQueryEncoding`, `TestResumeAndSilentConsent`, `TestSwitchAccount`, `TestConsentJSONOperations`, `TestOIDCClientAuthentication`, `TestUserInfoUniform401`, `TestPairwiseSubjects`, `TestRefreshOptIn`, `TestKindIsolation`, `TestFlavourHandlers`, `TestSetOIDCBackendValidation`, `TestMCPRefusesOpenID`.
|
||||
- Plugin tests: `TestAuthorizeStart`, `TestClientRegistry`, `TestConsentOnce`, `TestDiscoveryEndpoint`, `TestDiscoveryDocument`, `TestIncrementalConsent`, `TestRelyingPartyFlow`, `TestRevokeAuthorization`, `TestTokenEndpoint`, `TestUnconfiguredSite`, `TestUserInfoEndpoint`, `TestConsentPageSecurity`, `TestRouteGuard`, `TestUserDeleteCascade`, `TestZeroEditAdditivity`, `TestClaimBuilder`, `TestKeyRing`, `TestKeyRingMultiInstanceRace`, `TestKeyRingPreviousAppKey`, `TestPruneExpired`, `TestSubjectStability`, `TestBrandingSanitisers`, `TestBuckets`, `TestConsentRedirectMode`, `TestMCPStore`, `TestImportWinter`, `TestImportKeyDirErrors`, `TestRotateKeysCommand`, `TestScheduleConfig`, `TestPHPMethodMap`; files `testdata/PHP_METHOD_MAP.md`, `testdata/php_methods.txt`.
|
||||
- sm-user-plugin tests: `TestRequestUser`, `TestEndRequestSession`, `TestAvatarURL`, `TestDeactivatingEvent`.
|
||||
- 19.4-VALIDATION.md per-task map filled, `nyquist_compliant: true`, `wave_0_complete: true`.
|
||||
|
||||
<objective>
|
||||
Deliver the phase's unit tests (project rule: the last plan), port the PHP plugin's test suite case by case, and ship a fail-closed gate that runs everything across summercms.go, sm-oauthserver-plugin, sm-user-plugin and fonoteka.go.
|
||||
|
||||
Purpose: SC-5 (unit tests in the last plan) and the D-14 test map; regression proof for D-07 and D-09.
|
||||
Output: test commits in each repository, the gate script, and the updated VALIDATION.md (planning doc commit).
|
||||
</objective>
|
||||
|
||||
<execution_context>
|
||||
@~/.claude/msd-core/workflows/execute-plan.md
|
||||
@~/.claude/msd-core/templates/summary.md
|
||||
</execution_context>
|
||||
|
||||
<context>
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-VALIDATION.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-01-SUMMARY.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-02-SUMMARY.md
|
||||
@.planning/phases/19.4-oidc-provider-on-wristband/19.4-03-SUMMARY.md
|
||||
|
||||
Repos: summercms.go (wristband tests, gate, VALIDATION.md), ../sm-oauthserver-plugin, ../fonoteka.go/plugins/golem15/user (its own repository; never stage fonoteka.go's superproject pointer). Tests only; a defect a new test exposes is fixed in its own commit in the owning repository with its README change. No co-author tags, stage by path. Docker-backed tests skip under -short; run them on a Docker host (through sudo -u golem if the socket is denied) and record NOT RUN when no daemon answers.
|
||||
|
||||
<interfaces>
|
||||
- PHP tests (read-only): /media/nvme/dev/jz/wavepath.org/plugins/golem15/oauthserver/tests/{feature,security,unit}/*.php — 25 files, about 166 methods (AuthorizeStartTest 11, ClientRegistryTest 12, ConsentOnceTest 6, DiscoveryEndpointTest 4, IncrementalConsentTest 4, JumbojettInteropTest 1, RelyingPartyFlowTest 5, RevokeAuthorizationTest 9, TokenEndpointTest 10, UnconfiguredSiteTest 3, UserInfoEndpointTest 8; ConsentCsrfTest 9, PkceAndReplayTest 6, RedirectUriMatchTest 11, RouteGuardTest 9, UserDeleteCascadeTest 6, ZeroEditAdditivityTest 2; AuthCodeLifecycleTest 5, ClaimBuilderTest 12, DiscoveryDocumentTest 3, KeyRingTest 6, PkceVerifierTest 9, PruneExpiredTest 5, SubjectStabilityTest 5, TokenIssuerTest 10); fixtures in tests/fixtures.
|
||||
- Map analog: ../sm-userfriends-plugin/php_method_map_test.go (TestPHPMethodMap: checked-in method list, optional live tree, map rows regex) and ../sm-chat-plugin/testdata/PHP_METHOD_MAP.md (table format).
|
||||
- Gate analog: scripts/check-phase19.3.sh (stages, go test -json detectors, TAP detector not needed here, NOT RUN handling, self-test, environment overrides).
|
||||
- Test seams from plans 01-03: modules/wristband/oidc_fakes_test.go (memoryOIDCBackend, memoryKeyStore, fakeOIDCHost), ../sm-oauthserver-plugin/harness_test.go (bootOAuth, user and client helpers), ../sm-oauthserver-plugin/testmain_test.go (freshDB), the smoke tests named in each SUMMARY.
|
||||
</interfaces>
|
||||
</context>
|
||||
|
||||
<tasks>
|
||||
|
||||
<task type="tracer">
|
||||
<name>Task 1: Tracer: scripts/check-phase19.4.sh runs every repository's suite and the phase's existing smoke tests by name, and fails when one is missing, skipped or red</name>
|
||||
<files>scripts/check-phase19.4.sh</files>
|
||||
<read_first>scripts/check-phase19.3.sh (whole: stages, run helpers, go test -json detectors, NOT RUN logic, --self-test, environment overrides), the SUMMARYs of plans 01-03 (smoke test names actually created), 19.4-VALIDATION.md, 19.4-RESEARCH.md (Validation Architecture)</read_first>
|
||||
<action>Create scripts/check-phase19.4.sh (bash, set -euo pipefail, NO_COLOR) modelled on check-phase19.3.sh, header comment listing stages and failure rules and naming no application. A `run_required` helper runs `go test -count=1 -json -run '^(names)$'` for a package pattern (with `go -C {repo}` for sibling repositories) and fails the stage on any fail, any skip, zero matched tests, "no tests to run", or a required name without a pass event; subtests count only through their parent. Stages: `go` (summercms.go: go vet ./..., go test -short ./..., the Docker-free wristband names), `plugin` (go -C $OAUTHSERVER_PLUGIN vet ./... and test -short ./..., then the plugin's Docker-free names), `userplugin` (go -C $FONOTEKA vet ./plugins/golem15/user/... and test -short, plus the additive check: in $USER_PLUGIN, the diff since c077029 over *.go files removes no line declaring an exported func, method or type; capture git's status before filtering), `fonoteka` (D-09: go -C $FONOTEKA vet ./... ./plugins/golem15/fonoteka/..., test -short ./plugins/golem15/fonoteka/..., and by name the OAuth tests of plugins/golem15/fonoteka including TestOAuthResourceExplicit), `docker` (Docker host only: the Postgres names in the plugin, the user plugin and fonoteka; without a daemon it prints NOT RUN docker and fails only with PHASE194_REQUIRE_DOCKER=1), `parity` (TestPHPParityReplay and TestIDTokenShapeParity with PHASE194_REQUIRE_PARITY=1 when the flow files carry recorded responses; otherwise it prints `NOT RUN parity: D-14 unproven, phase verdict human_needed until recorded` and fails only with PHASE194_REQUIRE_PARITY=1), `docs` (go test -run '^TestDocsTree$' ./cmd/summer, go run ./cmd/summer docs:build --check, the decision note names golang-jwt/jwt/v5, coreos/go-oidc/v3 and zitadel, and a case-insensitive grep for the consuming applications' names over modules/wristband non-test files, docs/services/oauth-server.md and the plugin's go, md, yaml and tmpl files prints nothing). `--self-test` feeds planted go test -json streams (a fail, a skip, a missing name, zero tests) to the detectors and requires each to be refused. `--all` runs self-test, go, plugin, userplugin, fonoteka, docs, then docker and parity with their NOT RUN rules. Environment overrides PHASE194_ROOT, OAUTHSERVER_PLUGIN (default ../sm-oauthserver-plugin), USER_PLUGIN (default ../fonoteka.go/plugins/golem15/user), FONOTEKA (default ../fonoteka.go). In this task the required-name lists hold the smoke tests plans 01-03 created (from their SUMMARYs); Tasks 2-5 add their names. Commit the script.</action>
|
||||
<verify>
|
||||
<automated>bash -n scripts/check-phase19.4.sh && bash scripts/check-phase19.4.sh --self-test && bash scripts/check-phase19.4.sh go && bash scripts/check-phase19.4.sh plugin && bash scripts/check-phase19.4.sh userplugin && bash scripts/check-phase19.4.sh fonoteka && bash scripts/check-phase19.4.sh docs</automated>
|
||||
<fails_when>Non-zero exit: a syntax error, a self-test detector that accepts planted bad output, or a stage that fails (a smoke test missing, skipped or red, vet red, an sm-user-plugin export removed, fonoteka red, or the docs checks failing).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `bash scripts/check-phase19.4.sh nosuchstage` exits non-zero with a usage line listing go, plugin, userplugin, fonoteka, docker, parity, docs, --self-test and --all.
|
||||
- `grep -c 'TestOIDCTracerSmoke\|TestOIDCFlowSmoke\|TestImportWinterCutoverSmoke' scripts/check-phase19.4.sh` prints at least 3.
|
||||
- Renaming one required test locally (not committed) makes the matching stage exit non-zero; record the check in the SUMMARY.
|
||||
- `grep -c 'PHASE194_REQUIRE_DOCKER\|PHASE194_REQUIRE_PARITY' scripts/check-phase19.4.sh` prints at least 2.
|
||||
- `grep -c 'D-14 unproven' scripts/check-phase19.4.sh` prints at least 1 (the parity NOT RUN line says what it leaves open).
|
||||
</acceptance_criteria>
|
||||
<done>The phase has one gate that proves the whole OIDC provider across four repositories by name and cannot pass on a skipped test.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 2: Unit tests for wristband's OIDC flavour (PHP protocol cases plus Go-only behaviour), wired into the gate</name>
|
||||
<files>modules/wristband/oidc_discovery_test.go, modules/wristband/oidc_keys_test.go, modules/wristband/oidc_authorize_test.go, modules/wristband/oidc_consent_test.go, modules/wristband/oidc_token_test.go, modules/wristband/oidc_userinfo_test.go, modules/wristband/oidc_subject_test.go, modules/wristband/oidc_redirect_test.go, modules/wristband/oidc_refresh_test.go, modules/wristband/oidc_flavour_test.go, scripts/check-phase19.4.sh</files>
|
||||
<read_first>modules/wristband/oidc_*.go and oidc_fakes_test.go, the PHP tests unit/PkceVerifierTest.php, security/RedirectUriMatchTest.php, unit/TokenIssuerTest.php, unit/AuthCodeLifecycleTest.php, security/PkceAndReplayTest.php, security/ConsentCsrfTest.php (cases 1-5), 19.4-01-SUMMARY.md, 19.4-RESEARCH.md (Pattern 2, Pitfalls 2, 3, 5, 13)</read_first>
|
||||
<action>Per D-07, D-08, D-09, D-12, D-14, D-15, D-17; subtests named after the PHP methods without the test_ prefix. PHP ports: `TestPKCEVerifier` (PkceVerifierTest, 9 subtests), `TestRedirectURIMatch` (RedirectUriMatchTest, 11), `TestTokenIssuer` (TokenIssuerTest, 10: header alg and kid, verification against the served JWKS, iss from Options.Issuer, aud string and sub, nonce present and absent, at_hash, exp from IDTokenTTL, oas_at_ hashed and usable, old kid verifies during grace, identity claims cannot overwrite protocol claims), `TestAuthCodeLifecycle` (AuthCodeLifecycleTest, 5), `TestPKCEAndReplay` (PkceAndReplayTest, 6, including revocation of the token issued from a replayed code), `TestConsentCSRF` (ConsentCsrfTest cases 1-5: missing, forged, reused, other user's token, switch account burns the token and leaves the request answerable). Go-only: `TestDiscoveryFields` (exact bytes and order, max-age=3600, public, empty issuer 500 message, refresh fields only when enabled), `TestJWKSShapes` (RSA and EC member order, key-store error gives the fixed 500), `TestKeyPEMParsing` (PKCS#8 RSA and EC, PKCS#1, SEC1, garbage, public mismatch), `TestES256Ring`, `TestMixedRingJWKS` (both kinds, alg list order), `TestAuthorizeValidationOrder` (one case per PHP message in order, and that an unknown client wins over every other error), `TestRepeatedQueryParams` (last wins; state[] absent), `TestPHPQueryEncoding` (space, plus, tilde, slash, unicode, empty description and empty state dropped, no iss), `TestResumeAndSilentConsent` (expired, consumed and missing requests render expired_request; anonymous resume goes to login; silent path touches consent; the consent view excludes openid), `TestSwitchAccount`, `TestConsentJSONOperations` (ConsentRequest and DecideConsent mirror the HTML path, ErrAuthRequestExpired), `TestOIDCClientAuthentication` (Basic case-insensitive scheme, percent-decoding, empty id falls back to the form, missing prefix, dummy comparison path for unknown clients, lowercase realm), `TestUserInfoUniform401` (every failure kind gives the same status, empty body and header), `TestPairwiseSubjects` (sector rules, ErrSectorRequired, stability, userinfo equals id_token sub), `TestRefreshOptIn` (disabled server, client without OfflineAccess gives unauthorized_client, rotation, lineage revocation on replay, scope subset, id_token without nonce), `TestKindIsolation` (both directions at authorize, token and userinfo), `TestFlavourHandlers` (MCP-only handlers 404 on an OIDC server and the reverse), `TestSetOIDCBackendValidation` (MCP server and nil arguments refused), `TestMCPRefusesOpenID` (D-07: invalid_scope, and no id_token member in an MCP token response). Neutral names only. Add every name to the gate's go stage.</action>
|
||||
<verify>
|
||||
<automated>go vet ./... && go test -count=1 -short ./modules/wristband/... && bash scripts/check-phase19.4.sh go && go test -count=1 -short -run '^(TestPKCEAndReplay|TestTokenIssuer|TestRedirectURIMatch|TestKindIsolation|TestRefreshOptIn|TestMCPRefusesOpenID)$' -v ./modules/wristband 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 6</automated>
|
||||
<fails_when>Non-zero exit: vet or the wristband suite red, the gate's go stage fails (a required name missing, skipped or red), or fewer than six sampled top-level tests print "--- PASS".</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `go test -count=1 -short -run '^TestPKCEVerifier$' -v ./modules/wristband 2>&1 | grep -c -- ' --- PASS: TestPKCEVerifier/'` prints 9.
|
||||
- `go test -count=1 -short -run '^TestRedirectURIMatch$' -v ./modules/wristband 2>&1 | grep -c -- ' --- PASS: TestRedirectURIMatch/'` prints 11.
|
||||
- `grep -c 'TestTokenIssuer\|TestConsentCSRF\|TestPairwiseSubjects\|TestFlavourHandlers' scripts/check-phase19.4.sh` prints at least 4.
|
||||
- `grep -rliE 'plytarium|płytarium|fonoteka|wavepath' modules/wristband/oidc_*_test.go` prints nothing.
|
||||
</acceptance_criteria>
|
||||
<done>Every protocol rule of the OIDC flavour, PHP-inherited or Go-only, is pinned by a named test in the framework.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 3: Unit tests for the plugin's relying-party-facing behaviour (PHP feature and security tests on Postgres), wired into the gate</name>
|
||||
<files>../sm-oauthserver-plugin/authorize_test.go, ../sm-oauthserver-plugin/consent_test.go, ../sm-oauthserver-plugin/token_test.go, ../sm-oauthserver-plugin/userinfo_test.go, ../sm-oauthserver-plugin/discovery_test.go, ../sm-oauthserver-plugin/authorizations_test.go, ../sm-oauthserver-plugin/route_guard_test.go, ../sm-oauthserver-plugin/cascade_test.go, ../sm-oauthserver-plugin/clients_admin_test.go, scripts/check-phase19.4.sh</files>
|
||||
<read_first>PHP tests feature/*.php and security/{ConsentCsrfTest (cases 6-9), RouteGuardTest, UserDeleteCascadeTest}.php and tests/fixtures/*.php, ../sm-oauthserver-plugin/harness_test.go and the smoke tests, 19.4-02-SUMMARY.md, 19.4-03-SUMMARY.md</read_first>
|
||||
<action>Per D-03, D-04, D-05, D-08, D-14, D-15, D-18, D-19; Postgres tests skip under -short; subtests named after the PHP methods. Ports: `TestAuthorizeStart` (AuthorizeStartTest 11), `TestClientRegistry` (ClientRegistryTest 12, through the cabana admin API and the model), `TestConsentOnce` (6), `TestDiscoveryEndpoint` (4: content type, max-age=3600, public, unescaped URLs, JWKS with the active kid, unconfigured site still serves), `TestIncrementalConsent` (4), `TestRelyingPartyFlow` (5, including rotation within the grace window), `TestRevokeAuthorization` (9), `TestTokenEndpoint` (10), `TestUnconfiguredSite` (3), `TestUserInfoEndpoint` (8, including groups, communities with and without the userfriends tables, absolute picture), `TestConsentPageSecurity` (ConsentCsrfTest cases 6-9: frame headers, script-tag client name escaped, branding reflected, non-colour setting cannot escape the style block), `TestRouteGuard` (RouteGuardTest 9 with a fixture plugin registering /oauth/{provider} and its callback), `TestUserDeleteCascade` (UserDeleteCascadeTest 6: soft delete through the deactivate bulk action keeps the subject and removes the rest, hard delete removes everything, other users untouched; the GDPR scheduled path ported if the Go user plugin has one, else recorded not-applicable in the map). Go-only: `TestConsentRedirectMode` (redirect to consent_url, JSON show and decide, 410 on an expired request, boot fails without consent_url). Add every name to the gate's docker stage.</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && bash scripts/check-phase19.4.sh plugin && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestAuthorizeStart|TestTokenEndpoint|TestUserInfoEndpoint|TestRevokeAuthorization|TestUserDeleteCascade|TestRouteGuard)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 6</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red, the gate's plugin stage fails, or fewer than six sampled Postgres tests print "--- PASS" (Docker unavailable or a behaviour gap).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `go -C ../sm-oauthserver-plugin test -count=1 -run '^TestAuthorizeStart$' -v ./... 2>&1 | grep -c -- ' --- PASS: TestAuthorizeStart/'` prints 11.
|
||||
- `go -C ../sm-oauthserver-plugin test -count=1 -run '^TestClientRegistry$' -v ./... 2>&1 | grep -c -- ' --- PASS: TestClientRegistry/'` prints 12.
|
||||
- `grep -c 'TestConsentOnce\|TestRelyingPartyFlow\|TestConsentPageSecurity\|TestConsentRedirectMode' scripts/check-phase19.4.sh` prints at least 4.
|
||||
</acceptance_criteria>
|
||||
<done>Everything a relying party, a browser user or an administrator sees from the plugin is pinned case by case against the PHP suite.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 4: Unit tests for the plugin's internals (claims, key ring, subjects, prune, branding, buckets, MCP stores, import and commands) and the complete PHP method map</name>
|
||||
<files>../sm-oauthserver-plugin/claims_test.go, ../sm-oauthserver-plugin/discovery_test.go, ../sm-oauthserver-plugin/keyring_test.go, ../sm-oauthserver-plugin/prune_test.go, ../sm-oauthserver-plugin/subject_test.go, ../sm-oauthserver-plugin/branding_test.go, ../sm-oauthserver-plugin/buckets_test.go, ../sm-oauthserver-plugin/mcp_store_test.go, ../sm-oauthserver-plugin/console/import_winter_test.go, ../sm-oauthserver-plugin/console/commands_test.go, ../sm-oauthserver-plugin/zero_edit_test.go, ../sm-oauthserver-plugin/testdata/PHP_METHOD_MAP.md, ../sm-oauthserver-plugin/testdata/php_methods.txt, ../sm-oauthserver-plugin/php_method_map_test.go, scripts/check-phase19.4.sh</files>
|
||||
<read_first>PHP tests unit/{ClaimBuilderTest, DiscoveryDocumentTest, KeyRingTest, PruneExpiredTest, SubjectStabilityTest}.php and security/ZeroEditAdditivityTest.php, ../sm-userfriends-plugin/php_method_map_test.go, ../sm-chat-plugin/testdata/PHP_METHOD_MAP.md, ../sm-oauthserver-plugin/classes/*.go, console/*.go, buckets.go, modules/lagoon/encrypted.go (previous_keys), 19.4-02-SUMMARY.md, 19.4-03-SUMMARY.md</read_first>
|
||||
<action>Per D-05, D-10..D-13, D-15, D-18, D-19. Ports: `TestClaimBuilder` (12), `TestDiscoveryDocument` (DiscoveryDocumentTest 3: issuer config wins over app.url, trailing slash normalised, every field present), `TestKeyRing` (KeyRingTest 6, with "private key is encrypted at rest and never serialised" in place of the file-mode case), `TestPruneExpired` (5), `TestSubjectStability` (5, "public by default, pairwise only on opt-in"), `TestZeroEditAdditivity` (ZeroEditAdditivityTest: the plugin source names no consuming application; the shared-plugin case points to the gate's userplugin stage). Go-only: `TestKeyRingMultiInstanceRace` (concurrent first-key generation and concurrent rotation leave one active key), `TestKeyRingPreviousAppKey` (a key encrypted under an old app.key decrypts after rotation when app.previous_keys holds it, and fails closed with a fixed error without it), `TestBrandingSanitisers` (table over every sanitiser and the custom CSS cap), `TestBuckets` (the four D-18 buckets: limits, decay, key prefixes, Basic header ignored for the token key, bearer hashed), `TestMCPStore` (CreateWithCap under a concurrent race, sweep, mark consented, issue and exchange, rotation and lineage revocation, kind filter), console `TestImportWinter` (dry run, force, missing users, sequences, JSON columns, kind and sector defaults, settings and logo import) and `TestImportKeyDirErrors` (missing manifest, missing .pub, mismatched halves, duplicate kid, PKCS#1 accepted, output without PEM text), console `TestRotateKeysCommand` (output lines, --prune, failure message) and `TestScheduleConfig`. The map: testdata/php_methods.txt lists every PHP test method (file and name) extracted from the PHP tree; testdata/PHP_METHOD_MAP.md has one row per method with the Go test (Name or Name/subtest), the repository (framework or plugin) and the status (ported, adapted with a one-line reason, or not-applicable with a reason); `TestPHPMethodMap` checks that the list and the map agree one to one, compares the list with the live PHP tree when it exists (path override PHASE194_PHP_OAUTHSERVER), and checks that every named Go test function exists in the plugin's or ../summercms.go/modules/wristband's test sources (override SUMMERCMS_ROOT) and every named subtest appears as a t.Run name. Add every name to the gate (Docker-free names to the plugin stage, Postgres names to the docker stage).</action>
|
||||
<verify>
|
||||
<automated>go -C ../sm-oauthserver-plugin vet ./... && go -C ../sm-oauthserver-plugin test -count=1 -short ./... && bash scripts/check-phase19.4.sh plugin && go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestPHPMethodMap|TestClaimBuilder|TestKeyRing|TestKeyRingPreviousAppKey|TestImportWinter|TestMCPStore)$' -v ./... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 6</automated>
|
||||
<fails_when>Non-zero exit: vet or the short suite red, the gate's plugin stage fails, or fewer than six sampled tests print "--- PASS" (the map is incomplete or names a test that does not exist, or a Postgres test failed or was skipped without Docker).</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `grep -c '^| test_' ../sm-oauthserver-plugin/testdata/PHP_METHOD_MAP.md` equals `grep -c . ../sm-oauthserver-plugin/testdata/php_methods.txt`, and both are at least 160.
|
||||
- `grep -c 'not-applicable' ../sm-oauthserver-plugin/testdata/PHP_METHOD_MAP.md` prints at most 3, and each such row has a reason column that is not empty.
|
||||
- `grep -c 'TestPHPMethodMap\|TestKeyRingPreviousAppKey\|TestImportKeyDirErrors\|TestBuckets' scripts/check-phase19.4.sh` prints at least 4.
|
||||
</acceptance_criteria>
|
||||
<done>Every PHP test method is accounted for in Go, and the plugin's internals have their own tests.</done>
|
||||
</task>
|
||||
|
||||
<task type="auto">
|
||||
<name>Task 5: Unit tests for the sm-user-plugin additions, the full gate green across the four repositories, and the validation map completed</name>
|
||||
<files>../fonoteka.go/plugins/golem15/user/classes/session_user_test.go, ../fonoteka.go/plugins/golem15/user/classes/avatar_url_test.go, ../fonoteka.go/plugins/golem15/user/deactivating_event_test.go, scripts/check-phase19.4.sh, .planning/phases/19.4-oidc-provider-on-wristband/19.4-VALIDATION.md</files>
|
||||
<read_first>../fonoteka.go/plugins/golem15/user/classes/session_user.go, classes/avatar.go, classes/events.go, controllers/registration.go, controllers/users_admin_controller.go, the user plugin's existing tests for analogs (session_test.go, avatar_test.go, admin_users_test.go, classes/events_test.go), 19.4-VALIDATION.md, the SUMMARYs of plans 01-03</read_first>
|
||||
<action>Per D-05. sm-user-plugin tests (committed in its own repository): `TestRequestUser` (valid cookie, auth_token cookie, bearer header, expired, blacklisted, soft-deleted user, anonymous; only infrastructure errors return an error), `TestEndRequestSession` (jti blacklisted until expiry, forget cookie with the configured Domain and Path, no token still forgets, blacklist failure does not fail the call), `TestAvatarURL` (file avatar thumbnail, gravatar fallback with the size, applyAvatar's payload unchanged), `TestDeactivatingEvent` (the deactivate bulk action fires one event per newly deactivated user with the action's transaction, already-deactivated users fire none, a listener error rolls the action back, the event name constant). Add them to the gate's userplugin and docker stages. Run `bash scripts/check-phase19.4.sh --all` on a Docker host and fix any red stage (each fix its own commit in its repository). Update 19.4-VALIDATION.md: fill the per-task verification map with every task of plans 01-04 (task id, plan, wave, SC or D ids, threat refs, automated command, file exists, status), tick the Wave 0 list, keep the manual-only rows (tide recording if NOT RUN, the branding human-check), and set `nyquist_compliant: true` and `wave_0_complete: true` (status stays for /msd-validate-phase); commit it alone as a planning doc. The SUMMARY lists the release steps that wait for the user: push the sm-user-plugin commits (after reconciling with its origin), create and push the sm-oauthserver-plugin repository, tag a framework release with a changelog post, then bump the plugin's summercms require and the application pointers.</action>
|
||||
<verify>
|
||||
<automated>go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/user/... && go -C ../fonoteka.go test -count=1 -run '^(TestRequestUser|TestEndRequestSession|TestAvatarURL|TestDeactivatingEvent)$' -v ./plugins/golem15/user/... 2>&1 | grep -c -- '^--- PASS: Test' | grep -qx 4 && bash scripts/check-phase19.4.sh --all && grep -q '^nyquist_compliant: true' .planning/phases/19.4-oidc-provider-on-wristband/19.4-VALIDATION.md</automated>
|
||||
<fails_when>Non-zero exit: the user plugin's suite red, fewer than four "--- PASS" lines for its new tests (Docker unavailable for the DB-backed ones), any gate stage failing (NOT RUN docker or parity is reported but only fails with the REQUIRE variables; a parity NOT RUN pass completes this task without proving D-14), or VALIDATION.md not marked nyquist_compliant.</fails_when>
|
||||
</verify>
|
||||
<acceptance_criteria>
|
||||
- `bash scripts/check-phase19.4.sh --all` exits 0 and its output contains no line starting with FAIL.
|
||||
- `grep -c '^| 19.4-0[1-4]-' .planning/phases/19.4-oidc-provider-on-wristband/19.4-VALIDATION.md` prints at least 20.
|
||||
- `grep -c 'TestRequestUser\|TestEndRequestSession\|TestAvatarURL\|TestDeactivatingEvent' scripts/check-phase19.4.sh` prints at least 4.
|
||||
- `go test ./... ` in summercms.go, `go -C ../sm-oauthserver-plugin test ./...` and `go -C ../fonoteka.go test ./plugins/golem15/fonoteka/... ./plugins/golem15/user/...` each exit 0 on a Docker host.
|
||||
</acceptance_criteria>
|
||||
<done>The phase is proven by one green gate across every repository it touched, and the validation contract records how.</done>
|
||||
</task>
|
||||
|
||||
</tasks>
|
||||
|
||||
<threat_model>
|
||||
## Trust Boundaries
|
||||
|
||||
| Boundary | Description |
|
||||
|----------|-------------|
|
||||
| test results to the phase verdict | the gate's output decides whether the phase is verified |
|
||||
| sibling repositories to the gate | the gate reads other checkouts through environment overrides |
|
||||
|
||||
## STRIDE Threat Register
|
||||
|
||||
| Threat ID | Category | Component | Severity | Disposition | Mitigation Plan |
|
||||
|-----------|----------|-----------|----------|-------------|-----------------|
|
||||
| T-19.4-35 | Tampering | scripts/check-phase19.4.sh | medium | mitigate | fail-closed detectors (fail, skip, zero tests, missing name), --self-test with planted output, NOT RUN only for docker and parity and only without the REQUIRE variables, git status captured before filtering in the additive check |
|
||||
| T-19.4-SC | Tampering | Go module installs | high | mitigate | no module is installed in this plan; test-only modules stay as approved in plan 02 |
|
||||
</threat_model>
|
||||
|
||||
<verification>
|
||||
- Task 1: the gate's self-test and its Docker-free stages with the smoke tests of plans 01-03.
|
||||
- Tasks 2-4: wristband and plugin unit tests by name, the PHP method map complete.
|
||||
- Task 5: sm-user-plugin tests, `scripts/check-phase19.4.sh --all` green on a Docker host, VALIDATION.md compliant.
|
||||
</verification>
|
||||
|
||||
<success_criteria>
|
||||
- SC-5: unit tests for all new code delivered in the phase's last plan.
|
||||
- D-14: the PHP suite mapped case by case with at most three not-applicable rows, each explained.
|
||||
- D-07, D-09: MCP behaviour, fonoteka and sm-user-plugin unchanged and green.
|
||||
- The phase gate is green with `--all`; docker and parity either ran or are reported NOT RUN. Parity NOT RUN leaves D-14 unproven: the phase verdict is then human_needed, not passed.
|
||||
</success_criteria>
|
||||
|
||||
<output>
|
||||
Create `.planning/phases/19.4-oidc-provider-on-wristband/19.4-04-SUMMARY.md` when done, with the commits per repository, the gate output summary (each stage passed or NOT RUN; when parity is NOT RUN, a `## Human verification pending` section carrying the D-14 recording item from plan 03's SUMMARY), the not-applicable map rows, defects found and fixed, and the release steps that wait for the user's go-ahead.
|
||||
</output>
|
||||
@@ -0,0 +1,669 @@
|
||||
# Phase 19.4: OIDC provider on wristband - Pattern Map
|
||||
|
||||
**Mapped:** 2026-10-19
|
||||
**Files analyzed:** 38 (framework 14, new plugin repo 21, sm-user-plugin 3)
|
||||
**Analogs found:** 34 / 38
|
||||
|
||||
## Plan-time user decisions (recorded here for the planner)
|
||||
|
||||
- **4 plans:** (01) decision note + wristband OIDC engine + tracer; (02) plugin core; (03) admin screens, commands, import, tide parity, security review; (04) unit tests (last plan).
|
||||
- **MCP (OQ1):** the plugin stores implement `wristband.Backend`/`wristband.Tx` with a smoke test; `/oauth/mcp/*` + RFC 8414 metadata are mounted behind a config switch, **off by default**.
|
||||
- **Soft delete (OQ3):** add an additive deactivation event to sm-user-plugin's `DeactivateUsers`; the plugin cascades on it (and on `user.Deleting`).
|
||||
- **Interop test (OQ6):** the go-oidc + x/oauth2 interop test lives in the **plugin repo** (Postgres). The framework keeps a golang-jwt + stdlib JWKS tracer over memory fakes, so the root `go.mod` gains no test deps.
|
||||
|
||||
## Repositories and path roots
|
||||
|
||||
| Root | Tracked in | Notes |
|
||||
|------|-----------|-------|
|
||||
| `summercms.go/` (framework) | this repo | `modules/wristband`, `docs/`, `scripts/`, `.planning/notes/` |
|
||||
| `../sm-oauthserver-plugin/` | **new repo** | module `git.golem15.com/golem15/sm-oauthserver-plugin`, plugin ID `golem15.oauthserver` |
|
||||
| `../fonoteka.go/plugins/golem15/user/` | sm-user-plugin submodule, newest checkout at `c077029` (has `user.Deleting`) | all analog paths below verified with `git ls-files` inside the submodule |
|
||||
| `../fonoteka.go/plugins/golem15/fonoteka/` | fonoteka.go | adapter that must compile unchanged (D-09); only `Resource` gets set explicitly (folded todo) |
|
||||
|
||||
Analog repos used: `../sm-pgstripe-plugin` (plugin skeleton, settings with `lagoon.Encrypted`, import with secrets, go.mod/go.work, testmain), `../sm-faq-plugin` (table import keeping ids, cabana list/form controller, buckets, routes), `../sm-paymentgateway-plugin` (schedule + commands), `../sm-userfriends-plugin` (listening to sm-user-plugin events), `../sm-chat-plugin` (`jwt.auth` + throttle groups).
|
||||
|
||||
## File Classification
|
||||
|
||||
### Framework (`summercms.go`)
|
||||
|
||||
| New/Modified File | Role | Data Flow | Closest Analog | Match Quality |
|
||||
|-------------------|------|-----------|----------------|---------------|
|
||||
| `.planning/notes/2026-10-XX-oidc-on-wristband-golang-jwt.md` | decision note | — | `.planning/notes/2026-10-15-cooler-go-redis-otter.md` (+ `oauth2-wristband-direct-port.md`) | exact |
|
||||
| `modules/wristband/server.go` (modify: neutral `Resource` default, comments, flavour field) | config/service | request-response | itself (lines 20-137) | exact |
|
||||
| `modules/wristband/stores.go` (modify: `Kind` on `ClientRecord`, neutral comments) | model/interface | CRUD | itself (lines 15-31) | exact |
|
||||
| `modules/wristband/client_issue.go` (modify: comments; OIDC `oas_` id / `oas_cs_` secret helpers) | utility | transform | itself (lines 1-31) | exact |
|
||||
| `modules/wristband/oidc_options.go` | config | — | `server.go` Options/DefaultOptions/NewServer/SetBackend (20-137) | exact |
|
||||
| `modules/wristband/oidc_stores.go` | interface | CRUD | `stores.go` (ClientStore..Backend, 79-177) | exact |
|
||||
| `modules/wristband/oidc_discovery.go` | controller | request-response | `server.go` `metadataDocument` + `Metadata` + `writeExactJSON` (139-199) | exact |
|
||||
| `modules/wristband/oidc_keys.go` (KeyStore, JWK encode, signer, id_token) | service | transform | `modules/flare/vapid.go` (ES256 via golang-jwt, 100-117) + RESEARCH Code Examples | role-match |
|
||||
| `modules/wristband/oidc_authorize.go` (start/resume/decide/switch) | controller | request-response | `authorize.go` `Authorize` (25-75), `writeAuthorizeLocalError`/`authorizeErrorRedirect` (175-200); `consent.go` (`PendingRequest`/`IssueCode`/`DenyPending`) | exact |
|
||||
| `modules/wristband/oidc_token.go` | controller | request-response | `token.go` `Token`, `authenticateClient` (150-205), `writeTokenError` (411-417) | exact |
|
||||
| `modules/wristband/oidc_userinfo.go` | controller | request-response | `token.go` client-auth/error writers | role-match |
|
||||
| `modules/wristband/oidc_redirect.go` (PHP `urlencode` + ordered builder, loopback matcher) | utility | transform | `authorize.go` `rfc3986Escape`/`buildOrderedQuery`/`appendOrderedQuery` (227-272) | exact |
|
||||
| `modules/wristband/oidc_*_test.go` + tracer test | test | — | `server_test.go` (exact-bytes metadata), `token_test.go` fixtures, `registration_test.go` `memoryBackend` (20-32) | exact |
|
||||
| `modules/wristband/README.md`, `docs/services/oauth-server.md`, `docs/architecture/introduction.md` | docs | — | existing files (docs rule in CLAUDE.md) | exact |
|
||||
| `scripts/check-phase19.4.sh` | config/test gate | batch | `scripts/check-phase19.3.sh` | exact |
|
||||
| `../fonoteka.go/plugins/golem15/fonoteka/plugin.go` (set `Resource` default if config empty) + test | config | — | itself lines 153-175 | exact |
|
||||
|
||||
### New plugin (`../sm-oauthserver-plugin`)
|
||||
|
||||
| New File | Role | Data Flow | Closest Analog | Match Quality |
|
||||
|----------|------|-----------|----------------|---------------|
|
||||
| `go.mod`, `go.work` | config | — | `../sm-pgstripe-plugin/go.mod`, `go.work` | exact |
|
||||
| `plugin.go` | provider | — | `../sm-pgstripe-plugin/plugin.go` (1-88) + `../sm-faq-plugin/plugin.go` (Buckets 59-77) | exact |
|
||||
| `routes.go` | route | request-response | `../sm-faq-plugin/routes.go`, `../sm-chat-plugin/routes.go:28`, fonoteka `routes.go:376-383` (`GroupRaw`) | exact |
|
||||
| `schedule.go` (prune daily, opt-in rotate) + `Commands()` | config | batch | `../sm-paymentgateway-plugin/schedule.go` + `plugin.go:41,99` | exact |
|
||||
| `admin.go` (AdminFS, Settings item, AdminControllers) | config | — | `../sm-pgstripe-plugin/admin.go` (settings) + `../sm-faq-plugin/admin.go` (controllers) | exact |
|
||||
| `config/config.yaml` | config | — | `../sm-pgstripe-plugin/config/config.yaml` | exact |
|
||||
| `models/registry.go`, `models/*.go` (Client, AuthRequest, AuthCode, AccessToken, Consent, Subject, SigningKey, RefreshToken, Settings) | model | CRUD | `../sm-faq-plugin/models/faq.go` + `registry.go`; `../sm-pgstripe-plugin/models/settings.go` (Encrypted columns) | exact |
|
||||
| `models/client/{columns,fields}.yaml`, `models/settings/fields.yaml` | config (cabana) | — | `../sm-faq-plugin/models/faq/{columns,fields}.yaml`, `../sm-pgstripe-plugin/models/settings/fields.yaml` | exact |
|
||||
| `controllers/clients.go`, `controllers/clients/config_{list,form}.yaml`, `controllers/admin_registry.go` | controller (admin) | CRUD | `../sm-faq-plugin/controllers/faqs.go`, `faqs/config_*.yaml`, `admin_registry.go` | exact |
|
||||
| `updates/registry.go`, `updates/2026101900XX_*.go` | migration | — | `../sm-pgstripe-plugin/updates/registry.go`, `202610130001_create_golem15_pgstripe_settings.go` | exact |
|
||||
| `classes/store.go` (wristband.Backend + OIDCBackend over GORM) | service/adapter | CRUD | `../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go` (25-75, converters 313+) | exact |
|
||||
| `classes/keyring.go` (DB ring, lazy first key, rotate, prune) | service | CRUD | store adapter above + `models/settings.go` Encrypted usage | role-match |
|
||||
| `classes/cascade.go` (user delete/deactivate listener) | event handler | event-driven | `../sm-userfriends-plugin/boot.go:74-89` | exact |
|
||||
| `classes/claims.go` (name, picture, groups, communities, email) | service | transform | sm-user `controllers/api_controller.go` `applyAvatar` (1269-1297), `gravatarURL` (1247) | role-match |
|
||||
| `controllers/consent.go` + `views/consent.html.tmpl`, `views/error.html.tmpl` | controller | request-response (HTML) | none in plugins (see No Analog) | none |
|
||||
| `controllers/authorizations.go` (list/revoke JSON) | controller | CRUD | `../sm-chat-plugin/routes.go` jwt.auth group; sm-user `routes.go:26-28` token index/destroy | role-match |
|
||||
| `console/rotate_keys.go`, `console/prune.go` | command | batch | `../sm-paymentgateway-plugin/console/pg_*.go` | role-match |
|
||||
| `console/import_winter.go` (+ key_dir, + settings/logos flags) | command | file-I/O / batch | `../sm-faq-plugin/console/import_winter.go` (rows + setval), `../sm-pgstripe-plugin/console/import_winter.go` (settings + secrets) | exact |
|
||||
| `scripts/winter-export.sql` | config | file-I/O | `../sm-faq-plugin/scripts/winter-export.sql` | exact |
|
||||
| `lang/en/lang.yaml`, `lang/pl/lang.yaml` | config | — | `../sm-faq-plugin/lang`, `models.LangPrefix` in pgstripe `models/settings.go:14` | exact |
|
||||
| `testmain_test.go`, `*_smoke_test.go`, `interop_test.go` (go-oidc) | test | — | `../sm-pgstripe-plugin/testmain_test.go` (whole file) | exact |
|
||||
| `README.md` | docs | — | `../sm-pgstripe-plugin/README.md` | exact |
|
||||
|
||||
### sm-user-plugin (additive, `../fonoteka.go/plugins/golem15/user`)
|
||||
|
||||
| File | Role | Data Flow | Closest Analog | Match Quality |
|
||||
|------|------|-----------|----------------|---------------|
|
||||
| `classes/events.go` (add `DeactivatingEventName` + `DeactivatingEvent{User, Tx}`) | event | event-driven | same file `DeletingEvent` (11-12, 48-54) | exact |
|
||||
| `classes/admin_actions.go` `DeactivateUsers` (fire event per user) | service | event-driven | `controllers/registration.go` `FireDeletingEvent` (lines ~113-121) | exact |
|
||||
| exported avatar URL helper + optional user resolver (publish on app) | utility | request-response | `controllers/api_controller.go` `applyAvatar`/`gravatarURL`; `plugin.go:76-98` (`app.Publish`, `NewJWTGuard`) | exact |
|
||||
|
||||
## Pattern Assignments
|
||||
|
||||
### `modules/wristband/oidc_options.go` + `server.go` changes (config, D-06/D-09, folded todo)
|
||||
|
||||
**Analog:** `modules/wristband/server.go`
|
||||
|
||||
Options doc style + PHP default comment per field (lines 61-65, to be neutralised):
|
||||
```go
|
||||
// Resource is the expected RFC 8707 resource indicator value authorize
|
||||
// checks an optional resource query parameter against (PHP
|
||||
// config('fonoteka.mcp.resource'), D-03). PHP default:
|
||||
// "https://mcp.plytarium.com/mcp".
|
||||
Resource string
|
||||
```
|
||||
Change `DefaultOptions()` line 100 `Resource: "https://mcp.plytarium.com/mcp"` to `""`; reword lines 1-11 ("ported from Płytarium's…", "fonoteka model") and `stores.go:16-17,154-155,172-174`, `client_issue.go:1-7` to "the host application".
|
||||
|
||||
Constructor + backend seam (lines 108-137) — `SetBackend` has no return value and must stay that way (fonoteka calls it bare). New `NewOIDCServer(opts, oidcOpts)` / `SetOIDCBackend(b) error` sit beside it:
|
||||
```go
|
||||
type Server struct {
|
||||
opts Options
|
||||
backend Backend
|
||||
now func() time.Time
|
||||
randomBytes func(n int) (string, error)
|
||||
}
|
||||
func NewServer(opts Options) *Server {
|
||||
return &Server{opts: opts, now: time.Now, randomBytes: randomBase64URL}
|
||||
}
|
||||
func (s *Server) SetBackend(b Backend) { s.backend = b }
|
||||
```
|
||||
Add unexported `flavour` + `oidcOpts` + `oidcBackend` + `keys KeyStore` fields; keep `now`/`randomBytes` test seams for OIDC too.
|
||||
|
||||
**fonoteka side** (`../fonoteka.go/plugins/golem15/fonoteka/plugin.go:153-175`): already reads `golem15.fonoteka.oauth.resource`; add a Go-side fallback and a test asserting the booted server's resource.
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_stores.go` (interfaces, D-09)
|
||||
|
||||
**Analog:** `modules/wristband/stores.go`
|
||||
|
||||
Record struct style (lines 15-31) — plain app-agnostic structs, pointer for nullable:
|
||||
```go
|
||||
type ClientRecord struct {
|
||||
ID uint
|
||||
ClientID string
|
||||
ClientSecretHash *string // nil for public (auth method "none") clients
|
||||
...
|
||||
RevokedAt *time.Time
|
||||
ScopeCeiling []string // nil/empty means no ceiling
|
||||
CreatedAt time.Time
|
||||
}
|
||||
```
|
||||
Add `Kind string` here (keyed literals in fonoteka `oauth_store.go:313-335` stay source-compatible; `""` = MCP).
|
||||
|
||||
Tx bundle + Backend (lines 162-177) — copy shape for `OIDCTx`/`OIDCBackend` (`WithinOIDCTx`), plus a separate `KeyStore`:
|
||||
```go
|
||||
type Tx interface {
|
||||
ClientStore
|
||||
AuthCodeStore
|
||||
RefreshTokenStore
|
||||
AccessTokenIssuer
|
||||
}
|
||||
type Backend interface {
|
||||
WithinTx(ctx context.Context, fn func(Tx) error) error
|
||||
}
|
||||
```
|
||||
Not-found convention (from adapter `oauth_store.go:62-73`): stores return `(nil, nil)` on not-found, error only on DB failure. Method doc comments name the threat (`T-08-…`) — use `T-19.4-xx`.
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_discovery.go` (controller, request-response)
|
||||
|
||||
**Analog:** `modules/wristband/server.go` lines 139-199
|
||||
|
||||
Ordered struct = wire order (copy technique; field set from RESEARCH Pattern 2 "Discovery"):
|
||||
```go
|
||||
// encoding/json preserves struct declaration order, so this struct is the
|
||||
// single source of truth for the wire order.
|
||||
type metadataDocument struct {
|
||||
Issuer string `json:"issuer"`
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
...
|
||||
}
|
||||
func (s *Server) Metadata(w http.ResponseWriter, r *http.Request) {
|
||||
doc := metadataDocument{ Issuer: s.opts.Issuer, AuthorizationEndpoint: s.opts.Issuer + "/oauth/mcp/authorize", ... }
|
||||
writeExactJSON(w, http.StatusOK, doc, map[string]string{"Cache-Control": "no-cache, private"})
|
||||
}
|
||||
```
|
||||
OIDC: `Cache-Control: max-age=3600, public` (Pitfall 4); `writeExactJSON` (182-199) already uses `SetEscapeHTML(false)` = PHP `JSON_UNESCAPED_SLASHES`. JWKS handler uses the same writer. Empty issuer → 500 with PHP message.
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_keys.go` (service, transform)
|
||||
|
||||
**Analog:** `modules/flare/vapid.go` lines 100-117 (in-tree golang-jwt ES256 signing):
|
||||
```go
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
|
||||
"aud": aud,
|
||||
"exp": now.Add(VAPIDTokenLifetime).Unix(),
|
||||
"sub": subject,
|
||||
})
|
||||
signed, err := token.SignedString(signer)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("flare: sign VAPID token: %w", err)
|
||||
}
|
||||
```
|
||||
Use `jwt.MapClaims` (string `aud`; never `RegisteredClaims`, never flip `jwt.MarshalSingleStringAsArray`), `tok.Header["kid"] = kid`. JWK encoder and `signIDToken` bodies: RESEARCH.md "Code Examples" (lines 471-522). Error prefix convention: `"wristband: ..."` (as `stores.go:13`).
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_authorize.go` (controller, request-response)
|
||||
|
||||
**Analog:** `modules/wristband/authorize.go` + `consent.go`
|
||||
|
||||
Backend-nil guard + client lookup in a Tx, local error before any redirect (lines 31-63):
|
||||
```go
|
||||
func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) {
|
||||
if s.backend == nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
q := r.URL.Query()
|
||||
clientID := q.Get("client_id")
|
||||
var client *ClientRecord
|
||||
if clientID != "" {
|
||||
err := s.backend.WithinTx(ctx, func(tx Tx) error {
|
||||
c, err := tx.ByClientID(ctx, clientID)
|
||||
...
|
||||
})
|
||||
}
|
||||
if client == nil || client.RevokedAt != nil {
|
||||
writeAuthorizeLocalError(w, "Unknown client.")
|
||||
return
|
||||
}
|
||||
```
|
||||
Error redirect (lines 185-199) — OIDC copy must **drop `iss`** and use the PHP `urlencode` encoder, keep `Cache-Control` set before `writeRedirectHTML`:
|
||||
```go
|
||||
func (s *Server) authorizeErrorRedirect(w http.ResponseWriter, redirectURI, errCode, description string, state *string) {
|
||||
pairs := [][2]string{{"error", errCode}, {"error_description", description}, {"iss", s.opts.Issuer}}
|
||||
if state != nil { pairs = append(pairs, [2]string{"state", *state}) }
|
||||
w.Header().Set("Cache-Control", "no-store, private")
|
||||
writeRedirectHTML(w, http.StatusFound, appendOrderedQuery(redirectURI, pairs))
|
||||
}
|
||||
```
|
||||
Local errors in OIDC are rendered by the plugin (HTML, 400) — the engine returns a typed decision (`unknown_client`, `redirect_mismatch`, `inactive_client`, `expired_request`) instead of writing text/plain. Resume/decide/switch are exported operations in the style of `consent.go` `PendingRequest(ctx, requestID, userID)` / `IssueCode(...)` / `DenyPending(...)` (lines 47-130), called by plugin handlers that know the user.
|
||||
|
||||
`writeRedirectHTML` (`redirect_html.go:43-60`) is reused as-is for all OIDC 302s.
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_redirect.go` (utility, transform)
|
||||
|
||||
**Analog:** `authorize.go` lines 227-272
|
||||
```go
|
||||
func rfc3986Escape(s string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if isRFC3986Unreserved(c) { b.WriteByte(c) } else { fmt.Fprintf(&b, "%%%02X", c) }
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
func appendOrderedQuery(uri string, pairs [][2]string) string {
|
||||
sep := "?"
|
||||
if strings.Contains(uri, "?") { sep = "&" }
|
||||
return uri + sep + buildOrderedQuery(pairs)
|
||||
}
|
||||
```
|
||||
Copy into `phpURLEncode` (unreserved = `[A-Za-z0-9._-]`, space → `+`, `~` → `%7E`) and `appendPHPQuery`, dropping empty `error_description`/`state` (Pitfall 2). Do not edit the RFC 3986 versions (MCP bytes).
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_token.go` / `oidc_userinfo.go` (controller, request-response)
|
||||
|
||||
**Analog:** `token.go` lines 156-204 (`authenticateClient`) and 411-417 (`writeTokenError`)
|
||||
```go
|
||||
if authz := r.Header.Get("Authorization"); strings.HasPrefix(authz, "Basic ") {
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authz, "Basic "))
|
||||
...
|
||||
clientID = string(decoded[:idx]); secret = string(decoded[idx+1:])
|
||||
}
|
||||
...
|
||||
if !constantEqual(*client.ClientSecretHash, sha256Hex(secret)) {
|
||||
return nil, errInvalidClient
|
||||
}
|
||||
```
|
||||
OIDC differences: case-insensitive `basic ` prefix, `url.QueryUnescape` both halves, empty id falls back to form, `oas_cs_` prefix gate, dummy compare for unknown clients, `WWW-Authenticate: Basic realm="oauth"`, body `{error, error_description}`, `Cache-Control: no-store, private` + `Pragma: no-cache`, burn-then-check code consume (Pitfall 3). Shared primitives from `crypto.go:15-41` (`randomBase64URL`, `sha256Hex`, `constantEqual`, `s256Challenge`) reused unchanged.
|
||||
|
||||
---
|
||||
|
||||
### `modules/wristband/oidc_*_test.go` (test)
|
||||
|
||||
**Analogs:** `server_test.go:17-50` (exact-bytes const `want` + header asserts), `registration_test.go:20-32` (`memoryBackend` with `sync.Mutex` and slices — add a `memoryOIDCBackend` alongside, don't change the MCP one), `token_test.go:18-175` (fixture helpers `insertTokenTestClient`, `tokenRequest`, `assertTokenError`, `newTokenExchangeFixture`). Tests use neutral issuers (`https://issuer.example.test`) in new files — no app names. Tracer: discovery → JWKS → start → resume → decide → token, then `jwt.Parse` with a keyfunc built from the served JWKS (stdlib), check `at_hash`, `nonce`, `aud` string.
|
||||
|
||||
---
|
||||
|
||||
### `.planning/notes/2026-10-XX-oidc-on-wristband-golang-jwt.md` (decision note)
|
||||
|
||||
**Analog:** `.planning/notes/2026-10-15-cooler-go-redis-otter.md` — header block `# Decision: …`, `**Date:**`, `**Status:** Accepted`, `**Context:** Phase …, RESEARCH Standard Stack and Package Legitimacy Audit`; `## Decision` bullets with module @ version and why; "**X was rejected:**" paragraph; `## Related dependencies` (test-only go-oidc v3.21.0, x/oauth2 v0.37.0 in the plugin repo, installed after a human package check); `## Consequences`. Must say it supersedes STACK.md's zitadel/oidc row for OIDC.
|
||||
|
||||
### `scripts/check-phase19.4.sh` (gate)
|
||||
|
||||
**Analog:** `scripts/check-phase19.3.sh` (header lines 1-40): stages `go`, `docker`, `plugins` (here: `../sm-oauthserver-plugin` and the fonoteka D-09 regression), `docs` (TestDocsTree, `summer docs:build --check`, no-app-name grep), `--self-test`, `--all`, fail-closed on skipped/zero-match/missing required names, `PHASE194_REQUIRE_DOCKER`. Add an SC-1 grep for the decision note.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/go.mod` + `go.work`
|
||||
|
||||
**Analog:** `../sm-pgstripe-plugin/go.mod`, `go.work`
|
||||
```
|
||||
module git.golem15.com/golem15/sm-pgstripe-plugin
|
||||
go 1.27.0
|
||||
require (
|
||||
git.golem15.com/golem15/sm-user-plugin v0.1.1
|
||||
git.golem15.com/golem15/summercms v0.2.2
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
replace git.golem15.com/golem15/summercms => ../summercms.go
|
||||
```
|
||||
go.work:
|
||||
```
|
||||
go 1.27.0
|
||||
use .
|
||||
replace git.golem15.com/golem15/summercms => ../summercms.go
|
||||
replace git.golem15.com/golem15/sm-user-plugin => ../sm-summercmsio-app/plugins/golem15/user
|
||||
```
|
||||
For this phase point sm-user-plugin at the checkout that carries `user.Deleting` + the new deactivation event (`../fonoteka.go/plugins/golem15/user`, Pitfall 10). Add `github.com/golang-jwt/jwt/v5 v5.3.1` direct; go-oidc/x-oauth2 test-only after the human checkpoint.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/plugin.go` (provider)
|
||||
|
||||
**Analog:** `../sm-pgstripe-plugin/plugin.go` lines 1-88 (+ faq `Buckets` 59-77, paymentgateway `Schedule` line 99)
|
||||
```go
|
||||
// Package pgstripe is the golem15.pgstripe plugin: the port of ...
|
||||
package pgstripe
|
||||
|
||||
var (
|
||||
_ party.Plugin = (*Plugin)(nil)
|
||||
_ pact.HasConfig = (*Plugin)(nil)
|
||||
_ pact.HasMigrations = (*Plugin)(nil)
|
||||
_ pact.HasModels = (*Plugin)(nil)
|
||||
_ pact.HasLang = (*Plugin)(nil)
|
||||
_ pact.HasSettings = (*Plugin)(nil)
|
||||
_ pact.HasCommands = (*Plugin)(nil)
|
||||
_ pact.AdminAssets = (*Plugin)(nil)
|
||||
)
|
||||
const PluginID = "golem15.pgstripe"
|
||||
//go:embed config
|
||||
var configFS embed.FS
|
||||
//go:embed lang
|
||||
var langFS embed.FS
|
||||
type Plugin struct { app *backpack.App }
|
||||
func (p *Plugin) ID() string { return PluginID }
|
||||
func (p *Plugin) Requires() []string { return []string{"golem15.paymentgateway"} }
|
||||
func (p *Plugin) Register(app *backpack.App) error { p.app = app; return nil }
|
||||
func (p *Plugin) Boot(app *backpack.App) error { p.app = app; return nil }
|
||||
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
||||
func (p *Plugin) Migrations() []*gormigrate.Migration { return updates.All() }
|
||||
func (p *Plugin) Models() []any { return models.All() }
|
||||
func init() { party.Register(&Plugin{}) }
|
||||
```
|
||||
Here: `PluginID = "golem15.oauthserver"`, `Requires() = {"golem15.user"}`, add `pact.HasRoutes`, `surf.BucketProvider`, `pact.HasSchedule`, `pact.HasAdminControllers`. Boot builds the two `*wristband.Server` values from config (copy fonoteka `plugin.go:153-175` config-layering style: `strings.TrimSuffix(strings.TrimSpace(app.Config.String(...)), "/")`, `if v := app.Config.Int(...); v > 0 {...}`) and wires backends through a **lazy** backend that looks up `*gorm.DB` at request time (fonoteka `plugin.go:255-273` `lazyOAuthBackend` — `*gorm.DB` is published after Boot in the generated main). Publish **one wrapper type** holding both servers, never two `*wristband.Server` (backpack keeps the first; fonoteka looks up `*wristband.Server`). Register the cascade listeners in Boot (see `classes/cascade.go`).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/routes.go` (route)
|
||||
|
||||
**Analogs:** `../sm-faq-plugin/routes.go:16-21`, `../sm-chat-plugin/routes.go:28`, fonoteka `routes.go:376-383`
|
||||
```go
|
||||
// GroupRaw so house envelope/error middleware cannot be attached.
|
||||
r.GroupRaw("/", surf.Use(), func(g pact.Router) {
|
||||
g.Get("/.well-known/oauth-authorization-server", p.oauthServer.Metadata)
|
||||
g.Get("/oauth/mcp/authorize", p.oauthServer.Authorize)
|
||||
g.Post("/oauth/mcp/register", p.oauthServer.Register, "throttle:fonoteka-oauth-register")
|
||||
g.Post("/oauth/mcp/token", p.oauthServer.Token, "throttle:fonoteka-oauth-token")
|
||||
})
|
||||
```
|
||||
```go
|
||||
r.Group(APIPrefix, surf.Use("jwt.auth", "throttle:"+APIBucket), func(g pact.Router) { ... })
|
||||
```
|
||||
Four groups mirroring PHP's auth models (CONTEXT Specifics): public (discovery, JWKS — no middleware), server-to-server (`POST /oauth/token` `throttle:oauth-token` + `body.limit`, `GET /oauth/userinfo` `throttle:oauth-userinfo`), browser (`/oauth/authorize*` `throttle:oauth-authorize`), SPA (`/oauth/authorizations*` `jwt.auth` + `throttle:oauth-authorizations` + `cors:<profile>`). MCP group only `if cfg mcp.enabled` (default false). Port a RouteGuard test against `/oauth/{provider}` shadowing.
|
||||
|
||||
### Buckets (in `plugin.go` or `routes.go`)
|
||||
|
||||
**Analog:** `../sm-faq-plugin/plugin.go:59-77`
|
||||
```go
|
||||
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
||||
trusted := surf.TrustedProxies(nil)
|
||||
if p.app != nil {
|
||||
trusted = surf.TrustedProxies(p.app.Config)
|
||||
}
|
||||
return map[string]surf.Bucket{
|
||||
"faq-public-api": {
|
||||
Name: BucketPublicAPI, Max: 120, Decay: time.Minute,
|
||||
Key: func(r *http.Request) string { return "faq-public|" + surf.ClientIP(r, trusted) },
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
Keys per D-18 / RESEARCH Pattern 6: `oac:`+form `client_id` else `oac-ip:`+IP; `oau:`+sha256hex(bearer) else `oau-ip:`; authorize/authorizations user id (via the optional resolver) else IP. Bucket names are global — keep the `oauth-*` names.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/schedule.go` + console commands
|
||||
|
||||
**Analog:** `../sm-paymentgateway-plugin/schedule.go` (whole file) + `plugin.go:41,99`
|
||||
```go
|
||||
func schedule(p *Plugin) []pact.ScheduledCommand {
|
||||
return []pact.ScheduledCommand{
|
||||
{Command: "pg:cancel-sent-payments", Cadence: pact.Daily()},
|
||||
{Command: "pg:update-currencies", Cadence: pact.Every(10 * time.Minute)},
|
||||
}
|
||||
}
|
||||
func commands(p *Plugin) []bonfire.Command {
|
||||
return []bonfire.Command{ console.CancelSentPayments(p.app), ..., console.ImportWinter(p.app) }
|
||||
}
|
||||
// plugin.go
|
||||
func (p *Plugin) Schedule() []pact.ScheduledCommand { return schedule(p) }
|
||||
```
|
||||
`oauthserver:prune` → `pact.Daily()`; `oauthserver:rotate-keys` → `pact.Every(interval)` appended only when the config interval > 0.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/console/import_winter.go` (command, file-I/O)
|
||||
|
||||
**Analog (rows):** `../sm-faq-plugin/console/import_winter.go` lines 22-143
|
||||
```go
|
||||
type WinterOptions struct { File string; Force bool; DryRun bool }
|
||||
func ImportWinter(app *backpack.App) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "faq:import-winter",
|
||||
Description: "Copy a WinterCMS FAQ export into this application",
|
||||
Flags: []bonfire.Flag{
|
||||
{Name: "file", Description: "FAQ export (JSON lines from scripts/winter-export.sql)"},
|
||||
{Name: "force", Description: "Replace the FAQs the table already holds", Bare: true},
|
||||
{Name: "dry-run", Description: "Report what would be copied without writing", Bare: true},
|
||||
},
|
||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||
opts := WinterOptions{File: flagValue(in, "file"), Force: flagOn(in, "force"), DryRun: flagOn(in, "dry-run")}
|
||||
db, done, err := lookupDB(ctx, app)
|
||||
...
|
||||
_, err = ImportWinterFile(ctx, db, opts, out)
|
||||
return err
|
||||
},
|
||||
}
|
||||
}
|
||||
// existing > 0 && !Force → refuse; DryRun → report; else one db.Transaction:
|
||||
return tx.Exec(`SELECT setval(pg_get_serial_sequence('golem15_faq_faqs', 'id'), COALESCE(MAX(id), 1), MAX(id) IS NOT NULL) FROM golem15_faq_faqs`).Error
|
||||
```
|
||||
`helpers.go` (`flagValue`, `flagOn`, `lookupDB`, `readJSONLines`) copy from `../sm-faq-plugin/console/helpers.go`. Testable `ImportWinterFile(ctx, db, opts, out) (WinterReport, error)` split is the pattern.
|
||||
|
||||
**Analog (secrets/settings):** `../sm-pgstripe-plugin/console/import_winter.go` lines 1-140 — `WinterSettingsItem` constant, `AppKey` option + `lagoon.DecryptLaravelPayload`, masked mapping lines, `--force` for stored secrets. Use for the optional branding-settings import and for writing private PEMs into `lagoon.Encrypted`. Six tables + `--key-dir` (keys.json + `<kid>.key/.pub`, original kids, retired state, PKCS#8→PKCS#1 fallback, pub `Equal` check). Hashes copied as-is (D-19 confirmed).
|
||||
|
||||
**`scripts/winter-export.sql`:** copy header style of `../sm-faq-plugin/scripts/winter-export.sql` (read-only, `mysql -N -B --raw`, JSON_OBJECT one row per line, "check the table names first" block).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/updates/*` (migration)
|
||||
|
||||
**Analog:** `../sm-pgstripe-plugin/updates/registry.go` (whole) + `202610130001_create_golem15_pgstripe_settings.go`
|
||||
```go
|
||||
var createSettings = []*gormigrate.Migration{
|
||||
{
|
||||
ID: "202610130001_create_golem15_pgstripe_settings",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return run(tx, []string{
|
||||
`CREATE TABLE golem15_pgstripe_settings (
|
||||
id INTEGER PRIMARY KEY,
|
||||
...
|
||||
secret_key TEXT NULL,
|
||||
)`,
|
||||
`INSERT INTO golem15_pgstripe_settings (id) VALUES (1)`,
|
||||
})
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`DROP TABLE IF EXISTS golem15_pgstripe_settings`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
func init() { Register(createSettings...) }
|
||||
```
|
||||
Raw SQL only, never AutoMigrate (registry.go doc). Tables `golem15_oauthserver_{clients,auth_requests,auth_codes,access_tokens,consents,subjects,keys,refresh_tokens,settings}`; clients gain `kind`, `subject_type`, `sector_identifier`, `offline_access`, `token_endpoint_auth_method`, `is_dev`; subjects `(user_id, sector)` unique + `sub` unique; keys partial unique index `WHERE active`; keys `private_pem TEXT` (Encrypted ciphertext). Optional seed-first-key migration (Pitfall 6) needs the app key — prefer lazy generation in the keyring.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/models/*` (model)
|
||||
|
||||
**Analogs:** `../sm-faq-plugin/models/faq.go:14-50` (model with `TableName`, `MorphName`, `Fillable`, `Rules`), `models/registry.go` (Register/All), `../sm-pgstripe-plugin/models/settings.go:13-69`
|
||||
```go
|
||||
type FAQ struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Name string `gorm:"column:name"`
|
||||
CreatedAt *time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
func (FAQ) TableName() string { return "golem15_faq_faqs" }
|
||||
func (FAQ) MorphName() string { return `Golem15\FAQ\Models\FAQ` }
|
||||
func (FAQ) Fillable() []string { return []string{"name", "slug", ...} }
|
||||
func (FAQ) Rules() map[string]string { return map[string]string{"name": "required"} }
|
||||
```
|
||||
Encrypted column (pgstripe `settings.go:62`):
|
||||
```go
|
||||
SecretKey lagoon.Encrypted `gorm:"column:secret_key;type:text" json:"-"`
|
||||
```
|
||||
`SigningKey.PrivatePEM lagoon.Encrypted ... json:"-"`, read via `Reveal()`; never register `SigningKey` in any cabana form. `LangPrefix = "golem15.oauthserver::lang."`. Client `MorphName` `Golem15\OAuthServer\Models\Client` (logo attachOne, like sm-user `AttachRelations` avatar `models/user.go:68-70`).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/admin.go` + `controllers/clients.go` (admin, CRUD)
|
||||
|
||||
**Analogs:** `../sm-pgstripe-plugin/admin.go` (Settings item) and `../sm-faq-plugin/admin.go` + `controllers/faqs.go:13-36` + `controllers/admin_registry.go`
|
||||
```go
|
||||
//go:embed controllers/faqs/config_form.yaml controllers/faqs/config_list.yaml models/faq/fields.yaml models/faq/columns.yaml
|
||||
var adminFS embed.FS
|
||||
func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||
return controllers.AdminControllers(func() *backpack.App { if p == nil { return nil }; return p.app })
|
||||
}
|
||||
```
|
||||
```go
|
||||
type faqsAdminController struct{ app func() *backpack.App }
|
||||
func (faqsAdminController) ID() string { return FAQsControllerID }
|
||||
func (faqsAdminController) ModelName() string { return `Golem15\FAQ\Models\FAQ` }
|
||||
func (faqsAdminController) ConfigDir() string { return "controllers/faqs" }
|
||||
func (faqsAdminController) RequiredPermissions() []string { return []string{PermissionFAQs} }
|
||||
func (faqsAdminController) NewRecord() any { return &models.FAQ{} }
|
||||
```
|
||||
```go
|
||||
func (p *Plugin) Settings() []pact.SettingsItem {
|
||||
return []pact.SettingsItem{{
|
||||
Code: SettingsCode, Label: models.LangPrefix + "settings.label", ...,
|
||||
Permissions: []string{PermissionAccessSettings},
|
||||
Form: "models/settings/fields.yaml",
|
||||
NewModel: func() any { return &models.Settings{} },
|
||||
}}
|
||||
}
|
||||
```
|
||||
Client create must show the plaintext secret once (hook `FormAfterCreate`, see faq `controllers/faqs.go:55-60` hook style); regenerate-secret as a danger record action (Phase 18). YAML: copy `config_list.yaml`/`config_form.yaml` headers from faq; stock field types only (`text` for colours with hex validation, `textarea` custom CSS, `fileupload` logo, `checkbox`/`taglist` scopes, `dropdown` kind/subject_type) — RESEARCH OQ9.
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/classes/store.go` (adapter, CRUD)
|
||||
|
||||
**Analog:** `../fonoteka.go/plugins/golem15/fonoteka/classes/auth/oauth_store.go` lines 25-75 (+ converters 313-450)
|
||||
```go
|
||||
type OAuthStore struct { db *gorm.DB }
|
||||
var _ wristband.Backend = (*OAuthStore)(nil)
|
||||
func (s *OAuthStore) WithinTx(ctx context.Context, fn func(wristband.Tx) error) error {
|
||||
if s == nil || s.db == nil {
|
||||
return errors.New("fonoteka: oauth store has no database")
|
||||
}
|
||||
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return fn(&oauthTx{db: tx})
|
||||
})
|
||||
}
|
||||
type oauthTx struct { db *gorm.DB }
|
||||
var _ wristband.Tx = (*oauthTx)(nil)
|
||||
func (t *oauthTx) ByClientID(ctx context.Context, clientID string) (*wristband.ClientRecord, error) {
|
||||
var m models.OAuthClient
|
||||
err := t.db.WithContext(ctx).Where("client_id = ?", clientID).Take(&m).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil }
|
||||
if err != nil { return nil, err }
|
||||
rec := clientModelToRecord(&m)
|
||||
return &rec, nil
|
||||
}
|
||||
```
|
||||
Same `tx` handle for every method; filter `kind` in SQL (`WHERE kind = 'mcp'` for the MCP Tx, `'oidc'` for the OIDC Tx). Atomic consume as `UPDATE … WHERE consumed_at IS NULL AND expires_at > now` checking `RowsAffected == 1`. The MCP `Mint` needs the plugin's own access-token rows (no `inv_` tokens here).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/classes/cascade.go` (event-driven)
|
||||
|
||||
**Analog:** `../sm-userfriends-plugin/boot.go:74-89`
|
||||
```go
|
||||
func bootListeners(p *Plugin, app *backpack.App) error {
|
||||
if app == nil || app.Events == nil { return nil }
|
||||
app.Events.Listen[*userclasses.DeletingEvent](PluginID, p.onUserDeleting)
|
||||
return nil
|
||||
}
|
||||
func (p *Plugin) onUserDeleting(ctx context.Context, ev *userclasses.DeletingEvent) error {
|
||||
if p == nil || ev == nil || ev.User == nil || p.groups == nil { return nil }
|
||||
return p.groups.WithDB(ev.Tx).OnUserDeleting(ctx, ev.User.ID)
|
||||
}
|
||||
```
|
||||
Hard delete: remove subjects, consents, codes, tokens, auth requests in `ev.Tx`. New deactivation event: revoke consents/codes/tokens, keep subjects (PHP `UserCascade.php:127-141`). Test pattern: `../sm-userfriends-plugin/user_deleting_test.go:34` (`env.app.Events.Fire(ctx, &userclasses.DeletingEvent{User: owner, Tx: env.gdb})`).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/classes/claims.go` (transform)
|
||||
|
||||
**Analog:** sm-user `controllers/api_controller.go:1247-1297`
|
||||
```go
|
||||
func gravatarURL(email string, size int) string {
|
||||
sum := md5.Sum([]byte(strings.ToLower(strings.TrimSpace(email))))
|
||||
return fmt.Sprintf("//www.gravatar.com/avatar/%x?s=%d&d=mm", sum, size)
|
||||
}
|
||||
var f attach.File
|
||||
err := gdb.WithContext(ctx).
|
||||
Where("attachment_type = ? AND attachment_id = ? AND field = ?", user.MorphName(), strconv.FormatUint(uint64(user.ID), 10), "avatar").
|
||||
Take(&f).Error
|
||||
...
|
||||
url, err := f.Thumb(ctx, bucket, 128, 128, "auto")
|
||||
```
|
||||
Additive export in sm-user-plugin (e.g. `classes.AvatarURL(ctx, app, user, size) (string, error)`) wrapping this, so the claim builder doesn't re-implement it; `//x` → `https://x`. `communities`: guarded read-only SQL on `golem15_userfriends_*` when `Migrator().HasTable` (RESEARCH A9).
|
||||
|
||||
---
|
||||
|
||||
### sm-user-plugin additive changes
|
||||
|
||||
**`classes/events.go`** (analog: lines 11-12, 48-54):
|
||||
```go
|
||||
const DeletingEventName = "user.Deleting"
|
||||
// DeletingEvent fires from FormAfterDelete before ForceDeleteCleanup /
|
||||
// unscoped delete, inside the same transaction, ...
|
||||
type DeletingEvent struct {
|
||||
User *models.User
|
||||
Tx *gorm.DB
|
||||
}
|
||||
```
|
||||
Add `DeactivatingEventName = "user.Deactivating"` + `DeactivatingEvent{User, Tx}`.
|
||||
|
||||
**`classes/admin_actions.go` `DeactivateUsers`** (lines ~94-113): it has `ctx, db` but no `app`. Keep the signature (additive rule); fire via an optional package-level hook or a new `DeactivateUsersWithEvents(ctx, app, db, users)` that the admin action calls; firing pattern from `controllers/registration.go`:
|
||||
```go
|
||||
func FireDeletingEvent(ctx context.Context, app *backpack.App, user *models.User, tx *gorm.DB) error {
|
||||
if app == nil || app.Events == nil { return nil }
|
||||
return app.Events.Fire(ctx, &classes.DeletingEvent{User: user, Tx: tx})
|
||||
}
|
||||
```
|
||||
**Optional user resolver** (Pattern 4): publish next to the guard in `plugin.go:76-98` (`app.Publish(reg)`, `reg.Register(p.ID(), "jwt", bouncer.NewJWTGuard(secret, classes.GormUsers{App: app}, bl, "token", "auth_token"))`) — publish a small typed resolver wrapping that guard's `Authenticate`; logout/blacklist helper exported for switch-account. All five consuming apps must still build (Pitfall 10).
|
||||
|
||||
---
|
||||
|
||||
### `../sm-oauthserver-plugin/testmain_test.go` (test)
|
||||
|
||||
**Analog:** `../sm-pgstripe-plugin/testmain_test.go` (whole file, 115 lines) — `flag.Parse()` then `testing.Short()`; one `postgres:16-alpine` container; `freshDB(t)` creates a per-test database and drops it `WITH (FORCE)`. Copy verbatim, rename `golem15_pgstripe`/`pgstripe_` → `golem15_oauthserver`/`oauthserver_`. Interop test (`interop_test.go`, go-oidc) uses `freshDB` + an `httptest.Server` per RESEARCH "Interop tracer".
|
||||
|
||||
## Shared Patterns
|
||||
|
||||
### Exact wire bytes
|
||||
**Source:** `modules/wristband/server.go:182-199` (`writeExactJSON`), `redirect_html.go:43-60` (`writeRedirectHTML`)
|
||||
**Apply to:** discovery, JWKS, token, userinfo, all OIDC redirects. Ordered structs for key order; `SetEscapeHTML(false)`; set `Cache-Control` before writing (`max-age=3600, public` public docs; `no-store, private` token/userinfo/consent).
|
||||
|
||||
### Secrets and hashing
|
||||
**Source:** `modules/wristband/crypto.go:15-41`
|
||||
**Apply to:** client secrets, codes, access tokens, consent CSRF digest (`sha256Hex(token + "|" + userID)`), userinfo bucket key. Never log raw values; only `client_id` + IP + fixed reason.
|
||||
|
||||
### At-rest encryption
|
||||
**Source:** `../sm-pgstripe-plugin/models/settings.go:62` (`lagoon.Encrypted ... json:"-"`)
|
||||
**Apply to:** `SigningKey.PrivatePEM`; read with `Reveal()`; key model never in cabana.
|
||||
|
||||
### Plugin registries
|
||||
**Source:** `../sm-faq-plugin/models/registry.go`, `../sm-pgstripe-plugin/updates/registry.go`
|
||||
**Apply to:** `models.Register(...)` / `updates.Register(...)` from each file's `init()`.
|
||||
|
||||
### Lazy DB at request time
|
||||
**Source:** `../fonoteka.go/plugins/golem15/fonoteka/plugin.go:255-273` (`lazyOAuthBackend`)
|
||||
**Apply to:** both wristband backends and the key store in the plugin's Boot.
|
||||
|
||||
### Config keys
|
||||
**Source:** `../sm-pgstripe-plugin/config/config.yaml` header comment (`SUMMER_GOLEM15__PGSTRIPE__<KEY>`) + fonoteka `plugin.go:153-173` override layering
|
||||
**Apply to:** `golem15.oauthserver.{issuer,login_url,rotation_grace_hours,ttl.*,picture_size,consent_mode,consent_url,key_algorithm,rotation_interval,mcp.enabled,oidc_refresh}`; document the PHP env → Go key mapping in the README.
|
||||
|
||||
### Event listening on sm-user-plugin
|
||||
**Source:** `../sm-userfriends-plugin/boot.go:74-89`
|
||||
**Apply to:** cascade on `DeletingEvent` and the new `DeactivatingEvent`.
|
||||
|
||||
### Docs rule
|
||||
**Source:** CLAUDE.md "Documentation rules"
|
||||
**Apply to:** wristband README + `docs/services/oauth-server.md` in the same commit as API changes; no application names in framework files (gate grep).
|
||||
|
||||
## No Analog Found
|
||||
|
||||
| File | Role | Data Flow | Reason / use instead |
|
||||
|------|------|-----------|----------------------|
|
||||
| `../sm-oauthserver-plugin/controllers/consent.go` + `views/consent.html.tmpl`, `views/error.html.tmpl` | controller | request-response (server-rendered HTML) | No plugin renders full HTML pages with `html/template` (paymentgateway `views/mail/*.htm` are mail templates only). Use stdlib `html/template` + `embed`, PHP `views/consent.htm`/`error.htm` as layout source, headers from RESEARCH "Rendered pages", branding sanitisers ported from PHP `Settings::css/color/fontFamily/url` |
|
||||
| `../sm-oauthserver-plugin/classes/keyring.go` (DB key ring) | service | CRUD + crypto | No DB-backed key ring exists; combine adapter pattern + `lagoon.Encrypted` + RESEARCH Pattern 3 (partial unique index, retry on unique violation) |
|
||||
| `modules/wristband/oidc_keys.go` JWK encoder | utility | transform | No JWKS in tree; RESEARCH Code Examples (stdlib) |
|
||||
| Consent CSRF (`ConsentCsrf` port) | utility | transform | No one-shot user-bound CSRF in tree; port PHP `classes/ConsentCsrf.php:54-103` |
|
||||
|
||||
## Metadata
|
||||
|
||||
**Analog search scope:** `summercms.go/modules/{wristband,flare}`, `summercms.go/scripts`, `summercms.go/.planning/notes`, `../sm-pgstripe-plugin`, `../sm-faq-plugin`, `../sm-paymentgateway-plugin`, `../sm-userfriends-plugin`, `../sm-chat-plugin`, `../fonoteka.go/plugins/golem15/{fonoteka,user}`
|
||||
**Files scanned:** ~40
|
||||
**Pattern extraction date:** 2026-10-19
|
||||
@@ -568,17 +568,17 @@ Authorize compares `if resource != nil && *resource != s.opts.Resource` → `inv
|
||||
| A10 | Pairwise subs stored, not HMAC-derived; sector from redirect host or admin-set value, no remote sector_identifier_uri fetch | Pattern 5 | Spec-strictness for dynamically registered pairwise clients (none in 19.4: DCR is MCP-only) |
|
||||
| A11 | OpenID Foundation conformance suite as optional extra oracle | D-16 | None (optional) |
|
||||
|
||||
## Open Questions
|
||||
## Open Questions (RESOLVED)
|
||||
|
||||
1. **How much MCP wiring does the plugin ship in 19.4 (D-02)?** No consumer exists until 19.7 (fonoteka keeps its adapter). The plugin's stores must implement `wristband.Backend`/`Tx` (needs a refresh-tokens table and an MCP access-token mint — PHP has neither). Recommendation: implement the MCP store methods plus a smoke test, mount `/oauth/mcp/*` + RFC 8414 metadata behind a config switch (off by default), and leave MCP access-token *verification* to 19.7. Confirm with the user.
|
||||
2. **`communities` claim source.** PHP reads `Golem15\UserFriends\Models\GroupMember` when present. D-05 forbids a claims-provider interface. Options: read-only SQL against `golem15_userfriends_group_members` ⨝ `golem15_userfriends_groups` (`deleted_at IS NULL`) guarded by `Migrator().HasTable` [VERIFIED table names: `sm-userfriends-plugin/models/group_member.go:27`, `group.go:21`]; or a festival fire-and-collect event (like sm-user-plugin's `GetApiArrayEvent`) that sm-userfriends-plugin answers. Recommendation: the guarded SQL read (mirrors PHP's `class_exists` degrade-to-`[]`); confirm.
|
||||
3. **Soft-delete cascade.** Add an additive `user.Deactivating` (or similar) event to sm-user-plugin's `DeactivateUsers`, or accept that soft-deleted users fail closed at token/userinfo (GORM soft-delete scope) while their consent/token rows linger until hard delete. PHP test `test_soft_delete_removes_consents_codes_and_tokens` expects the former.
|
||||
4. **OIDC refresh (D-17) on the wire.** When disabled server-wide, behave byte-identically to PHP (`unsupported_grant_type` for `refresh_token`; discovery unchanged). When enabled: advertise `refresh_token`/`offline_access`; refresh response includes a fresh `id_token` without `nonce` (OIDC Core §12.2) [CITED: openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse]; a client without offline_access gets `unauthorized_client`? Recommendation: config flag default off; confirm error code.
|
||||
5. **Pairwise sector identifier.** Admin-entered sector string vs fetching a `sector_identifier_uri` JSON (OIDC Core §8.1) through `fetchguard` PublicOnly. Recommendation: admin-entered value in 19.4, require it when redirect hosts differ.
|
||||
6. **Where the interop test lives** (root module go.mod gains go-oidc/x-oauth2 test requires vs plugin repo). Recommendation: wristband keeps a memory-fake tracer using golang-jwt parse + a stdlib JWKS check; the go-oidc interop test lives in the plugin repo against Postgres. Confirm.
|
||||
7. **Optional user resolution seam** (Pattern 4): sm-user-plugin publishes a resolver vs bouncer `Registry.Guard(name)`. Both additive; pick one.
|
||||
8. **Branding settings + logos import** are not in D-19's six tables; include `system_settings` item `golem15_oauthserver_settings` and `system_files` attachments in `import-winter`? Recommendation: yes, optional flags.
|
||||
9. **cabana widgets.** PHP uses `colorpicker`, `codeeditor`, `checkboxlist`; cabana's form types are `text, textarea, number, checkbox, switch, dropdown, relation, relation-manager, widget, partial, fileupload, datepicker, password, permissioneditor, markdown, mltext, mltextarea, mlmarkdown, richeditor, repeater, money, taglist` [VERIFIED: `modules/cabana/form_schema.go:24-30`]. Use `text` (validated hex) for colours, `textarea` for custom CSS, `taglist`/`checkbox` per scope — or add widgets to cabana (scope creep). Recommendation: stock types.
|
||||
1. **How much MCP wiring does the plugin ship in 19.4 (D-02)?** No consumer exists until 19.7 (fonoteka keeps its adapter). The plugin's stores must implement `wristband.Backend`/`Tx` (needs a refresh-tokens table and an MCP access-token mint — PHP has neither). Recommendation: implement the MCP store methods plus a smoke test, mount `/oauth/mcp/*` + RFC 8414 metadata behind a config switch (off by default), and leave MCP access-token *verification* to 19.7. Confirm with the user. — RESOLVED (user decision at plan time): the plugin ships the MCP stores plus a smoke test; `/oauth/mcp/*` and RFC 8414 metadata are mounted only when `golem15.oauthserver.mcp.enabled` is true (default false); MCP access-token verification stays with 19.7. Owner: plan 02 Task 3.
|
||||
2. **`communities` claim source.** PHP reads `Golem15\UserFriends\Models\GroupMember` when present. D-05 forbids a claims-provider interface. Options: read-only SQL against `golem15_userfriends_group_members` ⨝ `golem15_userfriends_groups` (`deleted_at IS NULL`) guarded by `Migrator().HasTable` [VERIFIED table names: `sm-userfriends-plugin/models/group_member.go:27`, `group.go:21`]; or a festival fire-and-collect event (like sm-user-plugin's `GetApiArrayEvent`) that sm-userfriends-plugin answers. Recommendation: the guarded SQL read (mirrors PHP's `class_exists` degrade-to-`[]`); confirm. — RESOLVED: guarded read-only SQL on the two `golem15_userfriends_*` tables (`deleted_at IS NULL`), `[]` when either table is missing, no import of sm-userfriends-plugin. Owner: plan 02 Task 2.
|
||||
3. **Soft-delete cascade.** Add an additive `user.Deactivating` (or similar) event to sm-user-plugin's `DeactivateUsers`, or accept that soft-deleted users fail closed at token/userinfo (GORM soft-delete scope) while their consent/token rows linger until hard delete. PHP test `test_soft_delete_removes_consents_codes_and_tokens` expects the former. — RESOLVED (user decision at plan time): additive `user.Deactivating` event fired by sm-user-plugin's deactivate bulk action (`controllers.FireDeactivatingEvent`, `DeactivateUsers` keeps its signature); the plugin removes consents, codes and tokens on it. Owner: plan 02 Task 3.
|
||||
4. **OIDC refresh (D-17) on the wire.** When disabled server-wide, behave byte-identically to PHP (`unsupported_grant_type` for `refresh_token`; discovery unchanged). When enabled: advertise `refresh_token`/`offline_access`; refresh response includes a fresh `id_token` without `nonce` (OIDC Core §12.2) [CITED: openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse]; a client without offline_access gets `unauthorized_client`? Recommendation: config flag default off; confirm error code. — RESOLVED: server switch `OIDCOptions.RefreshEnabled` (plugin key `golem15.oauthserver.refresh.enabled`, default false; off is byte-identical to PHP); a client without `offline_access` asking for the grant gets `unauthorized_client`. Owners: plan 01 Task 3 (engine), plan 02 Task 1 (config key).
|
||||
5. **Pairwise sector identifier.** Admin-entered sector string vs fetching a `sector_identifier_uri` JSON (OIDC Core §8.1) through `fetchguard` PublicOnly. Recommendation: admin-entered value in 19.4, require it when redirect hosts differ. — RESOLVED: the administrator enters the sector; without it the single redirect host is the sector, and differing hosts give `ErrSectorRequired`; no `sector_identifier_uri` fetch in 19.4. Owners: plan 01 Task 3 (`SubjectSector`), plan 03 Task 2 (admin field and save-time check).
|
||||
6. **Where the interop test lives** (root module go.mod gains go-oidc/x-oauth2 test requires vs plugin repo). Recommendation: wristband keeps a memory-fake tracer using golang-jwt parse + a stdlib JWKS check; the go-oidc interop test lives in the plugin repo against Postgres. Confirm. — RESOLVED (user decision at plan time): go-oidc and x/oauth2 are test-only requirements of sm-oauthserver-plugin; the framework go.mod gains nothing and wristband keeps the golang-jwt plus stdlib JWKS tracer. Owners: plan 01 Task 1 (wristband tracer), plan 02 Tasks 4-5 (legitimacy check, `TestRelyingPartyInterop`).
|
||||
7. **Optional user resolution seam** (Pattern 4): sm-user-plugin publishes a resolver vs bouncer `Registry.Guard(name)`. Both additive; pick one. — RESOLVED: sm-user-plugin exports `classes.RequestUser` and `classes.EndRequestSession` on its own JWT guard configuration; no bouncer API change. Owner: plan 02 Task 1.
|
||||
8. **Branding settings + logos import** are not in D-19's six tables; include `system_settings` item `golem15_oauthserver_settings` and `system_files` attachments in `import-winter`? Recommendation: yes, optional flags. — RESOLVED: `import-winter` gains optional `--settings` (the `golem15_oauthserver_settings` item) and `--uploads-dir` (Winter storage path for `system_files` logos). Owner: plan 03 Task 2.
|
||||
9. **cabana widgets.** PHP uses `colorpicker`, `codeeditor`, `checkboxlist`; cabana's form types are `text, textarea, number, checkbox, switch, dropdown, relation, relation-manager, widget, partial, fileupload, datepicker, password, permissioneditor, markdown, mltext, mltextarea, mlmarkdown, richeditor, repeater, money, taglist` [VERIFIED: `modules/cabana/form_schema.go:24-30`]. Use `text` (validated hex) for colours, `textarea` for custom CSS, `taglist`/`checkbox` per scope — or add widgets to cabana (scope creep). Recommendation: stock types. — RESOLVED: stock cabana field types only (`text` with a hex rule for colours, `textarea` for custom CSS and redirect URIs, `switch`, `dropdown`, `fileupload`, scopes as checkboxes or a fixed-option taglist); no new cabana widgets. Owner: plan 03 Task 2.
|
||||
|
||||
## Environment Availability
|
||||
|
||||
|
||||
@@ -42,13 +42,27 @@ Filled in by the planner per task; seed rows from RESEARCH.md "Phase Requirement
|
||||
|
||||
| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status |
|
||||
|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------|
|
||||
| 19.4-01-xx | 01 | 1 | SC-1 | — | decision note names deps | gate script | `scripts/check-phase19.4.sh` | ❌ W0 | ⬜ pending |
|
||||
| 19.4-01-xx | 01 | 1 | SC-2 | T-19.4-xx | id_token signed RS256/ES256, aud=client_id, nonce, at_hash | unit | `go test -short ./modules/wristband -run 'TestOIDC(Discovery\|JWKS\|IDToken)'` | ❌ | ⬜ pending |
|
||||
| 19.4-01-xx | 01 | 1 | D-09 | — | MCP flow unchanged | regression | `go test -short ./modules/wristband/... && (cd ../fonoteka.go && go vet ./... && go test -short ./...)` | ✅ | ⬜ pending |
|
||||
| 19.4-02-xx | 02 | 2 | SC-2 | T-19.4-xx | RP library verifies id_token | interop | plugin `go test ./... -run TestRelyingPartyInterop` | ❌ | ⬜ pending |
|
||||
| 19.4-02-xx | 02 | 2 | SC-3 | T-19.4-xx | CSRF one-shot, kind isolation, cross-user revoke 404 | Postgres smoke | plugin `go test ./... -run 'Test(Authorize\|Consent\|Switch\|Authorizations\|Subject)'` | ❌ | ⬜ pending |
|
||||
| 19.4-03-xx | 03 | 3 | SC-3/SC-4 | T-19.4-xx | prune, rotate, import keeps kids and tokens | Postgres smoke | plugin `go test ./console -run 'Test(Prune\|RotateKeys\|ImportWinter)'` | ❌ | ⬜ pending |
|
||||
| 19.4-04-xx | 04 | 4 | SC-5 | — | PHP test map ported | unit | `go test ./...` (both repos) + `go test ./cmd/summer -run TestDocsTree` | ❌ | ⬜ pending |
|
||||
| 19.4-01-01 | 01 | 1 | SC-1, SC-2, D-06, D-09, D-16 | T-19.4-07, T-19.4-08, T-19.4-SC | decision note before code; id_token verifies against served JWKS; aud string, nonce, at_hash | tracer (memory fakes) | `go test -count=1 -short -run '^TestOIDCTracerSmoke$' -v ./modules/wristband` | ❌ W0 | ⬜ pending |
|
||||
| 19.4-01-02 | 01 | 1 | SC-3, D-04, D-07, D-08, D-14 | T-19.4-01, T-19.4-04, T-19.4-05 | rendered local errors, one-shot consent token, kind isolation, PHP encoding | smoke | `go test -count=1 -short -run '^(TestOIDCAuthorizeStartSmoke\|TestOIDCResumeDecideSwitchSmoke\|TestKindIsolationSmoke\|TestPHPRedirectEncodingSmoke)$' ./modules/wristband` | ❌ | ⬜ pending |
|
||||
| 19.4-01-03 | 01 | 1 | SC-2, D-12, D-15, D-17 | T-19.4-02, T-19.4-03, T-19.4-06, T-19.4-10, T-19.4-12 | burn-then-check replay revocation, uniform 401, mixed rings, pairwise, opt-in refresh | smoke | `go test -count=1 -short -run '^(TestOIDCTokenErrorsSmoke\|TestOIDCReplayRevokesSmoke\|TestOIDCUserInfoSmoke\|TestMixedKeyRingSmoke\|TestPairwiseSubjectSmoke\|TestOIDCRefreshOptInSmoke)$' ./modules/wristband` | ❌ | ⬜ pending |
|
||||
| 19.4-01-04 | 01 | 1 | SC-5, D-09, folded todo | T-19.4-14 | neutral Resource default; fonoteka unchanged | regression + docs | `go -C ../fonoteka.go test -count=1 -short ./plugins/golem15/fonoteka/... && go test -count=1 -run '^TestDocsTree$' ./cmd/summer` | ✅ | ⬜ pending |
|
||||
| 19.4-02-01 | 02 | 2 | SC-2, D-01, D-02, D-10, D-19 | T-19.4-15, T-19.4-16 | encrypted private PEM, one active key under a race | tracer (Postgres) | `go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestOIDCFlowSmoke\|TestKeyRingFirstKeyRaceSmoke)$' ./...` | ❌ W0 | ⬜ pending |
|
||||
| 19.4-02-02 | 02 | 2 | D-03, D-04, D-05, D-18 | T-19.4-17, T-19.4-18, T-19.4-20, T-19.4-21, T-19.4-22, T-19.4-25 | frame headers, sanitised branding, login handoff, switch blacklists jti, bucket keys, route guard | Postgres smoke | `go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestConsentPageBrandingSmoke\|TestLoginHandoffAndSwitchSmoke\|TestBucketKeysSmoke\|TestRouteGuardSmoke)$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-02-03 | 02 | 2 | SC-3, D-02, D-05, D-06 | T-19.4-19, T-19.4-23, T-19.4-24, T-19.4-26 | cross-user revoke 404, cascade on delete and deactivate, MCP off by default | Postgres smoke | `go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestAuthorizationsSmoke\|TestUserCascadeSmoke\|TestMCPStoreSmoke)$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-02-04 | 02 | 2 | D-16 | T-19.4-SC | blocking human package check before go-oidc and x/oauth2 | checkpoint | — (human reply recorded in SUMMARY) | — | ⬜ pending |
|
||||
| 19.4-02-05 | 02 | 2 | SC-2, D-16 | T-19.4-07 | stock RP verifies id_token and at_hash with RS256 and ES256 | interop | `go -C ../sm-oauthserver-plugin test -count=1 -run '^TestRelyingPartyInterop$' -v ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-01 | 03 | 3 | SC-4, D-11, D-19 | T-19.4-28, T-19.4-29 | original kids, old tokens and secrets work after import | tracer (Postgres) | `go -C ../sm-oauthserver-plugin test -count=1 -run '^TestImportWinterCutoverSmoke$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-02 | 03 | 3 | D-03, D-08 | T-19.4-27, T-19.4-32 | secret revealed once, hash never exposed, permissions | Postgres smoke | `go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestClientsAdminSmoke\|TestBrandingAdminSmoke)$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-03 | 03 | 3 | SC-3, D-13 | T-19.4-30, T-19.4-33 | grace window, daily prune, opt-in rotation | Postgres smoke | `go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestRotateAndPruneSmoke\|TestScheduleSmoke)$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-04 | 03 | 3 | D-14 | T-19.4-31 | parity suite prepared, replay skips without recordings | setup | `go -C ../sm-oauthserver-plugin test -count=1 ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-05 | 03 | 3 | D-14 | T-19.4-31 | human starts WavePath; vars file mode 0600 outside the repos | checkpoint | — (human action) | — | ⬜ pending |
|
||||
| 19.4-03-06 | 03 | 3 | D-14 | T-19.4-31 | Go replays PHP recordings; no secrets under testdata | parity | `PHASE194_REQUIRE_PARITY=1 go -C ../sm-oauthserver-plugin test -count=1 -run '^(TestPHPParityReplay\|TestIDTokenShapeParity)$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-03-07 | 03 | 3 | SC-4 | all T-19.4 | ASVS L1 review, every threat verified, fixed or accepted | review | `test -s .planning/phases/19.4-oidc-provider-on-wristband/19.4-SECURITY-REVIEW.md` | ❌ | ⬜ pending |
|
||||
| 19.4-04-01 | 04 | 4 | SC-5 | T-19.4-35 | gate fails closed on skip, fail, missing name | gate | `bash scripts/check-phase19.4.sh --self-test` | ❌ W0 | ⬜ pending |
|
||||
| 19.4-04-02 | 04 | 4 | SC-5, D-07, D-08, D-12, D-15, D-17 | T-19.4-01..14 | wristband PHP protocol cases and Go-only cases | unit | `bash scripts/check-phase19.4.sh go` | ❌ | ⬜ pending |
|
||||
| 19.4-04-03 | 04 | 4 | SC-5, D-03, D-04, D-05, D-14 | T-19.4-17..25 | plugin feature and security cases on Postgres | unit | `bash scripts/check-phase19.4.sh docker` | ❌ | ⬜ pending |
|
||||
| 19.4-04-04 | 04 | 4 | SC-5, D-10..D-13, D-18, D-19 | T-19.4-15, T-19.4-16, T-19.4-27..30 | internals and the complete PHP method map | unit | `go -C ../sm-oauthserver-plugin test -count=1 -run '^TestPHPMethodMap$' ./...` | ❌ | ⬜ pending |
|
||||
| 19.4-04-05 | 04 | 4 | SC-5, D-05, D-09 | T-19.4-26 | sm-user-plugin additions tested; full gate green | unit + gate | `bash scripts/check-phase19.4.sh --all` | ❌ | ⬜ pending |
|
||||
|
||||
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
|
||||
|
||||
@@ -57,7 +71,7 @@ Filled in by the planner per task; seed rows from RESEARCH.md "Phase Requirement
|
||||
## Wave 0 Requirements
|
||||
|
||||
- [ ] New repo `sm-oauthserver-plugin` with `go.mod`, `go.work`/replace to `../summercms.go`, `testmain_test.go`
|
||||
- [ ] Decision note `.planning/notes/2026-10-XX-oidc-on-wristband-golang-jwt.md`
|
||||
- [ ] Decision note `.planning/notes/2026-10-19-oidc-on-wristband-golang-jwt.md`
|
||||
- [ ] `scripts/check-phase19.4.sh` (named-test detector, fail-closed like 19.3)
|
||||
- [ ] Human verification before adding `coreos/go-oidc/v3` and `golang.org/x/oauth2` (test-only)
|
||||
|
||||
|
||||
52
.planning/phases/19.4-oidc-provider-on-wristband/COVERAGE.md
Normal file
52
.planning/phases/19.4-oidc-provider-on-wristband/COVERAGE.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# API Coverage — OpenID Connect provider surface (wristband OIDC flavour + sm-oauthserver-plugin)
|
||||
|
||||
> Full coverage by default. Opt-outs are explicit, reasoned decisions.
|
||||
|
||||
No external API integration: phase 19.4 implements an OpenID Connect provider; it calls no third-party service at runtime. The detector matched because the plans talk about OAuth endpoints, MCP and "wire bytes" of our own surface. The only outside libraries are golang-jwt v5 (already in go.mod, used to sign) and, test-only, go-oidc v3.21.0 with x/oauth2 v0.37.0 acting as a stock relying party (plan 02, after a blocking human package check).
|
||||
|
||||
The "API" that matters here is the relying-party-visible contract of the PHP `Golem15.OAuthServer` plugin, which D-14 makes the acceptance test. The matrix below records which OIDC and OAuth capabilities the Go provider implements (INTEGRATE) and which it leaves out on purpose (OPT-OUT), so a relying party's expectations can be checked against it.
|
||||
|
||||
| capability | decision | reason |
|
||||
|---|---|---|
|
||||
| discovery: /.well-known/openid-configuration with PHP's 14 fields in PHP order, Cache-Control max-age=3600, public | INTEGRATE | D-14; plan 01 |
|
||||
| discovery: subject_types_supported public and pairwise | INTEGRATE | D-15 (beyond PHP, roadmap asks for pairwise) |
|
||||
| discovery: id_token_signing_alg_values_supported from the key ring | INTEGRATE | D-12 |
|
||||
| discovery: refresh_token grant and offline_access scope advertised | INTEGRATE | only when refresh.enabled (D-17); otherwise byte-identical to PHP |
|
||||
| jwks: active key plus retired keys inside the grace window, RSA and EC JWKs with use, alg, kid | INTEGRATE | D-12, D-13 |
|
||||
| authorize: authorization code with mandatory S256 PKCE, PHP validation order and messages | INTEGRATE | D-14 |
|
||||
| authorize: rendered local errors for unknown client, redirect mismatch, inactive client, expired request | INTEGRATE | RFC 6749 §4.1.2.1 as PHP |
|
||||
| authorize: login handoff to login_url with only the resume path | INTEGRATE | D-04 |
|
||||
| authorize: resume, silent consent, incremental consent, deny, switch account | INTEGRATE | D-04, SC-3 |
|
||||
| authorize: one-shot consent CSRF token bound to the user | INTEGRATE | PHP ConsentCsrf |
|
||||
| authorize: SPA consent mode (redirect to the app's consent page plus JSON endpoints) | INTEGRATE | D-03 option |
|
||||
| authorize: is_dev loopback port exception | INTEGRATE | PHP RedirectUriMatcher |
|
||||
| authorize: prompt, max_age, login_hint, resource parameters | OPT-OUT | PHP ignores them; parity (D-14) |
|
||||
| authorize: response_type token or id_token (implicit, hybrid) | OPT-OUT | code flow only, as PHP; implicit is deprecated by OAuth 2.1 |
|
||||
| authorize: response_mode fragment or form_post | OPT-OUT | PHP advertises query only |
|
||||
| authorize: request objects (JAR) and pushed authorization requests (PAR) | OPT-OUT | not in the PHP contract; no relying party uses them |
|
||||
| authorize: PKCE plain | OPT-OUT | S256 only (PHP and OAuth 2.1) |
|
||||
| token: authorization_code grant with client_secret_basic and client_secret_post | INTEGRATE | PHP contract |
|
||||
| token: refresh_token grant with rotation and lineage revocation | INTEGRATE | opt-in per client and per server (D-17) |
|
||||
| token: client_secret_jwt, private_key_jwt, none (public OIDC clients) | OPT-OUT | PHP accepts confidential clients only; public clients stay on the MCP flavour |
|
||||
| token: burn-then-check code redemption and replay revocation | INTEGRATE | PHP PkceAndReplay contract |
|
||||
| id_token: iss, sub, aud (string), exp, iat, nonce, at_hash, allowlisted identity claims | INTEGRATE | PHP TokenIssuer |
|
||||
| id_token: auth_time, azp, acr, amr, jti | OPT-OUT | PHP emits none; adding them changes the claim set relying parties see |
|
||||
| id_token: ES256 signing | INTEGRATE | D-12 (configurable for new keys) |
|
||||
| id_token: encryption (JWE) | OPT-OUT | not in the PHP contract |
|
||||
| userinfo: GET with Bearer, scope-filtered claims, uniform 401 with empty body | INTEGRATE | PHP contract |
|
||||
| userinfo: POST, signed or encrypted responses | OPT-OUT | PHP serves GET only and plain JSON |
|
||||
| claims parameter, distributed and aggregated claims | OPT-OUT | not in the PHP contract |
|
||||
| authorized apps: GET /oauth/authorizations and DELETE /oauth/authorizations/{client_id} | INTEGRATE | SC-3, PHP AuthorizationsController |
|
||||
| OPTIONS preflight on /oauth/authorizations without a CORS profile | OPT-OUT | pact.Router has no OPTIONS verb; with cors_profile set the surf CORS profile answers preflight; recorded as a parity deviation |
|
||||
| key management: database ring, lazy first key, rotate-keys, grace window, prune | INTEGRATE | D-10, D-13 |
|
||||
| scheduled rotation | INTEGRATE | opt-in through rotation_interval (D-13) |
|
||||
| scheduled prune of codes, tokens, requests, retired keys | INTEGRATE | SC-3 |
|
||||
| import of the six PHP tables, key_dir with original kids, branding settings and logos | INTEGRATE | D-11, D-19, RESEARCH OQ8 |
|
||||
| token introspection (RFC 7662) | OPT-OUT | access tokens are opaque and used only at userinfo, as PHP |
|
||||
| token revocation endpoint (RFC 7009) | OPT-OUT | not in the PHP contract; users revoke through /oauth/authorizations |
|
||||
| RP-initiated logout, end_session_endpoint, check_session, front- and back-channel logout | OPT-OUT | not in the PHP contract; switch-account covers the session change PHP supports |
|
||||
| dynamic client registration for OIDC clients | OPT-OUT | D-08: registration is MCP-only, so a registered client never gets identity scopes |
|
||||
| sector_identifier_uri fetching for pairwise clients | OPT-OUT | RESEARCH OQ5: the administrator enters the sector; no remote fetch in this phase |
|
||||
| device authorization grant | OPT-OUT | Phase 19.6 |
|
||||
| openid scope and id_token for MCP clients | OPT-OUT | D-07: the engine supports it, Phase 19.7 decides |
|
||||
| MCP routes and RFC 8414 metadata from the plugin | INTEGRATE | behind mcp.enabled, off by default; access-token verification belongs to Phase 19.7 |
|
||||
Reference in New Issue
Block a user