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
Revert "feat(github): better GitHub app installation tracking" (#5355)
Will Hutchinson4d75fee38152
diff --git a/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json b/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.jsonnew file mode 100644index 0000000000..f4dbba6dd1--- /dev/null+++ b/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json@@ -0,0 +1,22 @@+{+ "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-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json b/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.jsonnew file mode 100644index 0000000000..8b8cc329a2--- /dev/null+++ b/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json@@ -0,0 +1,14 @@+{+ "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-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json b/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.jsonnew file mode 100644index 0000000000..c02348956b--- /dev/null+++ b/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json@@ -0,0 +1,15 @@+{+ "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/Cargo.lock b/Cargo.lockindex 73b976d07b..d075fd7491 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6131,7 +6131,6 @@ dependencies = ["anyhow","axum","axum-extra",- "base64 0.22.1","chrono","document_sub_type","documents",@@ -6142,7 +6141,6 @@ dependencies = ["hmac 0.12.1","http-body-util","jsonwebtoken 10.3.0",- "macro_authorization","macro_db_migrator","macro_env","macro_env_var",@@ -6154,7 +6152,6 @@ dependencies = ["model-entity","model-error-response","model_notifications",- "model_user","models_permissions","notification","redis",@@ -6170,7 +6167,6 @@ dependencies = ["tokio","tower 0.5.3","tracing",- "url","urlencoding","utoipa","uuid",diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex b79b854498..5858e9f80f 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -7802,14 +7802,11 @@"/github/install-sync": {"get": {"tags": ["github::inbound::github_sync_router"],- "summary": "Redirects an authenticated user to the github sync app installation page.",+ "summary": "Redirects the user to the github sync app installation page.","operationId": "install_sync","responses": {"307": {- "description": "Temporary redirect to the GitHub sync app installation page"- },- "401": {- "description": "Authentication failed"+ "description": "Redirects to the github sync app installation page"}}}diff --git a/crates/document_storage_service_client/src/github.rs b/crates/document_storage_service_client/src/github.rsnew file mode 100644index 0000000000..da61504254--- /dev/null+++ b/crates/document_storage_service_client/src/github.rs@@ -0,0 +1,37 @@+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 781ec71415..a3bc80c904 100644--- a/crates/document_storage_service_client/src/lib.rs+++ b/crates/document_storage_service_client/src/lib.rs@@ -4,6 +4,7 @@ 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 1eb225df2a..5a62998925 100644--- a/crates/github/Cargo.toml+++ b/crates/github/Cargo.toml@@ -5,14 +5,7 @@ publish = falseversion = "0.1.0"[features]-axum = [- "dep:axum",- "dep:axum-extra",- "dep:entity_access",- "dep:macro_authorization",- "dep:model-error-response",- "dep:utoipa",-]+axum = ["dep:axum", "dep:axum-extra", "dep:model-error-response", "dep:utoipa"]default = ["axum", "inbound", "link", "outbound", "ports", "sync"]inbound = ["axum", "ports"]link = ["dep:entity_access", "dep:foreign_entity", "ports"]@@ -39,13 +32,11 @@ 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 = [@@ -56,9 +47,6 @@ 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 }@@ -73,7 +61,6 @@ 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 }@@ -94,7 +81,6 @@ 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.rsdeleted file mode 100644index 0241c23fcb..0000000000--- a/crates/github/src/domain/models/installation_state.rs+++ /dev/null@@ -1,112 +0,0 @@-//! 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.rsdeleted file mode 100644index dc6bcd6606..0000000000--- a/crates/github/src/domain/models/installation_state/test.rs+++ /dev/null@@ -1,149 +0,0 @@-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 c037cab0ee..794baa50f9 100644--- a/crates/github/src/domain/models/mod.rs+++ b/crates/github/src/domain/models/mod.rs@@ -3,14 +3,10 @@#[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,@@ -19,10 +15,9 @@ pub use pull_request::{GithubPullRequestRef, GithubPullRequestStatus,};pub use sync::{- GithubAppInstallationSource, GithubInstallationAccessToken, GithubInstallationSetupAction,- GithubKey, GithubSetupAccessToken, GithubUserInstallation, GithubUserInstallationsPage,- GithubWebhookEventType, MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference,- ValidatedGithubWebhookEvent, extract_github_mentions, strip_markdown_code,+ GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,+ MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,+ extract_github_mentions, strip_markdown_code,};/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]@@ -42,19 +37,4 @@ 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,}diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rsindex d4f5b4d9e5..f954f74d43 100644--- a/crates/github/src/domain/models/sync.rs+++ b/crates/github/src/domain/models/sync.rs@@ -7,32 +7,6 @@ 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);@@ -56,40 +30,6 @@ 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,-}--/// 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 {diff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rsindex 235b14a14a..5d8c6cc6fc 100644--- a/crates/github/src/domain/ports/sync.rs+++ b/crates/github/src/domain/ports/sync.rs@@ -6,9 +6,8 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::domain::models::{EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,- GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, GithubSetupAccessToken,- GithubUserInstallation, MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference,- ValidatedGithubWebhookEvent,+ GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, MacroTaskId,+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,};/// Repository for accessing github sync data from the database.@@ -102,12 +101,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(+ &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(+ &self,+ github_user_id: &str,+ ) -> impl Future<Output = Result<Vec<String>, 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(&self,installation_id: &str,) -> impl Future<Output = Result<(), 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(+ &self,+ installation_id: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;}/// Client interface for making GitHub sync API calls.@@ -115,20 +135,6 @@ 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;-/// Generates an installation access token for a given GitHub App installation.fn generate_installation_access_token(&self,@@ -180,39 +186,21 @@ pub trait GithubSyncService: Send + Sync + 'static {webhook_event: &ValidatedGithubWebhookEvent,) -> impl Future<Output = Result<(), GithubError>> + Send;- /// 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 and ownership.- 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.- ///- /// New installation flows must use [`GithubSyncService::begin_installation_setup`].+ /// Returns the github sync app installation urlfn 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.+ ///+ /// 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;+/// Generates an installation access token for the github sync appfn generate_installation_access_token(&self,diff --git a/crates/github/src/domain/service/sync/handle_installation.rs b/crates/github/src/domain/service/sync/handle_installation.rsindex d6fd611f5d..3ddf28c83b 100644--- a/crates/github/src/domain/service/sync/handle_installation.rs+++ b/crates/github/src/domain/service/sync/handle_installation.rs@@ -18,10 +18,50 @@ impl<N: NotificationIngress,> GithubSyncServiceImpl<D, R, C, F, N>{+ /// Handle `installation` events with action `created`.+ ///+ /// Associates the GitHub App installation with the installer's team or user source.+ #[tracing::instrument(skip(self, event), err)]+ pub(crate) async fn handle_installation_created(+ &self,+ event: &ValidatedGithubWebhookEvent,+ ) -> Result<(), GithubError> {+ let installation_id = event+ .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");++ // 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)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ let sources = self.sources_for_github_user(&sender_github_user_id).await?;+ if sources.is_empty() {+ tracing::warn!(+ installation_id,+ "no github link found for sender, cannot associate installation with a source"+ );+ return Ok(());+ }++ self.associate_installation_with_sources(installation_id, &sources)+ .await+ }+/// Handle `installation` events with action `deleted`.///- /// Removes the installation's source associations. Idempotent: GitHub retries- /// webhooks, so deleting an already-removed installation succeeds.+ /// 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.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_installation_deleted(&self,@@ -39,9 +79,66 @@ 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 247c73fbb7..0c0868fdad 100644--- a/crates/github/src/domain/service/sync/mod.rs+++ b/crates/github/src/domain/service/sync/mod.rs@@ -13,11 +13,9 @@ mod notify_pr_checks;use crate::domain::{models::{EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,- GithubAppInstallationSource, GithubError, GithubInstallationAccessToken,- GithubInstallationSetupAction, GithubKey, GithubPullRequestDetails,- GithubPullRequestStatus, GithubWebhookEventType, InstallationState, MacroTaskId,+ GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,+ GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId,ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,- sign_installation_state, verify_installation_state,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -54,10 +52,6 @@ pub struct GithubSyncConfig {pub 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.@@ -986,12 +980,7 @@ impl<Ok(())}GithubWebhookEventType::Installation => match action {- Some("created") => {- tracing::info!(- "GitHub-initiated installation association is unsupported; use the authenticated setup flow"- );- Ok(())- }+ Some("created") => self.handle_installation_created(webhook_event).await,Some("deleted") => self.handle_installation_deleted(webhook_event).await,_ => {tracing::debug!(action, "skipping unhandled installation action");@@ -1001,97 +990,63 @@ impl<}}- #[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()))?;- installation_url- .query_pairs_mut()- .append_pair("state", &signed_state);-- Ok(installation_url.into())+ fn get_github_sync_app_url(&self) -> &str {+ &self.config.github_sync_app_url}- #[tracing::instrument(skip(self, state, code), err)]- async fn complete_installation_setup(+ #[tracing::instrument(skip(self), err)]+ async fn associate_installations_for_github_user(&self,- state: &str,- code: Option<&str>,- installation_id: Option<u64>,- setup_action: &str,+ github_user_id: &str,) -> Result<(), GithubError> {- 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)?;-- if setup_action == GithubInstallationSetupAction::Request {+ let installation_ids = self+ .repo+ .get_installation_ids_by_installer(github_user_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ if installation_ids.is_empty() {+ tracing::debug!(github_user_id, "no installations recorded for github user");return Ok(());}- let code = code.ok_or(GithubError::MissingInstallationSetupField("code"))?;- let installation_id = installation_id.ok_or(GithubError::MissingInstallationSetupField(- "installation_id",- ))?;- let access_token = self- .client- .exchange_setup_code(- &self.config.sync_app_client_id,- &self.config.sync_app_client_secret,- code,- )- .await?;- 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);+ 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(());}- let source = match state.team_id {- Some(team_id) => GithubAppInstallationSource::Team(team_id),- None => GithubAppInstallationSource::User(state.macro_user_id.into()),- };- self.associate_installation_with_sources(installation_id, &[source])- .await- }+ 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;+ }+ };- fn get_github_sync_app_url(&self) -> &str {- &self.config.github_sync_app_url+ // Keep going on failure so one broken installation doesn't block+ // associating the rest.+ self.associate_installation_with_sources(installation_id, &sources)+ .await+ .inspect_err(|error| {+ tracing::error!(+ error=?error,+ installation_id,+ "failed to associate installation with sources"+ );+ })+ .ok();+ }++ Ok(())}#[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 8ee189af91..41cc93a287 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -5,9 +5,8 @@ use crate::domain::{models::{EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,GithubInstallationAccessToken, GithubKey, GithubPullRequestCheckRun,- GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestStatus,- GithubSetupAccessToken, GithubUserInstallation, MacroTaskId, ResolvedTeamTaskReference,- TeamTaskReference, ValidatedGithubWebhookEvent,+ GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestStatus, MacroTaskId,+ ResolvedTeamTaskReference, TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -322,6 +321,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>>,}impl StubSyncRepo {@@ -335,6 +336,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()),}}@@ -415,6 +417,18 @@ impl StubSyncRepo {fn installation_sources(&self) -> Vec<(String, Vec<GithubAppInstallationSource>)> {self.installation_sources.lock().unwrap().clone()}++ fn with_installation_installer(self, installation_id: &str, github_user_id: &str) -> Self {+ self.installation_installers+ .lock()+ .unwrap()+ .insert(installation_id.to_string(), github_user_id.to_string());+ self+ }++ fn installation_installers(&self) -> HashMap<String, String> {+ self.installation_installers.lock().unwrap().clone()+ }}impl GithubSyncRepo for StubSyncRepo {@@ -577,6 +591,34 @@ impl GithubSyncRepo for StubSyncRepo {Ok(())}+ async fn upsert_installation_installer(+ &self,+ installation_id: &str,+ github_user_id: &str,+ ) -> Result<(), Self::Err> {+ self.installation_installers+ .lock()+ .unwrap()+ .insert(installation_id.to_string(), github_user_id.to_string());+ Ok(())+ }++ async fn get_installation_ids_by_installer(+ &self,+ github_user_id: &str,+ ) -> Result<Vec<String>, Self::Err> {+ let mut installation_ids: Vec<String> = self+ .installation_installers+ .lock()+ .unwrap()+ .iter()+ .filter(|(_, installer)| installer.as_str() == github_user_id)+ .map(|(installation_id, _)| installation_id.clone())+ .collect();+ installation_ids.sort();+ Ok(installation_ids)+ }+async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {self.installation_source_rows.lock()@@ -584,6 +626,14 @@ impl GithubSyncRepo for StubSyncRepo {.remove(installation_id);Ok(())}++ async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {+ self.installation_installers+ .lock()+ .unwrap()+ .remove(installation_id);+ Ok(())+ }}#[tokio::test]@@ -628,11 +678,6 @@ 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>>,- fail_setup_code_exchange: Mutex<bool>,- fail_user_installation_list: Mutex<bool>,pr_comments: Mutex<Vec<PrCommentCall>>,pull_request_details: Mutex<HashMap<String, GithubPullRequestDetails>>,pull_request_details_calls: Mutex<Vec<PullRequestDetailsCall>>,@@ -643,11 +688,6 @@ 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()),- fail_setup_code_exchange: Mutex::new(false),- fail_user_installation_list: Mutex::new(false),pr_comments: Mutex::new(Vec::new()),pull_request_details: Mutex::new(HashMap::new()),pull_request_details_calls: Mutex::new(Vec::new()),@@ -656,29 +696,6 @@ 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 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()}@@ -714,37 +731,6 @@ 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 generate_installation_access_token(&self,_jwt: &str,@@ -1061,12 +1047,9 @@ fn make_sync_service_with_repo_and_notification_ingress(GithubSyncServiceImpl::new(GithubSyncConfig {webhook_secret: "test-webhook-secret".to_string(),- github_sync_app_url: "https://github.com/apps/test/installations/new?existing=1"- .to_string(),+ github_sync_app_url: "test".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,@@ -1083,12 +1066,9 @@ 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: "https://github.com/apps/test/installations/new?existing=1"- .to_string(),+ github_sync_app_url: "test".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,@@ -2736,22 +2716,15 @@ async fn github_pr_status_changed_edited_does_not_notify() {}#[tokio::test]-async fn authenticated_installation_setup_backfill_does_not_notify() {- let service = make_sync_service();- service.client.set_user_installations(&[12345]);+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);service.client.set_open_pull_requests(vec![backfilled_pull_request("Backfilled PR")]);+ let event = installation_created_event(12345, 12345);- service- .complete_installation_setup(- &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),- Some("setup-code"),- Some(12345),- "install",- )- .await- .unwrap();+ service.process_webhook_event(&event).await.unwrap();assert_eq!(service.foreign_entity_service.foreign_entities().len(), 1);assert!(service.notification_ingress.requests().is_empty());@@ -3946,17 +3919,188 @@ fn installation_created_event(sender_id: u64, installation_id: u64) -> Validated}#[tokio::test]-async fn installation_created_is_noop() {- let service = make_sync_service();+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),+ ],+ )]+ );+}++#[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]);+ 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());+}++#[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();+ 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 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);++ service.process_webhook_event(&event).await.unwrap();++ assert_eq!(+ service.client.list_open_pull_requests_calls(),+ vec!["test-token".to_string()]+ );++ 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);++ 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);+ }++ 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());+}++#[tokio::test]+async fn installation_created_backfill_is_idempotent() {+ 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]);++ 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);++ 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());+}++#[tokio::test]+async fn installation_created_no_github_link() {+ 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.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());++ // 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())])+ );+}++#[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())])+ );}// ---------------------------------------------------------------------------@@ -3975,7 +4119,7 @@ fn installation_deleted_event(sender_id: u64, installation_id: u64) -> Validated}#[tokio::test]-async fn installation_deleted_removes_only_installation_sources() {+async fn installation_deleted_removes_sources_and_installer() {let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();let repo = StubSyncRepo::new()@@ -3985,7 +4129,9 @@ async fn installation_deleted_removes_only_installation_sources() {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);@@ -4000,6 +4146,11 @@ async fn installation_deleted_removes_only_installation_sources() {.unwrap().is_empty());+ assert_eq!(+ service.repo.installation_installers(),+ HashMap::from([("88888".to_string(), "67890".to_string())])+ );+// Other installations are untouched.assert_eq!(service@@ -4023,14 +4174,7 @@ async fn installation_deleted_unknown_installation_succeeds() {service.process_webhook_event(&event).await.unwrap();service.process_webhook_event(&event).await.unwrap();- assert!(- service- .repo- .get_installation_sources("99999")- .await- .unwrap()- .is_empty()- );+ assert!(service.repo.installation_installers().is_empty());}#[tokio::test]@@ -4047,6 +4191,143 @@ 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// ---------------------------------------------------------------------------@@ -5048,339 +5329,3 @@ 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()-}--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!(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_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_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_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(StubSyncRepo::new().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_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_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_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_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_verifies_request_state_then_no_ops() {- let service = make_sync_service();- service- .complete_installation_setup(- &installation_setup_state(None, chrono::Utc::now().timestamp() + 60),- None,- None,- "request",- )- .await- .unwrap();- assert!(service.client.setup_code_exchange_calls().is_empty());- assert!(service.repo.installation_sources().is_empty());-- assert!(matches!(- service- .complete_installation_setup("invalid", None, None, "request")- .await,- Err(GithubError::InvalidInstallationState)- ));-}--#[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 repeated_installation_association_is_idempotent() {- let service = make_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 883bd883e9..600e51d32c 100644--- a/crates/github/src/inbound.rs+++ b/crates/github/src/inbound.rs@@ -26,14 +26,6 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {crate::domain::models::GithubError::InvalidWebhookSignature => {(StatusCode::UNAUTHORIZED, "unauthenticated")}- crate::domain::models::GithubError::Forbidden => (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 4c93fe6002..9fdbb4ea4b 100644--- a/crates/github/src/inbound/github_sync_router/mod.rs+++ b/crates/github/src/inbound/github_sync_router/mod.rs@@ -8,200 +8,102 @@#[cfg(test)]mod test;-use std::sync::Arc;-use axum::{Router,- extract::{FromRef, FromRequest, Query, Request, State},+ extract::{FromRequest, 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 uuid::Uuid;+use std::sync::Arc;use crate::domain::{- models::{GithubError, InstallationState, ValidatedGithubWebhookEvent},+ models::{GithubError, ValidatedGithubWebhookEvent},ports::GithubSyncService,};-/// Router state containing the GitHub sync, entity access, and authorization services.-pub struct GithubSyncRouterState<T, Eas, Auth> {- /// The GitHub sync service implementation.+/// Router state containing the github sync service.+pub struct GithubSyncRouterState<T> {+ /// 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 the services don't need to be Clone (they are behind Arcs).-impl<T, Eas, Auth> Clone for GithubSyncRouterState<T, Eas, Auth> {+// Manual Clone impl so T doesn't need to be Clone (it's behind Arc).+impl<T> Clone for GithubSyncRouterState<T> {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, Eas, Auth, S>(state: GithubSyncRouterState<T, Eas, Auth>) -> Router<S>+pub fn github_sync_router<T, S>(state: GithubSyncRouterState<T>) -> Router<S>whereT: GithubSyncService,- Eas: EntityAccessService,- Auth: MacroAuthorizationService,S: Send + Sync + 'static,{Router::new()- .route(- "/install-sync",- axum::routing::get(install_sync_handler::<T, Eas, Auth>),- )+ .route("/install-sync", axum::routing::get(install_sync_handler)).route("/sync-redirect",- axum::routing::get(sync_redirect_handler::<T, Eas, Auth>),+ axum::routing::get(sync_redirect_handler::<T>),).route("/webhook",- axum::routing::post(github_webhook_event_handler::<T, Eas, Auth>),+ axum::routing::post(github_webhook_event_handler),).with_state(state)}-/// Redirects an authenticated user to the github sync app installation page.+/// Redirects the user to the github sync app installation page.#[utoipa::path(get,path = "/github/install-sync",operation_id = "install_sync",responses(- (status = 307, description = "Temporary redirect to the GitHub sync app installation page"),- (status = 401, description = "Authentication failed"),+ (status = 307, description = "Redirects to the github sync app installation page"),))]-#[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))+#[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)}/// Query params received from the GitHub App installation callback.-#[derive(Debug, Default, serde::Deserialize)]+#[derive(serde::Deserialize)]pub struct SyncRedirectParams {- /// 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>,+ /// 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,}-/// Completes a GitHub App installation callback and redirects back to Macro.+/// Callback after a user installs the GitHub App. Redirects to the main app.#[utoipa::path(get,path = "/github/sync-redirect",operation_id = "sync_redirect",params(- ("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"),+ ("code" = String, Query, description = "OAuth authorization code from GitHub"),+ ("installation_id" = String, Query, description = "GitHub App installation ID"),),responses(- (status = 307, description = "Temporary redirect to Macro; callback failures degrade to this redirect"),+ (status = 307, description = "Redirects to the main application"),))]#[tracing::instrument(skip_all)]-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 {+pub async fn sync_redirect_handler<T: GithubSyncService>(+ axum::extract::Query(_params): axum::extract::Query<SyncRedirectParams>,+) -> 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@@ -210,17 +112,15 @@ fn team_settings_redirect() -> Redirect {/// [`ValidatedGithubWebhookEvent`].pub struct GithubWebhookEventExtractor(pub ValidatedGithubWebhookEvent);-impl<T, Eas, Auth> FromRequest<GithubSyncRouterState<T, Eas, Auth>> for GithubWebhookEventExtractor+impl<T> FromRequest<GithubSyncRouterState<T>> for GithubWebhookEventExtractorwhereT: GithubSyncService,- Eas: EntityAccessService,- Auth: MacroAuthorizationService,{type Rejection = GithubError;async fn from_request(req: Request,- state: &GithubSyncRouterState<T, Eas, Auth>,+ state: &GithubSyncRouterState<T>,) -> Result<Self, Self::Rejection> {let (parts, body) = req.into_parts();@@ -252,13 +152,10 @@ where/// The main entrypoint for all github webhook events handling#[tracing::instrument(err, skip(ctx, event))]-pub async fn github_webhook_event_handler<T, Eas, Auth>(- State(ctx): State<GithubSyncRouterState<T, Eas, Auth>>,+pub async fn github_webhook_event_handler<T: GithubSyncService>(+ State(ctx): State<GithubSyncRouterState<T>>,GithubWebhookEventExtractor(event): GithubWebhookEventExtractor,-) -> Result<StatusCode, GithubError>-where- T: GithubSyncService,-{+) -> Result<StatusCode, GithubError> {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 6f1f42dae9..9683c6ba53 100644--- a/crates/github/src/inbound/github_sync_router/test.rs+++ b/crates/github/src/inbound/github_sync_router/test.rs@@ -1,205 +1,18 @@-use std::sync::{Arc, Mutex};+use std::sync::Arc;use axum::{Router, http::Request};-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 http_body_util::BodyExt;use tower::util::ServiceExt;-use uuid::Uuid;use crate::domain::{- models::{- GithubError, GithubInstallationAccessToken, InstallationState, ValidatedGithubWebhookEvent,- },+ models::{GithubError, GithubInstallationAccessToken, 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 {- 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()- }+ sync_app_url: String,}impl GithubSyncService for MockGithubSyncService {@@ -219,44 +32,8 @@ 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 {- "https://github.com/apps/my-sync-app/installations/new"+ &self.sync_app_url}async fn generate_installation_access_token(@@ -265,220 +42,65 @@ impl GithubSyncService for MockGithubSyncService {) -> Result<GithubInstallationAccessToken, GithubError> {unimplemented!()}-}--fn mock_router() -> (Router, Arc<MockGithubSyncService>) {- mock_router_with_team(None)-}--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)-}--fn request(uri: &str) -> Request<axum::body::Body> {- Request::builder()- .uri(uri)- .body(axum::body::Body::empty())- .unwrap()-}--fn authenticated_request(uri: &str) -> Request<axum::body::Body> {- Request::builder()- .uri(uri)- .header("authorization", "Bearer valid")- .body(axum::body::Body::empty())- .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")-}-fn app_url() -> String {- AppServiceUrl::unwrap_new().as_str().to_string()+ async fn associate_installations_for_github_user(+ &self,+ _github_user_id: &str,+ ) -> Result<(), GithubError> {+ unimplemented!()+ }}-#[tokio::test]-async fn install_sync_rejects_unauthenticated_requests() {- let (router, service) = mock_router();-- let response = router.oneshot(request("/install-sync")).await.unwrap();-- assert_eq!(response.status(), axum::http::StatusCode::UNAUTHORIZED);- assert!(service.begin_calls().is_empty());+fn mock_router(sync_app_url: &str) -> Router {+ github_sync_router(GithubSyncRouterState {+ service: Arc::new(MockGithubSyncService {+ sync_app_url: sync_app_url.to_string(),+ }),+ })}#[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));+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);- let personal_response = personal_router- .oneshot(authenticated_request("/install-sync"))- .await- .unwrap();- let team_response = team_router- .oneshot(authenticated_request("/install-sync"))- .await+ let request = Request::builder()+ .uri("/install-sync")+ .body(axum::body::Body::empty()).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),- }]- );-}--#[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();+ let res = router.oneshot(request).await.unwrap();- assert_eq!(- response.status(),- axum::http::StatusCode::TEMPORARY_REDIRECT- );- assert_eq!(service.begin_calls()[0].team_id, None);+ assert_eq!(res.status(), axum::http::StatusCode::TEMPORARY_REDIRECT);+ assert_eq!(res.headers().get("location").unwrap(), url);}#[tokio::test]-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()));+async fn install_sync_returns_empty_body() {+ let url = "https://github.com/apps/my-sync-app/installations/new";+ let router = mock_router(url);- 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+ let request = Request::builder()+ .uri("/install-sync")+ .body(axum::body::Body::empty()).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();+ let res = router.oneshot(request).await.unwrap();+ let bytes = res.into_body().collect().await.unwrap().to_bytes();- 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);+ assert!(bytes.is_empty());}#[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"),- ];+async fn install_sync_returns_not_found_for_wrong_path() {+ let router = mock_router("https://github.com/apps/my-sync-app");- 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 request = Request::builder()+ .uri("/wrong-path")+ .body(axum::body::Body::empty())+ .unwrap();- let response = router.oneshot(request("/wrong-path")).await.unwrap();+ let res = router.oneshot(request).await.unwrap();- assert_eq!(response.status(), axum::http::StatusCode::NOT_FOUND);+ assert_eq!(res.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 68fe05e6fd..515e87c4be 100644--- a/crates/github/src/outbound/github_sync_client.rs+++ b/crates/github/src/outbound/github_sync_client.rs@@ -1,7 +1,5 @@//! 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,};@@ -9,184 +7,19 @@ use super::pull_request_metadata::{use crate::domain::{models::{EnrichedGithubPullRequest, GithubError, GithubInstallationAccessToken,- GithubPullRequestDetails, GithubSetupAccessToken, GithubUserInstallation,- GithubUserInstallationsPage,+ GithubPullRequestDetails,},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)]+#[derive(Clone, Default)]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, 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.rsdeleted file mode 100644index 3cad9e5570..0000000000--- a/crates/github/src/outbound/github_sync_client/test.rs+++ /dev/null@@ -1,227 +0,0 @@-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 b370fe6932..cf57e36ee6 100644--- a/crates/github/src/outbound/pg_github_sync_repo.rs+++ b/crates/github/src/outbound/pg_github_sync_repo.rs@@ -367,6 +367,48 @@ impl GithubSyncRepo for PgGithubSyncRepo {Ok(())}+ #[tracing::instrument(skip(self), err)]+ async fn upsert_installation_installer(+ &self,+ installation_id: &str,+ github_user_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()+ "#,+ installation_id,+ github_user_id,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_installation_ids_by_installer(+ &self,+ github_user_id: &str,+ ) -> Result<Vec<String>, Self::Err> {+ let installation_ids = sqlx::query_scalar!(+ r#"+ SELECT installation_id+ FROM github_app_installation_installer+ WHERE github_user_id = $1+ ORDER BY installation_id+ "#,+ github_user_id,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(installation_ids)+ }+#[tracing::instrument(skip(self), err)]async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {sqlx::query!(@@ -381,4 +423,19 @@ impl GithubSyncRepo for PgGithubSyncRepo {Ok(())}++ #[tracing::instrument(skip(self), err)]+ async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ DELETE FROM github_app_installation_installer+ WHERE installation_id = $1+ "#,+ installation_id,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }}diff --git a/crates/github/src/outbound/pg_github_sync_repo/test.rs b/crates/github/src/outbound/pg_github_sync_repo/test.rsindex b2f58c2fc8..c2353a3323 100644--- a/crates/github/src/outbound/pg_github_sync_repo/test.rs+++ b/crates/github/src/outbound/pg_github_sync_repo/test.rs@@ -871,7 +871,67 @@ async fn test_upsert_installation_sources_idempotent_user_source(pool: Pool<Post}// ----------------------------------------------------------------------------// delete_installation_sources+// 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// ---------------------------------------------------------------------------#[sqlx::test(@@ -906,3 +966,32 @@ async fn test_delete_installation_sources_missing_installation_is_noop(pool: Poorepo.delete_installation_sources("missing").await.unwrap();repo.delete_installation_sources("missing").await.unwrap();}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_delete_installation_installer_removes_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();++ repo.delete_installation_installer("11111").await.unwrap();++ assert_eq!(+ repo.get_installation_ids_by_installer("12345")+ .await+ .unwrap(),+ vec!["22222"]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_delete_installation_installer_missing_installation_is_noop(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ repo.delete_installation_installer("missing").await.unwrap();+ repo.delete_installation_installer("missing").await.unwrap();+}diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 2038366a8e..97980716b0 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, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, 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, 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, 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, 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, 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, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, 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, 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, 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, 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, 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 70e58a8b0d..69f51b92b8 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, 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, 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, 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, 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> & {/**@@ -1314,10 +1314,10 @@ export class Sdk extends HeyApiClient {}/**- * Redirects an authenticated user to the github sync app installation page.+ * Redirects the user to the github sync app installation page.*/- 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 });+ 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 });}/**diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 5b4a78c922..005cf9663b 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -10465,13 +10465,6 @@ 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 b79b854498..5858e9f80f 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -7802,14 +7802,11 @@"/github/install-sync": {"get": {"tags": ["github::inbound::github_sync_router"],- "summary": "Redirects an authenticated user to the github sync app installation page.",+ "summary": "Redirects the user to the github sync app installation page.","operationId": "install_sync","responses": {"307": {- "description": "Temporary redirect to the GitHub sync app installation page"- },- "401": {- "description": "Authentication failed"+ "description": "Redirects to the github sync app installation page"}}}diff --git a/services/authentication_service/src/api/oauth2/github.rs b/services/authentication_service/src/api/oauth2/github.rsindex c3f4afadc6..6c906d1e0d 100644--- a/services/authentication_service/src/api/oauth2/github.rs+++ b/services/authentication_service/src/api/oauth2/github.rs@@ -101,7 +101,8 @@ async fn link_user(.map(|id| id.into_owned().lowercase()).context("valid macro user id")?;- ctx.github_link_service+ let link = ctx+ .github_link_service.link_user(¯o_user_id,&fusionauth_user_id,@@ -111,6 +112,20 @@ 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.rsnew file mode 100644index 0000000000..a3cc048110--- /dev/null+++ b/services/document_storage_service/src/api/internal/associate_github_installations.rs@@ -0,0 +1,48 @@+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 29b7cadbf1..f1d3bd8ba6 100644--- a/services/document_storage_service/src/api/internal/mod.rs+++ b/services/document_storage_service/src/api/internal/mod.rs@@ -28,6 +28,8 @@ 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> {@@ -194,6 +196,11 @@ 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 4de96268ee..959cfe6887 100644--- a/services/document_storage_service/src/api/mod.rs+++ b/services/document_storage_service/src/api/mod.rs@@ -88,8 +88,6 @@ 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 e6ceaded5e..f3e6e16dfe 100644--- a/services/document_storage_service/src/config.rs+++ b/services/document_storage_service/src/config.rs@@ -25,8 +25,6 @@ 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;@@ -100,8 +98,6 @@ 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 69bc07d143..ec849b1883 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -500,8 +500,6 @@ 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(),