Skip to content

feat: request access tokens per TES backend - #488

Merged
uniqueg merged 7 commits into
devfrom
feat/397-backend-audience
Nov 13, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/397-backend-audience

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

proTES can now request a separate access token for each TES backend, so backends (including those discovered in service registries) can't replay their tokens at each other. This is opt-in; nothing changes by default.

  • custom.tes.client_credentials.audience_parameter: resource (RFC 8707 resource indicators) or audience (the name some identity providers use). The default is null: one token for all backends, as before.
  • audience on entries of configured TES instances (type: ga4gh-tes) is the value sent for that backend, taken as written. Without it, the backend's normalized URL is sent. Discovered backends always send their base URL (normalized, without the TES API path).
  • Validation of audience:
    • it needs auth: client_credentials and audience_parameter;
    • it must not have surrounding whitespace;
    • for resource, it must be an absolute URI without query and fragment, of valid characters, percent escapes and port.
  • Token cache:
    • It is keyed by token endpoint, client, scope and audience.
    • It is keyed by the audience parameter too. Each token is fetched by one thread at a time; fetches in progress are tracked under the cache lock with a condition variable, never holding the lock during token requests. A slow token request for one audience does not hold up the other backends, and while a token is being refreshed, other threads use the cached copy.
    • Expired tokens are removed whenever a token is fetched.
  • Errors of token requests name the audience: No access token for resource '<audience>' from <endpoint>: ....
  • The startup log reads: TES backends with access tokens of proTES (each for its own audience, requested with resource): ....
  • Chart: tes.backends[].audience is added to the values schema (the key is the same in camelCase), plus values comments and a README note.
  • Docs:
    • docs/access-control.md gets a new "Tokens per TES instance" section: what the identity provider and the TES instances must do for this to help, and how to test it.
    • docs/configuration.md links to that section.
    • docs/upgrading.md gets a new "To version 0.7.0" section.

The issue's other option, no default auth for registry entries, is not part of this PR. That default comes from FOCA, and changing it would break existing configs. With audience_parameter set, discovered backends get tokens for their own URLs instead. No FOCA change is needed: the new entry field lives in proTES' TesServiceEntry, and registry entries need none.

Some identity providers set a client's audience once, at registration, and ignore or refuse resource/audience in token requests. With those, the setting doesn't help. The docs say so and recommend checking a decoded token before relying on the setting.

Closes #397

Verification

  • coverage run -m pytest -W ignore::DeprecationWarning (with chart dependencies built): all passed, coverage 100%.
  • pre-commit run --all-files: all hooks passed.
  • mkdocs build --strict: no warnings.
  • The new tests use only a mock identity provider. They cover:
    • token requests and caching per audience, for both parameters;
    • no audience in requests when the setting is off;
    • errors that name the audience;
    • concurrency: no blocking across audiences, a single fetch per token, the cached token used while a refresh is pending;
    • pruning of expired tokens;
    • per-entry and URL audiences for configured backends, URL audiences for discovered backends;
    • config validation;
    • the startup log;
    • chart rendering and schema.
  • Full review: adversarial-reviewer and quality-reviewer, 2 rounds; Sourcery (5 medium threads, all fixed). I fixed every medium finding and most lows.
  • CI: all checks passed (CI passed, Test on mongomock and MongoDB 7.0, Integration, Chart, Docs, Lint, Smoke test, Scan image, CodeQL, Read the Docs); no open code scanning alerts.

Declined review findings

  • Quality r1: in _fetch_token, the check idp.audience_parameter is not None repeats a guard in get_token. I kept it because mypy needs the narrowing to use the parameter as a dict key, and it keeps the static method correct on its own.
  • Quality r1: add audience to a commented example in deployment/values.yaml. Declined: the chart's examples are validated against the app config, and audience without audience_parameter is refused there. The values comments describe the key in prose instead. The other half of that finding was wrong: the schema already allows audience only on ga4gh-tes entries.
  • Quality r1: the 0.7.0 heading in docs/upgrading.md isn't confirmed. Declined: 0.7.0 is the issue's milestone, and release notes are written in the release-prep PR.
  • Adversarial r2: discovery of the issuer's token endpoint still runs under the cache lock, and its failures are not cached. Declined: this only matters until the first discovery succeeds (one issuer per config), and the behaviour is unchanged from dev. A comment now says so.
  • Adversarial r2: default audiences (backend URLs) are not validated against the resource rules. Declined: they are normalized URLs. A URL with a query fails at the identity provider with an error that names it.
  • Adversarial r2: no backoff after failed refreshes. Declined as out of scope. With the cached copy used during a refresh, only one thread per token waits for the identity provider.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV

uniqueg and others added 6 commits November 13, 2026 06:24
With `custom.tes.client_credentials.audience_parameter` (`resource`,
RFC 8707, or `audience`), proTES names the TES backend in each token
request: the `audience` of a configured backend's entry, or else the
backend's URL (always the URL for backends discovered in a registry).
Tokens are cached per endpoint, client, scope and audience, so a
backend that checks the audience refuses the tokens of the others.
Expired tokens are removed from the cache whenever a token is fetched.

Entries with `audience` need `audience_parameter`; for `resource`, the
audience must be an absolute URI without fragment. The startup log
says when each backend gets its own token. By default nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
`tes.backends[].audience` of TES instances is rendered into the app
config as it is; the values and the chart's README point to
`config.custom.tes.client_credentials.audience_parameter`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Access control gets a section on `audience_parameter` and `audience`,
with what the identity provider and the TES instances must do for it
to help; configuration links to it, and upgrading gets a section for
0.7.0 with the opt-in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Review fixes:

- The token cache's lock no longer covers token requests: each token
  key has a fetch lock of its own, so a slow request for one audience
  doesn't hold up backends with fresh cached tokens.
- Errors of token requests name the requested audience.
- `audience` needs `auth: client_credentials`, must not have
  surrounding whitespace, and for `resource` must be an absolute URI
  without query and fragment.
- Docs: the base URL of discovered backends, the cache per audience,
  the exact log and error texts; a duplicated docstring line removed.
- Tests: fakes of `get_token` match its signature; more cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Second review round:

- While one thread refreshes a token, others use the cached token
  instead of waiting for the identity provider.
- Fetch locks of fetches in progress are kept when expired tokens are
  pruned, so a token is still fetched once.
- Comments and docs: the lock and discovery, the quoted audience in
  error messages, the `TokenKey` cross-reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@uniqueg uniqueg added this to the v0.7.0 milestone Nov 13, 2026
@uniqueg uniqueg self-assigned this Nov 13, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add the client-credentials audience setting and per-TES-entry audience field that define how backend token audiences are represented.

  • pro_tes/config_models.py L276-282, L378-384 (+3 small edits)

Implementation

Validate audience configuration and implement audience-keyed token requests, caching, backend audience selection, and request integration.

  • pro_tes/config_models.py L335-361, L518-558
  • pro_tes/ga4gh/tes/backends.py L196-213, L284-329, L476-498 (+12 small edits)

UI

Update the startup log to indicate when each TES backend receives a token for its own audience.

  • pro_tes/security.py L225-235

Configuration

Expose the per-backend audience option in Helm values, validate it in the chart schema, and add chart configuration comments.

  • deployment/values.schema.json L543-547
  • deployment/values.yaml L71-74, L127-130

Documentation

Document per-instance tokens, their configuration and security requirements, and the version 0.7.0 upgrade option.

  • deployment/README.md L79-82
  • docs/access-control.md L286-289, L302-317, L358-417
  • docs/configuration.md L81-86
  • docs/upgrading.md L5-6, L13-42

Tests

Add coverage for audience-specific token requests, validation, backend selection, concurrency, caching, logging, and chart rendering.

  • tests/ga4gh/tes/test_backend_list.py L663-693 (+4 small edits)
  • tests/ga4gh/tes/test_backends.py L330-480, L623-657, L828-1003 (+3 small edits)
  • tests/test_chart.py L1124, L1151, L1216-1219
  • tests/test_security.py L373-394

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

@read-the-docs-community

read-the-docs-community Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35860058 | 📁 Comparing 9fa8af6 against latest (4bbca3d)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4bbca3d) to head (9fa8af6).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #488   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           31        31           
  Lines         3038      3105   +67     
=========================================
+ Hits          3038      3105   +67     

☔ 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 13, 2026 06:13
@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 9fa8af6

#397 feat: request backend-specific access tokens · 1 of 1 met

# Requirement Status Notes
1 Support backend-specific access tokens, with tokens cached per audience. ✅ Met The PR requests tokens using each configured backend's audience or normalized URL, and uses discovered backends' base URLs. The existing shared-token behavior remains the default; the docs describe the identity-provider and backend checks needed for audience separation to prevent replay.

@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="pro_tes/ga4gh/tes/backends.py" line_range="343" />
<code_context>
+                    # tokens are still fetched once; those of keys without
+                    # tokens (failed fetches) stay, bounded by the backends
+                    if not self._fetch_locks[stale].locked():
+                        del self._fetch_locks[stale]
+                self._tokens[key] = new
+            return new.value
</code_context>
<issue_to_address>
**Concurrent token fetches**

When a caller has retrieved an expired key’s unlocked fetch lock but has not acquired it when another successful fetch prunes that key, `_fetch_locks` drops the lock while the caller still holds its reference, so a later caller creates a replacement and both fetch the same key; the slower response can overwrite the newer cached token, leaving callers with an already-expired token.

Keep a per-key lock registered until no caller can still hold a reference to it, rather than pruning it based only on whether it is locked.

Also at `pro_tes/ga4gh/tes/backends.py:303-309`, `pro_tes/ga4gh/tes/backends.py:341`, `pro_tes/ga4gh/tes/backends.py:344`.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/backends.py" line_range="298" />
<code_context>
-            key = (endpoint, client_id, idp.scope)
-            token = self._tokens.get(key)
-            if token is not None and time.monotonic() < token.refresh_at:
+        key = TokenKey(endpoint, client_id, idp.scope, audience)
+        token, fresh = self._cached(key)
+        if token is not None and fresh:
</code_context>
<issue_to_address>
**Different token requests share a cache entry**

When the same process uses TES configurations with the same endpoint, client, scope, and audience but different `audience_parameter` values, `TokenKey` omits `audience_parameter`, so calls with otherwise identical keys but different parameters reuse a token requested with the first parameter; the second caller then sends a token that may not match its configured request, and the backend rejects it.

Include `audience_parameter` in `TokenKey` and its construction, or scope the cache to a single configuration.
</issue_to_address>

### Comment 3
<location path="pro_tes/config_models.py" line_range="525-529" />
<code_context>
+                    f"`audience` of {entry.url} must not have surrounding whitespace"
+                )
+            if parameter == "resource":
+                parts = urlsplit(audience)
+                if (
+                    not parts.scheme
+                    or not (parts.netloc or parts.path)
+                    or "?" in audience
+                    or "#" in audience
+                ):
</code_context>
<issue_to_address>
**Invalid audiences pass validation**

When a `resource` audience has a scheme and nonempty authority or path but malformed URI syntax, `urlsplit` and the component checks accept malformed values such as spaces, invalid percent escapes, or a non-numeric port, so the audience reaches the identity provider, which rejects the token request and prevents tasks from reaching that backend.

Validate the audience’s URI syntax in addition to checking its components, scheme, query, and fragment.
</issue_to_address>

### Comment 4
<location path="pro_tes/ga4gh/tes/backends.py" line_range="307" />
<code_context>
+        key = TokenKey(endpoint, client_id, idp.scope, audience)
+        token, fresh = self._cached(key)
+        if token is not None and fresh:
+            return token.value
+        with self._lock:
+            fetch_lock = self._fetch_locks.setdefault(key, threading.Lock())
</code_context>
<issue_to_address>
**Expired token returned during refresh**

When a caller is paused after the expiry check until the cached token expires, while another thread holds the fetch lock for its refresh, the cached token is checked for expiry before the nonblocking lock attempt, but this branch returns it without checking again. If the caller is delayed until the token expires while another thread holds the fetch lock, `_request_params` sends the expired token and the TES backend rejects the request.

Recheck expiry before returning the cached token; if it has expired, wait for the refresh instead.
</issue_to_address>

### Comment 5
<location path="pro_tes/ga4gh/tes/backends.py" line_range="303" />
<code_context>
+        if token is not None and fresh:
+            return token.value
+        with self._lock:
+            fetch_lock = self._fetch_locks.setdefault(key, threading.Lock())
+        if token is not None and time.monotonic() < token.expires_at:
+            # being refreshed by another thread: use it meanwhile
</code_context>
<issue_to_address>
**Failed-fetch locks accumulate**

When token requests fail for many distinct, possibly transient, discovered backend URLs, failed fetches leave entries in `_fetch_locks` without cached tokens, and the pruning loop only removes locks for expired cached tokens, so the lock objects accumulate and increase process memory use.

Remove failed-fetch lock entries once no caller or waiter can still use them.

Also at `pro_tes/ga4gh/tes/backends.py:342`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and when per-backend audiences are enabled, proTES requests and sends bearer tokens based on each backend’s configured audience or URL. If that mapping or token handling is wrong, a token could be accepted by an unintended TES backend; reverting stops future requests but cannot recall tokens already issued or undo any access they enabled.

Blocking findings: pro_tes/ga4gh/tes/backends.py:343, pro_tes/ga4gh/tes/backends.py:298, pro_tes/config_models.py:529, pro_tes/ga4gh/tes/backends.py:307, pro_tes/ga4gh/tes/backends.py:303


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

Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/config_models.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Sourcery review:

- Fetches in progress are a set guarded by the cache's lock, with a
  condition that is notified when a fetch ends, instead of a lock per
  key: no locks to prune or leak, and whether a cached token can still
  be used while it is refreshed is checked under the lock.
- The cache key includes the audience parameter.
- `resource` audiences must be URIs of valid characters, with valid
  percent escapes and port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@uniqueg
uniqueg merged commit 90a9254 into dev Nov 13, 2026
51 checks passed
@uniqueg
uniqueg deleted the feat/397-backend-audience branch November 13, 2026 06:51
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: request backend-specific access tokens

1 participant