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
fix(github): recover stale grants while preserving existing links (#8359)
Peter Chinmande639f32d440
diff --git a/.sqlx/query-74001908e096c8a385879654ad39d78ab16d62661412e0023d2f50cd7025a222.json b/.sqlx/query-74001908e096c8a385879654ad39d78ab16d62661412e0023d2f50cd7025a222.jsonnew file mode 100644index 0000000000..fca2a3b2ae--- /dev/null+++ b/.sqlx/query-74001908e096c8a385879654ad39d78ab16d62661412e0023d2f50cd7025a222.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE github_links\n SET fusionauth_user_id = $3, updated_at = NOW()\n WHERE github_user_id = $1 AND fusionauth_user_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "74001908e096c8a385879654ad39d78ab16d62661412e0023d2f50cd7025a222"+}diff --git a/Cargo.lock b/Cargo.lockindex 13349adcab..0559f0caf8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8765,6 +8765,7 @@ dependencies = ["urlencoding","utoipa","uuid",+ "wiremock","workspace-hack",]diff --git a/apps/web/src/lib/service-clients/service-auth/client.test.ts b/apps/web/src/lib/service-clients/service-auth/client.test.tsindex 96bba982be..26baaa3e74 100644--- a/apps/web/src/lib/service-clients/service-auth/client.test.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.test.ts@@ -125,3 +125,19 @@ describe('subscription checkout conflicts', () => {expect(result._unsafeUnwrapErr()[0]).toEqual({ code: 'CONFLICT', message });});});++describe('GitHub reconnect', () => {+ test('starts OAuth without deleting the current link', async () => {+ fetchCheckout.mockResolvedValueOnce(+ ok({ url: 'https://github.com/login/oauth/authorize' })+ );+ const result =+ await authServiceClient.reauthenticateGithub('tauri://localhost');+ expect(result.isOk()).toBe(true);+ expect(fetchCheckout).toHaveBeenCalledTimes(1);+ expect(fetchCheckout).toHaveBeenCalledWith(+ expect.stringContaining('/link/github'),+ expect.objectContaining({ method: 'POST' })+ );+ });+});diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex ca4be21472..6887f2f691 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -12,7 +12,7 @@ import {import { Telemetry } from '@macro-inc/observability';import { makePersisted } from '@solid-primitives/storage';-import { err, ok } from 'neverthrow';+import { ok } from 'neverthrow';import { createSignal } from 'solid-js';import type {AiPlanCatalog,@@ -1112,11 +1112,7 @@ export const authServiceClient = {},async reauthenticateGithub(originalUrl?: string) {- const deleteResult = await authServiceClient.deleteGithubLink();- if (deleteResult.isErr()) {- return err(deleteResult.error);- }-+ // The OAuth callback refreshes the grant after verifying the GitHub account.return authServiceClient.initGithubLink(originalUrl);},diff --git a/crates/fusionauth/AGENTS.md b/crates/fusionauth/AGENTS.mdindex 83986e88b1..b20713704e 100644--- a/crates/fusionauth/AGENTS.md+++ b/crates/fusionauth/AGENTS.md@@ -39,6 +39,14 @@ passwordless/password flows against the FusionAuth HTTP API.- `cargo test -p fusionauth`.+## Gotchas++- Link lookup and unlink map HTTP 400 `userId` / `[invalid]userId` errors to+ `UserDoesNotExist`; other validation, authentication, and server failures+ must remain errors. Never log identity-provider link tokens.+- Bound identity-provider link lookup, creation, and deletion requests to thirty+ seconds, including response-body reads; their callers may hold account locks.+## Related- Rules: `.agents/rules/config-and-service-urls.md` (FusionAuth base URL/keysdiff --git a/crates/fusionauth/Cargo.toml b/crates/fusionauth/Cargo.tomlindex 54a0038050..96fbc2fb77 100644--- a/crates/fusionauth/Cargo.toml+++ b/crates/fusionauth/Cargo.toml@@ -19,5 +19,5 @@ uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]-tokio = { workspace = true }+tokio = { workspace = true, features = ["test-util", "net", "io-util", "sync"] }wiremock = { workspace = true }diff --git a/crates/fusionauth/src/identity_provider.rs b/crates/fusionauth/src/identity_provider.rsindex 9c195ed355..1074bae73f 100644--- a/crates/fusionauth/src/identity_provider.rs+++ b/crates/fusionauth/src/identity_provider.rs@@ -2,10 +2,15 @@ use std::borrow::Cow;use crate::{FusionAuthClient, Result};+// Grant replacement holds a shared account lock across these requests.+const LINK_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);+mod link;mod login;mod lookup;mod search;+#[cfg(test)]+mod test;mod unlink;pub use link::{IdentityProviderLink, Link, LinkUserRequest, RetrieveLinkResponse};diff --git a/crates/fusionauth/src/identity_provider/link.rs b/crates/fusionauth/src/identity_provider/link.rsindex e9f37f3124..a2508f8942 100644--- a/crates/fusionauth/src/identity_provider/link.rs+++ b/crates/fusionauth/src/identity_provider/link.rs@@ -30,6 +30,17 @@ impl FusionAuthErrorBody {}}+/// Link lookups and deletes report a deleted user as a validation error.+pub(super) fn is_missing_user(body: &str) -> bool {+ serde_json::from_str::<FusionAuthErrorBody>(body)+ .ok()+ .is_some_and(|body| {+ body.field_errors+ .get("userId")+ .is_some_and(|errors| errors.iter().any(|error| error.code == "[invalid]userId"))+ })+}+#[derive(serde::Serialize, serde::Deserialize, Debug)]#[serde(rename_all = "camelCase")]/// Response containing identity provider links.@@ -81,13 +92,20 @@ pub(crate) async fn get_links(url.push_str(&format!("&identityProviderId={id}"));}- let res = client.client().get(url).send().await.map_err(|e| {- FusionAuthClientError::Generic(GenericErrorResponse {- message: e.to_string(),- })- })?;+ let res = client+ .client()+ .get(url)+ .timeout(super::LINK_REQUEST_TIMEOUT)+ .send()+ .await+ .map_err(|e| {+ FusionAuthClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;- match res.status() {+ let status = res.status();+ match status {reqwest::StatusCode::OK => {let response: RetrieveLinkResponse = res.json().await.map_err(|e| {tracing::error!(error=?e, "unable to parse response");@@ -96,17 +114,21 @@ pub(crate) async fn get_links(})})?;- tracing::trace!(identity_provider=?response.idp_links, "links found");+ tracing::trace!(link_count = response.idp_links.len(), "links found");Ok(response.idp_links)}+ reqwest::StatusCode::NOT_FOUND => Err(FusionAuthClientError::NoIdentityProviderFound),_ => {let body = res.text().await.map_err(|e| {FusionAuthClientError::Generic(GenericErrorResponse {message: e.to_string(),})})?;- tracing::error!(body=%body, "unexpected response from fusionauth");+ if status == reqwest::StatusCode::BAD_REQUEST && is_missing_user(&body) {+ return Err(FusionAuthClientError::UserDoesNotExist);+ }+ tracing::error!(%status, "unexpected response from fusionauth");Err(FusionAuthClientError::Generic(GenericErrorResponse {message: "unknown error".to_string(),@@ -150,6 +172,7 @@ pub(crate) async fn link_user(let res = client.client().post(format!("{base_url}/api/identity-provider/link",))+ .timeout(super::LINK_REQUEST_TIMEOUT).json(&request).send().awaitdiff --git a/crates/fusionauth/src/identity_provider/test.rs b/crates/fusionauth/src/identity_provider/test.rsnew file mode 100644index 0000000000..372862e700--- /dev/null+++ b/crates/fusionauth/src/identity_provider/test.rs@@ -0,0 +1,149 @@+use crate::{FusionAuthClient, error::FusionAuthClientError};+use serde_json::json;+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path, query_param},+};++fn client(base_url: String) -> FusionAuthClient {+ FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ base_url,+ "http://localhost/callback".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ )+}++#[tokio::test]+async fn grant_requests_time_out_when_the_provider_stops_responding() {+ use tokio::io::AsyncReadExt;++ for method in ["GET", "POST", "DELETE"] {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let (accepted, received) = tokio::sync::oneshot::channel();+ let server = tokio::spawn(async move {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut byte = [0];+ stream.read_exact(&mut byte).await.unwrap();+ accepted.send(()).unwrap();+ // Keep the connection open without returning an HTTP response.+ std::future::pending::<()>().await;+ drop(stream);+ });+ let client = client(format!("http://{address}"));+ let mut request = tokio::spawn(async move {+ match method {+ "GET" => client+ .get_links("identity", Some("github".into()))+ .await+ .map(|_| ()),+ "DELETE" => client.unlink_user("identity", "github", "1").await,+ _ => {+ client+ .link_user(super::LinkUserRequest {+ identity_provider_link: super::IdentityProviderLink {+ display_name: "octocat".into(),+ identity_provider_id: "github".into(),+ identity_provider_user_id: "1".into(),+ user_id: "identity".into(),+ token: "token".into(),+ },+ })+ .await+ }+ }+ });+ received.await.unwrap();+ tokio::time::pause();+ tokio::time::advance(super::LINK_REQUEST_TIMEOUT + std::time::Duration::from_secs(1)).await;+ let result = tokio::time::timeout(std::time::Duration::from_secs(1), &mut request).await;+ tokio::time::resume();+ server.abort();+ request.abort();+ assert!(+ matches!(result, Ok(Ok(Err(FusionAuthClientError::Generic(_))))),+ "{method} must time out as an infrastructure error: {result:?}"+ );+ }+}++#[tokio::test]+async fn deleted_identity_is_typed_for_lookup_and_disconnect() {+ let server = MockServer::start().await;+ for verb in ["GET", "DELETE"] {+ Mock::given(method(verb)).and(path("/api/identity-provider/link"))+ .and(query_param("userId", "fd3a2d52-7168-4810-96ff-8f793e0813cb"))+ .respond_with(ResponseTemplate::new(400).set_body_json(json!({+ "fieldErrors": { "userId": [{ "code": "[invalid]userId", "message": "No user exists with this Id" }] },+ "generalErrors": []+ })))+ .expect(1).mount(&server).await;+ }+ let client = client(server.uri());+ assert!(matches!(+ client+ .get_links(+ "fd3a2d52-7168-4810-96ff-8f793e0813cb",+ Some("github-idp".into())+ )+ .await,+ Err(FusionAuthClientError::UserDoesNotExist)+ ));+ assert!(matches!(+ client+ .unlink_user("fd3a2d52-7168-4810-96ff-8f793e0813cb", "github-idp", "1")+ .await,+ Err(FusionAuthClientError::UserDoesNotExist)+ ));+}++#[tokio::test]+async fn other_failures_are_not_misclassified_as_deleted_users() {+ for (status, body) in [+ (400, json!({ "fieldErrors": { "identityProviderId": [{ "code": "[invalid]identityProviderId" }] } }).to_string()),+ (400, "invalid JSON".into()),+ (401, String::new()),+ (500, json!({ "fieldErrors": { "userId": [{ "code": "[invalid]userId" }] } }).to_string()),+ ] {+ let server = MockServer::start().await;+ Mock::given(path("/api/identity-provider/link"))+ .respond_with(ResponseTemplate::new(status).set_body_string(body))+ .expect(2).mount(&server).await;+ let client = client(server.uri());+ assert!(matches!(client.get_links("user", Some("idp".into())).await, Err(FusionAuthClientError::Generic(_))));+ assert!(matches!(client.unlink_user("user", "idp", "1").await, Err(FusionAuthClientError::Generic(_))));+ }+}++#[tokio::test]+async fn absent_link_and_empty_links_are_distinct_from_infrastructure_errors() {+ let server = MockServer::start().await;+ Mock::given(query_param("userId", "absent"))+ .respond_with(ResponseTemplate::new(404))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(query_param("userId", "empty"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(json!({ "identityProviderLinks": [] })),+ )+ .expect(1)+ .mount(&server)+ .await;+ let client = client(server.uri());+ assert!(matches!(+ client.get_links("absent", Some("idp".into())).await,+ Err(FusionAuthClientError::NoIdentityProviderFound)+ ));+ assert!(+ client+ .get_links("empty", Some("idp".into()))+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/fusionauth/src/identity_provider/unlink.rs b/crates/fusionauth/src/identity_provider/unlink.rsindex bb6febc0f7..5192aaa2e8 100644--- a/crates/fusionauth/src/identity_provider/unlink.rs+++ b/crates/fusionauth/src/identity_provider/unlink.rs@@ -18,6 +18,7 @@ pub(crate) async fn unlink(.delete(format!("{base_url}/api/identity-provider/link?identityProviderId={idp_id}&identityProviderUserId={idp_user_id}&userId={user_id}",))+ .timeout(super::LINK_REQUEST_TIMEOUT).send().await.map_err(|e| {@@ -36,6 +37,9 @@ pub(crate) async fn unlink(match status {reqwest::StatusCode::OK => Ok(()),reqwest::StatusCode::NOT_FOUND => Err(FusionAuthClientError::NoIdentityProviderFound), // no idp to unlink+ reqwest::StatusCode::BAD_REQUEST if super::link::is_missing_user(&body) => {+ Err(FusionAuthClientError::UserDoesNotExist)+ }_ => Err(FusionAuthClientError::Generic(GenericErrorResponse {message: body,})),diff --git a/crates/github/AGENTS.md b/crates/github/AGENTS.mdindex aef522e827..262df68f63 100644--- a/crates/github/AGENTS.md+++ b/crates/github/AGENTS.md@@ -44,10 +44,26 @@ link flow, following the hexagonal architecture pattern.## Checks- `cargo test -p github --all-features` (`SQLX_OFFLINE` unset).+- Start local PostgreSQL and Redis first (`docs/development/database.md`);+ `REDIS_URL` overrides the Redis test endpoint. Keep the token-cache race test+ enabled in CI, which provisions Redis.- `just check` (from this directory) runs `cargo check --all-features`.## Gotchas+- Missing FusionAuth identities/grants require reauthentication; infrastructure+ errors remain errors. After OAuth proves GitHub identity, refresh the grant+ before returning an existing link. Reassign every sharer when its grant owner+ is gone, using the old owner as a compare-and-swap condition. Hold the user+ guard then the GitHub account guard through OAuth grant writes and DB changes;+ disconnect follows the same order. Cache tokens by identity and GitHub account.+- Keep lock-pool acquisition and advisory waits bounded at five seconds; only+ the dedicated lock connections use the five-second lock and ten-second+ statement timeouts. Never expire idle transactions while grant writes run.+- Grant replacement is unlink/relink with best-effort restoration. A timeout+ leaves the remote result uncertain; a crash can leave no grant. Preserve+ Macro links so a later verified OAuth attempt can recreate it.+- Webhook signature verification uses `hmac`/`subtle` for constant-timecomparison — don't swap in a plain `==` when touching`github_sync_router.rs`.diff --git a/crates/github/Cargo.toml b/crates/github/Cargo.tomlindex b29f2a4102..207ee59e72 100644--- a/crates/github/Cargo.toml+++ b/crates/github/Cargo.toml@@ -97,6 +97,8 @@ utoipa = { workspace = true, optional = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+axum = { workspace = true }+wiremock = { workspace = true }document_sub_type = { path = "../document_sub_type" }foreign_entity = { path = "../foreign_entity", default-features = false, features = ["ports",diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rsindex f936814108..d6698c603a 100644--- a/crates/github/src/domain/models.rs+++ b/crates/github/src/domain/models.rs@@ -31,7 +31,8 @@ pub use installation_state::{InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,};pub use link::{- GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubLinkStatus, GithubUserInfo,+ GithubAccessToken, GithubExchangeTokenResponse, GithubGrantLinkOutcome, GithubLink,+ GithubLinkStatus, GithubUserInfo,};pub use repository::{GithubRepository, PullRequestIndexPage, PullRequestIndexRequest};pub use sync::{@@ -53,6 +54,9 @@ pub enum GithubError {/// The Github link token has expired and the user must reauthenticate.#[error("reauthentication required")]ReauthenticationRequired,+ /// Reconnect must use the currently linked GitHub account.+ #[error("disconnect the current GitHub account before linking a different account")]+ AccountMismatch,/// No refresh token was provided in the token exchange#[error("no refresh token provided in token exchange")]NoRefreshTokenProvided,diff --git a/crates/github/src/domain/models/link.rs b/crates/github/src/domain/models/link.rsindex 3aa29c3312..7564a922f2 100644--- a/crates/github/src/domain/models/link.rs+++ b/crates/github/src/domain/models/link.rs@@ -26,6 +26,15 @@ impl AsRef<str> for GithubAccessToken {}}+/// Result of storing an OAuth grant on an authentication identity.+#[derive(Debug, PartialEq, Eq)]+pub enum GithubGrantLinkOutcome {+ /// The grant was created or refreshed.+ Linked,+ /// The authentication identity no longer exists.+ IdentityMissing,+}+/// A GitHub link record (as stored in the database)#[derive(Debug, Clone)]pub struct GithubLink {diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rsindex f06795f39c..66c3182a1b 100644--- a/crates/github/src/domain/ports/link.rs+++ b/crates/github/src/domain/ports/link.rs@@ -4,11 +4,12 @@ use std::future::Future;use crate::domain::models::{EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError,- GithubExchangeTokenResponse, GithubLink, GithubLinkStatus, GithubMergeMethod,- GithubMergeOutcome, GithubPullRequestDetails, GithubPullRequestMergeabilityEntry,- GithubPullRequestNumber, GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,- SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ GithubExchangeTokenResponse, GithubGrantLinkOutcome, GithubLink, GithubLinkStatus,+ GithubMergeMethod, GithubMergeOutcome, GithubPullRequestDetails,+ GithubPullRequestMergeabilityEntry, GithubPullRequestNumber, GithubPullRequestRef,+ GithubRepositoryMergeSettings, GithubUserInfo, MergeGithubPullRequestRequest,+ MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,+ SetGithubPullRequestDraftResponse,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};@@ -16,11 +17,27 @@ use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};////// All methods perform database operations — SQL queries are written/// directly in the outbound adapter implementation.-#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error; type LinkGuard = ();))]pub trait GithubRepo: Send + Sync + 'static {/// The error type returned by repository operations.type Err: Into<anyhow::Error> + Send + std::fmt::Debug;+ /// Held until the complete cross-system link operation finishes.+ type LinkGuard: Send;++ /// Serializes callbacks and disconnects for one Macro user.+ fn lock_user_link(+ &self,+ user_id: &str,+ ) -> impl Future<Output = Result<Self::LinkGuard, Self::Err>> + Send;++ /// Serializes mutations of a grant shared by multiple Macro users.+ fn lock_github_account(+ &self,+ guard: &mut Self::LinkGuard,+ github_user_id: &str,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Gets the github link by the macro user id, or `None` when the user has/// not linked GitHub.fn get_github_link_by_user_id<'a>(@@ -53,6 +70,15 @@ pub trait GithubRepo: Send + Sync + 'static {link: &GithubLink,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Repoints links sharing a missing grant after OAuth proves ownership of that GitHub account.+ /// Only links still referencing `previous_owner` are changed.+ fn reassign_github_grant(+ &self,+ github_user_id: &str,+ previous_owner: &uuid::Uuid,+ new_owner: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// deletes the in progress user linkfn delete_in_progress_user_link(&self,@@ -161,7 +187,7 @@ pub trait Auth: Send + Sync + 'static {/// The error type returned by repository operations.type Err: Into<anyhow::Error> + Send + std::fmt::Debug;- /// Links the github account to the auth user+ /// Creates or refreshes the grant after OAuth has verified the GitHub account.fn link_user(&self,fusionauth_user_id: &uuid::Uuid,@@ -169,7 +195,7 @@ pub trait Auth: Send + Sync + 'static {github_user_id: &str,username: &str,access_token: &str,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<GithubGrantLinkOutcome, Self::Err>> + Send;/// Deletes the github link for a auth userfn delete_user_link(@@ -178,12 +204,13 @@ pub trait Auth: Send + Sync + 'static {github_idp_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Retreives the users github access token+ /// Retrieves the GitHub token, or `None` if the identity or grant no longer exists.fn retreive_access_token(&self,fusionauth_user_id: &uuid::Uuid,github_idp_id: &str,- ) -> impl Future<Output = Result<GithubAccessToken, Self::Err>> + Send;+ github_user_id: &str,+ ) -> impl Future<Output = Result<Option<GithubAccessToken>, Self::Err>> + Send;}/// Service interface for github link operations (OAuth and account linking).diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rsindex 06171254e1..ff0533299b 100644--- a/crates/github/src/domain/service/link.rs+++ b/crates/github/src/domain/service/link.rs@@ -9,12 +9,12 @@ use macro_user_id::{use crate::domain::{models::{- EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError, GithubLink,- GithubLinkStatus, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,- GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest,- GithubPullRequestNumber, GithubPullRequestRef, MergeGithubPullRequestRequest,- MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,- SetGithubPullRequestDraftResponse,+ EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError,+ GithubGrantLinkOutcome, GithubLink, GithubLinkStatus, GithubMergeMethod,+ GithubMergeOutcome, GithubMergeRejection, GithubPullRequestMergeabilityEntry,+ GithubPullRequestMergeabilityRequest, GithubPullRequestNumber, GithubPullRequestRef,+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,},ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},};@@ -92,9 +92,14 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>) -> Result<GithubAccessToken, GithubError> {let access_token = self.auth- .retreive_access_token(&link.fusionauth_user_id, &self.config.idp_id)+ .retreive_access_token(+ &link.fusionauth_user_id,+ &self.config.idp_id,+ &link.github_user_id,+ ).await- .map_err(|e| GithubError::Internal(e.into()))?;+ .map_err(|e| GithubError::Internal(e.into()))?+ .ok_or(GithubError::ReauthenticationRequired)?;let token_is_expired = self.oauth@@ -376,11 +381,26 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github&self,macro_user_id: &MacroUserId<Lowercase<'static>>,) -> Result<(), GithubError> {+ let mut user_guard = self+ .repo+ .lock_user_link(macro_user_id.as_ref())+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;let Some(link) = self.find_user_link(macro_user_id).await? else {tracing::trace!("no github link found for user");return Ok(());};+ self.repo+ .lock_github_account(&mut user_guard, &link.github_user_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;+ // A different sharer may have repaired the owner while we waited.+ let link = self+ .find_user_link(macro_user_id)+ .await?+ .ok_or(GithubError::NoLinkFound)?;+// 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.@@ -417,7 +437,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> GithubOk(())}- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, user_id, code, redirect_uri), err)]async fn link_user(&self,user_id: &MacroUserId<Lowercase<'static>>,@@ -443,30 +463,28 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github.await.map_err(|e| GithubError::Internal(e.into()))?;- tracing::trace!(user_info=?user_info, "got user info");+ tracing::trace!(github_user_id = user_info.id, "got github user identity");let gh_id = user_info.id.to_string();+ let mut user_guard = self+ .repo+ .lock_user_link(user_id.as_ref())+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;// 1. Does THIS user already have a link, and to which account?let this_user_link = self.find_user_link(user_id).await?;if let Some(existing) = &this_user_link- && existing.github_user_id == gh_id+ && 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());+ return Err(GithubError::AccountMismatch);}- // 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.repo+ .lock_github_account(&mut user_guard, &gh_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;// 2. Does anyone already OWN this github account? (owner row = earliest row)let account_owner = self.repo@@ -476,17 +494,56 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Githublet 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+ let result = self+ .auth+ .link_user(+ &owner.fusionauth_user_id,+ &self.config.idp_id,+ &gh_id,+ &user_info.login,+ &tokens.access_token,+ )+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;+ if result == GithubGrantLinkOutcome::IdentityMissing {+ // OAuth verified this GitHub account; migrate every sharer+ // only after storing the grant on the current identity.+ let result = 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()))?;+ if result == GithubGrantLinkOutcome::IdentityMissing {+ return Err(GithubError::ReauthenticationRequired);+ }+ self.repo+ .reassign_github_grant(+ &gh_id,+ &owner.fusionauth_user_id,+ fusionauth_user_id,+ )+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;+ }+ // Re-read after compare-and-swap so a concurrent repair cannot leave+ // a new sharer pointing at the grant we originally observed.+ self.repo+ .get_github_link_by_github_user_id(&gh_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?+ .ok_or(GithubError::NoLinkFound)?+ .fusionauth_user_id}None => {// OWNER (first linker): create the FusionAuth IdP link/token as before.- self.auth+ let result = self+ .auth.link_user(fusionauth_user_id,&self.config.idp_id,@@ -497,12 +554,30 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github.await.map_err(|e| GithubError::Internal(e.into()))?;+ if result == GithubGrantLinkOutcome::IdentityMissing {+ return Err(GithubError::ReauthenticationRequired);+ }tracing::trace!("linked auth user");*fusionauth_user_id}};+ if let Some(existing) = this_user_link+ && existing.github_user_id == gh_id+ {+ let link = self+ .find_user_link(user_id)+ .await?+ .ok_or(GithubError::NoLinkFound)?;+ 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(link);+ }+// create github linklet link = GithubLink {id: macro_uuid::generate_uuid_v7(),@@ -517,7 +592,6 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Githubtracing::debug!(fusionauth_user_id=%fusionauth_user_id,github_user_id=%user_info.id,- github_username=%user_info.login,"creating github_links record");diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rsindex fe760cc0d8..f8d3289f05 100644--- a/crates/github/src/domain/service/link_test.rs+++ b/crates/github/src/domain/service/link_test.rs@@ -1,4 +1,5 @@mod lookup;+mod recovery;use std::sync::{Arc, Mutex};use chrono::Utc;@@ -22,12 +23,12 @@ use macro_user_id::{use crate::domain::{models::{EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubAccessToken,- GithubDraftOutcome, GithubError, GithubExchangeTokenResponse, GithubLink,- GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestDetails,- GithubPullRequestMerge, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,- GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestUpdateRejection,- GithubRepositoryMergeSettings, GithubUserInfo, MergeGithubPullRequestRequest,- SetGithubPullRequestDraftRequest,+ GithubDraftOutcome, GithubError, GithubExchangeTokenResponse, GithubGrantLinkOutcome,+ GithubLink, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,+ GithubPullRequestDetails, GithubPullRequestMerge, GithubPullRequestMergeability,+ GithubPullRequestMergeabilityEntry, GithubPullRequestNumber, GithubPullRequestRef,+ GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings, GithubUserInfo,+ MergeGithubPullRequestRequest, SetGithubPullRequestDraftRequest,},ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},};@@ -36,6 +37,7 @@ use super::{GithubLinkConfig, GithubLinkServiceImpl};#[derive(Clone)]struct StubGithubRepo {+ account_lock: Arc<tokio::sync::Mutex<()>>,state: Arc<Mutex<StubGithubRepoState>>,}@@ -68,6 +70,7 @@ impl StubGithubRepo {fn new(state: StubGithubRepoState) -> Self {Self {state: Arc::new(Mutex::new(state)),+ account_lock: Arc::new(tokio::sync::Mutex::new(())),}}@@ -112,6 +115,19 @@ impl StubGithubRepo {impl GithubRepo for StubGithubRepo {type Err = anyhow::Error;+ type LinkGuard = Option<tokio::sync::OwnedMutexGuard<()>>;++ async fn lock_user_link(&self, _user_id: &str) -> Result<Self::LinkGuard, Self::Err> {+ Ok(None)+ }+ async fn lock_github_account(+ &self,+ guard: &mut Self::LinkGuard,+ _github_user_id: &str,+ ) -> Result<(), Self::Err> {+ *guard = Some(self.account_lock.clone().lock_owned().await);+ Ok(())+ }async fn get_github_link_by_user_id<'a>(&self,@@ -143,6 +159,26 @@ impl GithubRepo for StubGithubRepo {Ok(())}+ async fn reassign_github_grant(+ &self,+ github_user_id: &str,+ previous_owner: &uuid::Uuid,+ new_owner: &uuid::Uuid,+ ) -> Result<(), Self::Err> {+ let mut state = self.state.lock().unwrap();+ for link in [&mut state.link_by_user_id].into_iter().flatten() {+ if link.github_user_id == github_user_id && link.fusionauth_user_id == *previous_owner {+ link.fusionauth_user_id = *new_owner;+ }+ }+ if let Some(link) = &mut state.link_by_github_user_id {+ if link.github_user_id == github_user_id && link.fusionauth_user_id == *previous_owner {+ link.fusionauth_user_id = *new_owner;+ }+ }+ Ok(())+ }+async fn delete_in_progress_user_link(&self,_in_progress_link_id: &uuid::Uuid,@@ -463,6 +499,11 @@ struct StubAuthState {link_user_calls: u32,delete_user_link_calls: u32,access_token_error: Option<String>,+ missing_access_token: bool,+ missing_identity: Option<uuid::Uuid>,+ link_error: Option<String>,+ linked_identities: Vec<uuid::Uuid>,+ link_barrier: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>)>,}impl StubAuth {@@ -492,14 +533,27 @@ impl Auth for StubAuth {async fn link_user(&self,- _fusionauth_user_id: &uuid::Uuid,+ fusionauth_user_id: &uuid::Uuid,_idp_id: &str,_github_user_id: &str,_username: &str,_access_token: &str,- ) -> Result<(), Self::Err> {- self.state.lock().unwrap().link_user_calls += 1;- Ok(())+ ) -> Result<GithubGrantLinkOutcome, Self::Err> {+ let barrier = self.state.lock().unwrap().link_barrier.take();+ if let Some((started, finish)) = barrier {+ started.notify_one();+ finish.notified().await;+ }+ let mut state = self.state.lock().unwrap();+ state.link_user_calls += 1;+ state.linked_identities.push(*fusionauth_user_id);+ if state.missing_identity == Some(*fusionauth_user_id) {+ return Ok(GithubGrantLinkOutcome::IdentityMissing);+ }+ if let Some(error) = &state.link_error {+ return Err(anyhow::anyhow!(error.clone()));+ }+ Ok(GithubGrantLinkOutcome::Linked)}async fn delete_user_link(@@ -515,11 +569,15 @@ impl Auth for StubAuth {&self,_fusionauth_user_id: &uuid::Uuid,_github_idp_id: &str,- ) -> Result<GithubAccessToken, Self::Err> {+ _github_user_id: &str,+ ) -> Result<Option<GithubAccessToken>, Self::Err> {if let Some(error) = &self.state.lock().unwrap().access_token_error {return Err(anyhow::anyhow!(error.clone()));}- Ok(GithubAccessToken::new(self.access_token.clone()))+ if self.state.lock().unwrap().missing_access_token {+ return Ok(None);+ }+ Ok(Some(GithubAccessToken::new(self.access_token.clone())))}}@@ -1418,7 +1476,7 @@ async fn get_pull_request_mergeability_rejects_too_many_pull_requests() {}#[tokio::test]-async fn link_user_as_sharer_reuses_owner_grant_without_calling_auth() {+async fn link_user_as_sharer_refreshes_owner_grant() {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);@@ -1445,7 +1503,7 @@ async fn link_user_as_sharer_reuses_owner_grant_without_calling_auth() {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!(auth.link_user_calls(), 1);assert_eq!(repo.delete_in_progress_user_link_calls(), 1);}@@ -1454,7 +1512,7 @@ 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 repo = StubGithubRepo::linked(existing.clone()).with_account_owner(existing.clone());let auth = StubAuth::new("valid-token");let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());@@ -1474,7 +1532,7 @@ async fn link_user_idempotent_relink_same_account_skips_insert() {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!(auth.link_user_calls(), 1);assert_eq!(repo.inserted_links().len(), 0);assert_eq!(repo.delete_in_progress_user_link_calls(), 1);}diff --git a/crates/github/src/domain/service/link_test/recovery.rs b/crates/github/src/domain/service/link_test/recovery.rsnew file mode 100644index 0000000000..adc217b5a0--- /dev/null+++ b/crates/github/src/domain/service/link_test/recovery.rs@@ -0,0 +1,235 @@+use super::*;+use crate::domain::models::GithubLinkStatus;++#[tokio::test]+async fn missing_grant_requires_reauthentication_without_calling_github() {+ let user_id = test_user_id();+ let auth = StubAuth::new("unused");+ auth.state.lock().unwrap().missing_access_token = true;+ let oauth = StubGithubOauth::new(false);+ let service = service(+ StubGithubRepo::linked(test_link(&user_id)),+ oauth.clone(),+ auth,+ );++ assert!(matches!(+ service.get_user_link_status(&user_id).await.unwrap(),+ GithubLinkStatus::ReauthenticationRequired+ ));+ assert!(oauth.validated_tokens().is_empty());+}++#[tokio::test]+async fn reconnect_repairs_existing_user_and_shared_owner_after_oauth() {+ let user_id = test_user_id();+ let existing = test_link(&user_id);+ let old_owner = existing.fusionauth_user_id;+ let current_identity = uuid::Uuid::from_u128(42);+ let repo = StubGithubRepo::linked(existing.clone()).with_account_owner(owner_link(old_owner));+ let auth = StubAuth::new("cached-token-from-deleted-identity");+ auth.state.lock().unwrap().missing_identity = Some(old_owner);+ let service = service(repo.clone(), StubGithubOauth::new(false), auth.clone());++ let link = service+ .link_user(+ &user_id,+ ¤t_identity,+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await+ .unwrap();++ assert_eq!(link.id, existing.id);+ assert_eq!(link.fusionauth_user_id, current_identity);+ assert_eq!(+ repo.state+ .lock()+ .unwrap()+ .link_by_github_user_id+ .as_ref()+ .unwrap()+ .fusionauth_user_id,+ current_identity+ );+ assert_eq!(+ auth.state.lock().unwrap().linked_identities,+ vec![old_owner, current_identity]+ );+ assert!(repo.inserted_links().is_empty());+ assert_eq!(repo.delete_github_link_calls(), 0);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 1);+}++#[tokio::test]+async fn new_sharer_repairs_missing_owner_before_inserting() {+ let user_id = test_user_id();+ let old_owner = uuid::Uuid::from_u128(41);+ let current_identity = uuid::Uuid::from_u128(42);+ let repo = StubGithubRepo::unlinked().with_account_owner(owner_link(old_owner));+ let auth = StubAuth::new("unused");+ auth.state.lock().unwrap().missing_identity = Some(old_owner);+ let service = service(repo.clone(), StubGithubOauth::new(false), auth);++ let link = service+ .link_user(+ &user_id,+ ¤t_identity,+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await+ .unwrap();++ assert_eq!(link.fusionauth_user_id, current_identity);+ assert_eq!(+ repo.inserted_links()[0].fusionauth_user_id,+ current_identity+ );+ assert_eq!(+ repo.state+ .lock()+ .unwrap()+ .link_by_github_user_id+ .as_ref()+ .unwrap()+ .fusionauth_user_id,+ current_identity+ );+}++#[tokio::test]+async fn failed_repair_preserves_links_and_pending_oauth() {+ let user_id = test_user_id();+ let existing = test_link(&user_id);+ let repo = StubGithubRepo::linked(existing.clone()).with_account_owner(existing.clone());+ let auth = StubAuth::new("unused");+ {+ let mut state = auth.state.lock().unwrap();+ state.missing_identity = Some(existing.fusionauth_user_id);+ state.link_error = Some("FusionAuth unavailable".into());+ }+ let service = service(repo.clone(), StubGithubOauth::new(false), auth);++ let result = service+ .link_user(+ &user_id,+ &uuid::Uuid::from_u128(42),+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await;++ assert!(matches!(result, Err(GithubError::Internal(_))));+ assert_eq!(+ repo.state+ .lock()+ .unwrap()+ .link_by_user_id+ .as_ref()+ .unwrap()+ .fusionauth_user_id,+ existing.fusionauth_user_id+ );+ assert!(repo.inserted_links().is_empty());+ assert_eq!(repo.delete_github_link_calls(), 0);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 0);+}++#[tokio::test]+async fn reconnect_with_different_account_preserves_existing_connection() {+ let user_id = test_user_id();+ let mut existing = test_link(&user_id);+ existing.github_user_id = "different-account".into();+ 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(42),+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await;++ assert!(matches!(result, Err(GithubError::AccountMismatch)));+ assert_eq!(auth.link_user_calls(), 0);+ assert_eq!(auth.delete_user_link_calls(), 0);+ assert_eq!(repo.delete_github_link_calls(), 0);+ assert!(repo.inserted_links().is_empty());+}++#[tokio::test]+async fn reconnect_serializes_another_refresh_and_disconnect_until_grant_is_stored() {+ for disconnect in [false, true] {+ let user_id = test_user_id();+ let existing = test_link(&user_id);+ let repo = StubGithubRepo::linked(existing.clone()).with_account_owner(existing.clone());+ let auth = StubAuth::new("valid-token");+ let started = Arc::new(tokio::sync::Notify::new());+ let finish = Arc::new(tokio::sync::Notify::new());+ auth.state.lock().unwrap().link_barrier = Some((started.clone(), finish.clone()));+ let service = Arc::new(service(+ repo.clone(),+ StubGithubOauth::new(false),+ auth.clone(),+ ));+ let first = tokio::spawn({+ let service = service.clone();+ let user_id = user_id.clone();+ async move {+ service+ .link_user(+ &user_id,+ &uuid::Uuid::nil(),+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await+ }+ });+ started.notified().await;+ let other_user = MacroUserIdStr::try_from_email("[email protected]")+ .unwrap()+ .0;+ let mut second = Box::pin(async {+ if disconnect {+ service.delete_user_link(&other_user).await+ } else {+ service+ .link_user(+ &other_user,+ &uuid::Uuid::nil(),+ &uuid::Uuid::nil(),+ "https://redirect.example",+ "code",+ )+ .await+ .map(|_| ())+ }+ });+ // Poll the competing operation while the first grant write is blocked.+ std::future::poll_fn(|cx| {+ assert!(std::future::Future::poll(second.as_mut(), cx).is_pending());+ std::task::Poll::Ready(())+ })+ .await;+ assert_eq!(auth.link_user_calls(), 0);+ assert_eq!(auth.delete_user_link_calls(), 0);+ assert_eq!(repo.delete_in_progress_user_link_calls(), 0);++ finish.notify_one();+ first.await.unwrap().unwrap();+ second.await.unwrap();+ assert_eq!(auth.link_user_calls(), if disconnect { 1 } else { 2 });+ assert_eq!(auth.delete_user_link_calls(), u32::from(disconnect));+ }+}diff --git a/crates/github/src/inbound.rs b/crates/github/src/inbound.rsindex 528d48b27e..286e61552e 100644--- a/crates/github/src/inbound.rs+++ b/crates/github/src/inbound.rs@@ -22,6 +22,10 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {StatusCode::PRECONDITION_REQUIRED,"ReauthenticationRequired".into(),),+ crate::domain::models::GithubError::AccountMismatch => (+ StatusCode::CONFLICT,+ "Disconnect the current GitHub account before linking a different account.".into(),+ ),crate::domain::models::GithubError::NoRefreshTokenProvided => (StatusCode::UNPROCESSABLE_ENTITY,"no refresh token was provided".into(),diff --git a/crates/github/src/outbound/github_auth_client.rs b/crates/github/src/outbound/github_auth_client.rsindex 82715f935a..9844ad31d6 100644--- a/crates/github/src/outbound/github_auth_client.rs+++ b/crates/github/src/outbound/github_auth_client.rs@@ -1,6 +1,5 @@//! Github FusionAuth implementation of the [`Auth`] port.-use anyhow::Context;use fusionauth::{FusionAuthClient,error::FusionAuthClientError,@@ -10,7 +9,7 @@ use redis::AsyncCommands;use redis::aio::MultiplexedConnection;use crate::domain::{- models::{GithubAccessToken, GithubLink},+ models::{GithubAccessToken, GithubGrantLinkOutcome, GithubLink},ports::Auth,};@@ -19,8 +18,11 @@ const TTL_SECONDS: u64 = 60 * 60 * 24;/// Generates the key for the github access token in redismacro_rules! github_access_token_key {- ($fusionauth_user_id:expr) => {- format!("github_access_token_key:{}", $fusionauth_user_id)+ ($fusionauth_user_id:expr, $github_user_id:expr) => {+ format!(+ "github_access_token_key:{}:{}",+ $fusionauth_user_id, $github_user_id+ )};}@@ -45,8 +47,9 @@ impl GithubAuthImpl {async fn clear_access_token_cache(&self,fusionauth_user_id: &uuid::Uuid,+ github_user_id: &str,) -> Result<(), anyhow::Error> {- let key = github_access_token_key!(fusionauth_user_id);+ let key = github_access_token_key!(fusionauth_user_id, github_user_id);let mut conn = self.conn.clone();conn.del::<&str, ()>(&key).await?;Ok(())@@ -56,7 +59,7 @@ impl GithubAuthImpl {impl Auth for GithubAuthImpl {type Err = anyhow::Error;- #[tracing::instrument(skip(self), err)]+ #[tracing::instrument(skip(self, username, access_token), err)]async fn link_user(&self,fusionauth_user_id: &uuid::Uuid,@@ -64,33 +67,29 @@ impl Auth for GithubAuthImpl {github_user_id: &str,username: &str,access_token: &str,- ) -> Result<(), Self::Err> {- match self- .fusionauth_client- .link_user(LinkUserRequest {- identity_provider_link: IdentityProviderLink {- display_name: username.into(),- identity_provider_id: idp_id.into(),- identity_provider_user_id: github_user_id.into(),- user_id: fusionauth_user_id.to_string().into(),- token: access_token.into(),- },- })- .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()),+ ) -> Result<GithubGrantLinkOutcome, Self::Err> {+ self.clear_access_token_cache(fusionauth_user_id, github_user_id)+ .await?;+ let result = refresh_grant(+ &self.fusionauth_client,+ fusionauth_user_id,+ idp_id,+ github_user_id,+ username,+ access_token,+ )+ .await;+ if matches!(&result, Ok(GithubGrantLinkOutcome::Linked)) {+ let key = github_access_token_key!(fusionauth_user_id, github_user_id);+ self.conn+ .clone()+ .set_ex::<&str, &str, ()>(&key, access_token, TTL_SECONDS)+ .await?;+ } else {+ self.clear_access_token_cache(fusionauth_user_id, github_user_id)+ .await?;}-- self.clear_access_token_cache(fusionauth_user_id).await?;-- Ok(())+ result}#[tracing::instrument(skip(self), err)]@@ -98,34 +97,58 @@ impl Auth for GithubAuthImpl {&self,fusionauth_user_id: &uuid::Uuid,github_idp_id: &str,- ) -> Result<GithubAccessToken, Self::Err> {- let key = github_access_token_key!(fusionauth_user_id);+ github_user_id: &str,+ ) -> Result<Option<GithubAccessToken>, Self::Err> {+ let key = github_access_token_key!(fusionauth_user_id, github_user_id);let mut conn = self.conn.clone();if let Some(access_token) = conn.get::<&str, Option<String>>(&key).await? {conn.expire::<&str, ()>(&key, TTL_SECONDS as i64).await?;- return Ok(GithubAccessToken::new(access_token));+ return Ok(Some(GithubAccessToken::new(access_token)));}- let links = self+ let links = match self.fusionauth_client.get_links(&fusionauth_user_id.to_string(),Some(github_idp_id.to_string()),)+ .await+ {+ Ok(links) => links,+ Err(+ FusionAuthClientError::UserDoesNotExist+ | FusionAuthClientError::NoIdentityProviderFound,+ ) => return Ok(None),+ Err(error) => return Err(error.into()),+ };++ // An identity may retain another account's grant for its remaining sharers.+ let Some(link) = links+ .iter()+ .find(|link| link.identity_provider_user_id == github_user_id)+ else {+ return Ok(None);+ };++ // A lookup that started before reconnect must not overwrite its fresh+ // token. If another writer won, return that token instead of our snapshot.+ let inserted: Option<String> = redis::cmd("SET")+ .arg(&key)+ .arg(&link.token)+ .arg("EX")+ .arg(TTL_SECONDS)+ .arg("NX")+ .query_async(&mut conn).await?;-- if links.is_empty() {- anyhow::bail!("user does not have a github link")- }-- // 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)- .await?;-- Ok(GithubAccessToken::new(link.token.clone()))+ let token = if inserted.is_none() {+ conn.get::<&str, Option<String>>(&key)+ .await?+ .unwrap_or_else(|| link.token.clone())+ } else {+ link.token.clone()+ };+ Ok(Some(GithubAccessToken::new(token)))}#[tracing::instrument(skip(self), err)]@@ -143,12 +166,83 @@ impl Auth for GithubAuthImpl {).await{- Ok(()) | Err(FusionAuthClientError::NoIdentityProviderFound) => {- self.clear_access_token_cache(&github_link.fusionauth_user_id)- .await?;+ Ok(())+ | Err(+ FusionAuthClientError::NoIdentityProviderFound+ | FusionAuthClientError::UserDoesNotExist,+ ) => {+ self.clear_access_token_cache(+ &github_link.fusionauth_user_id,+ &github_link.github_user_id,+ )+ .await?;Ok(())}Err(e) => Err(e.into()),}}}++/// Called while the domain service holds the shared GitHub account lock.+#[tracing::instrument(skip(fusionauth_client, username, access_token), err)]+async fn refresh_grant(+ fusionauth_client: &FusionAuthClient,+ fusionauth_user_id: &uuid::Uuid,+ idp_id: &str,+ github_user_id: &str,+ username: &str,+ access_token: &str,+) -> Result<GithubGrantLinkOutcome, anyhow::Error> {+ // Read FusionAuth directly: a cached token can outlive its identity.+ let links = match fusionauth_client+ .get_links(&fusionauth_user_id.to_string(), Some(idp_id.to_string()))+ .await+ {+ Ok(links) => links,+ Err(FusionAuthClientError::UserDoesNotExist) => {+ return Ok(GithubGrantLinkOutcome::IdentityMissing);+ }+ Err(FusionAuthClientError::NoIdentityProviderFound) => Vec::new(),+ Err(error) => return Err(error.into()),+ };+ let existing = links+ .iter()+ .find(|link| link.identity_provider_user_id == github_user_id);+ if existing.is_some_and(|link| link.token == access_token) {+ return Ok(GithubGrantLinkOutcome::Linked);+ }+ let request = |token: String| LinkUserRequest {+ identity_provider_link: IdentityProviderLink {+ display_name: username.into(),+ identity_provider_id: idp_id.into(),+ identity_provider_user_id: github_user_id.into(),+ user_id: fusionauth_user_id.to_string().into(),+ token: token.into(),+ },+ };+ if existing.is_some() {+ fusionauth_client+ .unlink_user(&fusionauth_user_id.to_string(), idp_id, github_user_id)+ .await?;+ }+ if let Err(error) = fusionauth_client+ .link_user(request(access_token.to_string()))+ .await+ {+ if let Some(existing) = existing {+ // FusionAuth has no update-link API. Restore the old grant if the+ // replacement fails, retaining the original error for the caller.+ if let Err(rollback_error) = fusionauth_client+ .link_user(request(existing.token.clone()))+ .await+ {+ tracing::error!(error=?rollback_error, "unable to restore github grant after failed refresh");+ }+ }+ return Err(error.into());+ }+ Ok(GithubGrantLinkOutcome::Linked)+}++#[cfg(test)]+mod test;diff --git a/crates/github/src/outbound/github_auth_client/test.rs b/crates/github/src/outbound/github_auth_client/test.rsnew file mode 100644index 0000000000..c883bfa142--- /dev/null+++ b/crates/github/src/outbound/github_auth_client/test.rs@@ -0,0 +1,314 @@+use super::*;+use serde_json::json;+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{body_partial_json, method, path},+};++fn client(server: &MockServer) -> FusionAuthClient {+ FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ server.uri(),+ "http://localhost/callback".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ )+}++fn grant(account: &str, token: &str) -> serde_json::Value {+ json!({+ "displayName": "octocat", "identityProviderId": "github",+ "identityProviderName": "GitHub", "identityProviderType": "GitHub",+ "identityProviderUserId": account, "insertInstant": 0,+ "lastLoginInstant": 0, "tenantId": "tenant", "token": token,+ "userId": uuid::Uuid::nil().to_string()+ })+}++#[tokio::test]+async fn refresh_replaces_the_matching_grant_and_restores_it_on_failure() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/api/identity-provider/link"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "identityProviderLinks": [grant("other", "other-token"), grant("1", "old-token")]+ })))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(wiremock::matchers::query_param(+ "identityProviderUserId",+ "1",+ ))+ .respond_with(ResponseTemplate::new(200))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(body_partial_json(json!({ "identityProviderLink": { "identityProviderUserId": "1", "token": "new-token" } })))+ .respond_with(ResponseTemplate::new(500)).expect(1).mount(&server).await;+ Mock::given(method("POST"))+ .and(body_partial_json(json!({ "identityProviderLink": { "identityProviderUserId": "1", "token": "old-token" } })))+ .respond_with(ResponseTemplate::new(200)).expect(1).mount(&server).await;++ let result = refresh_grant(+ &client(&server),+ &uuid::Uuid::nil(),+ "github",+ "1",+ "octocat",+ "new-token",+ )+ .await;++ assert!(result.is_err());+ let requests = server.received_requests().await.unwrap();+ assert_eq!(+ requests+ .iter()+ .map(|request| request.method.as_str())+ .collect::<Vec<_>>(),+ ["GET", "DELETE", "POST", "POST"]+ );+}++#[tokio::test]+async fn refresh_stores_fresh_token_and_identical_token_is_idempotent() {+ for old_token in ["old-token", "new-token"] {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(json!({ "identityProviderLinks": [grant("1", old_token)] })),+ )+ .expect(1)+ .mount(&server)+ .await;+ let writes = u64::from(old_token != "new-token");+ Mock::given(method("DELETE"))+ .respond_with(ResponseTemplate::new(200))+ .expect(writes)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(body_partial_json(+ json!({ "identityProviderLink": { "token": "new-token" } }),+ ))+ .respond_with(ResponseTemplate::new(200))+ .expect(writes)+ .mount(&server)+ .await;++ assert_eq!(+ refresh_grant(+ &client(&server),+ &uuid::Uuid::nil(),+ "github",+ "1",+ "octocat",+ "new-token"+ )+ .await+ .unwrap(),+ GithubGrantLinkOutcome::Linked+ );+ }+}++#[tokio::test]+async fn reconnect_recreates_a_grant_after_replacement_and_restoration_fail() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "identityProviderLinks": [grant("1", "old-token")]+ })))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .respond_with(ResponseTemplate::new(200))+ .expect(1)+ .mount(&server)+ .await;+ // Both the replacement and its best-effort restoration fail.+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(503))+ .expect(2)+ .mount(&server)+ .await;+ let client = client(&server);+ assert!(+ refresh_grant(+ &client,+ &uuid::Uuid::nil(),+ "github",+ "1",+ "octocat",+ "new-token"+ )+ .await+ .is_err()+ );+ server.verify().await;+ server.reset().await;++ // A crash after unlink leaves the same persistent state: an absent grant.+ // A subsequent verified OAuth attempt must recreate it without an unlink.+ Mock::given(method("GET"))+ .respond_with(ResponseTemplate::new(404))+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(body_partial_json(json!({+ "identityProviderLink": { "identityProviderUserId": "1", "token": "retry-token" }+ })))+ .respond_with(ResponseTemplate::new(200))+ .expect(1)+ .mount(&server)+ .await;+ assert_eq!(+ refresh_grant(+ &client,+ &uuid::Uuid::nil(),+ "github",+ "1",+ "octocat",+ "retry-token"+ )+ .await+ .unwrap(),+ GithubGrantLinkOutcome::Linked+ );+ let requests = server.received_requests().await.unwrap();+ assert_eq!(+ requests+ .iter()+ .map(|request| request.method.as_str())+ .collect::<Vec<_>>(),+ ["GET", "POST"]+ );+}++#[tokio::test]+async fn deleted_identity_is_reported_without_writes() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .respond_with(+ ResponseTemplate::new(400).set_body_json(+ json!({ "fieldErrors": { "userId": [{ "code": "[invalid]userId" }] } }),+ ),+ )+ .expect(1)+ .mount(&server)+ .await;++ assert_eq!(+ refresh_grant(+ &client(&server),+ &uuid::Uuid::nil(),+ "github",+ "1",+ "octocat",+ "new-token"+ )+ .await+ .unwrap(),+ GithubGrantLinkOutcome::IdentityMissing+ );+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}++#[tokio::test]+async fn delayed_lookup_cannot_overwrite_reconnected_token() {+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };+ use tokio::sync::Notify;++ let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into());+ let mut conn = redis::Client::open(url)+ .unwrap()+ .get_multiplexed_async_connection()+ .await+ .expect("GitHub integration tests require local Redis or REDIS_URL; see docs/development/database.md");+ let identity = macro_uuid::generate_uuid_v7();+ // Legacy identity-only entries must not be used for another account.+ let legacy_key = format!("github_access_token_key:{identity}");+ conn.set_ex::<_, _, ()>(&legacy_key, "wrong-account-token", 60)+ .await+ .unwrap();+ let requests = Arc::new(AtomicUsize::new(0));+ let started = Arc::new(Notify::new());+ let release = Arc::new(Notify::new());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let router = axum::Router::new().route("/api/identity-provider/link", axum::routing::get({+ let requests = requests.clone();+ let started = started.clone();+ let release = release.clone();+ move || {+ let requests = requests.clone();+ let started = started.clone();+ let release = release.clone();+ async move {+ let snapshot = json!({ "identityProviderLinks": [grant("other", "other-token"), grant("1", "old-token")] });+ if requests.fetch_add(1, Ordering::SeqCst) == 0 {+ started.notify_one();+ release.notified().await;+ }+ axum::Json(snapshot)+ }+ }+ }).delete(|| async { axum::http::StatusCode::OK }).post(|| async { axum::http::StatusCode::OK }));+ let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });+ let fusionauth = FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ format!("http://{address}"),+ "http://localhost/callback".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ );+ let adapter = GithubAuthImpl::new(fusionauth, conn.clone());+ let lookup = tokio::spawn({+ let adapter = adapter.clone();+ async move {+ adapter+ .retreive_access_token(&identity, "github", "1")+ .await+ .unwrap()+ .unwrap()+ }+ });+ started.notified().await;+ assert_eq!(+ adapter+ .link_user(&identity, "github", "1", "octocat", "new-token")+ .await+ .unwrap(),+ GithubGrantLinkOutcome::Linked+ );+ release.notify_one();++ assert_eq!(lookup.await.unwrap().as_str(), "new-token");+ assert_eq!(+ adapter+ .retreive_access_token(&identity, "github", "1")+ .await+ .unwrap()+ .unwrap()+ .as_str(),+ "new-token"+ );+ assert_eq!(requests.load(Ordering::SeqCst), 2);+ conn.del::<_, ()>(&[legacy_key, github_access_token_key!(identity, "1")])+ .await+ .unwrap();+ server.abort();+}diff --git a/crates/github/src/outbound/pg_github_repo.rs b/crates/github/src/outbound/pg_github_repo.rsindex c7119c3d40..9460fea3cf 100644--- a/crates/github/src/outbound/pg_github_repo.rs+++ b/crates/github/src/outbound/pg_github_repo.rs@@ -9,6 +9,7 @@ use macro_user_id::{user_id::{MacroUserId, MacroUserIdStr},};use sqlx::PgPool;+use std::time::Duration;use uuid::Uuid;use crate::domain::{models::GithubLink, ports::GithubRepo};@@ -17,17 +18,57 @@ use crate::domain::{models::GithubLink, ports::GithubRepo};#[derive(Clone)]pub struct PgGithubRepo {pool: PgPool,+ locks: PgPool,}impl PgGithubRepo {/// Create a new repository backed by the given connection pool.pub fn new(pool: PgPool) -> Self {- Self { pool }+ // Locks span external HTTP calls; keep waiters out of the data pool.+ let locks = sqlx::postgres::PgPoolOptions::new()+ .max_connections(5)+ .acquire_timeout(Duration::from_secs(5))+ .connect_lazy_with(+ (*pool.connect_options())+ .clone()+ .options([("lock_timeout", "5s"), ("statement_timeout", "10s")]),+ );+ Self { locks, pool }+ }++ async fn lock(+ pool: &PgPool,+ key: &str,+ ) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, sqlx::Error> {+ let mut guard = pool.begin().await?;+ sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key)+ .execute(&mut *guard)+ .await?;+ Ok(guard)}}impl GithubRepo for PgGithubRepo {type Err = sqlx::Error;+ type LinkGuard = sqlx::Transaction<'static, sqlx::Postgres>;++ #[tracing::instrument(skip(self, user_id), err)]+ async fn lock_user_link(&self, user_id: &str) -> Result<Self::LinkGuard, Self::Err> {+ Self::lock(&self.locks, &format!("github-link-user:{user_id}")).await+ }++ #[tracing::instrument(skip(self, guard), err)]+ async fn lock_github_account(+ &self,+ guard: &mut Self::LinkGuard,+ github_user_id: &str,+ ) -> Result<(), Self::Err> {+ let key = format!("github-link-account:{github_user_id}");+ sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key)+ .execute(&mut **guard)+ .await?;+ Ok(())+ }#[tracing::instrument(skip(self), err)]async fn get_github_link_by_user_id<'a>(@@ -157,6 +198,28 @@ impl GithubRepo for PgGithubRepo {Ok(())}+ #[tracing::instrument(skip(self), err)]+ async fn reassign_github_grant(+ &self,+ github_user_id: &str,+ previous_owner: &uuid::Uuid,+ new_owner: &uuid::Uuid,+ ) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ UPDATE github_links+ SET fusionauth_user_id = $3, updated_at = NOW()+ WHERE github_user_id = $1 AND fusionauth_user_id = $2+ "#,+ github_user_id,+ previous_owner,+ new_owner,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn delete_in_progress_user_link(&self,diff --git a/crates/github/src/outbound/pg_github_repo/test.rs b/crates/github/src/outbound/pg_github_repo/test.rsindex 6cecb8c6eb..55b72cf4e5 100644--- a/crates/github/src/outbound/pg_github_repo/test.rs+++ b/crates/github/src/outbound/pg_github_repo/test.rs@@ -319,3 +319,144 @@ async fn test_delete_in_progress_user_link_nonexistent(pool: Pool<Postgres>) {// Deleting a nonexistent row should not error (DELETE affects 0 rows)repo.delete_in_progress_user_link(&id).await.unwrap();}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_test_data"))+)]+async fn reassign_grant_moves_all_sharers_without_overwriting_other_accounts_or_repairs(+ pool: Pool<Postgres>,+) {+ let repo = PgGithubRepo::new(pool);+ let original = repo+ .get_github_link_by_github_user_id("12345")+ .await+ .unwrap()+ .unwrap();+ let old_owner = original.fusionauth_user_id;+ let new_owner = uuid::Uuid::from_u128(42);+ let mut sharer = original.clone();+ sharer.id = uuid::Uuid::from_u128(43);+ sharer.macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.insert_github_link(&sharer).await.unwrap();+ let mut unrelated = original.clone();+ unrelated.id = uuid::Uuid::from_u128(44);+ unrelated.github_user_id = "67890".into();+ repo.insert_github_link(&unrelated).await.unwrap();++ repo.reassign_github_grant("12345", &old_owner, &new_owner)+ .await+ .unwrap();+ // A late repair based on the former owner must not undo the completed repair.+ repo.reassign_github_grant("12345", &old_owner, &uuid::Uuid::from_u128(45))+ .await+ .unwrap();++ assert_eq!(+ repo.get_github_link_by_id(&original.id)+ .await+ .unwrap()+ .fusionauth_user_id,+ new_owner+ );+ assert_eq!(+ repo.get_github_link_by_id(&sharer.id)+ .await+ .unwrap()+ .fusionauth_user_id,+ new_owner+ );+ assert_eq!(+ repo.get_github_link_by_id(&unrelated.id)+ .await+ .unwrap()+ .fusionauth_user_id,+ old_owner+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn link_guard_holds_user_and_shared_account_locks_until_operation_finishes(+ pool: Pool<Postgres>,+) {+ let repo = PgGithubRepo::new(pool.clone());+ let mut guard = repo.lock_user_link("macro|[email protected]").await.unwrap();+ repo.lock_github_account(&mut guard, "1").await.unwrap();+ let mut other = pool.begin().await.unwrap();+ for key in [+ "github-link-user:macro|[email protected]",+ "github-link-account:1",+ ] {+ let locked = sqlx::query_scalar!(+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS "locked!""#,+ key+ )+ .fetch_one(&mut *other)+ .await+ .unwrap();+ assert!(!locked);+ }+ guard.rollback().await.unwrap();+ for key in [+ "github-link-user:macro|[email protected]",+ "github-link-account:1",+ ] {+ let locked = sqlx::query_scalar!(+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS "locked!""#,+ key+ )+ .fetch_one(&mut *other)+ .await+ .unwrap();+ assert!(locked);+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn contended_link_locks_time_out_and_release_the_waiters_user_lock(pool: Pool<Postgres>) {+ let repo = PgGithubRepo::new(pool);+ let mut owner = repo+ .lock_user_link("macro|[email protected]")+ .await+ .unwrap();+ repo.lock_github_account(&mut owner, "1").await.unwrap();++ let user_error = tokio::time::timeout(+ std::time::Duration::from_secs(15),+ repo.lock_user_link("macro|[email protected]"),+ )+ .await+ .expect("user lock wait must be bounded")+ .unwrap_err();+ assert_eq!(+ user_error.as_database_error().unwrap().code().as_deref(),+ Some("55P03")+ );++ let mut waiter = repo+ .lock_user_link("macro|[email protected]")+ .await+ .unwrap();+ let account_error = tokio::time::timeout(+ std::time::Duration::from_secs(15),+ repo.lock_github_account(&mut waiter, "1"),+ )+ .await+ .expect("account lock wait must be bounded")+ .unwrap_err();+ assert_eq!(+ account_error.as_database_error().unwrap().code().as_deref(),+ Some("55P03")+ );+ drop(waiter);+ // The failed transaction must not leave the waiter's user lock behind.+ let recovered = repo+ .lock_user_link("macro|[email protected]")+ .await+ .unwrap();+ recovered.rollback().await.unwrap();+ owner.rollback().await.unwrap();+ repo.locks.close().await;+}diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex ecf64d4504..7a2fc4b86b 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -551,3 +551,17 @@ OAuth token.The Codex section and its auth/config requests were exercised in Chromium withmocked backend responses on 2026-09-15. Provider login and a full deployed Macrosession were not exercised by that UI check.++### GitHub reconnect recovery++When GitHub reports that reauthentication is required, reconnect starts OAuth+without first deleting the current Macro link. Cancelling OAuth preserves it.+Selecting a different GitHub account fails without changing the connection; use+Disconnect first to switch accounts.+A successful callback refreshes the grant; if its old FusionAuth identity was+deleted, all Macro accounts sharing that GitHub account move to the new grant.+Verify reconnect both as the original linker and as another sharing account,+and verify an upstream outage leaves the current links intact and reports an error.+The Macro link survives a failed reconnect, but replacing the FusionAuth grant+is not atomic. A crash or failed restoration may leave it missing; retry OAuth+to recreate it after the provider recovers.diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex 2789e6d60d..8633742263 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -78,6 +78,11 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed## Gotchas+- GitHub reconnect preserves the current link until OAuth completes. A different+ account returns 409; disconnect first to switch accounts. Missing grants report+ reauthentication, while infrastructure failures remain server errors.+ Deploy grant-refresh support before releasing clients that omit the pre-OAuth+ disconnect; older callbacks leave an existing grant unchanged.- The signup allowlist has a temporary Develop-only bypass(`DEVELOPMENT_BYPASS_SIGNUP_ALLOWLIST`) that overrides the allowlist evenwhen present; see `README.md` before changing signup behavior.diff --git a/services/authentication_service/src/api/oauth2/github.rs b/services/authentication_service/src/api/oauth2/github.rsindex c3f4afadc6..5d0625fd6d 100644--- a/services/authentication_service/src/api/oauth2/github.rs+++ b/services/authentication_service/src/api/oauth2/github.rs@@ -39,6 +39,10 @@ impl IntoResponse for GithubLinkError {StatusCode::PRECONDITION_REQUIRED,REAUTHENTICATION_REQUIRED_MESSAGE,),+ GithubLinkError::GithubServiceError(GithubError::AccountMismatch) => (+ StatusCode::CONFLICT,+ "Disconnect the current GitHub account before linking a different account.",+ ),GithubLinkError::InternalError(error) => {tracing::error!(error=?error, "internal error occurred while linking github account");(StatusCode::INTERNAL_SERVER_ERROR, "internal error occurred")