Repository navigation
feat(auth): accept tokens of allow-listed clients - #154
Conversation
With tesk.api.authorisation.service-clients.enabled (off by default), a JWT access token whose iss is the configured issuer, whose client claim (default client_id) names a listed client and whose sub is that client (client credentials grant) is checked locally: signature against the issuer's JWKS (from discovery or a set URI; cached, refetched for an unknown key ID at most every 10 s; asymmetric algorithms only), exact iss, exp (required) and nbf/iat with a leeway, typ at+jwt (default on) and, if set, the audience. Valid tokens authenticate the client as a principal of its own without groups, which creates tasks without a group and lists, gets and cancels its own; invalid ones get 401 without a user info call. All other tokens go through the user info endpoint as before. The client ID is logged for accepted and refused tokens, never the token. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Access control: which tokens are accepted, the settings, an example of the tokens of a provider, how service clients are authorised, and the trust implications. Configuration: the new group of settings. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
From the review: requests to the issuer get 5 s timeouts and no retries; a failed discovery or key fetch (also an empty key set) isn't retried for 10 s, so forged tokens that claim a listed client refuse at once instead of queueing behind the issuer; keys are kept for 15 min if refetching them fails. Users whose sub is a listed client's ID are refused, as they would share the client's tasks. Unexpected errors are logged with their stack trace. Docs no longer claim an iat check, and recommend https for the issuer. More tests (ECDSA, non-string client claim, defaults, backoff, empty key set, authorities without groups). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
jose4j's reprieve only holds after a successful fetch of a non-empty key set, so after the first fetch, tokens with made-up key IDs could still make requests fetch the keys one after another while the issuer fails. The key set is now fetched at most once per interval, whatever the outcome, by one request at a time; other requests use the keys at hand. While one request builds the verifier, others are refused at once instead of waiting. Docs describe the timeouts, backoff and key retention. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Reviewer's GuideData structuresAdd service-client identity state to User and expose the shared no-group authorization predicate used to grant clients independent, group-free task access.
APIExtend authorization rules so clients and claim-authorized users can create ungrouped tasks and manage only their own ungrouped tasks.
ImplementationSelect allow-listed client JWTs for local verification, enforce issuer, key, signature and claim constraints with bounded key fetching, and delegate other tokens to user-info validation.
Wire local service-client token validation into the resource server only when the feature is enabled.
Introduce typed service-client validation settings, defaults, and accessors for enablement, issuer, clients, audience, token claims, and clock skew.
ConfigurationDeclare jose4j directly for JWT validation and set the service-client feature disabled by default in application properties.
DocumentationDocument how allow-listed service tokens are selected, validated, authorized, configured, and trusted, and summarize the new setting group.
TestsCover service-token validation, discovery and JWKS resilience, identity collision handling, and authorization behavior through focused unit and integration tests.
Other changesFiles not grouped.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## dev #154 +/- ##
==========================================
+ Coverage 73.73% 75.01% +1.27%
==========================================
Files 70 71 +1
Lines 3027 3266 +239
Branches 347 384 +37
==========================================
+ Hits 2232 2450 +218
- Misses 655 663 +8
- Partials 140 153 +13 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit b095d8b #153 feat(auth): accept tokens of allow-listed clients · 9 of 10 met
|
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="298" />
<code_context>
+
+ private VerificationKeyResolver keyResolver() throws IOException, JoseException {
+ String uri = this.jwksUri != null ? this.jwksUri : discoverJwksUri();
+ HttpsJwks jwks = new ThrottledHttpsJwks(uri, this.jwksRefreshIntervalMs);
+ jwks.setSimpleHttpGet(httpGet());
+ jwks.setRefreshReprieveThreshold(this.jwksRefreshIntervalMs);
</code_context>
<issue_to_address>
**HTTP issuer keys enable forgery**
When service-client authentication is enabled and the issuer or JWKS URI uses HTTP, or discovery returns an HTTP JWKS URI, on a network an attacker can intercept, `keyResolver` passes the configured or discovered JWKS URI to `HttpsJwks`, and discovery fetches the issuer URL without enforcing HTTPS. A network attacker who can intercept either HTTP request can substitute signing keys and mint tokens accepted as an allow-listed client, gaining that client's task permissions.
Reject non-HTTPS issuer and JWKS URLs by default, with any insecure test-only exception made explicit.
Also at `src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:361`.
</issue_to_address>
### Comment 2
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="242" />
<code_context>
+ || !this.clientIds.contains(client)) {
+ return null;
+ }
+ if (this.requireClientSubject && !client.equals(claims.getClaimValue("sub"))) {
+ return null; // a user's token, obtained through the client
+ }
</code_context>
<issue_to_address>
**Colliding user becomes client**
When a user access token from the configured issuer has a listed client's ID in both the configured client claim and `sub`, `listedClient` treats the token as a client-credentials token based only on the client claim matching `sub`, then verifies it and returns `authentication(clientId)` without consulting user info. A user whose ID collides with a listed client therefore gets that client's permissions and task access; the user-info collision guard does not run.
Require a trusted grant-specific discriminator, or otherwise reject colliding user identities before accepting the service-token path; matching client and subject IDs alone cannot distinguish the grants.
</issue_to_address>
### Comment 3
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="254" />
<code_context>
+ User.builder(clientId)
+ .allGroups(Collections.emptySet())
+ .serviceClient(true)
+ .legacyUserLabels(this.legacyUserLabels)
+ .build();
+ UsernamePasswordAuthenticationToken userAuthentication =
</code_context>
<issue_to_address>
**Clients access other users’ legacy tasks**
When legacy user labels are enabled and a listed client ID aliases another user's ID under the `@`-to-`_` normalization, the service-client principal inherits legacy-label matching, so `User.isCreatorOf` and `User.isCreator` treat the other user's old creator label as the client's; the client can list, get, and cancel that user's tasks.
Disable legacy-label matching for service-client principals and retain exact creator-hash checks for them.
Also at `src/main/java/uk/ac/ebi/tsc/tesk/config/security/User.java:195`, `src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:255`, `src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesService.java:44`.
</issue_to_address>
### Comment 4
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="380" />
<code_context>
+ .setJwsAlgorithmConstraints(ALGORITHMS)
+ .setExpectedIssuer(true, this.issuer)
+ .setRequireExpirationTime()
+ .setAllowedClockSkewInSeconds(this.clockSkewSeconds);
+ if (this.audience != null) {
+ builder.setExpectedAudience(true, this.audience);
</code_context>
<issue_to_address>
**Tokens with invalid `iat` are accepted**
When a listed client's signed token has a valid `exp` but omits `iat` or has an `iat` later than the allowed clock skew, `buildVerifier()` requires `exp` and configures clock skew but does not require or validate `iat`, so the token passes verification and authenticates before its stated issue time or without an issue time.
Require `iat` and reject tokens whose issue time is later than the allowed clock skew.
</issue_to_address>
### Comment 5
<location path="src/integration-test/java/uk/ac/ebi/tsc/tesk/ServiceClientAuthIT.java" line_range="221" />
<code_context>
+ // the own task only, also if Kubernetes returned others
+ listTasks(serviceToken())
+ .andExpect(status().isOk())
+ .andExpect(jsonPath("$.tasks.length()").value(1));
+ noUserInfoCalls();
+ }
</code_context>
<issue_to_address>
**Other-client tasks escape list test**
When creator-based filtering of returned jobs is removed, `serviceClient_getList_ownTasksOnly` checks only that the list has one task at `ServiceClientAuthIT.java:219-221`. Both fixtures have the name `task-123` (`MockUtil.java:88`), and `TaskListStrategy` deduplicates by name, so the test still passes if creator-based filtering is removed.
Give the two fixtures distinct task names and assert that the returned task belongs to the client.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 5 findings to address first, and a valid token for a listed client can locally authorize that client to launch arbitrary task containers and access or cancel its tasks without user-info validation. Reverting disables this path, but it cannot undo tasks already launched or effects they caused.
Blocking findings: src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:298, src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:242, src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:254, src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:380, src/integration-test/java/uk/ac/ebi/tsc/tesk/ServiceClientAuthIT.java:221
From the automated review: the issuer, a configured JWKS URI and a discovered jwks_uri must be https (http only to localhost, for tests); other settings stop startup, other discovered URIs are refused. Service tokens need iat (RFC 9068), neither in the future beyond the leeway nor more than a year old. Service clients never match tasks by the old creator label. The list test gives the other client's task its own name and checks the ID of the returned one. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Summary
Optional acceptance of access tokens of allow-listed service clients (OAuth 2.0 client credentials grant, e.g. a gateway calling TESK with its own token), checked locally against the issuer's keys instead of at the user info endpoint. Off by default; with it off, nothing changes.
issis the configured issuer (exact), whose client claim (defaultclient_id, RFC 9068; configurable, e.g.azp) is a listed client ID, and whosesubis that client ID (as in client-credentials tokens; configurable). Everything else (opaque tokens, other issuers, unlisted clients, user tokens obtained through a listed client) goes through the user info endpoint exactly as before.issuermust match, or a configured URI; cached, refetched for an unknownkidat most every 10 s), asymmetric algorithms only (nonone/HMAC), exactiss,expandiatrequired (iatnot in the future, at most a year old),exp/nbf/iatwith a leeway (default 60 s), headertyp: at+jwt(default on), and the audience if configured. A failed check gives401without a user info call.User#serviceClient): it creates tasks without a group, and lists, gets and cancels its own tasks only; no group rules apply. The SpEL rules use the newUser#authorisedWithoutGroup(claim users or service clients).subis a listed client ID is refused (401), as it would share the client's tasks.INFO) and refused (WARN, with a reason such asexpired,invalid signature,wrong audience) tokens; never the token.pom.xml) is now a direct dependency.Settings (
tesk.api.authorisation.service-clients.*; envTESK_API_AUTHORISATION_SERVICE_CLIENTS_*):enabled(false),issuer,client-ids,audience(unset),jwks-uri(discovery),client-claim(client_id),require-access-token-type(true),require-client-subject(true),clock-skew-seconds(60).Docs:
docs/access-control.md(new section "Tokens of services": selection, checks, settings, an example of a provider's client-credentials tokens, authorisation, trust implications),docs/configuration.md(settings row). The release notes are written in the release-prep PR (docs/releases/<version>.md), as for every release of this repo.Closes #153
Verification
./mvnw -B clean verify(Java 8): build, all unit tests and all 99 integration tests pass, JaCoCo coverage checks met.ServiceClientTokenServicesTest(40 tests; test RSA and EC keys, discovery and JWKS from WireMock): accepted client, ECDSA, non-string client claim, defaults, failed discovery backoff and retry, failed/empty key set backoff, throttled refresh while the issuer fails, user with a listed client's ID refused, unlisted client, other issuer (also without the trailing slash), opaque token, user token of a listed client, expired, within leeway, noexp, not yet valid, bad signature, unsigned (none), HMAC with the public key, unknown key ID (refresh), unknown key IDs refresh at most once per interval,typmissing orJWT, audience set/unset,azpas client claim, configured JWKS URI (no discovery), discovery of another issuer, discovery unavailable, startup validation, no token in logs.ServiceClientAuthIT: a service token creates (without group, creator labels of the client), lists (own tasks only), gets and cancels its own tasks without any user info call; others' and group tasks403; group task creation403; unlisted client401(via user info); expired and wrong-audience service tokens401without user info call; user tokens still go through user info and group rules../mvnw -B spotless:check checkstyle:check: 0 violations.mkdocs build --strict: passes.Reviews: two rounds of the adversarial and quality reviewer subagents; fixed: key-fetch throttling, backoff, timeouts and retention (medium),
iatwrongly documented as checked, users with a listed client's ID, narrower exception handling, https note, more tests.Declined review findings
DEBUGinstead ofINFO: the issue asks to log the client ID for accepted tokens; keptINFOas an audit trail, with the logger override documented for polling gateways.AuthIT,ClaimAuthIT, …) run with the setting off and are unchanged.subs, and RFC 9068 offers no claim that tells client-credentials tokens apart from others beyondsubequal to the client ID. Users from another provider's user info with a listed client's ID are refused (401).Sourcery round (fixed in b095d8b): https-only issuer and JWKS URIs (http only to localhost),
iatrequired and not in the future, no legacy-label matching for service clients, stricter list test.Open questions
None.
🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV