Skip to content

feat: add URL normalization and scheme checks - #366

Merged
uniqueg merged 8 commits into
devfrom
feat/url-checks
Oct 21, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/url-checks

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds foca.utils.urls, a URL check and normalization utility extracted from cloud-registry's service registration (cloud_registry/ga4gh/registry/service.py, including the https-only option of cloud-registry#147), so that cloud-registry, proTES, TRS-Filer and DRS-Filer can share it:

  • check_url(url, schemes, *, name): checks a URL as written. http/https URLs need a valid host (IDNA 2008 host names, dotted-decimal IPv4, bracketed IPv6 with optional zone ID), no user info, no port 0; mailto URLs need email addresses with domain names and no authority. Whitespace, control and format characters (except joiners in IDNA hosts) and malformed percent-encodings are rejected.
  • normalize_url(url, schemes, *, name, keep_query=False, keep_fragment=False): checks an HTTP(S) URL and normalizes it for comparisons (lowercase scheme/host, IDNA, canonical IPv6, no default ports, dot segments resolved, no repeated/trailing slashes, normalized percent-encodings; query and fragment dropped unless kept).
  • check_url_fields(data, fields): checks the fields an app names (dot-separated paths), each with its allowed schemes; FOCA doesn't know which fields hold URLs.
  • InvalidURL(ValueError) with code = 400, so FOCA's problem handler answers uncaught ones with 400; unsupported schemes (an app error) raise a plain ValueError. URLScheme (Literal["http", "https", "mailto"]), HTTP_SCHEMES, SUPPORTED_SCHEMES for app config models.
  • idna>=3.7,<4 is now a direct dependency (it was transitive via requests).
  • Docs: "Checking and normalizing URLs" in docs/utilities.md, API reference entry.

Differences from cloud-registry's helpers, relevant for its migration (cloud-registry#157):

  • Surrounding spaces are rejected; cloud-registry should call normalize_url(url.strip(" "), ...) to keep accepting them (normalized keys stay identical otherwise).
  • Stricter hosts (found in review): IPvFuture literals ([v1.example.org], which lost their brackets), percent-encoded hosts, numeric hosts that aren't dotted-decimal IPv4 (127.1), empty labels (a..org, example.org..) and percent-encoded zone IDs are rejected; mailto domains must not end in a numeric label. Invalid xn-- labels are rejected (found by Sourcery).
  • Raw ASCII characters that RFC 3986 only allows percent-encoded (e.g., <, |, backslashes, brackets) are rejected in paths, queries and fragments (found by Sourcery); cloud-registry accepted them.
  • Messages: "must use one of these schemes: 'http', 'https'." instead of "must be HTTP(S) URLs.", and mailto:/mailto://… now report "need valid email addresses".

Closes #342

Verification

  • pytest (with MongoDB 7.0 on port 12345): 1208 passed (Python 3.13); pytest tests/utils/test_urls.py: 198 passed on Python 3.11 and 3.13 (183 also on 3.10, before Sourcery fixes), also with idna==3.7 (lowest bound); 100% line coverage of foca/utils/urls.py.
  • ruff check, ruff format --check, mypy: clean; mkdocs build --strict: clean.
  • Two review rounds (adversarial + quality) and a Sourcery review; all findings fixed except those below.
  • CI (after the Sourcery fixes and merging dev): all checks pass, incl. Sourcery and codecov patch/project (lint/type-check/build, unit tests on Python 3.11-3.14 with MongoDB 7.0 and 3.13 with MongoDB 8.0, lowest direct dependencies, petstore integration, charts, Read the Docs).

Declined review findings

  • Testing the invalid-IPv6 branch of the private _normalize_host() directly (quality, medium): kept, as urlsplit() already rejects such hosts on Python 3.11.4+, so the branch is only reachable through the public API on older Python versions (before 3.11.4); the test keeps it covered on all versions.
  • Sourcery: zone identifiers lowercased by urlsplit() (not the case: SplitResult.hostname only lowercases the part before %), and one-shot scheme iterators shared between calls (callers pass collections, as typed; an exhausted iterator raises a plain ValueError). Replied in the threads.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 22, 2026 00:47
Add foca.utils.urls, extracted from cloud-registry's service
registration: check_url() checks URLs as written (HTTP(S) URLs with
valid hosts, mailto URLs with email addresses; no whitespace, control
or format characters, or malformed percent-encodings), normalize_url()
normalizes HTTP(S) base URLs for comparisons, and check_url_fields()
checks the fields an app names, each with its allowed schemes (e.g.,
https only). Invalid URLs raise InvalidURL, a ValueError with status
code 400. Declare idna as a direct dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reject hosts that would normalize to another host or bypass checks:
bracketed IP literals other than IPv6 (IPvFuture), percent-encoded
hosts, and numeric hosts that are not dotted-decimal IPv4 addresses
(e.g., 127.1); also mailto domains with a numeric last label. Raise
InvalidURL for non-string URLs in normalize_url(), accept iterators
as allowed schemes, make options keyword-only, and keep internal
constants private.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Show how a configured scheme option feeds the checks, link the API
reference for the rules, and list only public members there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove only one trailing dot of hosts and reject other empty labels
(e.g., a..org, 127.0.0.1..), which would make different hosts equal.
Limit IPv6 zone identifiers to unreserved characters, as newer Python
versions' urlsplit() does, so that Python 3.10 accepts no encoded
control characters there.

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

Adds a reusable, rigorously validated URL utility supporting HTTP(S) normalization, mailto checking, per-field scheme policies, and FOCA-compatible 400 errors, with dependency, documentation, and comprehensive test coverage.

Flow diagram for URL validation and normalization

flowchart LR
    App["Application"] --> Fields["check_url_fields(data, fields)"]
    Fields --> Check["check_url(url, schemes, name)"]
    Check --> Policy["Validate scheme policy"]
    Check --> HTTP["Validate HTTP(S) host, port, and URL characters"]
    Check --> Mailto["Validate mailto email addresses"]
    App --> Normalize["normalize_url(url, schemes, name)"]
    Normalize --> Check
    Normalize --> Canonical["Canonical scheme, host, path, query, and fragment"]
    Check -->|Invalid input| Error["InvalidURL(code = 400)"]
    Policy -->|Unsupported app configuration| ValueError["ValueError"]
Loading

File-Level Changes

Change Details Files
Introduces shared URL validation and normalization utilities with explicit scheme policies and client-safe error handling.
  • Validate HTTP(S) hosts, ports, user info, characters, percent-encoding, IDNA domains, IPv4/IPv6 literals, and mailto email addresses.
  • Normalize HTTP(S) URLs by canonicalizing scheme/host/IPs, ports, paths, percent-encoding, and optional query/fragment retention.
  • Expose scheme type aliases/constants and distinguish InvalidURL client errors from unsupported-configuration ValueErrors.
foca/utils/urls.py
pyproject.toml
Adds field-aware URL validation for application payloads.
  • Validate configured dot-separated fields while ignoring missing paths and rejecting present non-string or invalid values.
  • Support per-field allowed scheme collections for service, documentation, contact, and nested organization URLs.
foca/utils/urls.py
tests/utils/test_urls.py
Documents the URL utilities and publishes them in the API reference.
  • Add usage guidance for scheme configuration, checking, normalization, exception behavior, and whitespace compatibility.
  • Add the URL module and public members to generated API documentation.
docs/utilities.md
docs/reference.md
Provides comprehensive automated coverage for URL validation, normalization, edge cases, and integration behavior.
  • Cover canonicalization of hosts, IDNA, IPv4/IPv6 and zones, paths, ports, queries, fragments, and percent-encodings.
  • Cover invalid schemes, malformed URLs, unsafe characters, mailto rules, nested fields, iterators, and FOCA 400 responses.
tests/utils/test_urls.py

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

@uniqueg
uniqueg marked this pull request as ready for review October 21, 2026 23:22
@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 (3256f35) to head (4b0b9d4).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #366    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           24        25     +1     
  Lines         1822      2000   +178     
==========================================
+ Hits          1822      2000   +178     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

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

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

## Individual Comments

### Comment 1
<location path="foca/utils/urls.py" line_range="411" />
<code_context>
+    # Without user info, the host is in brackets if the authority starts
+    # with one (e.g., an IPv6 address)
+    bracketed = parts.netloc.startswith("[")
+    return parts, _normalize_host(parts.hostname, bracketed=bracketed, name=name)
+
+
</code_context>
<issue_to_address>
**Distinct scoped URLs collapse**

When an IPv6 URL has a case-sensitive zone identifier, `_split_http_url` passes `parts.hostname` to `_normalize_host`, but `urlsplit` lowercases the zone identifier. Normalization therefore merges distinct scoped destinations and can address the wrong interface.

Preserve the zone identifier’s original case from the URL authority while normalizing the host.

Also at `foca/utils/urls.py:446`.
</issue_to_address>

### Comment 2
<location path="foca/utils/urls.py" line_range="356" />
<code_context>
+            only digits, and at most 253 characters.
+    """
+    message = f"{name} need email addresses with a domain name."
+    if not domain.isascii():
+        try:
+            domain = idna.encode(domain, uts46=True, transitional=False).decode()
</code_context>
<issue_to_address>
**Invalid IDNA domains pass checks**

When an HTTP(S) host or mailto domain contains an invalid ASCII A-label, `_normalize_host` and `_check_domain` skip IDNA validation for ASCII input, so their regular-expression checks accept malformed A-labels such as `xn--a`; callers see invalid domains accepted as usable URLs.

Validate ASCII domains with IDNA as well as non-ASCII domains in both `_normalize_host` and `_check_domain`.

Also at `foca/utils/urls.py:357-366`, `foca/utils/urls.py:447-452`.
</issue_to_address>

### Comment 3
<location path="foca/utils/urls.py" line_range="299" />
<code_context>
+        InvalidURL: The URL has whitespace, control or format characters,
+            other than `allowed` ones.
+    """
+    if any(
+        char not in allowed
+        and (char.isspace() or unicodedata.category(char) in _REJECTED_CATEGORIES)
</code_context>
<issue_to_address>
**Forbidden URI characters pass checks**

When a URL path or query contains raw punctuation forbidden by URI syntax, such as `<`, `|` or a backslash, `_check_characters` does not reject printable URI-forbidden characters, and `_normalize_percent_encodings` preserves them. `check_url` accepts these URLs and `normalize_url` returns syntactically invalid URIs.

Reject raw characters that URI syntax forbids in paths and queries.

Also at `foca/utils/urls.py:396-398`, `foca/utils/urls.py:502`.
</issue_to_address>

### Comment 4
<location path="foca/utils/urls.py" line_range="278" />
<code_context>
+    """
+    _check_characters(url, name=name)
+    _check_percent_encodings(url, name=name)
+    path = urlsplit(url).path
+    if rest.startswith("//") or not path:
+        raise InvalidURL(f"{name} need valid email addresses.")
</code_context>
<issue_to_address>
**Malformed mailto URLs return 500**

When a mailto URL has a malformed bracketed authority, `_check_mailto` calls `urlsplit` before checking for an authority, and `urlsplit` raises a plain `ValueError`; FOCA’s default handler returns 500 instead of 400.

Convert `urlsplit`’s `ValueError` to `InvalidURL` in `_check_mailto`.
</issue_to_address>

### Comment 5
<location path="foca/utils/urls.py" line_range="235" />
<code_context>
+    """
+    if isinstance(schemes, str):
+        raise ValueError(f"Allowed URL schemes must be a collection: {schemes!r}")
+    allowed = frozenset(schemes)
+    if not allowed:
+        raise ValueError("Allowed URL schemes must not be empty")
</code_context>
<issue_to_address>
**Shared scheme iterators get exhausted**

When two concurrent checks share the same one-shot schemes iterator, `_check_schemes` consumes `schemes` with `frozenset(schemes)`, so concurrent checks sharing a one-shot iterator leave one request with an empty or partial allowed-scheme set; it raises `ValueError` or rejects a URL allowed by the configuration.

Require reusable scheme collections for shared configuration, or materialize the iterator once before sharing it between checks.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and a caller may rely on these checks before storing a service URL that clients later use to send tokens; if a URL that should be rejected passes, reverting the helper will not recall stored values or undo any resulting disclosure. The new idna dependency supports host validation but does not itself change application behavior.

Blocking findings: foca/utils/urls.py:411, foca/utils/urls.py:356, foca/utils/urls.py:299, foca/utils/urls.py:278, foca/utils/urls.py:235


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

Comment thread foca/utils/urls.py Resolved
Comment thread foca/utils/urls.py Resolved
Comment thread foca/utils/urls.py Resolved
Comment thread foca/utils/urls.py Resolved
Comment thread foca/utils/urls.py Resolved
uniqueg and others added 3 commits October 22, 2026 01:33
Reject ASCII characters that URLs only allow percent-encoded (e.g., <,
|, backslashes, brackets) in paths, queries and fragments, also of
mailto URLs; validate IDNA A-labels (xn--) of ASCII hosts and mailto
domains; and reject mailto URLs with an authority before splitting
them, so that malformed ones raise InvalidURL, not ValueError.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit fb27bd7 into dev Oct 21, 2026
14 checks passed
@uniqueg
uniqueg deleted the feat/url-checks branch October 21, 2026 23:57
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.

1 participant