Repository navigation
fix: allow only HTTP(S) URLs in registrations - #118
Conversation
Service URLs (`url`) must now use the scheme `http` or `https` (any case); `normalize_url()` rejected only URLs without scheme or host, so URLs such as `javascript:` or `file:` were accepted. Links (`contactUrl`, `documentationUrl`, `organization.url`) are declared with `format: uri`, which jsonschema doesn't check without an optional package. They are now checked on `POST` and `PUT` by `check_links()`: HTTP(S) URLs without whitespace, control characters or user info, with a valid host and port. Contact URLs can also be email addresses (`mailto:`), as in the GA4GH service info specification. Invalid URLs give `400 Bad Request`, saying why. The README says which URLs are accepted, and that clients should treat registry content as untrusted. Closes #115 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Service URLs and links are now checked by one helper, `_split_http_url()`, so that their rules can't drift apart. It also rejects: - whitespace and control characters, which `urlsplit()` strips or drops (tabs, newlines) while the URL is stored as written; service URLs may still have leading and trailing spaces; - port 0. Links with other allowed schemes (`mailto:` contact URLs) are checked for whitespace and control characters, too. The README notes that stored services with non-HTTP(S) URLs keep the app from starting until they are fixed, and the tests are trimmed and assert the messages. Refs #115 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`isprintable()` rejected format characters (Cf), and so international host names with zero width non-joiners or joiners (IDNA 2008, CONTEXTJ), which were accepted before. URLs now reject whitespace, control and format characters and separators (Cc, Cf, Zl, Zp, Zs), except joiners in hosts, which the IDNA check validates. Other format characters, such as bidirectional controls and soft hyphens (which UTS 46 would drop from hosts), stay rejected everywhere. `mailto:` links need a path again, so `mailto:#x` and `mailto:?to=...` are rejected. Also: `HTTP_SCHEMES` for the allowed schemes, a required `subject` for `_normalize_host()`, a comment on the spaces tolerated around service URLs, a README note on what the startup check covers, and fewer app-level tests. Refs #115 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR adds shared, field-aware URL validation for service registrations, restricting URLs to safe HTTP(S) values while allowing valid contact mailto addresses, preserving legacy service normalization and duplicate keys, covering the behavior with unit and API tests, and documenting the new rules and deployment implications. Sequence diagram for validated service registrationsequenceDiagram
participant Client
participant Registry
participant URLValidation
participant Database
Client->>Registry: POST or PUT /services
Registry->>URLValidation: check_links(data)
URLValidation->>URLValidation: check_link(url, field, schemes)
URLValidation->>URLValidation: _split_http_url(url, subject)
URLValidation-->>Registry: valid links
Registry->>URLValidation: normalize_url(service_url)
URLValidation-->>Registry: normalized service URL
Registry->>Database: _check_duplicate(key)
Database-->>Registry: no conflict
Registry->>Database: register metadata
Database-->>Registry: success
Registry-->>Client: 201 or 200 response
alt invalid URL or link
URLValidation-->>Registry: InvalidService
Registry-->>Client: 400 Bad Request with field name
end
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 #118 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 9 9
Lines 573 654 +81
=========================================
+ Hits 573 654 +81 ☔ 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="175" />
<code_context>
+ """
+ if any(
+ char not in allowed
+ and (char.isspace() or unicodedata.category(char) in REJECTED_CATEGORIES)
+ for char in url
+ ):
</code_context>
<issue_to_address>
**Surrogates cause server errors**
When a service or link URL contains an unpaired Unicode surrogate, `_check_characters()` does not reject Unicode surrogates, so URL normalization or BSON storage fails instead of raising `InvalidService`, and registration returns a 500.
Reject Unicode surrogates in `_check_characters()` so registration returns `InvalidService`.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/service.py" line_range="391" />
<code_context>
the retries.
"""
key = service_key(self.data)
+ check_links(self.data)
self._check_duplicate(key=key)
</code_context>
<issue_to_address>
**Invalid stored URLs survive deploys**
When an older app instance writes a keyed service with a URL rejected by the new rules, or such a keyed row already exists, `check_links()` runs only on new registrations, and `add_service_keys()` skips rows with `_serviceKey`, so the invalid row survives and `getServices()` serves it.
Revalidate keyed rows after older writers stop or before serving them, rather than skipping them solely because they have a key.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service.py" line_range="79" />
<code_context>
+ """
+ _check_characters(url, subject=subject, allowed=JOINERS)
try:
- parts = urlsplit(url.strip())
+ parts = urlsplit(url)
port = parts.port
</code_context>
<issue_to_address>
**Malformed escapes are stored**
When a registration link contains a malformed percent escape in its path, query, fragment, or `mailto:` address, `_split_http_url()` and the `mailto:` branch in `check_link()` do not validate percent escapes, so malformed links pass registration and are stored.
Validate percent escapes in every accepted URL form before returning from `check_link()`.
Also at `cloud_registry/ga4gh/registry/service.py:129-130`, `cloud_registry/ga4gh/registry/service.py:205`.
</issue_to_address>
### Comment 4
<location path="cloud_registry/ga4gh/registry/service.py" line_range="127" />
<code_context>
+ raise InvalidService(f"{subject} must be strings.")
+ scheme, _, rest = url.partition(":")
+ # without an authority, `urlsplit()` doesn't raise
+ if scheme.lower() in schemes and not rest.startswith("//") and urlsplit(url).path:
+ _check_characters(url, subject=subject)
+ return
</code_context>
<issue_to_address>
**Malformed contact links are stored**
When `contactUrl` is a nonempty `mailto:` URI whose path is not a valid email address, `check_link()` accepts any nonempty `mailto:` path without validating the mailbox, so registration stores and serves a malformed contact link.
Validate the `mailto:` mailbox before accepting the link.
</issue_to_address>
### Comment 5
<location path="cloud_registry/ga4gh/registry/service.py" line_range="199" />
<code_context>
+ invalid or no host, a scheme other than `http` and `https`, user
+ info, or an invalid port (or `0`).
+ """
+ _check_characters(url, subject=subject, allowed=JOINERS)
try:
- parts = urlsplit(url.strip())
</code_context>
<issue_to_address>
**Joiners pass in IPv6 zones**
When an IPv6 URL zone identifier contains a zero-width joiner or non-joiner, `_check_characters()` allows joiners across the URL, and `_normalize_host()` leaves IPv6 zones unvalidated, so the joiner passes validation and is stored.
Limit the joiner exception to IDNA-validated international host names and reject joiners in IPv6 zones.
</issue_to_address>
### Comment 6
<location path="cloud_registry/ga4gh/registry/service.py" line_range="207" />
<code_context>
+ raise InvalidService(f"{subject} must be valid URLs: {exc}.") from exc
+ _check_characters(parts.path + parts.query + parts.fragment, subject=subject)
+ if parts.scheme and parts.scheme.lower() not in HTTP_SCHEMES:
+ raise InvalidService(f"{subject} must be HTTP(S) URLs.")
if not parts.scheme or not parts.hostname:
- raise InvalidService("Service URLs need a scheme and a host.")
</code_context>
<issue_to_address>
**Published URL rules are stale**
When A client relies on the published OpenAPI contract and submits a URI that is not HTTP(S), or an otherwise disallowed link, openAPI consumers are told only that registration URLs need a scheme and host and must not contain user info, while the new checks also reject non-HTTP(S) schemes and links outside that rule. Clients following the published contract can submit values that now receive `400 Bad Request`.
Update the OpenAPI descriptions and schema constraints to document the HTTP(S) requirement, the `mailto:` exception for `contactUrl`, and the other enforced restrictions.
Also at `cloud_registry/ga4gh/registry/service.py:391`.
</issue_to_address>Sourcery assessment
Approval pending. 6 findings to address first.
Blocking findings: cloud_registry/ga4gh/registry/service.py:175, cloud_registry/ga4gh/registry/service.py:391, cloud_registry/ga4gh/registry/service.py:79, cloud_registry/ga4gh/registry/service.py:127, cloud_registry/ga4gh/registry/service.py:199, and 1 more
Address the Sourcery review of the URL checks: - Unpaired surrogates (Cs) are rejected (400); they failed later, when normalizing or encoding the service (500). - Malformed percent-encodings are rejected in paths, queries and fragments of HTTP(S) URLs, and in `mailto:` URLs; before, only paths of service URLs were checked. - `mailto:` URLs need comma-separated `local@domain` addresses, with a local part and a valid domain (minimally, not as of RFC 5322). - IPv6 zone identifiers must be ASCII (RFC 6874), so joiners are allowed only in international host names. The OpenAPI descriptions of the registration endpoints and URL fields, and the README, state the rules. Refs #115 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Unpaired surrogates in any string of a registration (e.g., `name` or `type.group`, which is also part of the key) failed when the service was encoded for the database (500). `check_strings()` now rejects them in all strings and keys of the request body, before anything else, with `400` naming the field. Also: - IPv6 zone identifiers must follow `%25` and be non-empty, so `[fe80::1%25]` and `[fe80::1%eth0]` are rejected. - Domains of `mailto:` addresses must be domain names: at least two labels of letters, digits and hyphens (after IDNA encoding), not IP addresses. Local parts must not contain `@` unless percent-encoded. - The README lists malformed percent-encodings among the stored URLs that keep the app from starting. Refs #115 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Read the Docs build for afe4c62 failed to check out the commit ("reference is not a tree"); trigger a new build. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Only HTTP(S) URLs are accepted in registrations (#115, from the v0.3.0 pre-release review).
urlmust usehttporhttps(any case).contactUrl,documentationUrlandorganization.urlare validated as HTTP(S) links too;contactUrlmay also be amailto:address, as the GA4GH spec allows (with an address;mailto:alone,mailto:?to=…ormailto://…are rejected). Invalid values give 400 with the field name, onPOSTandPUT.urllib.parseplus the existing host normalization). Duplicate-detection keys are unchanged for every URL that was accepted before (fuzz-compared againstdev).Not included (left for discussion in the issue): rejecting loopback, link-local and private addresses.
Closes #115
Verification
pytest(with Helm chart tests) under coverage: 527 passed, 100% ofcloud_registry.ruff check,ruff format --check, mypy,ast-grep scan, semgrep (.semgrep): passed.mailto:needslocal@domainaddresses with a domain name, joiners only in IDNA host names and RFC 6874-style zone IDs, OpenAPI descriptions), declined 1 (revalidating stored keyed rows: production data is reset at the redeploy). The fixes got another adversarial review (fuzzing: only 400s, no slow regexes).https:/host,//host), IDNA, user info, ports, wrong types and nesting, andmailto:edge cases: no bypass. Fixed from the reviews: one shared helper, consistent whitespace rules, port 0, IDN hosts with joiners (https://بیت.ir,https://क्ष.inkeep theirxn--keys),mailto:without an address, trimmed app-level tests, README notes.pre-commit run(hook repositories can't be fetched in the sandbox; hooks run individually).CI: all checks passed (tests on Python 3.10 and 3.12, Helm chart, Docker Compose, static analysis, Codecov, Read the Docs; the first docs build failed to check out the commit, an empty commit retriggered it).
Open questions
None.
🤖 Generated with Claude Code