Skip to content

feat: validate JWT access tokens - #221

Draft
uniqueg wants to merge 4 commits into
devfrom
feat/token-validator
Draft

uniqueg wants to merge 4 commits into
devfrom
feat/token-validator

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the token validation of the access control redesign as its own package, uk.ac.ebi.tsc.tesk.config.security.token. It is not wired into the request authentication yet: behaviour is unchanged. A later slice switches authentication to it and removes UserInfoTokenIntrospector (as authentication) and ServiceClientTokenServices.

  • TokenValidator: the only interface for token validation. It takes a bearer token and returns a TokenPrincipal, or throws an InvalidTokenException whose message gives the reason and never the token. TokenValidators.create picks the implementation from tesk.api.auth.token-validator. Only jwt exists for now. RFC 7662 introspection could be added later as a new implementation and a new value, with no changes for callers.
  • JwtAccessTokenValidator accepts JWT access tokens only:
    • a single signed JWT; opaque, encrypted and nested tokens are refused;
    • iss must match a configured issuer exactly, and the token is checked only against that issuer's keys;
    • the keys come from the issuer's OIDC discovery or from a configured jwks-uri (https only, http only for localhost);
    • only asymmetric algorithms can be configured (default RS256, ES256); none and HMAC are refused at startup;
    • typ must be at+jwt;
    • exp, iat and sub are required; nbf, the maximum age and the clock skew are checked.
  • Audience and caller kind:
    • user tokens: aud must contain one of the issuer's audiences, which are the front ends' client IDs;
    • listed service clients (client claim and sub are both the listed ID): aud must contain the client's own ID;
    • a user whose sub equals a listed client's ID is refused;
    • tokens with act (delegation) are refused until delegated actors are decided; that slice replaces this check.
  • TokenPrincipal.owner() is <iss>|<sub>. There is no group model.
  • If the issuer keys cannot be fetched (on the first fetch, or later once the cached keys have expired), the validator throws IssuerUnavailableException rather than InvalidTokenException. Its caller is to answer 503 instead of 401, so that clients retry. Requests that arrive during the first fetch wait for it, at most 15 s. Later failed attempts refuse at once. Each failed fetch is logged once at WARN.
  • IssuerVerifier reuses the key handling of ServiceClientTokenServices: the JWKS cache, the throttled refetch for unknown key IDs, the discovery backoff and isSecure. It is a copy until that class is removed, and both copies note that they must be kept in sync.
  • Docs: a new "Token validation" section in docs/development.md with the settings. The settings will go into configuration.md and access-control.md when the validator is wired in, because they have no effect before that.

The audience defaults are provisional. No real LS Login user token has been checked yet for typ, aud and where the entitlements live. uniqueg will check one before this slice is final. If aud turns out unusable, the audience rule changes before the wiring slice.

Closes #222

Verification

  • ./mvnw clean verify (JDK 21, Docker eclipse-temurin:21-jdk): all unit and integration tests pass, and the 100% line and branch coverage check passes.
  • ./mvnw spotless:check checkstyle:check: clean.
  • mkdocs build --strict: clean.
  • New tests: JwtAccessTokenValidatorTest (75 cases, against WireMock-served discovery and JWKS), IssuerVerifierTest and TokenValidatorsTest (binding from properties, defaults, selection).
  • CI on the draft PR: all checks pass (CI passed, Test, Lint, Docs, Smoke test, Scan image, CodeQL, codecov/patch and codecov/project).

Declined review findings

  • Move the structural checks of the settings to Bean Validation (quality, medium). Declined: the security checks (https, asymmetric algorithms, duplicate issuers and clients, an issuer that accepts nothing) are cross-field checks and have to stay in code. Splitting the checks between annotations and code would put them in two places. All the checks are in one place now, with the property paths in their messages.

  • Refuse unlisted clients own tokens (sub == client claim, client not listed), or require the client claim to be one of the audiences (adversarial, low). Declined for now: the design matrix treats an unlisted client with a valid token as an authenticated caller without the create right (row 9, 403 on create), and whether azp can be bound to the front ends depends on the pending LS Login user-token check.

  • Make IssuerVerifier shared with ServiceClientTokenServices now instead of copying (quality, medium). Declined for this slice: it would touch the class that a parallel slice (removal of the group model) changes, and the wiring slice deletes it anyway. I added keep-in-sync notes to both copies instead.

  • Make the thread-based IssuerVerifier tests drive two real requests instead of setting the field by reflection (quality round 2, medium). Declined: the test exercises exactly the re-check branch, and its waits are condition-based (no timing assertions).

  • Track the duplicate key handling and the registration of the settings in an issue (quality round 2, low). Covered by the wiring issue (see the design slice plan), which deletes ServiceClientTokenServices and registers and documents the settings.

Open questions

  • Should the per-client allowAnyAudience opt-in of the current service-client settings carry over into the new pipeline, or does "aud = the client's own ID" replace it? The config format (a list of objects per client) allows either without rework. This needs a decision before the wiring slice.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5

uniqueg and others added 4 commits November 25, 2026 00:19
Add the token validation of the access control redesign (D-388) as
its own package, behind one interface (TokenValidator), with the
implementation selected by tesk.api.auth.token-validator (only jwt
for now; introspection can be added later, D-408).

JwtAccessTokenValidator accepts single signed JWT access tokens
(typ at+jwt) of the configured issuers (exact iss), checked against
the issuer's keys from its discovery or a JWKS URI, with asymmetric
algorithms only, exp, iat and sub required, nbf, max age and clock
skew. User tokens need one of the issuer's audiences (front-end
client IDs); listed service clients (client claim and sub both the
client ID) need their own ID in aud (D-392). Users with a listed
client's ID and delegated tokens (act) are refused. The caller is
identified by <iss>|<sub>.

Not wired into the request authentication yet. The key handling of
ServiceClientTokenServices is reused in IssuerVerifier (a copy until
the switch removes that class).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Explain the rules in the Javadoc instead of citing decision records,
log refusals at INFO (callers without a valid token control their
rate) and accepted service clients at DEBUG, use switch expressions,
and note in ServiceClientTokenServices that its key handling has a
copy in IssuerVerifier until it is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Requests that arrive while the keys of an issuer are fetched now wait
for that fetch (bounded by the timeouts) instead of being refused, and
unavailable keys raise IssuerUnavailableException (for 503) instead
of InvalidTokenException (401), so that clients retry.

Also: the clock skew is the whole leeway for iat in the future (jose4j
adds it to the configured allowance), timeout-seconds is at most 300
(no int overflow of the milliseconds), TokenPrincipal.toString leaves
out the claims (personal data), and a token of one issuer signed with
another issuer's key is tested to be refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
Only the first attempt to fetch an issuer's keys makes other requests
wait (at most 15 s); later attempts refuse at once, so that forged
tokens of a dead issuer can't hold request threads. Keys that can't
be fetched again after the cache expired are reported as unavailable
(IssuerUnavailableException) instead of an invalid token. A failed
fetch is logged once at WARN, refused requests at INFO. timeout-seconds
is at most 60. Docs say that callers map the exceptions to 401/503.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqN5w1v5t1QRTKU7ad5
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the caller identity and validation settings that the validator depends on, including issuer, audience, client, algorithm, and token-lifetime data.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/TokenPrincipal.java L1-61
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/TokenValidationProperties.java L1-176

API

Expose the token-validation contract, its refusal and issuer-unavailable outcomes, and the factory that selects a validator.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/InvalidTokenException.java L1-17
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/IssuerUnavailableException.java L1-18
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/TokenValidator.java L1-23
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/TokenValidators.java L1-26

Implementation

Implement JWT access-token parsing, issuer-specific signature and claim checks, caller classification, and unavailable-key handling through the issuer verifier.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/IssuerVerifier.java L1-287
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/token/JwtAccessTokenValidator.java L1-339

Record that the existing service-client introspector has copied key-handling logic that must stay synchronized until replacement.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ServiceClientTokenServices.java L72-74

Documentation

Document the token-validation design, issuer and token rules, configuration properties, and the fact that authentication does not yet use the validator.

  • docs/development.md L130-189

Tests

Test issuer URL security, key fetching and refresh throttling, concurrent first-use behavior, and unavailable-key signaling.

  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/token/IssuerVerifierTest.java L1-277

Exercise JWT acceptance and refusal rules, issuer-key isolation and outages, caller classification, and startup configuration validation.

  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/token/JwtAccessTokenValidatorTest.java L1-932

Verify property binding and defaults, validator selection, principal identity and safe string representation, and generic error reasons.

  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/token/TokenValidatorsTest.java L1-124

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 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (db99a2d) to head (1caa45f).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #221    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           56        63     +7     
  Lines         2612      2929   +317     
  Branches       313       361    +48     
==========================================
+ Hits          2612      2929   +317     

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

This branch has not been deployed

No deployments
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: validate JWT access tokens

1 participant