Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): support GitHub linked to multiple accounts (#4502)
Will Hutchinsone0a1d7143296
diff --git a/plan.md b/plan.mddeleted file mode 100644index e40347f307..0000000000--- a/plan.md+++ /dev/null@@ -1,260 +0,0 @@-# Plan: Move GraphQL Soup document properties to a DataLoader edge--## Context--The `graphql_soup` crate currently exposes typed GraphQL Soup entities. `GraphqlSoupDocument` exposes `subType` and `properties` directly from the inline `models_soup::document::SoupDocument` payload.--We want `properties` to become a GraphQL edge resolved via DataLoader instead of reading the inline Soup payload. This decouples GraphQL property hydration from Soup item hydration and prepares the schema for reusable entity property edges.--Keep `subType` inline for now. It is intrinsic document metadata and does not need a DataLoader edge.--## Target GraphQL behavior--Frontend query should continue to look like:--```graphql-... on GraphqlSoupDocument {- id- name- subType {- kind- isCompleted- }- properties {- id- displayName- dataType- value {- kind- stringValue- selectOptionIds- }- }-}-```--But implementation should resolve `properties` through a DataLoader, not `SoupDocument.properties`.--## Design--### 1. Add reusable property edge key in `graphql_soup`--Use an entity-key shape, not document-only, so this can later support project/chat/email properties.--```rust-#[derive(Debug, Clone, Hash, PartialEq, Eq)]-pub struct EntityPropertiesKey {- pub entity_type: String,- pub entity_id: String,-}-```--For documents, build this from:--```rust-EntityPropertiesKey {- entity_id: self.0.id.to_string(),- entity_type: self.0.entity_type().to_string(),-}-```--Important: `SoupDocument::entity_type()` returns `Task` for task documents and `Document` otherwise, so this correctly supports task properties.--### 2. Add object-safe property reader trait in `graphql_soup`--Use `async_trait` to avoid pushing generics through every GraphQL type.--```rust-#[async_trait::async_trait]-pub trait SoupPropertyEdgeReader: Send + Sync + 'static {- async fn get_properties(- &self,- keys: Vec<EntityPropertiesKey>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report>;-}-```--Add dependencies if needed:--```toml-async-trait = { workspace = true }-rootcause = { workspace = true }-```--### 3. Add DataLoader in `graphql_soup`--Enable async-graphql dataloader feature if needed. Current crate uses `async-graphql = "7.2.1"`; change to include dataloader support if required by this version.--Example shape:--```rust-use async_graphql::dataloader::{DataLoader, Loader};--pub struct EntityPropertiesLoader {- reader: Arc<dyn SoupPropertyEdgeReader>,-}--impl EntityPropertiesLoader {- pub fn new(reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {- Self { reader }- }-}--#[async_trait::async_trait]-impl Loader<EntityPropertiesKey> for EntityPropertiesLoader {- type Value = Vec<SoupProperty>;- type Error = Arc<rootcause::Report>;-- async fn load(- &self,- keys: &[EntityPropertiesKey],- ) -> Result<HashMap<EntityPropertiesKey, Self::Value>, Self::Error> {- self.reader- .get_properties(keys.to_vec())- .await- .map_err(Arc::new)- }-}-```--Add a helper:--```rust-pub fn entity_properties_loader(- reader: Arc<dyn SoupPropertyEdgeReader>,-) -> DataLoader<EntityPropertiesLoader> {- DataLoader::new(EntityPropertiesLoader::new(reader), tokio::spawn)-}-```--This may require `tokio` as a dependency in `graphql_soup`.--### 4. Change `GraphqlSoupDocument.properties` resolver--Current resolver reads inline properties:--```rust-async fn properties(&self) -> Vec<GraphqlSoupProperty> {- self.0.properties.iter().cloned().map(GraphqlSoupProperty).collect()-}-```--Change to use DataLoader:--```rust-async fn properties(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlSoupProperty>> {- let loader = ctx.data::<DataLoader<EntityPropertiesLoader>>()?;- let key = EntityPropertiesKey {- entity_id: self.0.id.to_string(),- entity_type: self.0.entity_type().to_string(),- };-- let properties = loader.load_one(key).await?.unwrap_or_default();- Ok(properties.into_iter().map(GraphqlSoupProperty).collect())-}-```--Transition option: If wiring is incomplete, temporarily fall back to inline properties when loader is absent. Preferred final state is strict loader requirement.--### 5. Implement reader in `document_storage_service`--Implement `SoupPropertyEdgeReader` behind the existing `graphql` feature. The implementation should live in DSS or a DSS GraphQL module, not in `soup`.--Possible shape:--```rust-#[cfg(feature = "graphql")]-pub struct DssSoupPropertyEdgeReader {- // Prefer existing properties service/repo if it has batch APIs.- // Otherwise use PgPool/read-only pool and add/query a repository method.-}-```--Implementation target:--```rust-#[async_trait::async_trait]-impl graphql_soup::SoupPropertyEdgeReader for DssSoupPropertyEdgeReader {- async fn get_properties(- &self,- keys: Vec<EntityPropertiesKey>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report> {- // Batch fetch properties by entity_type/entity_id.- // Return empty Vec for keys with no properties.- }-}-```--Need to inspect existing `properties`, `properties_db_client`, or `system_properties` APIs for an appropriate batch lookup. If none exists, add a batch repo function to the appropriate properties crate.--### 6. Wire loader into DSS GraphQL request handler--Current GraphQL handler is in:--```text-rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs-```--It currently injects:--```rust-request.data(GraphqlSoupRequestContext { ... })-```--Add:--```rust-.data(graphql_soup::entity_properties_loader(- state.graphql_soup_property_reader.clone(),-))-```--This requires adding a property reader field to `ApiContext` under `#[cfg(feature = "graphql")]`, or including it in a small GraphQL state struct.--Example:--```rust-#[cfg(feature = "graphql")]-pub graphql_soup_property_reader: Arc<dyn graphql_soup::SoupPropertyEdgeReader>,-```--Construct it in `main.rs` when building `ApiContext`.--### 7. Keep crate boundaries clean--Dependency direction should remain:--```text-document_storage_service -> graphql_soup-document_storage_service -> properties/properties_db_client-graphql_soup -> models_soup/models_properties-soup -X-> graphql_soup-soup -X-> properties edge implementation-```--Do not make `soup` aware of GraphQL or the properties edge.--### 8. Validation--Run:--```bash-cd rust/cloud-storage-SQLX_OFFLINE=true cargo check -p graphql_soup-SQLX_OFFLINE=true cargo check -p document_storage_service --features graphql-SQLX_OFFLINE=true just check-SQLX_OFFLINE=true just clippy-just format-```--Note: `just clippy` has recently failed in this environment with an unrelated `sqlx_macros` / `aws_lc` undefined symbol. If it still fails, report that clearly and include successful checks.--## Acceptance criteria--- `GraphqlSoupDocument.properties` resolves via DataLoader.-- DataLoader batches property requests by `(entity_type, entity_id)`.-- Task documents use `entity_type = task`, normal documents use `entity_type = document`.-- Frontend GraphQL field shape remains `properties { ... }`.-- `SoupDocument.properties` is no longer read by the GraphQL resolver.-- Existing REST Soup API remains unchanged.-- GraphQL remains behind `document_storage_service` feature `graphql`, default off.diff --git a/rust/cloud-storage/.sqlx/query-086b8b198aff7df79c9b4a15829542effa0b1675e87a78ae2063e55850ac50f4.json b/rust/cloud-storage/.sqlx/query-086b8b198aff7df79c9b4a15829542effa0b1675e87a78ae2063e55850ac50f4.jsonnew file mode 100644index 0000000000..ef89899afc--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-086b8b198aff7df79c9b4a15829542effa0b1675e87a78ae2063e55850ac50f4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT github_user_id, macro_id\n FROM github_links\n WHERE github_user_id = ANY($1::text[])\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "github_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "macro_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "086b8b198aff7df79c9b4a15829542effa0b1675e87a78ae2063e55850ac50f4"+}diff --git a/rust/cloud-storage/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.json b/rust/cloud-storage/.sqlx/query-1757adf4eb7840d4177782445045960361098f82ee97ef628eb3fcd1c1e9db99.jsonsimilarity index 87%rename from rust/cloud-storage/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.jsonrename to rust/cloud-storage/.sqlx/query-1757adf4eb7840d4177782445045960361098f82ee97ef628eb3fcd1c1e9db99.jsonindex c06c14d875..df43ec4192 100644--- a/rust/cloud-storage/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.json+++ b/rust/cloud-storage/.sqlx/query-1757adf4eb7840d4177782445045960361098f82ee97ef628eb3fcd1c1e9db99.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, macro_id, fusionauth_user_id as \"fusionauth_user_id: Uuid\", github_username, github_user_id, created_at, updated_at\n FROM github_links\n WHERE github_user_id = $1\n ",+ "query": "\n SELECT id, macro_id, fusionauth_user_id as \"fusionauth_user_id: Uuid\", github_username, github_user_id, created_at, updated_at\n FROM github_links\n WHERE github_user_id = $1\n ORDER BY created_at ASC\n LIMIT 1\n ","describe": {"columns": [{@@ -54,5 +54,5 @@false]},- "hash": "594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4"+ "hash": "1757adf4eb7840d4177782445045960361098f82ee97ef628eb3fcd1c1e9db99"}diff --git a/rust/cloud-storage/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.json b/rust/cloud-storage/.sqlx/query-429c4e24508d25a6cf9b67d65ee20e83d59d08e95352fb498b652a697a016aa1.jsonsimilarity index 56%rename from rust/cloud-storage/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.jsonrename to rust/cloud-storage/.sqlx/query-429c4e24508d25a6cf9b67d65ee20e83d59d08e95352fb498b652a697a016aa1.jsonindex 104b3123e1..d35f174944 100644--- a/rust/cloud-storage/.sqlx/query-ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12.json+++ b/rust/cloud-storage/.sqlx/query-429c4e24508d25a6cf9b67d65ee20e83d59d08e95352fb498b652a697a016aa1.json@@ -1,12 +1,12 @@{"db_name": "PostgreSQL",- "query": "\n SELECT macro_id\n FROM github_links\n WHERE github_user_id = $1\n ",+ "query": "\n SELECT COUNT(*)\n FROM github_links\n WHERE github_user_id = $1\n ","describe": {"columns": [{"ordinal": 0,- "name": "macro_id",- "type_info": "Text"+ "name": "count",+ "type_info": "Int8"}],"parameters": {@@ -15,8 +15,8 @@]},"nullable": [- false+ null]},- "hash": "ed43958d3b45528df34f3216299e47e00e2aa671b9d235abffa4ad8bfe126c12"+ "hash": "429c4e24508d25a6cf9b67d65ee20e83d59d08e95352fb498b652a697a016aa1"}diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rsindex f45931d3c6..c3f4afadc6 100644--- a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs@@ -32,10 +32,6 @@ pub enum GithubLinkError {impl IntoResponse for GithubLinkError {fn into_response(self) -> Response {let (status_code, message): (StatusCode, &str) = match &self {- GithubLinkError::GithubServiceError(GithubError::AccountAlreadyLinked) => (- StatusCode::CONFLICT,- "github account is already linked with another Macro account",- ),GithubLinkError::GithubServiceError(GithubError::NoLinkFound) => {(StatusCode::NOT_FOUND, "no github link found")}diff --git a/rust/cloud-storage/github/fixtures/github_test_data.sql b/rust/cloud-storage/github/fixtures/github_test_data.sqlindex a282d2bfa8..077e3ee6c1 100644--- a/rust/cloud-storage/github/fixtures/github_test_data.sql+++ b/rust/cloud-storage/github/fixtures/github_test_data.sql@@ -8,6 +8,16 @@ INSERT INTOVALUES('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid);+INSERT INTO+ public.macro_user (id, username, email, stripe_customer_id)+VALUES+ ('99999999-9999-9999-9999-999999999999'::uuid, 'sharer', '[email protected]', 'cus_sharer');++INSERT INTO+ public."User" (id, email, macro_user_id)+VALUES+ ('macro|[email protected]', '[email protected]', '99999999-9999-9999-9999-999999999999'::uuid);+INSERT INTOpublic.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id) (SELECTdiff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rsindex 45c9d23d96..2cb416bd7a 100644--- a/rust/cloud-storage/github/src/domain/models/mod.rs+++ b/rust/cloud-storage/github/src/domain/models/mod.rs@@ -30,9 +30,6 @@ pub enum GithubError {/// The Github link token has expired and the user must reauthenticate.#[error("reauthentication required")]ReauthenticationRequired,- /// Github account is already linked- #[error("github account is already linked with another")]- AccountAlreadyLinked,/// No refresh token was provided in the token exchange#[error("no refresh token provided in token exchange")]NoRefreshTokenProvided,diff --git a/rust/cloud-storage/github/src/domain/ports/link.rs b/rust/cloud-storage/github/src/domain/ports/link.rsindex e16c2c26fa..56538fe1cd 100644--- a/rust/cloud-storage/github/src/domain/ports/link.rs+++ b/rust/cloud-storage/github/src/domain/ports/link.rs@@ -29,6 +29,12 @@ pub trait GithubRepo: Send + Sync + 'static {github_user_id: &str,) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;+ /// Counts the number of github links for the given github user id+ fn count_github_links_by_github_user_id(+ &self,+ github_user_id: &str,+ ) -> impl Future<Output = Result<i64, Self::Err>> + Send;+/// Gets the github link by idfn get_github_link_by_id(&self,diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rsindex 6defb0770b..b9d31792bf 100644--- a/rust/cloud-storage/github/src/domain/ports/sync.rs+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs@@ -51,12 +51,15 @@ pub trait GithubSyncRepo: Send + Sync + 'static {references: &[TeamTaskReference],) -> impl Future<Output = Result<Vec<MacroTaskId>, Self::Err>> + Send;- /// Looks up the macro user ID associated with a GitHub user ID via the `github_links` table.- /// Returns `None` if no link exists.- fn get_macro_id_by_github_user_id(+ /// Maps GitHub user IDs to the Macro user IDs linked to them via the `github_links` table.+ ///+ /// A GitHub user ID absent from the result has no link; a GitHub user ID may map to+ /// multiple Macro users because `github_links.github_user_id` is not unique (many Macro+ /// users may share one GitHub account).+ fn get_macro_ids_by_github_user_ids(&self,- github_user_id: &str,- ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+ github_user_ids: &[String],+ ) -> impl Future<Output = Result<std::collections::HashMap<String, Vec<String>>, Self::Err>> + Send;/// Maps GitHub logins to the Macro user IDs linked to them via the `github_links` table.///diff --git a/rust/cloud-storage/github/src/domain/service/link.rs b/rust/cloud-storage/github/src/domain/service/link.rsindex f73b3ece73..29c24d3498 100644--- a/rust/cloud-storage/github/src/domain/service/link.rs+++ b/rust/cloud-storage/github/src/domain/service/link.rs@@ -263,12 +263,33 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: ForeignEntityService> GithubLink}};- // Delete link from Auth- self.auth- .delete_user_link(&link, &self.config.idp_id)+ // Count how many Macro users share this GitHub account. The FusionAuth+ // IdP link + token live on the owner's row and are reused by every+ // sharer, so we must only tear the grant down when this is the last row.+ let link_count = self+ .repo+ .count_github_links_by_github_user_id(&link.github_user_id).await.map_err(|e| GithubError::Internal(e.into()))?;+ if link_count > 1 {+ // Other Macro users still share this GitHub account: leave the+ // FusionAuth grant in place so the remaining sharers keep working.+ //+ // Note: if the row being deleted is the OWNER's, the FusionAuth link+ // becomes orphaned (no row carries the IdP link anymore), but this is+ // benign — sharers still resolve the grant via the owner's+ // `fusionauth_user_id` stored on their own rows, and the final row+ // deletion below (when the last sharer leaves) cleans it up.+ } else {+ // This is the last/only row for this GitHub account: unlink+ // FusionAuth (and clear the Redis cache) before removing the row.+ self.auth+ .delete_user_link(&link, &self.config.idp_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;+ }+// Delete from repoself.repo.delete_github_link(&link.id)@@ -306,47 +327,87 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: ForeignEntityService> GithubLinktracing::trace!(user_info=?user_info, "got user info");- // Check if Github account is already linked to a different user- match self- .repo- .get_github_link_by_github_user_id(&user_info.id.to_string())- .await- {- Ok(link) => {- if !link.macro_id.0.eq(user_id) {- return Err(GithubError::AccountAlreadyLinked);- }- }+ let gh_id = user_info.id.to_string();++ // 1. Does THIS user already have a link, and to which account?+ let this_user_link = match self.repo.get_github_link_by_user_id(user_id).await {+ Ok(l) => Some(l),Err(e) => {- let err: anyhow::Error = e.into();- // We should only error if the error is something other- // than the link not existing- if !err.to_string().contains("no rows returned") {- return Err(GithubError::Internal(err));+ let e: anyhow::Error = e.into();+ if e.to_string().contains("no rows returned") {+ None+ } else {+ return Err(GithubError::Internal(e));}}+ };++ if let Some(existing) = &this_user_link+ && existing.github_user_id == gh_id+ {+ // Idempotent re-link of the SAME account by the SAME user: skip auth + skip+ // insert (avoids violating the new (macro_id, github_user_id) unique). Still+ // clean up the in-progress link, then return the existing link.+ let _ = self+ .repo+ .delete_in_progress_user_link(in_progess_link_id)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to delete in progress link id"));+ return Ok(existing.clone());}+ // else: user previously linked a DIFFERENT github account; fall through and link+ // the new one (frontend is single-valued; not enforced here — matches prior+ // behavior).- self.auth- .link_user(- fusionauth_user_id,- &self.config.idp_id,- &user_info.id.to_string(),- &user_info.login,- &tokens.access_token,- )- .await- .map_err(|e| GithubError::Internal(e.into()))?;+ // 2. Does anyone already OWN this github account? (owner row = earliest row)+ let account_owner = match self.repo.get_github_link_by_github_user_id(&gh_id).await {+ Ok(l) => Some(l),+ Err(e) => {+ let e: anyhow::Error = e.into();+ if e.to_string().contains("no rows returned") {+ None+ } else {+ return Err(GithubError::Internal(e));+ }+ }+ };- tracing::trace!("linked auth user");+ let row_fusionauth_user_id = match &account_owner {+ Some(owner) => {+ // SHARER: reuse the owner's shared FusionAuth grant. Do NOT call auth.link_user.+ tracing::debug!(+ owner_fa_id=%owner.fusionauth_user_id,+ github_user_id=%gh_id,+ "linking additional macro user as github account sharer"+ );+ owner.fusionauth_user_id+ }+ None => {+ // OWNER (first linker): create the FusionAuth IdP link/token as before.+ self.auth+ .link_user(+ fusionauth_user_id,+ &self.config.idp_id,+ &gh_id,+ &user_info.login,+ &tokens.access_token,+ )+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ tracing::trace!("linked auth user");++ *fusionauth_user_id+ }+ };// create github linklet link = GithubLink {id: macro_uuid::generate_uuid_v7(),macro_id: MacroUserIdStr(user_id.clone()),- fusionauth_user_id: *fusionauth_user_id,+ fusionauth_user_id: row_fusionauth_user_id,github_username: user_info.login.clone(),- github_user_id: user_info.id.to_string(),+ github_user_id: gh_id,created_at: Utc::now(),updated_at: Utc::now(),};diff --git a/rust/cloud-storage/github/src/domain/service/link_test.rs b/rust/cloud-storage/github/src/domain/service/link_test.rsindex 844072cf95..61af15bef0 100644--- a/rust/cloud-storage/github/src/domain/service/link_test.rs+++ b/rust/cloud-storage/github/src/domain/service/link_test.rs@@ -26,16 +26,77 @@ use super::{GithubLinkConfig, GithubLinkServiceImpl};#[derive(Clone)]struct StubGithubRepo {- link: Option<GithubLink>,+ state: Arc<Mutex<StubGithubRepoState>>,+}++struct StubGithubRepoState {+ /// Link returned by `get_github_link_by_user_id` (None → "no rows returned").+ link_by_user_id: Option<GithubLink>,+ /// Link returned by `get_github_link_by_github_user_id` (None → "no rows returned").+ link_by_github_user_id: Option<GithubLink>,+ /// Value returned by `count_github_links_by_github_user_id`.+ link_count: i64,+ inserted_links: Vec<GithubLink>,+ delete_github_link_calls: u32,+ delete_in_progress_user_link_calls: u32,+}++impl Default for StubGithubRepoState {+ fn default() -> Self {+ Self {+ link_by_user_id: None,+ link_by_github_user_id: None,+ link_count: 1,+ inserted_links: Vec::new(),+ delete_github_link_calls: 0,+ delete_in_progress_user_link_calls: 0,+ }+ }}impl StubGithubRepo {+ fn new(state: StubGithubRepoState) -> Self {+ Self {+ state: Arc::new(Mutex::new(state)),+ }+ }+fn linked(link: GithubLink) -> Self {- Self { link: Some(link) }+ Self::new(StubGithubRepoState {+ link_by_user_id: Some(link),+ ..StubGithubRepoState::default()+ })}fn unlinked() -> Self {- Self { link: None }+ Self::new(StubGithubRepoState::default())+ }++ /// Sets the link returned by `get_github_link_by_github_user_id`.+ fn with_account_owner(self, owner: GithubLink) -> Self {+ self.state.lock().unwrap().link_by_github_user_id = Some(owner);+ self+ }++ /// Sets the value returned by `count_github_links_by_github_user_id`.+ fn with_link_count(self, link_count: i64) -> Self {+ self.state.lock().unwrap().link_count = link_count;+ self+ }++ fn inserted_links(&self) -> Vec<GithubLink> {+ self.state.lock().unwrap().inserted_links.clone()+ }++ fn delete_github_link_calls(&self) -> u32 {+ self.state.lock().unwrap().delete_github_link_calls+ }++ fn delete_in_progress_user_link_calls(&self) -> u32 {+ self.state+ .lock()+ .unwrap()+ .delete_in_progress_user_link_calls}}@@ -46,7 +107,10 @@ impl GithubRepo for StubGithubRepo {&self,_macro_user_id: &MacroUserId<Lowercase<'a>>,) -> Result<GithubLink, Self::Err> {- self.link+ self.state+ .lock()+ .unwrap()+ .link_by_user_id.clone().ok_or_else(|| anyhow::anyhow!("no rows returned"))}@@ -55,14 +119,27 @@ impl GithubRepo for StubGithubRepo {&self,_github_user_id: &str,) -> Result<GithubLink, Self::Err> {- Err(anyhow::anyhow!("not implemented"))+ self.state+ .lock()+ .unwrap()+ .link_by_github_user_id+ .clone()+ .ok_or_else(|| anyhow::anyhow!("no rows returned"))+ }++ async fn count_github_links_by_github_user_id(+ &self,+ _github_user_id: &str,+ ) -> Result<i64, Self::Err> {+ Ok(self.state.lock().unwrap().link_count)}async fn get_github_link_by_id(&self, _id: &uuid::Uuid) -> Result<GithubLink, Self::Err> {Err(anyhow::anyhow!("not implemented"))}- async fn insert_github_link(&self, _link: &GithubLink) -> Result<(), Self::Err> {+ async fn insert_github_link(&self, link: &GithubLink) -> Result<(), Self::Err> {+ self.state.lock().unwrap().inserted_links.push(link.clone());Ok(())}@@ -70,10 +147,15 @@ impl GithubRepo for StubGithubRepo {&self,_in_progress_link_id: &uuid::Uuid,) -> Result<(), Self::Err> {+ self.state+ .lock()+ .unwrap()+ .delete_in_progress_user_link_calls += 1;Ok(())}async fn delete_github_link(&self, _link_id: &uuid::Uuid) -> Result<(), Self::Err> {+ self.state.lock().unwrap().delete_github_link_calls += 1;Ok(())}}@@ -212,14 +294,30 @@ impl GithubOauth for StubGithubOauth {#[derive(Clone)]struct StubAuth {access_token: String,+ state: Arc<Mutex<StubAuthState>>,+}++#[derive(Default)]+struct StubAuthState {+ link_user_calls: u32,+ delete_user_link_calls: u32,}impl StubAuth {fn new(access_token: &str) -> Self {Self {access_token: access_token.to_string(),+ state: Arc::new(Mutex::new(StubAuthState::default())),}}++ fn link_user_calls(&self) -> u32 {+ self.state.lock().unwrap().link_user_calls+ }++ fn delete_user_link_calls(&self) -> u32 {+ self.state.lock().unwrap().delete_user_link_calls+ }}impl Auth for StubAuth {@@ -233,6 +331,7 @@ impl Auth for StubAuth {_username: &str,_access_token: &str,) -> Result<(), Self::Err> {+ self.state.lock().unwrap().link_user_calls += 1;Ok(())}@@ -241,6 +340,7 @@ impl Auth for StubAuth {_github_link: &GithubLink,_github_idp_id: &str,) -> Result<(), Self::Err> {+ self.state.lock().unwrap().delete_user_link_calls += 1;Ok(())}@@ -448,6 +548,21 @@ fn test_link(user_id: &MacroUserId<Lowercase<'static>>) -> GithubLink {}}+fn owner_link(fusionauth_user_id: uuid::Uuid) -> GithubLink {+ let owner_user_id = MacroUserIdStr::try_from_email("[email protected]")+ .unwrap()+ .0;+ GithubLink {+ id: uuid::Uuid::from_u128(0xFFFF),+ macro_id: MacroUserIdStr(owner_user_id),+ fusionauth_user_id,+ github_username: "octocat".to_string(),+ github_user_id: "1".to_string(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ }+}+fn pull_request_ref() -> GithubPullRequestRef {GithubPullRequestRef {github_key: "macro/app/pull/7".to_string(),@@ -732,3 +847,128 @@ async fn enrich_pull_requests_returns_enriched_response_when_foreign_entity_patc);assert_eq!(foreign_entity_service.patch_calls().len(), 1);}++#[tokio::test]+async fn link_user_as_sharer_reuses_owner_grant_without_calling_auth() {+ let user_id = test_user_id();+ let owner_fusionauth_user_id = uuid::Uuid::from_u128(0xAAAA_AAAA_AAAA_AAAA_AAAA_AAAA_AAAA_AAAA);+ let arg_fusionauth_user_id = uuid::Uuid::from_u128(0xBBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB);++ let repo = StubGithubRepo::unlinked().with_account_owner(owner_link(owner_fusionauth_user_id));+ let auth = StubAuth::new("valid-token");+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let result = service+ .link_user(+ &user_id,+ &arg_fusionauth_user_id,+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await;++ assert!(result.is_ok());++ let inserted = repo.inserted_links();+ assert_eq!(inserted.len(), 1);+ // SHARER reuses the OWNER's fusionauth grant, not the argument.+ assert_eq!(inserted[0].fusionauth_user_id, owner_fusionauth_user_id);+ assert_ne!(inserted[0].fusionauth_user_id, arg_fusionauth_user_id);++ assert_eq!(auth.link_user_calls(), 0);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 1);+}++#[tokio::test]+async fn link_user_idempotent_relink_same_account_skips_insert() {+ let user_id = test_user_id();+ let existing = test_link(&user_id);++ let repo = StubGithubRepo::linked(existing.clone());+ let auth = StubAuth::new("valid-token");+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let result = service+ .link_user(+ &user_id,+ &uuid::Uuid::from_u128(0xBBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB),+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await;++ let link = result.expect("idempotent relink should succeed");+ // GithubLink does not derive PartialEq; compare identifying fields.+ assert_eq!(link.id, existing.id);+ assert_eq!(link.github_user_id, existing.github_user_id);+ assert_eq!(link.fusionauth_user_id, existing.fusionauth_user_id);++ assert_eq!(auth.link_user_calls(), 0);+ assert_eq!(repo.inserted_links().len(), 0);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 1);+}++#[tokio::test]+async fn link_user_as_owner_creates_grant() {+ let user_id = test_user_id();+ let arg_fusionauth_user_id = uuid::Uuid::from_u128(0xBBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB_BBBB);++ // No link for this user and no existing owner for the github account.+ let repo = StubGithubRepo::unlinked();+ let auth = StubAuth::new("valid-token");+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let result = service+ .link_user(+ &user_id,+ &arg_fusionauth_user_id,+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await;++ assert!(result.is_ok());++ let inserted = repo.inserted_links();+ assert_eq!(inserted.len(), 1);+ // OWNER (first linker) stores the argument's fusionauth grant.+ assert_eq!(inserted[0].fusionauth_user_id, arg_fusionauth_user_id);++ assert_eq!(auth.link_user_calls(), 1);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 1);+}++#[tokio::test]+async fn delete_user_link_sharer_keeps_fusionauth_grant() {+ let user_id = test_user_id();++ let repo = StubGithubRepo::linked(test_link(&user_id)).with_link_count(2);+ let auth = StubAuth::new("valid-token");+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let result = service.delete_user_link(&user_id).await;++ assert!(result.is_ok());+ // Other sharers remain, so the FusionAuth grant must stay in place.+ assert_eq!(auth.delete_user_link_calls(), 0);+ assert_eq!(repo.delete_github_link_calls(), 1);+}++#[tokio::test]+async fn delete_user_link_last_unlinks_fusionauth() {+ let user_id = test_user_id();++ let repo = StubGithubRepo::linked(test_link(&user_id)).with_link_count(1);+ let auth = StubAuth::new("valid-token");+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let result = service.delete_user_link(&user_id).await;++ assert!(result.is_ok());+ // Last/only row for this github account: tear down the FusionAuth grant.+ assert_eq!(auth.delete_user_link_calls(), 1);+ assert_eq!(repo.delete_github_link_calls(), 1);+}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.rsindex 7368f52736..5a632ae01d 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@@ -37,46 +37,58 @@ impl<tracing::info!(installation_id, "processing installation created event");- let macro_id = self+ let links = self.repo- .get_macro_id_by_github_user_id(&sender_github_user_id)+ .get_macro_ids_by_github_user_ids(std::slice::from_ref(&sender_github_user_id)).await.map_err(|e| GithubError::Internal(e.into()))?;- let macro_id = match macro_id {- Some(id) => id,- None => {- tracing::warn!(+ let macro_ids = links+ .get(&sender_github_user_id)+ .cloned()+ .unwrap_or_default();+ if macro_ids.is_empty() {+ tracing::warn!(+ installation_id,+ "no github link found for sender, cannot associate installation with a source"+ );+ return Ok(());+ }++ // A GitHub account may be linked to several Macro users; associate the+ // installation with 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!(installation_id,- "no github link found for sender, cannot associate installation with a source"+ "user has no teams, associating installation with user source");- return Ok(());+ let source = GithubAppInstallationSource::User(macro_id);+ if seen.insert(source.clone()) {+ sources.push(source);+ }+ } else {+ tracing::info!(+ installation_id,+ team_count = team_ids.len(),+ "associating installation with user teams"+ );+ for team_id in team_ids {+ let source = GithubAppInstallationSource::Team(team_id);+ if seen.insert(source.clone()) {+ sources.push(source);+ }+ }}- };-- let team_ids = self- .repo- .get_user_team_ids(¯o_id)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let sources = if team_ids.is_empty() {- tracing::info!(- installation_id,- "user has no teams, associating installation with user source"- );- vec![GithubAppInstallationSource::User(macro_id)]- } else {- tracing::info!(- installation_id,- team_count = team_ids.len(),- "associating installation with user teams"- );- team_ids- .into_iter()- .map(GithubAppInstallationSource::Team)- .collect()- };+ }self.repo.upsert_installation_sources(&installation_id_str, &sources)diff --git a/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs b/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rsindex fda83dd9a2..7652774732 100644--- a/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/notify_pr.rs@@ -198,43 +198,49 @@ impl<&self,github_user_ids: &HashSet<String>,) -> HashSet<MacroUserIdStr<'static>> {- let mut user_ids = HashSet::new();+ if github_user_ids.is_empty() {+ return HashSet::new();+ }- for github_user_id in github_user_ids {- let macro_id = match self- .repo- .get_macro_id_by_github_user_id(github_user_id)- .await- {- Ok(Some(macro_id)) => macro_id,- Ok(None) => {- tracing::trace!(- participant_github_user_id=%github_user_id,- "GitHub PR participant has no Macro user mapping"- );- continue;- }- Err(error) => {- tracing::warn!(- error=?error,- participant_github_user_id=%github_user_id,- "failed to map GitHub PR participant"- );- continue;- }- };+ let github_user_ids: Vec<String> = github_user_ids.iter().cloned().collect();+ let links = match self+ .repo+ .get_macro_ids_by_github_user_ids(&github_user_ids)+ .await+ {+ Ok(links) => links,+ Err(error) => {+ tracing::warn!(+ error=?error,+ "failed to map GitHub PR participants"+ );+ return HashSet::new();+ }+ };- match MacroUserIdStr::try_from(macro_id.clone()) {- Ok(user_id) => {- user_ids.insert(user_id);- }- Err(error) => {- tracing::warn!(- error=?error,- macro_id=%macro_id,- participant_github_user_id=%github_user_id,- "GitHub PR participant mapping is not a valid Macro user ID"- );+ let mut user_ids = HashSet::new();+ for (github_user_id, macro_ids) in links {+ if macro_ids.is_empty() {+ tracing::trace!(+ participant_github_user_id=%github_user_id,+ "GitHub PR participant has no Macro user mapping"+ );+ continue;+ }++ for macro_id in macro_ids {+ match MacroUserIdStr::try_from(macro_id.clone()) {+ Ok(user_id) => {+ user_ids.insert(user_id);+ }+ Err(error) => {+ tracing::warn!(+ error=?error,+ macro_id=%macro_id,+ participant_github_user_id=%github_user_id,+ "GitHub PR participant mapping is not a valid Macro user ID"+ );+ }}}}@@ -299,13 +305,12 @@ impl<event: &ValidatedGithubWebhookEvent,) -> Option<MacroUserIdStr<'static>> {let github_user_id = event.sender_github_user_id()?;- let macro_id = match self+ let links = match self.repo- .get_macro_id_by_github_user_id(&github_user_id)+ .get_macro_ids_by_github_user_ids(std::slice::from_ref(&github_user_id)).await{- Ok(Some(macro_id)) => macro_id,- Ok(None) => return None,+ Ok(links) => links,Err(error) => {tracing::warn!(error=?error,@@ -316,6 +321,10 @@ impl<}};+ // A notification has a single sender; many Macro users may share one+ // GitHub account, so pick the first mapped user.+ let macro_id = links.get(&github_user_id).and_then(|ids| ids.first())?;+match MacroUserIdStr::try_from(macro_id.clone()) {Ok(sender_id) => Some(sender_id),Err(error) => {diff --git a/rust/cloud-storage/github/src/domain/service/sync/notify_pr_activity.rs b/rust/cloud-storage/github/src/domain/service/sync/notify_pr_activity.rsindex 5f26fa80d8..ec66c6b9e1 100644--- a/rust/cloud-storage/github/src/domain/service/sync/notify_pr_activity.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/notify_pr_activity.rs@@ -64,45 +64,24 @@ impl<return;};- let reviewer_macro_id = match self- .repo- .get_macro_id_by_github_user_id(&reviewer_github_user_id)- .await- {- Ok(Some(macro_id)) => macro_id,- Ok(None) => {- tracing::trace!(- reviewer_github_user_id=%reviewer_github_user_id,- "skipping review-requested notification for unmapped reviewer"- );- return;- }- Err(error) => {- tracing::warn!(- error=?error,- reviewer_github_user_id=%reviewer_github_user_id,- "failed to map review-requested reviewer"- );- return;- }- };- let reviewer = match MacroUserIdStr::try_from(reviewer_macro_id.clone()) {- Ok(reviewer) => reviewer,- Err(error) => {- tracing::warn!(- error=?error,- macro_id=%reviewer_macro_id,- "review-requested reviewer mapping is not a valid Macro user ID"- );- return;- }- };+ let reviewers = self+ .macro_users_for_github_user_id(&reviewer_github_user_id)+ .await;+ if reviewers.is_empty() {+ tracing::trace!(+ reviewer_github_user_id=%reviewer_github_user_id,+ "skipping review-requested notification for unmapped reviewer"+ );+ return;+ }let reviewer_login = Self::payload_string(&event.payload, &["requested_reviewer", "login"]);let sender_id = self.notification_sender_id(event).await;for upsert in upserts {let recipients = self.notification_recipient_ids(&upsert.source).await;- if !recipients.contains(&reviewer) {+ let scoped_reviewers: HashSet<_> =+ recipients.intersection(&reviewers).cloned().collect();+ if scoped_reviewers.is_empty() {tracing::trace!(source_id=%upsert.source.source_id(),source_type=%upsert.source.source_type(),@@ -121,7 +100,7 @@ impl<notification,upsert.foreign_entity_id,sender_id.clone(),- HashSet::from([reviewer.clone()]),+ scoped_reviewers,).await;}@@ -255,7 +234,7 @@ impl<}};- let author = self.pull_request_author_macro_user(event).await;+ let authors = self.pull_request_author_macro_users(event).await;let review_github_id = event.payload.get("review")@@ -270,11 +249,9 @@ impl<for upsert in upserts {let recipients = self.notification_recipient_ids(&upsert.source).await;- let review_recipient = author- .as_ref()- .filter(|author| recipients.contains(*author))- .cloned();- if let Some(review_recipient) = &review_recipient {+ let review_recipients: HashSet<_> =+ recipients.intersection(&authors).cloned().collect();+ if !review_recipients.is_empty() {let notification = GithubPrReview {common: Self::github_pr_common(event, pull_request, upsert.foreign_entity_id),review_github_id,@@ -286,7 +263,7 @@ impl<notification,upsert.foreign_entity_id,sender_id.clone(),- HashSet::from([review_recipient.clone()]),+ review_recipients.clone(),).await;}@@ -294,7 +271,7 @@ impl<// Review wins for the author: drop them from the mention fan-out.let mut mention_recipients: HashSet<_> =recipients.intersection(&mentioned_users).cloned().collect();- if let Some(review_recipient) = &review_recipient {+ for review_recipient in &review_recipients {mention_recipients.remove(review_recipient);}if !mention_recipients.is_empty() {@@ -393,54 +370,82 @@ impl<}}- /// Resolve the pull request author from `pull_request.user.id` to a Macro- /// user via `github_links`. Returns `None` (with a trace) when unmapped.- async fn pull_request_author_macro_user(+ /// Resolve the pull request author from `pull_request.user.id` to the Macro+ /// users linked to that GitHub account via `github_links`. Returns an empty+ /// set (with a trace) when unmapped; a single GitHub account may be linked+ /// to several Macro users, so all of them are returned.+ async fn pull_request_author_macro_users(&self,event: &ValidatedGithubWebhookEvent,- ) -> Option<MacroUserIdStr<'static>> {- let author_github_user_id = event+ ) -> HashSet<MacroUserIdStr<'static>> {+ let Some(author_github_user_id) = event.payload.get("pull_request").and_then(|pull_request| pull_request.get("user")).and_then(|user| user.get("id")).and_then(|id| id.as_u64())- .map(|id| id.to_string())?;+ .map(|id| id.to_string())+ else {+ return HashSet::new();+ };- let macro_id = match self+ let authors = self+ .macro_users_for_github_user_id(&author_github_user_id)+ .await;+ if authors.is_empty() {+ tracing::trace!(+ author_github_user_id=%author_github_user_id,+ "pull request author has no Macro mapping"+ );+ }++ authors+ }++ /// Resolve a single GitHub user ID to the Macro users linked to it via+ /// `github_links`. Unmapped GitHub user IDs and invalid Macro IDs are+ /// skipped. A GitHub account may be linked to several Macro users.+ async fn macro_users_for_github_user_id(+ &self,+ github_user_id: &str,+ ) -> HashSet<MacroUserIdStr<'static>> {+ let links = match self.repo- .get_macro_id_by_github_user_id(&author_github_user_id)+ .get_macro_ids_by_github_user_ids(std::slice::from_ref(&github_user_id.to_string())).await{- Ok(Some(macro_id)) => macro_id,- Ok(None) => {- tracing::trace!(- author_github_user_id=%author_github_user_id,- "pull request author has no Macro mapping"- );- return None;- }+ Ok(links) => links,Err(error) => {tracing::warn!(error=?error,- author_github_user_id=%author_github_user_id,- "failed to map pull request author"+ github_user_id=%github_user_id,+ "failed to map GitHub user ID to Macro users");- return None;+ return HashSet::new();}};- match MacroUserIdStr::try_from(macro_id.clone()) {- Ok(author) => Some(author),- Err(error) => {- tracing::warn!(- error=?error,- macro_id=%macro_id,- "pull request author mapping is not a valid Macro user ID"- );- None- }- }+ let Some(macro_ids) = links.get(github_user_id) else {+ return HashSet::new();+ };++ macro_ids+ .iter()+ .filter_map(+ |macro_id| match MacroUserIdStr::try_from(macro_id.clone()) {+ Ok(user_id) => Some(user_id),+ Err(error) => {+ tracing::warn!(+ error=?error,+ macro_id=%macro_id,+ github_user_id=%github_user_id,+ "GitHub user mapping is not a valid Macro user ID"+ );+ None+ }+ },+ )+ .collect()}/// Resolve the Macro users @mentioned in `text` via their `github_links`diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 69899c10e6..bcef550f19 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -287,8 +287,11 @@ struct StubSyncRepo {tasks: Mutex<HashMap<String, HashSet<String>>>,/// Maps (installation_id, normalized team_slug, team_task_id) -> task ID.team_task_references: Mutex<HashMap<(String, String, i32), MacroTaskId>>,- /// Maps github_user_id -> macro_id for installation event lookups.- github_links: Mutex<HashMap<String, String>>,+ /// Maps github_user_id -> macro_ids for installation event lookups.+ ///+ /// A github_user_id may map to multiple Macro users because multiple Macro+ /// users can share one GitHub account.+ github_links: Mutex<HashMap<String, Vec<String>>>,/// Maps lowercase github login -> macro_ids for mention lookups.github_login_links: Mutex<HashMap<String, Vec<String>>>,/// Maps macro_id -> team_ids for installation event lookups.@@ -319,7 +322,9 @@ impl StubSyncRepo {self.github_links.lock().unwrap()- .insert(github_user_id.to_string(), macro_id.to_string());+ .entry(github_user_id.to_string())+ .or_default()+ .push(macro_id.to_string());self}@@ -461,16 +466,18 @@ impl GithubSyncRepo for StubSyncRepo {Ok(resolved)}- async fn get_macro_id_by_github_user_id(+ async fn get_macro_ids_by_github_user_ids(&self,- github_user_id: &str,- ) -> Result<Option<String>, Self::Err> {- Ok(self- .github_links- .lock()- .unwrap()- .get(github_user_id)- .cloned())+ github_user_ids: &[String],+ ) -> Result<HashMap<String, Vec<String>>, Self::Err> {+ let links = self.github_links.lock().unwrap();+ Ok(github_user_ids+ .iter()+ .filter_map(|github_user_id| {+ let macro_ids = links.get(github_user_id)?.clone();+ Some((github_user_id.clone(), macro_ids))+ })+ .collect())}async fn get_macro_ids_by_github_logins(@@ -3979,6 +3986,48 @@ async fn review_requested_notifies_only_mapped_reviewer_in_team() {);}+#[tokio::test]+async fn review_requested_fans_out_to_all_macro_users_sharing_reviewer_github_account() {+ // The requested reviewer's GitHub account (id 333) is shared by two Macro+ // users, both of whom are members of the source team. The notification+ // should fan out to both of them.+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();+ let repo = StubSyncRepo::new()+ .with_installation_sources("12345", vec![GithubAppInstallationSource::Team(team_id)])+ .with_team_members(+ team_id,+ vec![+ "macro|[email protected]",+ "macro|[email protected]",+ "macro|[email protected]",+ ],+ )+ .with_github_link("222", "macro|[email protected]")+ .with_github_link("333", "macro|[email protected]")+ .with_github_link("333", "macro|[email protected]");+ let service = make_sync_service_with_repo(repo);+ let event = notification_review_requested_event(Some((333, "bob-gh")), 222, "octocat");++ service.process_webhook_event(&event).await.unwrap();++ let requests = service.notification_ingress.requests();+ assert_eq!(+ requests.len(),+ 1,+ "expected only the review-requested notification"+ );++ let request = &requests[0];+ assert_github_notification_realtime_enabled_apns_disabled(request, "github_review_requested");+ assert_eq!(+ notification_request_recipients(request),+ vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ]+ );+}+#[tokio::test]async fn review_requested_unmapped_reviewer_does_not_notify() {let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();diff --git a/rust/cloud-storage/github/src/inbound.rs b/rust/cloud-storage/github/src/inbound.rsindex 66af30d09b..600e51d32c 100644--- a/rust/cloud-storage/github/src/inbound.rs+++ b/rust/cloud-storage/github/src/inbound.rs@@ -19,9 +19,6 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {StatusCode::PRECONDITION_REQUIRED,"ReauthenticationRequired",),- crate::domain::models::GithubError::AccountAlreadyLinked => {- (StatusCode::BAD_REQUEST, "account already linked")- }crate::domain::models::GithubError::NoRefreshTokenProvided => (StatusCode::UNPROCESSABLE_ENTITY,"no refresh token was provided",diff --git a/rust/cloud-storage/github/src/outbound/github_auth_client.rs b/rust/cloud-storage/github/src/outbound/github_auth_client.rsindex 01a586e170..82715f935a 100644--- a/rust/cloud-storage/github/src/outbound/github_auth_client.rs+++ b/rust/cloud-storage/github/src/outbound/github_auth_client.rs@@ -65,7 +65,8 @@ impl Auth for GithubAuthImpl {username: &str,access_token: &str,) -> Result<(), Self::Err> {- self.fusionauth_client+ match self+ .fusionauth_client.link_user(LinkUserRequest {identity_provider_link: IdentityProviderLink {display_name: username.into(),@@ -75,7 +76,17 @@ impl Auth for GithubAuthImpl {token: access_token.into(),},})- .await?;+ .await+ {+ Ok(()) => {}+ Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {+ tracing::info!(+ fusionauth_user_id=%fusionauth_user_id,+ "github idp link already exists, proceeding with existing grant"+ );+ }+ Err(e) => return Err(e.into()),+ }self.clear_access_token_cache(fusionauth_user_id).await?;@@ -108,7 +119,7 @@ impl Auth for GithubAuthImpl {anyhow::bail!("user does not have a github link")}- // SAFETY: at the moment, we only support 1 github link per user+ // SAFETY: each Macro user links at most one GitHub account, and many users can share one GitHub account. For shared accounts, every github_links row stores the owner's fusionauth_user_id, so this lookup resolves to the owner's single shared FusionAuth grant (and its cached token).let link = links.first().context("links should not be empty")?;conn.set_ex::<&str, &str, ()>(&key, &link.token, TTL_SECONDS)diff --git a/rust/cloud-storage/github/src/outbound/pg_github_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_repo.rsindex 067d11f77b..1de3d02d1c 100644--- a/rust/cloud-storage/github/src/outbound/pg_github_repo.rs+++ b/rust/cloud-storage/github/src/outbound/pg_github_repo.rs@@ -72,6 +72,8 @@ impl GithubRepo for PgGithubRepo {SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_atFROM github_linksWHERE github_user_id = $1+ ORDER BY created_at ASC+ LIMIT 1"#,github_user_id)@@ -95,6 +97,25 @@ impl GithubRepo for PgGithubRepo {}}+ #[tracing::instrument(skip(self), err)]+ async fn count_github_links_by_github_user_id(+ &self,+ github_user_id: &str,+ ) -> Result<i64, Self::Err> {+ let count = sqlx::query_scalar!(+ r#"+ SELECT COUNT(*)+ FROM github_links+ WHERE github_user_id = $1+ "#,+ github_user_id+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(count.unwrap_or(0))+ }+#[tracing::instrument(skip(self), err)]async fn get_github_link_by_id(&self, id: &uuid::Uuid) -> Result<GithubLink, Self::Err> {let link = sqlx::query!(diff --git a/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rsindex a926453ccc..a000774757 100644--- a/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs+++ b/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs@@ -132,26 +132,140 @@ async fn test_insert_github_link(pool: Pool<Postgres>) {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_test_data")))]-async fn test_insert_github_link_duplicate_github_user_id(pool: Pool<Postgres>) {+async fn test_insert_github_link_shared_github_user_id_succeeds(pool: Pool<Postgres>) {+ let repo = PgGithubRepo::new(pool);++ let now = chrono::Utc::now();+ let id = uuid::Uuid::new_v4();+ let link = GithubLink {+ id,+ // Different macro user than the fixture owner of github_user_id 12345.+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ fusionauth_user_id: uuid::Uuid::new_v4(),+ github_username: "shareruser".to_string(),+ github_user_id: "12345".to_string(), // same github account as fixture+ created_at: now,+ updated_at: now,+ };++ // A different macro user may now link the same github_user_id, since the+ // unique constraint is on (macro_id, github_user_id) rather than github_user_id.+ let result = repo.insert_github_link(&link).await;+ assert!(result.is_ok());++ // Confirm the row was actually persisted.+ let fetched = repo.get_github_link_by_id(&id).await.unwrap();+ assert_eq!(fetched.macro_id.as_ref(), "macro|[email protected]");+ assert_eq!(fetched.github_user_id, "12345");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_test_data"))+)]+async fn test_insert_github_link_duplicate_macro_and_github_user_id_fails(pool: Pool<Postgres>) {let repo = PgGithubRepo::new(pool);let now = chrono::Utc::now();let link = GithubLink {id: uuid::Uuid::new_v4(),- macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")+ // Existing fixture user who already owns github_user_id 12345.+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap().into_owned(),fusionauth_user_id: uuid::Uuid::new_v4(),- github_username: "otheruser".to_string(),- github_user_id: "12345".to_string(), // same as fixture+ github_username: "testuser".to_string(),+ github_user_id: "12345".to_string(), // same (macro_id, github_user_id) as fixturecreated_at: now,updated_at: now,};+ // Re-using the same (macro_id, github_user_id) pair must violate the+ // composite unique constraint.let result = repo.insert_github_link(&link).await;assert!(result.is_err());}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_test_data"))+)]+async fn test_get_github_link_by_github_user_id_returns_owner(pool: Pool<Postgres>) {+ let repo = PgGithubRepo::new(pool);++ // Insert a second link for github_user_id 12345 belonging to a different+ // macro user, with a created_at strictly later than the fixture row+ // (aaaa..., default/earlier timestamp) so the owner is unambiguous.+ let later = chrono::Utc::now() + chrono::Duration::days(1);+ let sharer_link = GithubLink {+ id: uuid::Uuid::new_v4(),+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ fusionauth_user_id: uuid::Uuid::new_v4(),+ github_username: "shareruser".to_string(),+ github_user_id: "12345".to_string(),+ created_at: later,+ updated_at: later,+ };+ repo.insert_github_link(&sharer_link).await.unwrap();++ // The owner is the earliest-created row (the fixture row), not the sharer.+ let link = repo+ .get_github_link_by_github_user_id("12345")+ .await+ .unwrap();++ assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");+ assert_eq!(link.github_username, "testuser");+ assert_eq!(link.github_user_id, "12345");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_test_data"))+)]+async fn test_count_github_links_by_github_user_id(pool: Pool<Postgres>) {+ let repo = PgGithubRepo::new(pool);++ // The fixture has a single row for github_user_id 12345.+ let count = repo+ .count_github_links_by_github_user_id("12345")+ .await+ .unwrap();+ assert_eq!(count, 1);++ // Add a second link for the same github account under a different macro user.+ let now = chrono::Utc::now();+ let sharer_link = GithubLink {+ id: uuid::Uuid::new_v4(),+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ fusionauth_user_id: uuid::Uuid::new_v4(),+ github_username: "shareruser".to_string(),+ github_user_id: "12345".to_string(),+ created_at: now,+ updated_at: now,+ };+ repo.insert_github_link(&sharer_link).await.unwrap();++ let count = repo+ .count_github_links_by_github_user_id("12345")+ .await+ .unwrap();+ assert_eq!(count, 2);++ // An absent github_user_id has no links.+ let count = repo+ .count_github_links_by_github_user_id("99999")+ .await+ .unwrap();+ assert_eq!(count, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_test_data"))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.rsindex 922fe623f7..20ab42b56c 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@@ -160,22 +160,35 @@ impl GithubSyncRepo for PgGithubSyncRepo {}#[tracing::instrument(skip(self), err)]- async fn get_macro_id_by_github_user_id(+ async fn get_macro_ids_by_github_user_ids(&self,- github_user_id: &str,- ) -> Result<Option<String>, Self::Err> {- let macro_id = sqlx::query_scalar!(+ github_user_ids: &[String],+ ) -> Result<std::collections::HashMap<String, Vec<String>>, Self::Err> {+ if github_user_ids.is_empty() {+ return Ok(std::collections::HashMap::new());+ }++ let rows = sqlx::query!(r#"- SELECT macro_id+ SELECT github_user_id, macro_idFROM github_links- WHERE github_user_id = $1+ WHERE github_user_id = ANY($1::text[])"#,- github_user_id,+ github_user_ids,)- .fetch_optional(&self.pool)+ .fetch_all(&self.pool).await?;- Ok(macro_id)+ let mut links: std::collections::HashMap<String, Vec<String>> =+ std::collections::HashMap::new();+ for row in rows {+ links+ .entry(row.github_user_id)+ .or_default()+ .push(row.macro_id);+ }++ Ok(links)}#[tracing::instrument(skip(self), err)]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.rsindex 4a8c125e07..6c0f9a13ac 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@@ -300,28 +300,81 @@ async fn test_get_installation_sources_empty(pool: Pool<Postgres>) {}// ----------------------------------------------------------------------------// get_macro_id_by_github_user_id+// get_macro_ids_by_github_user_ids// ---------------------------------------------------------------------------#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_installation_test_data")))]-async fn test_get_macro_id_by_github_user_id_found(pool: Pool<Postgres>) {+async fn test_get_macro_ids_by_github_user_ids_found(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);- let macro_id = repo.get_macro_id_by_github_user_id("12345").await.unwrap();+ let links = repo+ .get_macro_ids_by_github_user_ids(&["12345".to_string()])+ .await+ .unwrap();- assert_eq!(macro_id.as_deref(), Some("macro|[email protected]"));+ assert_eq!(+ links.get("12345"),+ Some(&vec!["macro|[email protected]".to_string()])+ );}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn test_get_macro_id_by_github_user_id_not_found(pool: Pool<Postgres>) {+async fn test_get_macro_ids_by_github_user_ids_not_found(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool);++ let links = repo+ .get_macro_ids_by_github_user_ids(&["99999".to_string()])+ .await+ .unwrap();++ assert!(!links.contains_key("99999"));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))+)]+async fn test_get_macro_ids_by_github_user_ids_fans_out_to_multiple_users(pool: Pool<Postgres>) {+ // A second link sharing github_user_id '12345' (github_user_id is not unique;+ // multiple Macro users may share one GitHub account).+ sqlx::query(+ r#"+ INSERT INTO public.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)+ VALUES ($1, $2, $3, $4, $5)+ "#,+ )+ .bind(Uuid::new_v4())+ .bind("macro|[email protected]")+ .bind(+ "cccccccc-cccc-cccc-cccc-cccccccccccc"+ .parse::<Uuid>()+ .unwrap(),+ )+ .bind("testuser2")+ .bind("12345")+ .execute(&pool)+ .await+ .unwrap();+let repo = PgGithubSyncRepo::new(pool);- let macro_id = repo.get_macro_id_by_github_user_id("99999").await.unwrap();+ let links = repo+ .get_macro_ids_by_github_user_ids(&["12345".to_string()])+ .await+ .unwrap();- assert!(macro_id.is_none());+ let mut macro_ids = links.get("12345").cloned().unwrap_or_default();+ macro_ids.sort();+ assert_eq!(+ macro_ids,+ vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ]+ );}// ---------------------------------------------------------------------------diff --git a/rust/cloud-storage/macro_db_client/migrations/20260630200839_allow_multiple_users_per_github_link.sql b/rust/cloud-storage/macro_db_client/migrations/20260630200839_allow_multiple_users_per_github_link.sqlnew file mode 100644index 0000000000..e6fbd09b50--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260630200839_allow_multiple_users_per_github_link.sql@@ -0,0 +1,14 @@+-- Relax GitHub account linking from "one GitHub account per user" to+-- "many Macro users may share one GitHub account". The unique index from+-- migration 20260226142003 encoded the old assumption and blocks a second+-- user from linking a GitHub account already linked by another user.+DROP INDEX IF EXISTS uq_github_links_github_user_id;++-- Keep GitHub-account lookups fast (sync queries by github_user_id) with a+-- non-unique index.+CREATE INDEX idx_github_links_github_user_id+ ON public.github_links (github_user_id);++-- Composite guard: a single user still cannot link the same GitHub account twice.+CREATE UNIQUE INDEX uq_github_links_macro_id_github_user_id+ ON public.github_links (macro_id, github_user_id);