Skip to content

feat!: check audiences per service client - #220

Merged
uniqueg merged 8 commits into
devfrom
feat/per-client-audiences
Nov 23, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/per-client-audiences

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Service clients get their own audiences (#215, tesk-api side of elixir-cloud-aai/TESK#336):

  • One JSON setting replaces client-ids and audience: tesk.api.authorisation.service-clients.clients / TESK_API_AUTHORISATION_SERVICE_CLIENTS_CLIENTS, a map from client ID to {"audiences": [...]} or {"allowAnyAudience": true}. The env format is one JSON variable because client IDs don't bind well to Spring map keys from env.
  • A token is accepted only if its aud is or contains one of the audiences of the client named in the token. That check runs on the verified claims, after the signature check. A client's token for another client's audience is refused (401, logged as wrong audience). The requireAtJwt, requireClientSubject, issuer and signature checks are unchanged, and so is the user-token path.
  • allowAnyAudience is set per client and defaults to false, as proposed in TESK#336. With service clients enabled, TESK API refuses to start in any of these cases:
    • the clients are unset or not a JSON object, or the object is empty;
    • a client ID is blank or appears twice (also after trimming);
    • a client has no audiences, an empty list, or a blank or non-string audience;
    • a client sets both fields, or has an unknown field;
    • the removed 2.0.0 settings are still set (plain, as a list or as env vars), in which case the message points to the upgrade notes.
  • allowAnyAudience stays opt-in for testing (decision d21 of the maintainer, 2026-11-23): it is the narrowest switch, kept for testing and for setting up federations while the audiences at an IdP that one doesn't control are being sorted out. The docs (access control: client settings and trust implications; upgrade notes) say what it does (accepts that client's tokens whatever their aud), the risk (every token that the trusted issuer issues to that client ID is accepted, also tokens meant for other services, so a token leaked from or replayed by another service works here), and that production should list audiences. TESK API logs a WARN at startup that names each client with allowAnyAudience (unit tests anyAudience_isWarnedAtStartup, audiencesOnly_areNotWarnedAtStartup).
  • This is a clean break with no compatibility layer. The docs are updated: access control (which tokens, settings, example, trust implications), configuration reference, and the upgrade notes for 2.1.0 (how to convert, the chart, rollback).

Closes #215

Verification

  • ./mvnw clean verify spotless:check checkstyle:check (JDK 21 in an eclipse-temurin:21-jdk container): BUILD SUCCESS. 18741 unit tests and 155 integration tests pass (on db3c6bb); CI on db3c6bb: all checks pass, Smoke test after one re-run of the same flaky Maven download, with merged JaCoCo coverage at 100% for lines and branches.
  • New unit tests in ServiceClientTokenServicesTest: per-client audiences, refusal across clients, allowAnyAudience per client, trimming, every startup refusal and its message, the removed settings (plain, env var and list forms), and the wiring in ResourceServerConfiguration.tokenIntrospector.
  • ServiceClientAuthIT: two clients with different audiences. A token for the other client's audience gets 401, and a client at its own audience gets 200. The existing cases are kept.
  • mkdocs build --strict: OK.
  • CI: all checks pass. CI passed is green. Scan image failed once on the known flaky download of the Maven distribution in the image build, and passed on re-run.
  • Reviews: two rounds of adversarial-reviewer and quality-reviewer. The medium findings (no wiring test, list and env-var forms of the removed settings not detected, missing rollback docs) are fixed, and so are the low findings that take only minutes. Sourcery raised 4 threads. Two are fixed: Unicode whitespace in client IDs, and the rolling-update note. Two are answered: an explicit allowAnyAudience: false next to audiences stays valid by design, and the docs now say so. All 4 threads are resolved, and CI is green again on c702d80. The d21 changes (startup warning, risk docs) had one round of adversarial-reviewer and quality-reviewer: no high or medium findings; the low ones are fixed (the level and message are matched on one line, the test without the warning sets its clients explicitly, the warning and Javadoc name federation setup as the docs do).

Declined review findings

  • Keeping the full allowAnyAudience risk text in one place only (quality, low): the maintainer asked for it where the setting is described, in the settings, the trust implications and the upgrade notes, so readers of any of them see it.

  • Splitting client(...) into smaller parse helpers (quality, low, optional): it is linear and fully tested, and splitting it would scatter the messages.

  • Allowing the removed settings with empty values (adversarial, low): a blanked old variable still refuses startup on purpose, so that leftovers get removed. The upgrade notes say so.

  • Detecting map-style children of the removed settings (client-ids.foo): nobody writes them, and they are ignored, as in 2.0.0.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5

Summary by Sourcery

Enforce service-client audiences per client through a breaking configuration change, while preserving an explicitly opt-in any-audience mode for testing and federation setup.

New Features:

  • Configure service clients with per-client audience allowlists or an explicit any-audience option.
  • Validate service client tokens against the audience configured for the client named in each token.

Bug Fixes:

  • Prevent tokens issued to one service client for another client's audience from being accepted.

Enhancements:

  • Replace the former shared client ID and audience settings with a single JSON service-client configuration.
  • Reject invalid service-client configurations and leftover 2.0.0 settings at startup, with actionable errors.
  • Warn at startup when clients use the security-sensitive allowAnyAudience option.

Documentation:

  • Update access-control, configuration, and upgrade documentation for per-client audiences, trust implications, migration, and rollback.

Tests:

  • Add unit and integration coverage for per-client audience validation, configuration failures, removed settings, startup warnings, and cross-client token rejection.

uniqueg and others added 3 commits November 23, 2026 06:27
Service clients are listed with their own audiences in one JSON
setting, tesk.api.authorisation.service-clients.clients (env
TESK_API_AUTHORISATION_SERVICE_CLIENTS_CLIENTS): client ID to
{"audiences": [...]} or {"allowAnyAudience": true}. A token is accepted
only if its aud holds one of that client's audiences, so a client's
token for another client's audience is refused. Issuer, signature, typ
and sub checks are unchanged.

BREAKING CHANGE: client-ids and audience are removed; with either still
set, or without clients, TESK API doesn't start. The upgrade notes say
how to convert.

Closes #215

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Detect the removed settings also as lists and environment variables,
hint at the removal when clients are unset, test the wiring in the
token introspector and the messages, and document rollback and the
shared audience.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
A removed setting that cannot be bound (e.g. a list with a gap) is
refused with the upgrade hint too; the notes say that empty values
count as set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@uniqueg uniqueg added priority: high High priority type flag: breaking change Proposed change breaks current API type: auth Related to authorization or authentication ecp-wp4: M4.4 ELIXIR Compute Platform WP4 milestone/deliverable this issue contributes to labels Nov 23, 2026
@uniqueg uniqueg self-assigned this Nov 23, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Replace the shared client-ID and audience properties with one per-client JSON setting that downstream validation and authentication depend on.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/AuthorisationProperties.java L121-129, L176-181

Implementation

Parse and validate per-client audience settings, reject removed configuration, and enforce each verified token’s audience against its named client.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java L109-141, L223-378, L473-488 (+17 small edits)

Wire startup rejection of removed settings into the enabled service-client token introspector.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ResourceServerConfiguration.java L14, L127, L138

Documentation

Explain the new per-client audience setting, its security implications, and migration or rollback steps for the breaking configuration change.

  • docs/access-control.md L359-402, L461-468 (+3 small edits)
  • docs/configuration.md L42
  • docs/upgrading.md L5-45
  • src/main/resources/application.properties L65

Tests

Update integration coverage and add unit checks for per-client audience enforcement, startup validation, removed settings, warnings, and configuration wiring.

  • src/integration-test/java/uk/ac/ebi/tsc/tesk/ServiceClientAuthIT.java L59-61, L313-342
  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServicesTest.java L388-472, L521-696 (+5 small edits)

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 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (b101f7b) to head (db3c6bb).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #220   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         2543      2612   +69     
  Branches       296       313   +17     
=========================================
+ Hits          2543      2612   +69     

☔ 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 23, 2026 05:51
@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit db3c6bb

#215 Service clients: audiences per client · 6 of 6 met

# Requirement Status Notes
1 Configure clients with their own audiences and accept a token only for an audience of the client named in its claim. ✅ Met The clients JSON setting maps client IDs to per-client audience settings; verified claims are checked against the named client’s audiences.
2 Refuse a client without audiences at startup, unless it has per-client allowAnyAudience. ✅ Met Startup validation requires non-empty audiences or allowAnyAudience: true; the latter is opt-in.
3 Keep requireAtJwt, requireClientSubject, issuer, signature and user-token checks unchanged. ✅ Met Audience validation runs after JWT verification, and the user-token path still delegates to the user-info introspector.
4 Cover per-client acceptance and cross-client audience refusal in ServiceClientTokenServicesTest and ServiceClientAuthIT. ✅ Met Unit and integration tests cover each client’s own audience and refusal of another client’s audience.
5 Update the configuration reference and upgrade notes. ✅ Met The configuration reference and 2.1.0 upgrade notes describe the new setting and conversion.
6 Make a clean break from the former shared settings and explain how to convert them in the upgrade notes. ✅ Met The old settings are rejected at startup when service clients are enabled, and the upgrade notes show how to migrate.

@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 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="docs/upgrading.md" line_range="5-36" />
<code_context>
+- **Service clients: audiences per client (breaking).** With tokens of
</code_context>
<issue_to_address>
**Old replicas bypass audience checks**

When a rolling upgrade leaves 2.0 replicas serving requests after client audiences have been split, the 2.0 replicas continue checking every listed client against the shared audience, so tokens rejected by 2.1 replicas still authenticate on requests routed to old replicas until they are drained.

Document that old replicas must be drained before relying on the per-client audience restriction, or require a deployment strategy that prevents mixed-version authentication.
</issue_to_address>

### Comment 2
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="319" />
<code_context>
+        }
+        boolean anyAudience = any != null && any.booleanValue();
+        JsonNode audiences = settings.get(AUDIENCES);
+        if (anyAudience) {
+            if (audiences != null) {
+                throw invalidClients(
</code_context>
<issue_to_address>
**Conflicting client settings are accepted**

When a client supplies both `audiences` and `allowAnyAudience: false`, `client()` enters the conflict check only when `anyAudience` is true, so the false value skips rejection and startup accepts the invalid client configuration.

Reject the combination whenever both settings are present, regardless of the boolean value.

Also at `src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:320-325`.
</issue_to_address>

### Comment 3
<location path="src/test/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServicesTest.java" line_range="532-534" />
<code_context>
+        properties
+                .getServiceClients()
+                .setClients(
+                        "{\" gateway-client \": {\"audiences\": [\" tesk \"],"
+                                + " \"allowAnyAudience\": false}}");
+        accepted(sign(claims(CLIENT)));
+        JwtClaims other = claims(CLIENT);
+        other.setAudience("other-service");
</code_context>
<issue_to_address>
**Trim test uses invalid settings**

When the trim test's client entry has both `audiences` and `allowAnyAudience: false`, `clients_areTrimmed` calls `accepted` at line 534 with both fields set, so enforcing the documented mutual-exclusion rule makes this test fail instead of verifying trimming. `invalidClients_failAtStartup` covers the both-fields case only with `allowAnyAudience: true` at lines 510–511.

Remove `allowAnyAudience: false` from the trim-test fixture, since false is the default.
</issue_to_address>

### Comment 4
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java" line_range="282-283" />
<code_context>
+        Map<String, Client> listed = new LinkedHashMap<>();
+        for (Map.Entry<String, JsonNode> entry : root.properties()) {
+            String id = entry.getKey().trim();
+            if (id.isEmpty()) {
+                throw invalidClients("a blank client ID");
+            }
+            if (listed.put(id, client(id, entry.getValue())) != null) {
</code_context>
<issue_to_address>
**Whitespace-only client IDs start**

When a JSON client key contains only Unicode whitespace not removed by `String.trim()`, `trim().isEmpty()` does not remove all Unicode whitespace, so an ID made only of characters such as U+2003 passes validation and becomes an allow-listed client ID instead of stopping startup.

Reject IDs that are blank using `isBlank()` before normalizing them.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if the per-client audience check is wrong, a signed token minted for another audience could authenticate as an allow-listed service client and use that client’s API access. Reverting can stop future acceptance, but it cannot undo data already exposed or actions already taken.

Blocking findings: docs/upgrading.md:36, src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java:319, src/test/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServicesTest.java:534


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

Comment thread docs/upgrading.md Resolved
Reject client IDs of Unicode whitespace only (strip instead of trim),
and document that allowAnyAudience true excludes audiences and that
2.0.0 pods keep the shared audience during a rolling update (Sourcery
review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
uniqueg and others added 2 commits November 23, 2026 22:34
Log a warning at startup that names each service client with
allowAnyAudience, as the setting accepts tokens meant for other
services and is meant for testing only (decision d21).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Say what allowAnyAudience does, that any token issued to the client
is accepted (also one leaked from or replayed by another service),
that it is meant for testing and setting up federations, and that
production should list audiences (decision d21).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
uniqueg added a commit that referenced this pull request Nov 23, 2026
Set date-released to 2026-11-24, the planned tag day, and add the
changes merged since the first prep commit to the curated notes:
owner-only task visibility (#218, #219), team names in labels
(#216, #217) and audiences per service client (#215, #220; #220 is
expected to merge before the tag); the merge of dev put them into the
upgrade intro. The notes link the upgrade notes of the v2.1.0 tag,
which never move, instead of the latest docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
uniqueg and others added 2 commits November 23, 2026 23:09
Match the level and the message on one line, and set the clients of
the test without the warning explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Say testing or setting up a federation in the startup warning and the
Javadoc, as the docs do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@uniqueg
uniqueg merged commit db99a2d into dev Nov 23, 2026
31 of 33 checks passed
@uniqueg
uniqueg deleted the feat/per-client-audiences branch November 23, 2026 22:40
uniqueg added a commit that referenced this pull request Nov 23, 2026
Brings #220 (audiences per service client); the notes say that any audience is an opt-in per client with a startup warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@uniqueg uniqueg mentioned this pull request Nov 25, 2026
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ecp-wp4: M4.4 ELIXIR Compute Platform WP4 milestone/deliverable this issue contributes to priority: high High priority type: auth Related to authorization or authentication type flag: breaking change Proposed change breaks current API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Service clients: audiences per client

1 participant