Skip to content

fix: allow only HTTP(S) URLs in registrations - #118

Merged
uniqueg merged 6 commits into
devfrom
fix/http-urls
Oct 21, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/http-urls

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Only HTTP(S) URLs are accepted in registrations (#115, from the v0.3.0 pre-release review).

  • The service url must use http or https (any case). contactUrl, documentationUrl and organization.url are validated as HTTP(S) links too; contactUrl may also be a mailto: address, as the GA4GH spec allows (with an address; mailto: alone, mailto:?to=… or mailto://… are rejected). Invalid values give 400 with the field name, on POST and PUT.
  • One shared check for service URLs and links: no whitespace, control or format characters (except zero-width joiners in international host names, which IDNA 2008 allows), a valid host and port (port 0 rejected), no user info. Service URLs still tolerate surrounding spaces (backward compatibility); links are stored as written and must not have any.
  • No new dependency (urllib.parse plus the existing host normalization). Duplicate-detection keys are unchanged for every URL that was accepted before (fuzz-compared against dev).
  • README: URL rules, a note that clients should treat registry content as untrusted, and which stored services the startup check now rejects (only services without a key are re-checked; production data is reset at the redeploy).

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% of cloud_registry.
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep (.semgrep): passed.
  • Sourcery: 6 threads; fixed 5 (unpaired surrogates now rejected in all strings of the body, malformed percent escapes, mailto: needs local@domain addresses 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).
  • Two review rounds (adversarial and quality). The adversarial reviews tried scheme tricks (case, tabs/newlines in the scheme, backslashes, https:/host, //host), IDNA, user info, ports, wrong types and nesting, and mailto: edge cases: no bypass. Fixed from the reviews: one shared helper, consistent whitespace rules, port 0, IDN hosts with joiners (https://بی‌ت.ir, https://क्‍ष.in keep their xn-- keys), mailto: without an address, trimmed app-level tests, README notes.
  • Not run: 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

uniqueg and others added 3 commits October 21, 2026 01:49
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The 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 registration

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

File-Level Changes

Change Details Files
Centralize strict HTTP(S) URL validation while preserving service URL normalization and duplicate-key compatibility.
  • Reject non-HTTP(S) schemes, malformed hosts or ports, port 0, user info, and unsafe whitespace/control/format characters.
  • Allow surrounding spaces only for service URLs; keep links unchanged and validate them as stored.
  • Preserve IDNA 2008 host normalization, including zero-width joiners, and existing duplicate-detection behavior.
cloud_registry/ga4gh/registry/service.py
Validate registration link metadata and support the GA4GH mailto exception for contact URLs.
  • Validate contactUrl, documentationUrl, and organization.url during POST and PUT with field-specific 400 errors.
  • Allow only address-bearing mailto links for contactUrl; reject mailto links for other fields and malformed mailto forms.
cloud_registry/ga4gh/registry/service.py
Expand automated coverage for URL safety, registration behavior, and compatibility edge cases.
  • Test schemes, ports, user info, malformed URLs, whitespace and format characters, IDNs, and mailto edge cases.
  • Verify POST and PUT behavior, field-specific failures, accepted values, and unchanged storage semantics.
tests/ga4gh/registry/test_service.py
tests/test_app.py
Document accepted URL formats, operational migration behavior, and safe client handling of registry content.
  • Explain HTTP(S) requirements, link storage rules, allowed contact mailto values, and rejected characters.
  • Document startup revalidation of previously unkeyed services and warn clients not to render or fetch registry URLs blindly.
README.md

Assessment against linked issues

Issue Objective Addressed Explanation
#115 Reject service registration URLs unless they are valid HTTP(S) URLs with a host, returning a 400 for invalid values. ✅
#115 Validate contactUrl, documentationUrl, and organization.url as safe HTTP(S) links, while allowing valid mailto: contact addresses, and reject invalid values during registration. ✅
#115 Document that registry content is untrusted and clients should handle its links safely. ✅

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (98771b3) to head (07baa3a).

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.
📢 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 21, 2026 00:24

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


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

uniqueg and others added 3 commits October 21, 2026 02:37
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]>
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.

fix: allow only HTTP(S) URLs in registrations

1 participant