Repository navigation
feat(plugins): add credentials of backends - #796
Conversation
Move proTES's token client and startup checks into FOCA, generic for TES and WES gateways (foca.plugins.backends.credentials): - ClientCredentialsConfig: the gateway's client at its identity provider (issuer or token endpoint, URL schemes, scope, audience parameter, auth method, refresh margin, timeout), embedded next to the backend list; check_client_credentials() checks both. - TokenProvider: client credentials grant (RFC 6749, section 4.4), cached per process and key, refreshed before expiry, one fetch per key at a time, cached token used while a refresh fails; client ID and secret from environment variables the gateway names. - get_credentials(): Bearer token (per audience, if requested), HTTP Basic from the environment, or none, as a requests auth object that replaces the caller's Authorization header and keeps .netrc out; BackendSession takes no .netrc credentials after redirects. - check_backends(): startup checks and logs, as in proTES. - ServiceEntry.audience: audience of the gateway's tokens. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the review of the credentials of backends: - Ask the identity provider without holding the provider's lock: discovery is single-flight per issuer, like token fetches. - Return a failed fetch or discovery for 5 seconds (FAILURE_RETRY) instead of retrying it per waiting thread. - Don't follow redirects of discovery documents either. - Bound token lifetimes (finite, at most 24 hours; digit strings count as seconds). - Read credentials as FOCA's get_env does, also from <name>_FILE. - Release waiting threads with try/finally; BackendList.is_own(). - Export only what gateways need; document all of it in the API reference, with imports in the examples. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresAdd backend audience configuration and expose whether entries or registries use gateway tokens, establishing the data consumed by credential resolution.
Make the backend-list ownership check public so startup validation can reuse the same definition of backends that point back to the gateway.
APIDefine the public client configuration, credential objects, token provider, request session, resolver, and startup-check interfaces, and re-export them from the backend package.
ImplementationImplement credential validation, environment and file secret loading, safe Authorization handling, token discovery and caching, audience resolution, and backend startup checks.
DocumentationDocument backend credential configuration, migration expectations, and the newly exposed API.
TestsAdd coverage for configuration validation, credential resolution, token fetching and caching, security protections, concurrency, and startup checks.
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 #796 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 75 76 +1
Lines 10082 10550 +468
==========================================
+ Hits 10082 10550 +468
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Address the second review of the credentials of backends: - Reset the locks and fetches in progress of token providers in forked processes (Gunicorn, Celery workers). - Bound waits for another thread's fetch (WAIT_FACTOR x timeout). - Store nothing from fetches that clear() overtook. - Turn plain OSError of requests (e.g., missing CA bundle) into request errors, so they become cached CredentialsError. - Bound huge integer expires_in without float overflow. - Prune expired discovery failures; BackendList.is_own() only. - Rewrap and clarify the docs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Linked issuesChecked at commit f08d759 #794 feat(plugins): add credentials of backends · 5 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 12 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/backends/credentials.py" line_range="878-880" />
<code_context>
+ deadline = time.monotonic() + WAIT_FACTOR * client.timeout
+ with self._fetched:
+ while True:
+ cached = self._token_endpoints.get(issuer)
+ if cached is not None:
+ return cached
+ if issuer not in self._discovering:
+ failure = self._discovery_failures.get(issuer)
</code_context>
<issue_to_address>
**Client secrets go to HTTP endpoints**
When the same provider is used for the same issuer with different `url_schemes`, and the permissive client discovers an HTTP endpoint first, `_get_token_endpoint()` returns the issuer-cached endpoint without checking the current client’s schemes, so `_fetch_token()` sends the client credentials to that HTTP endpoint.
Validate each cached endpoint against the current client’s `url_schemes` before returning or using it.
Also at `foca/plugins/backends/credentials.py:901`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/backends/credentials.py" line_range="1022" />
<code_context>
+ # without the response body, which may echo the request
+ status = exc.response.status_code if exc.response is not None else None
+ raise CredentialsError(
+ f"No access token{target} from {endpoint}: {type(exc).__name__}"
+ f" (status {status})"
+ ) from exc
</code_context>
<issue_to_address>
**URL query secrets appear in errors**
When an accepted issuer or token endpoint URL has a secret in its query and a discovery or token request fails, `_discover()` and `_fetch_token()` include the full issuer or endpoint in `CredentialsError` messages, and cached failures are logged, exposing the query secret to callers and application logs.
Redact query strings from endpoint and issuer values before including them in errors or logs.
Also at `foca/plugins/backends/credentials.py:951-953`.
</issue_to_address>
### Comment 3
<location path="foca/plugins/backends/credentials.py" line_range="559" />
<code_context>
+
+ def __init__(self) -> None:
+ """Create a session."""
+ super().__init__()
+ self.auth = NO_CREDENTIALS
+
</code_context>
<issue_to_address>
**Backend cookies cross service boundaries**
When a gateway reuses one `BackendSession` for backends on sibling hosts and one backend sets a cookie for their shared parent domain, `requests.Session` stores response cookies and sends them on later requests. A cookie set for a shared parent domain by one backend is therefore sent to a sibling backend using the same session, exposing backend-set session data across services.
Disable cookie storage and sending in `BackendSession`, for example by applying the empty-domain cookie policy used by `GuardedClient`.
</issue_to_address>
### Comment 4
<location path="foca/plugins/backends/credentials.py" line_range="815" />
<code_context>
+ del self._failures[gone]
+ self._fetched.notify_all()
+ if new is not None:
+ return new.value
+ if token is None or time.monotonic() >= token.expires_at:
+ raise error # type: ignore[misc] # set if no token was fetched
</code_context>
<issue_to_address>
**Expired tokens are returned**
When the token lifetime is zero or elapses while the token request is in progress, `_fetch_token()` sets `expires_at` using the request start time, but `get_token()` returns `new.value` without checking that expiry, so the backend receives an already-expired bearer token and its request fails authentication.
Check the newly fetched token’s expiry before returning it, and handle an already-expired token as a failed fetch.
Also at `foca/plugins/backends/credentials.py:109`, `foca/plugins/backends/credentials.py:816`, `foca/plugins/backends/credentials.py:1006`, `foca/plugins/backends/credentials.py:1053`.
</issue_to_address>
### Comment 5
<location path="foca/plugins/backends/credentials.py" line_range="481-482" />
<code_context>
+ def headers(self) -> dict[str, str]:
+ """Headers with the credentials (empty for none), for other clients."""
+ if self._authorization is None:
+ return {}
+ return {"Authorization": self._authorization}
+
+ def apply(self, headers: MutableMapping[str, str]) -> None:
</code_context>
<issue_to_address>
**Caller authorization survives none**
When a non-requests client combines `credentials.headers` with an outbound header mapping that already contains `Authorization` and the resolved mode is `none`, `Credentials.headers` returns an empty mapping for no credentials, so merging it with outbound headers that already contain `Authorization` leaves that header intact; a gateway using the documented headers approach can forward caller credentials despite `auth: none`.
Document and require applying credentials to the existing mutable header mapping (or provide a non-requests API that removes existing authorization headers).
Also at `docs/plugins.md:392`.
</issue_to_address>
### Comment 6
<location path="foca/plugins/backends/credentials.py" line_range="1072" />
<code_context>
+ provider._reset_lock()
+
+
+os.register_at_fork(after_in_child=_reset_after_fork)
+
+
</code_context>
<issue_to_address>
**Windows backend imports fail**
When the backend package is imported on Windows, `os.register_at_fork` is unavailable on Windows, so importing `foca.plugins.backends.credentials` raises `AttributeError`. Because `foca.plugins.backends.__init__` imports this module unconditionally, importing the backend package fails there too.
Guard the registration with an availability check and retain the fork-reset behavior only on platforms that support it.
</issue_to_address>
### Comment 7
<location path="foca/plugins/backends/credentials.py" line_range="163" />
<code_context>
+ not allowed.
+ """
+ try:
+ normalize_url(url, schemes=schemes, name=name, keep_query=True)
+ except InvalidURL as exc:
+ raise ValueError(
</code_context>
<issue_to_address>
**Accepted URLs produce wrong requests**
When the configured issuer contains a query or fragment, or the token endpoint contains a fragment, `check_idp_url()` accepts these URL components, but `_discover()` appends the discovery path to the unnormalized issuer, making the path part of the query or fragment; a token endpoint fragment is also dropped during the request. Discovery or token acquisition then fails for the accepted configuration.
Reject unsupported query and fragment components during validation, or construct the discovery and token request URLs from parsed components so their paths are correct.
Also at `foca/plugins/backends/credentials.py:936-937`.
</issue_to_address>
### Comment 8
<location path="foca/plugins/backends/credentials.py" line_range="1208" />
<code_context>
+ if entry.basic is None:
+ # prevented by validation, unless the config was changed later
+ raise RuntimeError(f"{label} {entry.url}: `auth: basic` without `basic`")
+ return _missing_env(entry.basic.username_env, entry.basic.password_env)
+ if entry.auth == "none":
+ logger.warning("%s %s: no authentication (`auth: none`)", label, entry.url)
</code_context>
<issue_to_address>
**Invalid Basic values pass startup**
When a configured Basic username contains a colon or either Basic value contains control characters, `_check_service()` checks only whether Basic environment variables are available, so a username containing a colon or control characters passes startup and `get_credentials()` later raises `CredentialsError` on requests to that backend.
Validate present Basic values with `Credentials.basic()` during `check_backends()` and fail startup for invalid values.
</issue_to_address>
### Comment 9
<location path="foca/plugins/backends/credentials.py" line_range="755" />
<code_context>
+ token was obtained.
+ """
+ client_id = _get_env(self.client_id_env)
+ client_secret = _get_env(self.client_secret_env)
+ if client.audience_parameter is None:
+ audience = None
</code_context>
<issue_to_address>
**Valid cached token is ignored**
When a token has been cached and the client-secret variable or its `_FILE` becomes unavailable, `get_token` reads the client secret before checking its cache, so a missing or unreadable secret makes it raise `CredentialsError` even when a cached token is still valid. Requests to backends fail until the secret becomes available again.
Check for and return a usable cached token before requiring the secret, and treat secret-read errors during refresh as refresh failures while a cached token remains valid.
</issue_to_address>
### Comment 10
<location path="foca/plugins/backends/credentials.py" line_range="760" />
<code_context>
+ audience = None
+ endpoint = self._get_token_endpoint(client)
+ key = TokenKey(
+ endpoint, client_id, client.scope, client.audience_parameter, audience
+ )
+ deadline = time.monotonic() + WAIT_FACTOR * client.timeout
</code_context>
<issue_to_address>
**Refresh margin depends on first caller**
When a provider is shared across client configurations with the same key fields but different `refresh_before` values, `TokenKey` omits `refresh_before`, while the cached token’s `refresh_at` is computed using the client that fetched it. When a client with a larger margin reuses a token fetched under a smaller margin, `get_token()` keeps returning it past the configured refresh point, leaving backend requests with a token close to expiry.
Include `refresh_before` in the cache key or calculate refresh eligibility using the current client’s setting and the cached token’s expiry.
</issue_to_address>
### Comment 11
<location path="foca/plugins/backends/credentials.py" line_range="87" />
<code_context>
+"""Seconds that a failed token fetch or discovery is not tried again: calls
+meanwhile get the same error (or a cached token that is still valid)."""
+
+_DIGITS = re.compile(r"[0-9]{1,9}")
+
+
</code_context>
<issue_to_address>
**Long expiry values refresh too often**
When the identity provider returns `expires_in` as a digit string longer than nine characters, `_DIGITS` rejects the value, so `_lifetime()` uses the 60-second default instead of capping the numeric lifetime at 24 hours; the provider refreshes tokens unnecessarily often.
Accept longer digit strings and cap their numeric value at `MAX_TOKEN_LIFETIME`.
</issue_to_address>
### Comment 12
<location path="docs/migration-0.23.md" line_range="236" />
<code_context>
subclasses of `BackendList` that bypass its validation, and pass
`api="wes"` instead.
+
+## FOCA resolves the credentials of backends
+
+FOCA now resolves the [credentials of
</code_context>
<issue_to_address>
**Changelog entry**
The issue asks for both backend-credentials documentation and a changelog entry. The plugin and migration docs are present, but the change adds no changelog or release-notes entry.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 11 findings to address first, and if credential resolution or redirect handling sends a gateway token to an unintended backend, that backend may gain access or receive authenticated requests. Reverting stops future sends but cannot retract credentials already disclosed or calls already made.
Blocking findings: foca/plugins/backends/credentials.py:880, foca/plugins/backends/credentials.py:1022, foca/plugins/backends/credentials.py:559, foca/plugins/backends/credentials.py:815, foca/plugins/backends/credentials.py:482, and 6 more
Address the automated review of the credentials of backends: - Check endpoints cached by issuer against the calling client's URL schemes, so secrets don't go to http endpoints of another client. - Refuse queries and fragments in URLs of the identity provider. - Keep no cookies in BackendSession. - Use the calling client's refresh margin for cached tokens. - Read the client secret per fetch: cached tokens stay usable while it is unavailable. - Check HTTP Basic values on startup. - Cap long digit strings of expires_in. - Document Credentials.apply() for clients other than requests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Moves proTES's credentials of backends into FOCA, generic for TES and WES gateways (
foca.plugins.backends, new modulecredentials.py), so that proWES (elixir-cloud-aai/prowes#182) and later proTES use one implementation:ClientCredentialsConfig: the gateway's client at its identity provider (issuerortoken_endpoint,url_schemes,scope,audience_parameter,auth_method,refresh_before,timeout), embedded next to the backend list (e.g.,custom.wes.client_credentials);check_client_credentials()checks the list against it (identity provider needed for tokens, audiences needaudience_parameter, RFC 8707 resource indicators);uses_tokens().TokenProvider(client_id_env, client_secret_env): client credentials grant (RFC 6749, section 4.4), with OIDC discovery of the token endpoint; cached per process and key (endpoint, client, scope, audience parameter, audience), refreshedrefresh_beforeseconds before expiry (at most half the lifetime), one fetch per key (and one discovery per issuer) at a time, cached token used while a refresh fails. Changes against proTES's original, from the review: no lock is held while the identity provider is asked (proTES held it during discovery); a failed fetch or discovery is returned for 5 s (FAILURE_RETRY) instead of being retried by each waiting thread in turn; discovery doesn't follow redirects either;expires_inmust be finite and is capped at 24 h (digit strings count as seconds, huge integers don't overflow); unexpected errors also release waiting threads; waits for another thread's fetch are bounded (3 xtimeout); forked processes get new locks and no fetches in progress;clear()overtakes running fetches; plainOSErrors ofrequests(e.g., a missingREQUESTS_CA_BUNDLE) become cachedCredentialsErrors; from the automated review: endpoints cached per issuer are checked against the calling client's schemes, IdP URLs without queries and fragments, no cookies inBackendSession, the calling client's refresh margin, the secret read per fetch (cached tokens survive its absence), Basic values checked on startup.foca.config.environment.get_env): from the variable or from a file named by<name>_FILE(e.g., a mounted Secret); errors name variables only.get_credentials(backend, entry, client, provider, auth=None): Bearer token (for the entry'saudience, or the backend's URL, if audiences are requested), HTTP Basic from the variables ofbasic, or none, asCredentials: arequestsauth object that replaces anyAuthorizationheader (also withnone), keeps.netrcout, and has.headersfor other clients (e.g.,GuardedClient); its repr leaves the credentials out. Tokens with characters other than visible ASCII and Basic user names with colons or control characters are refused (header injection).BackendSession:requestssession without.netrccredentials, also after redirects.check_backends(entries, client, provider, api=..., public_url=..., key=...): the startup checks ofpro_tes/security.py(missing variables, list vs. client and API, registries without public URL, backends at or below it via the newBackendList.is_own(),basic/none/http/private-address warnings, token recipients logged by URL).ServiceEntry.audience(only withauth: client_credentials, no surrounding whitespace).The client model lives in
credentials.py(re-exported fromfoca.plugins.backends), not inconfig.py, becausetests/test_chart_gateway_keys.pytakes every multi-word field of the models ofconfig.pyas a key of backend entries that the chart renders; the chart renders only<key>.backends, and apps passclient_credentialsthroughconfig.custom.<key>as before. No chart change.proTES is not changed here; its follow-up (use FOCA's provider, drop its own) is drafted for after the FOCA release.
Docs:
docs/plugins.md("Credentials of backends"),docs/migration-0.23.md("FOCA resolves the credentials of backends"), API reference.Verification
pytest tests -m "not mongodb": 5202 passed, 2 skipped. MongoDB tests not run locally (the port is reserved for another session); CI runs them.coverageoffoca/plugins/backends/*: 100%.tests/plugins/test_plugin_credentials.py(135 tests, stable over repeated runs): cache, refresh, refresh failure, failure retry window, short/unknown/unbounded lifetimes, configured endpoint, audiences (per parameter, slow audiences concurrently, refresh while pending), slow discovery not blocking cached tokens, unexpected errors of fetch and discovery, redirected discovery, expired tokens and failures removed, missing client variables,_FILEvariables, invalid token responses (no secret in messages), unreachable endpoint/issuer, invalid discovery documents (no user info in messages), a local HTTP identity provider (discovery without.netrc, Basic client auth, no redirect of token requests),BackendSessionand.netrc, each credential mode for configured and discovered backends, plugin-chosen credentials, startup checks.ruff check,ruff format --check,mypy(189 files),semgrep --config=.semgrep,ast-grep scan,mkdocs build --strict: pass.Declined review findings
GuardedClient/trust_env=Falsefor the identity provider (quality, medium): deliberate. The IdP is configured by the admin, not by users or registries; deployments may need the environment's proxies andREQUESTS_CA_BUNDLEfor it (as in proTES).BackendSessiononly removes.netrc; documented.ClientCredentialsConfigintoconfig.py(quality, low): see above (chart key test); it is re-exported fromfoca.plugins.backends, so the import path is the same. The private_Modelbase is shared within the package on purpose (sameextra="forbid",hide_input_in_errorssemantics).os.register_at_forkfor Windows (Sourcery):registry.pyof the same package registers unconditionally; FOCA gateways run on Linux.docs/releases/0.23.0.mdis written at release prep; the migration guide holds the unreleased entry.##(quality, low): it is about entries of backend lists (auth), so it stays under "Backend lists". Release notes for 0.23.0 aren't written yet; the migration guide has the entry.Open questions
None.
Closes #794
🤖 Generated with Claude Code