Repository navigation
feat!: call TES backends with service tokens - #251
Conversation
proTES no longer passes credentials of callers on to TES backends. Each backend of `custom.tes.service_list` is an object with its URL and `auth`: - `client_credentials` (default): an access token of proTES itself, from the OAuth 2.0 client credentials grant at the configured token endpoint (or the issuer's discovery document); cached per process and fetched anew before it expires, for every request, also in the Celery worker. Client ID and secret come from PROTES_CLIENT_ID and PROTES_CLIENT_SECRET only. - `basic`: HTTP Basic credentials from the environment variables named in the config (transitional). - `none`: no credentials. The app refuses to start if credentials of a backend are missing, and warns of backends with `basic` or `none`. Backend and identity provider URLs must be `https` unless `custom.tes.url_schemes` allows `http`; backends that middlewares add, but are not configured, are skipped. Basic credentials are no longer parsed from requests, stored (`basic_auth`) or sent to Celery; a startup migration removes them, and credentials in input and output URLs, from stored tasks. Tasks with credentials in input or output URLs are rejected (`400`), or stripped with `custom.controllers.post_task.url_credentials: strip`, before they are stored; the Funnel exception is gone. The base config lists no backends anymore. The smoke test authenticates at the fake backend with a token of proTES, which the fake backend requires. BREAKING CHANGE: `custom.tes.service_list` entries are objects (`url`, `auth`), backends get proTES' own token by default, tasks with credentials in URLs are rejected, and the Celery task takes no credentials anymore. Closes #213 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe the `auth` modes of TES backends, the client of proTES and its environment variables, the URL scheme and URL credential settings, and how to upgrade existing configs and stored tasks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Strip credentials also from outputs logged in stored tasks (earlier versions forwarded them to Funnel, which logs output URLs). - Keep using a cached token until it expires if fetching a new one fails, instead of failing right away. - Check the credentials of TES backends when the Celery worker starts, so that a worker without them doesn't start. - Map missing credentials and unconfigured backends to problem details (cancellation), and fail clearly for `auth: basic` without `basic`. - Pass PROTES_CLIENT_ID and PROTES_CLIENT_SECRET through Docker Compose. - Document that all token backends get the same token, the Compose and chart status, and that credentials added by middlewares are removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Remove credentials from the URLs of outputs that backends log before the task tracker stores them, so that tasks forwarded by earlier versions don't get them back after the startup migration. - Fail the backend check for `auth: basic` without `basic`, instead of logging it as `auth: none`. - Re-wrap two docs paragraphs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flagged log calls log backend URLs and the messages of BackendAuthError, which name endpoints and error types only, never tokens or client secrets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideReworks proTES backend communication so every configured TES instance is contacted with proTES-owned, per-backend-configured credentials—preferably cached OAuth client-credentials tokens—while eliminating caller credential propagation, sanitizing legacy and newly submitted task data, enforcing secure backend configuration, and covering the complete app, worker, and smoke-test flow. Sequence diagram for authenticated TES task forwardingsequenceDiagram
actor Caller
participant ProTES
participant IdP
participant TES
Caller->>ProTES: POST /tasks
ProTES->>ProTES: _handle_url_credentials()
ProTES->>ProTES: create_client()
ProTES->>ProTES: TokenProvider.get_token()
alt Cached token is reusable
ProTES-->>ProTES: Use cached token
else Token requires refresh
ProTES->>IdP: POST token endpoint
IdP-->>ProTES: Bearer access token
ProTES-->>ProTES: Cache token
end
ProTES->>TES: create_task() with proTES Bearer token
TES-->>ProTES: Remote task ID
ProTES-->>Caller: Local task ID
Sequence diagram for Celery task tracking with refreshed backend credentialssequenceDiagram
participant Celery
participant ProTES
participant TES
Celery->>ProTES: task__track_task_progress()
ProTES->>ProTES: create_client()
ProTES->>ProTES: TokenProvider.get_token()
ProTES->>TES: get_task() with current backend credentials
TES-->>ProTES: Task state and logs
ProTES->>ProTES: strip_auth() from logged output URLs
ProTES-->>Celery: Update stored task state
Flow diagram for backend credential validation and startupflowchart TD
Start[App or Celery worker starts] --> Load[Load custom.tes configuration]
Load --> Validate[Validate backend URLs and auth modes]
Validate --> Check["check_backends()"]
Check --> Missing{Required environment credentials missing?}
Missing -->|Yes| Refuse[Refuse startup]
Missing -->|No| Migrate["remove_stored_credentials()"]
Migrate --> Ready[Accept requests or track tasks]
Flow diagram for task URL credential handlingflowchart TD
Receive[Receive task] --> Inspect["_handle_url_credentials()"]
Inspect --> Credentials{Input or output URL has credentials?}
Credentials -->|No| Middleware[Apply middlewares]
Credentials -->|Reject mode| BadRequest[Return 400 Bad Request]
Credentials -->|Strip mode| Remove["strip_auth() before storing"]
Remove --> Middleware
Middleware --> StripAdded["strip_auth() for credentials added by middleware"]
StripAdded --> Configured{Backend is configured?}
Configured -->|No| Skip[Skip backend]
Configured -->|Yes| Relay["_relayed_task() and forward with backend credentials"]
File-Level Changes
Assessment against linked issues
Possibly linked issues
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 #251 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 25 26 +1
Lines 1226 1517 +291
==========================================
+ Hits 1226 1517 +291 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pro_tes/utils/db.py" line_range="69-71" />
<code_context>
+ result.modified_count,
+ )
+ # URLs with user information (`scheme://user:password@host...`)
+ pattern = {"$regex": "^[^/?#]*//[^/?#]*@"}
+ fields = [*FILE_FIELDS, LOG_OUTPUTS_FIELD]
+ query = {"$or": [{f"{field}.url": pattern} for field in fields]}
+ stripped = 0
+ for document in collection.find(
</code_context>
<issue_to_address>
**Legacy URL credentials survive migration**
When A previously stored input or output URL has leading whitespace before a credential-bearing URL, `remove_stored_credentials` only fetches URLs matching the anchored MongoDB regex, so a stored URL with leading whitespace is skipped even though `has_credentials` recognizes its user information after `urlsplit` trims that whitespace. The legacy credentials remain in the database after startup.
Ensure the migration query also selects URLs whose leading whitespace is ignored by `urlsplit`, or scan the relevant stored URL fields without that restrictive prefix filter.
</issue_to_address>
### Comment 2
<location path="pro_tes/config_models.py" line_range="359" />
<code_context>
+ if not (parts.scheme and parts.hostname):
+ raise ValueError(f"TES backend URL without scheme or host: {self.url!r}")
+ if has_credentials:
+ raise ValueError(
+ "TES backend URLs must not have credentials; use `auth: basic`"
+ " with credentials from the environment"
</code_context>
<issue_to_address>
**Hostless token URLs pass validation**
When the configured issuer or token endpoint has an allowed scheme but no hostname, `Tes.check_urls` accepts the URL, so the app starts and `TokenProvider` later fails during discovery or token retrieval, leaving token-authenticated backends unusable.
Require a hostname when validating the configured issuer and token endpoint.
Also at `pro_tes/config_models.py:357-358`, `pro_tes/ga4gh/tes/backends.py:189-191`.
</issue_to_address>
### Comment 3
<location path="pro_tes/ga4gh/tes/backends.py" line_range="190" />
<code_context>
+ endpoint = document.get("token_endpoint")
+ if not (
+ isinstance(endpoint, str)
+ and urlsplit(endpoint).scheme in config.url_schemes
+ ):
+ raise BackendAuthError(
</code_context>
<issue_to_address>
**Malformed token URLs bypass auth handling**
When the identity provider returns a discovery document with a malformed `token_endpoint` URL, `urlsplit` raises `ValueError` in `_get_token_endpoint`, which escapes as a non-`BackendAuthError`; `TaskRuns.create_task` then aborts relay instead of handling the backend failure, and the caller gets a server error with the stored task left in `UNKNOWN`.
Catch the parsing `ValueError` and raise `BackendAuthError` so task creation handles the failure through its backend-failure path.
</issue_to_address>
### Comment 4
<location path="pro_tes/config_models.py" line_range="256" />
<code_context>
+ has_credentials = parts.username is not None or parts.password is not None
+ except ValueError as exc:
+ raise ValueError(f"Invalid TES backend URL: {self.url!r}") from exc
+ if not (parts.scheme and parts.hostname):
+ raise ValueError(f"TES backend URL without scheme or host: {self.url!r}")
+ if has_credentials:
</code_context>
<issue_to_address>
**Invalid backend port passes validation**
When A configured TES backend URL contains a nonnumeric or out-of-range port, `TesBackend.check_backend` checks the URL scheme and hostname but never validates the port. A URL such as `https://tes.example.org:bad` therefore passes startup validation, then fails when requests uses it, so the configured backend cannot receive tasks.
Validate the parsed port during backend configuration validation and reject invalid values at startup.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 4 findings to address first, and proTES sends the same bearer token to every configured TES backend, so a misconfigured or untrusted backend can use that token until it expires; reverting stops future sends but cannot claw back a token already exposed. Startup also removes stored caller credentials and URL user information, which reverting will not restore.
Blocking findings: pro_tes/utils/db.py:71, pro_tes/config_models.py:359, pro_tes/ga4gh/tes/backends.py:190, pro_tes/config_models.py:256
- Reject URLs of TES backends with invalid ports, and URLs of the issuer and token endpoint without host or with invalid ports, at startup. - Treat malformed or hostless token endpoints in discovery documents as authentication failures of the backend, instead of letting a ValueError abort the relay. - Test that the migration also strips URLs with leading whitespace. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # docs/upgrading.md # pro_tes/app.py # pro_tes/ga4gh/tes/task_runs.py # tests/ga4gh/tes/test_server.py # tests/smoke/check.sh
The chart now has `protes.extraEnv`: name the variables of the credentials of TES instances in its README, and point to it instead of the issue of the chart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
proTES now authenticates at TES backends with credentials of its own, never with those of its callers (#213, child of #201).
auth(custom.tes.service_listentries are now objects:url,auth, optionalbasic):client_credentials(default): proTES's own access token, from the OAuth 2.0 client credentials grant atcustom.tes.client_credentials.token_endpoint, or the token endpoint of the issuer's OpenID Connect discovery document. The token is cached per process and fetched againrefresh_beforeseconds before it expires (at most half its lifetime). It is looked up for every request, so the Celery worker's long polling also gets fresh tokens. The client ID and secret come only fromPROTES_CLIENT_IDandPROTES_CLIENT_SECRET. The token request usesclient_secret_basic(RFC 6749 §2.3.1 encoding) orclient_secret_post, and follows no redirects.basic: HTTP Basic credentials from the environment variables named inbasic.username_env/basic.password_env. Transitional: to be removed once all nodes accept tokens.none: no credentials.basicandnonebackend, when no backends are configured, and whenhttpis allowed.500), also on cancellation.parse_basic_auth(),BasicAuthandDbDocument.basic_authare removed. The Celery task no longer takesuser/password. A startup migration removesbasic_auth, and credentials in input/output URLs (also in the outputs that backends such as Funnel logged), from stored tasks (S2). The task tracker also removes credentials from the output URLs that backends log, so that tasks forwarded by earlier versions don't get them back.user:password@in input or output URLs are rejected with400(default), or stripped (custom.controllers.post_task.url_credentials: strip) before anything is stored. Credentials that middlewares add are always stripped. The Funnel exception (Funnel got the credentials) and its service-info probe are gone.httpsunlesscustom.tes.url_schemesallowshttp(for local tests). Backend URLs with credentials, and duplicate backends, are rejected.service_list: []). All examples use fictitiousexample.orgvalues.TaskRuns._relayed_task()builds each backend's copy of the task. This is where the user identity tags (Q4, decided to come later) belong. None are set yet.PROTES_CLIENT_ID/PROTES_CLIENT_SECRETto the app and the worker.docs/access-control.md(Credentials of TES instances),docs/configuration.md,docs/api.md,docs/middlewares.md,docs/upgrading.md, README,config.dev.yaml. proTES has no deployment handover notes in the repo.Breaking changes
custom.tes.service_list: entries are objects (url,auth) instead of URLs, andauthdefaults toclient_credentials. The base list is empty.400), also for Funnel backends.tasks.track_run_progresstakes nouser/passwordanymore. The new worker rejects tracking jobs queued by earlier versions.custom.tes.service_listget objects instead of URLs.All of these are described in
docs/upgrading.md.For the chart (#216)
PROTES_CLIENT_IDandPROTES_CLIENT_SECRET, e.g. from a Secret, if any backend hasauth: client_credentials(the default).auth: basicneed the environment variables named in their config (basic.username_env,basic.password_env). The names are chosen by the deployment. The chart (merged in build(chart)!: use the FOCA library chart #252) sets all of them withprotes.extraEnv. This PR names the variables in the chart README's example.configvalue:custom.tes.service_list,custom.tes.url_schemes(default[https]),custom.tes.client_credentials(issuer/token_endpoint,scope,auth_method,refresh_before,timeout), andcustom.controllers.post_task.url_credentials.security.auth.audience.How it was verified
.venv/bin/coverage run -m pytest -W ignore::DeprecationWarning→ 533 passed, 76 skipped (chart tests that need tools not installed locally; after merging origin/dev with feat(access-control)!: own tasks per user #250 and build(chart)!: use the FOCA library chart #252);coverage report→ 100%pre-commit run --all-files(ruff, ruff-format, semgrep, gitleaks, actionlint, ast-grep, mypy) → all passedmkdocs build --strict→ built without warningsdocker compose up -d --build --waitwithtests/smoke/compose.yaml, thentests/smoke/check.sh) → "Smoke test passed" locally before the merge with feat(access-control)!: own tasks per user #250, and in CI ("Run app with Docker Compose") after it. The task was relayed and tracked toCOMPLETEwith proTES's client-credentials token, which the fake backend requires.Declined review findings
client_credentialsbackend gets the same proTES token, so a malicious backend could replay it at the others. This is the agreed MVP policy (one proTES client; token exchange is the target). The risk is documented indocs/access-control.md: configure only trusted backends and use short token lifetimes._relayed_task(): kept as the explicit extension point for user identity tags, as the maintainer asked.[^/?#]*matches leading whitespace too, and the migration test now covers it.python-logger-credential-disclosure(push hook): suppressed inline; the two log calls log backend URLs andBackendAuthErrormessages, which name endpoints and error types only.Open questions
None blocking. Follow-up proposed: an issue for the user identity tags (names, and the Conquest on-behalf-of path, Q4), since this PR closes #213 without them.
Closes #213
🤖 Generated with Claude Code