Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mcp): move MCP OAuth broker state from Redis to Postgres (#9070)
Eric Hayesdc946069cedc
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 9f8b33905f..77307263c0 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -10135,6 +10135,7 @@"crates/ai_toolset","crates/bot_id","crates/cowlike",+ "crates/cursor_api_key","crates/fusionauth","crates/genai_telemetry","crates/macro_auth",diff --git a/.sqlx/query-005b2d9e2dc4f3b13ecd07d1bed862f79d43c45f3d439ee8b8f4dfa9462eeb47.json b/.sqlx/query-005b2d9e2dc4f3b13ecd07d1bed862f79d43c45f3d439ee8b8f4dfa9462eeb47.jsonnew file mode 100644index 0000000000..93c5a1ea24--- /dev/null+++ b/.sqlx/query-005b2d9e2dc4f3b13ecd07d1bed862f79d43c45f3d439ee8b8f4dfa9462eeb47.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_refresh_token_bindings\n (refresh_token_digest, client_id, grant_id, expires_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (refresh_token_digest)\n DO UPDATE SET\n client_id = EXCLUDED.client_id,\n grant_id = EXCLUDED.grant_id,\n expires_at = EXCLUDED.expires_at\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "005b2d9e2dc4f3b13ecd07d1bed862f79d43c45f3d439ee8b8f4dfa9462eeb47"+}diff --git a/.sqlx/query-096b28739f6352b832e668ae807edc0ec80a77368faadc42e5b13c2c8a5a19d8.json b/.sqlx/query-096b28739f6352b832e668ae807edc0ec80a77368faadc42e5b13c2c8a5a19d8.jsonnew file mode 100644index 0000000000..96869b6796--- /dev/null+++ b/.sqlx/query-096b28739f6352b832e668ae807edc0ec80a77368faadc42e5b13c2c8a5a19d8.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_revoked_grants WHERE expires_at <= now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "096b28739f6352b832e668ae807edc0ec80a77368faadc42e5b13c2c8a5a19d8"+}diff --git a/.sqlx/query-100353cb3992befe06389ed704026a867fd8d6d4c0759034adffd42dc31ca573.json b/.sqlx/query-100353cb3992befe06389ed704026a867fd8d6d4c0759034adffd42dc31ca573.jsonnew file mode 100644index 0000000000..1e6052dfcd--- /dev/null+++ b/.sqlx/query-100353cb3992befe06389ed704026a867fd8d6d4c0759034adffd42dc31ca573.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_refresh_token_bindings\n (refresh_token_digest, client_id, grant_id, expires_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (refresh_token_digest) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "100353cb3992befe06389ed704026a867fd8d6d4c0759034adffd42dc31ca573"+}diff --git a/.sqlx/query-24e19dc21131f0bedea8c252fa838974ac9adbec1124f2b7c85ea936216e2e8b.json b/.sqlx/query-24e19dc21131f0bedea8c252fa838974ac9adbec1124f2b7c85ea936216e2e8b.jsonnew file mode 100644index 0000000000..f2d383a2df--- /dev/null+++ b/.sqlx/query-24e19dc21131f0bedea8c252fa838974ac9adbec1124f2b7c85ea936216e2e8b.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_authorization_codes (\n code_digest, client_id, tokens_ciphertext, kms_key_id, encryption_version,\n code_challenge, redirect_uri, access_token_expires_at, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Bytea",+ "Text",+ "Int2",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "24e19dc21131f0bedea8c252fa838974ac9adbec1124f2b7c85ea936216e2e8b"+}diff --git a/.sqlx/query-345ad21282695615d5bfb3483b05fe061c3decf5afe0586c6b33ba272f85a91a.json b/.sqlx/query-345ad21282695615d5bfb3483b05fe061c3decf5afe0586c6b33ba272f85a91a.jsonnew file mode 100644index 0000000000..00b2fcb985--- /dev/null+++ b/.sqlx/query-345ad21282695615d5bfb3483b05fe061c3decf5afe0586c6b33ba272f85a91a.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_clients (client_id, client_name, redirect_uris, expires_at)\n VALUES ($1, $2, $3, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "TextArray",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "345ad21282695615d5bfb3483b05fe061c3decf5afe0586c6b33ba272f85a91a"+}diff --git a/.sqlx/query-38cb225ca6f02ff44e73dc59876421595ade6710896dc9c95585bf6fea6b3779.json b/.sqlx/query-38cb225ca6f02ff44e73dc59876421595ade6710896dc9c95585bf6fea6b3779.jsonnew file mode 100644index 0000000000..2f54de4412--- /dev/null+++ b/.sqlx/query-38cb225ca6f02ff44e73dc59876421595ade6710896dc9c95585bf6fea6b3779.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_pending_authorizations WHERE expires_at <= now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "38cb225ca6f02ff44e73dc59876421595ade6710896dc9c95585bf6fea6b3779"+}diff --git a/.sqlx/query-45eca6ecc7b5142bb8f798017fa37dda822dfd655caecd38f1f164c3f61b7079.json b/.sqlx/query-45eca6ecc7b5142bb8f798017fa37dda822dfd655caecd38f1f164c3f61b7079.jsonnew file mode 100644index 0000000000..91ac640536--- /dev/null+++ b/.sqlx/query-45eca6ecc7b5142bb8f798017fa37dda822dfd655caecd38f1f164c3f61b7079.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_refresh_token_bindings WHERE refresh_token_digest = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "45eca6ecc7b5142bb8f798017fa37dda822dfd655caecd38f1f164c3f61b7079"+}diff --git a/.sqlx/query-506aa1032be62f39d04bea231ce902a807867bcb77b8557cd7766cbe46c0e5ad.json b/.sqlx/query-506aa1032be62f39d04bea231ce902a807867bcb77b8557cd7766cbe46c0e5ad.jsonnew file mode 100644index 0000000000..44c48619b6--- /dev/null+++ b/.sqlx/query-506aa1032be62f39d04bea231ce902a807867bcb77b8557cd7766cbe46c0e5ad.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM mcp_oauth_revoked_grants\n WHERE grant_id = $1 AND expires_at > now()\n ) AS \"revoked!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "revoked!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "506aa1032be62f39d04bea231ce902a807867bcb77b8557cd7766cbe46c0e5ad"+}diff --git a/.sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.json b/.sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.jsonnew file mode 100644index 0000000000..da905238a2--- /dev/null+++ b/.sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_pending_authorizations\n (session_id, client_id, code_challenge, client_state, client_redirect_uri, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288"+}diff --git a/.sqlx/query-661b9107b84525ea70b913bea13f69346c2b3ed93b188b3ace5f0cbdcf3c35e4.json b/.sqlx/query-661b9107b84525ea70b913bea13f69346c2b3ed93b188b3ace5f0cbdcf3c35e4.jsonnew file mode 100644index 0000000000..e47df1c269--- /dev/null+++ b/.sqlx/query-661b9107b84525ea70b913bea13f69346c2b3ed93b188b3ace5f0cbdcf3c35e4.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE mcp_oauth_clients\n SET expires_at = $2\n WHERE client_id = $1 AND expires_at > now()\n RETURNING client_id, client_name, redirect_uris\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "client_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "client_name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "redirect_uris",+ "type_info": "TextArray"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "661b9107b84525ea70b913bea13f69346c2b3ed93b188b3ace5f0cbdcf3c35e4"+}diff --git a/.sqlx/query-78f8be1a72443124c407cac43b91e24bba24794154cc4c0609410364199f1a38.json b/.sqlx/query-78f8be1a72443124c407cac43b91e24bba24794154cc4c0609410364199f1a38.jsonnew file mode 100644index 0000000000..10ac2dc4dd--- /dev/null+++ b/.sqlx/query-78f8be1a72443124c407cac43b91e24bba24794154cc4c0609410364199f1a38.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM mcp_oauth_authorization_codes\n WHERE code_digest = $1\n RETURNING client_id, tokens_ciphertext, kms_key_id, encryption_version,\n code_challenge, redirect_uri, access_token_expires_at, expires_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "client_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "tokens_ciphertext",+ "type_info": "Bytea"+ },+ {+ "ordinal": 2,+ "name": "kms_key_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "encryption_version",+ "type_info": "Int2"+ },+ {+ "ordinal": 4,+ "name": "code_challenge",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "redirect_uri",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "access_token_expires_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "expires_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "78f8be1a72443124c407cac43b91e24bba24794154cc4c0609410364199f1a38"+}diff --git a/.sqlx/query-801de48fd4679fa4083ba8a319a512b67424d47abff0ce32a5a7b7be8fa6ae97.json b/.sqlx/query-801de48fd4679fa4083ba8a319a512b67424d47abff0ce32a5a7b7be8fa6ae97.jsonnew file mode 100644index 0000000000..1588b454d4--- /dev/null+++ b/.sqlx/query-801de48fd4679fa4083ba8a319a512b67424d47abff0ce32a5a7b7be8fa6ae97.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_clients WHERE expires_at <= now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "801de48fd4679fa4083ba8a319a512b67424d47abff0ce32a5a7b7be8fa6ae97"+}diff --git a/.sqlx/query-84dcc76fc48c10724dbb6e228c2f077a52a0fcc13fba01e58721b81a51bbadd9.json b/.sqlx/query-84dcc76fc48c10724dbb6e228c2f077a52a0fcc13fba01e58721b81a51bbadd9.jsonnew file mode 100644index 0000000000..0acd1ecf39--- /dev/null+++ b/.sqlx/query-84dcc76fc48c10724dbb6e228c2f077a52a0fcc13fba01e58721b81a51bbadd9.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT client_id, grant_id\n FROM mcp_oauth_refresh_token_bindings\n WHERE refresh_token_digest = $1 AND expires_at > now()\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "client_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "grant_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "84dcc76fc48c10724dbb6e228c2f077a52a0fcc13fba01e58721b81a51bbadd9"+}diff --git a/.sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.json b/.sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.jsonnew file mode 100644index 0000000000..efad69c6e5--- /dev/null+++ b/.sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM mcp_oauth_pending_authorizations\n WHERE session_id = $1\n RETURNING client_id, code_challenge, client_state, client_redirect_uri, expires_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "client_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "code_challenge",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "client_state",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "client_redirect_uri",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "expires_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78"+}diff --git a/.sqlx/query-b8cc6194eabc83a3f00a71ae63457acddf6075a9b9987ec908ccde3cb652b321.json b/.sqlx/query-b8cc6194eabc83a3f00a71ae63457acddf6075a9b9987ec908ccde3cb652b321.jsonnew file mode 100644index 0000000000..cbbd8223d4--- /dev/null+++ b/.sqlx/query-b8cc6194eabc83a3f00a71ae63457acddf6075a9b9987ec908ccde3cb652b321.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_authorization_codes WHERE expires_at <= now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "b8cc6194eabc83a3f00a71ae63457acddf6075a9b9987ec908ccde3cb652b321"+}diff --git a/.sqlx/query-c2327a892c64d5f2def8a0733938e6babd15c4455d3f40002ea8786cf6388640.json b/.sqlx/query-c2327a892c64d5f2def8a0733938e6babd15c4455d3f40002ea8786cf6388640.jsonnew file mode 100644index 0000000000..79df8ea691--- /dev/null+++ b/.sqlx/query-c2327a892c64d5f2def8a0733938e6babd15c4455d3f40002ea8786cf6388640.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM mcp_oauth_refresh_token_bindings WHERE expires_at <= now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "c2327a892c64d5f2def8a0733938e6babd15c4455d3f40002ea8786cf6388640"+}diff --git a/.sqlx/query-e1799f5d7e076c199a0cbdd92f1516aca23e2fd10ad100825cf7c02ba0afaf5b.json b/.sqlx/query-e1799f5d7e076c199a0cbdd92f1516aca23e2fd10ad100825cf7c02ba0afaf5b.jsonnew file mode 100644index 0000000000..7b4d0b4583--- /dev/null+++ b/.sqlx/query-e1799f5d7e076c199a0cbdd92f1516aca23e2fd10ad100825cf7c02ba0afaf5b.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_clients (client_id, client_name, redirect_uris, expires_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (client_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "TextArray",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "e1799f5d7e076c199a0cbdd92f1516aca23e2fd10ad100825cf7c02ba0afaf5b"+}diff --git a/.sqlx/query-ee8909b218259300b169b35afc1ad6667b2efe911688f1a5dd7285a98eb3afb1.json b/.sqlx/query-ee8909b218259300b169b35afc1ad6667b2efe911688f1a5dd7285a98eb3afb1.jsonnew file mode 100644index 0000000000..5e5ec4e68b--- /dev/null+++ b/.sqlx/query-ee8909b218259300b169b35afc1ad6667b2efe911688f1a5dd7285a98eb3afb1.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_revoked_grants (grant_id, expires_at)\n VALUES ($1, $2)\n ON CONFLICT (grant_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "ee8909b218259300b169b35afc1ad6667b2efe911688f1a5dd7285a98eb3afb1"+}diff --git a/.sqlx/query-f1e4fcef9f1bed9e17f18d6e790121655663be6757debbdc25e57c1de0bf6cbb.json b/.sqlx/query-f1e4fcef9f1bed9e17f18d6e790121655663be6757debbdc25e57c1de0bf6cbb.jsonnew file mode 100644index 0000000000..975880c1d5--- /dev/null+++ b/.sqlx/query-f1e4fcef9f1bed9e17f18d6e790121655663be6757debbdc25e57c1de0bf6cbb.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO mcp_oauth_revoked_grants (grant_id, expires_at)\n VALUES ($1, $2)\n ON CONFLICT (grant_id) DO UPDATE SET expires_at = EXCLUDED.expires_at\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "f1e4fcef9f1bed9e17f18d6e790121655663be6757debbdc25e57c1de0bf6cbb"+}diff --git a/Cargo.lock b/Cargo.lockindex ea4348b189..86dddb6560 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12610,16 +12610,21 @@ version = "0.1.0"dependencies = ["ai_toolset","anyhow",+ "async-trait","axum","base64 0.22.1","bot_id",+ "chrono",+ "cursor_api_key","fusionauth","macro_auth",+ "macro_db_migrator","macro_user_id","redis","serde","serde_json","sha2 0.10.9",+ "sqlx","thiserror 2.0.18","tokio","tower 0.5.3",@@ -12629,6 +12634,7 @@ dependencies = ["urlencoding","uuid","workspace-hack",+ "zeroize",][[package]]diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.mdindex 4b1807a9c4..a84aeb01fc 100644--- a/crates/macro_db_client/AGENTS.md+++ b/crates/macro_db_client/AGENTS.md@@ -113,3 +113,8 @@ draft generation so Undo/resend cannot inherit an old deletion.The import ledger accepts Jira Cloud sources with `jira_issue`, `jira_project`and `jira_epic` kinds. Jira has its own concurrent partial team-claim index; sourceand kind constraints expand without rewriting existing rows and validate separately.++`mcp_oauth_*` tables hold the public MCP OAuth broker's state (registrations,+refresh token bindings, pending authorizations, issued codes); their queries and+expiry sweep belong to `mcp_auth_proxy`. Rows carry `expires_at` and have no+foreign keys; the broker deletes expired rows.diff --git a/crates/macro_db_client/migrations/20261028210002_mcp_oauth_postgres_storage.sql b/crates/macro_db_client/migrations/20261028210002_mcp_oauth_postgres_storage.sqlnew file mode 100644index 0000000000..bff2e74f59--- /dev/null+++ b/crates/macro_db_client/migrations/20261028210002_mcp_oauth_postgres_storage.sql@@ -0,0 +1,73 @@+-- OAuth broker state for the public MCP server (`mcp_auth_proxy`), moved out+-- of the shared Redis cache. Every row carries its own expiry; reads ignore+-- expired rows and the broker's cleanup task deletes them.++-- Clients created through dynamic client registration. `expires_at` slides+-- forward each time the registration is used.+CREATE TABLE mcp_oauth_clients (+ client_id text PRIMARY KEY,+ client_name text NOT NULL,+ redirect_uris text[] NOT NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ expires_at timestamptz NOT NULL+);++CREATE INDEX mcp_oauth_clients_expires_at_idx ON mcp_oauth_clients (expires_at);++-- Which client and grant each outstanding refresh token was issued to, keyed+-- by the SHA-256 digest of the token so no usable credential is stored. Every+-- token rotated out of one authorization code shares a `grant_id`. Not a+-- foreign key: a binding outlives neither its token nor the check it feeds,+-- and expires on its own schedule.+CREATE TABLE mcp_oauth_refresh_token_bindings (+ refresh_token_digest text PRIMARY KEY,+ client_id text NOT NULL,+ grant_id text NOT NULL,+ expires_at timestamptz NOT NULL+);++CREATE INDEX mcp_oauth_refresh_token_bindings_expires_at_idx+ ON mcp_oauth_refresh_token_bindings (expires_at);++-- Grants revoked through `/revoke`. A refresh token whose binding names one is+-- refused, so a revocation that raced a refresh still covers the token that+-- refresh rotated to. Kept at least as long as any binding in the family.+CREATE TABLE mcp_oauth_revoked_grants (+ grant_id text PRIMARY KEY,+ expires_at timestamptz NOT NULL+);++CREATE INDEX mcp_oauth_revoked_grants_expires_at_idx+ ON mcp_oauth_revoked_grants (expires_at);++-- Authorization requests waiting for the upstream login, keyed by the broker+-- session id carried through the upstream `state`.+CREATE TABLE mcp_oauth_pending_authorizations (+ session_id text PRIMARY KEY,+ client_id text NOT NULL,+ code_challenge text NOT NULL,+ client_state text NOT NULL,+ client_redirect_uri text NOT NULL,+ expires_at timestamptz NOT NULL+);++CREATE INDEX mcp_oauth_pending_authorizations_expires_at_idx+ ON mcp_oauth_pending_authorizations (expires_at);++-- Authorization codes the broker issued, keyed by the SHA-256 digest of the+-- code. The upstream tokens the code redeems for are KMS-encrypted, with the+-- code digest and client in the encryption context.+CREATE TABLE mcp_oauth_authorization_codes (+ code_digest text PRIMARY KEY,+ client_id text NOT NULL,+ tokens_ciphertext bytea NOT NULL,+ kms_key_id text NOT NULL,+ encryption_version smallint NOT NULL,+ code_challenge text NOT NULL,+ redirect_uri text NOT NULL,+ access_token_expires_at timestamptz NOT NULL,+ expires_at timestamptz NOT NULL+);++CREATE INDEX mcp_oauth_authorization_codes_expires_at_idx+ ON mcp_oauth_authorization_codes (expires_at);diff --git a/infra/stacks/agent-harness-service/agent_harness_service.ts b/infra/stacks/agent-harness-service/agent_harness_service.tsindex 3d12574669..8ca82b381c 100644--- a/infra/stacks/agent-harness-service/agent_harness_service.ts+++ b/infra/stacks/agent-harness-service/agent_harness_service.ts@@ -1,6 +1,7 @@import * as aws from '@pulumi/aws';import * as awsx from '@pulumi/awsx';import * as pulumi from '@pulumi/pulumi';+import * as doppler from '@pulumiverse/doppler';import {DATADOG_API_KEY,DEFAULT_CONTINUE_BEFORE_STEADY_STATE,@@ -25,6 +26,9 @@ import {const gatewayLoadBalancer = getGatewayAlb();const BASE_NAME = pulumi.getProject();+/** Must match `ENCRYPTION_PURPOSE` in `mcp_auth_proxy::outbound::postgres`. */+const MCP_OAUTH_KMS_PURPOSE = 'mcp-oauth-authorization-code';+const MCP_OAUTH_KMS_ACTIONS = ['kms:Encrypt', 'kms:Decrypt'];const REPO_ROOT = '../../..';type Args = {@@ -225,6 +229,8 @@ export class AgentHarnessService extends pulumi.ComponentResource {{ parent: this, dependsOn: [this.role] });+ const mcpOauthKms = this.createMcpOauthKmsKey(tags);+const image = new EcrImage(`${BASE_NAME}-ecr-image-${stack}`,{@@ -491,6 +497,7 @@ export class AgentHarnessService extends pulumi.ComponentResource {// association.dependsOn: [...args.configurationSecrets,+ ...mcpOauthKms,gatewayTargetGroup.listener_rule,...publicHostRules,...sharedApiRules,@@ -502,6 +509,105 @@ export class AgentHarnessService extends pulumi.ComponentResource {this.setupServiceAlarms();}+ /**+ * The key the public MCP OAuth broker encrypts its authorization codes'+ * upstream tokens with, and the Doppler value naming it. Returns what the+ * ECS service must wait for, so no task starts unable to issue a code.+ */+ private createMcpOauthKmsKey(tags: { [key: string]: string }) {+ const accountRootArn = pulumi.interpolate`arn:aws:iam::${aws.getCallerIdentityOutput().accountId}:root`;+ const key = new aws.kms.Key(+ `${BASE_NAME}-mcp-oauth-key`,+ {+ description: `Public MCP OAuth authorization code encryption key for ${stack}`,+ deletionWindowInDays: 30,+ enableKeyRotation: true,+ policy: aws.iam.getPolicyDocumentOutput({+ statements: [+ {+ sid: 'AllowAccountKeyAdministration',+ effect: 'Allow',+ principals: [{ type: 'AWS', identifiers: [accountRootArn] }],+ actions: [+ 'kms:CancelKeyDeletion',+ 'kms:Create*',+ 'kms:Delete*',+ 'kms:Describe*',+ 'kms:Disable*',+ 'kms:Enable*',+ 'kms:Get*',+ 'kms:List*',+ 'kms:Put*',+ 'kms:Revoke*',+ 'kms:ScheduleKeyDeletion',+ 'kms:TagResource',+ 'kms:UntagResource',+ 'kms:Update*',+ ],+ resources: ['*'],+ },+ {+ sid: 'AllowMcpOauthCodeEncryption',+ effect: 'Allow',+ principals: [{ type: 'AWS', identifiers: [this.role.arn] }],+ actions: MCP_OAUTH_KMS_ACTIONS,+ resources: ['*'],+ conditions: [+ {+ test: 'StringEquals',+ variable: 'kms:EncryptionContext:macro:purpose',+ values: [MCP_OAUTH_KMS_PURPOSE],+ },+ ],+ },+ ],+ }).json,+ tags,+ },+ { parent: this, protect: stack === 'prod' }+ );+ const alias = new aws.kms.Alias(+ `${BASE_NAME}-mcp-oauth-key-alias`,+ { name: `alias/${BASE_NAME}-mcp-oauth-${stack}`, targetKeyId: key.keyId },+ { parent: this }+ );+ const rolePolicy = new aws.iam.RolePolicy(+ `${BASE_NAME}-mcp-oauth-kms-policy`,+ {+ role: this.role.id,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: MCP_OAUTH_KMS_ACTIONS,+ Resource: key.arn,+ Effect: 'Allow',+ Condition: {+ StringEquals: {+ 'kms:EncryptionContext:macro:purpose': MCP_OAUTH_KMS_PURPOSE,+ },+ },+ },+ ],+ },+ },+ { parent: this }+ );+ // MacroConfig reads only Doppler in ECS, so the key reaches the service+ // through it rather than the container environment.+ const dopplerKeyId = new doppler.Secret(+ `harness-MCP_OAUTH_KMS_KEY_ID-${stack}`,+ {+ project: 'agent-harness-service',+ config: stack === 'prod' ? 'prd' : 'dev',+ name: 'MCP_OAUTH_KMS_KEY_ID',+ value: alias.name,+ },+ { parent: this }+ );+ return [rolePolicy, dopplerKeyId];+ }+private initializeSecurityGroups({vpcId,}: {diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 301bbbe458..c3b9b3fa3c 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -41,6 +41,9 @@ macro_env_var::env_vars!(/// custom MCP servers a person added in Macro are the ones the egress/// proxy can refresh and stamp for their sandboxes.pub struct McpCredentialsKeySecretName;+ /// Dedicated KMS key the public MCP OAuth broker encrypts the upstream+ /// tokens behind its authorization codes with.+ pub struct McpOauthKmsKeyId;);macro_env_var::maybe_env_vars!(@@ -141,6 +144,8 @@ pub struct Config {pub database_url: DatabaseUrl,/// Shared Redis used for cross-replica command forwarding.pub redis_uri: RedisUri,+ /// KMS key for the public MCP OAuth broker's authorization codes.+ pub mcp_oauth_kms_key_id: McpOauthKmsKeyId,/// Base URL of the Daytona REST API.#[macro_config_default(String::from("https://app.daytona.io/api"))]pub daytona_api_url: String,diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 156b1538da..fe23fc1069 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -678,6 +678,7 @@ async fn run() -> anyhow::Result<()> {&secrets,tool_context.clone(),pool.clone(),+ aws_sdk_kms::Client::new(&aws_config),macro_auth::middleware::decode_jwt::JwtValidationArgs::new_with_secret_manager(config.environment,&secrets,diff --git a/services/agent_harness_service/src/public_mcp.rs b/services/agent_harness_service/src/public_mcp.rsindex 7a5821a34b..ca9c88d864 100644--- a/services/agent_harness_service/src/public_mcp.rs+++ b/services/agent_harness_service/src/public_mcp.rs@@ -11,6 +11,7 @@ use crate::config::Config;use analytics::McpAnalytics;use analytics_client::{AnalyticsClient, AnalyticsClientConfig, PostHogConfig};use anyhow::Context;+use cursor_api_key::cipher::AwsKmsCiphertexts;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use mcp_auth_proxy::{domain::{@@ -19,7 +20,9 @@ use mcp_auth_proxy::{},outbound::{fusionauth::FusionAuthOAuthProvider,+ postgres::PostgresAuthStore,redis::{RedisClientRegistry, RedisInflightAuth},+ redis_cutover::{RedisCutoverAuthStore, backfill_from_redis},},};use rmcp::transport::streamable_http_server::{@@ -54,13 +57,15 @@ pub async fn router(secrets: &secretsmanager_client::SecretsManager,tool_context: ai_tools::ToolServiceContext,db: sqlx::PgPool,+ kms: aws_sdk_kms::Client,jwt_args: JwtValidationArgs,background_tasks: tokio_util::task::TaskTracker,cancellation: tokio_util::sync::CancellationToken,code_mode: Option<PublicCodeMode>,) -> anyhow::Result<axum::Router> {let public_url = macro_service_urls::McpPublicUrl::new()?;- let auth_proxy = build_auth_proxy(config, secrets, &public_url).await?;+ let (auth_proxy, backfill) =+ build_auth_proxy(config, secrets, &public_url, db.clone(), kms).await?;let analytics = build_analytics(config, db);let item_base_url = macro_service_urls::AppServiceUrl::new()?.to_string();let static_file_base_url =@@ -110,6 +115,7 @@ pub async fn router(},);+ background_tasks.spawn(backfill);let cleanup_state = auth_proxy.clone();background_tasks.spawn(async move {let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));@@ -137,11 +143,18 @@ pub async fn router()}+/// The broker, and the one-off copy of its Redis state into Postgres to run+/// in the background.async fn build_auth_proxy(config: &Config,secretsmanager_client: &secretsmanager_client::SecretsManager,public_url: ¯o_service_urls::McpPublicUrl,-) -> anyhow::Result<McpAuthProxyServiceImpl<RedisInflightAuth>> {+ db: sqlx::PgPool,+ kms: aws_sdk_kms::Client,+) -> anyhow::Result<(+ McpAuthProxyServiceImpl<RedisCutoverAuthStore>,+ impl Future<Output = ()> + Send + 'static,+)> {let mcp_public_url = public_url.to_string();let mcp_oauth_redirect_uri = format!("{mcp_public_url}/oauth/callback");@@ -187,7 +200,26 @@ async fn build_auth_proxy(.context("failed to initialize MCP auth provider")?;let redis_client = redis::Client::open(config.redis_uri.as_ref().to_owned()).context("failed to initialize redis client for MCP auth proxy")?;- let client_registry = Arc::new(RedisClientRegistry::new(redis_client.clone()));+ let legacy_clients = Arc::new(RedisClientRegistry::new(redis_client.clone()));+ let postgres = PostgresAuthStore::new(+ db,+ Arc::new(AwsKmsCiphertexts::new(+ kms,+ config.mcp_oauth_kms_key_id.as_ref().to_owned(),+ )),+ );+ let store = Arc::new(RedisCutoverAuthStore::new(+ postgres.clone(),+ legacy_clients.clone(),+ Arc::new(RedisInflightAuth::new(redis_client)),+ ));+ let backfill = async move {+ // Failure leaves the lazy fallback to copy entries as they are used;+ // the next deploy retries the rest.+ if let Err(error) = backfill_from_redis(&legacy_clients, &postgres).await {+ tracing::error!(error = ?error, "MCP OAuth backfill from Redis failed");+ }+ };let redirect_uri_policy = build_redirect_uri_policy(config);tracing::info!(@@ -195,14 +227,15 @@ async fn build_auth_proxy("initialized MCP OAuth redirect URI policy");- Ok(McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {+ let auth_proxy = McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {public_url: mcp_public_url,redirect_uri_policy,- inflight_auth: Arc::new(RedisInflightAuth::new(redis_client)),- client_registrations: client_registry.clone(),- refresh_token_bindings: client_registry,+ inflight_auth: store.clone(),+ client_registrations: store.clone(),+ refresh_token_bindings: store,oauth_provider: Arc::new(auth_provider),- }))+ });+ Ok((auth_proxy, backfill))}/// PostHog MCP analytics when `POSTHOG_API_KEY` is set; otherwise disabled.diff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.mdindex f862e86a22..3aa79fd959 100644--- a/services/mcp_auth_proxy/AGENTS.md+++ b/services/mcp_auth_proxy/AGENTS.md@@ -19,8 +19,16 @@ in front of FusionAuth, which doesn't support DCR itself.- `src/domain/ports.rs`: `ClientRegistrationStore`, `OAuthProvider`,`RefreshTokenBindingStore` — the ports the service depends on.- `src/inbound/axum_router.rs`: HTTP routes; `src/inbound/middleware.rs`: auth.-- `src/outbound/fusionauth.rs`, `src/outbound/redis.rs`: concrete adapters- (gated behind the `outbound` feature; `inbound`/`outbound` are each optional).+- `src/outbound/postgres.rs`: the store of record for all broker state+ (registrations, refresh token bindings, pending authorizations, issued+ codes). Issued codes are stored by digest with their upstream tokens+ KMS-encrypted under `MCP_OAUTH_KMS_KEY_ID`.+- `src/outbound/redis_cutover.rs`: wraps the Postgres store during the move+ off Redis: Postgres first, Redis fallback with copy-forward, registrations+ and bindings mirrored to Redis, plus the startup backfill.+- `src/outbound/fusionauth.rs`, `src/outbound/redis.rs`: the upstream provider+ and the legacy Redis store (all adapters gated behind the `outbound`+ feature; `inbound`/`outbound` are each optional).## Scope@@ -39,7 +47,8 @@ in front of FusionAuth, which doesn't support DCR itself.## Checks-- `cargo test -p mcp_auth_proxy` (`SQLX_OFFLINE` unset).+- `cargo test -p mcp_auth_proxy --all-features` (`SQLX_OFFLINE` unset; the+ Postgres adapter tests need a migrated local MacroDB).## Shared listener@@ -62,6 +71,13 @@ and other library consumers. Both retain OAuth metadata, CORS, and bearer auth.- A binding carries the grant id of its token family; rotation must copy itand refresh must check the revoked-grant marker, or `/revoke` stops coveringrotated tokens. Bindings stored as a bare client id are their own family.+- Redis is legacy. Write new state to Postgres only; the cutover module's+ Redis mirroring exists solely for replicas on the previous build. Remove it+ only after a deploy that started once no replica ran the Redis-only build+ has logged `backfilled MCP OAuth state from legacy Redis` in each+ environment (an earlier backfill can miss entries those replicas wrote+ late); then wire `PostgresAuthStore` directly and delete `redis.rs` and+ `redis_cutover.rs`.## Relateddiff --git a/services/mcp_auth_proxy/Cargo.toml b/services/mcp_auth_proxy/Cargo.tomlindex 79dbf278b8..41516d66d3 100644--- a/services/mcp_auth_proxy/Cargo.toml+++ b/services/mcp_auth_proxy/Cargo.toml@@ -16,7 +16,13 @@ inbound = ["dep:tower","dep:tower-http",]-outbound = ["dep:fusionauth"]+outbound = [+ "dep:chrono",+ "dep:cursor_api_key",+ "dep:fusionauth",+ "dep:sqlx",+ "dep:zeroize",+][dependencies]anyhow = { workspace = true }@@ -24,6 +30,8 @@ ai_toolset = { path = "../../crates/ai_toolset", optional = true }axum = { workspace = true, features = ["tower-log"], optional = true }base64 = { workspace = true }bot_id = { path = "../../crates/bot_id", optional = true }+chrono = { workspace = true, optional = true }+cursor_api_key = { path = "../../crates/cursor_api_key", optional = true }fusionauth = { path = "../../crates/fusionauth", optional = true }macro_auth = { path = "../../crates/macro_auth", optional = true }macro_user_id = { path = "../../crates/macro_user_id", optional = true }@@ -31,6 +39,7 @@ redis = { workspace = true, features = ["aio", "tokio-comp"] }serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }+sqlx = { workspace = true, optional = true }thiserror = { workspace = true }tower = { workspace = true, features = ["util"], optional = true }tower-http = { workspace = true, optional = true }@@ -39,7 +48,10 @@ url = { workspace = true }urlencoding = { workspace = true }uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }+zeroize = { workspace = true, optional = true }[dev-dependencies]+async-trait = { workspace = true }macro_auth = { path = "../../crates/macro_auth", features = ["testing"] }-tokio = { workspace = true }+macro_db_migrator = { path = "../../crates/macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/services/mcp_auth_proxy/src/outbound.rs b/services/mcp_auth_proxy/src/outbound.rsindex 5be5d37057..1bdbe7b7e6 100644--- a/services/mcp_auth_proxy/src/outbound.rs+++ b/services/mcp_auth_proxy/src/outbound.rs@@ -2,5 +2,9 @@/// FusionAuth-backed upstream OAuth provider.pub mod fusionauth;-/// Redis-backed in-flight OAuth state store.+/// Postgres-backed store for all broker state.+pub mod postgres;+/// Redis-backed store the broker used before Postgres; read during the cutover.pub mod redis;+/// Postgres store of record that falls back to Redis during the cutover.+pub mod redis_cutover;diff --git a/services/mcp_auth_proxy/src/outbound/postgres.rs b/services/mcp_auth_proxy/src/outbound/postgres.rsnew file mode 100644index 0000000000..dbfcb47670--- /dev/null+++ b/services/mcp_auth_proxy/src/outbound/postgres.rs@@ -0,0 +1,510 @@+//! Postgres-backed storage for every piece of broker state.+//!+//! Each row carries its own `expires_at`. Reads ignore expired rows, so a row+//! is dead the moment it expires even if [`InflightAuthStore::cleanup_expired`]+//! has not swept it yet.+//!+//! The upstream tokens behind an issued authorization code are the only+//! credentials stored here. They are KMS-encrypted with the code's digest and+//! client in the encryption context, so a row copied under another code or+//! client does not decrypt. Codes themselves are stored as digests, like refresh+//! tokens, so reading the table yields nothing redeemable.++#[cfg(test)]+mod test;++use std::{+ collections::HashMap,+ sync::Arc,+ time::{Duration, SystemTime},+};++use anyhow::Context;+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use chrono::{DateTime, Utc};+use cursor_api_key::cipher::KmsCiphertexts;+use sha2::{Digest, Sha256};+use sqlx::PgPool;+use zeroize::Zeroizing;++use crate::domain::{+ models::{+ AccessToken, IssuedAuthorizationCode, PendingAuthorization, RefreshToken,+ RefreshTokenBinding, RegisteredClient,+ },+ ports::{+ ClientRegistrationStore, GrantRevokedFuture, RefreshTokenBindingFuture,+ RefreshTokenBindingStore, RegisteredClientFuture, StoreWriteFuture,+ },+ service::{+ AUTHORIZATION_CODE_TTL, CLIENT_REGISTRATION_TTL, InflightAuthStore, PENDING_AUTH_TTL,+ REFRESH_TOKEN_BINDING_TTL, REVOKED_GRANT_TTL,+ },+};++/// The scheme `tokens_ciphertext` is written with.+const ENCRYPTION_VERSION: i16 = 1;++/// Names the purpose in the encryption context, so no other feature's+/// ciphertext decrypts as an authorization code's tokens.+const ENCRYPTION_PURPOSE: &str = "mcp-oauth-authorization-code";++/// KMS refuses direct encryption of more than this many bytes.+const KMS_MAX_PLAINTEXT_BYTES: usize = 4096;++/// Postgres store for client registrations, refresh token bindings, and+/// in-flight handshake state.+#[derive(Clone)]+pub struct PostgresAuthStore {+ pool: PgPool,+ kms: Arc<dyn KmsCiphertexts>,+}++impl PostgresAuthStore {+ /// Creates a store over `pool`, encrypting issued code tokens with `kms`.+ pub fn new(pool: PgPool, kms: Arc<dyn KmsCiphertexts>) -> Self {+ Self { pool, kms }+ }++ /// Copies a registration from another store, keeping the time it had left.+ /// An existing row wins, so a copy can never overwrite newer state.+ pub async fn import_client(+ &self,+ client: &RegisteredClient,+ remaining: Duration,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_clients (client_id, client_name, redirect_uris, expires_at)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (client_id) DO NOTHING+ "#,+ client.client_id,+ client.client_name,+ &client.redirect_uris,+ expires_at(remaining)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to import client registration")?;+ Ok(())+ }++ /// Copies a refresh token binding from another store, keeping the time it+ /// had left. An existing row wins, so a copy can never overwrite newer+ /// state.+ pub async fn import_binding(+ &self,+ refresh_token_digest: &str,+ binding: &RefreshTokenBinding,+ remaining: Duration,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_refresh_token_bindings+ (refresh_token_digest, client_id, grant_id, expires_at)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (refresh_token_digest) DO NOTHING+ "#,+ refresh_token_digest,+ binding.client_id,+ binding.grant_id,+ expires_at(remaining)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to import refresh token binding")?;+ Ok(())+ }++ /// Copies a grant revocation from another store, keeping the time it had+ /// left. An existing row wins, so a copy can never shorten a revocation.+ pub async fn import_revoked_grant(+ &self,+ grant_id: &str,+ remaining: Duration,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_revoked_grants (grant_id, expires_at)+ VALUES ($1, $2)+ ON CONFLICT (grant_id) DO NOTHING+ "#,+ grant_id,+ expires_at(remaining)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to import grant revocation")?;+ Ok(())+ }+}++fn expires_at(remaining: Duration) -> anyhow::Result<DateTime<Utc>> {+ Ok(Utc::now() + chrono::Duration::from_std(remaining).context("expiry out of range")?)+}++fn code_digest(code: &str) -> String {+ URL_SAFE_NO_PAD.encode(Sha256::digest(code.as_bytes()))+}++fn encryption_context(code_digest: &str, client_id: &str) -> HashMap<String, String> {+ HashMap::from([+ ("macro:purpose".to_owned(), ENCRYPTION_PURPOSE.to_owned()),+ (+ "macro:encryption-version".to_owned(),+ ENCRYPTION_VERSION.to_string(),+ ),+ ("macro:code-digest".to_owned(), code_digest.to_owned()),+ ("macro:client-id".to_owned(), client_id.to_owned()),+ ])+}++#[derive(serde::Serialize, serde::Deserialize)]+struct CodeTokens {+ access_token: AccessToken,+ refresh_token: RefreshToken,+}++impl ClientRegistrationStore for PostgresAuthStore {+ fn insert_client<'a>(&'a self, client: &'a RegisteredClient) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_clients (client_id, client_name, redirect_uris, expires_at)+ VALUES ($1, $2, $3, $4)+ "#,+ client.client_id,+ client.client_name,+ &client.redirect_uris,+ expires_at(CLIENT_REGISTRATION_TTL)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist client registration")?;+ Ok(())+ })+ }++ fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a> {+ Box::pin(async move {+ // Reading re-arms the expiry in the same statement, so a+ // registration lapses only after going unused for the whole window.+ let row = sqlx::query!(+ r#"+ UPDATE mcp_oauth_clients+ SET expires_at = $2+ WHERE client_id = $1 AND expires_at > now()+ RETURNING client_id, client_name, redirect_uris+ "#,+ client_id,+ expires_at(CLIENT_REGISTRATION_TTL)?,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch client registration")?;+ Ok(row.map(|row| RegisteredClient {+ client_id: row.client_id,+ client_name: row.client_name,+ redirect_uris: row.redirect_uris,+ }))+ })+ }+}++impl RefreshTokenBindingStore for PostgresAuthStore {+ fn bind<'a>(+ &'a self,+ refresh_token_digest: &'a str,+ binding: &'a RefreshTokenBinding,+ ) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_refresh_token_bindings+ (refresh_token_digest, client_id, grant_id, expires_at)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (refresh_token_digest)+ DO UPDATE SET+ client_id = EXCLUDED.client_id,+ grant_id = EXCLUDED.grant_id,+ expires_at = EXCLUDED.expires_at+ "#,+ refresh_token_digest,+ binding.client_id,+ binding.grant_id,+ expires_at(REFRESH_TOKEN_BINDING_TTL)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist refresh token binding")?;+ Ok(())+ })+ }++ fn binding<'a>(&'a self, refresh_token_digest: &'a str) -> RefreshTokenBindingFuture<'a> {+ Box::pin(async move {+ let row = sqlx::query!(+ r#"+ SELECT client_id, grant_id+ FROM mcp_oauth_refresh_token_bindings+ WHERE refresh_token_digest = $1 AND expires_at > now()+ "#,+ refresh_token_digest,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch refresh token binding")?;+ Ok(row.map(|row| RefreshTokenBinding {+ client_id: row.client_id,+ grant_id: row.grant_id,+ }))+ })+ }++ fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ sqlx::query!(+ "DELETE FROM mcp_oauth_refresh_token_bindings WHERE refresh_token_digest = $1",+ refresh_token_digest,+ )+ .execute(&self.pool)+ .await+ .context("failed to delete refresh token binding")?;+ Ok(())+ })+ }++ fn revoke_grant<'a>(&'a self, grant_id: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_revoked_grants (grant_id, expires_at)+ VALUES ($1, $2)+ ON CONFLICT (grant_id) DO UPDATE SET expires_at = EXCLUDED.expires_at+ "#,+ grant_id,+ expires_at(REVOKED_GRANT_TTL)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist grant revocation")?;+ Ok(())+ })+ }++ fn is_grant_revoked<'a>(&'a self, grant_id: &'a str) -> GrantRevokedFuture<'a> {+ Box::pin(async move {+ let revoked = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1 FROM mcp_oauth_revoked_grants+ WHERE grant_id = $1 AND expires_at > now()+ ) AS "revoked!"+ "#,+ grant_id,+ )+ .fetch_one(&self.pool)+ .await+ .context("failed to read grant revocation")?;+ Ok(revoked)+ })+ }+}++impl InflightAuthStore for PostgresAuthStore {+ async fn insert_pending(+ &self,+ session_id: &str,+ pending: PendingAuthorization,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_pending_authorizations+ (session_id, client_id, code_challenge, client_state, client_redirect_uri, expires_at)+ VALUES ($1, $2, $3, $4, $5, $6)+ "#,+ session_id,+ pending.client_id,+ pending.code_challenge,+ pending.client_state,+ pending.client_redirect_uri,+ expires_at(PENDING_AUTH_TTL)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist pending authorization")?;+ Ok(())+ }++ async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {+ // DELETE ... RETURNING consumes the row atomically, so a session+ // completes at most once even when callbacks race.+ let row = sqlx::query!(+ r#"+ DELETE FROM mcp_oauth_pending_authorizations+ WHERE session_id = $1+ RETURNING client_id, code_challenge, client_state, client_redirect_uri, expires_at+ "#,+ session_id,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch pending authorization")?;+ Ok(row+ .filter(|row| row.expires_at > Utc::now())+ .map(|row| PendingAuthorization {+ client_id: row.client_id,+ code_challenge: row.code_challenge,+ client_state: row.client_state,+ client_redirect_uri: row.client_redirect_uri,+ }))+ }++ #[tracing::instrument(+ name = "mcp_oauth.store_code",+ skip_all,+ err,+ fields(client_id = %issued.client_id)+ )]+ async fn insert_issued(+ &self,+ code: &str,+ issued: IssuedAuthorizationCode,+ ) -> anyhow::Result<()> {+ let digest = code_digest(code);+ let plaintext = Zeroizing::new(+ serde_json::to_vec(&CodeTokens {+ access_token: issued.access_token,+ refresh_token: issued.refresh_token,+ })+ .context("failed to serialize authorization code tokens")?,+ );+ anyhow::ensure!(+ plaintext.len() <= KMS_MAX_PLAINTEXT_BYTES,+ "authorization code tokens are {} bytes, over the {KMS_MAX_PLAINTEXT_BYTES} byte KMS limit",+ plaintext.len()+ );+ let (ciphertext, kms_key_id) = self+ .kms+ .encrypt(encryption_context(&digest, &issued.client_id), &plaintext)+ .await+ .context("failed to encrypt authorization code tokens")?;+ sqlx::query!(+ r#"+ INSERT INTO mcp_oauth_authorization_codes (+ code_digest, client_id, tokens_ciphertext, kms_key_id, encryption_version,+ code_challenge, redirect_uri, access_token_expires_at, expires_at+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ "#,+ digest,+ issued.client_id,+ ciphertext,+ kms_key_id,+ ENCRYPTION_VERSION,+ issued.code_challenge,+ issued.redirect_uri,+ DateTime::<Utc>::from(issued.access_token_expires_at),+ expires_at(AUTHORIZATION_CODE_TTL)?,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist issued authorization code")?;+ Ok(())+ }++ #[tracing::instrument(name = "mcp_oauth.redeem_code", skip_all, err)]+ async fn take_issued(&self, code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {+ let digest = code_digest(code);+ // Consumed before decrypting: a code is single use even if the decrypt+ // that follows fails.+ let row = sqlx::query!(+ r#"+ DELETE FROM mcp_oauth_authorization_codes+ WHERE code_digest = $1+ RETURNING client_id, tokens_ciphertext, kms_key_id, encryption_version,+ code_challenge, redirect_uri, access_token_expires_at, expires_at+ "#,+ digest,+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to fetch issued authorization code")?;+ let Some(row) = row.filter(|row| row.expires_at > Utc::now()) else {+ return Ok(None);+ };+ anyhow::ensure!(+ row.encryption_version == ENCRYPTION_VERSION,+ "unsupported authorization code encryption version {}",+ row.encryption_version+ );+ let plaintext = self+ .kms+ .decrypt(+ &row.kms_key_id,+ &row.tokens_ciphertext,+ encryption_context(&digest, &row.client_id),+ )+ .await+ .context("failed to decrypt authorization code tokens")?;+ let tokens: CodeTokens = serde_json::from_slice(&plaintext)+ .context("failed to deserialize authorization code tokens")?;+ Ok(Some(IssuedAuthorizationCode {+ client_id: row.client_id,+ access_token: tokens.access_token,+ refresh_token: tokens.refresh_token,+ code_challenge: row.code_challenge,+ redirect_uri: row.redirect_uri,+ access_token_expires_at: SystemTime::from(row.access_token_expires_at),+ }))+ }++ async fn cleanup_expired(&self) -> anyhow::Result<()> {+ let mut transaction = self.pool.begin().await.context("failed to begin cleanup")?;+ let clients = sqlx::query!("DELETE FROM mcp_oauth_clients WHERE expires_at <= now()")+ .execute(&mut *transaction)+ .await+ .context("failed to delete expired client registrations")?+ .rows_affected();+ let bindings =+ sqlx::query!("DELETE FROM mcp_oauth_refresh_token_bindings WHERE expires_at <= now()")+ .execute(&mut *transaction)+ .await+ .context("failed to delete expired refresh token bindings")?+ .rows_affected();+ let revoked_grants =+ sqlx::query!("DELETE FROM mcp_oauth_revoked_grants WHERE expires_at <= now()")+ .execute(&mut *transaction)+ .await+ .context("failed to delete expired grant revocations")?+ .rows_affected();+ let pending =+ sqlx::query!("DELETE FROM mcp_oauth_pending_authorizations WHERE expires_at <= now()")+ .execute(&mut *transaction)+ .await+ .context("failed to delete expired pending authorizations")?+ .rows_affected();+ let codes =+ sqlx::query!("DELETE FROM mcp_oauth_authorization_codes WHERE expires_at <= now()")+ .execute(&mut *transaction)+ .await+ .context("failed to delete expired authorization codes")?+ .rows_affected();+ transaction+ .commit()+ .await+ .context("failed to commit cleanup")?;+ if clients + bindings + revoked_grants + pending + codes > 0 {+ tracing::info!(+ clients,+ bindings,+ revoked_grants,+ pending,+ codes,+ "swept expired MCP OAuth state"+ );+ }+ Ok(())+ }+}diff --git a/services/mcp_auth_proxy/src/outbound/postgres/test.rs b/services/mcp_auth_proxy/src/outbound/postgres/test.rsnew file mode 100644index 0000000000..fb59156a76--- /dev/null+++ b/services/mcp_auth_proxy/src/outbound/postgres/test.rs@@ -0,0 +1,288 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;++use super::*;+use crate::test_support::FakeKms;++fn store(pool: PgPool) -> PostgresAuthStore {+ PostgresAuthStore::new(pool, Arc::new(FakeKms::default()))+}++fn registered_client(client_id: &str) -> RegisteredClient {+ RegisteredClient {+ client_id: client_id.to_owned(),+ client_name: "test-client".to_owned(),+ redirect_uris: vec!["http://127.0.0.1:51000/oauth/callback".to_owned()],+ }+}++fn binding(client_id: &str, grant_id: &str) -> RefreshTokenBinding {+ RefreshTokenBinding {+ client_id: client_id.to_owned(),+ grant_id: grant_id.to_owned(),+ }+}++fn issued_code(client_id: &str) -> IssuedAuthorizationCode {+ IssuedAuthorizationCode {+ client_id: client_id.to_owned(),+ access_token: AccessToken::from("upstream-access-token"),+ refresh_token: RefreshToken::from("upstream-refresh-token"),+ code_challenge: "challenge".to_owned(),+ redirect_uri: "http://127.0.0.1:51000/oauth/callback".to_owned(),+ access_token_expires_at: SystemTime::UNIX_EPOCH + Duration::from_secs(4_000_000_000),+ }+}++async fn client_expires_at(pool: &PgPool, client_id: &str) -> DateTime<Utc> {+ sqlx::query_scalar!(+ "SELECT expires_at FROM mcp_oauth_clients WHERE client_id = $1",+ client_id+ )+ .fetch_one(pool)+ .await+ .expect("registration row")+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_registration_is_found_until_it_expires(pool: PgPool) {+ let store = store(pool);+ store+ .insert_client(®istered_client("live"))+ .await+ .expect("insert");+ store+ .import_client(®istered_client("lapsed"), Duration::ZERO)+ .await+ .expect("import");++ let found = store+ .find_client("live")+ .await+ .expect("lookup")+ .expect("live client");+ assert_eq!(found.client_name, "test-client");+ assert_eq!(+ found.redirect_uris,+ ["http://127.0.0.1:51000/oauth/callback"]+ );+ assert!(store.find_client("lapsed").await.expect("lookup").is_none());+ assert!(+ store+ .find_client("unknown")+ .await+ .expect("lookup")+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn finding_a_registration_extends_it(pool: PgPool) {+ let store = store(pool.clone());+ store+ .import_client(®istered_client("client"), Duration::from_secs(60))+ .await+ .expect("import");+ let before = client_expires_at(&pool, "client").await;++ store+ .find_client("client")+ .await+ .expect("lookup")+ .expect("client");++ let after = client_expires_at(&pool, "client").await;+ assert!(+ after > before + chrono::Duration::days(89),+ "a used registration should get a fresh 90-day window"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_import_never_replaces_an_existing_row(pool: PgPool) {+ let store = store(pool);+ store+ .bind("digest", &binding("current-client", "current-grant"))+ .await+ .expect("bind");++ store+ .import_binding(+ "digest",+ &binding("stale-client", "stale-grant"),+ Duration::from_secs(60),+ )+ .await+ .expect("import");++ assert_eq!(+ store.binding("digest").await.expect("lookup"),+ Some(binding("current-client", "current-grant"))+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_binding_follows_bind_rebind_and_unbind(pool: PgPool) {+ let store = store(pool);+ store+ .bind("digest", &binding("client-a", "grant-a"))+ .await+ .expect("bind");+ store+ .bind("digest", &binding("client-b", "grant-b"))+ .await+ .expect("rebind");+ assert_eq!(+ store.binding("digest").await.expect("lookup"),+ Some(binding("client-b", "grant-b"))+ );++ store.unbind("digest").await.expect("unbind");+ assert!(store.binding("digest").await.expect("lookup").is_none());++ store+ .import_binding("lapsed", &binding("client-a", "grant-a"), Duration::ZERO)+ .await+ .expect("import");+ assert!(store.binding("lapsed").await.expect("lookup").is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_revoked_grant_stays_revoked_until_it_expires(pool: PgPool) {+ let store = store(pool);+ assert!(!store.is_grant_revoked("grant").await.expect("lookup"));++ store.revoke_grant("grant").await.expect("revoke");+ store.revoke_grant("grant").await.expect("revoke again");+ assert!(store.is_grant_revoked("grant").await.expect("lookup"));+ assert!(!store.is_grant_revoked("other").await.expect("lookup"));++ store+ .import_revoked_grant("lapsed", Duration::ZERO)+ .await+ .expect("import");+ assert!(!store.is_grant_revoked("lapsed").await.expect("lookup"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_pending_authorization_is_taken_once(pool: PgPool) {+ let store = store(pool);+ store+ .insert_pending(+ "session",+ PendingAuthorization {+ client_id: "client".to_owned(),+ code_challenge: "challenge".to_owned(),+ client_state: "state".to_owned(),+ client_redirect_uri: "http://127.0.0.1:51000/oauth/callback".to_owned(),+ },+ )+ .await+ .expect("insert");++ let pending = store+ .take_pending("session")+ .await+ .expect("take")+ .expect("pending");+ assert_eq!(pending.client_state, "state");+ assert!(store.take_pending("session").await.expect("take").is_none());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_issued_code_redeems_once_for_its_tokens(pool: PgPool) {+ let store = store(pool);+ store+ .insert_issued("broker-code", issued_code("client"))+ .await+ .expect("insert");++ let issued = store+ .take_issued("broker-code")+ .await+ .expect("take")+ .expect("issued code");+ assert_eq!(issued.client_id, "client");+ assert_eq!(issued.access_token.as_str(), "upstream-access-token");+ assert_eq!(issued.refresh_token.as_str(), "upstream-refresh-token");+ assert_eq!(issued.redirect_uri, "http://127.0.0.1:51000/oauth/callback");+ assert_eq!(+ issued.access_token_expires_at,+ SystemTime::UNIX_EPOCH + Duration::from_secs(4_000_000_000)+ );+ assert!(+ store+ .take_issued("broker-code")+ .await+ .expect("take")+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_issued_code_row_holds_neither_the_code_nor_the_tokens(pool: PgPool) {+ let store = store(pool.clone());+ store+ .insert_issued("broker-code", issued_code("client"))+ .await+ .expect("insert");++ let row =+ sqlx::query!("SELECT code_digest, tokens_ciphertext FROM mcp_oauth_authorization_codes")+ .fetch_one(&pool)+ .await+ .expect("row");+ assert_ne!(row.code_digest, "broker-code");+ let ciphertext = String::from_utf8_lossy(&row.tokens_ciphertext);+ assert!(!ciphertext.contains("upstream-access-token"));+ assert!(!ciphertext.contains("upstream-refresh-token"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn tokens_moved_to_another_client_do_not_decrypt(pool: PgPool) {+ let store = store(pool.clone());+ store+ .insert_issued("broker-code", issued_code("client"))+ .await+ .expect("insert");+ sqlx::query!("UPDATE mcp_oauth_authorization_codes SET client_id = 'attacker'")+ .execute(&pool)+ .await+ .expect("tamper");++ assert!(store.take_issued("broker-code").await.is_err());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn cleanup_deletes_only_expired_rows(pool: PgPool) {+ let store = store(pool.clone());+ store+ .insert_client(®istered_client("live"))+ .await+ .expect("insert");+ store+ .import_client(®istered_client("lapsed"), Duration::ZERO)+ .await+ .expect("import");+ store+ .bind("live", &binding("live", "live"))+ .await+ .expect("bind");+ store+ .import_binding("lapsed", &binding("lapsed", "lapsed"), Duration::ZERO)+ .await+ .expect("import");++ store.cleanup_expired().await.expect("cleanup");++ let clients = sqlx::query_scalar!("SELECT client_id FROM mcp_oauth_clients")+ .fetch_all(&pool)+ .await+ .expect("clients");+ let bindings =+ sqlx::query_scalar!("SELECT refresh_token_digest FROM mcp_oauth_refresh_token_bindings")+ .fetch_all(&pool)+ .await+ .expect("bindings");+ assert_eq!(clients, ["live"]);+ assert_eq!(bindings, ["live"]);+}diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rsindex 4326635ad9..40beaf7dfd 100644--- a/services/mcp_auth_proxy/src/outbound/redis.rs+++ b/services/mcp_auth_proxy/src/outbound/redis.rs@@ -75,6 +75,99 @@ impl RedisClientRegistry {fn revoked_grant_key(grant_id: &str) -> String {format!("{REVOKED_GRANT_KEY_PREFIX}{grant_id}")}++ /// Every live registration, with the time it has left.+ pub async fn export_clients(&self) -> anyhow::Result<Vec<(RegisteredClient, Duration)>> {+ let entries = self.export(CLIENT_KEY_PREFIX).await?;+ entries+ .into_iter()+ .map(|(_, json, remaining)| {+ let client = serde_json::from_str::<StoredRegisteredClient>(&json)+ .map(RegisteredClient::from)+ .context("failed to deserialize client registration")?;+ Ok((client, remaining))+ })+ .collect()+ }++ /// Every live refresh token binding as `(digest, binding, time left)`.+ pub async fn export_bindings(+ &self,+ ) -> anyhow::Result<Vec<(String, RefreshTokenBinding, Duration)>> {+ let entries = self.export(REFRESH_BINDING_KEY_PREFIX).await?;+ entries+ .into_iter()+ .map(|(digest, value, remaining)| {+ let binding = parse_refresh_token_binding(&digest, value)?;+ Ok((digest, binding, remaining))+ })+ .collect()+ }++ /// Every live grant revocation as `(grant_id, time left)`.+ pub async fn export_revoked_grants(&self) -> anyhow::Result<Vec<(String, Duration)>> {+ let entries = self.export(REVOKED_GRANT_KEY_PREFIX).await?;+ Ok(entries+ .into_iter()+ .map(|(grant_id, _, remaining)| (grant_id, remaining))+ .collect())+ }++ /// Reads every key under `prefix` as `(suffix, value, time left)`. Keys+ /// that expire mid-scan, or carry no TTL, are skipped.+ async fn export(&self, prefix: &str) -> anyhow::Result<Vec<(String, String, Duration)>> {+ let mut conn = self+ .client+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;+ let mut keys: Vec<String> = Vec::new();+ let mut cursor: u64 = 0;+ loop {+ let (next, batch): (u64, Vec<String>) = redis::cmd("SCAN")+ .arg(cursor)+ .arg("MATCH")+ .arg(format!("{prefix}*"))+ .arg("COUNT")+ .arg(EXPORT_SCAN_COUNT)+ .query_async(&mut conn)+ .await+ .with_context(|| format!("failed to scan keys under {prefix}"))?;+ keys.extend(batch);+ if next == 0 {+ break;+ }+ cursor = next;+ }+ // SCAN may return a key more than once.+ keys.sort_unstable();+ keys.dedup();++ let mut entries = Vec::with_capacity(keys.len());+ for chunk in keys.chunks(EXPORT_READ_BATCH) {+ let mut pipeline = redis::pipe();+ for key in chunk {+ pipeline.get(key).pttl(key);+ }+ let values: Vec<(Option<String>, i64)> = pipeline+ .query_async(&mut conn)+ .await+ .with_context(|| format!("failed to read keys under {prefix}"))?;+ for (key, (value, remaining_ms)) in chunk.iter().zip(values) {+ let (Some(value), Ok(remaining_ms)) = (value, u64::try_from(remaining_ms)) else {+ continue;+ };+ if let Some(suffix) = key.strip_prefix(prefix) {+ entries.push((+ suffix.to_owned(),+ value,+ Duration::from_millis(remaining_ms),+ ));+ }+ }+ }+ Ok(entries)+ }}#[derive(serde::Serialize, serde::Deserialize)]@@ -104,6 +197,12 @@ fn parse_refresh_token_binding(})}+/// Keys SCAN examines per call while exporting. The cache holds millions of+/// unrelated keys, so a larger page means far fewer round trips.+const EXPORT_SCAN_COUNT: usize = 10_000;+/// Keys read per pipelined round trip while exporting.+const EXPORT_READ_BATCH: usize = 500;+#[derive(serde::Serialize, serde::Deserialize)]struct StoredRegisteredClient {client_id: String,diff --git a/services/mcp_auth_proxy/src/outbound/redis/test.rs b/services/mcp_auth_proxy/src/outbound/redis/test.rsindex 4186ae0d3e..0bfb95bcdd 100644--- a/services/mcp_auth_proxy/src/outbound/redis/test.rs+++ b/services/mcp_auth_proxy/src/outbound/redis/test.rs@@ -264,3 +264,73 @@ async fn handshake_state_round_trips_with_its_client_id() {"an issued code must be single-use");}++#[tokio::test]+#[ignore = "requires a local Redis"]+async fn export_returns_live_registrations_bindings_and_revocations_with_their_ttl() {+ let registry = RedisClientRegistry::new(client());+ let client_id = unique("client");+ let digest = unique("digest");+ let legacy_digest = unique("legacy-digest");+ let grant_id = unique("grant");+ let binding = RefreshTokenBinding {+ client_id: client_id.clone(),+ grant_id: grant_id.clone(),+ };+ registry+ .insert_client(®istered_client(&client_id))+ .await+ .expect("insert should succeed");+ registry+ .bind(&digest, &binding)+ .await+ .expect("bind should succeed");+ registry+ .revoke_grant(&grant_id)+ .await+ .expect("revoke should succeed");+ // A binding written before grants were tracked holds the bare client id.+ let mut conn = client()+ .get_multiplexed_async_connection()+ .await+ .expect("connect");+ conn.set_ex::<String, &str, ()>(+ RedisClientRegistry::refresh_binding_key(&legacy_digest),+ &client_id,+ 60,+ )+ .await+ .expect("legacy bind should succeed");++ let clients = registry.export_clients().await.expect("export clients");+ let (exported, remaining) = clients+ .iter()+ .find(|(exported, _)| exported.client_id == client_id)+ .expect("the registration should be exported");+ assert_eq!(exported.client_name, "test-client");+ assert!(*remaining > CLIENT_REGISTRATION_TTL - Duration::from_secs(60));++ let bindings = registry.export_bindings().await.expect("export bindings");+ let (_, bound, remaining) = bindings+ .iter()+ .find(|(exported, _, _)| *exported == digest)+ .expect("the binding should be exported");+ assert_eq!(*bound, binding);+ assert!(*remaining > REFRESH_TOKEN_BINDING_TTL - Duration::from_secs(60));+ let (_, legacy, _) = bindings+ .iter()+ .find(|(exported, _, _)| *exported == legacy_digest)+ .expect("the legacy binding should be exported");+ assert_eq!(legacy.client_id, client_id);+ assert_eq!(legacy.grant_id, legacy_digest);++ let revoked = registry+ .export_revoked_grants()+ .await+ .expect("export revocations");+ let (_, remaining) = revoked+ .iter()+ .find(|(exported, _)| *exported == grant_id)+ .expect("the revocation should be exported");+ assert!(*remaining > REVOKED_GRANT_TTL - Duration::from_secs(60));+}diff --git a/services/mcp_auth_proxy/src/outbound/redis_cutover.rs b/services/mcp_auth_proxy/src/outbound/redis_cutover.rsnew file mode 100644index 0000000000..d1ab710543--- /dev/null+++ b/services/mcp_auth_proxy/src/outbound/redis_cutover.rs@@ -0,0 +1,317 @@+//! Moves broker state from Redis to Postgres without logging anyone out.+//!+//! Postgres is the store of record. Redis is kept only so nothing written+//! there before the cutover is lost, and so replicas still on the Redis-only+//! build keep working until a rolling deploy replaces them:+//!+//! - Registrations, refresh token bindings, and grant revocations are written+//! to both stores, and read from Postgres first. A miss falls back to Redis+//! and copies what it finds into Postgres. [`backfill_from_redis`] copies+//! the rest at startup.+//! - Pending authorizations and issued codes are written to Postgres only, so+//! upstream tokens never go to Redis again and a code can be redeemed in only+//! one store. A take falls back to Redis for handshakes started before the+//! cutover; Redis consumes those atomically too.+//! A handshake a new replica starts and an old one finishes fails once+//! mid-rollout, and the client retries the login.+//!+//! Redis is best-effort throughout. A Redis failure is logged and treated as+//! a miss; it never fails a request Postgres can serve.+//!+//! Once every replica runs this build and the backfill has completed, the next+//! change wires [`PostgresAuthStore`] directly and deletes this module and the+//! Redis adapter.++#[cfg(test)]+mod test;++use std::sync::Arc;++use crate::domain::{+ models::{+ IssuedAuthorizationCode, PendingAuthorization, RefreshTokenBinding, RegisteredClient,+ },+ ports::{+ ClientRegistrationStore, GrantRevokedFuture, RefreshTokenBindingFuture,+ RefreshTokenBindingStore, RegisteredClientFuture, StoreWriteFuture,+ },+ service::{+ CLIENT_REGISTRATION_TTL, InflightAuthStore, REFRESH_TOKEN_BINDING_TTL, REVOKED_GRANT_TTL,+ },+};++use super::{+ postgres::PostgresAuthStore,+ redis::{RedisClientRegistry, RedisInflightAuth},+};++/// Postgres-backed broker state that still reads, and partly writes, the+/// legacy Redis store during the cutover.+#[derive(Clone)]+pub struct RedisCutoverAuthStore<C = RedisClientRegistry, I = RedisInflightAuth> {+ postgres: PostgresAuthStore,+ legacy_clients: Arc<C>,+ legacy_inflight: Arc<I>,+}++impl<C, I> RedisCutoverAuthStore<C, I> {+ /// Creates a store of record in `postgres` that falls back to the legacy+ /// stores.+ pub fn new(+ postgres: PostgresAuthStore,+ legacy_clients: Arc<C>,+ legacy_inflight: Arc<I>,+ ) -> Self {+ Self {+ postgres,+ legacy_clients,+ legacy_inflight,+ }+ }+}++fn log_legacy_error(operation: &'static str, error: &anyhow::Error) {+ tracing::warn!(error = ?error, operation, "legacy Redis MCP OAuth store failed");+}++impl<C, I> ClientRegistrationStore for RedisCutoverAuthStore<C, I>+where+ C: ClientRegistrationStore + RefreshTokenBindingStore + 'static,+ I: Send + Sync + 'static,+{+ fn insert_client<'a>(&'a self, client: &'a RegisteredClient) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ self.postgres.insert_client(client).await?;+ if let Err(error) = self.legacy_clients.insert_client(client).await {+ log_legacy_error("insert_client", &error);+ }+ Ok(())+ })+ }++ fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a> {+ Box::pin(async move {+ if let Some(client) = self.postgres.find_client(client_id).await? {+ return Ok(Some(client));+ }+ let legacy = match self.legacy_clients.find_client(client_id).await {+ Ok(legacy) => legacy,+ Err(error) => {+ log_legacy_error("find_client", &error);+ None+ }+ };+ let Some(client) = legacy else {+ return Ok(None);+ };+ tracing::info!(%client_id, "copied MCP OAuth client registration from legacy Redis");+ // The Redis read just re-armed its TTL, so the copy gets a full one.+ self.postgres+ .import_client(&client, CLIENT_REGISTRATION_TTL)+ .await?;+ Ok(Some(client))+ })+ }+}++impl<C, I> RefreshTokenBindingStore for RedisCutoverAuthStore<C, I>+where+ C: ClientRegistrationStore + RefreshTokenBindingStore + 'static,+ I: Send + Sync + 'static,+{+ fn bind<'a>(+ &'a self,+ refresh_token_digest: &'a str,+ binding: &'a RefreshTokenBinding,+ ) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ self.postgres.bind(refresh_token_digest, binding).await?;+ if let Err(error) = self+ .legacy_clients+ .bind(refresh_token_digest, binding)+ .await+ {+ log_legacy_error("bind", &error);+ }+ Ok(())+ })+ }++ fn binding<'a>(&'a self, refresh_token_digest: &'a str) -> RefreshTokenBindingFuture<'a> {+ Box::pin(async move {+ if let Some(binding) = self.postgres.binding(refresh_token_digest).await? {+ return Ok(Some(binding));+ }+ let legacy = match self.legacy_clients.binding(refresh_token_digest).await {+ Ok(legacy) => legacy,+ Err(error) => {+ log_legacy_error("binding", &error);+ None+ }+ };+ let Some(binding) = legacy else {+ return Ok(None);+ };+ tracing::info!(+ client_id = %binding.client_id,+ grant_id = %binding.grant_id,+ "copied MCP OAuth refresh token binding from legacy Redis"+ );+ // A full TTL, not the Redis remainder: the refresh that asked for+ // this binding is about to re-bind its successor anyway.+ self.postgres+ .import_binding(refresh_token_digest, &binding, REFRESH_TOKEN_BINDING_TTL)+ .await?;+ Ok(Some(binding))+ })+ }++ fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ // Redis first: once Postgres has dropped the binding, a lookup+ // must not find the Redis copy and bring it back.+ if let Err(error) = self.legacy_clients.unbind(refresh_token_digest).await {+ log_legacy_error("unbind", &error);+ }+ self.postgres.unbind(refresh_token_digest).await+ })+ }++ fn revoke_grant<'a>(&'a self, grant_id: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ self.postgres.revoke_grant(grant_id).await?;+ // Mirrored so replicas still on the Redis-only build refuse the+ // family too.+ if let Err(error) = self.legacy_clients.revoke_grant(grant_id).await {+ log_legacy_error("revoke_grant", &error);+ }+ Ok(())+ })+ }++ fn is_grant_revoked<'a>(&'a self, grant_id: &'a str) -> GrantRevokedFuture<'a> {+ Box::pin(async move {+ if self.postgres.is_grant_revoked(grant_id).await? {+ return Ok(true);+ }+ // A replica on the Redis-only build records revocations there.+ let revoked = match self.legacy_clients.is_grant_revoked(grant_id).await {+ Ok(revoked) => revoked,+ Err(error) => {+ log_legacy_error("is_grant_revoked", &error);+ false+ }+ };+ if revoked {+ tracing::info!(%grant_id, "copied MCP OAuth grant revocation from legacy Redis");+ self.postgres+ .import_revoked_grant(grant_id, REVOKED_GRANT_TTL)+ .await?;+ }+ Ok(revoked)+ })+ }+}++impl<C, I> InflightAuthStore for RedisCutoverAuthStore<C, I>+where+ C: Send + Sync + 'static,+ I: InflightAuthStore + 'static,+{+ async fn insert_pending(+ &self,+ session_id: &str,+ pending: PendingAuthorization,+ ) -> anyhow::Result<()> {+ self.postgres.insert_pending(session_id, pending).await+ }++ async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {+ if let Some(pending) = self.postgres.take_pending(session_id).await? {+ return Ok(Some(pending));+ }+ self.legacy_inflight+ .take_pending(session_id)+ .await+ .or_else(|error| {+ log_legacy_error("take_pending", &error);+ Ok(None)+ })+ }++ async fn insert_issued(+ &self,+ code: &str,+ issued: IssuedAuthorizationCode,+ ) -> anyhow::Result<()> {+ self.postgres.insert_issued(code, issued).await+ }++ async fn take_issued(&self, code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {+ if let Some(issued) = self.postgres.take_issued(code).await? {+ return Ok(Some(issued));+ }+ self.legacy_inflight+ .take_issued(code)+ .await+ .or_else(|error| {+ log_legacy_error("take_issued", &error);+ Ok(None)+ })+ }++ async fn cleanup_expired(&self) -> anyhow::Result<()> {+ self.postgres.cleanup_expired().await+ }+}++/// Copies every registration, refresh token binding, and grant revocation+/// still in Redis into Postgres, keeping the time each had left.+///+/// Safe to run on every replica at once and to repeat: a row already in+/// Postgres is left as it is.+#[tracing::instrument(+ name = "mcp_oauth.backfill_from_redis",+ skip_all,+ err,+ fields(+ clients = tracing::field::Empty,+ bindings = tracing::field::Empty,+ revoked_grants = tracing::field::Empty+ )+)]+pub async fn backfill_from_redis(+ legacy: &RedisClientRegistry,+ postgres: &PostgresAuthStore,+) -> anyhow::Result<()> {+ let clients = legacy.export_clients().await?;+ let client_count = clients.len();+ for (client, remaining) in clients {+ postgres.import_client(&client, remaining).await?;+ }+ // Revocations before bindings, so no binding of a revoked family is+ // honored in Postgres before its revocation is.+ let revoked_grants = legacy.export_revoked_grants().await?;+ let revoked_grant_count = revoked_grants.len();+ for (grant_id, remaining) in revoked_grants {+ postgres.import_revoked_grant(&grant_id, remaining).await?;+ }+ let bindings = legacy.export_bindings().await?;+ let binding_count = bindings.len();+ for (digest, binding, remaining) in bindings {+ postgres+ .import_binding(&digest, &binding, remaining)+ .await?;+ }+ tracing::Span::current()+ .record("clients", client_count)+ .record("bindings", binding_count)+ .record("revoked_grants", revoked_grant_count);+ tracing::info!(+ clients = client_count,+ bindings = binding_count,+ revoked_grants = revoked_grant_count,+ "backfilled MCP OAuth state from legacy Redis"+ );+ Ok(())+}diff --git a/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs b/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rsnew file mode 100644index 0000000000..c4b0f3a52b--- /dev/null+++ b/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs@@ -0,0 +1,338 @@+use std::time::{Duration, SystemTime};++use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;++use super::*;+use crate::{+ domain::models::{AccessToken, RefreshToken},+ test_support::{FakeClientRegistry, FakeInflightAuth, FakeKms},+};++type Store<C = FakeClientRegistry, I = FakeInflightAuth> = RedisCutoverAuthStore<C, I>;++fn postgres(pool: PgPool) -> PostgresAuthStore {+ PostgresAuthStore::new(pool, Arc::new(FakeKms::default()))+}++fn cutover(pool: PgPool) -> (Store, Arc<FakeClientRegistry>, Arc<FakeInflightAuth>) {+ let legacy_clients = Arc::new(FakeClientRegistry::default());+ let legacy_inflight = Arc::new(FakeInflightAuth::default());+ let store = RedisCutoverAuthStore::new(+ postgres(pool),+ legacy_clients.clone(),+ legacy_inflight.clone(),+ );+ (store, legacy_clients, legacy_inflight)+}++fn registered_client(client_id: &str) -> RegisteredClient {+ RegisteredClient {+ client_id: client_id.to_owned(),+ client_name: "test-client".to_owned(),+ redirect_uris: vec!["http://127.0.0.1:51000/oauth/callback".to_owned()],+ }+}++fn binding(client_id: &str, grant_id: &str) -> RefreshTokenBinding {+ RefreshTokenBinding {+ client_id: client_id.to_owned(),+ grant_id: grant_id.to_owned(),+ }+}++fn issued_code(client_id: &str) -> IssuedAuthorizationCode {+ IssuedAuthorizationCode {+ client_id: client_id.to_owned(),+ access_token: AccessToken::from("upstream-access-token"),+ refresh_token: RefreshToken::from("upstream-refresh-token"),+ code_challenge: "challenge".to_owned(),+ redirect_uri: "http://127.0.0.1:51000/oauth/callback".to_owned(),+ access_token_expires_at: SystemTime::UNIX_EPOCH + Duration::from_secs(4_000_000_000),+ }+}++/// A legacy store whose every call fails, like Redis refusing writes.+struct BrokenLegacy;++fn broken<T>() -> anyhow::Result<T> {+ Err(anyhow::anyhow!(+ "ReadOnly: You can't write against a read only replica."+ ))+}++impl ClientRegistrationStore for BrokenLegacy {+ fn insert_client<'a>(&'a self, _client: &'a RegisteredClient) -> StoreWriteFuture<'a> {+ Box::pin(async { broken() })+ }++ fn find_client<'a>(&'a self, _client_id: &'a str) -> RegisteredClientFuture<'a> {+ Box::pin(async { broken() })+ }+}++impl RefreshTokenBindingStore for BrokenLegacy {+ fn bind<'a>(+ &'a self,+ _digest: &'a str,+ _binding: &'a RefreshTokenBinding,+ ) -> StoreWriteFuture<'a> {+ Box::pin(async { broken() })+ }++ fn binding<'a>(&'a self, _digest: &'a str) -> RefreshTokenBindingFuture<'a> {+ Box::pin(async { broken() })+ }++ fn unbind<'a>(&'a self, _digest: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async { broken() })+ }++ fn revoke_grant<'a>(&'a self, _grant_id: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async { broken() })+ }++ fn is_grant_revoked<'a>(&'a self, _grant_id: &'a str) -> GrantRevokedFuture<'a> {+ Box::pin(async { broken() })+ }+}++impl InflightAuthStore for BrokenLegacy {+ async fn insert_pending(&self, _: &str, _: PendingAuthorization) -> anyhow::Result<()> {+ broken()+ }++ async fn take_pending(&self, _: &str) -> anyhow::Result<Option<PendingAuthorization>> {+ broken()+ }++ async fn insert_issued(&self, _: &str, _: IssuedAuthorizationCode) -> anyhow::Result<()> {+ broken()+ }++ async fn take_issued(&self, _: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {+ broken()+ }++ async fn cleanup_expired(&self) -> anyhow::Result<()> {+ broken()+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_registration_only_in_redis_is_found_and_copied(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool.clone());+ legacy_clients+ .insert_client(®istered_client("pre-cutover"))+ .await+ .expect("legacy insert");++ let found = store+ .find_client("pre-cutover")+ .await+ .expect("lookup")+ .expect("legacy registration");+ assert_eq!(found.client_id, "pre-cutover");++ let copied = postgres(pool)+ .find_client("pre-cutover")+ .await+ .expect("lookup");+ assert!(copied.is_some(), "the fallback should copy into Postgres");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_new_registration_is_written_to_both_stores(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool.clone());++ store+ .insert_client(®istered_client("new"))+ .await+ .expect("insert");++ assert!(+ postgres(pool)+ .find_client("new")+ .await+ .expect("lookup")+ .is_some()+ );+ assert!(+ legacy_clients+ .find_client("new")+ .await+ .expect("lookup")+ .is_some(),+ "replicas still on the Redis-only build must see new registrations"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_binding_only_in_redis_is_found_and_copied(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool.clone());+ legacy_clients+ .bind("pre-cutover-digest", &binding("client", "grant"))+ .await+ .expect("legacy bind");++ assert_eq!(+ store.binding("pre-cutover-digest").await.expect("lookup"),+ Some(binding("client", "grant"))+ );+ assert_eq!(+ postgres(pool)+ .binding("pre-cutover-digest")+ .await+ .expect("lookup"),+ Some(binding("client", "grant"))+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_unbound_digest_stays_unbound_in_both_stores(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool);+ store+ .bind("digest", &binding("client", "grant"))+ .await+ .expect("bind");+ assert!(+ legacy_clients+ .binding("digest")+ .await+ .expect("lookup")+ .is_some(),+ "a binding is mirrored to Redis"+ );++ store.unbind("digest").await.expect("unbind");++ assert!(store.binding("digest").await.expect("lookup").is_none());+ assert!(+ legacy_clients+ .binding("digest")+ .await+ .expect("lookup")+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_revocation_is_written_to_both_stores(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool.clone());++ store.revoke_grant("grant").await.expect("revoke");++ assert!(+ postgres(pool)+ .is_grant_revoked("grant")+ .await+ .expect("lookup")+ );+ assert!(+ legacy_clients+ .is_grant_revoked("grant")+ .await+ .expect("lookup"),+ "replicas still on the Redis-only build must refuse the family too"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_revocation_only_in_redis_is_honored_and_copied(pool: PgPool) {+ let (store, legacy_clients, _) = cutover(pool.clone());+ legacy_clients+ .revoke_grant("pre-cutover-grant")+ .await+ .expect("legacy revoke");++ assert!(+ store+ .is_grant_revoked("pre-cutover-grant")+ .await+ .expect("lookup")+ );+ assert!(+ postgres(pool)+ .is_grant_revoked("pre-cutover-grant")+ .await+ .expect("lookup"),+ "the fallback should copy into Postgres"+ );+ assert!(!store.is_grant_revoked("other").await.expect("lookup"));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn issued_codes_are_never_written_to_redis(pool: PgPool) {+ let (store, _, legacy_inflight) = cutover(pool);++ store+ .insert_issued("broker-code", issued_code("client"))+ .await+ .expect("insert");++ assert!(!legacy_inflight.holds_issued_code("broker-code"));+ assert!(+ store+ .take_issued("broker-code")+ .await+ .expect("take")+ .is_some()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_code_issued_before_the_cutover_redeems_once(pool: PgPool) {+ let (store, _, legacy_inflight) = cutover(pool);+ legacy_inflight+ .insert_issued("pre-cutover-code", issued_code("client"))+ .await+ .expect("legacy insert");++ let issued = store+ .take_issued("pre-cutover-code")+ .await+ .expect("take")+ .expect("legacy code");+ assert_eq!(issued.client_id, "client");+ assert!(+ store+ .take_issued("pre-cutover-code")+ .await+ .expect("take")+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_failing_redis_does_not_fail_requests(pool: PgPool) {+ let store: Store<BrokenLegacy, BrokenLegacy> = RedisCutoverAuthStore::new(+ postgres(pool),+ Arc::new(BrokenLegacy),+ Arc::new(BrokenLegacy),+ );++ store+ .insert_client(®istered_client("client"))+ .await+ .expect("registration succeeds without Redis");+ assert!(store.find_client("client").await.expect("lookup").is_some());+ assert!(+ store+ .find_client("unknown")+ .await+ .expect("lookup")+ .is_none()+ );++ store+ .bind("digest", &binding("client", "grant"))+ .await+ .expect("bind");+ assert!(store.binding("other").await.expect("lookup").is_none());+ store.revoke_grant("grant").await.expect("revoke");+ assert!(!store.is_grant_revoked("other").await.expect("lookup"));+ store.unbind("digest").await.expect("unbind");++ assert!(store.take_pending("session").await.expect("take").is_none());+ assert!(store.take_issued("code").await.expect("take").is_none());+}diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rsindex e0832d0f78..14928be6eb 100644--- a/services/mcp_auth_proxy/src/test_support.rs+++ b/services/mcp_auth_proxy/src/test_support.rs@@ -421,3 +421,53 @@ pub fn query_param(url: &str, name: &str) -> Option<String> {.find_map(|pair| pair.strip_prefix(&prefix)).map(str::to_owned)}++#[cfg(feature = "outbound")]+pub use fake_kms::FakeKms;++#[cfg(feature = "outbound")]+mod fake_kms {+ use std::{collections::HashMap, sync::Mutex};++ use cursor_api_key::cipher::{KmsCiphertexts, KmsCiphertextsError};+ use zeroize::Zeroizing;++ /// A ciphertext, the context it was encrypted under, and its plaintext.+ type Encryption = (Vec<u8>, HashMap<String, String>, Vec<u8>);++ /// A KMS that, like the real one, refuses a decrypt whose context differs+ /// from the one the ciphertext was encrypted under.+ #[derive(Default)]+ pub struct FakeKms {+ stored: Mutex<Vec<Encryption>>,+ }++ #[async_trait::async_trait]+ impl KmsCiphertexts for FakeKms {+ async fn encrypt(+ &self,+ encryption_context: HashMap<String, String>,+ plaintext: &[u8],+ ) -> Result<(Vec<u8>, String), KmsCiphertextsError> {+ let mut stored = self.stored.lock().expect("lock");+ let ciphertext = format!("ciphertext-{}", stored.len()).into_bytes();+ stored.push((ciphertext.clone(), encryption_context, plaintext.to_vec()));+ Ok((ciphertext, "fake-kms-key".to_owned()))+ }++ async fn decrypt(+ &self,+ _kms_key_id: &str,+ ciphertext: &[u8],+ encryption_context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, KmsCiphertextsError> {+ self.stored+ .lock()+ .expect("lock")+ .iter()+ .find(|(stored, context, _)| stored == ciphertext && *context == encryption_context)+ .map(|(_, _, plaintext)| Zeroizing::new(plaintext.clone()))+ .ok_or(KmsCiphertextsError)+ }+ }+}diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex f9ccc4fb38..989bd4d0e9 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -387,6 +387,10 @@ impl InfraEnv {"CODEX_OAUTH_KMS_KEY_ID".into(),resources::CODEX_OAUTH_KMS_ALIAS.into(),);+ env.insert(+ "MCP_OAUTH_KMS_KEY_ID".into(),+ resources::MCP_OAUTH_KMS_ALIAS.into(),+ );// Dummy creds: the SDK talks to LocalStack, never real AWS.env.insert("AWS_ACCESS_KEY_ID".into(), "test".into());env.insert("AWS_SECRET_ACCESS_KEY".into(), "test".into());diff --git a/tooling/xtask/crates/xtask_local/src/local/localstack.rs b/tooling/xtask/crates/xtask_local/src/local/localstack.rsindex 1b6b2c0d56..40b0224e03 100644--- a/tooling/xtask/crates/xtask_local/src/local/localstack.rs+++ b/tooling/xtask/crates/xtask_local/src/local/localstack.rs@@ -84,6 +84,10 @@ async fn create_kms_keys(kms: &aws_sdk_kms::Client) -> Result<()> {resources::CODEX_OAUTH_KMS_ALIAS,"ChatGPT OAuth envelope encryption key (local)",),+ (+ resources::MCP_OAUTH_KMS_ALIAS,+ "MCP OAuth authorization code encryption key (local)",+ ),(resources::WHATSAPP_SESSION_KMS_ALIAS,"WhatsApp session data key encryption key (local)",diff --git a/tooling/xtask/crates/xtask_local/src/local/resources.rs b/tooling/xtask/crates/xtask_local/src/local/resources.rsindex 653f5fdf8b..a5559fa8a9 100644--- a/tooling/xtask/crates/xtask_local/src/local/resources.rs+++ b/tooling/xtask/crates/xtask_local/src/local/resources.rs@@ -43,6 +43,9 @@ pub const CURSOR_API_KEY_KMS_ALIAS: &str = "alias/macro-local-cursor-api-key";/// Dedicated envelope-encryption key for local ChatGPT account connections.pub const CODEX_OAUTH_KMS_ALIAS: &str = "alias/macro-local-codex-oauth";+/// Key the public MCP OAuth broker encrypts its authorization codes' tokens with.+pub const MCP_OAUTH_KMS_ALIAS: &str = "alias/macro-local-mcp-oauth";+/// The WhatsApp session service's key for per-account data keys. The service/// computes this name from `ENVIRONMENT` (`SessionKmsKey` in its `config.rs`).pub const WHATSAPP_SESSION_KMS_ALIAS: &str = "alias/whatsapp-session-service-local";