Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(github): treat a missing GitHub link as a status, not an error (#7888)

teobd5a56a577e7
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index 74f627e5c5..f936814108 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -30,7 +30,9 @@ pub use github_pull_requests::domain::models::{
pub use installation_state::{
InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,
};
-pub use link::{GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubUserInfo};
+pub use link::{
+ GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubLinkStatus, GithubUserInfo,
+};
pub use repository::{GithubRepository, PullRequestIndexPage, PullRequestIndexRequest};
pub use sync::{
GithubAppInstallationSource, GithubAuthenticatedUser, GithubInstallationAccessToken,
diff --git a/crates/github/src/domain/models/link.rs b/crates/github/src/domain/models/link.rs
index b72b54f663..3aa29c3312 100644
--- a/crates/github/src/domain/models/link.rs
+++ b/crates/github/src/domain/models/link.rs
@@ -45,6 +45,17 @@ pub struct GithubLink {
pub updated_at: chrono::DateTime<chrono::Utc>,
}
+/// Whether a user's GitHub link can be used.
+#[derive(Debug, Clone)]
+pub enum GithubLinkStatus {
+ /// The user has not linked a GitHub account.
+ NotLinked,
+ /// The user linked a GitHub account, but its token no longer works.
+ ReauthenticationRequired,
+ /// The user's GitHub link has a working token.
+ Linked(GithubLink),
+}
+
/// GitHub OAuth token exchange response
#[derive(Debug, Deserialize)]
pub struct GithubExchangeTokenResponse {
diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rs
index 5b06147947..f06795f39c 100644
--- a/crates/github/src/domain/ports/link.rs
+++ b/crates/github/src/domain/ports/link.rs
@@ -4,9 +4,9 @@ use std::future::Future;
use crate::domain::models::{
EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError,
- GithubExchangeTokenResponse, GithubLink, GithubMergeMethod, GithubMergeOutcome,
- GithubPullRequestDetails, GithubPullRequestMergeabilityEntry, GithubPullRequestNumber,
- GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
+ GithubExchangeTokenResponse, GithubLink, GithubLinkStatus, GithubMergeMethod,
+ GithubMergeOutcome, GithubPullRequestDetails, GithubPullRequestMergeabilityEntry,
+ GithubPullRequestNumber, GithubPullRequestRef, GithubRepositoryMergeSettings, GithubUserInfo,
MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,
SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,
};
@@ -21,17 +21,19 @@ pub trait GithubRepo: Send + Sync + 'static {
/// The error type returned by repository operations.
type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
- /// Gets the github link by the macro user id
+ /// 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>(
&self,
macro_user_id: &MacroUserId<Lowercase<'a>>,
- ) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<GithubLink>, Self::Err>> + Send;
- /// Gets the github link by the github user id
+ /// Gets the owner's github link for the github user id, or `None` when no
+ /// Macro user has linked that GitHub account.
fn get_github_link_by_github_user_id(
&self,
github_user_id: &str,
- ) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<GithubLink>, Self::Err>> + Send;
/// Counts the number of github links for the given github user id
fn count_github_links_by_github_user_id(
@@ -204,23 +206,18 @@ pub trait GithubLinkService: Send + Sync + 'static {
code: &str,
) -> impl Future<Output = Result<GithubLink, GithubError>> + Send;
- /// Gets a users github link
- fn get_user_link(
- &self,
- user_id: &MacroUserId<Lowercase<'static>>,
- ) -> impl Future<Output = Result<GithubLink, GithubError>> + Send;
-
/// Deletes the link for the user
fn delete_user_link(
&self,
user_id: &MacroUserId<Lowercase<'static>>,
) -> impl Future<Output = Result<(), GithubError>> + Send;
- /// Checks whether the user's Github link token is valid.
- fn check_user_link_token(
+ /// Reports whether the user has linked GitHub and whether the link's
+ /// token still works.
+ fn get_user_link_status(
&self,
user_id: &MacroUserId<Lowercase<'static>>,
- ) -> impl Future<Output = Result<(), GithubError>> + Send;
+ ) -> impl Future<Output = Result<GithubLinkStatus, GithubError>> + Send;
/// Enriches GitHub pull request references with details from the GitHub API.
fn enrich_pull_requests(
diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rs
index d2ea0626ac..06171254e1 100644
--- a/crates/github/src/domain/service/link.rs
+++ b/crates/github/src/domain/service/link.rs
@@ -10,7 +10,7 @@ use macro_user_id::{
use crate::domain::{
models::{
EnrichedGithubPullRequest, GithubAccessToken, GithubDraftOutcome, GithubError, GithubLink,
- GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
+ GithubLinkStatus, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,
GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest,
GithubPullRequestNumber, GithubPullRequestRef, MergeGithubPullRequestRequest,
MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,
@@ -64,32 +64,32 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>
}
}
- fn link_lookup_error(error: R::Err) -> GithubError {
- let error: anyhow::Error = error.into();
-
- if error.to_string().contains("no rows returned") {
- return GithubError::NoLinkFound;
- }
-
- GithubError::Internal(error)
- }
-
- async fn get_user_link_for_validation(
+ async fn find_user_link(
&self,
macro_user_id: &MacroUserId<Lowercase<'static>>,
- ) -> Result<GithubLink, GithubError> {
+ ) -> Result<Option<GithubLink>, GithubError> {
self.repo
.get_github_link_by_user_id(macro_user_id)
.await
- .map_err(Self::link_lookup_error)
+ .map_err(|e| GithubError::Internal(e.into()))
}
async fn validated_access_token(
&self,
macro_user_id: &MacroUserId<Lowercase<'static>>,
) -> Result<GithubAccessToken, GithubError> {
- let link = self.get_user_link_for_validation(macro_user_id).await?;
+ let link = self
+ .find_user_link(macro_user_id)
+ .await?
+ .ok_or(GithubError::NoLinkFound)?;
+
+ self.validated_link_access_token(&link).await
+ }
+ async fn validated_link_access_token(
+ &self,
+ link: &GithubLink,
+ ) -> Result<GithubAccessToken, GithubError> {
let access_token = self
.auth
.retreive_access_token(&link.fusionauth_user_id, &self.config.idp_id)
@@ -205,23 +205,21 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
}
#[tracing::instrument(skip(self), err)]
- async fn get_user_link(
+ async fn get_user_link_status(
&self,
macro_user_id: &MacroUserId<Lowercase<'static>>,
- ) -> Result<GithubLink, GithubError> {
- self.repo
- .get_github_link_by_user_id(macro_user_id)
- .await
- .map_err(Self::link_lookup_error)
- }
+ ) -> Result<GithubLinkStatus, GithubError> {
+ let Some(link) = self.find_user_link(macro_user_id).await? else {
+ return Ok(GithubLinkStatus::NotLinked);
+ };
- #[tracing::instrument(skip(self), err)]
- async fn check_user_link_token(
- &self,
- macro_user_id: &MacroUserId<Lowercase<'static>>,
- ) -> Result<(), GithubError> {
- self.validated_access_token(macro_user_id).await?;
- Ok(())
+ match self.validated_link_access_token(&link).await {
+ Ok(_) => Ok(GithubLinkStatus::Linked(link)),
+ Err(GithubError::ReauthenticationRequired) => {
+ Ok(GithubLinkStatus::ReauthenticationRequired)
+ }
+ Err(error) => Err(error),
+ }
}
#[tracing::instrument(skip(self, pull_requests), err)]
@@ -378,18 +376,9 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
&self,
macro_user_id: &MacroUserId<Lowercase<'static>>,
) -> Result<(), GithubError> {
- // Get link
- let link = match self.repo.get_github_link_by_user_id(macro_user_id).await {
- Ok(link) => link,
- Err(e) => {
- let e: anyhow::Error = e.into();
- if e.to_string().contains("no rows returned") {
- tracing::trace!("no github link found for user");
- return Ok(());
- }
-
- return Err(GithubError::Internal(e));
- }
+ let Some(link) = self.find_user_link(macro_user_id).await? else {
+ tracing::trace!("no github link found for user");
+ return Ok(());
};
// Count how many Macro users share this GitHub account. The FusionAuth
@@ -459,17 +448,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
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 e: anyhow::Error = e.into();
- if e.to_string().contains("no rows returned") {
- None
- } else {
- return Err(GithubError::Internal(e));
- }
- }
- };
+ let this_user_link = self.find_user_link(user_id).await?;
if let Some(existing) = &this_user_link
&& existing.github_user_id == gh_id
@@ -489,17 +468,11 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
// behavior).
// 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));
- }
- }
- };
+ let account_owner = self
+ .repo
+ .get_github_link_by_github_user_id(&gh_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
let row_fusionauth_user_id = match &account_owner {
Some(owner) => {
diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rs
index f6f8d6a6c7..fe760cc0d8 100644
--- a/crates/github/src/domain/service/link_test.rs
+++ b/crates/github/src/domain/service/link_test.rs
@@ -40,9 +40,9 @@ struct StubGithubRepo {
}
struct StubGithubRepoState {
- /// Link returned by `get_github_link_by_user_id` (None → "no rows returned").
+ /// Link returned by `get_github_link_by_user_id`.
link_by_user_id: Option<GithubLink>,
- /// Link returned by `get_github_link_by_github_user_id` (None → "no rows returned").
+ /// Link returned by `get_github_link_by_github_user_id`.
link_by_github_user_id: Option<GithubLink>,
/// Value returned by `count_github_links_by_github_user_id`.
link_count: i64,
@@ -116,25 +116,15 @@ impl GithubRepo for StubGithubRepo {
async fn get_github_link_by_user_id<'a>(
&self,
_macro_user_id: &MacroUserId<Lowercase<'a>>,
- ) -> Result<GithubLink, Self::Err> {
- self.state
- .lock()
- .unwrap()
- .link_by_user_id
- .clone()
- .ok_or_else(|| anyhow::anyhow!("no rows returned"))
+ ) -> Result<Option<GithubLink>, Self::Err> {
+ Ok(self.state.lock().unwrap().link_by_user_id.clone())
}
async fn get_github_link_by_github_user_id(
&self,
_github_user_id: &str,
- ) -> Result<GithubLink, Self::Err> {
- self.state
- .lock()
- .unwrap()
- .link_by_github_user_id
- .clone()
- .ok_or_else(|| anyhow::anyhow!("no rows returned"))
+ ) -> Result<Option<GithubLink>, Self::Err> {
+ Ok(self.state.lock().unwrap().link_by_github_user_id.clone())
}
async fn count_github_links_by_github_user_id(
@@ -472,6 +462,7 @@ struct StubAuth {
struct StubAuthState {
link_user_calls: u32,
delete_user_link_calls: u32,
+ access_token_error: Option<String>,
}
impl StubAuth {
@@ -482,6 +473,11 @@ impl StubAuth {
}
}
+ fn fail_access_token(self, error: &str) -> Self {
+ self.state.lock().unwrap().access_token_error = Some(error.to_string());
+ self
+ }
+
fn link_user_calls(&self) -> u32 {
self.state.lock().unwrap().link_user_calls
}
@@ -520,6 +516,9 @@ impl Auth for StubAuth {
_fusionauth_user_id: &uuid::Uuid,
_github_idp_id: &str,
) -> Result<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()))
}
}
@@ -823,55 +822,7 @@ fn service_with_foreign_entities(
}
#[tokio::test]
-async fn check_user_link_token_accepts_valid_token() {
- let user_id = test_user_id();
- let oauth = StubGithubOauth::new(false);
- let service = service(
- StubGithubRepo::linked(test_link(&user_id)),
- oauth.clone(),
- StubAuth::new("valid-token"),
- );
-
- let result = service.check_user_link_token(&user_id).await;
-
- assert!(result.is_ok());
- assert_eq!(oauth.validated_tokens(), vec!["valid-token".to_string()]);
-}
-
-#[tokio::test]
-async fn check_user_link_token_returns_reauthentication_required_for_expired_token() {
- let user_id = test_user_id();
- let oauth = StubGithubOauth::new(true);
- let service = service(
- StubGithubRepo::linked(test_link(&user_id)),
- oauth.clone(),
- StubAuth::new("expired-token"),
- );
-
- let result = service.check_user_link_token(&user_id).await;
-
- assert!(matches!(result, Err(GithubError::ReauthenticationRequired)));
- assert_eq!(oauth.validated_tokens(), vec!["expired-token".to_string()]);
-}
-
-#[tokio::test]
-async fn check_user_link_token_returns_no_link_found_without_db_link() {
- let user_id = test_user_id();
- let oauth = StubGithubOauth::new(false);
- let service = service(
- StubGithubRepo::unlinked(),
- oauth.clone(),
- StubAuth::new("valid-token"),
- );
-
- let result = service.check_user_link_token(&user_id).await;
-
- assert!(matches!(result, Err(GithubError::NoLinkFound)));
- assert!(oauth.validated_tokens().is_empty());
-}
-
-#[tokio::test]
-async fn check_user_link_token_enrich_pull_requests_reauthenticates_before_details() {
+async fn enrich_pull_requests_reauthenticates_before_details() {
let user_id = test_user_id();
let oauth = StubGithubOauth::new(true);
let service = service(
diff --git a/crates/github/src/domain/service/link_test/lookup.rs b/crates/github/src/domain/service/link_test/lookup.rs
index 24681f4ac8..f5a44fbed6 100644
--- a/crates/github/src/domain/service/link_test/lookup.rs
+++ b/crates/github/src/domain/service/link_test/lookup.rs
@@ -1,49 +1,71 @@
use super::*;
+use crate::domain::models::GithubLinkStatus;
#[tokio::test]
-async fn get_user_link_returns_no_link_found_without_db_link() {
+async fn get_user_link_status_is_not_linked_without_db_link() {
let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false);
let service = service(
StubGithubRepo::unlinked(),
- StubGithubOauth::new(false),
+ oauth.clone(),
StubAuth::new("valid-token"),
);
- assert!(matches!(
- service.get_user_link(&user_id).await,
- Err(GithubError::NoLinkFound)
- ));
+ let status = service.get_user_link_status(&user_id).await.unwrap();
+
+ assert!(matches!(status, GithubLinkStatus::NotLinked));
+ assert!(oauth.validated_tokens().is_empty());
}
#[tokio::test]
-async fn get_user_link_returns_no_link_found_after_concurrent_unlink() {
+async fn get_user_link_status_is_linked_with_valid_token() {
let user_id = test_user_id();
- let repo = StubGithubRepo::linked(test_link(&user_id));
+ let expected = test_link(&user_id);
+ let oauth = StubGithubOauth::new(false);
let service = service(
- repo.clone(),
- StubGithubOauth::new(false),
+ StubGithubRepo::linked(expected.clone()),
+ oauth.clone(),
StubAuth::new("valid-token"),
);
- service.check_user_link_token(&user_id).await.unwrap();
- repo.state.lock().unwrap().link_by_user_id = None;
- assert!(matches!(
- service.get_user_link(&user_id).await,
- Err(GithubError::NoLinkFound)
- ));
+ let status = service.get_user_link_status(&user_id).await.unwrap();
+
+ let GithubLinkStatus::Linked(actual) = status else {
+ panic!("expected a linked status, got {status:?}");
+ };
+ assert_eq!(actual.github_user_id, expected.github_user_id);
+ assert_eq!(actual.github_username, expected.github_username);
+ assert_eq!(oauth.validated_tokens(), vec!["valid-token".to_string()]);
}
#[tokio::test]
-async fn get_user_link_preserves_link_identity() {
+async fn get_user_link_status_requires_reauthentication_for_expired_token() {
let user_id = test_user_id();
- let expected = test_link(&user_id);
+ let oauth = StubGithubOauth::new(true);
let service = service(
- StubGithubRepo::linked(expected.clone()),
- StubGithubOauth::new(false),
- StubAuth::new("valid-token"),
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("expired-token"),
);
- let actual = service.get_user_link(&user_id).await.unwrap();
- assert_eq!(actual.github_user_id, expected.github_user_id);
- assert_eq!(actual.github_username, expected.github_username);
+ let status = service.get_user_link_status(&user_id).await.unwrap();
+
+ assert!(matches!(status, GithubLinkStatus::ReauthenticationRequired));
+ assert_eq!(oauth.validated_tokens(), vec!["expired-token".to_string()]);
+}
+
+#[tokio::test]
+async fn get_user_link_status_surfaces_token_lookup_failures() {
+ let user_id = test_user_id();
+ let oauth = StubGithubOauth::new(false);
+ let service = service(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth.clone(),
+ StubAuth::new("valid-token").fail_access_token("an unknown error occurred"),
+ );
+
+ let result = service.get_user_link_status(&user_id).await;
+
+ assert!(matches!(result, Err(GithubError::Internal(_))));
+ assert!(oauth.validated_tokens().is_empty());
}
diff --git a/crates/github/src/outbound/pg_github_repo.rs b/crates/github/src/outbound/pg_github_repo.rs
index 1de3d02d1c..c7119c3d40 100644
--- a/crates/github/src/outbound/pg_github_repo.rs
+++ b/crates/github/src/outbound/pg_github_repo.rs
@@ -33,8 +33,8 @@ impl GithubRepo for PgGithubRepo {
async fn get_github_link_by_user_id<'a>(
&self,
macro_user_id: &MacroUserId<Lowercase<'a>>,
- ) -> Result<GithubLink, Self::Err> {
- let link = sqlx::query!(
+ ) -> Result<Option<GithubLink>, Self::Err> {
+ sqlx::query!(
r#"
SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
FROM github_links
@@ -54,20 +54,15 @@ impl GithubRepo for PgGithubRepo {
updated_at: r.updated_at,
}))
.fetch_optional(&self.pool)
- .await?;
-
- match link {
- Some(l) => Ok(l),
- None => Err(sqlx::Error::RowNotFound),
- }
+ .await
}
#[tracing::instrument(skip(self), err)]
async fn get_github_link_by_github_user_id(
&self,
github_user_id: &str,
- ) -> Result<GithubLink, Self::Err> {
- let link = sqlx::query!(
+ ) -> Result<Option<GithubLink>, Self::Err> {
+ sqlx::query!(
r#"
SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
FROM github_links
@@ -89,12 +84,7 @@ impl GithubRepo for PgGithubRepo {
updated_at: r.updated_at,
}))
.fetch_optional(&self.pool)
- .await?;
-
- match link {
- Some(l) => Ok(l),
- None => Err(sqlx::Error::RowNotFound),
- }
+ .await
}
#[tracing::instrument(skip(self), err)]
diff --git a/crates/github/src/outbound/pg_github_repo/test.rs b/crates/github/src/outbound/pg_github_repo/test.rs
index a000774757..6cecb8c6eb 100644
--- a/crates/github/src/outbound/pg_github_repo/test.rs
+++ b/crates/github/src/outbound/pg_github_repo/test.rs
@@ -16,7 +16,11 @@ async fn test_get_github_link_by_user_id(pool: Pool<Postgres>) {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
- let link = repo.get_github_link_by_user_id(&user_id.0).await.unwrap();
+ let link = repo
+ .get_github_link_by_user_id(&user_id.0)
+ .await
+ .unwrap()
+ .expect("fixture user has a github link");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
@@ -39,7 +43,7 @@ async fn test_get_github_link_by_user_id_not_found(pool: Pool<Postgres>) {
.into_owned();
let result = repo.get_github_link_by_user_id(&user_id.0).await;
- assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+ assert!(matches!(result, Ok(None)));
}
#[sqlx::test(
@@ -52,7 +56,8 @@ async fn test_get_github_link_by_github_user_id(pool: Pool<Postgres>) {
let link = repo
.get_github_link_by_github_user_id("12345")
.await
- .unwrap();
+ .unwrap()
+ .expect("fixture github account is linked");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
@@ -68,7 +73,7 @@ async fn test_get_github_link_by_github_user_id_not_found(pool: Pool<Postgres>)
let result = repo.get_github_link_by_github_user_id("99999").await;
- assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+ assert!(matches!(result, Ok(None)));
}
#[sqlx::test(
@@ -216,7 +221,8 @@ async fn test_get_github_link_by_github_user_id_returns_owner(pool: Pool<Postgre
let link = repo
.get_github_link_by_github_user_id("12345")
.await
- .unwrap();
+ .unwrap()
+ .expect("fixture github account is linked");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
diff --git a/services/authentication_service/src/api/link/github.rs b/services/authentication_service/src/api/link/github.rs
index 9dcbeea6a4..a0d2ff6bf1 100644
--- a/services/authentication_service/src/api/link/github.rs
+++ b/services/authentication_service/src/api/link/github.rs
@@ -5,7 +5,10 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use github::domain::{models::GithubError, ports::GithubLinkService};
+use github::domain::{
+ models::{GithubError, GithubLinkStatus},
+ ports::GithubLinkService,
+};
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_middleware::tracking::ClientIp;
use model::response::{EmptyResponse, ErrorResponse};
@@ -78,6 +81,18 @@ impl IntoResponse for InitGithubLinkError {
}
}
+const NO_GITHUB_LINK_MESSAGE: &str = "no github link found";
+
+fn error_response(status_code: StatusCode, message: &'static str) -> Response {
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+}
+
#[derive(thiserror::Error, Debug)]
pub enum GithubLinkStatusError {
#[error(transparent)]
@@ -86,27 +101,9 @@ pub enum GithubLinkStatusError {
impl IntoResponse for GithubLinkStatusError {
fn into_response(self) -> Response {
- let (status_code, message) = match &self {
- Self::Github(GithubError::NoLinkFound) => {
- (StatusCode::NOT_FOUND, "no github link found")
- }
- Self::Github(GithubError::ReauthenticationRequired) => (
- StatusCode::PRECONDITION_REQUIRED,
- REAUTHENTICATION_REQUIRED_MESSAGE,
- ),
- Self::Github(error) => {
- tracing::error!(error=?error, "failed to check GitHub link status");
- (StatusCode::INTERNAL_SERVER_ERROR, "internal error")
- }
- };
-
- (
- status_code,
- Json(ErrorResponse {
- message: message.into(),
- }),
- )
- .into_response()
+ let Self::Github(error) = &self;
+ tracing::error!(error=?error, "failed to check GitHub link status");
+ error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
}
}
@@ -128,18 +125,31 @@ pub async fn check_github_link_status_handler(
State(ctx): State<ApiContext>,
ip_context: ClientIp,
authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
-) -> Result<Json<GithubLinkStatusResponse>, GithubLinkStatusError> {
+) -> Result<Response, GithubLinkStatusError> {
let user_id = &authorization.authorization.user.macro_user_id;
- ctx.github_link_service
- .check_user_link_token(user_id)
+ let status = ctx
+ .github_link_service
+ .get_user_link_status(user_id)
.await?;
- let link = ctx.github_link_service.get_user_link(user_id).await?;
+ // No link and an expired token are expected states: answer them here
+ // rather than as `Err`, which `instrument(err)` would log as an error.
+ let response = match status {
+ GithubLinkStatus::Linked(link) => Json(GithubLinkStatusResponse {
+ reauthentication_required: false,
+ github_username: link.github_username,
+ github_user_id: link.github_user_id,
+ })
+ .into_response(),
+ GithubLinkStatus::NotLinked => {
+ error_response(StatusCode::NOT_FOUND, NO_GITHUB_LINK_MESSAGE)
+ }
+ GithubLinkStatus::ReauthenticationRequired => error_response(
+ StatusCode::PRECONDITION_REQUIRED,
+ REAUTHENTICATION_REQUIRED_MESSAGE,
+ ),
+ };
- Ok(Json(GithubLinkStatusResponse {
- reauthentication_required: false,
- github_username: link.github_username,
- github_user_id: link.github_user_id,
- }))
+ Ok(response)
}
#[derive(Debug, serde::Deserialize)]