Repository navigation
feat: use tokens sent with public reads - #255
Conversation
Let the public reads (GET /services, /services/{serviceId},
/services/types, /verifications and /services/{serviceId}/verification)
accept an optional bearer token, and apply the visibility rules for its
user, so that admins and owners see the pending items they may see.
Reject invalid or expired tokens on these reads as on other operations
(401 with an invalid_token challenge) rather than treating them as
anonymous, so that clients notice and log in again.
Pending services can't be verified (409), and services that become
pending lose their verification, also when only the version of their
type changes.
Closes #245
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read requests as anonymous, with a warning, when their token can't be validated for reasons other than being invalid (e.g., the identity provider is unavailable), so that public reads keep working. Parse the Authorization header as Connexion does (any whitespace), tell pending from conflicting verifications with one read, and document the optional token on every public read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Validate tokens with a thin wrapper around FOCA's validate_token that keeps the rejection for the request, so that public reads re-raise invalid_token rejections without validating the token again (and calling the user info endpoint twice). Log tokens that can't be validated otherwise at info level, and re-wrap the spec descriptions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuidePublic catalogue and verification reads now optionally use bearer tokens to enforce the requesting user’s visibility, with invalid-token challenges preserved and operational validation failures falling back to anonymous access; pending services are also prevented from being verified and lose existing verification when they become pending. Sequence diagram for bearer-token public readssequenceDiagram
participant Client
participant Connexion
participant FOCA
participant ReadController
Client->>Connexion: GET public read with Authorization
Connexion->>FOCA: validate_bearer_token(token)
alt Valid token
FOCA-->>Connexion: token_info
Connexion->>ReadController: check_read_token()
ReadController-->>Client: User-scoped visible results
else Invalid or expired token
FOCA-->>Connexion: Unauthorized invalid_token
Connexion->>ReadController: check_read_token()
ReadController-->>Client: 401 invalid_token
else Validation unavailable
FOCA-->>Connexion: Unauthorized without invalid_token
Connexion->>ReadController: check_read_token()
ReadController-->>Client: Anonymous public results
else No token or non-Bearer scheme
Connexion->>ReadController: check_read_token()
ReadController-->>Client: Anonymous public results
end
Flow diagram for pending service verificationflowchart LR
Update["Service update or flag sync"] --> Pending["Service becomes pending"]
Pending --> Remove["Remove existing verification"]
Verify["PUT /services/{serviceId}/verification"] --> Check{service pending}
Check -->|yes| Conflict["409 Conflict"]
Check -->|no| Store["Store verification"]
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 #255 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 17 17
Lines 1683 1734 +51
=========================================
+ Hits 1683 1734 +51 ☔ 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="cloud_registry/ga4gh/registry/service_types.py" line_range="327" />
<code_context>
{**query, PENDING_SERVICE: {"$ne": True}},
- {"$set": {PENDING_SERVICE: True}},
+ # pending services aren't verified
+ {"$set": {PENDING_SERVICE: True}, "$unset": {VERIFIED: ""}},
)
else:
</code_context>
<issue_to_address>
**Stale verifications remain on pending services**
When the database already contains services marked pending with stored verifications, `_sync_flags()` excludes those services because their pending flag is already true, so it does not unset `VERIFIED`; verification reads can expose the stale verifications to users allowed to see the services.
Update pending services with stored verifications even when their pending flag is already true.
Also at `cloud_registry/ga4gh/registry/service_types.py:328`.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/verification.py" line_range="219-226" />
<code_context>
)
if service is None:
- if not service_exists(serviceId):
+ stored = get_collection("services").find_one(
+ {"id": serviceId}, {"_id": False, PENDING_SERVICE: True}
+ )
+ if stored is None:
raise NotFound
+ if stored.get(PENDING_SERVICE) is True:
+ return _not_verified(serviceId, PendingVerification())
return _not_verified(serviceId, VerificationConflict())
logger.info(
"Service '%s' verified by '%s'.",
</code_context>
<issue_to_address>
**Approval causes a spurious conflict**
When an admin approves the service type after the conditional verification update fails but before the fallback read, the fallback read sees the now-approved service and returns `VerificationConflict` instead of retrying the verification, so the caller gets `409` even though the service is no longer pending and still matches the checked details.
Retry the conditional verification update when the fallback finds the service is no longer pending, while preserving the URL and API-type checks.
</issue_to_address>
### Comment 3
<location path="tests/test_service_types.py" line_range="1115-1116" />
<code_context>
+ response = client.put(path, headers=headers(ADMIN))
+ assert response.status_code == 409
+ assert "pending" in response.get_json()["detail"]
+ assert client.get(path, headers=headers(ADMIN)).status_code == 404
assert approve(client, TES).status_code == 200
+ assert client.put(path, headers=headers(ADMIN)).status_code == 200
</code_context>
<issue_to_address>
**Stale verification survives pending state**
When a replacement or flag sync marks a service pending but fails to remove its stored verification, when the pending transition leaves `VERIFIED` stored, `test_pending_after_verification` at lines 1115–1116 and `test_flagged_loses_verification` at line 1134 still pass: both read endpoints filter pending services, so they return 404 or an empty list even though the stale verification will reappear when the service is approved.
Assert that `VERIFIED` is absent from the stored service, or approve the service again and assert that its old verification does not reappear.
Also at `tests/test_service_types.py:1134`.
</issue_to_address>
### Comment 4
<location path="cloud_registry/api/additions.openapi.yaml" line_range="581" />
<code_context>
- it is registered at the time of the request. The verification is kept when the service is
- updated with the same URL and API type (e.g., a new version), and
- removed when they change, including other spellings of the URL.
+ Pending services (see `GET /approvals`) can't be verified (`409`):
+ their type is approved first. Invalid URLs in the body, and bodies
+ that are neither JSON nor empty (or `null`), return `400`. Without a
</code_context>
<issue_to_address>
**409 documentation omits pending**
When a caller consults the OpenAPI `409` response description for a pending service, the `PUT /services/{serviceId}/verification` implementation also returns `409` for pending services, but the OpenAPI `409` response description only names URL or API-type mismatches, so clients reading that response contract get an incomplete explanation.
Update the `409` response description to include pending services as a conflict reason.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and a valid token now lets admins and users with roles see pending service details on public reads, so a mistake in the visibility checks could expose data; reverting restores the previous read behavior. Services that become pending also have their stored verification cleared, which the revert would not restore, though an admin can verify them again.
Blocking findings: cloud_registry/ga4gh/registry/service_types.py:327, cloud_registry/ga4gh/registry/verification.py:226, tests/test_service_types.py:1116
Remove verifications also from services already flagged as pending, so that startup clears those stored before. Try a verification once more if the service isn't pending anymore after the conditional update failed, so that an approval meanwhile doesn't cause a spurious 409, and name pending services in the 409 response of the spec. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Public reads now use a bearer token if one is sent. Pending services can no longer be verified.
Tokens on public reads
GET /services,GET /services/{serviceId},GET /services/types,GET /verificationsandGET /services/{serviceId}/verification. The spec gives them the security requirement[{bearerAuth: []}, {}].bearerAuth.validate_token, as on every other operation, so LS Login tokens work the same way.Invalid tokens: decision
401withWWW-Authenticate: Bearer error="invalid_token", as on other operations. It is not treated as anonymous, so clients notice the problem and log in again instead of silently seeing less.validate_bearer_token, a thin wrapper around FOCA'svalidate_token(set asx-bearerInfoFuncinconfig.yaml) that keeps the rejection for the request. The new decoratorcheck_read_tokenre-raises that rejection if it isinvalid_token, so each token is validated only once.Authorizationheader is parsed as Connexion parses it: the scheme is matched in any case, and the token is split off at any whitespace.docs/api.mdand in the operation descriptions.Pending services and verification (maintainer amendment)
PUT /services/{serviceId}/verificationreturns409while the service is pending. The check is part of the same write, and the detail explains what to do.type.versionchanges to a pending version;Closes #245
Verification
All passed locally:
pytestagainst MongoDB 7.0.34, with coveragepytestwith mongomockruff check,ruff format,mypy cloud_registry testsmkdocs build --strictpre-commit run --all-files(includes semgrep and ast-grep)The 228 Helm chart tests didn't run locally because Helm isn't installed; CI runs them. CI on the PR passed, including
ChartandCI passed.New tests:
Basicscheme (ignored);bearer invalid, bareBearer,Bearerfollowed by spaces, a tab, and an expired token.GET /services,GET /services/{id}andGET /services/types.409on verifying a pending service.Declined review findings
permissions.pybelow the module constants: this is layout only.test_reads_with_tokenby endpoint: its loop already names the user and the endpoint in each assertion.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Enable user-aware public reads with optional bearer tokens and enforce that pending services cannot retain or receive verifications.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: