Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(github): BE setup check for reauth with github (#3705)

Will Hutchinsonf0515fa2af43
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index 67cb3ec225..f3c6b70dab 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -24,6 +24,7 @@ import type {
GetProfilePicturesRequestBody,
GetUserInfo,
GetUserLinkExistsParams,
+ GithubLinkStatusResponse,
InitGithubLinkParams,
InitGithubLinkResponse,
InitGmailLinkParams,
@@ -290,6 +291,11 @@ export type enrichGithubPullRequestsResponse404 = {
status: 404;
};
+export type enrichGithubPullRequestsResponse428 = {
+ data: ErrorResponse;
+ status: 428;
+};
+
export type enrichGithubPullRequestsResponse500 = {
data: ErrorResponse;
status: 500;
@@ -302,6 +308,7 @@ export type enrichGithubPullRequestsResponseSuccess =
export type enrichGithubPullRequestsResponseError = (
| enrichGithubPullRequestsResponse401
| enrichGithubPullRequestsResponse404
+ | enrichGithubPullRequestsResponse428
| enrichGithubPullRequestsResponse500
) & {
headers: Headers;
@@ -718,6 +725,75 @@ export const deleteGithubLink = async (
} as deleteGithubLinkResponse;
};
+/**
+ * @summary Checks whether the authenticated user's GitHub link token is valid.
+ */
+export type checkGithubLinkStatusResponse200 = {
+ data: GithubLinkStatusResponse;
+ status: 200;
+};
+
+export type checkGithubLinkStatusResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type checkGithubLinkStatusResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type checkGithubLinkStatusResponse428 = {
+ data: ErrorResponse;
+ status: 428;
+};
+
+export type checkGithubLinkStatusResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type checkGithubLinkStatusResponseSuccess =
+ checkGithubLinkStatusResponse200 & {
+ headers: Headers;
+ };
+export type checkGithubLinkStatusResponseError = (
+ | checkGithubLinkStatusResponse401
+ | checkGithubLinkStatusResponse404
+ | checkGithubLinkStatusResponse428
+ | checkGithubLinkStatusResponse500
+) & {
+ headers: Headers;
+};
+
+export type checkGithubLinkStatusResponse =
+ | checkGithubLinkStatusResponseSuccess
+ | checkGithubLinkStatusResponseError;
+
+export const getCheckGithubLinkStatusUrl = () => {
+ return `/link/github/status`;
+};
+
+export const checkGithubLinkStatus = async (
+ options?: RequestInit
+): Promise<checkGithubLinkStatusResponse> => {
+ const res = await fetch(getCheckGithubLinkStatusUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: checkGithubLinkStatusResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as checkGithubLinkStatusResponse;
+};
+
/**
* @summary Initiates a Gmail link for a user
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/githubLinkStatusResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/githubLinkStatusResponse.ts
new file mode 100644
index 0000000000..032271872b
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/githubLinkStatusResponse.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface GithubLinkStatusResponse {
+ /** Whether the user must reauthenticate their GitHub link. */
+ reauthentication_required: boolean;
+}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index 6be1f0c986..f46046cec0 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -41,6 +41,7 @@ export * from './getProfilePicturesRequestBody';
export * from './getUserInfo';
export * from './getUserInfoOrganizationId';
export * from './getUserLinkExistsParams';
+export * from './githubLinkStatusResponse';
export * from './githubPullRequestCheckRun';
export * from './githubPullRequestCheckRunCompletedAt';
export * from './githubPullRequestCheckRunConclusion';
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 43799d8f90..f070cde555 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -224,6 +224,16 @@
}
}
},
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -541,6 +551,65 @@
}
}
},
+ "/link/github/status": {
+ "get": {
+ "tags": ["link::github"],
+ "summary": "Checks whether the authenticated user's GitHub link token is valid.",
+ "operationId": "check_github_link_status",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GithubLinkStatusResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "428": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/link/gmail": {
"post": {
"tags": ["link::gmail"],
@@ -3710,6 +3779,16 @@
}
}
},
+ "GithubLinkStatusResponse": {
+ "type": "object",
+ "required": ["reauthentication_required"],
+ "properties": {
+ "reauthentication_required": {
+ "type": "boolean",
+ "description": "Whether the user must reauthenticate their GitHub link."
+ }
+ }
+ },
"GithubPullRequestCheckRun": {
"type": "object",
"description": "A check run associated with a GitHub pull request.",
diff --git a/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs b/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs
index ed67042540..33e197ed9c 100644
--- a/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs
+++ b/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs
@@ -22,19 +22,20 @@ pub enum EnrichGithubPullRequestsProxyError {
impl IntoResponse for EnrichGithubPullRequestsProxyError {
fn into_response(self) -> Response {
- let status_code = match &self {
- Self::Github(GithubError::NoLinkFound) => StatusCode::NOT_FOUND,
+ 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",
+ ),
Self::Github(error) => {
tracing::error!(error=?error, "failed to enrich GitHub pull requests");
- StatusCode::INTERNAL_SERVER_ERROR
+ (StatusCode::INTERNAL_SERVER_ERROR, "internal error")
}
};
- let message = match &self {
- Self::Github(GithubError::NoLinkFound) => "no github link found",
- Self::Github(_) => "internal error",
- };
-
(
status_code,
Json(ErrorResponse {
@@ -59,6 +60,7 @@ pub fn router() -> Router<ApiContext> {
(status = 200, body = EnrichGithubPullRequestsResponse),
(status = 401, body = ErrorResponse),
(status = 404, body = ErrorResponse),
+ (status = 428, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
diff --git a/rust/cloud-storage/authentication_service/src/api/link/github.rs b/rust/cloud-storage/authentication_service/src/api/link/github.rs
index 4fc238723a..603f388f35 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/github.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/github.rs
@@ -14,6 +14,14 @@ use crate::api::{context::ApiContext, oauth2::OAuthState};
use model::response::{EmptyResponse, ErrorResponse};
+const REAUTHENTICATION_REQUIRED_MESSAGE: &str = "ReauthenticationRequired";
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]
+pub struct GithubLinkStatusResponse {
+ /// Whether the user must reauthenticate their GitHub link.
+ pub reauthentication_required: bool,
+}
+
#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]
pub struct InitGithubLinkResponse {
/// The OAuth authorization URL to redirect the user to
@@ -63,6 +71,66 @@ impl IntoResponse for InitGithubLinkError {
}
}
+#[derive(thiserror::Error, Debug)]
+pub enum GithubLinkStatusError {
+ #[error(transparent)]
+ Github(#[from] GithubError),
+}
+
+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()
+ }
+}
+
+/// Checks whether the authenticated user's GitHub link token is valid.
+#[utoipa::path(
+ get,
+ operation_id = "check_github_link_status",
+ path = "/link/github/status",
+ responses(
+ (status = 200, body=GithubLinkStatusResponse),
+ (status = 401, body=ErrorResponse),
+ (status = 404, body=ErrorResponse),
+ (status = 428, body=ErrorResponse),
+ (status = 500, body=ErrorResponse),
+ )
+ )]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context, user_id=%user_context.macro_user_id), err)]
+pub async fn check_github_link_status_handler(
+ State(ctx): State<ApiContext>,
+ ip_context: ClientIp,
+ user_context: MacroUserExtractor,
+) -> Result<Json<GithubLinkStatusResponse>, GithubLinkStatusError> {
+ ctx.github_link_service
+ .check_user_link_token(&user_context.macro_user_id)
+ .await?;
+
+ Ok(Json(GithubLinkStatusResponse {
+ reauthentication_required: false,
+ }))
+}
+
#[derive(Debug, serde::Deserialize)]
pub(crate) struct InitGithubLinkQueryParams {
/// Once the frontend is update to NOT 2x urlencode this then this should be changed to
diff --git a/rust/cloud-storage/authentication_service/src/api/link/mod.rs b/rust/cloud-storage/authentication_service/src/api/link/mod.rs
index a04f9831af..04ec123b5e 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/mod.rs
@@ -1,7 +1,7 @@
use crate::api::context::ApiContext;
use axum::{
Router,
- routing::{delete, post},
+ routing::{delete, get, post},
};
pub(in crate::api) mod create_in_progress_link;
pub(in crate::api) mod github;
@@ -14,5 +14,9 @@ pub fn router(_state: ApiContext) -> Router<ApiContext> {
.route("/", post(create_in_progress_link::handler))
.route("/github", post(github::init_github_link_handler))
.route("/github", delete(github::delete_github_link_handler))
+ .route(
+ "/github/status",
+ get(github::check_github_link_status_handler),
+ )
.route("/gmail", post(gmail::init_gmail_link_handler))
}
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index c387a5e7f0..6bbac983c5 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -20,7 +20,7 @@ use crate::api::email::generate_email_link::GenerateEmailLinkRequest;
use crate::api::email::resend_fusionauth_verify_user_email::ResendFusionauthVerifyUserEmailRequest;
use crate::api::jwt::macro_api_token::MacroApiTokenResponse;
use crate::api::link::create_in_progress_link::CreateInProgressLinkResponse;
-use crate::api::link::github::InitGithubLinkResponse;
+use crate::api::link::github::{GithubLinkStatusResponse, InitGithubLinkResponse};
use crate::api::link::gmail::InitGmailLinkResponse;
use crate::api::merge::create_merge_request::CreateAccountMergeRequest;
use crate::api::user::create_user::CreateUserRequest;
@@ -77,6 +77,7 @@ use model::user::{
link::create_in_progress_link::handler,
link::github::init_github_link_handler,
link::github::delete_github_link_handler,
+ link::github::check_github_link_status_handler,
link::gmail::init_gmail_link_handler,
/// /github_pull_requests
@@ -176,6 +177,7 @@ use model::user::{
GenerateEmailLinkRequest,
CreateInProgressLinkResponse,
InitGithubLinkResponse,
+ GithubLinkStatusResponse,
InitGmailLinkResponse,
// GitHub pull requests
@@ -252,6 +254,25 @@ mod tests {
operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),
Some("#/components/schemas/EnrichGithubPullRequestsResponse")
);
+ assert!(operation["responses"].get("428").is_some());
+ }
+
+ #[test]
+ fn github_link_status_openapi_includes_path_and_schema() {
+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();
+ let operation = &openapi["paths"]["/link/github/status"]["get"];
+
+ assert_eq!(operation["operationId"], "check_github_link_status");
+ assert_eq!(
+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),
+ Some("#/components/schemas/GithubLinkStatusResponse")
+ );
+ assert!(operation["responses"].get("428").is_some());
+ assert!(
+ openapi["components"]["schemas"]
+ .get("GithubLinkStatusResponse")
+ .is_some()
+ );
}
#[test]
diff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rs
index 1c016f7fa6..58432abe1d 100644
--- a/rust/cloud-storage/github/src/domain/models/mod.rs
+++ b/rust/cloud-storage/github/src/domain/models/mod.rs
@@ -26,6 +26,9 @@ pub enum GithubError {
/// No Github link was found
#[error("no link found")]
NoLinkFound,
+ /// The Github link token has expired and the user must reauthenticate.
+ #[error("reauthentication required")]
+ ReauthenticationRequired,
/// Github account is already linked
#[error("github account is already linked with another")]
AccountAlreadyLinked,
diff --git a/rust/cloud-storage/github/src/domain/ports/link.rs b/rust/cloud-storage/github/src/domain/ports/link.rs
index d71e4de24b..e16c2c26fa 100644
--- a/rust/cloud-storage/github/src/domain/ports/link.rs
+++ b/rust/cloud-storage/github/src/domain/ports/link.rs
@@ -83,6 +83,12 @@ pub trait GithubOauth: Send + Sync + 'static {
access_token: &str,
) -> impl Future<Output = Result<GithubUserInfo, Self::Err>> + Send;
+ /// Checks if the access token is expired or invalid.
+ fn is_access_token_expired(
+ &self,
+ access_token: &str,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
/// Gets pull request details using the user's access token.
fn get_pull_request_details(
&self,
@@ -157,6 +163,12 @@ pub trait GithubLinkService: Send + Sync + 'static {
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(
+ &self,
+ user_id: &MacroUserId<Lowercase<'static>>,
+ ) -> impl Future<Output = Result<(), GithubError>> + Send;
+
/// Enriches GitHub pull request references with details from the GitHub API.
fn enrich_pull_requests(
&self,
diff --git a/rust/cloud-storage/github/src/domain/service/link.rs b/rust/cloud-storage/github/src/domain/service/link.rs
index 8b90aeb2db..bf4f99e347 100644
--- a/rust/cloud-storage/github/src/domain/service/link.rs
+++ b/rust/cloud-storage/github/src/domain/service/link.rs
@@ -7,7 +7,9 @@ use macro_user_id::{
};
use crate::domain::{
- models::{EnrichedGithubPullRequest, GithubError, GithubLink, GithubPullRequestRef},
+ models::{
+ EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubLink, GithubPullRequestRef,
+ },
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -40,6 +42,51 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {
config,
}
}
+
+ 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(
+ &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)
+ }
+
+ 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 access_token = self
+ .auth
+ .retreive_access_token(&link.fusionauth_user_id, &self.config.idp_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ let token_is_expired = self
+ .oauth
+ .is_access_token_expired(access_token.as_str())
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ if token_is_expired {
+ return Err(GithubError::ReauthenticationRequired);
+ }
+
+ Ok(access_token)
+ }
}
impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkServiceImpl<R, U, F> {
@@ -65,6 +112,15 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkSer
.map_err(|e| GithubError::Internal(e.into()))
}
+ #[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(())
+ }
+
#[tracing::instrument(skip(self, pull_requests), err)]
async fn enrich_pull_requests(
&self,
@@ -75,29 +131,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkSer
return Ok(Vec::new());
}
- 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 let Some(db_err) = e.downcast_ref::<sqlx::Error>()
- && matches!(db_err, sqlx::Error::RowNotFound)
- {
- return Err(GithubError::NoLinkFound);
- }
-
- if e.to_string().contains("no rows returned") {
- return Err(GithubError::NoLinkFound);
- }
-
- return Err(GithubError::Internal(e));
- }
- };
-
- let access_token = self
- .auth
- .retreive_access_token(&link.fusionauth_user_id, &self.config.idp_id)
- .await
- .map_err(|e| GithubError::Internal(e.into()))?;
+ let access_token = self.validated_access_token(macro_user_id).await?;
let mut enriched_pull_requests = Vec::with_capacity(pull_requests.len());
@@ -143,14 +177,12 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkSer
Ok(link) => link,
Err(e) => {
let e: anyhow::Error = e.into();
- if let Some(db_err) = e.downcast_ref::<sqlx::Error>()
- && matches!(db_err, sqlx::Error::RowNotFound)
- {
+ if e.to_string().contains("no rows returned") {
tracing::trace!("no github link found for user");
return Ok(());
- } else {
- return Err(GithubError::Internal(e));
}
+
+ return Err(GithubError::Internal(e));
}
};
diff --git a/rust/cloud-storage/github/src/domain/service/link_test.rs b/rust/cloud-storage/github/src/domain/service/link_test.rs
new file mode 100644
index 0000000000..5e3310fb1e
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/link_test.rs
@@ -0,0 +1,341 @@
+use std::sync::{Arc, Mutex};
+
+use chrono::Utc;
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+
+use crate::domain::{
+ models::{
+ GithubAccessToken, GithubError, GithubExchangeTokenResponse, GithubLink,
+ GithubPullRequestDetails, GithubPullRequestRef, GithubUserInfo,
+ },
+ ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
+};
+
+use super::{GithubLinkConfig, GithubLinkServiceImpl};
+
+#[derive(Clone)]
+struct StubGithubRepo {
+ link: Option<GithubLink>,
+}
+
+impl StubGithubRepo {
+ fn linked(link: GithubLink) -> Self {
+ Self { link: Some(link) }
+ }
+
+ fn unlinked() -> Self {
+ Self { link: None }
+ }
+}
+
+impl GithubRepo for StubGithubRepo {
+ type Err = anyhow::Error;
+
+ async fn get_github_link_by_user_id<'a>(
+ &self,
+ _macro_user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> Result<GithubLink, Self::Err> {
+ self.link
+ .clone()
+ .ok_or_else(|| anyhow::anyhow!("no rows returned"))
+ }
+
+ async fn get_github_link_by_github_user_id(
+ &self,
+ _github_user_id: &str,
+ ) -> Result<GithubLink, Self::Err> {
+ Err(anyhow::anyhow!("not implemented"))
+ }
+
+ async fn get_github_link_by_id(&self, _id: &uuid::Uuid) -> Result<GithubLink, Self::Err> {
+ Err(anyhow::anyhow!("not implemented"))
+ }
+
+ async fn insert_github_link(&self, _link: &GithubLink) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn delete_in_progress_user_link(
+ &self,
+ _in_progress_link_id: &uuid::Uuid,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn delete_github_link(&self, _link_id: &uuid::Uuid) -> Result<(), Self::Err> {
+ Ok(())
+ }
+}
+
+#[derive(Clone, Default)]
+struct StubGithubOauth {
+ state: Arc<Mutex<StubGithubOauthState>>,
+}
+
+#[derive(Default)]
+struct StubGithubOauthState {
+ token_is_expired: bool,
+ validated_tokens: Vec<String>,
+ pull_request_detail_calls: Vec<PullRequestDetailCall>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct PullRequestDetailCall {
+ access_token: String,
+ owner: String,
+ repo: String,
+ number: u64,
+}
+
+impl StubGithubOauth {
+ fn new(token_is_expired: bool) -> Self {
+ Self {
+ state: Arc::new(Mutex::new(StubGithubOauthState {
+ token_is_expired,
+ ..StubGithubOauthState::default()
+ })),
+ }
+ }
+
+ fn validated_tokens(&self) -> Vec<String> {
+ self.state.lock().unwrap().validated_tokens.clone()
+ }
+
+ fn pull_request_detail_calls(&self) -> Vec<PullRequestDetailCall> {
+ self.state.lock().unwrap().pull_request_detail_calls.clone()
+ }
+}
+
+impl GithubOauth for StubGithubOauth {
+ type Err = anyhow::Error;
+
+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ &self,
+ _client_id: &str,
+ _redirect_uri: &str,
+ _state: T,
+ ) -> Result<String, Self::Err> {
+ Ok("https://github.example/oauth".to_string())
+ }
+
+ async fn exchange_oauth_code_for_tokens(
+ &self,
+ _client_id: &str,
+ _client_secret: &str,
+ _redirect_uri: &str,
+ _code: &str,
+ ) -> Result<GithubExchangeTokenResponse, Self::Err> {
+ Ok(GithubExchangeTokenResponse {
+ access_token: "access-token".to_string(),
+ token_type: "bearer".to_string(),
+ scope: "repo user:email".to_string(),
+ refresh_token: None,
+ expires_in: None,
+ refresh_token_expires_in: None,
+ })
+ }
+
+ async fn get_user_info(&self, _access_token: &str) -> Result<GithubUserInfo, Self::Err> {
+ Ok(GithubUserInfo {
+ id: 1,
+ login: "octocat".to_string(),
+ email: None,
+ name: None,
+ })
+ }
+
+ async fn is_access_token_expired(&self, access_token: &str) -> Result<bool, Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.validated_tokens.push(access_token.to_string());
+ Ok(state.token_is_expired)
+ }
+
+ async fn get_pull_request_details(
+ &self,
+ access_token: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+ ) -> Result<GithubPullRequestDetails, Self::Err> {
+ self.state
+ .lock()
+ .unwrap()
+ .pull_request_detail_calls
+ .push(PullRequestDetailCall {
+ access_token: access_token.to_string(),
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ number,
+ });
+
+ Ok(GithubPullRequestDetails {
+ title: "Add token validation".to_string(),
+ state: "open".to_string(),
+ merged_at: None,
+ additions: 12,
+ deletions: 3,
+ comments: None,
+ checks: None,
+ })
+ }
+}
+
+#[derive(Clone)]
+struct StubAuth {
+ access_token: String,
+}
+
+impl StubAuth {
+ fn new(access_token: &str) -> Self {
+ Self {
+ access_token: access_token.to_string(),
+ }
+ }
+}
+
+impl Auth for StubAuth {
+ type Err = anyhow::Error;
+
+ async fn link_user(
+ &self,
+ _fusionauth_user_id: &uuid::Uuid,
+ _idp_id: &str,
+ _github_user_id: &str,
+ _username: &str,
+ _access_token: &str,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn delete_user_link(
+ &self,
+ _github_link: &GithubLink,
+ _github_idp_id: &str,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
+
+ async fn retreive_access_token(
+ &self,
+ _fusionauth_user_id: &uuid::Uuid,
+ _github_idp_id: &str,
+ ) -> Result<GithubAccessToken, Self::Err> {
+ Ok(GithubAccessToken::new(self.access_token.clone()))
+ }
+}
+
+fn test_user_id() -> MacroUserId<Lowercase<'static>> {
+ MacroUserIdStr::try_from_email("[email protected]")
+ .unwrap()
+ .0
+}
+
+fn test_link(user_id: &MacroUserId<Lowercase<'static>>) -> GithubLink {
+ GithubLink {
+ id: uuid::Uuid::nil(),
+ macro_id: MacroUserIdStr((*user_id).clone()),
+ fusionauth_user_id: uuid::Uuid::nil(),
+ github_username: "octocat".to_string(),
+ github_user_id: "1".to_string(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+}
+
+fn pull_request_ref() -> GithubPullRequestRef {
+ GithubPullRequestRef {
+ github_key: "macro/app/pull/7".to_string(),
+ owner: "macro".to_string(),
+ repo: "app".to_string(),
+ number: 7,
+ url: "https://github.com/macro/app/pull/7".to_string(),
+ display_name: "macro/app#7".to_string(),
+ }
+}
+
+fn service(
+ repo: StubGithubRepo,
+ oauth: StubGithubOauth,
+ auth: StubAuth,
+) -> GithubLinkServiceImpl<StubGithubRepo, StubGithubOauth, StubAuth> {
+ GithubLinkServiceImpl::new(
+ repo,
+ oauth,
+ auth,
+ GithubLinkConfig {
+ client_id: "client-id".to_string(),
+ client_secret: "client-secret".to_string(),
+ idp_id: "github-idp".to_string(),
+ },
+ )
+}
+
+#[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() {
+ 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
+ .enrich_pull_requests(&user_id, vec![pull_request_ref()])
+ .await;
+
+ assert!(matches!(result, Err(GithubError::ReauthenticationRequired)));
+ assert_eq!(oauth.validated_tokens(), vec!["expired-token".to_string()]);
+ assert!(oauth.pull_request_detail_calls().is_empty());
+}
diff --git a/rust/cloud-storage/github/src/domain/service/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rs
index 11390246fd..aae7b837e7 100644
--- a/rust/cloud-storage/github/src/domain/service/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/mod.rs
@@ -10,3 +10,6 @@ mod link;
#[cfg(feature = "link")]
pub use link::{GithubLinkConfig, GithubLinkServiceImpl};
+
+#[cfg(all(test, feature = "link"))]
+mod link_test;
diff --git a/rust/cloud-storage/github/src/inbound.rs b/rust/cloud-storage/github/src/inbound.rs
index 4b645483b5..66af30d09b 100644
--- a/rust/cloud-storage/github/src/inbound.rs
+++ b/rust/cloud-storage/github/src/inbound.rs
@@ -15,6 +15,10 @@ impl axum::response::IntoResponse for crate::domain::models::GithubError {
crate::domain::models::GithubError::NoLinkFound => {
(StatusCode::FORBIDDEN, "no account link found")
}
+ crate::domain::models::GithubError::ReauthenticationRequired => (
+ StatusCode::PRECONDITION_REQUIRED,
+ "ReauthenticationRequired",
+ ),
crate::domain::models::GithubError::AccountAlreadyLinked => {
(StatusCode::BAD_REQUEST, "account already linked")
}
diff --git a/rust/cloud-storage/github/src/outbound/github_auth_client.rs b/rust/cloud-storage/github/src/outbound/github_auth_client.rs
index 7f4eb8ec23..01a586e170 100644
--- a/rust/cloud-storage/github/src/outbound/github_auth_client.rs
+++ b/rust/cloud-storage/github/src/outbound/github_auth_client.rs
@@ -41,6 +41,16 @@ impl GithubAuthImpl {
conn,
}
}
+
+ async fn clear_access_token_cache(
+ &self,
+ fusionauth_user_id: &uuid::Uuid,
+ ) -> Result<(), anyhow::Error> {
+ let key = github_access_token_key!(fusionauth_user_id);
+ let mut conn = self.conn.clone();
+ conn.del::<&str, ()>(&key).await?;
+ Ok(())
+ }
}
impl Auth for GithubAuthImpl {
@@ -67,6 +77,8 @@ impl Auth for GithubAuthImpl {
})
.await?;
+ self.clear_access_token_cache(fusionauth_user_id).await?;
+
Ok(())
}
@@ -120,7 +132,11 @@ impl Auth for GithubAuthImpl {
)
.await
{
- Ok(()) | Err(FusionAuthClientError::NoIdentityProviderFound) => Ok(()),
+ Ok(()) | Err(FusionAuthClientError::NoIdentityProviderFound) => {
+ self.clear_access_token_cache(&github_link.fusionauth_user_id)
+ .await?;
+ Ok(())
+ }
Err(e) => Err(e.into()),
}
}
diff --git a/rust/cloud-storage/github/src/outbound/github_oauth_client.rs b/rust/cloud-storage/github/src/outbound/github_oauth_client.rs
index b35d868b3b..d2310c8787 100644
--- a/rust/cloud-storage/github/src/outbound/github_oauth_client.rs
+++ b/rust/cloud-storage/github/src/outbound/github_oauth_client.rs
@@ -183,6 +183,34 @@ impl GithubOauth for GithubOauthImpl {
Ok(user_info)
}
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn is_access_token_expired(&self, access_token: &str) -> Result<bool, Self::Err> {
+ let user_response = self
+ .client
+ .get("https://api.github.com/user")
+ .header("Authorization", format!("Bearer {}", access_token))
+ .header("User-Agent", "Macro-Auth-Service")
+ .timeout(Duration::from_secs(30))
+ .send()
+ .await?;
+
+ let status = user_response.status();
+
+ if status == reqwest::StatusCode::UNAUTHORIZED {
+ return Ok(true);
+ }
+
+ if !status.is_success() {
+ let error_body = user_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ anyhow::bail!("failed to validate access token {}", error_body);
+ }
+
+ Ok(false)
+ }
+
#[tracing::instrument(skip(self, access_token), err)]
async fn get_pull_request_details(
&self,