Repository navigation
feat: validate bearer tokens - #4
Conversation
Add an owner and an auth context to runs (migration 000009) and scope repository reads to the owner carried in the request context (new package internal/ownership). New runs are stamped with that owner; Get, GetStatus and List on runs and Get, GetByTESID, List and ListByRunID on tasks return only that owner's runs and their tasks. Runs without an owner never match an owner. Nothing sets an owner yet, so behaviour is unchanged: an unscoped context sees everything, as internal callers keep doing. Token validation (next slice) will scope API requests. Add an integration CI job that runs the PostgreSQL repository tests and rolls the newest migration down and up again. Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
- TES CreateTask answers 404 when the run in conquest_run_id can't be read (missing, or hidden by the owner scope) instead of attaching the task to it; other store errors give 500. - Owner filters append to the query's arguments and number their placeholder from them, instead of hand-counted numbers. - Run.Owner and Run.AuthContext are never serialised. - Integration tests cancel their tasks, so that they stay out of the dispatch queue; cover paged ListByRunID and an owner without runs. - README: scoping covers reads only; runnable integration test snippet. Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
List and ListByRunID compared created_at (timestamptz) with the token's Unix nanoseconds as an integer, which pgx can't encode: every second page of runs or tasks failed with 500. parseCursor now returns a time.Time. Found by the new integration tests; unrelated to run owners. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Create ignores an Owner the caller set on the run and refuses a context scoped to an empty owner ID (ErrEmptyOwner), whose caller could never read the run. Addresses Sourcery review findings. Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Add package internal/auth: with CONQUEST_AUTH_ENABLED=true, the public WES and TES routes require an OAuth 2.0 access token (JWT, RFC 9068) from a configured issuer: exact iss, keys only from that issuer's JWKS (configured or discovered), asymmetric algorithms only, typ at+jwt, exp/nbf/iat with leeway, sub set, and aud by caller class (user: one of the issuer's front-end audiences; listed service client with its own token: aud == its client ID). Accepted requests are scoped to the owner "<iss>|<sub>" (package ownership), so callers see only their own runs. Issuers live in a YAML file (CONQUEST_AUTH_CONFIG), validated at startup. service-info stays open unless CONQUEST_AUTH_SERVICE_INFO_PUBLIC=false. Probes, the runner callback API and the storage gateway are unaffected. Off by default: no change for existing deployments. Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
- Key sets resolve outside the lock, one request at a time; requests meanwhile or within the retry delay fail fast with 503 instead of queueing behind a slow issuer. The delay starts after the attempt. Discovery uses the authenticator's context. - A key set that can't be fetched on first use is a 503 and retried, not an empty key set. - Tokens must carry a kid; keys marked use=enc never verify tokens. - Untrusted iss values are truncated before they are logged. - The service-info exemption matches chi's route pattern, not the request path. - CONQUEST_AUTH_* switches parse through a strict helper. - Tests assert why each token is refused; cover access token types, discovery retry, unreachable and slow key sets, encryption keys. - README: runner callback API must stay off public routes; key handling details. Part of elixir-cloud-aai/generic-issues#18. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
…idation # Conflicts: # README.md
- An unknown kid refetch gets the request timeout as its deadline, not 1 ms, so rotated keys are picked up at once (rate limit kept). - A failed key set attempt cancels its context, stopping the refresh goroutine the library started; refresh errors go to our logger. - Resolution state is reset in a defer, so a panic can't leave an issuer stuck in "being fetched". - README: the chart can't switch authentication on yet. Part of elixir-cloud-aai/generic-issues#146. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
A timeout of a minute or more let unknown-kid lookups queue on the refetch limiter. Cap timeout_seconds at 30 so they fail at once, and document that junk key IDs can delay a rotated key by up to a minute. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Reviewer's GuideAPIAdd an authenticated router constructor that guards public WES and TES routes while leaving probes, internal routes, and extra routes outside the middleware.
Uses of the APIBuild the configured authenticator and wire it into the router, including the route-pattern-based service-info exemption.
ImplementationImplement bearer-token parsing, issuer key resolution, JWT and audience validation, failure handling, and request ownership scoping.
ConfigurationAdd strict auth environment settings and validate the issuer, audience, algorithm, URL, timeout, and clock-skew configuration.
DocumentationDocument authentication behavior, token acceptance rules, issuer configuration, route exposure, and upgrade considerations.
TestsTest token validation and key-fetch behavior, route protection and exemptions, and auth configuration defaults and rejection cases.
Lock files and vendored codeRecord the JWT, JWKS, and rate-limiting dependency changes in the Go module files.
Other changesFiles not grouped.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Linked issuesChecked at commit 7e03f03 #146 Conquest: validate LS Login bearer tokens on WES/TES · 6 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="internal/auth/auth.go" line_range="115" />
<code_context>
+ if err := cfg.Validate(); err != nil {
+ return nil, err
+ }
+ client := &http.Client{Timeout: cfg.timeout()}
+ a := &Authenticator{
+ issuers: make(map[string]*issuer, len(cfg.Issuers)),
</code_context>
<issue_to_address>
**Forged tokens pass verification**
When an HTTPS discovery or JWKS endpoint redirects to HTTP, `http.Client` follows the redirect, so `discover` or the JWKS fetch trusts the plaintext response and accepts attacker-supplied signing keys; callers can present forged tokens as authenticated.
Reject HTTPS-to-HTTP redirects for discovery and JWKS requests, or verify that the final response URL remains HTTPS.
Also at `internal/auth/auth.go:341`, `internal/auth/auth.go:380`.
</issue_to_address>
### Comment 2
<location path="internal/api/server.go" line_range="25" />
<code_context>
+// NewRouterWithAuth is NewRouter with authn (e.g. auth.Authenticator's
+// Middleware) in front of the public WES and TES routes; nil mounts none.
+// Probes, the internal runner routes and extra routes are not affected.
+func NewRouterWithAuth(wesHandler *wes.Handler, tesHandler *tes.Handler, authn func(http.Handler) http.Handler, extra ...func(chi.Router)) http.Handler {
r := chi.NewRouter()
</code_context>
<issue_to_address>
**Runner callbacks bypass authentication**
When the server is reachable through a route or network path that exposes `/internal/runs/...` to an untrusted caller, an unauthenticated caller that can reach the server can invoke `/internal/runs/{run_id}/...` to submit tasks to, inspect, or cancel tasks for runs without proving ownership; the caller can interfere with other users’ workflows.
Authenticate runner callbacks or enforce a deployment-level access restriction that reliably prevents untrusted callers from reaching these routes.
Also at `README.md:352`.
</issue_to_address>
### Comment 3
<location path="internal/auth/auth.go" line_range="55" />
<code_context>
+}
+
+// Owner is the caller's owner identifier: "<iss>|<sub>".
+func (p *Principal) Owner() string { return p.Issuer + "|" + p.Subject }
+
+// authContext is what runs record about how their owner authenticated:
</code_context>
<issue_to_address>
**Issuer identities can collide**
When two configured issuer URLs differ by a raw `|` in the path and their subjects contain the corresponding delimiter-separated values, the unescaped `|` makes distinct `(iss, sub)` pairs produce the same owner ID, so repository scoping treats those callers as one owner and each can read the other’s runs. `checkURL` accepts issuer paths containing `|` without rejecting or encoding that delimiter.
Encode the issuer and subject unambiguously when constructing owner IDs, or reject issuer URLs containing the delimiter and use a collision-proof encoding regardless.
Also at `internal/auth/config.go:145-157`.
</issue_to_address>
### Comment 4
<location path="internal/auth/auth.go" line_range="122" />
<code_context>
+ jwt.WithValidMethods(cfg.Algorithms),
+ jwt.WithLeeway(cfg.clockSkew()),
+ jwt.WithExpirationRequired(),
+ jwt.WithIssuedAt(),
+ ),
+ log: log,
</code_context>
<issue_to_address>
**Incomplete access-token claims accepted**
When a trusted issuer signs an otherwise acceptable `at+jwt` token without one or more RFC 9068-required claims, `jwt.WithIssuedAt()` does not require `iat`, and the user-token validation accepts a configured audience without `client_id`; the checks also do not require `jti`. `Authenticate` accepts tokens that fail the advertised profile, and callers are treated as authenticated.
Require and validate all RFC 9068 mandatory claims, including `iat`, `client_id`, and `jti`, before accepting the token.
Also at `internal/auth/auth.go:123`, `internal/auth/auth.go:195-196`.
</issue_to_address>
### Comment 5
<location path="cmd/conquest/auth.go" line_range="37" />
<code_context>
+ return nil, err
+ }
+ if cfg.AuthServiceInfoPublic {
+ a.Public = isServiceInfo
+ }
+ issuers := make([]string, len(authCfg.Issuers))
</code_context>
<issue_to_address>
**Anonymous callers see workload counts**
When authentication is enabled while `CONQUEST_AUTH_SERVICE_INFO_PUBLIC` is left at its default true, the public service-info exemption lets unauthenticated callers reach WES `GetServiceInfo`, which returns unscoped system-wide run-state counts; callers can infer activity across all owners even when authentication is enabled.
Require authentication for service-info by default, or omit tenant-wide state counts from its public response.
Also at `README.md:354`.
</issue_to_address>
### Comment 6
<location path="internal/auth/config.go" line_range="133" />
<code_context>
+ }
+ // The cap keeps the unknown-kid wait below the refetch interval (one
+ // minute), so lookups fail at once while the refetch slot is used up.
+ if *c.TimeoutSeconds <= 0 || *c.TimeoutSeconds > 30 {
+ return fmt.Errorf("timeout_seconds must be between 1 and 30")
+ }
</code_context>
<issue_to_address>
**503 response arrives too late**
When `timeout_seconds` is 30 and an issuer request stalls until the client timeout, the issuer fetch can use the full 30 seconds, then the handler attempts to write the 503 after the server's 30-second `WriteTimeout` expires; callers see a timeout or dropped connection instead of the documented 503.
Set the maximum auth fetch timeout below the server's `WriteTimeout` with enough margin to write the error response.
</issue_to_address>
### Comment 7
<location path="internal/api/server_test.go" line_range="62" />
<code_context>
+ for _, path := range open {
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
+ if w.Code == http.StatusUnauthorized {
+ t.Errorf("GET %s: guarded", path)
+ }
</code_context>
<issue_to_address>
**Missing routes pass unguarded**
When an open route, such as the runner callback service-info route, is accidentally unregistered, `TestNewRouterWithAuth_GuardsOnlyThePublicAPIs` accepts a 404 when an open route is missing: line 62 reports failure only for 401, so removing the runner callback routes still passes as “not guarded.”
Assert the expected success status for each open route, including the callback and extra route, rather than checking only for 401.
</issue_to_address>
### Comment 8
<location path="internal/config/config_test.go" line_range="232" />
<code_context>
+ t.Setenv("CONQUEST_POSTGRES_DSN", "postgres://example")
+ t.Setenv("CONQUEST_S3_BUCKET", "conquest")
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
</code_context>
<issue_to_address>
**Auth tests inherit environment**
When the test process has non-default auth environment variables, or a malformed `CONQUEST_AUTH_ENABLED` value, `TestLoad_AuthDefaults` at line 232 fails when exported auth variables override defaults. `TestLoad_RejectsInvalidAuthSwitch` at line 263 can pass its service-info case on an unrelated malformed `CONQUEST_AUTH_ENABLED` error, because it accepts any `Load` error.
Unset all `CONQUEST_AUTH_*` variables before each `Load`, then set only the variable under test.
Also at `internal/config/config_test.go:263`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 8 findings to address first, and when authentication is enabled, a token-validation or owner-scoping flaw could let a caller access another caller’s runs or trigger workflows; reverting removes the check but cannot retract data already exposed or undo work already submitted.
Blocking findings: internal/auth/auth.go:115, internal/api/server.go:25, internal/auth/auth.go:55, internal/auth/auth.go:122, cmd/conquest/auth.go:37, and 3 more
- refuse redirects of discovery and key set requests to plain http - refuse issuer URLs with |, the owner ID separator - require iat (RFC 9068) - cap timeout_seconds at 10: two issuer requests in a row must fit in the server's 30 s write timeout - assert that open routes exist; isolate the auth env in tests Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Summary
Slice S3 of the Conquest auth design (generic-issues#18): validate LS Login (OIDC) bearer access tokens on the public WES and TES APIs and scope every request to its caller, using the run owners from #2. Off by default (
CONQUEST_AUTH_ENABLED=false): no change for existing deployments.internal/auth(golang-jwt/jwt v5.3.1, MicahParks/keyfunc v3.9.1). A token is accepted when:Authorization: Bearerheader (no query or cookie tokens);noneor HMAC);issequals a configured issuer exactly; keys only from that issuer's JWKS (jwks_urior OIDC discovery, which must name the same issuer);kidrequired; keys withuse: encnever verify;typisat+jwt(RFC 9068; refuses ID tokens);expandiatrequired,nbf/iatnot in the future (60 s leeway);subset; redirects only to https (or loopback http); issuer URLs without|; issuer request timeout 1-10 s (default 10);audcontains one of the issuer's front-end client IDs; a listed service client's own token (client_idlisted,sub == client_id) hasaudequal to its own client ID only (D-392). No any-audience opt-in (D-414 Q9). A token whosesubis a listed client ID but isn't that client's own token is refused.<iss>|<sub>(packageinternal/ownership);auth_contextstoresclient_idandscopeonly.WWW-Authenticate: Bearer/Bearer error="invalid_token"; cause logged, never the token (untrustedisstruncated). Issuer metadata or key set unreachable: 503, one fetch at a time (others fail fast), retried 10 s after the failed attempt; failed attempts stop their refresh goroutines. Unknownkid: key set refetched at most once a minute.api.NewRouterWithAuth(NewRouterdelegates to it) wraps only the public WES/TES routes in a chi group; probes,/internal/runs/...(runner callback) and the storage gateway are unaffected.service-infostays open by default (CONQUEST_AUTH_SERVICE_INFO_PUBLIC), matched by chi route pattern.cmd/conquest/auth.gobuilds the middleware.CONQUEST_AUTH_ENABLED,CONQUEST_AUTH_SERVICE_INFO_PUBLIC(strict booleans: a typo fails startup instead of leaving the API open, unlike the otherCONQUEST_*booleans),CONQUEST_AUTH_CONFIG(YAML, strict, validated at startup: issuers, audiences, service clients, https only except loopback, asymmetric algorithms only).Not in this PR: entitlement check at submit (S4; until then any accepted caller can submit), runner callback authentication (S1; the README says
/internal/runsmust stay off public routes), Helm chart settings (generic-issues#147).Closes elixir-cloud-aai/generic-issues#146
Verification
go build ./...,go vet ./...,go test -race -count=1 ./...: pass locally (Go 1.25.5).internal/auth/auth_test.go(one refusal case per rule, each asserting its reason; user, ES256 and service-client tokens accepted; typ variants; discovery retry and recovery; unreachable and slow key sets; key rotation with a slow JWKS; no goroutine growth over failed attempts; panic recovery; middleware 401/503 and owner scoping),config_test.go,internal/api/server_test.go(every public route guarded; probes, runner callback and extra routes not),cmd/conquest/auth_test.go(service-info exemption on/off, POST and lookalike paths guarded),internal/config(auth settings, strict booleans). Design matrix rows covered here: 1, 5 (with feat: record run owners #2), 8-11.timeout_secondscapped so unknown-kid lookups never queue on the refetch limiter).|in issuer URLs, requirediat,timeout_secondscapped at 10 (two issuer requests in a row stay below the 30 s write timeout), open-route and env-isolation test gaps. Declined: runner callback auth (S1, out of scope), requiredjti/client_id(no replay cache; users are bound byaud), closing service-info by default (design: world-readable; aggregate counts only, switch documented).Declined review findings
authCtxincmd/conquest/main.go(low): kept;appCtxis created after the router, and moving it would reorder more upstream code.NewRouterWithAuthas a second constructor instead of a functional option onNewRouter(low): kept; existing call sites are unchanged either way.Principal.Serviceunused outside tests (low): kept for S4 (service clients skip the userinfo entitlement check).kids can use up the once-a-minute refetch (low): accepted and documented in the README; a rotated key is then picked up up to a minute late. A per-caller budget would need the unverified token's claims, which an attacker controls.Open questions
None.
🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5