Repository navigation
Send the UK proxy's own credential to the Public API - #133
Merged
Merged
Conversation
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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #132
Summary
The Modal app
marriage-household-apiproxies 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 inAuthorization: Beareron 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 secretmarriage-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 thepolicyengine-api-accessskill's templatetemplates/public_api_token.py, from PolicyEngine/policyengine-skills commit2e751e5. 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:OSError,http.client.HTTPException) also becomesPublicApiTokenError, because urllib wraps only failures while sending inURLError;What the module does:
client_credentialsgrant, with a 10-second timeout;repr(), errors and the store.backend/public_api.py(new) reads the fivePOLICYENGINE_API_*settings when a UK request needs them and keeps one token provider per client.marriage-household-api-public-api-token, created on first use, so containers share one token instead of each asking Auth0.https://api.policyengine.orgwithout a credential, as before.POLICYENGINE_API_URLthat 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_apiadds the token and posts toPOLICYENGINE_API_URL+/uk/calculate.CalculationError.backend/modal_app.py:HouseholdAPIgetssecrets=[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) andbackend/tests/conftest.py(new: removes the five variables from every test's environment).backend/README.mdanddocs/testing.mddescribe:modal serveon this app, which would use the production secret;Environment variables and secrets
Every variable the changed code reads comes from one place: the Modal secret
marriage-household-api-policyengine-apiin workspacepolicyengine, created on 2026-11-09 with production values. The image build reads none of them.POLICYENGINE_API_URLPublicApiSettings.from_environment, throughpublic_api_tokens()inbackend/public_api.py, while a UK request is handledmarriage-household-api-policyengine-apiHouseholdAPIthroughsecrets=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_DOMAINPOLICYENGINE_API_AUTH0_AUDIENCEPOLICYENGINE_API_AUTH0_CLIENT_IDPOLICYENGINE_API_AUTH0_CLIENT_SECRETci.yml) and the manuallive-uk.ymlprovide 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.marriage-household-api-public-api-tokenis not a setting. The app creates it on its first UK request in a container, using the container's own Modal credentials.Unverified:
required_keysmakes a deploy fail if a key is missing, not if a value is wrong. The check after the deploy (below) confirms them.restrict_modal_accessis 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 inbackend/README.md. That needs the maintainers' go-ahead:The client ID
7YpjS3AwYLroyuyM86KvxTUyFgFFoK6Pis 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:After deploying: run one UK calculation. Then the Public API's records (Cloud Logging,
request.completedwithcaller.client_id=7YpjS3AwYLroyuyM86KvxTUyFgFFoK6P) should showcaller.kindserveron/<country_id>/calculatewith status 200, and nopublic_api_credential_refusedevent 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 intest_uk_accounting.pyweren't run locally: CI runs them. They passheaders=through**kwargs, and with no settings the request goes to the same URL as before.Red-green, first round (12 tests):
6588f50(tests only), 11 failed on their assertions, exit code 1.test_without_settings_the_request_carries_no_credentialpassed: it describes the behaviour without settings, which doesn't change.ad3b6e8(code), all 12 passed, exit code 0.Red-green, after review round 1 (17 tests):
96af183(tests only), 4 failed on their assertions, exit code 1. These were the threetest_token_answer_that_breaks_off_gives_the_usual_json_errorcases (closed-before-answer,reset-while-reading,incomplete-answer) andtest_inside_modal_missing_settings_are_refused_before_any_request. The other 13 passed.35c41a9(fix), all 17 passed, exit code 0.Red-green, after review round 2 (20 tests):
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], andtest_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.7044d40(fix), all 20 passed, exit code 0.Lint:
ruff check backendandruff format --check backendpass 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.
ad3b6e8):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 in96af183and35c41a9.SETTING_VARIABLESin tests;35c41a9):One bug, with two triggers that still reached Starlette's plain-text 500 without CORS headers:
AttributeError);POLICYENGINE_API_URL(httpx.InvalidURL).Fixed test-first in
2cfd194and7044d40.Code-quality points applied:
modal serve.7044d40): no substantiated bugs, so review ended there.394cf89: the timeout comment inuk.pyno 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 thebackendpackage at module level. So deploying doesn't depend on which directorymodal deployruns from. A test checks that the list matchesSETTING_VARIABLES.On the 401 path, the chained
httpx.HTTPStatusErrorkeeps itsrequest, 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_apihelper inpublic_api_token.pyis 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_DOMAINgets 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:
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