Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(github): allow github app installation before github account link (#4612)

Will Hutchinson7538515d6a7c
diff --git a/rust/cloud-storage/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json b/rust/cloud-storage/.sqlx/query-3e0f4214fbae78a344d4586f760c460aabf24e4707e9aa8e7259516f6cecf214.json
new file mode 100644
index 0000000000..f4dbba6dd1
--- /dev/null
+++ b/rust/cloud-storage/.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/rust/cloud-storage/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json b/rust/cloud-storage/.sqlx/query-cacd042c1649e843312bfeb40093ebc2ae8fb2a14a0bc5841be3d09c1cb8b1a7.json
new file mode 100644
index 0000000000..c02348956b
--- /dev/null
+++ b/rust/cloud-storage/.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/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs
index c3f4afadc6..6c906d1e0d 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs
+++ b/rust/cloud-storage/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(
&macro_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/rust/cloud-storage/document_storage_service/src/api/internal/associate_github_installations.rs b/rust/cloud-storage/document_storage_service/src/api/internal/associate_github_installations.rs
new file mode 100644
index 0000000000..3fa1bc9018
--- /dev/null
+++ b/rust/cloud-storage/document_storage_service/src/api/internal/associate_github_installations.rs
@@ -0,0 +1,46 @@
+use crate::api::context::ApiContext;
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use github::domain::ports::GithubSyncService;
+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), err(Debug))]
+pub async fn associate_github_installations_handler(
+ State(ctx): State<ApiContext>,
+ 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/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
index 35d3fc7115..3e2b145f00 100644
--- a/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/internal/mod.rs
@@ -27,6 +27,8 @@ use macro_middleware::{
cloud_storage::{document::ensure_document_exists, thread::ensure_thread_exists},
};
+mod associate_github_installations;
+
/// Internal routes. All routes are authenticated via the internal_access middleware
/// These routes are not part of the public Swagger documentation and should never be
pub fn router(state: ApiContext) -> Router<ApiContext> {
@@ -178,5 +180,10 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/validate_item_ids",
post(validate_item_ids::handler).layer(ensure_user_exists_middleware),
)
+ // Github routes
+ .route(
+ "/github/installations/{github_user_id}/associate",
+ post(associate_github_installations::associate_github_installations_handler),
+ )
.route("/health", get(async move || "healthy"))
}
diff --git a/rust/cloud-storage/document_storage_service_client/src/github.rs b/rust/cloud-storage/document_storage_service_client/src/github.rs
new file mode 100644
index 0000000000..da61504254
--- /dev/null
+++ b/rust/cloud-storage/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/rust/cloud-storage/document_storage_service_client/src/lib.rs b/rust/cloud-storage/document_storage_service_client/src/lib.rs
index 781ec71415..a3bc80c904 100644
--- a/rust/cloud-storage/document_storage_service_client/src/lib.rs
+++ b/rust/cloud-storage/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/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rs
index b9d31792bf..dc35781b17 100644
--- a/rust/cloud-storage/github/src/domain/ports/sync.rs
+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs
@@ -96,6 +96,20 @@ pub trait GithubSyncRepo: Send + Sync + 'static {
installation_id: &str,
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;
}
/// Client interface for making GitHub sync API calls.
@@ -157,6 +171,18 @@ pub trait GithubSyncService: Send + Sync + 'static {
/// Returns the github sync app installation url
fn get_github_sync_app_url(&self) -> &str;
+ /// Associates any GitHub App installations installed by the given GitHub
+ /// user with that user's Macro sources (teams or user), then backfills
+ /// open pull requests for newly associated installations.
+ ///
+ /// 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 app
fn generate_installation_access_token(
&self,
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
index 5a632ae01d..dda4217d3e 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
@@ -29,7 +29,6 @@ impl<
let installation_id = event
.installation_id()
.ok_or_else(|| GithubError::Internal(anyhow::anyhow!("missing installation.id")))?;
- let installation_id_str = installation_id.to_string();
let sender_github_user_id = event.sender_github_user_id().ok_or_else(|| {
GithubError::Internal(anyhow::anyhow!("missing sender.id in installation event"))
@@ -37,17 +36,15 @@ impl<
tracing::info!(installation_id, "processing installation created event");
- let links = self
- .repo
- .get_macro_ids_by_github_user_ids(std::slice::from_ref(&sender_github_user_id))
+ // 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 macro_ids = links
- .get(&sender_github_user_id)
- .cloned()
- .unwrap_or_default();
- if macro_ids.is_empty() {
+ 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"
@@ -55,8 +52,26 @@ impl<
return Ok(());
}
- // A GitHub account may be linked to several Macro users; associate the
- // installation with the team/user source of every linked user.
+ self.associate_installation_with_sources(installation_id, &sources)
+ .await
+ }
+
+ /// 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 {
@@ -68,8 +83,8 @@ impl<
if team_ids.is_empty() {
tracing::info!(
- installation_id,
- "user has no teams, associating installation with user source"
+ github_user_id,
+ "user has no teams, using user source for installation association"
);
let source = GithubAppInstallationSource::User(macro_id);
if seen.insert(source.clone()) {
@@ -77,9 +92,9 @@ impl<
}
} else {
tracing::info!(
- installation_id,
+ github_user_id,
team_count = team_ids.len(),
- "associating installation with user teams"
+ "using team sources for installation association"
);
for team_id in team_ids {
let source = GithubAppInstallationSource::Team(team_id);
@@ -90,12 +105,22 @@ impl<
}
}
+ 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(
+ &self,
+ installation_id: u64,
+ sources: &[GithubAppInstallationSource],
+ ) -> Result<(), GithubError> {
self.repo
- .upsert_installation_sources(&installation_id_str, &sources)
+ .upsert_installation_sources(&installation_id.to_string(), sources)
.await
.map_err(|e| GithubError::Internal(e.into()))?;
- self.backfill_open_pull_request_foreign_entities(installation_id, &sources)
+ self.backfill_open_pull_request_foreign_entities(installation_id, sources)
.await?;
Ok(())
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index b158d3881e..202083dc22 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -957,6 +957,61 @@ impl<
&self.config.github_sync_app_url
}
+ #[tracing::instrument(skip(self), err)]
+ async fn associate_installations_for_github_user(
+ &self,
+ github_user_id: &str,
+ ) -> Result<(), GithubError> {
+ 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 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(());
+ }
+
+ 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;
+ }
+ };
+
+ // 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)]
async fn generate_installation_access_token(
&self,
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index bcef550f19..d77bcdd4ab 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -302,6 +302,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 {
@@ -315,6 +317,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()),
}
}
@@ -392,6 +395,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 {
@@ -549,6 +564,34 @@ impl GithubSyncRepo for StubSyncRepo {
.push((installation_id.to_string(), sources.to_vec()));
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)
+ }
}
#[tokio::test]
@@ -3821,9 +3864,128 @@ 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 anything
+ // No github link for sender — should succeed without inserting any sources
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert!(service.repo.installation_sources().is_empty());
+ assert!(service.client.list_open_pull_requests_calls().is_empty());
+
+ // The installer is still recorded so a later link can associate the
+ // installation retroactively.
+ assert_eq!(
+ service.repo.installation_installers(),
+ HashMap::from([("11111".to_string(), "99999".to_string())])
+ );
+}
+
+#[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())])
+ );
+}
+
+#[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());
}
diff --git a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
index 2f351a89d2..9683c6ba53 100644
--- a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
+++ b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
@@ -42,6 +42,13 @@ impl GithubSyncService for MockGithubSyncService {
) -> Result<GithubInstallationAccessToken, GithubError> {
unimplemented!()
}
+
+ async fn associate_installations_for_github_user(
+ &self,
+ _github_user_id: &str,
+ ) -> Result<(), GithubError> {
+ unimplemented!()
+ }
}
fn mock_router(sync_app_url: &str) -> Router {
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
index 20ab42b56c..5ccda32310 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs
@@ -344,4 +344,46 @@ 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)
+ }
}
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
index 6c0f9a13ac..188648515e 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
@@ -721,3 +721,63 @@ async fn test_upsert_installation_sources_idempotent_user_source(pool: Pool<Post
)]
);
}
+
+// ---------------------------------------------------------------------------
+// installation installer
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_upsert_installation_installer_records_installer(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ repo.upsert_installation_installer("11111", "12345")
+ .await
+ .unwrap();
+ repo.upsert_installation_installer("22222", "12345")
+ .await
+ .unwrap();
+
+ let installation_ids = repo
+ .get_installation_ids_by_installer("12345")
+ .await
+ .unwrap();
+
+ assert_eq!(installation_ids, vec!["11111", "22222"]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_upsert_installation_installer_replaces_installer(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ repo.upsert_installation_installer("11111", "12345")
+ .await
+ .unwrap();
+ repo.upsert_installation_installer("11111", "67890")
+ .await
+ .unwrap();
+
+ assert!(
+ repo.get_installation_ids_by_installer("12345")
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ repo.get_installation_ids_by_installer("67890")
+ .await
+ .unwrap(),
+ vec!["11111"]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_installation_ids_by_installer_empty(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ let installation_ids = repo
+ .get_installation_ids_by_installer("missing")
+ .await
+ .unwrap();
+
+ assert!(installation_ids.is_empty());
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260708172449_github_app_installation_installer.sql b/rust/cloud-storage/macro_db_client/migrations/20260708172449_github_app_installation_installer.sql
new file mode 100644
index 0000000000..853161bc17
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260708172449_github_app_installation_installer.sql
@@ -0,0 +1,27 @@
+-- Records which GitHub user installed each GitHub App installation, so an
+-- installation can be associated with Macro sources when the installer links
+-- their GitHub account after installing the app.
+CREATE TABLE github_app_installation_installer
+(
+ installation_id TEXT PRIMARY KEY, -- The github installation id converted to a string
+ github_user_id TEXT NOT NULL, -- The stable numeric github user id of the installer
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX "github_app_installation_installer_github_user_id_idx"
+ ON github_app_installation_installer (github_user_id);
+
+-- Backfill installers for existing user-sourced installations. A user source's
+-- source_id is a macro user id that was linked to the installer's github
+-- account at install time, so reversing through github_links recovers the
+-- installer's github user id. Installations whose user sources resolve to more
+-- than one github account are skipped rather than guessed at, as are
+-- team-sourced installations (the installing team member is not recoverable).
+INSERT INTO github_app_installation_installer (installation_id, github_user_id)
+SELECT gai.id, MIN(gl.github_user_id)
+FROM github_app_installation gai
+ JOIN github_links gl ON gl.macro_id = gai.source_id
+WHERE gai.source_type = 'user'::github_app_installation_source_type
+GROUP BY gai.id
+HAVING COUNT(DISTINCT gl.github_user_id) = 1;