Repository navigation
feat: request access tokens per TES backend - #488
Conversation
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
Reviewer's GuideData structuresAdd the client-credentials audience setting and per-TES-entry audience field that define how backend token audiences are represented.
ImplementationValidate audience configuration and implement audience-keyed token requests, caching, backend audience selection, and request integration.
UIUpdate the startup log to indicate when each TES backend receives a token for its own audience.
ConfigurationExpose the per-backend audience option in Helm values, validate it in the chart schema, and add chart configuration comments.
DocumentationDocument per-instance tokens, their configuration and security requirements, and the version 0.7.0 upgrade option.
TestsAdd coverage for audience-specific token requests, validation, backend selection, concurrency, caching, logging, and chart rendering.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 9fa8af6 #397 feat: request backend-specific access tokens · 1 of 1 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="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 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
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) oraudience(the name some identity providers use). The default isnull: one token for all backends, as before.audienceon 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).audience:auth: client_credentialsandaudience_parameter;resource, it must be an absolute URI without query and fragment, of valid characters, percent escapes and port.No access token for resource '<audience>' from <endpoint>: ....TES backends with access tokens of proTES (each for its own audience, requested withresource): ....tes.backends[].audienceis added to the values schema (the key is the same in camelCase), plus values comments and a README note.docs/access-control.mdgets 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.mdlinks to that section.docs/upgrading.mdgets a new "To version 0.7.0" section.The issue's other option, no default
authfor registry entries, is not part of this PR. That default comes from FOCA, and changing it would break existing configs. Withaudience_parameterset, 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/audiencein 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.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
_fetch_token, the checkidp.audience_parameter is not Nonerepeats a guard inget_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.audienceto a commented example indeployment/values.yaml. Declined: the chart's examples are validated against the app config, andaudiencewithoutaudience_parameteris refused there. The values comments describe the key in prose instead. The other half of that finding was wrong: the schema already allowsaudienceonly onga4gh-tesentries.docs/upgrading.mdisn't confirmed. Declined: 0.7.0 is the issue's milestone, and release notes are written in the release-prep PR.dev. A comment now says so.resourcerules. Declined: they are normalized URLs. A URL with a query fails at the identity provider with an error that names it.Open questions
None.
🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV