Skip to content

feat!: reject duplicate service registrations - #108

Merged
uniqueg merged 5 commits into
devfrom
feat/reject-duplicates
Oct 20, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/reject-duplicates

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Services are unique by URL and API type (#102), so the same deployment can't be registered several times, by the same or by different users.

  • Key: the normalized url plus type.group and type.artifact (case-insensitive). The version is not part of it, so that upgrading a service to a new API version updates its entry, and the API type covers several APIs under one base URL.
    • URLs are compared after normalizing common spellings: lowercase schemes and hosts, international host names encoded with IDNA 2008 (new dependency idna), canonical IPv6 addresses, percent-encoded non-ASCII path characters; without trailing host dots, default ports (443 for https, 80 for http), dot segments, repeated and trailing slashes, needless percent-encoding, queries and fragments. http and https are different services.
    • Invalid URLs, URLs without scheme or host, or with user info (user:password@), are rejected (400 Bad Request, with a detail saying why).
  • Storage: the internal field _serviceKey is computed on every write and has a unique, sparse index in config.yaml. It is excluded from responses.
  • Conflicts: POST /services, or a PUT that changes a service to the URL and type of another one, returns 409 Conflict. The problem details name the registered service, in detail and in the extension member serviceId, so that the UI can link to it. FOCA's problem details are fixed per exception class, so the controller builds this response.
    • Conflicts are checked before writing, and again on duplicate key errors, which covers concurrent registrations. No roles are granted on conflicts.
  • Existing data: on startup, services without a key get one (add_service_keys()). If stored services are duplicates, or have invalid URLs, the app refuses to start and names them all (also on concurrent duplicate key errors). The index is sparse, so that it can be created before the keys are added. The redeploy starts with an empty database anyway.
  • Docs:
    • README "Duplicate services": the key, the normalization, the 409, and the squatting risk with how admins handle it (delete the entry, or reassign its owner). It also explains why proving control of the URL was rejected (self-declared IDs, SSRF).
    • deployment/README.md: the upgrade note.
    • API descriptions: POST and PUT /services, plus a DuplicateService response.

Closes #102.

Breaking changes

  • Registering a service with the URL and API type of a registered one returns 409. Changing a service to them via PUT also returns 409.
  • Service URLs with user info, or without scheme or host, are rejected (400).
  • The app refuses to start while stored services are duplicates (names them).

Verification

  • pytest (Helm 3.18.6 on PATH, package installed): 207 passed, 100% coverage. New tests cover:
    • URL normalization (case, default ports, trailing slashes and dots, dot segments incl. %2e%2e, percent-encoding, IDNA, IPv6, non-ASCII paths, queries, fragments, whitespace) and invalid URLs (no scheme or host, user info, invalid ports);
    • keys (type case-insensitive, version ignored, other artifacts differ, missing URL or type);
    • conflicts on POST (spelling variants and other versions) and on PUT (onto another service's key; an unchanged key or a new version is accepted);
    • concurrent registrations (POST and PUT), and other duplicate key errors being raised;
    • API: 409 problem details naming the service, the same URL with another type accepted, _serviceKey not served, 400 for invalid URLs on POST and PUT;
    • the startup backfill: keys added, existing keys kept, duplicates and invalid URLs named, and main() adding keys or refusing to start.
  • Existing tests now register services with distinct URLs.
  • ruff check, ruff format --check, mypy cloud_registry tests: clean.
  • helm lint --strict: passes. gitleaks dir .: no leaks. ast-grep scan: clean.
  • Reviews (adversarial + quality, 2 rounds): fixed: IDNA 2008 instead of Python's IDNA 2003 codec, trailing dots stripped after encoding, dot-only hosts rejected, canonical IPv6, non-ASCII paths, decoded %2e%2e segments, duplicate key errors in the backfill, problem titles from FOCA's mapping, docs (mongosh examples, upgrade note). Declined: a module-level counter for unique test URLs (simple, test-only); building the problem responses in the controller (FOCA's are fixed per class, see build: upgrade to FOCA 0.15 #104); percent-encoding in hosts not normalized (rare, documented as common spellings only).
  • CI: all checks pass (tests on Python 3.10 and 3.12, static analysis, Helm chart, Docker Compose, Read the Docs).
  • Sourcery: 6 findings; 5 fixed in da70289 (keys as JSON arrays, Unicode case folding, hosts checked as RFC 3986 registered names, malformed percent-encodings rejected, backfill keeps concurrently written keys; 215 tests, 100% coverage, CI green again); 1 declined (rollback race from feat!: add owner-based access control #106, out of scope, drafted as a follow-up issue).

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 20, 2026 19:20
Identify services by their normalized URL (lowercase scheme and host,
no default port, trailing slash, query or fragment) and API type
(type.group and type.artifact, case-insensitive, not the version),
stored in the internal field _serviceKey with a unique, sparse index
and excluded from responses.

POST /services, or a PUT that changes a service to the URL and type of
another one, returns 409 Conflict as problem details naming the
registered service (detail and serviceId); conflicts are checked
before writing and again on duplicate key errors (concurrent
registrations). URLs without scheme or host, or with user info, are
rejected (400).

On startup, services stored without a key get one; if stored services
are duplicates, the app refuses to start and names them.

Closes #102.

BREAKING CHANGE: registering a service with the URL and API type of a
registered one returns 409, service URLs with user info are rejected,
and the app refuses to start while stored services are duplicates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Normalize further spellings of the same URL: trailing dots of hosts,
international host names (IDNA), dot segments, repeated slashes and
needless percent-encoding; strip whitespace around API types. Reject
malformed URLs (e.g., unclosed IPv6 brackets) and non-string URLs and
types with 400 instead of 500, and say why in the problem details.

On startup, name all services with invalid URLs or duplicate keys at
once. Document how to fix them with mongosh, and upgrading with the
app scaled to 0 replicas, so that old pods don't register services
without keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Encode international host names with IDNA 2008 (UTS 46, the idna
package), strip trailing dots after encoding and reject dot-only hosts.
Canonicalize IPv6 addresses and percent-encode non-ASCII characters in
paths. Collect duplicate key errors in the startup backfill as well.

Explain the normalization as covering common spellings, clarify which
release the upgrade note refers to, and test the API's 400 responses
for POST and PUT.

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

The PR enforces service uniqueness through a normalized URL/API-type key, a unique sparse index, and race-safe POST/PUT conflict handling, while validating URLs, hiding the internal key, migrating legacy records at startup, and documenting the API and upgrade behavior.

Sequence diagram for duplicate-safe service registration

sequenceDiagram
    actor Client
    participant API as Service API
    participant RegisterService
    participant MongoDB

    Client->>API: POST /services or PUT /services/{serviceId}
    API->>RegisterService: register_metadata()
    RegisterService->>RegisterService: service_key(data)
    RegisterService->>MongoDB: find_one(_serviceKey, excluding current id)
    alt invalid URL or type
        RegisterService-->>API: InvalidService
        API-->>Client: 400 Problem Details
    else existing matching service
        RegisterService-->>API: DuplicateService(existing_id)
        API-->>Client: 409 with serviceId
    else no existing match
        RegisterService->>MongoDB: insert_one or replace_one with _serviceKey
        alt concurrent duplicate key
            RegisterService->>MongoDB: find_one(_serviceKey)
            RegisterService-->>API: DuplicateService(existing_id)
            API-->>Client: 409 with serviceId
        else write succeeds
            API-->>Client: service identifier
        end
    end
Loading

Flow diagram for legacy service key backfill

flowchart TD
    START[Application startup] --> BACKFILL["add_service_keys()"]
    BACKFILL --> LOAD[Find services without _serviceKey]
    LOAD --> KEY["service_key(service)"]
    KEY -->|invalid URL or type| FAIL[Collect startup problem]
    KEY --> LOOKUP[Find existing matching _serviceKey]
    LOOKUP -->|duplicate| FAIL
    LOOKUP -->|unique| UPDATE[Update service with _serviceKey]
    UPDATE -->|DuplicateKeyError| FAIL
    UPDATE --> DONE[Start application]
    FAIL --> REFUSE[Raise RuntimeError and refuse startup]
Loading

File-Level Changes

Change Details Files
Introduces canonical service identity and durable uniqueness enforcement based on normalized URL plus case-insensitive API group and artifact.
  • Adds URL validation and normalization for schemes, hosts, IDNA, IPv6, ports, paths, and rejected credentials or malformed URLs.
  • Computes _serviceKey on writes and adds a unique sparse database index.
  • Preserves API-version updates and permits different API types at the same URL.
cloud_registry/ga4gh/registry/service.py
cloud_registry/config.yaml
requirements.txt
tests/ga4gh/registry/test_service.py
tests/test_config.py
Adds conflict-safe registration behavior for POST and PUT, including concurrent duplicate detection and request-specific problem details.
  • Checks for duplicates before writes and rechecks duplicate-key failures to handle races.
  • Returns 400 for invalid services and 409 responses naming the existing service via serviceId.
  • Excludes _serviceKey from service responses.
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
tests/test_app.py
Adds startup migration and fail-fast handling for legacy or inconsistent service data.
  • Backfills missing keys while retaining existing keys.
  • Reports all invalid or duplicate stored services and prevents startup when migration cannot complete.
  • Documents the required zero-replica upgrade procedure and database remediation.
cloud_registry/app.py
cloud_registry/ga4gh/registry/service.py
deployment/README.md
README.md
tests/test_app.py
tests/ga4gh/registry/test_service.py
Documents the uniqueness contract, operational risks, and API responses.
  • Describes normalization rules, squatting mitigation, conflict behavior, and rejected URL-control verification.
  • Adds POST/PUT conflict documentation and the DuplicateService problem schema.
  • Updates existing tests and fixtures to use distinct service URLs.
README.md
cloud_registry/api/additions.openapi.yaml
tests/conftest.py
tests/mock_data.py
tests/test_access_control.py
tests/test_app.py

Assessment against linked issues

Issue Objective Addressed Explanation
#102 Prevent duplicate service registrations by enforcing uniqueness on the normalized base URL and case-insensitive API type group and artifact, excluding API version; reject conflicting POST and PUT requests with 409 responses identifying the existing service, and keep the internal uniqueness key out of API responses. ✅
#102 Normalize and validate service URLs for uniqueness, including common spelling variants, and handle existing stored services by backfilling keys while preventing startup when duplicates or invalid URLs are found. ✅
#102 Document the duplicate-registration behavior, upgrade and existing-data handling, and the squatting risk with the available admin mitigations. ✅

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (6fec73c) to head (da70289).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #108    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files            8         8            
  Lines          336       462   +126     
==========================================
+ Hits           336       462   +126     

☔ 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 17:51

@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="249-253" />
<code_context>
+
         # replace or insert service with provided ID (PUT)
         if self.replace:
-            result = self.db_coll.replace_one(
-                filter={"id": self.data["id"]},
-                replacement=self.data,
-                upsert=True,
-            )
+            try:
+                result = self.db_coll.replace_one(
</code_context>
<issue_to_address>
**Successful replacement is deleted**

When a PUT creates a previously absent ID, owner setup fails, and another PUT replaces that ID before rollback runs, the first PUT sets `was_created`, then its owner setup fails. A concurrent PUT can replace the same ID and return successfully; the first request’s `_unregister_service` then deletes by ID alone, so the successful replacement disappears.

Make rollback conditional on the created record still being the one this request inserted, or make service creation and owner assignment atomic.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/service.py" line_range="179" />
<code_context>
+    if not all(isinstance(value, str) for value in (url, group, artifact)):
+        raise InvalidService("Service URLs and types must be strings.")
+    return " ".join(
+        (group.strip().lower(), artifact.strip().lower(), normalize_url(url))
+    )

</code_context>
<issue_to_address>
**Distinct API types collide**

When two distinct group/artifact pairs contain spaces and produce the same joined text, `service_key` serializes the type fields with an unescaped space, so the pairs produce the same key for the same URL. The unique index rejects a valid registration as a duplicate, and startup backfill can treat stored services as duplicates.

Serialize the group and artifact unambiguously, for example with escaping or length prefixes.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/service.py" line_range="325" />
<code_context>
+            )
+            continue
+        try:
+            collection.update_one({"id": service["id"]}, {"$set": {KEY: key}})
+        except DuplicateKeyError:
+            # registered concurrently, e.g., by an app of an older version
</code_context>
<issue_to_address>
**Backfill overwrites a newer service key**

When one app instance is backfilling a keyless service while another already-serving instance PUTs a different URL or API type to that same service, `add_service_keys()` writes the key computed from its earlier cursor result using only the service ID. A concurrently serving app can replace that service with a new URL and key first, after which the backfill overwrites the key with the stale one; duplicate checks then miss registrations for the current URL.

Make the backfill update conditional on `_serviceKey` still being absent, and handle a missed update without overwriting the concurrently written key.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/service.py" line_range="105-110" />
<code_context>
+        except ValueError as exc:
+            raise InvalidService(f"Invalid host in service URL: {exc}.") from exc
+        return f"[{address}%{zone}]" if zone else f"[{address}]"
+    if not host.isascii():
+        try:
+            host = idna.encode(host, uts46=True, transitional=False).decode()
+        except idna.IDNAError as exc:
+            raise InvalidService(f"Invalid host in service URL: {exc}.") from exc
+    host = host.rstrip(".")
+    if not host:
+        raise InvalidService("Service URLs need a scheme and a host.")
</code_context>
<issue_to_address>
**Invalid ASCII hosts are accepted**

When a submitted or stored service URL has an ASCII hostname containing a URI-invalid character, such as a space, `_normalize_host` validates only non-ASCII hosts with IDNA and returns the invalid ASCII hostname. Registration stores the service instead of returning 400, and startup backfill accepts a legacy service instead of reporting it.

Validate ASCII hostnames against URI hostname rules before returning them from `_normalize_host`.
</issue_to_address>

### Comment 5
<location path="cloud_registry/ga4gh/registry/service.py" line_range="105" />
<code_context>
+        except ValueError as exc:
+            raise InvalidService(f"Invalid host in service URL: {exc}.") from exc
+        return f"[{address}%{zone}]" if zone else f"[{address}]"
+    if not host.isascii():
+        try:
+            host = idna.encode(host, uts46=True, transitional=False).decode()
</code_context>
<issue_to_address>
**Malformed percent escapes are accepted**

When a service URL contains a malformed percent escape, such as `%ZZ` in its host or path, the URL normalization accepts the malformed escape: `_normalize_path` preserves `%` and only decodes valid escapes. Registration stores the URL instead of returning 400, and startup backfill can key a pre-existing invalid service.

Reject malformed percent escapes in the URL before normalization.

Also at `cloud_registry/ga4gh/registry/service.py:128`.
</issue_to_address>

### Comment 6
<location path="cloud_registry/ga4gh/registry/service.py" line_range="179-181" />
<code_context>
+    if not all(isinstance(value, str) for value in (url, group, artifact)):
+        raise InvalidService("Service URLs and types must be strings.")
+    return " ".join(
+        (group.strip().lower(), artifact.strip().lower(), normalize_url(url))
+    )


 def service_exists(id: str) -> bool:
</code_context>
<issue_to_address>
**Unicode type casing differs**

When two services use the same URL and their API type fields differ only by Unicode case-fold equivalents, `lower()` does not apply Unicode case folding, so API type strings that differ only by Unicode case-fold equivalents can produce different keys and both be stored for the same URL. The unique index then permits duplicate services under the documented case-insensitive type rule.

Use Unicode case folding for the type fields, or constrain the fields to an explicitly ASCII case-insensitive alphabet.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and startup writes a derived _serviceKey onto existing service records; if normalization incorrectly treats distinct services as duplicates, startup can fail until the records are corrected. Those keys are bounded and can be recomputed or removed, though reverting the code alone does not remove the writes.

Blocking findings: cloud_registry/ga4gh/registry/service.py:253, cloud_registry/ga4gh/registry/service.py:179, cloud_registry/ga4gh/registry/service.py:325, cloud_registry/ga4gh/registry/service.py:110, cloud_registry/ga4gh/registry/service.py:105, and 1 more


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

Address Sourcery's review:
- serialize keys as JSON arrays, so that types whose fields join to the
  same text don't collide, and compare types with Unicode case folding;
- reject hosts that aren't registered names (RFC 3986) and malformed
  percent-encodings in paths;
- add keys in the startup backfill only to services still without one,
  so that a concurrent replacement's key is kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 9838284 into dev Oct 20, 2026
11 checks passed
@uniqueg
uniqueg deleted the feat/reject-duplicates branch October 20, 2026 18:09
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: reject duplicate service registrations

1 participant