Skip to content

feat: add public URLs and typed custom config - #465

Merged
uniqueg merged 5 commits into
devfrom
feat/public-url-custom-config
Oct 24, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/public-url-custom-config

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves the public URL and typed custom config helpers of cloud-registry (cloud_registry/utils.py) into FOCA, generically:

  • server.public_url (new, optional, default None): absolute http/https URL of the app as clients see it, including any path prefix of a reverse proxy. Checked and normalized with foca.utils.urls.normalize_url() (no user info; e.g., lowercase host, no default port or trailing slash, canonical bracketed IPv6 hosts with encoded zone IDs, so _format_host() is not needed). Queries and fragments (also empty ones) are rejected.
  • foca.utils.urls.get_public_url(path=""): in a request context, public_url followed by the app's root path (request.script_root) and path, percent-encoded (the prefix of public_url as configured), without trailing slash unless it is the host's root, as in cloud-registry. Raises RuntimeError if public_url is not set: no fallback to the Host and X-Forwarded-* headers, which clients control unless a proxy sets them. Paths with dot segments (., ..) raise InvalidURL (400), as clients would resolve them, e.g., to URLs outside of the app, and paths may come from clients (identifiers). Paths with unpaired surrogates, which cannot be encoded, also raise InvalidURL. Percent-encodings in path are kept literally (%2e%2e becomes %252e%252e).
  • foca.get_custom_config(model) (in foca.config.access, exported from foca): the custom config of the current app, typed, if it is an instance of model; otherwise RuntimeError, naming the expected and found types and hinting that custom_config_model must be the model's full module path.
  • Docs: configuration/server.md (public URL section with a proxy example), configuration/custom.md (get_custom_config()), utilities.md (building public URLs), API reference, templates/config.yaml, and a short entry under "Other changes" in migration-0.18.md (opt-in, no changes needed for existing apps).

Backwards compatible: new optional setting and functions only.

Verification

Locally (Python 3.12, MongoDB 7.0 on port 12345), after merging origin/dev:

  • coverage run -m pytest: all passed (2255 with MongoDB after merging origin/dev; 2127 without MongoDB after the last commit), 1 skipped; coverage report: 100%
  • mypy: no issues (88 files)
  • ruff check, ruff format --check: pass
  • pre-commit run --all-files: all hooks pass (incl. semgrep, ast-grep and their rule tests)
  • mkdocs build --strict: builds without warnings

Review: adversarial-reviewer and quality-reviewer, 2 rounds, no high findings. Round 1 fixes (InvalidURL instead of ValueError for dot segments, docstring and docs corrections, extra tests) are in the third commit; round 2 fixes (InvalidURL for unpaired surrogates, only get_config imported lazily because of the import cycle, normalization tests) in the last one.

CI: all checks pass (unit tests on Python 3.11 to 3.15 with MongoDB 7.0 and 8.0 and lowest dependencies, integration tests, chart tests on kind, image scans, CodeQL, Codecov patch and project, Read the Docs).

Declined review findings

  • Slashes within path segments (e.g., an identifier a/b) cannot be expressed, as path is a whole, not percent-encoded path, as in cloud-registry. Accepting a sequence of segments would change the API proposed in feat: add public URLs and typed custom config #460; documented instead (apps should not allow slashes in identifiers that are part of public URLs).
  • Repeated slashes inside paths (/a//b) are kept, not collapsed or rejected, as they are part of the path as given; documented and tested.

Open questions

None. The issue's open question (fallback to the request URL when public_url is unset) keeps the choice the issue names: no fallback, RuntimeError; a fallback can be added later.

Follow-ups

  • cloud-registry: replace custom.endpoints.service with server.public_url and delete get_custom_config(), get_public_url() and _format_host() from cloud_registry/utils.py (separate issue there, as described in feat: add public URLs and typed custom config #460).
  • foca-common chart: possibly a helper setting server.public_url from hostName (its tests set custom.public_url today).

Closes #460

🤖 Generated with Claude Code

Summary by Sourcery

Add opt-in support for client-facing public URLs and typed custom configuration access.

New Features:

  • Add optional server.public_url configuration for normalized client-facing application URLs.
  • Provide get_public_url() for safely building percent-encoded public application URLs in request contexts.
  • Provide typed get_custom_config() access to application-specific configuration models.

Enhancements:

  • Reject unsafe or ambiguous public URL paths, including dot segments and unencodable characters, while avoiding trust in request host headers.
  • Document public URL configuration, URL construction, and typed custom configuration access.

Documentation:

  • Document public URL configuration, public URL generation, typed custom configuration, API references, migration guidance, and configuration templates.

Tests:

  • Add coverage for public URL normalization, URL generation, path validation, and typed custom configuration errors and access.

uniqueg and others added 5 commits October 24, 2026 14:44
Add the optional setting `server.public_url`, the URL of the app as
clients see it behind a reverse proxy or ingress. It is checked and
normalized with `foca.utils.urls` and must not have a query or
fragment.

Add `foca.utils.urls.get_public_url()`, which builds URLs of paths of
the app from it, the root path of the app and the path, percent-
encoded. It raises a `RuntimeError` if `public_url` is not set, rather
than trusting the `Host` and `X-Forwarded-*` headers of requests, and a
`ValueError` for paths with dot segments.

Add `foca.get_custom_config()`, which returns the custom config of the
app typed as the given model, or raises a `RuntimeError`.

Moved from cloud-registry (`cloud_registry/utils.py`), generalized.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe `server.public_url` (with a proxy example), `get_public_url()`
and `get_custom_config()`, add the option to `templates/config.yaml`,
and mention both in the notes for 0.18.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Raise `InvalidURL` (400 Bad Request) instead of a plain `ValueError`
for dot segments, as paths may come from clients. Import Flask and the
config only in `get_public_url()`, so that URL checks stay independent
of them. Document how percent-encodings and slashes in paths are kept,
and tidy tests and docs after review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Raise `InvalidURL` (400) for paths with unpaired surrogates, which
`quote()` cannot encode, rather than a `UnicodeEncodeError` (500).
Import Flask at module level again; only `get_config()` is imported
lazily, because of the import cycle with the config models. Test that
`server.public_url` resolves dot segments and repeated slashes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.18.0 milestone Oct 24, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces two opt-in FOCA helpers: normalized reverse-proxy-aware public URL generation with defensive path validation, and typed access to custom application configuration, with exports, documentation, templates, and extensive tests.

Sequence diagram for building a validated public URL

sequenceDiagram
    participant App as FOCA app
    participant Config as ServerConfig
    participant Request as Flask request
    participant URLs as get_public_url
    participant Client as Client

    App->>Config: _normalize_public_url(public_url)
    Config-->>App: normalized server.public_url
    Client->>URLs: get_public_url(path)
    URLs->>Config: get_config()
    URLs->>Request: read script_root
    URLs->>URLs: quote(root) and quote(path)
    URLs-->>Client: public URL

    alt public_url is not configured
        URLs-->>Client: RuntimeError
    else path has dot segments or unpaired surrogates
        URLs-->>Client: InvalidURL
    end
Loading

File-Level Changes

Change Details Files
Adds normalized, opt-in public URL configuration and secure request-context URL construction.
  • Adds optional server.public_url with HTTP(S)-only validation, normalization, and rejection of credentials, queries, and fragments.
  • Adds get_public_url() using configured URL, application root path, and percent-encoded path components while rejecting dot segments and unpaired surrogates.
  • Exports the helper and documents reverse-proxy prefix and header-handling behavior.
  • Adds comprehensive normalization, encoding, security, and request-context tests.
foca/models/config.py
foca/utils/urls.py
foca/__init__.py
docs/configuration/server.md
docs/utilities.md
docs/reference.md
docs/migration-0.18.md
templates/config.yaml
tests/models/test_config.py
tests/utils/test_urls.py
Adds typed access to application custom configuration.
  • Introduces generic get_custom_config(model) with runtime type validation and diagnostic errors for missing or mismatched configuration.
  • Re-exports the accessor from foca, using lazy config access to avoid import cycles.
  • Documents model-path requirements and adds tests for typed, base-class, missing, mismatched, and context-dependent access.
foca/config/access.py
foca/__init__.py
docs/configuration/custom.md
docs/reference.md
docs/migration-0.18.md
tests/config/test_access.py

Assessment against linked issues

Issue Objective Addressed Explanation
#460 Add an optional server.public_url setting that accepts an absolute HTTP(S) URL, rejects user info, queries, and fragments, and normalizes the URL. ✅
#460 Provide get_public_url() to build client-facing URLs from the configured public URL, app root path, and requested path, with the required encoding and slash behavior, and raise an error when no public URL is configured. ✅
#460 Provide and export get_custom_config(model) for retrieving typed custom configuration, and document and test the new setting and helpers. ✅

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 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (6661f3f) to head (19413f0).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #465   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         3342      3378   +36     
=========================================
+ Hits          3342      3378   +36     
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.

@uniqueg
uniqueg marked this pull request as ready for review October 24, 2026 13:02

@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 reviewed your changes and they look great!

Sourcery assessment

Approved.


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

@uniqueg
uniqueg merged commit 7802f8e into dev Oct 24, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/public-url-custom-config branch October 24, 2026 13:04
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: add public URLs and typed custom config

1 participant