Skip to content

feat: let admins verify services - #111

Merged
uniqueg merged 4 commits into
devfrom
feat/verified-services
Oct 20, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/verified-services

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Admins can mark registered services as verified (#64). The GA4GH Service Registry endpoints are unchanged; verification is served by additional endpoints only:

  • PUT /services/{serviceId}/verification (admin only): verifies the service, or renews the verification time. An optional body {"url": ..., "type": {...}} names what the admin checked: if the service no longer has exactly that URL and API type, nothing changes and the response is 409 Conflict (checked atomically). Bodies that aren't empty, null or a JSON object (e.g. form data, malformed JSON) and invalid URLs get 400 Bad Request, so the check can't be skipped by accident. Returns {"url": ..., "type": {...}, "verified_at": ...}.
  • DELETE /services/{serviceId}/verification (admin only): removes the verification.
  • GET /services/{serviceId}/verification (public): {"url": ..., "type": {...}, "verified_at": ...}, or 404 if the service is unknown or not verified.
  • GET /verifications (public): all verified services as [{"service_id": ..., "url": ..., "type": {...}, "verified_at": ...}], sorted by identifier. Clients such as proTES combine it with GET /services, keeping services whose identifier, URL and type match.

The time is stored in a hidden service field (_verifiedAt), never served by the GA4GH endpoints. A verification is reset in the same write when the service's URL changes in any way (exact string comparison, so also queries, fragments, case or trailing slashes) or its API type changes, using compare-and-swap with retries, so a concurrent verify or unverify is never lost and a verification never survives such a change. Name, version and other changes keep it. Verifications and unverifications are logged with the admin's sub.

Admin-only access needs no new policy: no policy matches /services/:id/verification, so only the admin role grants it; owners and maintainers get 403 (tested).

Field names are snake_case, like the other additions resources (/me, permissions).

README: new section "Verified services".

Closes #64

Verification

Locally (Python 3.12, Helm 3.18.6):

  • ruff check ., ruff format --check .: passed
  • mypy cloud_registry tests: no issues in 28 files
  • ast-grep scan, ast-grep test --skip-snapshot-tests: passed
  • pytest under coverage (chart tests included): 332 passed, none skipped; coverage 100% (571 statements)
  • gitleaks: no leaks
  • Two review rounds (adversarial and quality); all findings fixed.

CI: all checks passed (static code analysis; tests on Python 3.10 and 3.12; Helm chart; Docker Compose; Read the Docs).

Notes

  • server._problem moved to cloud_registry.exceptions.problem, for the 409 from the verification controller.
  • After admins have verified services, rolling back to an older version would serve the hidden field; this is noted for the operator handover.

🤖 Generated with Claude Code

Summary by Sourcery

Enable administrators to verify registered services while keeping existing GA4GH service endpoints unchanged.

New Features:

  • Add public endpoints for reading verified services and admin-only endpoints for verifying, renewing, and removing service verifications.

Bug Fixes:

  • Automatically clear verification when a service URL or API type changes, including concurrent updates, so stale verification cannot persist.

Enhancements:

  • Keep verification metadata hidden from the existing GA4GH service responses while exposing the checked URL, API type, and verification timestamp through dedicated endpoints.
  • Restrict verification changes to administrators and record verification changes in the application logs.
  • Move reusable problem-details response generation into the shared exceptions module.

Documentation:

  • Document verified-service workflows, endpoint behavior, matching requirements, and lifecycle rules in the README.
  • Extend the OpenAPI specification with verification endpoints and schemas.

Tests:

  • Add unit and integration coverage for verification access control, validation, conflict handling, listing, renewal, removal, hidden metadata, lifecycle resets, and concurrent updates.

uniqueg and others added 3 commits October 20, 2026 21:44
Add admin-only PUT and DELETE /services/{serviceId}/verification and
public GET /services/{serviceId}/verification and GET /verifications.
The GA4GH endpoints are unchanged. The verification time is kept in a
hidden service field, which is reset in the same write when the
service's URL or API type changes (compare-and-swap with retries).

Closes #64

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Verifications now name what was verified, and are bound to it:

- PUT /services/{serviceId}/verification accepts an optional body with
  the URL and API type the admin checked. The service is only verified
  if it has exactly that URL (as written) and the same API type key,
  checked in the update filter; otherwise 409, nothing changes.
- Replacing a service keeps its verification only if the stored URL is
  unchanged as written and the key is unchanged, so other spellings
  (e.g., an added query or fragment, which keys ignore) reset it. The
  compare-and-swap filter includes the URL as read.
- Verification responses include the URL and API type of the service,
  read from the same document, so that clients can match them against
  GET /services.

The problem details helper of the server module is public now, to
build the 409 response.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PUT /services/{serviceId}/verification verified services
unconditionally if the body wasn't parsed (e.g., form data, text, or
malformed JSON), as Connexion then passes no body. Such requests return
400 now; only an empty body or JSON null verify the service as
registered. Invalid URLs in the body return 400 with the reason, not
409.

Also:
- Move `problem()` to `cloud_registry.exceptions`, for both
  controllers.
- Build the verification query step by step, returning errors early;
  name filter variables `query`.
- Describe both meanings of `retries` of `register_metadata()`.
- Set `x-body-name` on the request body, as Connexion advises.
- List the reset rules of verifications in the README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces admin-managed service verification through dedicated endpoints, storing verification timestamps privately and exposing matched verification data publicly. Verification is protected with strict input validation and atomic URL/type checks, is safely reset during concurrent service identity changes, and is covered by OpenAPI updates, documentation, and extensive lifecycle, authorization, and concurrency tests.

Sequence diagram for atomic admin service verification

sequenceDiagram
    actor Admin
    participant API
    participant ServicesDB

    Admin->>API: PUT /services/{serviceId}/verification
    API->>ServicesDB: find_one_and_update(id, url, service_key)
    alt Service matches checked URL and API type
        ServicesDB-->>API: service with _verifiedAt
        API-->>Admin: 200 Verification
    else Service exists but identity differs
        ServicesDB-->>API: no match
        API-->>Admin: 409 Conflict
    else Service is unknown
        ServicesDB-->>API: no service
        API-->>Admin: 404 Not Found
    end
Loading

Sequence diagram for verified service discovery

sequenceDiagram
    participant Client
    participant Registry

    Client->>Registry: GET /services
    Registry-->>Client: Registered services
    Client->>Registry: GET /verifications
    Registry-->>Client: Verified services sorted by service_id
    Client->>Client: Keep matching service_id, url and type
Loading

File-Level Changes

Change Details Files
Adds public and admin-only verification endpoints with atomic checked verification, renewal, removal, retrieval, and sorted listing.
  • Defines OpenAPI routes and snake_case verification schemas.
  • Implements verification persistence, timestamp formatting, conflict handling, and public reads.
  • Rejects malformed or non-JSON bodies and invalid URLs to prevent accidental unconditional verification.
  • Uses existing role policy behavior so only admins can write verifications; logs admin subjects.
cloud_registry/ga4gh/registry/verification.py
cloud_registry/api/additions.openapi.yaml
cloud_registry/exceptions.py
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/server.py
Integrates verification state into service lifecycle while preserving GA4GH service responses.
  • Stores verification time in hidden _verifiedAt field excluded by the service projection.
  • Adds compare-and-swap replacement retries to retain verification only when URL text and normalized API type remain compatible.
  • Resets verification atomically on URL or API type changes and removes it with service deletion.
  • Preserves verification across name, version, and other non-identity updates.
cloud_registry/ga4gh/registry/service.py
tests/ga4gh/registry/test_service.py
tests/ga4gh/registry/test_verification.py
Documents the verified-service workflow and validates the complete API and concurrency behavior with unit and integration coverage.
  • Documents admin usage, matching semantics, client consumption, lifecycle rules, and rollback considerations.
  • Tests authorization, public access, response formats, malformed bodies, conflicts, sorting, renewal, deletion, hidden fields, and service updates.
  • Verifies the original GA4GH endpoints and schemas remain unchanged.
README.md
tests/test_verification.py

Assessment against linked issues

Issue Objective Addressed Explanation
#64 Allow only ECP_CLN:ADMIN users to verify or unverify services, and automatically clear verification when a service's URL changes. ✅
#64 Expose verification status through the API and let clients identify or filter for verified services. ✅
#64 Update the UI to show verified badges, provide admin verify/unverify actions, and offer a verified-services filter. ❌ The PR adds backend endpoints and documentation, but contains no changes to the cloud-registry UI.

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 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (45e3306) to head (eb81b5e).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #111   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            8         9    +1     
  Lines          492       573   +81     
=========================================
+ Hits           492       573   +81     

☔ 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 20, 2026 20:38

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="cloud_registry/ga4gh/registry/service.py" line_range="22-25" />
<code_context>
 # Internal field identifying a service by its normalized URL and API type
 # (not version), with a unique index (cf. `config.yaml`); not served
 KEY = "_serviceKey"
+# Internal field with the time an admin verified a service (cf.
+# `verification.py`); removed when its URL (as written) or key changes; not
+# served
+VERIFIED = "_verifiedAt"
 # Projection excluding internal fields
-PROJECTION = {"_id": False, KEY: False}
</code_context>
<issue_to_address>
**Verification metadata leaks or disappears**

When an old application replica handles a read or replacement after a new version has stored a verification, the old projection exposes `_verifiedAt` in service responses, and the old whole-document replacement removes it, so callers see internal metadata or the service loses its verification.

Make verification metadata rollout-safe so old replicas neither expose it in service responses nor erase it during replacement, or prevent old replicas from handling these records.

Also at `cloud_registry/ga4gh/registry/service.py:27`, `cloud_registry/ga4gh/registry/service.py:329-340`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/verification.py" line_range="250" />
<code_context>
+    )
+    return [
+        {"service_id": service["id"], **_verification(service)} for service in services
+    ]
</code_context>
<issue_to_address>
**Recreated services inherit stale trust**

When a client fetches `/verifications`, then a service is deleted and recreated with the same identifier, URL, and type before the client fetches `/services`, `getVerifications` provides no service-incarnation value, so the documented identifier/URL/type match accepts the new, unverified record using the stale verification. Include an incarnation value in both reads and require it to match, or expose verification atomically with the service.

Include an incarnation value in both reads and require it to match, or expose verification atomically with the service.

Also at `README.md:243`.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/verification.py" line_range="118-120" />
<code_context>
+        passes to controllers as no body.
+    """
+    # form data is consumed when it is parsed, so it isn't in the raw body
+    if request.form or request.files:
+        return True
+    data = request.get_data().strip()
+    return bool(data) and not (request.is_json and data == b"null")
+
</code_context>
<issue_to_address>
**Empty form bodies bypass rejection**

When a nonempty form body parses to empty `request.form` and `request.files`, `request.form` parsing consumes form data even when it produces no fields (for example, a body of `&`). `_has_unparsed_body()` then reads an empty stream and returns false, so `putServiceVerification()` verifies the service unconditionally instead of rejecting the non-JSON body; an admin's intended checked-URL precondition is skipped.

Determine whether the body is empty or JSON `null` before accessing the form parser, or otherwise preserve the original body-presence information.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/service.py" line_range="346-349" />
<code_context>
     OAuthProblem,
     Unauthorized,
 )
+from flask import Response
 from werkzeug.exceptions import (
</code_context>
<issue_to_address>
**Concurrent service updates fail**

When another request inserts the same identifier first, or changes an existing service after `_replace()` reads it but before the conditional replacement, the upsert raises `DuplicateKeyError`; the handler calls `_check_duplicate()`, which excludes the same identifier, and then re-raises instead of retrying. The caller's registration or update fails with a 500.

Retry the replacement after re-reading the service when a duplicate-key error is caused by a concurrent write to the same identifier.
</issue_to_address>

### Comment 5
<location path="cloud_registry/ga4gh/registry/verification.py" line_range="196" />
<code_context>
+        )
+    service = get_collection("services").find_one_and_update(
+        query,
+        {"$set": {VERIFIED: _now()}},
+        projection=VERIFICATION_PROJECTION,
+        return_document=ReturnDocument.AFTER,
</code_context>
<issue_to_address>
**Renewal time moves backward**

When two admin PUTs overlap and the earlier request samples its time before a later request but reaches Mongo after it, `_now()` is sampled before the database write and stored unconditionally, so an earlier request that reaches Mongo after a later renewal overwrites its newer timestamp. Callers then see `verified_at` move backward and the newer check appear stale.

Set the timestamp at the atomic database write, or atomically retain the maximum timestamp.
</issue_to_address>

### Comment 6
<location path="tests/test_verification.py" line_range="244" />
<code_context>
+    first = verify(client).json["verified_at"]
+    second = verify(client)
+    assert second.status_code == 200
+    assert second.json["verified_at"] >= first
+    assert verified(client) == [service]
+
</code_context>
<issue_to_address>
**Renewal can go untested**

When the second PUT leaves the stored verification time unchanged, `test_verify_again` accepts an unchanged timestamp because `>=` is true when `second.json["verified_at"]` equals `first`; a PUT that never renews the verification therefore passes.

Control the clock so the second verification has a later millisecond, then assert that timestamp is returned and stored.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and if an admin verifies the wrong URL or API type, clients may treat that public verification as a trust signal and send credentials or work to an endpoint that was not checked. Revoking the verification or reverting the change cannot undo anything already sent.

Blocking findings: cloud_registry/ga4gh/registry/service.py:25, cloud_registry/ga4gh/registry/verification.py:250, cloud_registry/ga4gh/registry/verification.py:120, cloud_registry/ga4gh/registry/service.py:349, cloud_registry/ga4gh/registry/verification.py:196, and 1 more


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

Comment thread tests/test_verification.py Resolved
- Reject form bodies without fields (e.g., `&`) when verifying: they
  are consumed when parsed, so a body counts as sent if the request
  has a content length although its raw data is gone.
- Read a service again and retry if replacing it fails with a
  duplicate key error not caused by another service with the same key
  (e.g., a concurrent upsert with the identifier), instead of failing
  with 500; real duplicates still return 409.
- Never move the time of a verification back on renewals (`$max`), and
  serve the time stored.
- Control the clock in the renewal tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 4f5bd02 into dev Oct 20, 2026
9 checks passed
@uniqueg
uniqueg deleted the feat/verified-services branch October 20, 2026 20:55
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.

Cloud Registry: admin-set "verified" flag (backend and UI)

1 participant