Repository navigation
feat: add URL normalization and scheme checks - #366
Conversation
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]>
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]>
Reviewer's GuideAdds 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 normalizationflowchart 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"]
File-Level Changes
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 #366 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 24 25 +1
Lines 1822 2000 +178
==========================================
+ Hits 1822 2000 +178
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 thehttps-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/httpsURLs need a valid host (IDNA 2008 host names, dotted-decimal IPv4, bracketed IPv6 with optional zone ID), no user info, no port0;mailtoURLs 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)withcode = 400, so FOCA's problem handler answers uncaught ones with400; unsupported schemes (an app error) raise a plainValueError.URLScheme(Literal["http", "https", "mailto"]),HTTP_SCHEMES,SUPPORTED_SCHEMESfor app config models.idna>=3.7,<4is now a direct dependency (it was transitive via requests).docs/utilities.md, API reference entry.Differences from cloud-registry's helpers, relevant for its migration (cloud-registry#157):
normalize_url(url.strip(" "), ...)to keep accepting them (normalized keys stay identical otherwise).[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. Invalidxn--labels are rejected (found by Sourcery).<,|, backslashes, brackets) are rejected in paths, queries and fragments (found by Sourcery); cloud-registry accepted them.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 withidna==3.7(lowest bound); 100% line coverage offoca/utils/urls.py.ruff check,ruff format --check,mypy: clean;mkdocs build --strict: clean.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
_normalize_host()directly (quality, medium): kept, asurlsplit()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.urlsplit()(not the case:SplitResult.hostnameonly lowercases the part before%), and one-shot scheme iterators shared between calls (callers pass collections, as typed; an exhausted iterator raises a plainValueError). Replied in the threads.Open questions
None.
🤖 Generated with Claude Code