Skip to content

feat(auth): accept tokens of allow-listed clients - #154

Merged
uniqueg merged 5 commits into
devfrom
feat/153-service-client-tokens
Nov 12, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/153-service-client-tokens

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

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.

  • Selection: a bearer token is a service token if it is a signed JWT whose iss is the configured issuer (exact), whose client claim (default client_id, RFC 9068; configurable, e.g. azp) is a listed client ID, and whose sub is 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.
  • Checks of a service token: signature against the issuer's JWKS (https only; from OIDC discovery, whose issuer must match, or a configured URI; cached, refetched for an unknown kid at most every 10 s), asymmetric algorithms only (no none/HMAC), exact iss, exp and iat required (iat not in the future, at most a year old), exp/nbf/iat with a leeway (default 60 s), header typ: at+jwt (default on), and the audience if configured. A failed check gives 401 without a user info call.
  • Authorisation: the client is a principal of its own (ID = client ID, no groups, 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 new User#authorisedWithoutGroup (claim users or service clients).
  • Robustness: requests to the issuer have 5 s timeouts and no retries; the key set is fetched at most once per 10 s whatever the outcome, by one request at a time; a failed discovery or key fetch is not retried for 10 s (tokens are refused at once meanwhile); keys are kept 15 min if a refetch fails. So forged tokens that claim a listed client can't make requests queue behind a slow issuer.
  • Shared ID namespace: with the setting on, a user-info principal whose sub is a listed client ID is refused (401), as it would share the client's tasks.
  • Logging: client ID for accepted (INFO) and refused (WARN, with a reason such as expired, invalid signature, wrong audience) tokens; never the token.
  • jose4j (already on the classpath through the Kubernetes client, version managed in pom.xml) is now a direct dependency.

Settings (tesk.api.authorisation.service-clients.*; env TESK_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.
    • New unit tests 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, no exp, 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, typ missing or JWT, audience set/unset, azp as client claim, configured JWKS URI (no discovery), discovery of another issuer, discovery unavailable, startup validation, no token in logs.
    • New integration test 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 tasks 403; group task creation 403; unlisted client 401 (via user info); expired and wrong-audience service tokens 401 without 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.
  • CI: all checks passed (CI passed, Test, Lint, Docs, Smoke test, Scan image, CodeQL, codecov/project).

Reviews: two rounds of the adversarial and quality reviewer subagents; fixed: key-fetch throttling, backoff, timeouts and retention (medium), iat wrongly documented as checked, users with a listed client's ID, narrower exception handling, https note, more tests.

Declined review findings

  • Log accepted service tokens at DEBUG instead of INFO: the issue asks to log the client ID for accepted tokens; kept INFO as an audit trail, with the logger override documented for polling gateways.
  • A test for nested JWTs/JWEs and a Spring-context test of the disabled wiring: nested tokens fall through by a one-line check; the existing auth integration tests (AuthIT, ClaimAuthIT, …) run with the setting off and are unchanged.
  • Treat an empty refreshed key set as a failure that keeps the old keys: jose4j's cache can't be kept from a subclass without reimplementing it; an empty set now refuses service tokens, fetched again at most every 10 s.
  • Log the class instead of the message of I/O errors: the messages hold only the public issuer/JWKS URL and status, which operators need for diagnosis; never the token.
  • Sourcery: "a user whose ID collides with a listed client becomes the client" on the service-token path. The issuer that signs the token assigns both client IDs and user subs, and RFC 9068 offers no claim that tells client-credentials tokens apart from others beyond sub equal 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), iat required 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

uniqueg and others added 4 commits November 12, 2026 17:35
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
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add service-client identity state to User and expose the shared no-group authorization predicate used to grant clients independent, group-free task access.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/User.java L45-51, L89-101, L166-171 (+10 small edits)

API

Extend authorization rules so clients and claim-authorized users can create ungrouped tasks and manage only their own ungrouped tasks.

  • src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesService.java L22-75 (5 small edits)

Implementation

Select 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.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java L1-466

Wire local service-client token validation into the resource server only when the feature is enabled.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ResourceServerConfiguration.java L55-59, L109-113 (+5 small edits)

Introduce typed service-client validation settings, defaults, and accessors for enablement, issuer, clients, audience, token claims, and clock skew.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/AuthorisationProperties.java L41-43, L90-193, L198-201

Configuration

Declare jose4j directly for JWT validation and set the service-client feature disabled by default in application properties.

  • pom.xml L121-126
  • src/main/resources/application.properties L51-54

Documentation

Document how allow-listed service tokens are selected, validated, authorized, configured, and trusted, and summarize the new setting group.

  • docs/access-control.md L48, L210-351
  • docs/configuration.md L35

Tests

Cover service-token validation, discovery and JWKS resilience, identity collision handling, and authorization behavior through focused unit and integration tests.

  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServicesTest.java L1-621
  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/UserCreatorTest.java L49-67

Other changes

Files not grouped.

  • src/integration-test/java/uk/ac/ebi/tsc/tesk/ServiceClientAuthIT.java L1-330

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.45643% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.01%. Comparing base (99778a8) to head (b095d8b).

Files with missing lines Patch % Lines
...sk/config/security/ServiceClientTokenServices.java 89.24% 9 Missing and 11 partials ⚠️
.../java/uk/ac/ebi/tsc/tesk/config/security/User.java 78.57% 1 Missing and 2 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 12, 2026 17:46
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit b095d8b

#153 feat(auth): accept tokens of allow-listed clients · 9 of 10 met

# Requirement Status Notes
1 Add opt-in service-client settings, off by default ✅ Met The settings are added with enabled=false by default, and the custom token services are wired only when enabled.
2 Locally validate listed service tokens and send other tokens through the existing user-info path ✅ Met Service-token selection and validation are implemented in ServiceClientTokenServices; tokens that do not qualify are passed to the existing token services.
3 Authorize a service client to create tasks and access only its own tasks, without group rules ✅ Met Service clients are group-less principals, and the authorization rules and label selector restrict their task access to their own ungrouped tasks.
4 Optionally require the access-token type header ✅ Met The typ check defaults to on and can be disabled with require-access-token-type.
5 Log the client ID, not the token, for accepted and refused service tokens ✅ Met Accepted and refused service-token paths log the client ID and do not include the token.
6 Add unit tests for the listed token-validation and fallback cases ✅ Met The new unit tests cover accepted and unlisted clients, other issuers, expiry, signatures, unknown-key refresh, and opaque-token fallback.
7 Add an integration test with service and user tokens ✅ Met ServiceClientAuthIT checks service-token task operations and user-token validation through the user-info endpoint.
8 Document service tokens in access-control and configuration docs ✅ Met Both requested documentation files are updated with the settings and service-client behavior.
9 Include the change in the release notes ❌ Not addressed No release-note entry is included in this diff; the PR description says release notes are written in the release-prep PR.
10 Keep behavior unchanged when the setting is off ✅ Met The existing token services are replaced only when service-client support is enabled.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(auth): accept tokens of allow-listed clients

1 participant