Skip to content

Send the UK proxy's own credential to the Public API - #133

Merged
anth-volk merged 7 commits into
mainfrom
marriage-backend-public-api-credential
Nov 12, 2026
Merged

anth-volk merged 7 commits into
mainfrom
marriage-backend-public-api-credential

Conversation

@anth-volk

Copy link
Copy Markdown
Contributor

Fixes #132

Summary

The Modal app marriage-household-api proxies the calculator's UK household calculations to the Public API's /uk/calculate. Until now it sent no credential. The Public API is becoming callable only by PolicyEngine's own servers. This PR makes the backend send its own Auth0 client-credentials token in Authorization: Bearer on every Public API request. The token comes from the Public API's own tenant, and the client's secret is read at run time from the Modal secret marriage-household-api-policyengine-api.

US calculations run in this backend's own process and are unchanged. The browser still calls only the Modal app.

Changes

  • backend/public_api_token.py (new) is the policyengine-api-access skill's template templates/public_api_token.py, from PolicyEngine/policyengine-skills commit 2e751e5. It is reformatted for this repository's Ruff, and three lint exceptions (# noqa: BLE001, # noqa: FLY002) are added for rules the locked Ruff 0.16.6 enables. It has two changes, both found in review:

    • a connection that fails while Auth0's answer is read (OSError, http.client.HTTPException) also becomes PublicApiTokenError, because urllib wraps only failures while sending in URLError;
    • a 2xx answer whose JSON is not an object is refused like one without a token.

    What the module does:

    • requests a token with the client_credentials grant, with a 10-second timeout;
    • keeps it in memory and in a shared store until five minutes before it expires (tokens last 24 hours);
    • never follows a redirect;
    • never requests a new token after a 401;
    • keeps the client secret out of repr(), errors and the store.
  • backend/public_api.py (new) reads the five POLICYENGINE_API_* settings when a UK request needs them and keeps one token provider per client.

    • Inside a Modal container, the shared store is the Modal Dict marriage-household-api-public-api-token, created on first use, so containers share one token instead of each asking Auth0.
    • Outside Modal with no settings (local runs, the manual "Live UK integration checks" workflow), requests go to https://api.policyengine.org without a credential, as before.
    • Inside Modal the settings are required. A partial set is refused everywhere, and so is a POLICYENGINE_API_URL that doesn't parse as an https URL with a host. Each of these is refused before any network call, as the JSON 500 "The UK calculation service is not configured.", and the log names only variable names.
  • backend/uk.py: post_to_public_api adds the token and posts to POLICYENGINE_API_URL + /uk/calculate.

    • A 401 from the Public API is logged with the client ID (never the secret or token) and becomes the existing "unavailable" CalculationError.
    • A failed token request does the same and sends nothing to the Public API.
    • The 110-second upstream timeout now includes the token request, so a request stays within the Modal function's 120 seconds.
  • backend/modal_app.py: HouseholdAPI gets secrets=[modal.Secret.from_name("marriage-household-api-policyengine-api", required_keys=[...the five...])], so a deploy fails if the secret or a key is missing. The image ships the two new modules.

  • backend/tests/test_public_api_credential.py (new, 20 tests) and backend/tests/conftest.py (new: removes the five variables from every test's environment).

  • backend/README.md and docs/testing.md describe:

    • the credential, the secret and the Dict;
    • the failure behaviour, and that the timeouts apply to each connection and read;
    • not running modal serve on this app, which would use the production secret;
    • what happens to the manual live UK checks.

Environment variables and secrets

Every variable the changed code reads comes from one place: the Modal secret marriage-household-api-policyengine-api in workspace policyengine, created on 2026-11-09 with production values. The image build reads none of them.

Variable Read by Provider Wiring
POLICYENGINE_API_URL PublicApiSettings.from_environment, through public_api_tokens() in backend/public_api.py, while a UK request is handled Modal secret marriage-household-api-policyengine-api Attached to HouseholdAPI through secrets= on @app.cls. Modal sets the keys as environment variables in each container. Containers restored from the memory snapshot keep the snapshot's environment, which includes them. The @modal.enter(snap=True) step reads none of them.
POLICYENGINE_API_AUTH0_DOMAIN same same same
POLICYENGINE_API_AUTH0_AUDIENCE same same same
POLICYENGINE_API_AUTH0_CLIENT_ID same same same
POLICYENGINE_API_AUTH0_CLIENT_SECRET same; sent only in the token request's body same same
  • CI (ci.yml) and the manual live-uk.yml provide none of these. This repository has no GitHub Actions secrets or variables. So both run the path without a credential: standard CI mocks the Public API, and the live UK checks call it without a credential.
  • The Modal Dict marriage-household-api-public-api-token is not a setting. The app creates it on its first UK request in a container, using the container's own Modal credentials.

Unverified:

  • The secret's values. They were written by the Public API maintainers on 2026-11-09 and can't be read back. required_keys makes a deploy fail if a key is missing, not if a value is wrong. The check after the deploy (below) confirms them.
  • That a restored container still has the secret's variables. Modal 1.5.5's restore code changes only Modal's own settings and leaves other environment variables at their snapshot values, but this is confirmed only once a deployed container sends the token.
  • That the container may create the Dict. Nothing restricts its Modal access (restrict_modal_access is off), but this is confirmed only after the deploy.

Deployment

No workflow deploys this app. The last deploy, v6, was done by hand on 2026-10-30 from 0c9e1fe. Merging changes nothing until someone deploys by hand, as in backend/README.md. That needs the maintainers' go-ahead:

env -u MODAL_TOKEN_ID -u MODAL_TOKEN_SECRET uv run --project backend modal deploy backend/modal_app.py

The client ID 7YpjS3AwYLroyuyM86KvxTUyFgFFoK6P is on the Public API's production allow list (PUBLIC_API_SERVER_CLIENT_IDS, read on 2026-11-11), so the token is accepted today. The Public API still serves requests without a credential (PUBLIC_API_SERVER_CREDENTIAL_REQUIRED=0), so rolling back is safe:

env -u MODAL_TOKEN_ID -u MODAL_TOKEN_SECRET uv run --project backend modal app rollback marriage-household-api v6

After deploying: run one UK calculation. Then the Public API's records (Cloud Logging, request.completed with caller.client_id = 7YpjS3AwYLroyuyM86KvxTUyFgFFoK6P) should show caller.kind server on /<country_id>/calculate with status 200, and no public_api_credential_refused event for this client. Before this change, the Public API had no records under this client.

Testing

Each test was run individually by its pytest node ID, from backend/. No full suite was run. The existing tests in test_uk_accounting.py weren't run locally: CI runs them. They pass headers= through **kwargs, and with no settings the request goes to the same URL as before.

Red-green, first round (12 tests):

  • At 6588f50 (tests only), 11 failed on their assertions, exit code 1. test_without_settings_the_request_carries_no_credential passed: it describes the behaviour without settings, which doesn't change.
  • At ad3b6e8 (code), all 12 passed, exit code 0.

Red-green, after review round 1 (17 tests):

  • At 96af183 (tests only), 4 failed on their assertions, exit code 1. These were the three test_token_answer_that_breaks_off_gives_the_usual_json_error cases (closed-before-answer, reset-while-reading, incomplete-answer) and test_inside_modal_missing_settings_are_refused_before_any_request. The other 13 passed.
  • At 35c41a9 (fix), all 17 passed, exit code 0.

Red-green, after review round 2 (20 tests):

  • At 2cfd194 (tests only), 3 failed on their assertions, exit code 1: test_token_answer_that_breaks_off_gives_the_usual_json_error[answer-not-an-object], and test_unusable_public_api_url_is_refused_before_any_request[malformed] and [not-https]. The other 17 passed. This includes the redirect case, which now answers 302 rather than 307: urllib's default handler would follow a 302, so the case shows that the provider's opener refuses it.
  • At 7044d40 (fix), all 20 passed, exit code 0.

Lint: ruff check backend and ruff format --check backend pass with the locked Ruff 0.16.6.

Review

These were self-reviews by fresh subagents of the same workflow, so no review disposition was given.

  • Round 1 (ad3b6e8):
    • One bug: a token answer that broke off while being read (RemoteDisconnected, ConnectionResetError, IncompleteRead, ssl.SSLError) escaped the token provider. Starlette then answered with a plain-text 500 without CORS headers, so the browser saw a network error. Fixed test-first in 96af183 and 35c41a9.
    • Code-quality points applied:
      • require the settings inside Modal;
      • fake only urllib's HTTPS handler in tests, so the real opener and its redirect refusal are tested;
      • load a private copy of the Modal app in its test;
      • take the variable names from SETTING_VARIABLES in tests;
      • add a return type;
      • correct two documentation statements.
  • Round 2 (35c41a9):
    • One bug, with two triggers that still reached Starlette's plain-text 500 without CORS headers:

      • a 2xx token answer whose JSON is not an object (AttributeError);
      • a malformed POLICYENGINE_API_URL (httpx.InvalidURL).

      Fixed test-first in 2cfd194 and 7044d40.

    • Code-quality points applied:

      • a 302 redirect case;
      • per-connection-and-read timeout wording;
      • a warning against modal serve.
  • Round 3 (7044d40): no substantiated bugs, so review ended there.
    • Code-quality points applied in 394cf89: the timeout comment in uk.py no longer says the 110 seconds limit the whole request, and the settings log says "missing or unusable".

Left as they are:

  • The five variable names are written out again in backend/modal_app.py, which keeps its existing pattern of importing nothing from the backend package at module level. So deploying doesn't depend on which directory modal deploy runs from. A test checks that the list matches SETTING_VARIABLES.

  • On the 401 path, the chained httpx.HTTPStatusError keeps its request, whose headers hold the token. Nothing logs or serializes it: no error reporter is installed, and the web layer returns only the message.

  • The copied call_public_api helper in public_api_token.py is unused. The file stays close to the template so later updates are easy to compare.

  • The live UK checks and local runs will fail once the Public API requires a credential. No client exists for them, and the production client must not be used there.

  • POLICYENGINE_API_AUTH0_DOMAIN gets no format check. A malformed value surfaces as a failed token request ("unavailable") rather than "not configured". Only the diagnosis is slower; the secret never shows.

  • No test covers:

    • a failing Modal Dict read or write (the provider logs a warning and falls back to Auth0 or to memory);
    • an expired token in the Dict being overwritten;
    • concurrent requests sharing one token request under the provider's lock.

    That code is the template's, unchanged.

  • Neither the Dict calls nor DNS lookups have a timeout of their own.

  • The two changes to the copied template also apply to the template itself, on Add policyengine-api-access and stop sending browser code to the Public API policyengine-skills#116. This PR doesn't change it.

🤖 Generated with Claude Code

anth-volk and others added 7 commits November 11, 2026 20:10
The UK adapter posts to the Public API's /uk/calculate without any
credential. These tests describe the intended behaviour: with the five
POLICYENGINE_API_* settings from the Modal secret, each request carries
this backend's Auth0 client-credentials token, cached in memory and in a
shared Modal Dict, replaced five minutes before it expires, never
renewed after a 401, and never revealed in errors or logs. They also
check that the Modal app ships every backend module and attaches the
secret. A conftest fixture keeps a developer's own settings out of the
tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Public API will soon answer only PolicyEngine's servers. The UK
adapter now sends this backend's Auth0 client-credentials token from
the Public API's own tenant in Authorization: Bearer.

- backend/public_api_token.py is the policyengine-api-access skill's
  template, reformatted. It requests one token, keeps it in memory and
  in a shared store until five minutes before it expires, never renews
  it after a 401, never follows redirects, and keeps the secret out of
  its errors.
- backend/public_api.py reads the five POLICYENGINE_API_* settings when
  a request needs them and uses the Modal Dict
  marriage-household-api-public-api-token inside Modal containers.
  Without any setting, requests go to https://api.policyengine.org
  without a credential, as before; a partial set is refused.
- backend/uk.py adds the token, logs a 401 with the client ID, and
  counts the token request against its 110-second upstream timeout.
- modal_app.py attaches the Modal secret
  marriage-household-api-policyengine-api, requiring its five keys,
  and ships the two new modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ttings

Review round 1 found that a token request failing while Auth0's answer
is read (RemoteDisconnected, ConnectionResetError, IncompleteRead)
escapes the token provider. Starlette then answers with a plain-text 500
without CORS headers. The new HTTP-route tests expect the usual JSON 500.

The fake Auth0 now replaces only urllib's HTTPS handler, so the
provider's own opener, its redirect refusal (new "redirected" case) and
urllib's error handling are in the tested path. Another new test expects
a Modal container with no usable settings to refuse the request instead
of sending it without a credential. The Modal app test loads a private
copy of the module, and the tests take the variable names from
SETTING_VARIABLES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… on Modal

- public_api_token.py: urllib wraps only failures while sending in
  URLError. A connection that closes, resets or ends early while
  Auth0's answer is read now also becomes PublicApiTokenError (OSError,
  http.client.HTTPException), so the browser gets the usual JSON 500
  with CORS headers instead of Starlette's plain-text 500. This is the
  one change from the skill's template.
- public_api.py: inside a Modal container the five settings are
  required, so a secret with empty values fails the UK request instead
  of silently dropping the credential. _shared_token_store has a return
  type.
- backend/README.md and docs/testing.md: the Dict is created once, not
  on every deploy; no client exists for local runs or the live UK
  workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le URLs

Review round 2 found two more inputs that reach Starlette's plain-text
500 without CORS headers: a 2xx token answer whose JSON is not an
object (AttributeError in the token provider), and a malformed
POLICYENGINE_API_URL (httpx.InvalidURL from httpx.post). The new tests
expect the usual JSON 500, and expect an unusable or non-https address
to be refused before any request. The redirect case now uses 302, which
urllib's default handler would follow, so it shows that the provider's
opener refuses redirects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…I URL

- public_api_token.py: a 2xx answer whose JSON is not an object is
  refused like one without a token (PublicApiTokenError), instead of
  raising AttributeError. This is the template's second change.
- public_api.py: POLICYENGINE_API_URL must parse as an https URL with a
  host; otherwise the request is refused as "not configured" before
  any network call, instead of httpx.InvalidURL escaping as a
  plain-text 500, or the token going out unencrypted.
- backend/README.md: the timeouts apply to each connection and read,
  not to the whole request; don't run `modal serve`, which would use
  the production secret.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 3: the timeout comment said the 110 seconds keep a request
within Modal's 120 seconds, but httpx applies it to each connection and
read. The settings log also called an unusable URL "incomplete".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 11, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
marriage Ready Ready Preview Nov 11, 2026 5:08pm UTC

Request Review

@anth-volk
anth-volk marked this pull request as ready for review November 12, 2026 22:01
@anth-volk
anth-volk merged commit 74c8849 into main Nov 12, 2026
3 checks passed
@anth-volk
anth-volk deleted the marriage-backend-public-api-credential branch November 12, 2026 22:07

This branch was successfully deployed

1 active deployment
Preview — 394cf89a Deployed Nov 11, 2026 by vercel[bot]
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.

The UK proxy should send its own credential to the Public API

1 participant