Repository navigation
Issue #1182: feat: stand up the control-plane service skeleton with its own database - #1384
Conversation
…ts own database First slice of #1182: a control_plane_restapi base and lif_control_plane_api project that package only cognito_auth and logging, a /health-check that pings the control plane's own database, and Cognito auth that fails closed when no user pool is configured. Local compose gets the service plus a separate Postgres container whose migrations folder (empty for now) is its initdb.d. The developer-key table and endpoints wait on #1190. The deploy workflow, CloudFormation params and Aurora database are the AWS half. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…oject uv.lock Apply #1385's pattern (Issue #957) to the new lif_control_plane_api image: the builder runs `uv sync --locked` and exports the lock to constraints.txt, and the runtime installs the wheel with `--constraint`, so local compose gets the locked versions instead of re-resolving from PyPI. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…osed An empty strategy list is a supported configuration: every request that isn't on a public path gets 401 "Missing or invalid credentials", whatever credentials it carries. The control-plane skeleton (#1384) relies on this instead of carrying its own explicit deny. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and step keys (#1406) ##### Description of Change **Problem.** The Dagster LIF job (`orchestrators/dagster/lif-orchestrator/src/lif_orchestrator/defs/lif_job.py`) logs learner records at INFO, and Dagster stores a second copy of every `context.log` message in its event log. The query-plan part with `person_id`, the adapter's raw record, the translation's input and output, the fragments, the final job results, and the response body on a failed translation or callback were all logged. Measured on `main`: all 12 sites in the issue, plus `:121`, put learner values into the stored event log. **Solution.** Each line now logs metadata only, following #1352: adapter and source ids, schema ids, fragment paths with item counts, a dict's key count or a list's length, the HTTP status, and an exception's type name. | Line on `main` | Now logs | |---|---| | `:95` part | adapter id + source id | | `:116` adapter data | `a dict with N keys` / `a list of N items` | | `:121` adapter failure *(not in the issue)* | ids + exception type name, no `exc_info` | | `:142` translation input | source/target schema ids + shape | | `:153`, `:262` failed response | status code only | | `:158` translation response | shape | | `:163` person.all fragment | removed (it repeated `:158`) | | `:170` requested fragments | fragment paths | | `:192` translation result | fragment paths + item counts | | `:198` translation failure | exception type name, no `exc_info` | | `:233` multiple results | adapter id + source id | | `:253` final job results | per part: ids, fragment paths + counts, `error` | **The mapping key no longer carries the learner identifier** (`generate_mapping_key`, not in the issue's list). Dagster puts the mapping key in every step key, which it logs and shows in its UI, so `person_id.identifier` reached every step event. It now uses the part's position in the plan. This also fixes a bug: Dagster accepts only `[A-Za-z0-9_]` in mapping keys, so on `main` **a learner identifier with a dash or a dot (for example `A123.4`) failed the whole job** with `DagsterInvalidDefinitionError`, and that error message contained the identifier. Measured on `main`. **Not changed here.** - **Exceptions an op raises are still stored by Dagster.** When `run_lif_adapter` or `run_translation` re-raises for a retry, or `send_results_to_query_planner` fails, Dagster records the exception's message and traceback in its own `STEP_UP_FOR_RETRY` / `STEP_FAILURE` / `PIPELINE_FAILURE` events. These aren't the job's log lines. The real `requests.HTTPError` message carries only the status and the URL (schema ids), but an adapter exception or a Pydantic `ValidationError` can carry learner values. Fixing that means re-raising sanitized exceptions, which changes what operators see on a failed run. Follow-up: #1407. - **Dropping `exc_info` isn't pinned by the test.** In the in-process harness, the traceback reaches neither the stored log entry nor the console, so the test can't tell whether it's there. It's dropped because the traceback ends with the same message. **Deploy.** `dagster_code_location.yml` watches `orchestrators/dagster/lif-orchestrator/**`, so merging rebuilds the dev code-location image. Demo picks it up on the next promotion. No shared brick under `components/` is touched. **How to test** ```bash uv run pytest test/orchestrators/ ``` ##### Related Issues Closes #1359 Refs #1319, #1351, #1352, #1341, #1407 ##### Type of Change - [x] Bug fix (non-breaking change which fixes an issue) ##### Project Area(s) Affected - [x] orchestrators/ - [x] test/ or e2e/ --- ##### Checklist - [x] commit message follows commit guidelines (see commitlint.config.mjs) - [x] tests are included (unit and/or integration tests) - [x] code passes linting checks (`uv run ruff check`) - [x] code passes formatting checks (`uv run ruff format`) - [x] code passes type checking (`uv run ty check`) - [x] pre-commit hooks have been run successfully ##### Testing - `test/orchestrators/dagster/lif_orchestrator/test_lif_job_log_redaction.py` runs the real job in-process (`execute_in_process`, ephemeral instance) with the adapter and HTTP calls stubbed, using sentinel learner values in the identifier, the adapter record, the translator response, the error bodies and the exception text. It checks every field of the job's own stored log entries, every step key, and the console output. Three runs cover success (two parts for one source, which also takes the "Multiple results" path), a failed translation plus a failed callback, and a failed adapter. Two more pin the mapping key. - **It lives under `test/` so CI runs it.** The orchestrator's own `tests/` don't run in CI (#1341). The test adds the orchestrator's `src` to `sys.path`; the root environment already has the Dagster version it pins (1.11.12). It also undoes the demo-adapter registration that importing `lif_job` performs, which otherwise broke the `demo_data_source_adapters` registry tests (measured, then fixed). - On `main`'s `lif_job.py` all 5 fail. I put each of the 14 old statements back one at a time, and each was caught. - Full suite with Postgres (pgtest container): 1183 passed, 0 skipped (10-19, on `main` `85b88f6` + this change). ##### Additional Notes - `cspell.json` gains `capfd` (the pytest fixture the new test uses). - Overlap with open PRs, all checked with a test merge and all clean: draft #1332 also edits `lif_job.py` (the results callback), and #1402, #1398 and #1384 also add words to `cspell.json`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dereck <dereck.haskins@gmail.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Benito Gonzalez <bgonzalez@unicon.net>
#1398 replaced cognito_auth with the single lif.auth brick (ADR 0007). The base now composes AuthMiddleware with cognito_strategy, and with no user pool it passes no strategies, so non-public paths still fail closed without contacting Cognito. The hand-rolled deny middleware is gone, and the project packages auth instead of cognito_auth. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
@bjagg I'm taking this out of draft and asking you to review the skeleton on its own. Nothing in it depends on the open #1190 questions, so it can land now, and the key endpoints follow in a second PR. Refreshed today (
What this PR is: the control-plane service and its own database, without the developer-key table or endpoints. The description has the full list. In short: a FastAPI base on Two questions are still open, and they decide what comes after this PR:
|
bjagg
left a comment
There was a problem hiding this comment.
Approving the skeleton. I read it against lif.auth and ran it merged with current main (61ec9b9 locally, no conflicts): the 7 tests pass.
What I checked:
- Fails closed. With no pool,
strategiesis empty, so every non-public path is a 401 anddecode_cognito_jwtis never reached; the test pins that.methodsunset means every method is checked. - Public surface is the shared defaults only:
/health,/health-check, and the/docsand/openapi.jsonprefixes. - Token checks come from
decode_cognito_jwt: RS256 against the pool's JWKS, issuer verified,token_usemust beidoraccess. - Packaging is only
control_plane_restapi,authandlogging, and the compose database has no host port.
Two things, neither blocking:
CONTROL_PLANE_AUTH__CLIENT_IDis optional. With a pool set and no client ID,decode_cognito_jwtskips theaud/client_idcheck, so a token from any app client in that pool gets through. That's harmless while there are no endpoints, but this service will issue developer keys, so I'd fail closed on a missing client ID the same way as a missing pool: in this PR, or at the latest in the key PR.cspell.jsonlistsasyncpgtwice after the merge, because main already has it, so this PR's addition can go.
The branch is behind main, so it needs an update before it can merge.
|
On the deploy workflow: please write |
…p a duplicate cspell word With a user pool set and no CONTROL_PLANE_AUTH__CLIENT_ID, decode_cognito_jwt skips the aud/client_id check, so a token from any app client in the pool would pass. The control plane now treats a missing client ID like a missing pool: no strategies, every non-public path 401. main already lists asyncpg in cspell.json, so this branch's copy goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Thanks, @bjagg. Both are in, and the branch is refreshed:
main is merged in ( Thanks for the deploy-workflow answer. I'll open |
…space (#1465) ##### Description of Change Records the #1190 Q1/Q2 decision as **ADR 0008** (`docs/design/adr/general/0008-control-plane-key-owner-and-workspace.md`), as promised in my 10-26 comment there. #1182's key table needs this before its first migration ships, and #1183's copy depends on it. @bjagg, these are your answers from #1190. Please check that the wording matches what you meant. **What it decides** (it extends ADR 0006 decision 3, which left the workspace identifier open): 1. **Local-login users can't issue developer keys** (Q1), so `OwnerSub` stays a bare Cognito `sub`, and #1183 copies existing values unchanged. 2. **The workspace is the tenant schema name, stored as an opaque string** (Q2). The control plane never parses the value or builds it from parts. The group-to-schema rule stays in `tenant_routing`. 3. **The request names the workspace explicitly**, because the control plane can't read MDR's signed `lif_workspace` cookie. 4. **Membership:** one of the caller's `cognito:groups` must satisfy `tenant_schema_for_group(group) == workspace`, the same rule as MDR's `find_workspace`. Otherwise the request gets a `403`. 5. **Issuing and listing are per workspace, and revoking is by owner**, so a user who has left a group can still revoke a key they issued there. A key that isn't the caller's is a `404`, as in MDR. The ADR also lists the alternatives: issuer-qualified owners (not chosen now), the Cognito group name (rejected), and a new workspace ID (deferred to the identity half of #1190). Its consequences include two that are worth a look: - Two group names that map to one schema both pass the membership check. That's an existing gap, and it grants no access MDR doesn't already grant. - Leaving a group doesn't revoke keys you've already issued. **How to review:** read the ADR against #1190 (my 10-07 comment and your 11-03 answer) and ADR 0006. The ADR is **Accepted**, because it records decisions you've already made. If you'd rather review it as Proposed first, say so and I'll change it. The code that implements it, the key table and the three endpoints, comes in a separate PR stacked on #1384. ##### Related Issues Refs #1190 Refs #1182 ##### Type of Change - [x] Documentation update ##### Project Area(s) Affected - [x] Documentation (docs/, READMEs, ARCHITECTURE.md, CLAUDE.md) --- ##### Checklist - [x] commit message follows commit guidelines (see commitlint.config.mjs) - [x] documentation is changed or added (in /docs directory): the ADR, plus its `docs/INDEX.md` entry - [x] pre-commit hooks have been run successfully ##### Testing Docs only. pre-commit passes on both files (cspell, ty, pytest). The code it cites was checked on `main` (`04faff7`): `_require_owner_sub` at `bases/lif/mdr_restapi/developer_api_key_endpoints.py:20-29` and `find_workspace` at `components/lif/mdr_services/workspace_service.py:119`. ##### Additional Notes No open PR adds a `general/0008`, so there's no number collision. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: dereck <dereck.haskins@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Benito Gonzalez <bgonzalez@unicon.net>
…d to a workspace (#1466) ##### Description of Change > **Update 11-04:** #1384 and #1465 (ADR 0008) are merged, and main is merged in here (`1948bef`), so the diff is just this PR's 13 files. CI is green, and against real PostgreSQL the brick, control-plane and MDR key tests pass (48 passed, 0 skipped). It implements **ADR 0008**. The second slice of #1182: the control plane's developer-key table and its three endpoints. **The key store (shared brick `developer_keys`, additive)** - New `workspace_store.py`: `WorkspaceDeveloperApiKey`, one table for every workspace's keys, with an explicit `Workspace` column and a **unique `KeyHash`** (ADR 0006 decision 3). It also has `create_` / `list_` / `revoke_workspace_developer_api_key`. Key generation and the DTOs are shared with the MDR functions. - **MDR is unchanged.** The new model is on its own SQLAlchemy registry, so it never shares `SQLModel.metadata` with MDR's `DeveloperApiKey`. Both map a table called `DeveloperApiKeys`, but in different databases. Adding a `Workspace` column to MDR's model instead would have broken every MDR key query (its tenant tables have no such column) or needed an MDR Flyway migration. A test pins the separation. - **Consumers of the brick:** `lif_mdr_api` (its workflow already watches `developer_keys/**`; it only gains new, unused code) and now `lif_control_plane_api`. **The migration** `projects/lif_control_plane_database/migrations/V1.0__developer_api_keys.sql`: the control plane's own migration set, not MDR's Flyway. Its column types follow MDR's V1.5, so #1183 can copy rows across, plus `Workspace`, a unique index on `KeyHash`, and an index on `(Workspace, OwnerSub)`. It's idempotent, and the tests apply it twice. **The endpoints** (`bases/lif/control_plane_restapi/api_key_endpoints.py`) | Endpoint | Who | Result | |---|---|---| | `POST /api-keys/?workspace=W` | a Cognito member of `W` | `201`, with the raw key shown once | | `GET /api-keys/?workspace=W` | a Cognito member of `W` | the caller's own keys in `W` | | `DELETE /api-keys/{id}` | the key's owner | `204`. Needs ownership only, so it works after leaving `W`. Someone else's key is a `404`. | - **Membership** (ADR 0008 decision 4): one of the caller's `cognito:groups` must satisfy `tenant_schema_for_group(group) == W`, the rule MDR's `find_workspace` applies. Otherwise the request gets a `403`, before the database is touched. `W` is compared whole and never built from a group. - **Owner** = the token's `sub` (decision 1). A caller that isn't a Cognito user gets a `400`. That can't happen today, since Cognito is the only strategy, but it guards the decision if another strategy is ever added. - The workspace goes in the query string on both `POST` and `GET`, so the request body stays MDR's `CreateDeveloperApiKeyDTO`. **Packaging:** the project adds `developer_keys` and `tenant_routing` to its bricks, and `sqlmodel~=0.0.27`. Its lock is pinned to `0.0.27`, the version the root env and MDR's image run; an unpinned lock picked `0.0.48`. **Draft #1464's `paths:` now covers both bricks** (`9590840` there). **Limitations / not in this PR:** - No dev deploy yet: that needs #1464 and the AWS half (the database, login and migration runner). - Keys still authenticate nothing until #1184. - Copying MDR's existing keys is #1183. - Removing a user from a group doesn't revoke their keys (ADR 0008, Consequences). **How to review:** read ADR 0008 first, then `workspace_store.py` against MDR's `core.py`, then the endpoints. The tests below show which paths are covered. ##### Related Issues Refs #1182 Refs #1190 ##### Type of Change - [x] New feature (non-breaking change which adds functionality) ##### Project Area(s) Affected - [x] bases/ - [x] components/ - [x] projects/ - [x] test/ or e2e/ - [x] Database schema (migrations): the control plane's own folder, not MDR's - [x] API endpoints - [x] Documentation (docs/, READMEs, ARCHITECTURE.md, CLAUDE.md) --- ##### Checklist - [x] commit message follows commit guidelines (see commitlint.config.mjs) - [x] tests are included (unit and/or integration tests) - [x] code passes linting checks (`uv run ruff check`) - [x] code passes formatting checks (`uv run ruff format`) - [x] code passes type checking (`uv run ty check`) - [x] pre-commit hooks have been run successfully - [x] API changes: base (Python code) documentation in `docs/` and project README updated (the base, brick, project and migrations READMEs) ##### Testing - [x] Automated tests added/updated - `test/components/lif/developer_keys/test_workspace_store.py`, against a throwaway PostgreSQL with the real migration applied twice: list scoped to workspace and owner, raw key not stored, `KeyHash` uniqueness enforced by the database, revoke-by-owner with 404s and an idempotent revoke, and the store kept off MDR's metadata. - `test/bases/lif/control_plane_restapi/test_api_key_endpoints.py`: a `403` for non-members and for a caller with no groups, before the database; `422` for a missing or empty workspace; a group name or a different spelling of the schema is no match; `401` without a token; the Cognito-only owner check, at each endpoint, with a stubbed non-Cognito strategy; and the full issue → list → revoke flow against PostgreSQL. - **Full suite against real PostgreSQL** (pgtest container, so the DB-backed tests run instead of skipping): **1757 passed, 1 skipped**. The skip is the snapshot-regeneration test, which needs `LIF_UPDATE_SCHEMA_SNAPSHOTS=1`. That run includes every MDR test, among them MDR's own key endpoints. - **Mutation probes**, in a scratch worktree: disabling the membership check fails 4 tests; disabling the Cognito-only check fails the 3 endpoint cases (`096d91e`, after bjagg's review), and so does any single endpoint reading `request.state.principal` directly instead of calling `_require_owner_sub`. Against PostgreSQL: dropping the unique `KeyHash` index fails 1 test; listing without the workspace filter fails 1; revoking without the owner check fails 2; and a non-idempotent `CREATE TABLE` errors 4 tests. - [x] Manual testing performed: on a fresh `lif-control-plane-database` in local compose, initdb ran `V1.0__developer_api_keys.sql`, which created the table, `ux_DeveloperApiKeys_KeyHash` (unique) and `ix_DeveloperApiKeys_Workspace_OwnerSub`. Re-applying it with `ON_ERROR_STOP=1` exited 0. Not done: an end-to-end call in compose, because local compose has no Cognito pool, so every key path is a `401`. The Postgres-backed endpoint test covers that flow with stubbed tokens. ##### Additional Notes - **Merge order:** none left: #1384 and #1465 are merged. #1464 (draft) is independent. This one Refs #1182, because the dev deploy is still to come. - **Shared brick:** `developer_keys` is packaged by `lif_mdr_api` too. The change there is additive, and MDR's tests pass on it (see above). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: dereck <dereck.haskins@gmail.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Description of Change
The first slice of #1182, as described in the claim comment there: the control-plane service and its own database, without the developer-key endpoints. The key table and endpoints wait on #1190 Q1/Q2 (the workspace column's value and whether
OwnerSubmust be issuer-qualified), so no migration in this PR bets on either answer.New service
bases/lif/control_plane_restapi/:create_app(engine, cognito_config)plus the module-levelapp./health-checkis public. It returns200when the control plane's database answersSELECT 1, and503otherwise.lif.auth'sAuthMiddlewarewithcognito_strategy, as the LDE composes it; ADR 0007), configured withCONTROL_PLANE_AUTH__*. It fails closed: if the user pool or the client ID isn't configured, the middleware gets no strategies, so every non-public path returns401. A missing client ID counts becausedecode_cognito_jwtwould otherwise skip theaud/client_idcheck and accept a token from any app client in the pool. The base never handscognito_strategyan empty pool, because it would then try to fetch JWKS for that pool on every request that carries a token.methodsis left unset, so every HTTP method is checked.CONTROL_PLANE__DATABASE_URLis required. Startup fails with a message naming it, following Config hygiene: unguarded int(os.getenv(...)) at module scope crash-loops services on a malformed value (6 on main, 3 more in flight) #1179's fail-fast decision. Config hygiene: unguarded int(os.getenv(...)) at module scope crash-loops services on a malformed value (6 on main, 3 more in flight) #1179 has no sharedenv_inthelper yet, so the parsing is local (see the claim comment).projects/lif_control_plane_api/(port 8014). Its boilerplate is copied from the LDE, with only the names, port and target changed. It packages onlycontrol_plane_restapi,authandlogging: nothing from the MDR domain, checked in the built image.sqlalchemy[asyncio]~=2.0.0uses the extra and the minor-range pin from Local compose: the MDR and Identity Mapper images built from Dockerfile2 crash at startup (SQLAlchemy 2.1 without greenlet) #1374, and the image resolves SQLAlchemy 2.0.54 with greenlet.pyjwt[crypto]is required bylif.auth.cognito(Issue #1034: LDE needs pyjwt[crypto] for Cognito RS256 (unblocks playground go-live) #1093).projects/lif_control_plane_database/migrations/. It has no migrations yet, only a README with the conventions (sortableV…__…sqlnames, idempotent like MDR's V1.2+).Local compose (
deployments/advisor-demo-docker/docker-compose.yml)lif-control-plane-database: its own Postgres container, with its own database and login (control_planeby default, overridable). The migrations folder is mounted as/docker-entrypoint-initdb.d, so there's no runner script. It's on a newlif-net-control-plane-dbnetwork, with no host port.lif-control-plane-api: built fromDockerfile2. It waits for the database to be healthy, and its healthcheck calls/health-check. Networks:lif-net-org1and the database network.Not in this PR (the AWS half, @bjagg's, per the claim): the dev/demo Aurora database and login,
cloudformation/*-lif-control-plane.params, the taskdef includes and theSTACKSentry. Also not here: the deploy workflow, which I asked about on #1182. Thecheck_workflow_pathsguard passes because there's no workflow for the new project yet. When the workflow is added, itspaths:needscomponents/lif/auth/**andcomponents/lif/logging/**. There's no CORS either, since nothing calls this from a browser yet. That comes with the cutover (#1185).One thing to look at for ECS:
/health-checkincludes the database. That's right for local compose, but if the ECS/ALB health check points at it, a database outage would cycle the tasks. A DB-free liveness path may be worth adding when the CloudFormation is written.Doc drift, not fixed here:
docs/operations/guides/adding-a-new-microservice.mduseslif.datatypes.core.HealthCheckResponse, which doesn't exist anywhere in the repo, andAuthMiddlewarefrommdr_auth, which an MDR-independent service can't use (since #1398 the shared one islif.auth).How to check it (compose now won't start any service until
SECRET_KEY,MDR__AUTH__JWT_SECRET_KEYandLIF_DEMO_USER_PASSWORDare set, in.envor the shell; the control plane uses none of them)Related Issues
Refs #1182, #1041
Type of Change
Project Area(s) Affected
Checklist
uv run ruff check)uv run ruff format)uv run ty check)Testing
Unit tests (
test/bases/lif/control_plane_restapi/test_core.py, 7 tests):200when the database answers, and503when it doesn't;401without a token, and a valid token gets past the middleware;401even with a token, health still works, and token verification is never attempted;require_envnames the variable when it's missing, empty or whitespace.The fail-closed test still bites after the port: handing the empty pool to
cognito_strategymakes it fail (checked by mutation). Full suite (after the main merge): 1399 passed, 178 skipped (the DB-backed MDR tests, which skip without a local Postgres; nothing here needs one).poly checkreports only the expected "Cannot locate jwt in lif_graphql_api" warning, the same as main (see thelif.authREADME).Manual, in local compose re-run 10-26 on the rebuilt image (FastAPI 0.143.0, Starlette 1.8.0, SQLAlchemy 2.0.54, greenlet 3.5.6, asyncpg 0.32.0, PyJWT 2.15.1):
healthy, and it packagesauth,control_plane_restapiandlogging(nocognito_auth);/health-checkreturns200,/docsreturns200, and requests without a pool return401withWWW-Authenticate: Bearer, with or without a token;503, and it recovers to200once the database is back;Note: the unit tests run on the root lock (FastAPI 0.115 / Starlette 0.46), and the image runs on the project lock. The manual run is what covers the newer versions.
🤖 Generated with Claude Code