Repository navigation
feat: import service info safely - #362
Conversation
Fetch URLs that users supply without server-side request forgery: allowed schemes, public addresses checked after resolving and pinned for the connection, no redirects, limits of size and total time, no credentials. It knows nothing of the registry, so FOCA can take it. Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
POST /services/import fetches the service info of a service and returns the values for a registration, checked as one. It needs a login, is limited per user, and every failed fetch gets the same response. Closes #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Findings of the review: requests can't take all threads, losing the race to start a rate limit window isn't being at the limit, rejected addresses aren't logged, errors don't repeat fetched values, and only global unicast IPv6 addresses pass. Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the scheme's default port out of the Host header, and refuse any user info. The chart's schema is the library's, so the egress policy's values move to the top level (egressNetworkPolicy). Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR adds a hardened, non-persistent service-info import workflow: a pinned and constrained network fetcher supplies validated registration fields through an authenticated, rate-limited endpoint, with configurable private-network access and optional Helm egress isolation documented and tested. Sequence diagram for service-info importsequenceDiagram
actor User
participant API as POST_services_import
participant Limit as Fetch_limit
participant Fetch as safe_get
participant Service as Service_info_endpoint
participant Validate as RegisterService_check
User->>API: POST serviceInfoUrl
API->>API: service_url
API->>Limit: check_fetch_limit
API->>Fetch: safe_get
Fetch->>Service: GET /service-info
Service-->>Fetch: 200 JSON
Fetch-->>API: response body
API->>Validate: check
Validate-->>API: registration values
API-->>User: 200 values for POST /services
Flow diagram for hardened service-info fetchingflowchart TD
A[User-supplied serviceInfoUrl] --> B[service_url]
B --> C{Allowed scheme and /service-info suffix?}
C -- No --> D[400 Bad Request]
C -- Yes --> E[check_fetch_limit]
E --> F{Rate limit or worker slot available?}
F -- No --> G[429 Too Many Requests]
F -- Yes --> H[safe_get]
H --> I[Resolve host and check every address]
I --> J[Connect to pinned address]
J --> K[GET without credentials or redirects]
K --> L{Fetch succeeds within 256 KiB and 10 seconds?}
L -- No --> M[502 Bad Gateway]
L -- Yes --> N[service_values]
N --> O[RegisterService.check]
O --> P{Valid registration fields?}
P -- No --> Q[400 field-specific error]
P -- Yes --> R[200 values; nothing stored]
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 #362 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 23 25 +2
Lines 2579 2874 +295
==========================================
+ Hits 2579 2874 +295 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Whatever the defaults of the Python version and its OpenSSL, as CodeQL asks for (py/insecure-protocol). Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="deployment/values.yaml" line_range="43-46" />
<code_context>
+ - 127.0.0.0/8
+ - 169.254.0.0/16
+ - 172.16.0.0/12
+ - 192.0.0.0/24
+ - 192.168.0.0/16
+ - 198.18.0.0/15
+ - 224.0.0.0/3
+ - ::/3
+ - 64:ff9b::/96
</code_context>
<issue_to_address>
**Non-public destinations remain allowed**
When the egress policy is enabled and cluster routing reaches an omitted special-use or documentation range, the default `exceptCidrs` omits ranges such as `192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24` and `2001:db8::/32`, so the generated policy permits traffic to them on allowed ports despite its public-only restriction.
Add the omitted non-public ranges to the default `exceptCidrs` list.
</issue_to_address>
### Comment 2
<location path="cloud_registry/safe_fetch.py" line_range="144-146" />
<code_context>
+ return
+ addresses.extend(dict.fromkeys(str(info[4][0]) for info in infos))
+
+ thread = threading.Thread(target=lookup, daemon=True, name="safe-fetch-resolve")
+ thread.start()
+ thread.join(deadline.left())
+ if thread.is_alive() or not addresses:
+ raise Unreachable
</code_context>
<issue_to_address>
**Resolver threads accumulate**
When DNS lookups remain blocked past the fetch deadline and requests continue to arrive, `_resolve()` returns `Unreachable` after the timed `thread.join()`, but `getaddrinfo()` continues in the daemon thread after the fetch slot is released; repeated requests accumulate resolver threads and exhaust worker resources.
Bound resolver concurrency or keep the fetch slot occupied until each resolver thread exits.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service_import.py" line_range="329-338" />
<code_context>
+ fetches = get_collection(FETCHES)
+ current = now()
+ window = current - FETCH_WINDOW
+ if fetches.update_one(
+ {"_id": user, "windowStart": {"$gt": window}, "count": {"$lt": limit}},
+ {"$inc": {"count": 1}},
+ ).modified_count:
+ return
+ try:
+ # a new window, unless the user has one, at the limit (duplicate key)
+ fetches.update_one(
+ {"_id": user, "windowStart": {"$lte": window}},
+ {"$set": {"windowStart": current, "count": 1}},
+ upsert=True,
+ )
</code_context>
<issue_to_address>
**Hourly quota resets too early**
When a user uses the quota near the end of a window and continues immediately after it expires, `check_fetch_limit()` resets the whole count based on `windowStart`, even though later counted fetches may still be less than an hour old; the user can exceed the configured per-hour limit in a short period.
Track and enforce fetches over a rolling one-hour window instead of resetting the entire count based on `windowStart`.
</issue_to_address>
### Comment 4
<location path="cloud_registry/safe_fetch.py" line_range="184" />
<code_context>
+ timeout: Timeout of each socket operation, in seconds.
+ context: TLS settings; plain HTTP if `None`.
+ """
+ super().__init__(host, port, timeout=timeout)
+ # so that the `Host` header only has ports other than the scheme's
+ self.default_port = _DEFAULT_PORTS["http" if context is None else "https"]
</code_context>
<issue_to_address>
**IPv6 imports send malformed Host**
When the service-info address uses an IPv6 literal, `host` is passed unbracketed to `HTTPConnection`, which constructs the `Host` header from it; IPv6 literals therefore produce an invalid header such as `2001:db8::1:8443` instead of `[2001:db8::1]:8443`, so services using IPv6 literals reject imports.
Format IPv6 literals with brackets in the Host header, while preserving the port rules for the scheme.
</issue_to_address>
### Comment 5
<location path="cloud_registry/safe_fetch.py" line_range="291" />
<code_context>
+ raise AddressNotAllowed
+ if not host:
+ raise Unreachable
+ port = port or _DEFAULT_PORTS[scheme]
+ target = parts.path or "/"
+ if parts.query:
</code_context>
<issue_to_address>
**Port zero fetches another endpoint**
When a service-info URL has an explicit port of `0` and passes URL validation, `safe_get` replaces the explicit port `0` with the scheme’s default port, so it fetches a different endpoint than the supplied address. The import response still returns a service URL containing `:0`, which does not identify the endpoint that was fetched.
Reject port `0` or preserve it instead of replacing it with the scheme’s default.
</issue_to_address>
### Comment 6
<location path="cloud_registry/ga4gh/registry/service_import.py" line_range="330" />
<code_context>
+ current = now()
+ window = current - FETCH_WINDOW
+ if fetches.update_one(
+ {"_id": user, "windowStart": {"$gt": window}, "count": {"$lt": limit}},
+ {"$inc": {"count": 1}},
+ ).modified_count:
</code_context>
<issue_to_address>
**Migration resets active fetch quotas**
When a subject namespace migration runs while users still have unexpired fetch-count records, `check_fetch_limit` stores counts under the request subject, but `namespace_subjects` rewrites other subject-keyed data and leaves these records untouched; after the subject is namespaced, that user starts a fresh quota while the old record remains, allowing extra fetches until it expires.
Include `service_info_fetches` in the namespace migration, merging any bare-subject count into the namespaced subject’s record.
</issue_to_address>
### Comment 7
<location path="cloud_registry/ga4gh/registry/service_import.py" line_range="212" />
<code_context>
+ services = get_custom_config(CustomConfig).endpoints.services
+ body = safe_get(
+ # with an encoded host name
+ normalize_url(address),
+ schemes=frozenset(services.url_schemes),
+ networks=private_networks(),
</code_context>
<issue_to_address>
**Import fetches a normalized path**
When a valid service-info URL contains path segments such as `..` or repeated slashes and the server treats the original and normalized paths differently, `normalize_url(address)` removes dot segments and collapses repeated slashes before the fetch, while `service_url()` returns the original path for registration. A server that routes those paths differently returns metadata for a different endpoint than the URL in the registration response.
Use the same canonical URL for both fetching and the returned registration, or fetch the supplied path without path normalization.
</issue_to_address>Linked issues
#359 feat: import service info safely · 7 of 7 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Add a tested fetch helper free of registry logic. | ✅ Met | The standalone safe_fetch module contains the fetch logic, with coverage in tests/test_safe_fetch.py. |
| 2 | Allow only permitted schemes and addresses; check resolved addresses and pin the connection; avoid redirects, limit size and time, and send no token. | ✅ Met | safe_get checks all resolved addresses before connecting to a pinned address, accepts only configured schemes and HTTP 200 responses, and applies response and time limits; the import passes only a User-Agent header. |
| 3 | Provide POST /services/import with login and a per-user rate limit; require an address ending in /service-info and derive url by removing that suffix. | ✅ Met | The route requires authentication, checks the configured fetch limit, and rejects addresses that do not meet the required form. |
| 4 | Validate imported values as for a manual registration and return the same outward error for failed fetches. | ✅ Met | Imported values are schema-checked and passed through RegisterService.check(); fetch-layer errors share the same 502 response. |
| 5 | Configure permitted private ranges (none by default) and fetches per hour. | ✅ Met | ServiceInfoConfig defaults to an empty private_networks list and 30 fetches per hour, and validates both settings. |
| 6 | Add an optional egress NetworkPolicy as a second layer. | ✅ Met | The chart adds the opt-in egressNetworkPolicy and tests its rendered rules and configuration. |
| 7 | Document the API and rejected-fetching reasoning, configuration, upgrade notes, and chart setup; stress that services should make service info public. | ✅ Met | The API, configuration, upgrading, and deployment README docs cover the import and its safeguards, and recommend publicly available service info. |
Sourcery assessment
Needs a human reviewer. 7 findings to address first, and if the address checks or pinned-connection logic are wrong, an authenticated user could make the registry reach an unintended host and receive service-info fields in the response. Reverting stops future fetches, but cannot undo information already exposed.
Blocking findings: deployment/values.yaml:46, cloud_registry/safe_fetch.py:146, cloud_registry/ga4gh/registry/service_import.py:338, cloud_registry/safe_fetch.py:184, cloud_registry/safe_fetch.py:291, and 2 more
Bound lookups, which can outlive their fetches if the resolver hangs. Refuse port 0 instead of fetching the scheme's default port. Return the normalized URL, which is what gets fetched. Add documentation ranges and Teredo to the addresses the egress policy excludes. Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rewriting addresses would turn international host names into their encoded form. Host names stay as written, and paths that normalizing would change are refused, so that what gets fetched is what is returned. Refs #359 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
First part of #358: the registry can fetch service info, safely, and users can import it.
cloud_registry/safe_fetch.py: helper without registry logic (standard library only). Allowed schemes, TLS 1.2 or newer, public addresses checked after resolving and pinned for the connection, certificate checked for the host name, no redirects, 256 KiB, 10 s in total (also against dripping servers), at most 8 lookups at a time, no credentials.POST /services/import: login, 30 fetches per user and hour (custom.endpoints.services.service_info.fetches_per_hour), 2 fetches per worker at a time, the same502for every failed fetch. The address must end in/service-info, with a path in normal form, andurlis set by cutting that off. Values go through the schema and checks of a registration; errors name the field, never the fetched value. Nothing is stored; the client registers withPOST /services.private_networks(none by default).egressNetworkPolicy(top level, ascloudRegistryfollows the library's schema, which a test pins).jsonschemabecomes a direct dependency (already locked, through Connexion).Closes #359
Verification
py/insecure-protocolalerts are fixed. Two open Trivy notes forlibapt-pkg(CVE-2026-109518, severity unknown) come fromdev, not from this PR, and the image scan passes with them.tests/test_safe_fetch.py,tests/test_service_import.py,tests/test_chart.py, with 100% coverage of the new modules;ruff0.17.3,mypy,mkdocs build --strict. An earlier full local run had one failure, the chart schema test, since fixed; CI ran the full suite on the final commit.Declined review findings
200that isn't service info returning400rather than the502: kept, as users need to know what's wrong; it only distinguishes hosts that passed the address checks, anddocs/configuration.mdsays so.service_info_fetchesin the subject migration (the records expire within two hours); brackets for IPv6 in theHostheader (not a bug; a test now pins it).🤖 Generated with Claude Code