Skip to content

feat: use tokens sent with public reads - #255

Merged
uniqueg merged 4 commits into
devfrom
feat/token-public-reads
Oct 26, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/token-public-reads

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Public reads now use a bearer token if one is sent. Pending services can no longer be verified.

Tokens on public reads

  • Five reads now accept requests both with and without a token: GET /services, GET /services/{serviceId}, GET /services/types, GET /verifications and GET /services/{serviceId}/verification. The spec gives them the security requirement [{bearerAuth: []}, {}].
  • With a valid token, the visibility rules apply to its user. Admins and the owners of pending services see them, and the users who added pending types see those types.
  • Without a token, nothing changes. Login-for-reads deployments are also unchanged, because their patch still requires bearerAuth.
  • Tokens go through FOCA's validate_token, as on every other operation, so LS Login tokens work the same way.

Invalid tokens: decision

  • An invalid or expired token gets 401 with WWW-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.
  • Connexion falls back to anonymous when the token fails. Connexion now validates tokens with validate_bearer_token, a thin wrapper around FOCA's validate_token (set as x-bearerInfoFunc in config.yaml) that keeps the rejection for the request. The new decorator check_read_token re-raises that rejection if it is invalid_token, so each token is validated only once.
  • A token that can't be validated for other reasons, such as an unavailable identity provider, is read as anonymous and this is logged (at info level, so that tokens that keep failing do not flood the logs), so the public catalogue keeps working.
  • The Authorization header is parsed as Connexion parses it: the scheme is matched in any case, and the token is split off at any whitespace.
  • This is documented in docs/api.md and in the operation descriptions.

Pending services and verification (maintainer amendment)

  • PUT /services/{serviceId}/verification returns 409 while the service is pending. The check is part of the same write, and the detail explains what to do.
  • Services that become pending lose their verification:
    • in the replacing write, also when only type.version changes to a pending version;
    • and when a flag sync marks them pending.
  • The log line about the removed verification now also names "pending" as a reason.

Closes #245

Verification

All passed locally:

Check Result
pytest against MongoDB 7.0.34, with coverage 1263 passed, 228 skipped; 100% coverage
pytest with mongomock passed
ruff check, ruff format, mypy cloud_registry tests passed
mkdocs build --strict passed
pre-commit run --all-files (includes semgrep and ast-grep) passed

The 228 Helm chart tests didn't run locally because Helm isn't installed; CI runs them. CI on the PR passed, including Chart and CI passed.

New tests:

  • Each public read with:
    • no token;
    • a valid token;
    • the Basic scheme (ignored);
    • invalid tokens: wrong key, bearer invalid, bare Bearer, Bearer followed by spaces, a tab, and an expired token.
  • An unavailable identity provider (falls back to anonymous, and the token is validated only once).
  • Visibility by user (anonymous, other user, owner, admin) on GET /services, GET /services/{id} and GET /services/types.
  • 409 on verifying a pending service.
  • Loss of verification on a type-version change to pending, and on a flag sync.

Declined review findings

  • Move the helpers in permissions.py below the module constants: this is layout only.
  • Split test_reads_with_token by endpoint: its loop already names the user and the endpoint in each assertion.
  • A token that validates but lacks the access-control identity claim: it gets no roles and so sees only what anonymous requests see (FOCA's behaviour); there is no leak and no change here.

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:

  • Allow optional bearer tokens on public service, service-type, and verification reads so responses reflect the requesting user's visibility permissions.

Bug Fixes:

  • Reject invalid or expired bearer tokens on public reads while preserving anonymous access when token validation fails for infrastructure-related reasons.
  • Prevent pending services from being verified and remove existing verifications when services become pending.

Enhancements:

  • Document token-aware public reads, invalid-token behavior, and pending-service verification rules in the API specification and user documentation.

Documentation:

  • Update API documentation and operation descriptions for optional authentication on public reads and pending verification behavior.

Tests:

  • Add coverage for authenticated and unauthenticated public reads, token failure modes, user-specific visibility, and verification removal for pending services.

uniqueg and others added 3 commits October 26, 2026 12:20
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Public 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 reads

sequenceDiagram
    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
Loading

Flow diagram for pending service verification

flowchart 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"]
Loading

File-Level Changes

Change Details Files
Allow optional bearer authentication on public reads while preserving strict handling of invalid tokens.
  • Added optional bearer security requirements to five read endpoints and documented token behavior.
  • Added a shared token parser, Connexion/FOCA validation wrapper, and read decorator to apply user visibility, reject invalid tokens, and fall back to anonymous on non-token validation failures.
  • Applied the decorator to service, service-type, verification, and verification-list reads.
  • Added coverage for anonymous, valid, ignored-scheme, invalid, expired, and identity-provider outage scenarios.
cloud_registry/api/additions.openapi.yaml
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/verification.py
tests/test_app.py
tests/test_service_types.py
Prevent pending services from being verified or retaining verification state.
  • Added an atomic pending-state check to verification writes returning a descriptive 409 response.
  • Stopped verification preservation when replacement updates make a service pending, including pending type-version changes.
  • Removed verification during pending-flag synchronization and updated removal logging.
cloud_registry/api/additions.openapi.yaml
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_types.py
cloud_registry/ga4gh/registry/verification.py
tests/test_service_types.py
tests/test_verification.py
Update API and user documentation to describe token-aware visibility and pending-verification rules.
  • Documented optional tokens, invalid-token responses, and anonymous fallback when validation infrastructure is unavailable.
  • Documented token-based access to pending resources and verification removal or rejection for pending services.
docs/api.md
cloud_registry/api/additions.openapi.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#245 Use an optional bearer token on all five public reads to apply the caller’s visibility rules, while preserving anonymous behavior and compatibility with LS Login tokens. ✅
#245 Define and document behavior for invalid or expired tokens, and test anonymous, valid, and invalid-token requests on each public read. ✅
#245 Prevent verification of pending services, return 409 for such attempts, and ensure services that become pending lose any existing verification. ✅

Possibly linked issues


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

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (da25c9b) to head (3893f02).

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.
📢 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 October 26, 2026 12:29

@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 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


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

Comment thread tests/test_service_types.py Resolved
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]>
@uniqueg
uniqueg merged commit 9ce0ef1 into dev Oct 26, 2026
19 checks passed
@uniqueg
uniqueg deleted the feat/token-public-reads branch October 26, 2026 12:47
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: use tokens sent with public reads

1 participant