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(github): better GitHub app installation tracking (#5356)
Will Hutchinson09e92dd75cea
diff --git a/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.json b/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.jsonindex 71348ac40d..6b9c79fc3e 100644--- a/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.json+++ b/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.json@@ -35,7 +35,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.json b/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.jsonindex a64a4e61fc..cbb809a7c2 100644--- a/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.json+++ b/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -113,7 +114,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -155,7 +157,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.jsonindex 0c0204cf7b..625010797d 100644--- a/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json+++ b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -67,7 +68,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json b/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.jsondeleted file mode 100644index f4dbba6dd1..0000000000--- a/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT installation_id\n FROM github_app_installation_installer\n WHERE github_user_id = $1\n ORDER BY installation_id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "installation_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214"-}diff --git a/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.json b/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.jsonindex a562fc8cc7..14090c2bfc 100644--- a/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.json+++ b/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.json@@ -24,7 +24,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json b/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.jsondeleted file mode 100644index 8b8cc329a2..0000000000--- a/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM github_app_installation_installer\n WHERE installation_id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41"-}diff --git a/.sqlx/query-45ac2a692bf3676d053ca1905fe8586ff1dd139822d3cbde8e125add5575194a.json b/.sqlx/query-45ac2a692bf3676d053ca1905fe8586ff1dd139822d3cbde8e125add5575194a.jsonindex 743e277ed9..697aeae999 100644--- a/.sqlx/query-45ac2a692bf3676d053ca1905fe8586ff1dd139822d3cbde8e125add5575194a.json+++ b/.sqlx/query-45ac2a692bf3676d053ca1905fe8586ff1dd139822d3cbde8e125add5575194a.json@@ -25,7 +25,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.json b/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.jsonindex 6f47bbf27f..6ced5d7c76 100644--- a/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.json+++ b/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.json b/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.jsonindex ef5af28e2b..170cdf8f1f 100644--- a/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.json+++ b/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.json@@ -24,7 +24,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.json b/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.jsonindex 30c7bb54c5..5ed75dc206 100644--- a/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.json+++ b/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -113,7 +114,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -155,7 +157,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.json b/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.jsonindex 1634fc9c55..76543634dc 100644--- a/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.json+++ b/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json b/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.jsonindex b20cd00e77..fc162172ba 100644--- a/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json+++ b/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -72,7 +73,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-622ebfa7fabdea2e10fd50a9a2a6bb0b822c3d54b92aa4cd0022d9bbdf2d925b.json b/.sqlx/query-622ebfa7fabdea2e10fd50a9a2a6bb0b822c3d54b92aa4cd0022d9bbdf2d925b.jsonnew file mode 100644index 0000000000..ead4f12515--- /dev/null+++ b/.sqlx/query-622ebfa7fabdea2e10fd50a9a2a6bb0b822c3d54b92aa4cd0022d9bbdf2d925b.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT source_id AS \"source_id!\", source_type::text AS \"source_type!\"\n FROM github_app_installation_request\n WHERE github_user_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_type!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "622ebfa7fabdea2e10fd50a9a2a6bb0b822c3d54b92aa4cd0022d9bbdf2d925b"+}diff --git a/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.json b/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.jsonindex dd0f75ea70..66a65818f9 100644--- a/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.json+++ b/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -121,7 +122,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.json b/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.jsonindex a6f7cd5922..b887727dc7 100644--- a/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.json+++ b/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.json@@ -20,7 +20,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.json b/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.jsonindex 9b7df6ca51..c0859295bc 100644--- a/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.json+++ b/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.jsonindex de71e6fb4f..e4c1b6f559 100644--- a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json+++ b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -68,7 +69,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.json b/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.jsonindex 551831f606..0e73a87f03 100644--- a/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.json+++ b/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json b/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.jsonindex d2f6d4250c..d91ee00599 100644--- a/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json+++ b/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json@@ -25,7 +25,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.json b/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.jsonindex 4b3b9da95a..7b26589551 100644--- a/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.json+++ b/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.json b/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.jsonindex 0fe26da4f8..eff841fd3f 100644--- a/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.json+++ b/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.json@@ -66,7 +66,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json b/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.jsonindex d0ee7130af..bf2feb76b0 100644--- a/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json+++ b/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -73,7 +74,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.json b/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.jsonindex 8594056ddf..e5e7920533 100644--- a/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.json+++ b/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.json@@ -19,7 +19,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json b/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.jsondeleted file mode 100644index c02348956b..0000000000--- a/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO github_app_installation_installer (installation_id, github_user_id)\n VALUES ($1, $2)\n ON CONFLICT (installation_id)\n DO UPDATE SET github_user_id = EXCLUDED.github_user_id, updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7"-}diff --git a/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.json b/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.jsonindex b126dea627..93db5a63f2 100644--- a/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.json+++ b/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -113,7 +114,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -151,7 +153,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-d5e0b6000fae29a4efa47e877d4644daf4a6d6946fb7cb236d8ff2b4b6695f5b.json b/.sqlx/query-d5e0b6000fae29a4efa47e877d4644daf4a6d6946fb7cb236d8ff2b4b6695f5b.jsonnew file mode 100644index 0000000000..af223cda1d--- /dev/null+++ b/.sqlx/query-d5e0b6000fae29a4efa47e877d4644daf4a6d6946fb7cb236d8ff2b4b6695f5b.json@@ -0,0 +1,26 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO github_app_installation_request (github_user_id, source_id, source_type)\n VALUES ($1, $2, $3::github_app_installation_source_type)\n ON CONFLICT (github_user_id) DO UPDATE\n SET source_id = EXCLUDED.source_id,\n source_type = EXCLUDED.source_type,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ {+ "Custom": {+ "name": "github_app_installation_source_type",+ "kind": {+ "Enum": [+ "team",+ "user"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "d5e0b6000fae29a4efa47e877d4644daf4a6d6946fb7cb236d8ff2b4b6695f5b"+}diff --git a/.sqlx/query-d9c372dac5f825978a6ca0c99565c95bcf903c21e2da117aea436047d0e2a654.json b/.sqlx/query-d9c372dac5f825978a6ca0c99565c95bcf903c21e2da117aea436047d0e2a654.jsonnew file mode 100644index 0000000000..020aba9812--- /dev/null+++ b/.sqlx/query-d9c372dac5f825978a6ca0c99565c95bcf903c21e2da117aea436047d0e2a654.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM github_app_installation_request\n WHERE github_user_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "d9c372dac5f825978a6ca0c99565c95bcf903c21e2da117aea436047d0e2a654"+}diff --git a/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json b/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.jsonindex 01d2427d83..d1e11cbb40 100644--- a/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json+++ b/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json@@ -29,7 +29,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}@@ -72,7 +73,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json b/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.jsonindex 38d93cc368..1eb8d0c3e8 100644--- a/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json+++ b/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json@@ -30,7 +30,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.json b/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.jsonindex f395a59f2b..ace10abd78 100644--- a/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.json+++ b/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.json@@ -77,7 +77,8 @@"USER","COMPANY","TASK",- "CALL_RECORD"+ "CALL_RECORD",+ "CALENDAR_EVENT"]}}diff --git a/Cargo.lock b/Cargo.lockindex 927d3ab3b3..ccb074688f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6162,6 +6162,7 @@ dependencies = ["anyhow","axum","axum-extra",+ "base64 0.22.1","chrono","document_sub_type","documents",@@ -6172,6 +6173,7 @@ dependencies = ["hmac 0.12.1","http-body-util","jsonwebtoken 10.3.0",+ "macro_authorization","macro_db_migrator","macro_env","macro_env_var",@@ -6183,6 +6185,7 @@ dependencies = ["model-entity","model-error-response","model_notifications",+ "model_user","models_permissions","notification","redis",@@ -6198,6 +6201,7 @@ dependencies = ["tokio","tower 0.5.3","tracing",+ "url","urlencoding","utoipa","uuid",diff --git a/apps/web/src/features/settings/GitHub.tsx b/apps/web/src/features/settings/GitHub.tsxindex 883fc00e59..d8292866fd 100644--- a/apps/web/src/features/settings/GitHub.tsx+++ b/apps/web/src/features/settings/GitHub.tsx@@ -128,15 +128,28 @@ export function GitHubCard() {label="GitHub App"description="Choose repositories for Macro to sync.">- <a- href={`${SERVER_HOSTS['document-storage-service']}/github/install-sync`}- target="_blank"- rel="noopener noreferrer"- class="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ {/* The install callback rejects users without a linked account, so+ don't offer the flow until the account above is connected. */}+ <Show+ when={status() === 'linked'}+ fallback={+ <span class="text-xs text-ink-muted">+ {githubLink.isLoading+ ? 'Loading…'+ : 'Connect your GitHub account first'}+ </span>+ }>- Configure app- <ArrowUpRightIcon class="size-3.5 opacity-70" />- </a>+ <a+ href={`${SERVER_HOSTS['document-storage-service']}/github/install-sync`}+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ >+ Configure app+ <ArrowUpRightIcon class="size-3.5 opacity-70" />+ </a>+ </Show></SettingsRow></SettingsCard>);diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 78401c9fdb..35bb67de1a 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -22,6 +22,7 @@ import SpinnerIcon from '@phosphor/spinner.svg';import TrashIcon from '@phosphor/trash.svg';import UsersIcon from '@phosphor/users.svg';import XIcon from '@phosphor/x.svg';+import { useGithubLinkStatusQuery } from '@queries/auth';import {useJoinTeamMutation,useRejectInvitationMutation,@@ -811,6 +812,7 @@ function TeamManagement(props: {const teamQuery = useTeamQuery(() => props.teamId);const invitesQuery = useTeamInvitesQuery(() => props.teamId);+ const githubLink = useGithubLinkStatusQuery();const deleteInviteMutation = useDeleteTeamInviteMutation();const removeUserMutation = useRemoveUserFromTeamMutation();@@ -1307,15 +1309,29 @@ function TeamManagement(props: {title="GitHub App"description="Connect your team's repositories for pull request sync.">- <a- href={`${SERVER_HOSTS['document-storage-service']}/github/install-sync`}- target="_blank"- rel="noopener noreferrer"- class="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ {/* The install callback rejects users without a linked GitHub+ account, so don't offer the flow until they've connected one+ in their personal settings. */}+ <Show+ when={githubLink.data?.status === 'linked'}+ fallback={+ <span class="text-xs text-ink-muted">+ {githubLink.isLoading+ ? 'Loading…'+ : 'Connect your GitHub account first'}+ </span>+ }>- Configure app- <ArrowUpRightIcon class="size-3.5 opacity-70" />- </a>+ <a+ href={`${SERVER_HOSTS['document-storage-service']}/github/install-sync`}+ target="_blank"+ rel="noopener noreferrer"+ class="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-sm font-medium text-ink-muted outline-none transition-colors hover:bg-ink/4 hover:text-ink focus-visible:bg-ink/6"+ >+ Configure app+ <ArrowUpRightIcon class="size-3.5 opacity-70" />+ </a>+ </Show></IntegrationRow></SettingsCard></SettingsSection>diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex cc99b57896..492709d071 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -7953,11 +7953,14 @@"/github/install-sync": {"get": {"tags": ["github::inbound::github_sync_router"],- "summary": "Redirects the user to the github sync app installation page.",+ "summary": "Redirects an authenticated user to the github sync app installation page.","operationId": "install_sync","responses": {"307": {- "description": "Redirects to the github sync app installation page"+ "description": "Temporary redirect to the GitHub sync app installation page"+ },+ "401": {+ "description": "Authentication failed"}}}diff --git a/crates/document_storage_service_client/src/github.rs b/crates/document_storage_service_client/src/github.rsdeleted file mode 100644index da61504254..0000000000--- a/crates/document_storage_service_client/src/github.rs+++ /dev/null@@ -1,37 +0,0 @@-use super::DocumentStorageServiceClient;-use anyhow::Result;--const ASSOCIATE_GITHUB_INSTALLATIONS_TIMEOUT: std::time::Duration =- std::time::Duration::from_secs(15);--impl DocumentStorageServiceClient {- /// Associates GitHub App installations installed by the given GitHub user- /// with that user's Macro sources. Intended to be called after a github- /// link is created for the user.- #[tracing::instrument(skip(self))]- pub async fn associate_github_installations(&self, github_user_id: &str) -> Result<()> {- let res = self- .client- .post(format!(- "{}/internal/github/installations/{}/associate",- self.url, github_user_id- ))- .timeout(ASSOCIATE_GITHUB_INSTALLATIONS_TIMEOUT)- .send()- .await?;-- let status_code = res.status();-- if status_code != reqwest::StatusCode::OK {- let body: String = res.text().await?;- tracing::error!(- body=%body,- status=%status_code,- "unexpected response from document storage service"- );- anyhow::bail!(body);- }-- Ok(())- }-}diff --git a/crates/document_storage_service_client/src/lib.rs b/crates/document_storage_service_client/src/lib.rsindex a3bc80c904..781ec71415 100644--- a/crates/document_storage_service_client/src/lib.rs+++ b/crates/document_storage_service_client/src/lib.rs@@ -4,7 +4,6 @@ pub(crate) mod constants;pub mod delete;pub mod document;pub mod error;-pub mod github;pub mod notification;pub mod project;pub mod thread;diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.tomlindex 5a62998925..1eb225df2a 100644--- a/crates/github/Cargo.toml+++ b/crates/github/Cargo.toml@@ -5,7 +5,14 @@ publish = falseversion = "0.1.0"[features]-axum = ["dep:axum", "dep:axum-extra", "dep:model-error-response", "dep:utoipa"]+axum = [+ "dep:axum",+ "dep:axum-extra",+ "dep:entity_access",+ "dep:macro_authorization",+ "dep:model-error-response",+ "dep:utoipa",+]default = ["axum", "inbound", "link", "outbound", "ports", "sync"]inbound = ["axum", "ports"]link = ["dep:entity_access", "dep:foreign_entity", "ports"]@@ -32,11 +39,13 @@ sync = [[dependencies]anyhow = { workspace = true }+base64 = { workspace = true }chrono = { workspace = true }documents = { path = "../documents", default-features = false, features = ["ports",], optional = true }entity_access = { path = "../entity_access", default-features = false, features = [+ "inbound","ports",], optional = true }foreign_entity = { path = "../foreign_entity", default-features = false, features = [@@ -47,6 +56,9 @@ hmac = { workspace = true }jsonwebtoken = { workspace = true }macro_env = { path = "../macro_env" }macro_env_var = { path = "../macro_env_var" }+macro_authorization = { path = "../macro_authorization", default-features = false, features = [+ "axum",+], optional = true }macro_service_urls = { path = "../macro_service_urls" }model-entity = { path = "../model-entity", optional = true }model_notifications = { path = "../model_notifications", optional = true }@@ -61,6 +73,7 @@ subtle = "2.6.1"thiserror = { workspace = true }tracing = { workspace = true }urlencoding = { workspace = true, optional = true }+url = { workspace = true }uuid = { workspace = true }fusionauth = { path = "../fusionauth", optional = true }@@ -81,6 +94,7 @@ http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }mockall = { workspace = true }model = { path = "../model" }+model_user = { path = "../model_user" }models_permissions = { path = "../models_permissions" }rootcause = { workspace = true }tokio = { workspace = true }diff --git a/crates/github/src/domain/models/installation_state.rs b/crates/github/src/domain/models/installation_state.rsnew file mode 100644index 0000000000..0241c23fcb--- /dev/null+++ b/crates/github/src/domain/models/installation_state.rs@@ -0,0 +1,112 @@+//! Signed state carried through a GitHub App installation flow.++use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use hmac::{Hmac, Mac};+use macro_user_id::user_id::MacroUserIdStr;+use serde::{Deserialize, Serialize};+use sha2::Sha256;+use uuid::Uuid;++#[cfg(test)]+mod test;++type HmacSha256 = Hmac<Sha256>;++/// Authenticated context for a GitHub App installation flow.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct InstallationState {+ /// The Macro user who began the installation flow.+ pub macro_user_id: MacroUserIdStr<'static>,+ /// The team to associate with the installation, or `None` for a personal installation.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_id: Option<Uuid>,+ /// The token expiration time in Unix seconds.+ pub exp: i64,+}++/// An error encountered while signing or verifying installation state.+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum InstallationStateError {+ /// The payload could not be serialized.+ #[error("installation state payload could not be serialized")]+ Serialization,+ /// The token does not have the expected encoding or payload shape.+ #[error("installation state token is malformed")]+ Malformed,+ /// The token's signature is invalid.+ #[error("installation state signature is invalid")]+ InvalidSignature,+ /// The token has reached its expiration time.+ #[error("installation state token has expired")]+ Expired,+}++/// Serialize and sign an installation-state payload.+///+/// The returned token is `base64url(payload).base64url(signature)`, without+/// padding. The signature is HMAC-SHA256 over the encoded payload.+pub fn sign_installation_state(+ payload: &InstallationState,+ secret: &[u8],+) -> Result<String, InstallationStateError> {+ let json = serde_json::to_vec(payload).map_err(|_| InstallationStateError::Serialization)?;+ let encoded_payload = URL_SAFE_NO_PAD.encode(json);+ let signature = signature_for(encoded_payload.as_bytes(), secret);++ Ok(format!(+ "{encoded_payload}.{}",+ URL_SAFE_NO_PAD.encode(signature)+ ))+}++/// Verify and deserialize an installation-state token.+///+/// `current_timestamp` is expressed in Unix seconds. A token is expired when+/// the current timestamp is equal to or later than its `exp` value.+pub fn verify_installation_state(+ token: &str,+ secret: &[u8],+ current_timestamp: i64,+) -> Result<InstallationState, InstallationStateError> {+ let (encoded_payload, encoded_signature) = split_token(token)?;+ let signature = URL_SAFE_NO_PAD+ .decode(encoded_signature)+ .map_err(|_| InstallationStateError::Malformed)?;++ let mut verifier =+ HmacSha256::new_from_slice(secret).expect("HMAC-SHA256 accepts keys of any length");+ verifier.update(encoded_payload.as_bytes());+ verifier+ .verify_slice(&signature)+ .map_err(|_| InstallationStateError::InvalidSignature)?;++ let json = URL_SAFE_NO_PAD+ .decode(encoded_payload)+ .map_err(|_| InstallationStateError::Malformed)?;+ let payload: InstallationState =+ serde_json::from_slice(&json).map_err(|_| InstallationStateError::Malformed)?;++ if current_timestamp >= payload.exp {+ return Err(InstallationStateError::Expired);+ }++ Ok(payload)+}++fn split_token(token: &str) -> Result<(&str, &str), InstallationStateError> {+ let mut segments = token.split('.');+ let payload = segments.next().filter(|segment| !segment.is_empty());+ let signature = segments.next().filter(|segment| !segment.is_empty());++ match (payload, signature, segments.next()) {+ (Some(payload), Some(signature), None) => Ok((payload, signature)),+ _ => Err(InstallationStateError::Malformed),+ }+}++fn signature_for(payload: &[u8], secret: &[u8]) -> [u8; 32] {+ let mut signer =+ HmacSha256::new_from_slice(secret).expect("HMAC-SHA256 accepts keys of any length");+ signer.update(payload);+ signer.finalize().into_bytes().into()+}diff --git a/crates/github/src/domain/models/installation_state/test.rs b/crates/github/src/domain/models/installation_state/test.rsnew file mode 100644index 0000000000..dc6bcd6606--- /dev/null+++ b/crates/github/src/domain/models/installation_state/test.rs@@ -0,0 +1,149 @@+use super::*;++const SECRET: &[u8] = b"a distinct installation state test secret";+const NOW: i64 = 1_730_000_000;++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++fn state(team_id: Option<Uuid>, exp: i64) -> InstallationState {+ InstallationState {+ macro_user_id: user_id(),+ team_id,+ exp,+ }+}++fn sign_raw_payload(payload: &[u8]) -> String {+ let encoded_payload = URL_SAFE_NO_PAD.encode(payload);+ let signature = signature_for(encoded_payload.as_bytes(), SECRET);+ format!("{encoded_payload}.{}", URL_SAFE_NO_PAD.encode(signature))+}++#[test]+fn team_payload_round_trips_deterministically() {+ let payload = state(+ Some(Uuid::parse_str("8c06ab3e-693c-45a7-8f92-1b5a5bf876ac").unwrap()),+ NOW + 3_600,+ );++ let first_token = sign_installation_state(&payload, SECRET).unwrap();+ let second_token = sign_installation_state(&payload, SECRET).unwrap();++ assert_eq!(first_token, second_token);+ assert!(!first_token.contains('='));+ assert_eq!(+ verify_installation_state(&first_token, SECRET, NOW).unwrap(),+ payload+ );+}++#[test]+fn personal_payload_round_trips_without_team_field() {+ let payload = state(None, NOW + 3_600);+ let token = sign_installation_state(&payload, SECRET).unwrap();+ let encoded_payload = token.split_once('.').unwrap().0;+ let json = URL_SAFE_NO_PAD.decode(encoded_payload).unwrap();++ assert!(!String::from_utf8(json).unwrap().contains("team_id"));+ assert_eq!(+ verify_installation_state(&token, SECRET, NOW).unwrap(),+ payload+ );+}++#[test]+fn expiration_boundary_is_enforced() {+ let token = sign_installation_state(&state(None, NOW), SECRET).unwrap();++ assert_eq!(+ verify_installation_state(&token, SECRET, NOW - 1),+ Ok(state(None, NOW))+ );+ assert_eq!(+ verify_installation_state(&token, SECRET, NOW),+ Err(InstallationStateError::Expired)+ );+ assert_eq!(+ verify_installation_state(&token, SECRET, NOW + 1),+ Err(InstallationStateError::Expired)+ );+}++#[test]+fn malformed_tokens_are_rejected() {+ for token in [+ "",+ "payload",+ ".signature",+ "payload.",+ "payload.signature.extra",+ "%%%.signature",+ "payload.%%%",+ ] {+ assert!(+ verify_installation_state(token, SECRET, NOW).is_err(),+ "token should be rejected: {token}"+ );+ }++ let malformed_json = sign_raw_payload(b"not json");+ assert_eq!(+ verify_installation_state(&malformed_json, SECRET, NOW),+ Err(InstallationStateError::Malformed)+ );+}++#[test]+fn malformed_ids_are_rejected() {+ let malformed_team_id = sign_raw_payload(+ br#"{"macro_user_id":"macro|[email protected]","team_id":"not-a-uuid","exp":1730003600}"#,+ );+ let malformed_user_id = sign_raw_payload(+ br#"{"macro_user_id":"not-a-macro-user","team_id":"8c06ab3e-693c-45a7-8f92-1b5a5bf876ac","exp":1730003600}"#,+ );++ assert_eq!(+ verify_installation_state(&malformed_team_id, SECRET, NOW),+ Err(InstallationStateError::Malformed)+ );+ assert_eq!(+ verify_installation_state(&malformed_user_id, SECRET, NOW),+ Err(InstallationStateError::Malformed)+ );+}++#[test]+fn payload_tampering_is_rejected() {+ let token = sign_installation_state(&state(None, NOW + 3_600), SECRET).unwrap();+ let (encoded_payload, encoded_signature) = token.split_once('.').unwrap();+ let mut json: serde_json::Value =+ serde_json::from_slice(&URL_SAFE_NO_PAD.decode(encoded_payload).unwrap()).unwrap();+ json["exp"] = (NOW + 7_200).into();+ let tampered_payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json).unwrap());+ let tampered_token = format!("{tampered_payload}.{encoded_signature}");++ assert_eq!(+ verify_installation_state(&tampered_token, SECRET, NOW),+ Err(InstallationStateError::InvalidSignature)+ );+}++#[test]+fn signature_tampering_and_wrong_secrets_are_rejected() {+ let token = sign_installation_state(&state(None, NOW + 3_600), SECRET).unwrap();+ let (encoded_payload, encoded_signature) = token.split_once('.').unwrap();+ let mut signature = URL_SAFE_NO_PAD.decode(encoded_signature).unwrap();+ signature[0] ^= 1;+ let tampered_token = format!("{encoded_payload}.{}", URL_SAFE_NO_PAD.encode(signature));++ assert_eq!(+ verify_installation_state(&tampered_token, SECRET, NOW),+ Err(InstallationStateError::InvalidSignature)+ );+ assert_eq!(+ verify_installation_state(&token, b"wrong secret", NOW),+ Err(InstallationStateError::InvalidSignature)+ );+}diff --git a/crates/github/src/domain/models/mod.rs b/crates/github/src/domain/models/mod.rsindex 794baa50f9..d7e18a4028 100644--- a/crates/github/src/domain/models/mod.rs+++ b/crates/github/src/domain/models/mod.rs@@ -3,10 +3,14 @@#[cfg(test)]mod test;+mod installation_state;mod link;mod pull_request;mod sync;+pub use installation_state::{+ InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,+};pub use link::{GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubUserInfo};pub use pull_request::{EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,@@ -15,9 +19,10 @@ pub use pull_request::{GithubPullRequestRef, GithubPullRequestStatus,};pub use sync::{- GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,- MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,- extract_github_mentions, strip_markdown_code,+ GithubAppInstallationSource, GithubAuthenticatedUser, GithubInstallationAccessToken,+ GithubInstallationSetupAction, GithubKey, GithubSetupAccessToken, GithubUserInstallation,+ GithubUserInstallationsPage, GithubWebhookEventType, MacroTaskId, ResolvedTeamTaskReference,+ TeamTaskReference, ValidatedGithubWebhookEvent, extract_github_mentions, strip_markdown_code,};/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]@@ -37,4 +42,23 @@ pub enum GithubError {/// Invalid github webhook signature#[error("invalid github webhook signature")]InvalidWebhookSignature,+ /// The authenticated user is not a member of the requested team.+ #[error("user is not permitted to configure GitHub sync for this team")]+ Forbidden,+ /// The installation setup state is malformed, invalid, or expired.+ #[error("invalid installation setup state")]+ InvalidInstallationState,+ /// GitHub reported an unsupported installation setup action.+ #[error("invalid installation setup action")]+ InvalidInstallationSetupAction,+ /// A required installation callback field was absent.+ #[error("missing installation setup callback field: {0}")]+ MissingInstallationSetupField(&'static str),+ /// The installation is not visible to the GitHub user who completed setup.+ #[error("GitHub installation is not owned by the setup user")]+ InstallationNotOwned,+ /// The GitHub account completing setup is not linked to the Macro user the+ /// setup state was minted for.+ #[error("GitHub account is not linked to the Macro user who started setup")]+ SetupUserNotLinked,}diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rsindex f954f74d43..4598ac76a1 100644--- a/crates/github/src/domain/models/sync.rs+++ b/crates/github/src/domain/models/sync.rs@@ -7,6 +7,32 @@ use std::sync::LazyLock;use regex::Regex;use serde::Deserialize;+use super::GithubError;++/// Action reported by GitHub after an installation setup flow.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GithubInstallationSetupAction {+ /// A new GitHub App installation was created.+ Install,+ /// An existing installation's repository selection was updated.+ Update,+ /// Installation was requested from an organization administrator.+ Request,+}++impl TryFrom<&str> for GithubInstallationSetupAction {+ type Error = GithubError;++ fn try_from(value: &str) -> Result<Self, Self::Error> {+ match value {+ "install" => Ok(Self::Install),+ "update" => Ok(Self::Update),+ "request" => Ok(Self::Request),+ _ => Err(GithubError::InvalidInstallationSetupAction),+ }+ }+}+/// Github key used for tracking tasks#[derive(Debug, Clone)]pub struct GithubKey(String);@@ -30,6 +56,47 @@ impl AsRef<str> for GithubKey {}}+/// OAuth access token returned after exchanging a GitHub App setup code.+#[derive(Clone, Deserialize)]+pub struct GithubSetupAccessToken {+ access_token: String,+}++impl GithubSetupAccessToken {+ /// Creates an access token from GitHub's OAuth response value.+ pub fn new(access_token: String) -> Self {+ Self { access_token }+ }++ /// Returns the access token without transferring ownership of the secret.+ pub fn as_str(&self) -> &str {+ &self.access_token+ }+}++/// A GitHub App installation visible to an authenticated GitHub user.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]+pub struct GithubUserInstallation {+ /// GitHub's numeric installation identifier.+ pub id: u64,+}++/// The GitHub user behind an OAuth user access token.+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]+pub struct GithubAuthenticatedUser {+ /// GitHub's stable numeric user identifier.+ pub id: u64,+}++/// One page of installations visible to an authenticated GitHub user.+#[derive(Debug, Clone, Deserialize)]+pub struct GithubUserInstallationsPage {+ /// Number of installations visible across every page.+ pub total_count: u64,+ /// Installations returned on this page.+ pub installations: Vec<GithubUserInstallation>,+}+/// GitHub App installation access token response#[derive(Debug, Clone, Deserialize)]pub struct GithubInstallationAccessToken {@@ -273,6 +340,22 @@ impl ValidatedGithubWebhookEvent {.map(|id| id.to_string())}+ /// Extract the requester's GitHub user ID from the webhook payload.+ ///+ /// `requester` is only present on `installation` events created by an+ /// org admin approving another user's installation request; it identifies+ /// the user who originally requested the install (the `sender` is the+ /// approving admin). Uses the numeric `requester.id` rather than+ /// `requester.login` because GitHub usernames can change but user IDs are+ /// stable.+ pub fn requester_github_user_id(&self) -> Option<String> {+ self.payload+ .get("requester")+ .and_then(|r| r.get("id"))+ .and_then(|v| v.as_u64())+ .map(|id| id.to_string())+ }+/// Extract text from the PR context (title, body, branch) regardless of/// event type. For comment/review events this returns the surrounding PR/// info so callers can determine which task IDs are already associateddiff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rsindex 5d8c6cc6fc..c91e4d18fd 100644--- a/crates/github/src/domain/ports/sync.rs+++ b/crates/github/src/domain/ports/sync.rs@@ -5,9 +5,10 @@ use std::future::Future;use macro_user_id::user_id::MacroUserIdStr;use crate::domain::models::{- EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,- GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, MacroTaskId,- ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubAuthenticatedUser, GithubError,+ GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, GithubSetupAccessToken,+ GithubUserInstallation, MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference,+ ValidatedGithubWebhookEvent,};/// Repository for accessing github sync data from the database.@@ -101,32 +102,33 @@ pub trait GithubSyncRepo: Send + Sync + 'static {sources: &[GithubAppInstallationSource],) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Records the GitHub user that installed a GitHub App installation,- /// replacing any previously recorded installer for the installation.- fn upsert_installation_installer(+ /// Deletes all source associations for a GitHub App installation.+ /// Deleting an installation with no associations is a no-op (idempotent).+ fn delete_installation_sources(&self,installation_id: &str,- github_user_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Returns the installation IDs installed by the given GitHub user.- fn get_installation_ids_by_installer(+ /// Records the Macro source a GitHub user asked to sync when requesting an+ /// org install that awaits admin approval. Replaces any earlier pending+ /// request by the same GitHub user (latest intent wins).+ fn upsert_installation_request(&self,github_user_id: &str,- ) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;+ source: &GithubAppInstallationSource,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Deletes all source associations for a GitHub App installation.- /// Deleting an installation with no associations is a no-op (idempotent).- fn delete_installation_sources(+ /// Returns the pending installation request source for a GitHub user, if any.+ fn get_installation_request(&self,- installation_id: &str,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ github_user_id: &str,+ ) -> impl Future<Output = Result<Option<GithubAppInstallationSource>, Self::Err>> + Send;- /// Deletes the recorded installer for a GitHub App installation.- /// Deleting an installation with no recorded installer is a no-op (idempotent).- fn delete_installation_installer(+ /// Deletes a GitHub user's pending installation request.+ /// Deleting a missing request is a no-op (idempotent).+ fn delete_installation_request(&self,- installation_id: &str,+ github_user_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;}@@ -135,6 +137,26 @@ pub trait GithubSyncRepo: Send + Sync + 'static {/// Abstracts HTTP communication with GitHub's API so the service/// layer does not need to manage its own HTTP client.pub trait GithubSyncClient: Send + Sync + 'static {+ /// Exchanges a GitHub App setup callback code for a user access token.+ fn exchange_setup_code(+ &self,+ client_id: &str,+ client_secret: &str,+ code: &str,+ ) -> impl Future<Output = Result<GithubSetupAccessToken, GithubError>> + Send;++ /// Lists every GitHub App installation visible to a user access token.+ fn list_user_installations(+ &self,+ access_token: &str,+ ) -> impl Future<Output = Result<Vec<GithubUserInstallation>, GithubError>> + Send;++ /// Fetches the GitHub user behind a user access token.+ fn get_authenticated_user(+ &self,+ access_token: &str,+ ) -> impl Future<Output = Result<GithubAuthenticatedUser, GithubError>> + Send;+/// Generates an installation access token for a given GitHub App installation.fn generate_installation_access_token(&self,@@ -186,20 +208,40 @@ pub trait GithubSyncService: Send + Sync + 'static {webhook_event: &ValidatedGithubWebhookEvent,) -> impl Future<Output = Result<(), GithubError>> + Send;- /// Returns the github sync app installation url- fn get_github_sync_app_url(&self) -> &str;-- /// Associates any GitHub App installations installed by the given GitHub- /// user with that user's Macro sources (teams or user), then backfills- /// open pull requests for newly associated installations.+ /// Begins an authenticated GitHub App installation setup flow.+ fn begin_installation_setup(+ &self,+ _macro_user_id: &MacroUserIdStr<'_>,+ _team_id: Option<uuid::Uuid>,+ ) -> impl Future<Output = Result<String, GithubError>> + Send {+ async {+ Err(GithubError::Internal(anyhow::anyhow!(+ "installation setup is unsupported"+ )))+ }+ }++ /// Completes an installation setup callback after verifying its state,+ /// that the completing GitHub account is linked to the state's Macro user,+ /// and (for install/update) that the account owns the installation.+ fn complete_installation_setup(+ &self,+ _state: &str,+ _code: Option<&str>,+ _installation_id: Option<u64>,+ _setup_action: &str,+ ) -> impl Future<Output = Result<(), GithubError>> + Send {+ async {+ Err(GithubError::Internal(anyhow::anyhow!(+ "installation setup is unsupported"+ )))+ }+ }++ /// Returns the raw installation URL for legacy inbound adapters.///- /// Intended to be called when a `github_links` row is created after the- /// app was installed, since the installation webhook could not resolve a- /// Macro user at install time.- fn associate_installations_for_github_user(- &self,- github_user_id: &str,- ) -> impl Future<Output = Result<(), GithubError>> + Send;+ /// New installation flows must use [`GithubSyncService::begin_installation_setup`].+ fn get_github_sync_app_url(&self) -> &str;/// Generates an installation access token for the github sync appfn generate_installation_access_token(diff --git a/crates/github/src/domain/service/sync/handle_installation.rs b/crates/github/src/domain/service/sync/handle_installation.rsindex 3ddf28c83b..d949b08e6e 100644--- a/crates/github/src/domain/service/sync/handle_installation.rs+++ b/crates/github/src/domain/service/sync/handle_installation.rs@@ -20,7 +20,12 @@ impl<{/// Handle `installation` events with action `created`.///- /// Associates the GitHub App installation with the installer's team or user source.+ /// Completes the org-approval install flow: when an admin approves another+ /// user's installation request, the payload's `requester` identifies who+ /// asked, and their pending installation request (recorded by the+ /// authenticated setup callback) carries the Macro source to associate.+ /// Installations created directly through the authenticated setup flow+ /// have no `requester` and are associated by the setup callback instead.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_installation_created(&self,@@ -30,38 +35,46 @@ impl<.installation_id().ok_or_else(|| GithubError::Internal(anyhow::anyhow!("missing installation.id")))?;- let sender_github_user_id = event.sender_github_user_id().ok_or_else(|| {- GithubError::Internal(anyhow::anyhow!("missing sender.id in installation event"))- })?;-- tracing::info!(installation_id, "processing installation created event");+ let Some(requester_github_user_id) = event.requester_github_user_id() else {+ tracing::info!(+ installation_id,+ "installation created without a requester; direct installs are associated by the authenticated setup flow"+ );+ return Ok(());+ };- // Always record the installer, even when no link exists yet: it lets a- // later github_links creation associate this installation retroactively.- self.repo- .upsert_installation_installer(&installation_id.to_string(), &sender_github_user_id)+ let Some(source) = self+ .repo+ .get_installation_request(&requester_github_user_id).await- .map_err(|e| GithubError::Internal(e.into()))?;-- let sources = self.sources_for_github_user(&sender_github_user_id).await?;- if sources.is_empty() {+ .map_err(|e| GithubError::Internal(e.into()))?+ else {tracing::warn!(installation_id,- "no github link found for sender, cannot associate installation with a source"+ requester_github_user_id,+ "no pending installation request found for approved installation");return Ok(());- }+ };++ self.associate_installation_with_sources(installation_id, &[source])+ .await?;- self.associate_installation_with_sources(installation_id, &sources)+ // Deleted only after association succeeds so a webhook redelivery can+ // retry; a redelivery after deletion finds no pending request and is a+ // no-op.+ self.repo+ .delete_installation_request(&requester_github_user_id).await+ .map_err(|e| GithubError::Internal(e.into()))?;++ Ok(())}/// Handle `installation` events with action `deleted`.///- /// Removes the installation's source associations and recorded installer- /// so the installation is no longer used for PR backfills or retroactive- /// association when a github link is created later. Idempotent: GitHub- /// retries webhooks, so deleting an already-removed installation succeeds.+ /// Removes the installation's source associations. Idempotent: GitHub retries+ /// webhooks, so deleting an already-removed installation succeeds.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_installation_deleted(&self,@@ -79,66 +92,9 @@ impl<.await.map_err(|e| GithubError::Internal(e.into()))?;- self.repo- .delete_installation_installer(&installation_id)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-Ok(())}- /// Compute the Macro sources (teams or users) for every Macro user linked- /// to the given GitHub user. Returns an empty list when no link exists.- pub(crate) async fn sources_for_github_user(- &self,- github_user_id: &str,- ) -> Result<Vec<GithubAppInstallationSource>, GithubError> {- let links = self- .repo- .get_macro_ids_by_github_user_ids(std::slice::from_ref(&github_user_id.to_string()))- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let macro_ids = links.get(github_user_id).cloned().unwrap_or_default();-- // A GitHub account may be linked to several Macro users; collect the- // team/user source of every linked user.- let mut seen = std::collections::HashSet::new();- let mut sources = Vec::new();- for macro_id in macro_ids {- let team_ids = self- .repo- .get_user_team_ids(¯o_id)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- if team_ids.is_empty() {- tracing::info!(- github_user_id,- "user has no teams, using user source for installation association"- );- let source = GithubAppInstallationSource::User(macro_id);- if seen.insert(source.clone()) {- sources.push(source);- }- } else {- tracing::info!(- github_user_id,- team_count = team_ids.len(),- "using team sources for installation association"- );- for team_id in team_ids {- let source = GithubAppInstallationSource::Team(team_id);- if seen.insert(source.clone()) {- sources.push(source);- }- }- }- }-- Ok(sources)- }-/// Persist the installation-to-source associations and backfill open pull/// requests visible to the installation.pub(crate) async fn associate_installation_with_sources(diff --git a/crates/github/src/domain/service/sync/mod.rs b/crates/github/src/domain/service/sync/mod.rsindex 0c0868fdad..7319084876 100644--- a/crates/github/src/domain/service/sync/mod.rs+++ b/crates/github/src/domain/service/sync/mod.rs@@ -13,9 +13,11 @@ mod notify_pr_checks;use crate::domain::{models::{EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,- GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,- GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId,+ GithubAppInstallationSource, GithubError, GithubInstallationAccessToken,+ GithubInstallationSetupAction, GithubKey, GithubPullRequestDetails,+ GithubPullRequestStatus, GithubWebhookEventType, InstallationState, MacroTaskId,ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,+ sign_installation_state, verify_installation_state,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -46,12 +48,16 @@ maybe_env_vars! {pub struct GithubSyncConfig {/// The webhook secret used to validate github webhook eventspub webhook_secret: String,- /// The url to the github sync app installation page+ /// The URL to the GitHub Sync App profile or installation page.pub github_sync_app_url: String,/// The PEM key for the github sync apppub sync_app_pem: String,/// The client id for the github sync apppub sync_app_client_id: String,+ /// The client secret for the GitHub sync App's setup OAuth exchange.+ pub sync_app_client_secret: String,+ /// Secret used to sign installation setup state carried through GitHub.+ pub installation_state_secret: String,}/// The concrete github sync service implementation.@@ -990,63 +996,143 @@ impl<}}- fn get_github_sync_app_url(&self) -> &str {- &self.config.github_sync_app_url+ #[tracing::instrument(skip(self), fields(macro_user_id = %macro_user_id), err)]+ async fn begin_installation_setup(+ &self,+ macro_user_id: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ team_id: Option<uuid::Uuid>,+ ) -> Result<String, GithubError> {+ if let Some(team_id) = team_id {+ let team_ids = self+ .repo+ .get_user_team_ids(macro_user_id.as_ref())+ .await+ .map_err(|error| GithubError::Internal(error.into()))?;+ if !team_ids.contains(&team_id) {+ return Err(GithubError::Forbidden);+ }+ }++ let state = InstallationState {+ macro_user_id: macro_user_id::user_id::MacroUserIdStr::try_from(+ macro_user_id.as_ref().to_string(),+ )+ .map_err(|error| GithubError::Internal(error.into()))?,+ team_id,+ exp: chrono::Utc::now().timestamp() + 60 * 60,+ };+ let signed_state =+ sign_installation_state(&state, self.config.installation_state_secret.as_bytes())+ .map_err(|error| GithubError::Internal(error.into()))?;++ let mut installation_url = url::Url::parse(&self.config.github_sync_app_url)+ .map_err(|error| GithubError::Internal(error.into()))?;+ let configured_path = installation_url.path().trim_end_matches('/');+ if !configured_path.ends_with("/installations/new") {+ installation_url.set_path(&format!("{configured_path}/installations/new"));+ }+ installation_url+ .query_pairs_mut()+ .append_pair("state", &signed_state);++ Ok(installation_url.into())}- #[tracing::instrument(skip(self), err)]- async fn associate_installations_for_github_user(+ #[tracing::instrument(skip(self, state, code), err)]+ async fn complete_installation_setup(&self,- github_user_id: &str,+ state: &str,+ code: Option<&str>,+ installation_id: Option<u64>,+ setup_action: &str,) -> Result<(), GithubError> {- let installation_ids = self- .repo- .get_installation_ids_by_installer(github_user_id)- .await- .map_err(|e| GithubError::Internal(e.into()))?;+ let state = verify_installation_state(+ state,+ self.config.installation_state_secret.as_bytes(),+ chrono::Utc::now().timestamp(),+ )+ .map_err(|_| GithubError::InvalidInstallationState)?;+ let setup_action = GithubInstallationSetupAction::try_from(setup_action)?;++ let code = code.ok_or(GithubError::MissingInstallationSetupField("code"))?;+ // A request callback carries no installation_id: the installation only+ // comes into existence when an org admin approves.+ let installation_id = match setup_action {+ GithubInstallationSetupAction::Request => None,+ GithubInstallationSetupAction::Install | GithubInstallationSetupAction::Update => Some(+ installation_id.ok_or(GithubError::MissingInstallationSetupField(+ "installation_id",+ ))?,+ ),+ };- if installation_ids.is_empty() {- tracing::debug!(github_user_id, "no installations recorded for github user");- return Ok(());- }+ let access_token = self+ .client+ .exchange_setup_code(+ &self.config.sync_app_client_id,+ &self.config.sync_app_client_secret,+ code,+ )+ .await?;- let sources = self.sources_for_github_user(github_user_id).await?;- if sources.is_empty() {- tracing::debug!(- github_user_id,- "no macro sources found for github user, skipping installation association"- );- return Ok(());+ // The state is a bearer token carried through GitHub in a URL, so it+ // must not be honored on signature and expiry alone: require the+ // GitHub account completing the flow to be linked to the Macro user+ // the state was minted for. This stops a leaked or attacker-minted+ // state from binding someone else's installation to a foreign source.+ let github_user_id = self+ .client+ .get_authenticated_user(access_token.as_str())+ .await?+ .id+ .to_string();+ let links = self+ .repo+ .get_macro_ids_by_github_user_ids(std::slice::from_ref(&github_user_id))+ .await+ .map_err(|error| GithubError::Internal(error.into()))?;+ let completer_is_state_user = links.get(&github_user_id).is_some_and(|macro_ids| {+ macro_ids+ .iter()+ .any(|id| id == state.macro_user_id.as_ref())+ });+ if !completer_is_state_user {+ return Err(GithubError::SetupUserNotLinked);}- for installation_id in installation_ids {- let installation_id: u64 = match installation_id.parse() {- Ok(id) => id,- Err(error) => {- tracing::error!(- error=?error,- installation_id,- "stored installation id is not a u64"- );- continue;- }- };+ let source = match state.team_id {+ Some(team_id) => GithubAppInstallationSource::Team(team_id),+ None => GithubAppInstallationSource::User(state.macro_user_id.into()),+ };- // Keep going on failure so one broken installation doesn't block- // associating the rest.- self.associate_installation_with_sources(installation_id, &sources)+ let Some(installation_id) = installation_id else {+ // Park the requested source keyed by the requester's GitHub+ // identity so the installation.created webhook can complete the+ // association once an org admin approves.+ return self+ .repo+ .upsert_installation_request(&github_user_id, &source).await- .inspect_err(|error| {- tracing::error!(- error=?error,- installation_id,- "failed to associate installation with sources"- );- })- .ok();+ .map_err(|error| GithubError::Internal(error.into()));+ };++ let installations = self+ .client+ .list_user_installations(access_token.as_str())+ .await?;+ if !installations+ .iter()+ .any(|installation| installation.id == installation_id)+ {+ return Err(GithubError::InstallationNotOwned);}- Ok(())+ self.associate_installation_with_sources(installation_id, &[source])+ .await+ }++ fn get_github_sync_app_url(&self) -> &str {+ &self.config.github_sync_app_url}#[tracing::instrument(skip(self), err)]diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex 41cc93a287..8c1d77ec4a 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -3,10 +3,11 @@ use std::sync::{Arc, Mutex};use crate::domain::{models::{- EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,- GithubInstallationAccessToken, GithubKey, GithubPullRequestCheckRun,- GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestStatus, MacroTaskId,- ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubAuthenticatedUser,+ GithubError, GithubInstallationAccessToken, GithubKey, GithubPullRequestCheckRun,+ GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestStatus,+ GithubSetupAccessToken, GithubUserInstallation, MacroTaskId, ResolvedTeamTaskReference,+ TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -45,6 +46,9 @@ use super::*;/// UUID that corresponds to the short ID `2BuyvtY3aeEvHx4uG8iD51`.const KNOWN_TASK_UUID: &str = "0d0dc589-f301-43f1-8b11-4ab448ca4bb4";+/// GitHub user id returned by [`StubSyncClient::get_authenticated_user`].+const TEST_GITHUB_USER_ID: u64 = 987654;+/// SAFETY: This is used for testing only/// Minimal RSA private key used only for test JWT signing.const TEST_PEM: &str = "-----BEGIN RSA PRIVATE KEY-----@@ -321,8 +325,8 @@ struct StubSyncRepo {installation_source_rows: Mutex<HashMap<String, HashSet<GithubAppInstallationSource>>>,/// Recorded installation source upserts: (installation_id, sources).installation_sources: Mutex<Vec<(String, Vec<GithubAppInstallationSource>)>>,- /// Installer github user id keyed by installation id.- installation_installers: Mutex<HashMap<String, String>>,+ /// Pending installation requests keyed by requester github user id.+ installation_requests: Mutex<HashMap<String, GithubAppInstallationSource>>,}impl StubSyncRepo {@@ -336,7 +340,7 @@ impl StubSyncRepo {team_members: Mutex::new(HashMap::new()),installation_source_rows: Mutex::new(HashMap::new()),installation_sources: Mutex::new(Vec::new()),- installation_installers: Mutex::new(HashMap::new()),+ installation_requests: Mutex::new(HashMap::new()),}}@@ -418,16 +422,20 @@ impl StubSyncRepo {self.installation_sources.lock().unwrap().clone()}- fn with_installation_installer(self, installation_id: &str, github_user_id: &str) -> Self {- self.installation_installers+ fn with_installation_request(+ self,+ github_user_id: &str,+ source: GithubAppInstallationSource,+ ) -> Self {+ self.installation_requests.lock().unwrap()- .insert(installation_id.to_string(), github_user_id.to_string());+ .insert(github_user_id.to_string(), source);self}- fn installation_installers(&self) -> HashMap<String, String> {- self.installation_installers.lock().unwrap().clone()+ fn installation_requests(&self) -> HashMap<String, GithubAppInstallationSource> {+ self.installation_requests.lock().unwrap().clone()}}@@ -591,47 +599,43 @@ impl GithubSyncRepo for StubSyncRepo {Ok(())}- async fn upsert_installation_installer(- &self,- installation_id: &str,- github_user_id: &str,- ) -> Result<(), Self::Err> {- self.installation_installers+ async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {+ self.installation_source_rows.lock().unwrap()- .insert(installation_id.to_string(), github_user_id.to_string());+ .remove(installation_id);Ok(())}- async fn get_installation_ids_by_installer(+ async fn upsert_installation_request(&self,github_user_id: &str,- ) -> Result<Vec<String>, Self::Err> {- let mut installation_ids: Vec<String> = self- .installation_installers+ source: &GithubAppInstallationSource,+ ) -> Result<(), Self::Err> {+ self.installation_requests.lock().unwrap()- .iter()- .filter(|(_, installer)| installer.as_str() == github_user_id)- .map(|(installation_id, _)| installation_id.clone())- .collect();- installation_ids.sort();- Ok(installation_ids)+ .insert(github_user_id.to_string(), source.clone());+ Ok(())}- async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {- self.installation_source_rows+ async fn get_installation_request(+ &self,+ github_user_id: &str,+ ) -> Result<Option<GithubAppInstallationSource>, Self::Err> {+ Ok(self+ .installation_requests.lock().unwrap()- .remove(installation_id);- Ok(())+ .get(github_user_id)+ .cloned())}- async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {- self.installation_installers+ async fn delete_installation_request(&self, github_user_id: &str) -> Result<(), Self::Err> {+ self.installation_requests.lock().unwrap()- .remove(installation_id);+ .remove(github_user_id);Ok(())}}@@ -678,6 +682,14 @@ struct PullRequestDetailsCall {}struct StubSyncClient {+ setup_code_exchange_calls: Mutex<Vec<(String, String, String)>>,+ user_installation_list_calls: Mutex<Vec<String>>,+ user_installations: Mutex<Vec<GithubUserInstallation>>,+ authenticated_user_calls: Mutex<Vec<String>>,+ authenticated_user_id: Mutex<u64>,+ fail_setup_code_exchange: Mutex<bool>,+ fail_user_installation_list: Mutex<bool>,+ fail_get_authenticated_user: Mutex<bool>,pr_comments: Mutex<Vec<PrCommentCall>>,pull_request_details: Mutex<HashMap<String, GithubPullRequestDetails>>,pull_request_details_calls: Mutex<Vec<PullRequestDetailsCall>>,@@ -688,6 +700,14 @@ struct StubSyncClient {impl StubSyncClient {fn new() -> Self {Self {+ setup_code_exchange_calls: Mutex::new(Vec::new()),+ user_installation_list_calls: Mutex::new(Vec::new()),+ user_installations: Mutex::new(Vec::new()),+ authenticated_user_calls: Mutex::new(Vec::new()),+ authenticated_user_id: Mutex::new(TEST_GITHUB_USER_ID),+ fail_setup_code_exchange: Mutex::new(false),+ fail_user_installation_list: Mutex::new(false),+ fail_get_authenticated_user: Mutex::new(false),pr_comments: Mutex::new(Vec::new()),pull_request_details: Mutex::new(HashMap::new()),pull_request_details_calls: Mutex::new(Vec::new()),@@ -696,6 +716,37 @@ impl StubSyncClient {}}+ fn set_user_installations(&self, installation_ids: &[u64]) {+ *self.user_installations.lock().unwrap() = installation_ids+ .iter()+ .map(|id| GithubUserInstallation { id: *id })+ .collect();+ }++ fn fail_setup_code_exchange(&self) {+ *self.fail_setup_code_exchange.lock().unwrap() = true;+ }++ fn fail_user_installation_list(&self) {+ *self.fail_user_installation_list.lock().unwrap() = true;+ }++ fn fail_get_authenticated_user(&self) {+ *self.fail_get_authenticated_user.lock().unwrap() = true;+ }++ fn authenticated_user_calls(&self) -> Vec<String> {+ self.authenticated_user_calls.lock().unwrap().clone()+ }++ fn setup_code_exchange_calls(&self) -> Vec<(String, String, String)> {+ self.setup_code_exchange_calls.lock().unwrap().clone()+ }++ fn user_installation_list_calls(&self) -> Vec<String> {+ self.user_installation_list_calls.lock().unwrap().clone()+ }+fn pr_comments(&self) -> Vec<PrCommentCall> {self.pr_comments.lock().unwrap().clone()}@@ -731,6 +782,55 @@ impl StubSyncClient {}impl GithubSyncClient for StubSyncClient {+ async fn exchange_setup_code(+ &self,+ client_id: &str,+ client_secret: &str,+ code: &str,+ ) -> Result<GithubSetupAccessToken, GithubError> {+ self.setup_code_exchange_calls.lock().unwrap().push((+ client_id.to_string(),+ client_secret.to_string(),+ code.to_string(),+ ));+ if *self.fail_setup_code_exchange.lock().unwrap() {+ return Err(GithubError::Internal(anyhow::anyhow!("exchange failed")));+ }+ Ok(GithubSetupAccessToken::new("test-user-token".to_string()))+ }++ async fn list_user_installations(+ &self,+ access_token: &str,+ ) -> Result<Vec<GithubUserInstallation>, GithubError> {+ self.user_installation_list_calls+ .lock()+ .unwrap()+ .push(access_token.to_string());+ if *self.fail_user_installation_list.lock().unwrap() {+ return Err(GithubError::Internal(anyhow::anyhow!("listing failed")));+ }+ Ok(self.user_installations.lock().unwrap().clone())+ }++ async fn get_authenticated_user(+ &self,+ access_token: &str,+ ) -> Result<GithubAuthenticatedUser, GithubError> {+ self.authenticated_user_calls+ .lock()+ .unwrap()+ .push(access_token.to_string());+ if *self.fail_get_authenticated_user.lock().unwrap() {+ return Err(GithubError::Internal(anyhow::anyhow!(+ "authenticated user lookup failed"+ )));+ }+ Ok(GithubAuthenticatedUser {+ id: *self.authenticated_user_id.lock().unwrap(),+ })+ }+async fn generate_installation_access_token(&self,_jwt: &str,@@ -1047,9 +1147,12 @@ fn make_sync_service_with_repo_and_notification_ingress(GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),- github_sync_app_url: "test".to_string(),+ github_sync_app_url: "https://github.com/apps/test/installations/new?existing=1"+ .to_string(),sync_app_pem: TEST_PEM.to_string(),sync_app_client_id: "test-sync-app-client-id".to_string(),+ sync_app_client_secret: "test-sync-app-client-secret".to_string(),+ installation_state_secret: "test-installation-state-secret".to_string(),},doc_service,foreign_entity_service,@@ -1066,9 +1169,12 @@ fn make_sync_service_with_doc_service() -> (TestGithubSyncService, Arc<StubDocumlet service = GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),- github_sync_app_url: "test".to_string(),+ github_sync_app_url: "https://github.com/apps/test/installations/new?existing=1"+ .to_string(),sync_app_pem: TEST_PEM.to_string(),sync_app_client_id: "test-sync-app-client-id".to_string(),+ sync_app_client_secret: "test-sync-app-client-secret".to_string(),+ installation_state_secret: "test-installation-state-secret".to_string(),},doc_service.clone(),foreign_entity_service,@@ -2716,15 +2822,22 @@ async fn github_pr_status_changed_edited_does_not_notify() {}#[tokio::test]-async fn github_pr_status_changed_installation_backfill_does_not_notify() {- let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");- let service = make_sync_service_with_repo(repo);+async fn authenticated_installation_setup_backfill_does_not_notify() {+ let service = make_setup_sync_service();+ service.client.set_user_installations(&[12345]);service.client.set_open_pull_requests(vec![backfilled_pull_request("Backfilled PR")]);- let event = installation_created_event(12345, 12345);- service.process_webhook_event(&event).await.unwrap();+ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("setup-code"),+ Some(12345),+ "install",+ )+ .await+ .unwrap();assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);assert!(service.notification_ingress.requests().is_empty());@@ -3918,189 +4031,101 @@ fn installation_created_event(sender_id: u64, installation_id: u64) -> Validated)}-#[tokio::test]-async fn installation_created_associates_teams() {- let team_a: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();- let team_b: uuid::Uuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap();-- let repo = StubSyncRepo::new()- .with_github_link("12345", "macro|[email protected]")- .with_user_teams("macro|[email protected]", vec![team_a, team_b]);-- let service = make_sync_service_with_repo(repo);- let event = installation_created_event(12345, 99999);-- service.process_webhook_event(&event).await.unwrap();-- let sources = service.repo.installation_sources();- assert_eq!(- sources,- vec![(- "99999".to_string(),- vec![- GithubAppInstallationSource::Team(team_a),- GithubAppInstallationSource::Team(team_b),- ],- )]- );+/// An `installation.created` event emitted when an org admin approves another+/// user's installation request: the `sender` is the approving admin and the+/// `requester` is who originally asked.+fn approved_installation_created_event(+ requester_id: u64,+ installation_id: u64,+) -> ValidatedGithubWebhookEvent {+ ValidatedGithubWebhookEvent::new(+ "installation".to_string(),+ serde_json::json!({+ "action": "created",+ "installation": { "id": installation_id },+ "sender": { "login": "org-admin", "id": 111 },+ "requester": { "login": "org-member", "id": requester_id }+ }),+ )}#[tokio::test]-async fn installation_created_backfills_open_pr_for_single_source() {- let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");-- let service = make_sync_service_with_repo(repo);- let doc_service = service.document_service.clone();- let foreign_entity_service = service.foreign_entity_service.clone();- let pull_request = backfilled_pull_request("fixes MACRO-2BuyvtY3aeEvHx4uG8iD51");- let expected_metadata = serde_json::to_value(&pull_request).unwrap();- service.client.set_open_pull_requests(vec![pull_request]);+async fn installation_created_without_requester_is_noop() {+ // Direct installs are associated by the authenticated setup callback, not+ // the webhook, and the sender must never be used as an association+ // heuristic.+ let service = make_sync_service();let event = installation_created_event(12345, 99999);service.process_webhook_event(&event).await.unwrap();- assert_eq!(- service.client.list_open_pull_requests_calls(),- vec!["test-token".to_string()]- );-- let foreign_entities = foreign_entity_service.foreign_entities();- assert_eq!(foreign_entities.len(), 1);-- let foreign_entity = &foreign_entities[0];- assert_eq!(foreign_entity.foreign_entity_id, "my-org/my-repo/pull/42");- assert_eq!(- foreign_entity.foreign_entity_source,- GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE- );- assert_eq!(foreign_entity.stored_for_id, "macro|[email protected]");- assert_eq!(foreign_entity.stored_for_auth_entity, "user");- assert_eq!(foreign_entity.metadata, expected_metadata);- assert_eq!(foreign_entity_service.create_calls().len(), 1);- assert!(foreign_entity_service.patch_calls().is_empty());- assert!(service.client.pr_comments().is_empty());- assert!(doc_service.task_status_calls().is_empty());+ assert!(service.repo.installation_sources().is_empty());+ assert!(service.client.setup_code_exchange_calls().is_empty());+ assert!(service.client.user_installation_list_calls().is_empty());+ assert!(service.client.list_open_pull_requests_calls().is_empty());+ assert!(service.foreign_entity_service.foreign_entities().is_empty());}#[tokio::test]-async fn installation_created_backfills_open_pr_for_multiple_sources() {- let team_a: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();- let team_b: uuid::Uuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap();+async fn installation_created_with_requester_associates_pending_request_source() {+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();let repo = StubSyncRepo::new()- .with_github_link("12345", "macro|[email protected]")- .with_user_teams("macro|[email protected]", vec![team_a, team_b]);-+ .with_installation_request("12345", GithubAppInstallationSource::Team(team_id));let service = make_sync_service_with_repo(repo);- let doc_service = service.document_service.clone();- let foreign_entity_service = service.foreign_entity_service.clone();- let pull_request = backfilled_pull_request("backfilled PR");- let expected_metadata = serde_json::to_value(&pull_request).unwrap();- service.client.set_open_pull_requests(vec![pull_request]);- let event = installation_created_event(12345, 99999);+ let event = approved_installation_created_event(12345, 99999);service.process_webhook_event(&event).await.unwrap();assert_eq!(- service.client.list_open_pull_requests_calls(),- vec!["test-token".to_string()]+ service.repo.installation_sources(),+ vec![(+ "99999".to_string(),+ vec![GithubAppInstallationSource::Team(team_id)]+ )]);+ // The pending request is consumed once the association lands.+ assert!(service.repo.installation_requests().is_empty());+}- let mut foreign_entities = foreign_entity_service.foreign_entities();- foreign_entities.sort_by(|left, right| left.stored_for_id.cmp(&right.stored_for_id));- assert_eq!(foreign_entities.len(), 2);+#[tokio::test]+async fn installation_created_with_unknown_requester_is_noop() {+ let service = make_sync_service();+ let event = approved_installation_created_event(12345, 99999);- for foreign_entity in &foreign_entities {- assert_eq!(foreign_entity.foreign_entity_id, "my-org/my-repo/pull/42");- assert_eq!(- foreign_entity.foreign_entity_source,- GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE- );- assert_eq!(foreign_entity.stored_for_auth_entity, "team");- assert_eq!(foreign_entity.metadata, expected_metadata);- }+ service.process_webhook_event(&event).await.unwrap();- assert_eq!(foreign_entities[0].stored_for_id, team_a.to_string());- assert_eq!(foreign_entities[1].stored_for_id, team_b.to_string());- assert_eq!(foreign_entity_service.create_calls().len(), 2);- assert!(foreign_entity_service.patch_calls().is_empty());- assert!(service.client.pr_comments().is_empty());- assert!(doc_service.task_status_calls().is_empty());+ assert!(service.repo.installation_sources().is_empty());}#[tokio::test]-async fn installation_created_backfill_is_idempotent() {+async fn installation_created_redelivery_after_association_is_noop() {let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();let repo = StubSyncRepo::new()- .with_github_link("12345", "macro|[email protected]")- .with_user_teams("macro|[email protected]", vec![team_id]);-+ .with_installation_request("12345", GithubAppInstallationSource::Team(team_id));let service = make_sync_service_with_repo(repo);- let doc_service = service.document_service.clone();- let foreign_entity_service = service.foreign_entity_service.clone();- let pull_request = backfilled_pull_request("fixes MACRO-2BuyvtY3aeEvHx4uG8iD51");- let expected_metadata = serde_json::to_value(&pull_request).unwrap();- service.client.set_open_pull_requests(vec![pull_request]);- let event = installation_created_event(12345, 99999);+ let event = approved_installation_created_event(12345, 99999);+ // GitHub retries webhooks: a redelivery after the pending request was+ // consumed must succeed without re-associating.service.process_webhook_event(&event).await.unwrap();service.process_webhook_event(&event).await.unwrap();- assert_eq!(- service.client.list_open_pull_requests_calls(),- vec!["test-token".to_string(), "test-token".to_string()]- );-- let foreign_entities = foreign_entity_service.foreign_entities();- assert_eq!(foreign_entities.len(), 1);- assert_eq!(- foreign_entities[0].foreign_entity_id,- "my-org/my-repo/pull/42"- );- assert_eq!(foreign_entities[0].stored_for_id, team_id.to_string());- assert_eq!(foreign_entities[0].stored_for_auth_entity, "team");- assert_eq!(foreign_entities[0].metadata, expected_metadata);- assert_eq!(foreign_entity_service.create_calls().len(), 1);-- let patch_calls = foreign_entity_service.patch_calls();- assert_eq!(patch_calls.len(), 1);- assert_eq!(patch_calls[0].0, foreign_entities[0].id);- assert_eq!(patch_calls[0].1.metadata, Some(expected_metadata));- assert!(service.client.pr_comments().is_empty());- assert!(doc_service.task_status_calls().is_empty());+ assert_eq!(service.repo.installation_sources().len(), 1);}#[tokio::test]-async fn installation_created_no_github_link() {+async fn installation_created_missing_installation_id_errors() {let service = make_sync_service();- let event = installation_created_event(99999, 11111);-- // No github link for sender — should succeed without inserting any sources- service.process_webhook_event(&event).await.unwrap();-- assert!(service.repo.installation_sources().is_empty());- assert!(service.client.list_open_pull_requests_calls().is_empty());-- // The installer is still recorded so a later link can associate the- // installation retroactively.- assert_eq!(- service.repo.installation_installers(),- HashMap::from([("11111".to_string(), "99999".to_string())])+ let event = ValidatedGithubWebhookEvent::new(+ "installation".to_string(),+ serde_json::json!({+ "action": "created",+ "sender": { "login": "org-admin", "id": 111 },+ "requester": { "login": "org-member", "id": 12345 }+ }),);-}-#[tokio::test]-async fn installation_created_records_installer_with_github_link() {- let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");-- let service = make_sync_service_with_repo(repo);- let event = installation_created_event(12345, 11111);-- service.process_webhook_event(&event).await.unwrap();-- assert_eq!(- service.repo.installation_installers(),- HashMap::from([("11111".to_string(), "12345".to_string())])- );+ service.process_webhook_event(&event).await.unwrap_err();}// ---------------------------------------------------------------------------@@ -4119,7 +4144,7 @@ fn installation_deleted_event(sender_id: u64, installation_id: u64) -> Validated}#[tokio::test]-async fn installation_deleted_removes_sources_and_installer() {+async fn installation_deleted_removes_only_installation_sources() {let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();let repo = StubSyncRepo::new()@@ -4129,9 +4154,7 @@ async fn installation_deleted_removes_sources_and_installer() {vec![GithubAppInstallationSource::User("macro|[email protected]".to_string(),)],- )- .with_installation_installer("99999", "12345")- .with_installation_installer("88888", "67890");+ );let service = make_sync_service_with_repo(repo);let event = installation_deleted_event(12345, 99999);@@ -4146,11 +4169,6 @@ async fn installation_deleted_removes_sources_and_installer() {.unwrap().is_empty());- assert_eq!(- service.repo.installation_installers(),- HashMap::from([("88888".to_string(), "67890".to_string())])- );-// Other installations are untouched.assert_eq!(service@@ -4174,7 +4192,14 @@ async fn installation_deleted_unknown_installation_succeeds() {service.process_webhook_event(&event).await.unwrap();service.process_webhook_event(&event).await.unwrap();- assert!(service.repo.installation_installers().is_empty());+ assert!(+ service+ .repo+ .get_installation_sources("99999")+ .await+ .unwrap()+ .is_empty()+ );}#[tokio::test]@@ -4191,143 +4216,6 @@ async fn installation_deleted_missing_installation_id_errors() {service.process_webhook_event(&event).await.unwrap_err();}-#[tokio::test]-async fn associate_installations_for_github_user_associates_and_backfills() {- let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();-- // The installation was created before the user linked github: only the- // installer is recorded, no sources. The github link now exists.- let repo = StubSyncRepo::new()- .with_installation_installer("99999", "12345")- .with_github_link("12345", "macro|[email protected]")- .with_user_teams("macro|[email protected]", vec![team_id]);-- let service = make_sync_service_with_repo(repo);- let foreign_entity_service = service.foreign_entity_service.clone();- let pull_request = backfilled_pull_request("backfilled PR");- service.client.set_open_pull_requests(vec![pull_request]);-- service- .associate_installations_for_github_user("12345")- .await- .unwrap();-- let sources = service.repo.installation_sources();- assert_eq!(- sources,- vec![(- "99999".to_string(),- vec![GithubAppInstallationSource::Team(team_id)],- )]- );-- assert_eq!(- service.client.list_open_pull_requests_calls(),- vec!["test-token".to_string()]- );- let foreign_entities = foreign_entity_service.foreign_entities();- assert_eq!(foreign_entities.len(), 1);- assert_eq!(foreign_entities[0].stored_for_id, team_id.to_string());- assert_eq!(foreign_entities[0].stored_for_auth_entity, "team");-}--#[tokio::test]-async fn associate_installations_for_github_user_associates_multiple_installations() {- let repo = StubSyncRepo::new()- .with_installation_installer("11111", "12345")- .with_installation_installer("22222", "12345")- .with_installation_installer("33333", "someone-else")- .with_github_link("12345", "macro|[email protected]");-- let service = make_sync_service_with_repo(repo);-- service- .associate_installations_for_github_user("12345")- .await- .unwrap();-- let user_source = vec![GithubAppInstallationSource::User(- "macro|[email protected]".to_string(),- )];- assert_eq!(- service.repo.installation_sources(),- vec![- ("11111".to_string(), user_source.clone()),- ("22222".to_string(), user_source),- ]- );-}--#[tokio::test]-async fn associate_installations_for_github_user_without_installations_is_noop() {- let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");-- let service = make_sync_service_with_repo(repo);-- service- .associate_installations_for_github_user("12345")- .await- .unwrap();-- assert!(service.repo.installation_sources().is_empty());- assert!(service.client.list_open_pull_requests_calls().is_empty());-}--#[tokio::test]-async fn associate_installations_for_github_user_without_link_is_noop() {- let repo = StubSyncRepo::new().with_installation_installer("99999", "12345");-- let service = make_sync_service_with_repo(repo);-- service- .associate_installations_for_github_user("12345")- .await- .unwrap();-- assert!(service.repo.installation_sources().is_empty());- assert!(service.client.list_open_pull_requests_calls().is_empty());-}--#[tokio::test]-async fn installation_created_no_teams_associates_user() {- let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");- // user_teams is empty by default-- let service = make_sync_service_with_repo(repo);- let event = installation_created_event(12345, 11111);-- service.process_webhook_event(&event).await.unwrap();-- let sources = service.repo.installation_sources();- assert_eq!(- sources,- vec![(- "11111".to_string(),- vec![GithubAppInstallationSource::User(- "macro|[email protected]".to_string(),- )],- )]- );-}--#[tokio::test]-async fn installation_deleted_is_skipped() {- let service = make_sync_service();- let event = ValidatedGithubWebhookEvent::new(- "installation".to_string(),- serde_json::json!({- "action": "deleted",- "installation": { "id": 12345 },- "sender": { "login": "testuser", "id": 12345 }- }),- );-- // Should not error — just skips- service.process_webhook_event(&event).await.unwrap();-- assert!(service.repo.installation_sources().is_empty());-}-// ---------------------------------------------------------------------------// notify_review_requested// ---------------------------------------------------------------------------@@ -5329,3 +5217,528 @@ async fn bot_opened_pr_body_mention_does_not_notify_mention() {let requests = service.notification_ingress.requests();assert!(requests_with_tag(&requests, "github_pr_mention").is_empty());}++fn installation_setup_user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++/// Repo where the setup user has linked the stub client's GitHub account,+/// which `complete_installation_setup` requires of whoever finishes the flow.+fn installation_setup_repo() -> StubSyncRepo {+ StubSyncRepo::new().with_github_link(+ &TEST_GITHUB_USER_ID.to_string(),+ installation_setup_user().as_ref(),+ )+}++fn make_setup_sync_service() -> TestGithubSyncService {+ make_sync_service_with_repo(installation_setup_repo())+}++fn installation_setup_state(team_id: Option<uuid::Uuid>, exp: i64) -> String {+ sign_installation_state(+ &InstallationState {+ macro_user_id: installation_setup_user(),+ team_id,+ exp,+ },+ b"test-installation-state-secret",+ )+ .unwrap()+}++#[tokio::test]+async fn begin_team_installation_setup_preserves_query_and_signs_team() {+ let user = installation_setup_user();+ let team_id = uuid::Uuid::new_v4();+ let service = make_sync_service_with_repo(+ StubSyncRepo::new().with_user_teams(user.as_ref(), vec![team_id]),+ );++ let setup_url = service+ .begin_installation_setup(&user, Some(team_id))+ .await+ .unwrap();+ let url = url::Url::parse(&setup_url).unwrap();+ let query: HashMap<_, _> = url.query_pairs().into_owned().collect();+ let state = verify_installation_state(+ query.get("state").unwrap(),+ b"test-installation-state-secret",+ chrono::Utc::now().timestamp(),+ )+ .unwrap();++ assert_eq!(url.path(), "/apps/test/installations/new");+ assert_eq!(query.get("existing").map(String::as_str), Some("1"));+ assert_eq!(state.macro_user_id, user);+ assert_eq!(state.team_id, Some(team_id));+ assert!(state.exp <= chrono::Utc::now().timestamp() + 60 * 60);+}++#[tokio::test]+async fn begin_installation_setup_normalizes_app_profile_url() {+ let user = installation_setup_user();+ let mut service = make_sync_service();+ service.config.github_sync_app_url = "https://github.com/apps/test?existing=1".to_string();++ let setup_url = service.begin_installation_setup(&user, None).await.unwrap();+ let url = url::Url::parse(&setup_url).unwrap();+ let query: HashMap<_, _> = url.query_pairs().into_owned().collect();++ assert_eq!(url.path(), "/apps/test/installations/new");+ assert_eq!(query.get("existing").map(String::as_str), Some("1"));+ assert!(query.contains_key("state"));+}++#[tokio::test]+async fn begin_personal_installation_setup_does_not_infer_teams() {+ let user = installation_setup_user();+ let service = make_sync_service_with_repo(+ StubSyncRepo::new().with_user_teams(user.as_ref(), vec![uuid::Uuid::new_v4()]),+ );++ let setup_url = service.begin_installation_setup(&user, None).await.unwrap();+ let url = url::Url::parse(&setup_url).unwrap();+ let signed_state = url+ .query_pairs()+ .find_map(|(key, value)| (key == "state").then(|| value.into_owned()))+ .unwrap();+ let state = verify_installation_state(+ &signed_state,+ b"test-installation-state-secret",+ chrono::Utc::now().timestamp(),+ )+ .unwrap();++ assert_eq!(state.team_id, None);+}++#[tokio::test]+async fn begin_installation_setup_rejects_non_member() {+ let error = make_sync_service()+ .begin_installation_setup(&installation_setup_user(), Some(uuid::Uuid::new_v4()))+ .await+ .unwrap_err();++ assert!(matches!(error, GithubError::Forbidden));+}++#[tokio::test]+async fn complete_installation_setup_associates_team_personal_and_update_sources() {+ let team_id = uuid::Uuid::new_v4();+ let team_service = make_setup_sync_service();+ team_service.client.set_user_installations(&[41]);+ team_service+ .complete_installation_setup(+ &installation_setup_state(Some(team_id), chrono::Utc::now().timestamp() + 60),+ Some("team-code"),+ Some(41),+ "install",+ )+ .await+ .unwrap();+ assert_eq!(+ team_service.repo.installation_sources(),+ vec![(+ "41".to_string(),+ vec![GithubAppInstallationSource::Team(team_id)]+ )]+ );++ let personal_service = make_setup_sync_service();+ personal_service.client.set_user_installations(&[42]);+ personal_service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("personal-code"),+ Some(42),+ "update",+ )+ .await+ .unwrap();+ assert_eq!(+ personal_service.repo.installation_sources(),+ vec![(+ "42".to_string(),+ vec![GithubAppInstallationSource::User(+ installation_setup_user().into()+ )]+ )]+ );+ assert_eq!(+ personal_service.client.setup_code_exchange_calls(),+ vec![(+ "test-sync-app-client-id".to_string(),+ "test-sync-app-client-secret".to_string(),+ "personal-code".to_string()+ )]+ );+ assert_eq!(+ personal_service.client.user_installation_list_calls(),+ vec!["test-user-token".to_string()]+ );+}++#[tokio::test]+async fn update_associates_an_existing_installation_with_one_new_source() {+ let existing_team = uuid::Uuid::new_v4();+ let requested_team = uuid::Uuid::new_v4();+ let service =+ make_sync_service_with_repo(installation_setup_repo().with_installation_sources(+ "43",+ vec![GithubAppInstallationSource::Team(existing_team)],+ ));+ service.client.set_user_installations(&[43]);++ service+ .complete_installation_setup(+ &installation_setup_state(Some(requested_team), chrono::Utc::now().timestamp() + 60),+ Some("update-code"),+ Some(43),+ "update",+ )+ .await+ .unwrap();++ let sources: HashSet<_> = service+ .repo+ .get_installation_sources("43")+ .await+ .unwrap()+ .into_iter()+ .collect();+ assert_eq!(+ sources,+ HashSet::from([+ GithubAppInstallationSource::Team(existing_team),+ GithubAppInstallationSource::Team(requested_team),+ ])+ );+ assert_eq!(+ service.repo.installation_sources(),+ vec![(+ "43".to_string(),+ vec![GithubAppInstallationSource::Team(requested_team)]+ )]+ );+}++#[tokio::test]+async fn complete_installation_setup_rejects_expired_and_tampered_state() {+ let service = make_sync_service();+ let expired = installation_setup_state(None, chrono::Utc::now().timestamp());+ assert!(matches!(+ service+ .complete_installation_setup(&expired, Some("code"), Some(1), "install")+ .await,+ Err(GithubError::InvalidInstallationState)+ ));++ let mut tampered = installation_setup_state(None, chrono::Utc::now().timestamp() + 60);+ tampered.push('x');+ assert!(matches!(+ service+ .complete_installation_setup(&tampered, Some("code"), Some(1), "install")+ .await,+ Err(GithubError::InvalidInstallationState)+ ));+ assert!(service.client.setup_code_exchange_calls().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_rejects_foreign_installation() {+ let service = make_setup_sync_service();+ service.client.set_user_installations(&[1, 2]);+ let result = service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("code"),+ Some(3),+ "install",+ )+ .await;++ assert!(matches!(result, Err(GithubError::InstallationNotOwned)));+ assert!(service.repo.installation_sources().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_fails_closed_on_exchange_or_listing_failure() {+ let exchange_service = make_setup_sync_service();+ exchange_service.client.fail_setup_code_exchange();+ let state = installation_setup_state(None, chrono::Utc::now().timestamp() + 60);+ assert!(+ exchange_service+ .complete_installation_setup(&state, Some("code"), Some(1), "install")+ .await+ .is_err()+ );+ assert!(+ exchange_service+ .client+ .user_installation_list_calls()+ .is_empty()+ );+ assert!(exchange_service.repo.installation_sources().is_empty());++ let listing_service = make_setup_sync_service();+ listing_service.client.fail_user_installation_list();+ assert!(+ listing_service+ .complete_installation_setup(&state, Some("code"), Some(1), "install")+ .await+ .is_err()+ );+ assert!(listing_service.repo.installation_sources().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_accepts_installation_from_complete_paginated_result() {+ let service = make_setup_sync_service();+ let installation_ids: Vec<u64> = (1..=150).collect();+ service.client.set_user_installations(&installation_ids);++ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("code"),+ Some(150),+ "install",+ )+ .await+ .unwrap();++ assert_eq!(service.repo.installation_sources().len(), 1);+}++#[tokio::test]+async fn complete_installation_setup_request_parks_team_pending_request() {+ let team_id = uuid::Uuid::new_v4();+ let service = make_setup_sync_service();+ service+ .complete_installation_setup(+ &installation_setup_state(Some(team_id), chrono::Utc::now().timestamp() + 60),+ Some("request-code"),+ None,+ "request",+ )+ .await+ .unwrap();++ // No installation exists until an org admin approves, so nothing is+ // associated yet...+ assert!(service.repo.installation_sources().is_empty());+ assert!(service.client.user_installation_list_calls().is_empty());+ // ...but the requested source is parked, keyed by the requester's GitHub+ // identity, for the installation.created webhook to complete.+ assert_eq!(+ service.repo.installation_requests(),+ HashMap::from([(+ TEST_GITHUB_USER_ID.to_string(),+ GithubAppInstallationSource::Team(team_id)+ )])+ );+ assert_eq!(+ service.client.authenticated_user_calls(),+ vec!["test-user-token".to_string()]+ );+}++#[tokio::test]+async fn complete_installation_setup_request_parks_personal_pending_request() {+ let service = make_setup_sync_service();+ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("request-code"),+ None,+ "request",+ )+ .await+ .unwrap();++ assert_eq!(+ service.repo.installation_requests(),+ HashMap::from([(+ TEST_GITHUB_USER_ID.to_string(),+ GithubAppInstallationSource::User(installation_setup_user().into())+ )])+ );+}++#[tokio::test]+async fn complete_installation_setup_request_rejects_invalid_state_and_missing_code() {+ let service = make_sync_service();++ assert!(matches!(+ service+ .complete_installation_setup("invalid", Some("code"), None, "request")+ .await,+ Err(GithubError::InvalidInstallationState)+ ));++ assert!(matches!(+ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ None,+ None,+ "request",+ )+ .await,+ Err(GithubError::MissingInstallationSetupField("code"))+ ));++ assert!(service.client.setup_code_exchange_calls().is_empty());+ assert!(service.repo.installation_requests().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_request_fails_closed_on_identity_failure() {+ let service = make_setup_sync_service();+ service.client.fail_get_authenticated_user();++ assert!(+ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("request-code"),+ None,+ "request",+ )+ .await+ .is_err()+ );+ assert!(service.repo.installation_requests().is_empty());+}++#[tokio::test]+async fn requested_install_is_associated_after_admin_approval() {+ let team_id = uuid::Uuid::new_v4();+ let service = make_setup_sync_service();++ // A team member requests the org install: no installation exists yet.+ service+ .complete_installation_setup(+ &installation_setup_state(Some(team_id), chrono::Utc::now().timestamp() + 60),+ Some("request-code"),+ None,+ "request",+ )+ .await+ .unwrap();+ assert!(service.repo.installation_sources().is_empty());++ // Days later an org admin approves, which creates the installation and+ // emits installation.created with the original requester.+ let event = approved_installation_created_event(TEST_GITHUB_USER_ID, 555);+ service.process_webhook_event(&event).await.unwrap();++ assert_eq!(+ service.repo.installation_sources(),+ vec![(+ "555".to_string(),+ vec![GithubAppInstallationSource::Team(team_id)]+ )]+ );+ assert!(service.repo.installation_requests().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_rejects_missing_fields_and_unknown_action() {+ let service = make_sync_service();+ let state = installation_setup_state(None, chrono::Utc::now().timestamp() + 60);++ assert!(matches!(+ service+ .complete_installation_setup(&state, None, Some(1), "install")+ .await,+ Err(GithubError::MissingInstallationSetupField("code"))+ ));+ assert!(matches!(+ service+ .complete_installation_setup(&state, Some("code"), None, "update")+ .await,+ Err(GithubError::MissingInstallationSetupField(+ "installation_id"+ ))+ ));+ assert!(matches!(+ service+ .complete_installation_setup(&state, None, None, "other")+ .await,+ Err(GithubError::InvalidInstallationSetupAction)+ ));+}++#[tokio::test]+async fn complete_installation_setup_rejects_unlinked_completer() {+ // A signed state alone must not be honored: whoever finishes the flow has+ // to be linked to the Macro user the state was minted for, or a leaked or+ // attacker-minted state could bind an installation to a foreign source.+ let service = make_sync_service();+ service.client.set_user_installations(&[9]);+ let state = installation_setup_state(None, chrono::Utc::now().timestamp() + 60);++ assert!(matches!(+ service+ .complete_installation_setup(&state, Some("code"), Some(9), "install")+ .await,+ Err(GithubError::SetupUserNotLinked)+ ));+ assert!(matches!(+ service+ .complete_installation_setup(&state, Some("code"), None, "request")+ .await,+ Err(GithubError::SetupUserNotLinked)+ ));++ assert!(service.repo.installation_sources().is_empty());+ assert!(service.repo.installation_requests().is_empty());+ // The identity check happens before the ownership listing.+ assert!(service.client.user_installation_list_calls().is_empty());+}++#[tokio::test]+async fn complete_installation_setup_rejects_completer_linked_to_other_user() {+ let service = make_sync_service_with_repo(StubSyncRepo::new().with_github_link(+ &TEST_GITHUB_USER_ID.to_string(),+ "macro|[email protected]",+ ));+ service.client.set_user_installations(&[9]);++ assert!(matches!(+ service+ .complete_installation_setup(+ &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),+ Some("code"),+ Some(9),+ "install",+ )+ .await,+ Err(GithubError::SetupUserNotLinked)+ ));+ assert!(service.repo.installation_sources().is_empty());+}++#[tokio::test]+async fn repeated_installation_association_is_idempotent() {+ let service = make_setup_sync_service();+ service.client.set_user_installations(&[77]);+ let state = installation_setup_state(None, chrono::Utc::now().timestamp() + 60);++ for _ in 0..2 {+ service+ .complete_installation_setup(&state, Some("code"), Some(77), "install")+ .await+ .unwrap();+ }++ let rows = service.repo.get_installation_sources("77").await.unwrap();+ assert_eq!(+ rows,+ vec![GithubAppInstallationSource::User(+ installation_setup_user().into()+ )]+ );+}diff --git a/crates/github/src/inbound.rs b/crates/github/src/inbound.rsindex 600e51d32c..02266a47f5 100644--- a/crates/github/src/inbound.rs+++ b/crates/github/src/inbound.rs@@ -26,6 +26,17 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {crate::domain::models::GithubError::InvalidWebhookSignature => {(StatusCode::UNAUTHORIZED, "unauthenticated")}+ crate::domain::models::GithubError::Forbidden+ | crate::domain::models::GithubError::SetupUserNotLinked => {+ (StatusCode::FORBIDDEN, "forbidden")+ }+ crate::domain::models::GithubError::InvalidInstallationState+ | crate::domain::models::GithubError::InvalidInstallationSetupAction+ | crate::domain::models::GithubError::MissingInstallationSetupField(_)+ | crate::domain::models::GithubError::InstallationNotOwned => (+ StatusCode::BAD_REQUEST,+ "invalid installation setup callback",+ ),};(diff --git a/crates/github/src/inbound/github_sync_router/mod.rs b/crates/github/src/inbound/github_sync_router/mod.rsindex 9fdbb4ea4b..4c93fe6002 100644--- a/crates/github/src/inbound/github_sync_router/mod.rs+++ b/crates/github/src/inbound/github_sync_router/mod.rs@@ -8,102 +8,200 @@#[cfg(test)]mod test;+use std::sync::Arc;+use axum::{Router,- extract::{FromRequest, Request, State},+ extract::{FromRef, FromRequest, Query, Request, State},response::Redirect,};+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use entity_access::{+ domain::{models::MemberTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::OptionalMacroUserTeamExtractorV2,+};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOnly,+};use macro_service_urls::AppServiceUrl;use reqwest::StatusCode;-use std::sync::Arc;+use uuid::Uuid;use crate::domain::{- models::{GithubError, ValidatedGithubWebhookEvent},+ models::{GithubError, InstallationState, ValidatedGithubWebhookEvent},ports::GithubSyncService,};-/// Router state containing the github sync service.-pub struct GithubSyncRouterState<T> {- /// The github sync service implementation.+/// Router state containing the GitHub sync, entity access, and authorization services.+pub struct GithubSyncRouterState<T, Eas, Auth> {+ /// The GitHub sync service implementation.pub service: Arc<T>,+ /// Service used to resolve the authenticated user's optional team.+ pub entity_access_service: Arc<Eas>,+ /// State used to authenticate installation setup requests.+ pub authorization_state: MacroAuthorizationState<Auth>,}-// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).-impl<T> Clone for GithubSyncRouterState<T> {+// Manual Clone impl so the services don't need to be Clone (they are behind Arcs).+impl<T, Eas, Auth> Clone for GithubSyncRouterState<T, Eas, Auth> {fn clone(&self) -> Self {Self {service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ authorization_state: self.authorization_state.clone(),}}}+impl<T, Eas, Auth> FromRef<GithubSyncRouterState<T, Eas, Auth>> for Arc<Eas> {+ fn from_ref(state: &GithubSyncRouterState<T, Eas, Auth>) -> Self {+ state.entity_access_service.clone()+ }+}++impl<T, Eas, Auth> FromRef<GithubSyncRouterState<T, Eas, Auth>> for MacroAuthorizationState<Auth> {+ fn from_ref(state: &GithubSyncRouterState<T, Eas, Auth>) -> Self {+ state.authorization_state.clone()+ }+}+/// Build the github sync router.-pub fn github_sync_router<T, S>(state: GithubSyncRouterState<T>) -> Router<S>+pub fn github_sync_router<T, Eas, Auth, S>(state: GithubSyncRouterState<T, Eas, Auth>) -> Router<S>whereT: GithubSyncService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,S: Send + Sync + 'static,{Router::new()- .route("/install-sync", axum::routing::get(install_sync_handler))+ .route(+ "/install-sync",+ axum::routing::get(install_sync_handler::<T, Eas, Auth>),+ ).route("/sync-redirect",- axum::routing::get(sync_redirect_handler::<T>),+ axum::routing::get(sync_redirect_handler::<T, Eas, Auth>),).route("/webhook",- axum::routing::post(github_webhook_event_handler),+ axum::routing::post(github_webhook_event_handler::<T, Eas, Auth>),).with_state(state)}-/// Redirects the user to the github sync app installation page.+/// Redirects an authenticated user to the github sync app installation page.#[utoipa::path(get,path = "/github/install-sync",operation_id = "install_sync",responses(- (status = 307, description = "Redirects to the github sync app installation page"),+ (status = 307, description = "Temporary redirect to the GitHub sync app installation page"),+ (status = 401, description = "Authentication failed"),))]-#[tracing::instrument(skip(ctx))]-pub async fn install_sync_handler<T: GithubSyncService>(- State(ctx): State<GithubSyncRouterState<T>>,-) -> Redirect {- let url = ctx.service.get_github_sync_app_url();- Redirect::temporary(url)+#[tracing::instrument(skip(ctx, authorization, team), err)]+pub async fn install_sync_handler<T, Eas, Auth>(+ State(ctx): State<GithubSyncRouterState<T, Eas, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOnly>,+ team: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+) -> Result<Redirect, GithubError>+where+ T: GithubSyncService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let team_id = team+ .entity_access_receipt+ .map(|receipt| Uuid::parse_str(&receipt.entity().entity_id))+ .transpose()+ .map_err(|error| GithubError::Internal(error.into()))?;+ let url = ctx+ .service+ .begin_installation_setup(&authorization.authorization.macro_user_id, team_id)+ .await?;++ Ok(Redirect::temporary(&url))}/// Query params received from the GitHub App installation callback.-#[derive(serde::Deserialize)]+#[derive(Debug, Default, serde::Deserialize)]pub struct SyncRedirectParams {- /// The OAuth authorization code from GitHub (unused for now).- #[allow(dead_code)]- pub code: String,- /// The GitHub App installation ID (unused for now).- #[allow(dead_code)]- pub installation_id: String,+ /// OAuth authorization code from GitHub.+ pub code: Option<String>,+ /// GitHub App installation ID.+ pub installation_id: Option<String>,+ /// Signed Macro installation context.+ pub state: Option<String>,+ /// GitHub's setup result (`install`, `update`, or `request`).+ pub setup_action: Option<String>,}-/// Callback after a user installs the GitHub App. Redirects to the main app.+/// Completes a GitHub App installation callback and redirects back to Macro.#[utoipa::path(get,path = "/github/sync-redirect",operation_id = "sync_redirect",params(- ("code" = String, Query, description = "OAuth authorization code from GitHub"),- ("installation_id" = String, Query, description = "GitHub App installation ID"),+ ("code" = Option<String>, Query, description = "OAuth authorization code from GitHub"),+ ("installation_id" = Option<String>, Query, description = "GitHub App installation ID"),+ ("state" = Option<String>, Query, description = "Signed Macro installation context"),+ ("setup_action" = Option<String>, Query, description = "GitHub setup result: install, update, or request"),),responses(- (status = 307, description = "Redirects to the main application"),+ (status = 307, description = "Temporary redirect to Macro; callback failures degrade to this redirect"),))]#[tracing::instrument(skip_all)]-pub async fn sync_redirect_handler<T: GithubSyncService>(- axum::extract::Query(_params): axum::extract::Query<SyncRedirectParams>,-) -> Redirect {+pub async fn sync_redirect_handler<T, Eas, Auth>(+ State(ctx): State<GithubSyncRouterState<T, Eas, Auth>>,+ Query(params): Query<SyncRedirectParams>,+) -> Redirect+where+ T: GithubSyncService,+ Auth: MacroAuthorizationService,+{+ let state = params.state.as_deref().unwrap_or_default();+ let setup_action = params.setup_action.as_deref().unwrap_or_default();+ let installation_id = params+ .installation_id+ .as_deref()+ .and_then(|value| value.parse::<u64>().ok());++ let result = ctx+ .service+ .complete_installation_setup(state, params.code.as_deref(), installation_id, setup_action)+ .await;++ if let Err(error) = result {+ tracing::error!(error=?error, "failed to complete GitHub installation setup");+ return app_redirect();+ }++ if setup_action != "request" && callback_team_id(state).is_some() {+ return team_settings_redirect();+ }++ app_redirect()+}++fn callback_team_id(state: &str) -> Option<Uuid> {+ let encoded_payload = state.split_once('.')?.0;+ let payload = URL_SAFE_NO_PAD.decode(encoded_payload).ok()?;+ serde_json::from_slice::<InstallationState>(&payload)+ .ok()?+ .team_id+}++fn app_redirect() -> Redirect {Redirect::temporary(AppServiceUrl::unwrap_new().as_str())}+fn team_settings_redirect() -> Redirect {+ let app_url = AppServiceUrl::unwrap_new();+ let destination = format!("{}/settings/team", app_url.as_str().trim_end_matches('/'));+ Redirect::temporary(&destination)+}+/// Extractor that validates an incoming GitHub webhook event.////// Reads the `X-Hub-Signature-256` header and the raw request body, then@@ -112,15 +210,17 @@ pub async fn sync_redirect_handler<T: GithubSyncService>(/// [`ValidatedGithubWebhookEvent`].pub struct GithubWebhookEventExtractor(pub ValidatedGithubWebhookEvent);-impl<T> FromRequest<GithubSyncRouterState<T>> for GithubWebhookEventExtractor+impl<T, Eas, Auth> FromRequest<GithubSyncRouterState<T, Eas, Auth>> for GithubWebhookEventExtractorwhereT: GithubSyncService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,{type Rejection = GithubError;async fn from_request(req: Request,- state: &GithubSyncRouterState<T>,+ state: &GithubSyncRouterState<T, Eas, Auth>,) -> Result<Self, Self::Rejection> {let (parts, body) = req.into_parts();@@ -152,10 +252,13 @@ where/// The main entrypoint for all github webhook events handling#[tracing::instrument(err, skip(ctx, event))]-pub async fn github_webhook_event_handler<T: GithubSyncService>(- State(ctx): State<GithubSyncRouterState<T>>,+pub async fn github_webhook_event_handler<T, Eas, Auth>(+ State(ctx): State<GithubSyncRouterState<T, Eas, Auth>>,GithubWebhookEventExtractor(event): GithubWebhookEventExtractor,-) -> Result<StatusCode, GithubError> {+) -> Result<StatusCode, GithubError>+where+ T: GithubSyncService,+{tracing::info!("github_webhook");ctx.service.process_webhook_event(&event).await?;diff --git a/crates/github/src/inbound/github_sync_router/test.rs b/crates/github/src/inbound/github_sync_router/test.rsindex 9683c6ba53..6f1f42dae9 100644--- a/crates/github/src/inbound/github_sync_router/test.rs+++ b/crates/github/src/inbound/github_sync_router/test.rs@@ -1,18 +1,205 @@-use std::sync::Arc;+use std::sync::{Arc, Mutex};use axum::{Router, http::Request};-use http_body_util::BodyExt;+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use entity_access::domain::{+ models::{+ AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EntityAccessReceipt,+ EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,+ },+ ports::EntityAccessService,+};+use macro_authorization::{+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,+ MacroAuthorizationState,+};+use macro_service_urls::AppServiceUrl;+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};+use model_user::UserContext;+use rootcause::Report;use tower::util::ServiceExt;+use uuid::Uuid;use crate::domain::{- models::{GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent},+ models::{+ GithubError, GithubInstallationAccessToken, InstallationState, ValidatedGithubWebhookEvent,+ },ports::GithubSyncService,};use super::{GithubSyncRouterState, github_sync_router};+const USER_ID: &str = "macro|[email protected]";++#[derive(Clone)]+struct TestAuthorizationService;++impl MacroAuthorizationService for TestAuthorizationService {+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {+ if jwt != "valid" {+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));+ }++ Ok(UserContext {+ user_id: USER_ID.to_string(),+ fusion_user_id: "fusion-github-installer".to_string(),+ permissions: None,+ organization_id: None,+ })+ }++ async fn authorize_internal(+ &self,+ _provided_key: &str,+ _claims: InternalIdentityClaims,+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))+ }+}++#[derive(Clone, Copy)]+struct TestEntityAccessService {+ team_id: Option<Uuid>,+}++impl EntityAccessService for TestEntityAccessService {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ _bot_id: BotId,+ _scope: BotAccessScope,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel(+ &self,+ _call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_call_channel_by_channel_id(+ &self,+ _channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ Err(AccessError::Internal)+ }++ async fn get_user_team(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ Ok(self.team_id.map(|team_id| UserTeamInfo {+ team_id,+ role: TeamRole::Member,+ }))+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct BeginCall {+ macro_user_id: String,+ team_id: Option<Uuid>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct CompleteCall {+ state: String,+ code: Option<String>,+ installation_id: Option<u64>,+ setup_action: String,+}+struct MockGithubSyncService {- sync_app_url: String,+ begin_calls: Arc<Mutex<Vec<BeginCall>>>,+ complete_calls: Arc<Mutex<Vec<CompleteCall>>>,+}++impl MockGithubSyncService {+ fn new() -> Self {+ Self {+ begin_calls: Arc::new(Mutex::new(Vec::new())),+ complete_calls: Arc::new(Mutex::new(Vec::new())),+ }+ }++ fn begin_calls(&self) -> Vec<BeginCall> {+ self.begin_calls.lock().unwrap().clone()+ }++ fn complete_calls(&self) -> Vec<CompleteCall> {+ self.complete_calls.lock().unwrap().clone()+ }}impl GithubSyncService for MockGithubSyncService {@@ -32,8 +219,44 @@ impl GithubSyncService for MockGithubSyncService {unimplemented!()}+ async fn begin_installation_setup(+ &self,+ macro_user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<String, GithubError> {+ self.begin_calls.lock().unwrap().push(BeginCall {+ macro_user_id: macro_user_id.to_string(),+ team_id,+ });+ Ok("https://github.com/apps/my-sync-app/installations/new?state=signed".to_string())+ }++ async fn complete_installation_setup(+ &self,+ state: &str,+ code: Option<&str>,+ installation_id: Option<u64>,+ setup_action: &str,+ ) -> Result<(), GithubError> {+ self.complete_calls.lock().unwrap().push(CompleteCall {+ state: state.to_string(),+ code: code.map(str::to_string),+ installation_id,+ setup_action: setup_action.to_string(),+ });++ if matches!(state, "" | "malformed" | "ownership-failure")+ || !matches!(setup_action, "install" | "update" | "request")+ || (setup_action != "request" && (code.is_none() || installation_id.is_none()))+ {+ return Err(GithubError::InvalidInstallationState);+ }++ Ok(())+ }+fn get_github_sync_app_url(&self) -> &str {- &self.sync_app_url+ "https://github.com/apps/my-sync-app/installations/new"}async fn generate_installation_access_token(@@ -42,65 +265,220 @@ impl GithubSyncService for MockGithubSyncService {) -> Result<GithubInstallationAccessToken, GithubError> {unimplemented!()}+}- async fn associate_installations_for_github_user(- &self,- _github_user_id: &str,- ) -> Result<(), GithubError> {- unimplemented!()- }+fn mock_router() -> (Router, Arc<MockGithubSyncService>) {+ mock_router_with_team(None)}-fn mock_router(sync_app_url: &str) -> Router {- github_sync_router(GithubSyncRouterState {- service: Arc::new(MockGithubSyncService {- sync_app_url: sync_app_url.to_string(),- }),- })+fn mock_router_with_team(team_id: Option<Uuid>) -> (Router, Arc<MockGithubSyncService>) {+ let service = Arc::new(MockGithubSyncService::new());+ let router = github_sync_router(GithubSyncRouterState {+ service: service.clone(),+ entity_access_service: Arc::new(TestEntityAccessService { team_id }),+ authorization_state: MacroAuthorizationState::new(Arc::new(TestAuthorizationService)),+ });+ (router, service)}-#[tokio::test]-async fn install_sync_redirects_to_github_sync_app_url() {- let url = "https://github.com/apps/my-sync-app/installations/new";- let router = mock_router(url);+fn request(uri: &str) -> Request<axum::body::Body> {+ Request::builder()+ .uri(uri)+ .body(axum::body::Body::empty())+ .unwrap()+}- let request = Request::builder()- .uri("/install-sync")+fn authenticated_request(uri: &str) -> Request<axum::body::Body> {+ Request::builder()+ .uri(uri)+ .header("authorization", "Bearer valid").body(axum::body::Body::empty())- .unwrap();+ .unwrap()+}- let res = router.oneshot(request).await.unwrap();+fn callback_state(team_id: Option<Uuid>) -> String {+ let state = InstallationState {+ macro_user_id: MacroUserIdStr::try_from(USER_ID.to_string()).unwrap(),+ team_id,+ exp: i64::MAX,+ };+ let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&state).unwrap());+ format!("{payload}.test-signature")+}- assert_eq!(res.status(), axum::http::StatusCode::TEMPORARY_REDIRECT);- assert_eq!(res.headers().get("location").unwrap(), url);+fn app_url() -> String {+ AppServiceUrl::unwrap_new().as_str().to_string()}#[tokio::test]-async fn install_sync_returns_empty_body() {- let url = "https://github.com/apps/my-sync-app/installations/new";- let router = mock_router(url);+async fn install_sync_rejects_unauthenticated_requests() {+ let (router, service) = mock_router();- let request = Request::builder()- .uri("/install-sync")- .body(axum::body::Body::empty())+ let response = router.oneshot(request("/install-sync")).await.unwrap();++ assert_eq!(response.status(), axum::http::StatusCode::UNAUTHORIZED);+ assert!(service.begin_calls().is_empty());+}++#[tokio::test]+async fn install_sync_uses_the_authenticated_users_optional_team() {+ let team_id = Uuid::new_v4();+ let (personal_router, personal_service) = mock_router();+ let (team_router, team_service) = mock_router_with_team(Some(team_id));++ let personal_response = personal_router+ .oneshot(authenticated_request("/install-sync"))+ .await.unwrap();+ let team_response = team_router+ .oneshot(authenticated_request("/install-sync"))+ .await+ .unwrap();++ assert_eq!(+ personal_response.status(),+ axum::http::StatusCode::TEMPORARY_REDIRECT+ );+ assert_eq!(+ team_response.status(),+ axum::http::StatusCode::TEMPORARY_REDIRECT+ );+ assert_eq!(+ personal_service.begin_calls(),+ vec![BeginCall {+ macro_user_id: USER_ID.to_string(),+ team_id: None,+ }]+ );+ assert_eq!(+ team_service.begin_calls(),+ vec![BeginCall {+ macro_user_id: USER_ID.to_string(),+ team_id: Some(team_id),+ }]+ );+}- let res = router.oneshot(request).await.unwrap();- let bytes = res.into_body().collect().await.unwrap().to_bytes();+#[tokio::test]+async fn install_sync_does_not_accept_team_context_from_the_query() {+ let (router, service) = mock_router();++ let response = router+ .oneshot(authenticated_request(+ "/install-sync?team_id=00000000-0000-0000-0000-000000000001",+ ))+ .await+ .unwrap();- assert!(bytes.is_empty());+ assert_eq!(+ response.status(),+ axum::http::StatusCode::TEMPORARY_REDIRECT+ );+ assert_eq!(service.begin_calls()[0].team_id, None);}#[tokio::test]-async fn install_sync_returns_not_found_for_wrong_path() {- let router = mock_router("https://github.com/apps/my-sync-app");+async fn successful_callbacks_redirect_to_the_matching_destination() {+ let (router, _) = mock_router();+ let personal_state = callback_state(None);+ let team_state = callback_state(Some(Uuid::new_v4()));- let request = Request::builder()- .uri("/wrong-path")- .body(axum::body::Body::empty())+ let personal = router+ .clone()+ .oneshot(request(&format!(+ "/sync-redirect?state={personal_state}&code=code&installation_id=1&setup_action=install"+ )))+ .await.unwrap();+ let team = router+ .oneshot(request(&format!(+ "/sync-redirect?state={team_state}&code=code&installation_id=2&setup_action=update"+ )))+ .await+ .unwrap();++ assert_eq!(+ personal+ .headers()+ .get("location")+ .unwrap()+ .to_str()+ .unwrap(),+ app_url()+ );+ assert_eq!(+ team.headers().get("location").unwrap().to_str().unwrap(),+ format!("{}/settings/team", app_url().trim_end_matches('/'))+ );+}++#[tokio::test]+async fn request_callback_without_installation_id_redirects_to_the_app() {+ let (router, service) = mock_router();+ let state = callback_state(Some(Uuid::new_v4()));++ let response = router+ .oneshot(request(&format!(+ "/sync-redirect?state={state}&setup_action=request"+ )))+ .await+ .unwrap();++ assert_eq!(+ response.status(),+ axum::http::StatusCode::TEMPORARY_REDIRECT+ );+ assert_eq!(+ response+ .headers()+ .get("location")+ .unwrap()+ .to_str()+ .unwrap(),+ app_url()+ );+ assert_eq!(service.complete_calls()[0].installation_id, None);+}++#[tokio::test]+async fn degraded_callbacks_always_return_a_temporary_redirect() {+ let (router, _) = mock_router();+ let state = callback_state(None);+ let cases = [+ "/sync-redirect".to_string(),+ "/sync-redirect?state=malformed&setup_action=install".to_string(),+ format!(+ "/sync-redirect?state={state}&code=code&installation_id=invalid&setup_action=install"+ ),+ "/sync-redirect?state=ownership-failure&code=code&installation_id=3&setup_action=install"+ .to_string(),+ format!("/sync-redirect?state={state}&setup_action=unknown"),+ ];++ for uri in cases {+ let response = router.clone().oneshot(request(&uri)).await.unwrap();+ assert_eq!(+ response.status(),+ axum::http::StatusCode::TEMPORARY_REDIRECT,+ "callback {uri} did not degrade to a redirect"+ );+ assert_eq!(+ response+ .headers()+ .get("location")+ .unwrap()+ .to_str()+ .unwrap(),+ app_url()+ );+ }+}++#[tokio::test]+async fn wrong_path_returns_not_found() {+ let (router, _) = mock_router();- let res = router.oneshot(request).await.unwrap();+ let response = router.oneshot(request("/wrong-path")).await.unwrap();- assert_eq!(res.status(), axum::http::StatusCode::NOT_FOUND);+ assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);}diff --git a/crates/github/src/outbound/github_sync_client.rs b/crates/github/src/outbound/github_sync_client.rsindex 515e87c4be..18b9fc0899 100644--- a/crates/github/src/outbound/github_sync_client.rs+++ b/crates/github/src/outbound/github_sync_client.rs@@ -1,25 +1,224 @@//! Github Sync Client implementation of the [`GithubSyncClient`] port.+use std::time::Duration;+use super::pull_request_metadata::{fetch_open_pull_requests_for_installation, fetch_pull_request_metadata,};use crate::domain::{models::{- EnrichedGithubPullRequest, GithubError, GithubInstallationAccessToken,- GithubPullRequestDetails,+ EnrichedGithubPullRequest, GithubAuthenticatedUser, GithubError,+ GithubInstallationAccessToken, GithubPullRequestDetails, GithubSetupAccessToken,+ GithubUserInstallation, GithubUserInstallationsPage,},ports::GithubSyncClient,};+const GITHUB_API_BASE_URL: &str = "https://api.github.com";+const GITHUB_OAUTH_BASE_URL: &str = "https://github.com";+const USER_INSTALLATIONS_PAGE_SIZE: u64 = 100;+const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);++#[cfg(test)]+mod test;+/// Github sync client implementation backed by a reusable [`reqwest::Client`].-#[derive(Clone, Default)]+#[derive(Clone)]pub struct GithubSyncClientImpl {/// The reqwest clientclient: reqwest::Client,+ #[cfg(test)]+ api_base_url: Option<String>,+}++impl Default for GithubSyncClientImpl {+ fn default() -> Self {+ Self {+ client: build_client(),+ #[cfg(test)]+ api_base_url: None,+ }+ }+}++fn build_client() -> reqwest::Client {+ reqwest::Client::builder()+ .timeout(REQUEST_TIMEOUT)+ .build()+ .expect("GitHub sync reqwest client should build")+}++impl GithubSyncClientImpl {+ fn api_base_url(&self) -> &str {+ #[cfg(test)]+ if let Some(api_base_url) = &self.api_base_url {+ return api_base_url;+ }++ GITHUB_API_BASE_URL+ }++ fn oauth_base_url(&self) -> &str {+ #[cfg(test)]+ if let Some(api_base_url) = &self.api_base_url {+ return api_base_url;+ }++ GITHUB_OAUTH_BASE_URL+ }++ #[cfg(test)]+ fn with_api_base_url(api_base_url: String) -> Self {+ Self {+ client: build_client(),+ api_base_url: Some(api_base_url),+ }+ }}impl GithubSyncClient for GithubSyncClientImpl {+ #[tracing::instrument(skip(self, client_secret, code), err)]+ async fn exchange_setup_code(+ &self,+ client_id: &str,+ client_secret: &str,+ code: &str,+ ) -> Result<GithubSetupAccessToken, GithubError> {+ #[derive(serde::Serialize)]+ struct TokenRequest<'a> {+ client_id: &'a str,+ client_secret: &'a str,+ code: &'a str,+ }++ let response = self+ .client+ .post(format!(+ "{}/login/oauth/access_token",+ self.oauth_base_url()+ ))+ .header("Accept", "application/json")+ .json(&TokenRequest {+ client_id,+ client_secret,+ code,+ })+ .send()+ .await+ .map_err(|_| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub setup token exchange request failed"+ ))+ })?;++ let status = response.status();+ if !status.is_success() {+ return Err(GithubError::Internal(anyhow::anyhow!(+ "GitHub setup token exchange failed with status {status}"+ )));+ }++ response.json().await.map_err(|_| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub setup token exchange returned a malformed response"+ ))+ })+ }++ #[tracing::instrument(skip(self, access_token), err)]+ async fn list_user_installations(+ &self,+ access_token: &str,+ ) -> Result<Vec<GithubUserInstallation>, GithubError> {+ let mut page = 1_u64;+ let mut installations = Vec::new();++ loop {+ let response = self+ .client+ .get(format!(+ "{}/user/installations?per_page={USER_INSTALLATIONS_PAGE_SIZE}&page={page}",+ self.api_base_url()+ ))+ .header("Authorization", format!("Bearer {access_token}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Macro-Auth-Service")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .send()+ .await+ .map_err(|_| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub user installation list request failed"+ ))+ })?;++ let status = response.status();+ if !status.is_success() {+ return Err(GithubError::Internal(anyhow::anyhow!(+ "GitHub user installation list failed with status {status}"+ )));+ }++ let response_page: GithubUserInstallationsPage =+ response.json().await.map_err(|_| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub user installation list returned a malformed response"+ ))+ })?;+ let total_count = response_page.total_count;+ let page_is_empty = response_page.installations.is_empty();+ installations.extend(response_page.installations);++ if installations.len() as u64 >= total_count {+ return Ok(installations);+ }+ if page_is_empty {+ return Err(GithubError::Internal(anyhow::anyhow!(+ "GitHub user installation pagination ended before total_count"+ )));+ }++ page = page.checked_add(1).ok_or_else(|| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub user installation pagination exceeded page limit"+ ))+ })?;+ }+ }++ #[tracing::instrument(skip(self, access_token), err)]+ async fn get_authenticated_user(+ &self,+ access_token: &str,+ ) -> Result<GithubAuthenticatedUser, GithubError> {+ let response = self+ .client+ .get(format!("{}/user", self.api_base_url()))+ .header("Authorization", format!("Bearer {access_token}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Macro-Auth-Service")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .send()+ .await+ .map_err(|_| {+ GithubError::Internal(anyhow::anyhow!("GitHub authenticated user request failed"))+ })?;++ let status = response.status();+ if !status.is_success() {+ return Err(GithubError::Internal(anyhow::anyhow!(+ "GitHub authenticated user request failed with status {status}"+ )));+ }++ response.json().await.map_err(|_| {+ GithubError::Internal(anyhow::anyhow!(+ "GitHub authenticated user request returned a malformed response"+ ))+ })+ }+#[tracing::instrument(skip(self, jwt), err)]async fn generate_installation_access_token(&self,diff --git a/crates/github/src/outbound/github_sync_client/test.rs b/crates/github/src/outbound/github_sync_client/test.rsnew file mode 100644index 0000000000..3cad9e5570--- /dev/null+++ b/crates/github/src/outbound/github_sync_client/test.rs@@ -0,0 +1,227 @@+use std::io::{Read, Write};+use std::net::{TcpListener, TcpStream};+use std::sync::mpsc::{self, Receiver};+use std::thread::JoinHandle;+use std::time::Duration;++use super::*;++struct MockResponse {+ status: &'static str,+ body: String,+}++impl MockResponse {+ fn json(body: serde_json::Value) -> Self {+ Self {+ status: "200 OK",+ body: body.to_string(),+ }+ }+}++struct MockServer {+ base_url: String,+ requests: Receiver<String>,+ handle: JoinHandle<()>,+}++impl MockServer {+ fn start(responses: Vec<MockResponse>) -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let base_url = format!("http://{}", listener.local_addr().unwrap());+ let (request_sender, requests) = mpsc::channel();+ let handle = std::thread::spawn(move || {+ for response in responses {+ let (mut stream, _) = listener.accept().unwrap();+ let request = read_request(&mut stream);+ request_sender.send(request).unwrap();+ write!(+ stream,+ "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ response.status,+ response.body.len(),+ response.body+ )+ .unwrap();+ }+ });++ Self {+ base_url,+ requests,+ handle,+ }+ }++ fn finish(self) -> Vec<String> {+ self.handle.join().unwrap();+ self.requests.try_iter().collect()+ }+}++fn read_request(stream: &mut TcpStream) -> String {+ stream+ .set_read_timeout(Some(Duration::from_secs(5)))+ .unwrap();+ let mut request = Vec::new();+ let mut buffer = [0_u8; 4096];++ loop {+ let bytes_read = stream.read(&mut buffer).unwrap();+ if bytes_read == 0 {+ break;+ }+ request.extend_from_slice(&buffer[..bytes_read]);++ let Some(header_end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") else {+ continue;+ };+ let headers = String::from_utf8_lossy(&request[..header_end]);+ let content_length = headers+ .lines()+ .find_map(|line| {+ let (name, value) = line.split_once(':')?;+ name.eq_ignore_ascii_case("content-length")+ .then(|| value.trim().parse::<usize>().unwrap())+ })+ .unwrap_or(0);+ if request.len() >= header_end + 4 + content_length {+ break;+ }+ }++ String::from_utf8(request).unwrap()+}++#[tokio::test]+async fn exchanges_setup_code_for_access_token() {+ let server = MockServer::start(vec![MockResponse::json(serde_json::json!({+ "access_token": "returned-user-token",+ "token_type": "bearer",+ "scope": ""+ }))]);+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());++ let token = client+ .exchange_setup_code("sync-client-id", "client-secret", "callback-code")+ .await+ .unwrap();++ assert_eq!(token.as_str(), "returned-user-token");+ let requests = server.finish();+ assert!(requests[0].starts_with("POST /login/oauth/access_token HTTP/1.1"));+ assert!(+ requests[0]+ .to_ascii_lowercase()+ .contains("accept: application/json")+ );+ assert!(requests[0].contains("\"client_id\":\"sync-client-id\""));+ assert!(requests[0].contains("\"client_secret\":\"client-secret\""));+ assert!(requests[0].contains("\"code\":\"callback-code\""));+}++#[tokio::test]+async fn rejects_unsuccessful_setup_code_exchange_without_leaking_secrets() {+ let server = MockServer::start(vec![MockResponse {+ status: "401 Unauthorized",+ body: "{\"error\":\"bad_verification_code\"}".to_string(),+ }]);+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());++ let error = client+ .exchange_setup_code("sync-client-id", "very-secret", "sensitive-code")+ .await+ .err()+ .unwrap()+ .to_string();++ assert!(error.contains("401 Unauthorized"));+ assert!(!error.contains("very-secret"));+ assert!(!error.contains("sensitive-code"));+ server.finish();+}++#[tokio::test]+async fn finds_installation_on_a_later_page() {+ let first_page: Vec<_> = (1..=100)+ .map(|id| serde_json::json!({ "id": id }))+ .collect();+ let server = MockServer::start(vec![+ MockResponse::json(serde_json::json!({+ "total_count": 101,+ "installations": first_page+ })),+ MockResponse::json(serde_json::json!({+ "total_count": 101,+ "installations": [{ "id": 999 }]+ })),+ ]);+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());++ let installations = client+ .list_user_installations("user-access-token")+ .await+ .unwrap();++ assert_eq!(installations.len(), 101);+ assert!(+ installations+ .iter()+ .any(|installation| installation.id == 999)+ );+ let requests = server.finish();+ assert!(requests[0].starts_with("GET /user/installations?per_page=100&page=1 HTTP/1.1"));+ assert!(requests[1].starts_with("GET /user/installations?per_page=100&page=2 HTTP/1.1"));+ for request in requests {+ let lowercase_request = request.to_ascii_lowercase();+ assert!(lowercase_request.contains("authorization: bearer user-access-token"));+ assert!(lowercase_request.contains("accept: application/vnd.github+json"));+ assert!(lowercase_request.contains("x-github-api-version: 2022-11-28"));+ assert!(lowercase_request.contains("user-agent: macro-auth-service"));+ }+}++#[tokio::test]+async fn rejects_unsuccessful_installation_list_without_leaking_token() {+ let server = MockServer::start(vec![MockResponse {+ status: "403 Forbidden",+ body: "{\"message\":\"forbidden\"}".to_string(),+ }]);+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());++ let error = client+ .list_user_installations("sensitive-user-token")+ .await+ .unwrap_err()+ .to_string();++ assert!(error.contains("403 Forbidden"));+ assert!(!error.contains("sensitive-user-token"));+ server.finish();+}++#[tokio::test]+async fn rejects_malformed_later_pagination_response_without_leaking_token() {+ let server = MockServer::start(vec![+ MockResponse::json(serde_json::json!({+ "total_count": 2,+ "installations": [{ "id": 1 }]+ })),+ MockResponse {+ status: "200 OK",+ body: "not-json sensitive-user-token".to_string(),+ },+ ]);+ let client = GithubSyncClientImpl::with_api_base_url(server.base_url.clone());++ let error = client+ .list_user_installations("sensitive-user-token")+ .await+ .unwrap_err()+ .to_string();++ assert!(error.contains("malformed response"));+ assert!(!error.contains("sensitive-user-token"));+ assert_eq!(server.finish().len(), 2);+}diff --git a/crates/github/src/outbound/pg_github_sync_repo.rs b/crates/github/src/outbound/pg_github_sync_repo.rsindex cf57e36ee6..424df4dae4 100644--- a/crates/github/src/outbound/pg_github_sync_repo.rs+++ b/crates/github/src/outbound/pg_github_sync_repo.rs@@ -368,20 +368,13 @@ impl GithubSyncRepo for PgGithubSyncRepo {}#[tracing::instrument(skip(self), err)]- async fn upsert_installation_installer(- &self,- installation_id: &str,- github_user_id: &str,- ) -> Result<(), Self::Err> {+ async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {sqlx::query!(r#"- INSERT INTO github_app_installation_installer (installation_id, github_user_id)- VALUES ($1, $2)- ON CONFLICT (installation_id)- DO UPDATE SET github_user_id = EXCLUDED.github_user_id, updated_at = NOW()+ DELETE FROM github_app_installation+ WHERE id = $1"#,installation_id,- github_user_id,).execute(&self.pool).await?;@@ -390,48 +383,84 @@ impl GithubSyncRepo for PgGithubSyncRepo {}#[tracing::instrument(skip(self), err)]- async fn get_installation_ids_by_installer(+ async fn upsert_installation_request(&self,github_user_id: &str,- ) -> Result<Vec<String>, Self::Err> {- let installation_ids = sqlx::query_scalar!(+ source: &GithubAppInstallationSource,+ ) -> Result<(), Self::Err> {+ sqlx::query!(r#"- SELECT installation_id- FROM github_app_installation_installer- WHERE github_user_id = $1- ORDER BY installation_id+ INSERT INTO github_app_installation_request (github_user_id, source_id, source_type)+ VALUES ($1, $2, $3::github_app_installation_source_type)+ ON CONFLICT (github_user_id) DO UPDATE+ SET source_id = EXCLUDED.source_id,+ source_type = EXCLUDED.source_type,+ updated_at = NOW()"#,github_user_id,+ source.source_id(),+ source.source_type() as &str,)- .fetch_all(&self.pool)+ .execute(&self.pool).await?;- Ok(installation_ids)+ Ok(())}#[tracing::instrument(skip(self), err)]- async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {- sqlx::query!(+ async fn get_installation_request(+ &self,+ github_user_id: &str,+ ) -> Result<Option<GithubAppInstallationSource>, Self::Err> {+ let row = sqlx::query!(r#"- DELETE FROM github_app_installation- WHERE id = $1+ SELECT source_id AS "source_id!", source_type::text AS "source_type!"+ FROM github_app_installation_request+ WHERE github_user_id = $1"#,- installation_id,+ github_user_id,)- .execute(&self.pool)+ .fetch_optional(&self.pool).await?;- Ok(())+ let Some(row) = row else {+ return Ok(None);+ };++ match row.source_type.as_str() {+ "team" => match uuid::Uuid::parse_str(&row.source_id) {+ Ok(team_id) => Ok(Some(GithubAppInstallationSource::Team(team_id))),+ Err(error) => {+ tracing::warn!(+ github_user_id,+ source_id = row.source_id,+ error=?error,+ "github_app_installation_request team source_id is not a UUID"+ );+ Ok(None)+ }+ },+ "user" => Ok(Some(GithubAppInstallationSource::User(row.source_id))),+ _ => {+ tracing::warn!(+ github_user_id,+ source_id = row.source_id,+ source_type = row.source_type,+ "github_app_installation_request has unknown source_type"+ );+ Ok(None)+ }+ }}#[tracing::instrument(skip(self), err)]- async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {+ async fn delete_installation_request(&self, github_user_id: &str) -> Result<(), Self::Err> {sqlx::query!(r#"- DELETE FROM github_app_installation_installer- WHERE installation_id = $1+ DELETE FROM github_app_installation_request+ WHERE github_user_id = $1"#,- installation_id,+ github_user_id,).execute(&self.pool).await?;diff --git a/crates/github/src/outbound/pg_github_sync_repo/test.rs b/crates/github/src/outbound/pg_github_sync_repo/test.rsindex c2353a3323..081c4211af 100644--- a/crates/github/src/outbound/pg_github_sync_repo/test.rs+++ b/crates/github/src/outbound/pg_github_sync_repo/test.rs@@ -871,67 +871,7 @@ async fn test_upsert_installation_sources_idempotent_user_source(pool: Pool<Post}// ----------------------------------------------------------------------------// installation installer-// -----------------------------------------------------------------------------#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_upsert_installation_installer_records_installer(pool: Pool<Postgres>) {- let repo = PgGithubSyncRepo::new(pool);-- repo.upsert_installation_installer("11111", "12345")- .await- .unwrap();- repo.upsert_installation_installer("22222", "12345")- .await- .unwrap();-- let installation_ids = repo- .get_installation_ids_by_installer("12345")- .await- .unwrap();-- assert_eq!(installation_ids, vec!["11111", "22222"]);-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_upsert_installation_installer_replaces_installer(pool: Pool<Postgres>) {- let repo = PgGithubSyncRepo::new(pool);-- repo.upsert_installation_installer("11111", "12345")- .await- .unwrap();- repo.upsert_installation_installer("11111", "67890")- .await- .unwrap();-- assert!(- repo.get_installation_ids_by_installer("12345")- .await- .unwrap()- .is_empty()- );- assert_eq!(- repo.get_installation_ids_by_installer("67890")- .await- .unwrap(),- vec!["11111"]- );-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_get_installation_ids_by_installer_empty(pool: Pool<Postgres>) {- let repo = PgGithubSyncRepo::new(pool);-- let installation_ids = repo- .get_installation_ids_by_installer("missing")- .await- .unwrap();-- assert!(installation_ids.is_empty());-}--// ----------------------------------------------------------------------------// delete_installation_sources / delete_installation_installer+// delete_installation_sources// ---------------------------------------------------------------------------#[sqlx::test(@@ -967,31 +907,77 @@ async fn test_delete_installation_sources_missing_installation_is_noop(pool: Poorepo.delete_installation_sources("missing").await.unwrap();}+// ---------------------------------------------------------------------------+// installation requests+// ---------------------------------------------------------------------------+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_delete_installation_installer_removes_installer(pool: Pool<Postgres>) {+async fn test_installation_request_roundtrip(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);+ let team_id: Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();++ assert_eq!(repo.get_installation_request("777").await.unwrap(), None);- repo.upsert_installation_installer("11111", "12345")+ repo.upsert_installation_request("777", &GithubAppInstallationSource::Team(team_id)).await.unwrap();- repo.upsert_installation_installer("22222", "12345")+ assert_eq!(+ repo.get_installation_request("777").await.unwrap(),+ Some(GithubAppInstallationSource::Team(team_id))+ );++ repo.delete_installation_request("777").await.unwrap();+ assert_eq!(repo.get_installation_request("777").await.unwrap(), None);+ // Deleting a missing request is a no-op.+ repo.delete_installation_request("777").await.unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_upsert_installation_request_replaces_earlier_request(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);+ let first_team: Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();++ repo.upsert_installation_request("777", &GithubAppInstallationSource::Team(first_team)).await.unwrap();+ repo.upsert_installation_request(+ "777",+ &GithubAppInstallationSource::User("macro|[email protected]".to_string()),+ )+ .await+ .unwrap();- repo.delete_installation_installer("11111").await.unwrap();-+ // The latest request wins; requests by other users are untouched.assert_eq!(- repo.get_installation_ids_by_installer("12345")- .await- .unwrap(),- vec!["22222"]+ repo.get_installation_request("777").await.unwrap(),+ Some(GithubAppInstallationSource::User(+ "macro|[email protected]".to_string()+ )));}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_delete_installation_installer_missing_installation_is_noop(pool: Pool<Postgres>) {+async fn test_installation_requests_are_scoped_by_github_user(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);+ let team_id: Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();++ repo.upsert_installation_request("777", &GithubAppInstallationSource::Team(team_id))+ .await+ .unwrap();+ repo.upsert_installation_request(+ "888",+ &GithubAppInstallationSource::User("macro|[email protected]".to_string()),+ )+ .await+ .unwrap();- repo.delete_installation_installer("missing").await.unwrap();- repo.delete_installation_installer("missing").await.unwrap();+ repo.delete_installation_request("777").await.unwrap();++ assert_eq!(repo.get_installation_request("777").await.unwrap(), None);+ assert_eq!(+ repo.get_installation_request("888").await.unwrap(),+ Some(GithubAppInstallationSource::User(+ "macro|[email protected]".to_string()+ ))+ );}diff --git a/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.down.sql b/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.down.sqlnew file mode 100644index 0000000000..c4ab14c5e7--- /dev/null+++ b/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.down.sql@@ -0,0 +1 @@+DROP TABLE github_app_installation_request;diff --git a/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.up.sql b/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.up.sqlnew file mode 100644index 0000000000..7cc35c1ed1--- /dev/null+++ b/crates/macro_db_client/migrations/20260804132220_github_app_installation_request.up.sql@@ -0,0 +1,19 @@+-- Pending GitHub App installation requests awaiting org-admin approval.+--+-- When a non-admin requests the sync app install, GitHub's setup callback+-- carries setup_action=request with no installation_id (the installation does+-- not exist until an admin approves). The callback's OAuth code identifies the+-- requesting GitHub user, so the requested Macro source is parked here and the+-- association completes when the installation.created webhook arrives with a+-- matching requester.+--+-- Keyed by requester so a repeat request (e.g. after switching teams) replaces+-- the earlier one: only the requester's latest intent is honored on approval.+CREATE TABLE github_app_installation_request+(+ github_user_id TEXT PRIMARY KEY, -- The stable numeric github user id of the requester+ source_id TEXT NOT NULL,+ source_type github_app_installation_source_type NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex a74c5e8b6f..ff12ca7458 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 0a0f49fb1d..431bd3c741 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -1328,10 +1328,10 @@ export class Sdk extends HeyApiClient {}/**- * Redirects the user to the github sync app installation page.+ * Redirects an authenticated user to the github sync app installation page.*/- public installSync<ThrowOnError extends boolean = false>(options?: Options<InstallSyncData, ThrowOnError>): RequestResult<unknown, unknown, ThrowOnError> {- return (options?.client ?? this.client).get<unknown, unknown, ThrowOnError>({ url: '/github/install-sync', ...options });+ public installSync<ThrowOnError extends boolean = false>(options?: Options<InstallSyncData, ThrowOnError>): RequestResult<unknown, InstallSyncErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<unknown, InstallSyncErrors, ThrowOnError>({ url: '/github/install-sync', ...options });}/**diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex da944c611d..b5a9a2d06b 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -10963,6 +10963,13 @@ export type InstallSyncData = {url: '/github/install-sync';};+export type InstallSyncErrors = {+ /**+ * Authentication failed+ */+ 401: unknown;+};+export type HealthHandlerData = {body?: never;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex cc99b57896..492709d071 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -7953,11 +7953,14 @@"/github/install-sync": {"get": {"tags": ["github::inbound::github_sync_router"],- "summary": "Redirects the user to the github sync app installation page.",+ "summary": "Redirects an authenticated user to the github sync app installation page.","operationId": "install_sync","responses": {"307": {- "description": "Redirects to the github sync app installation page"+ "description": "Temporary redirect to the GitHub sync app installation page"+ },+ "401": {+ "description": "Authentication failed"}}}diff --git a/services/authentication_service/src/api/oauth2/github.rs b/services/authentication_service/src/api/oauth2/github.rsindex 6c906d1e0d..c3f4afadc6 100644--- a/services/authentication_service/src/api/oauth2/github.rs+++ b/services/authentication_service/src/api/oauth2/github.rs@@ -101,8 +101,7 @@ async fn link_user(.map(|id| id.into_owned().lowercase()).context("valid macro user id")?;- let link = ctx- .github_link_service+ ctx.github_link_service.link_user(¯o_user_id,&fusionauth_user_id,@@ -112,20 +111,6 @@ async fn link_user().await?;- // Associate any GitHub App installations this GitHub user made before- // linking. Fire-and-forget: the link itself succeeded, and association can- // also happen lazily on the next installation webhook.- let document_storage_service_client = ctx.document_storage_service_client.clone();- tokio::spawn(async move {- document_storage_service_client- .associate_github_installations(&link.github_user_id)- .await- .inspect_err(|e| {- tracing::error!(error=?e, "failed to associate github installations after link");- })- .ok();- });-Ok(())}diff --git a/services/document_storage_service/src/api/internal/associate_github_installations.rs b/services/document_storage_service/src/api/internal/associate_github_installations.rsdeleted file mode 100644index a3cc048110..0000000000--- a/services/document_storage_service/src/api/internal/associate_github_installations.rs+++ /dev/null@@ -1,48 +0,0 @@-use crate::api::context::{ApiContext, AuthorizationService};-use axum::{- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use github::domain::ports::GithubSyncService;-use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};-use model::response::{EmptyResponse, GenericErrorResponse};--#[derive(serde::Deserialize)]-pub struct Params {- pub github_user_id: String,-}--/// Associates GitHub App installations installed by the given GitHub user with-/// that user's Macro sources. Called by the authentication service after a-/// `github_links` row is created, so installations made before linking get-/// associated retroactively.-#[utoipa::path(- post,- path = "/github/installations/{github_user_id}/associate",- operation_id = "associate_github_installations",- params(- ("github_user_id" = String, Path, description = "Stable numeric GitHub user ID")- ),- responses(- (status = 200, body = EmptyResponse),- (status = 401, body = GenericErrorResponse),- (status = 500, body = GenericErrorResponse),- )-)]-#[tracing::instrument(skip(ctx, _auth), err(Debug))]-pub async fn associate_github_installations_handler(- State(ctx): State<ApiContext>,- _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,- Path(Params { github_user_id }): Path<Params>,-) -> Result<Response, Response> {- ctx.github_sync_service- .associate_installations_for_github_user(&github_user_id)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to associate github installations");- (StatusCode::INTERNAL_SERVER_ERROR).into_response()- })?;-- Ok((StatusCode::OK, axum::Json(EmptyResponse {})).into_response())-}diff --git a/services/document_storage_service/src/api/internal/mod.rs b/services/document_storage_service/src/api/internal/mod.rsindex f1d3bd8ba6..29b7cadbf1 100644--- a/services/document_storage_service/src/api/internal/mod.rs+++ b/services/document_storage_service/src/api/internal/mod.rs@@ -28,8 +28,6 @@ use macro_middleware::cloud_storage::{document::ensure_document_exists, thread::ensure_thread_exists,};-mod associate_github_installations;-/// Internal routes authenticate through extractors on each handler./// These routes are not part of the public Swagger documentation.pub fn router(state: ApiContext) -> Router<ApiContext> {@@ -196,11 +194,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {).route("/item_ids", get(get_item_ids::get_item_ids_handler)).route("/validate_item_ids", post(validate_item_ids::handler))- // Github routes- .route(- "/github/installations/{github_user_id}/associate",- post(associate_github_installations::associate_github_installations_handler),- ).route("/health", get(health_handler))}diff --git a/services/document_storage_service/src/api/mod.rs b/services/document_storage_service/src/api/mod.rsindex 007227e249..fc6852298a 100644--- a/services/document_storage_service/src/api/mod.rs+++ b/services/document_storage_service/src/api/mod.rs@@ -88,6 +88,8 @@ fn items_router(state: ApiContext) -> Router<ApiContext> {fn api_router(state: ApiContext) -> Router {let github_sync_service_router_state = GithubSyncRouterState {service: state.github_sync_service.clone(),+ entity_access_service: state.entity_access_service.clone(),+ authorization_state: state.authorization_state.clone(),};// Webhook router is outside auth — LiveKit validates via its own JWT,diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rsindex f3e6e16dfe..e6ceaded5e 100644--- a/services/document_storage_service/src/config.rs+++ b/services/document_storage_service/src/config.rs@@ -25,6 +25,8 @@ env_vars! {pub struct OpensearchPassword;pub struct GithubSyncAppUrl;pub struct GithubSyncAppClientId;+ pub struct GithubInstallationStateSecret;+ pub struct GithubSyncAppClientSecret;/// Comma-separated Kafka bootstrap servers for the macro event broker.pub struct KafkaBrokers;pub struct LivekitServerUrl;@@ -98,6 +100,8 @@ pub struct Config {pub opensearch_password: OpensearchPassword,pub github_sync_app_url: GithubSyncAppUrl,pub github_sync_app_client_id: GithubSyncAppClientId,+ pub github_installation_state_secret: GithubInstallationStateSecret,+ pub github_sync_app_client_secret: GithubSyncAppClientSecret,pub kafka_brokers: KafkaBrokers,pub livekit_server_url: LivekitServerUrl,pub livekit_api_key: LivekitApiKey,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 5b3cada917..6e38e4fbf9 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -501,6 +501,8 @@ async fn main() -> anyhow::Result<()> {github_sync_app_url: config.github_sync_app_url.to_string(),sync_app_pem: config.github_sync_app_pem_secret_key.as_ref().to_string(),sync_app_client_id: config.github_sync_app_client_id.to_string(),+ sync_app_client_secret: config.github_sync_app_client_secret.to_string(),+ installation_state_secret: config.github_installation_state_secret.to_string(),},document_service.clone(),foreign_entity_service.clone(),