Skip to content

feat: import service info safely - #362

Merged
uniqueg merged 7 commits into
devfrom
feat/service-info-import
Nov 5, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/service-info-import

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

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 same 502 for every failed fetch. The address must end in /service-info, with a path in normal form, and url is 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 with POST /services.
  • Config: private_networks (none by default).
  • Chart: optional egress NetworkPolicy, egressNetworkPolicy (top level, as cloudRegistry follows the library's schema, which a test pins).
  • Docs: API (the rejected-fetching reasoning is replaced; proving control stays rejected), configuration, upgrade notes, chart README, release notes.
  • jsonschema becomes a direct dependency (already locked, through Connexion).

Closes #359

Verification

  • CI on a9878ad: all checks passed, including tests on mongomock and MongoDB 7.0, the smoke test, chart, docs, image scan and Sourcery.
  • Code scanning: the two CodeQL py/insecure-protocol alerts are fixed. Two open Trivy notes for libapt-pkg (CVE-2026-109518, severity unknown) come from dev, not from this PR, and the image scan passes with them.
  • Locally: tests/test_safe_fetch.py, tests/test_service_import.py, tests/test_chart.py, with 100% coverage of the new modules; ruff 0.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.
  • Real servers on loopback for plain HTTP and TLS (pinning, SNI and certificate check, dripping in each phase); an end-to-end test through the app with a local service in a permitted network.
  • Not run: against real public services.

Declined review findings

  • Secrets in the path of accepted addresses can still reach the logs: paths are no place for secrets, and the address is needed to debug failed imports.
  • Reviewer's note on a 200 that isn't service info returning 400 rather than the 502: kept, as users need to know what's wrong; it only distinguishes hosts that passed the address checks, and docs/configuration.md says so.
  • Sourcery: rolling instead of fixed window for the fetch limit (the limit guards against abuse, the worst case is twice the limit around a window's end); including service_info_fetches in the subject migration (the records expire within two hours); brackets for IPv6 in the Host header (not a bug; a test now pins it).

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 5, 2026 01:32
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 import

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

Flow diagram for hardened service-info fetching

flowchart 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]
Loading

File-Level Changes

Change Details Files
Add a standard-library URL fetcher with SSRF, TLS, redirect, credential, size, and total-time protections, including DNS resolution checks and pinned connections.
  • Allow only caller-approved HTTP(S) schemes and permitted public or configured private networks.
  • Resolve all addresses before connecting and preserve the checked address for the connection.
  • Enforce hostname certificate validation, no redirects, 200-only responses, 256 KiB limits, and 10-second deadlines including slow handshakes and dripping responses.
  • Expose uniform network failure exceptions without leaking network details.
cloud_registry/safe_fetch.py
tests/test_safe_fetch.py
Implement authenticated service-info import that fetches, filters, validates, and returns registration values without persisting them.
  • Add POST /services/import with address validation, /service-info stripping, login enforcement, and consistent 400/429/502 behavior.
  • Reuse registration schema and service checks while ignoring unsupported fields and sanitizing validation errors to field names.
  • Add per-user hourly MongoDB-backed fetch limits and a per-worker concurrent-fetch semaphore.
  • Add service-info configuration for permitted private networks and fetch frequency.
cloud_registry/api/additions.openapi.yaml
cloud_registry/ga4gh/registry/service_import.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/service_models/custom_config.py
cloud_registry/config.yaml
cloud_registry/exceptions.py
tests/test_service_import.py
tests/mock_data.py
pyproject.toml
uv.lock
Add an optional Helm egress NetworkPolicy and document operational, API, configuration, and upgrade requirements for outbound imports.
  • Add disabled-by-default egress controls for DNS, release MongoDB, public service ports, excluded CIDRs, and explicit private destinations.
  • Extend the chart schema and test rendered policy defaults, isolation, customization, and invalid values.
  • Document import safeguards, rate limits, private-network risks, required egress, and upgrade behavior.
  • Update API and release documentation with the new endpoint and security model.
deployment/templates/networkpolicy-egress.yaml
deployment/values.yaml
deployment/values.schema.json
deployment/README.md
tests/test_chart.py
docs/api.md
docs/configuration.md
docs/releases/1.0.0rc2.md
docs/upgrading.md

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

Comment thread cloud_registry/safe_fetch.py Fixed
Comment thread tests/test_safe_fetch.py Fixed
@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9ba72e9) to head (a9878ad).
⚠️ Report is 1 commits behind head on dev.

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

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]>
@uniqueg
uniqueg marked this pull request as ready for review November 5, 2026 01:14

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


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

Comment thread deployment/values.yaml Resolved
Comment thread cloud_registry/safe_fetch.py Resolved
Comment thread cloud_registry/safe_fetch.py Resolved
Comment thread cloud_registry/safe_fetch.py Resolved
uniqueg and others added 2 commits November 5, 2026 02:28
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]>
@uniqueg
uniqueg merged commit 0db1b0c into dev Nov 5, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/service-info-import branch November 5, 2026 02:01
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.

feat: import service info safely

2 participants