Repository navigation
feat!: reject duplicate service registrations - #108
Conversation
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]>
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]>
Reviewer's GuideThe 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 registrationsequenceDiagram
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
Flow diagram for legacy service key backfillflowchart 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]
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 #108 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 8 8
Lines 336 462 +126
==========================================
+ Hits 336 462 +126 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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.
urlplustype.groupandtype.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.idna), canonical IPv6 addresses, percent-encoded non-ASCII path characters; without trailing host dots, default ports (443 forhttps, 80 forhttp), dot segments, repeated and trailing slashes, needless percent-encoding, queries and fragments.httpandhttpsare different services.user:password@), are rejected (400 Bad Request, with adetailsaying why)._serviceKeyis computed on every write and has a unique, sparse index inconfig.yaml. It is excluded from responses.POST /services, or aPUTthat changes a service to the URL and type of another one, returns409 Conflict. The problem details name the registered service, indetailand in the extension memberserviceId, so that the UI can link to it. FOCA's problem details are fixed per exception class, so the controller builds this response.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.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.POSTandPUT /services, plus aDuplicateServiceresponse.Closes #102.
Breaking changes
409. Changing a service to them viaPUTalso returns409.400).Verification
pytest(Helm 3.18.6 on PATH, package installed): 207 passed, 100% coverage. New tests cover:%2e%2e, percent-encoding, IDNA, IPv6, non-ASCII paths, queries, fragments, whitespace) and invalid URLs (no scheme or host, user info, invalid ports);POST(spelling variants and other versions) and onPUT(onto another service's key; an unchanged key or a new version is accepted);POSTandPUT), and other duplicate key errors being raised;409problem details naming the service, the same URL with another type accepted,_serviceKeynot served,400for invalid URLs onPOSTandPUT;main()adding keys or refusing to start.ruff check,ruff format --check,mypy cloud_registry tests: clean.helm lint --strict: passes.gitleaks dir .: no leaks.ast-grep scan: clean.%2e%2esegments, 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).Open questions
None.
🤖 Generated with Claude Code