Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): get GitHub access token (#1701)
Will Hutchinson9394f5db2f4c
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 232e5ad314..aeec9c8b51 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4098,11 +4098,13 @@ dependencies = ["macro_user_id","macro_uuid","mockall",+ "redis","reqwest","serde","serde_json","sqlx","thiserror 2.0.17",+ "tokio","tracing","urlencoding","uuid",diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex b937f6a411..a454532541 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -2,7 +2,7 @@ use std::sync::Arc;use axum::extract::FromRef;use github::domain::service::GithubServiceImpl;-use github::outbound::github_fusionauth_client::GithubFusionAuthImpl;+use github::outbound::github_auth_client::GithubAuthImpl;use github::outbound::github_oauth_client::GithubOauthImpl;use github::outbound::pg_github_repo::PgGithubRepo;use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -45,7 +45,7 @@ pub(crate) type NotificationIngressType = NotificationIngressService<>;pub(crate) type GithubServiceType =- GithubServiceImpl<PgGithubRepo, GithubOauthImpl, GithubFusionAuthImpl>;+ GithubServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 7f182f1291..a34ae1f99e 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -4,7 +4,7 @@ use document_storage_service_client::DocumentStorageServiceClient;use github::{domain::service::{GithubConfig, GithubServiceImpl},outbound::{- github_fusionauth_client::GithubFusionAuthImpl, github_oauth_client::GithubOauthImpl,+ github_auth_client::GithubAuthImpl, github_oauth_client::GithubOauthImpl,pg_github_repo::PgGithubRepo,},};@@ -201,7 +201,7 @@ async fn main() -> anyhow::Result<()> {),),),- digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn),+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn.clone()),block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>().append::<model_notifications::ChannelInviteMetadata>(),@@ -237,7 +237,7 @@ async fn main() -> anyhow::Result<()> {let github_service_impl = GithubServiceImpl::new(PgGithubRepo::new(db.clone()),GithubOauthImpl::default(),- GithubFusionAuthImpl::new(auth_client.clone()),+ GithubAuthImpl::new(auth_client.clone(), redis_multiplexed_conn),GithubConfig {client_id: config.github_client_id,client_secret: config.github_client_secret,diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex 9c0f841687..2241f2f1e3 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -12,6 +12,8 @@ outbound = ["dep:reqwest","dep:serde_json","dep:urlencoding",+ "dep:redis",+ "dep:tokio","dep:fusionauth","ports"]@@ -31,6 +33,8 @@ urlencoding = { workspace = true, optional = true }fusionauth = { path = "../fusionauth", optional = true }macro_uuid = { path = "../macro_uuid" }macro_user_id = { path = "../macro_user_id" }+redis = { workspace = true, features = ["aio", "tokio-comp"], optional = true }+tokio = { workspace = true, features = ["sync"], optional = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/github/src/domain/models.rs b/rust/cloud-storage/github/src/domain/models.rsindex eec19c0f52..afb3755910 100644--- a/rust/cloud-storage/github/src/domain/models.rs+++ b/rust/cloud-storage/github/src/domain/models.rs@@ -3,6 +3,18 @@use macro_user_id::user_id::MacroUserIdStr;use serde::Deserialize;+/// Github access token+#[derive(Clone)]+#[allow(dead_code)]+pub struct GithubAccessToken(String);++impl GithubAccessToken {+ /// Creates a new GithubAccessToken+ pub fn new(token: String) -> Self {+ Self(token)+ }+}+/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]pub enum GithubError {diff --git a/rust/cloud-storage/github/src/domain/ports.rs b/rust/cloud-storage/github/src/domain/ports.rsindex 217faf168f..1c986b7115 100644--- a/rust/cloud-storage/github/src/domain/ports.rs+++ b/rust/cloud-storage/github/src/domain/ports.rs@@ -4,7 +4,9 @@use std::future::Future;-use crate::domain::models::{GithubError, GithubExchangeTokenResponse, GithubUserInfo};+use crate::domain::models::{+ GithubAccessToken, GithubError, GithubExchangeTokenResponse, GithubUserInfo,+};use super::models::GithubLink;use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};@@ -79,13 +81,13 @@ pub trait GithubOauth: Send + Sync + 'static {) -> impl Future<Output = Result<GithubUserInfo, Self::Err>> + Send;}-/// Repository for handling fusionauth related actions.+/// Repository for handling auth related actions.#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]-pub trait FusionAuth: Send + Sync + 'static {+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 fusionauth user+ /// Links the github account to the auth userfn link_user(&self,fusionauth_user_id: &uuid::Uuid,@@ -94,6 +96,13 @@ pub trait FusionAuth: Send + Sync + 'static {username: &str,access_token: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Retreives the users github access token+ fn retreive_access_token(+ &self,+ fusionauth_user_id: &uuid::Uuid,+ github_idp_id: &str,+ ) -> impl Future<Output = Result<GithubAccessToken, Self::Err>>;}/// Service interface for github operations.diff --git a/rust/cloud-storage/github/src/domain/service.rs b/rust/cloud-storage/github/src/domain/service.rsindex 6a38331241..f0fd5d5ddc 100644--- a/rust/cloud-storage/github/src/domain/service.rs+++ b/rust/cloud-storage/github/src/domain/service.rs@@ -8,7 +8,7 @@ use macro_user_id::{use crate::domain::{models::{GithubError, GithubLink},- ports::{FusionAuth, GithubOauth, GithubRepo, GithubService},+ ports::{Auth, GithubOauth, GithubRepo, GithubService},};/// Github config@@ -23,26 +23,26 @@ pub struct GithubConfig {}/// The concrete github service implementation.-pub struct GithubServiceImpl<R: GithubRepo, U: GithubOauth, F: FusionAuth> {+pub struct GithubServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {repo: R,oauth: U,- fusion: F,+ auth: F,config: GithubConfig,}-impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> GithubServiceImpl<R, U, F> {+impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubServiceImpl<R, U, F> {/// Create a new github service.- pub fn new(repo: R, oauth: U, fusion: F, config: GithubConfig) -> Self {+ pub fn new(repo: R, oauth: U, auth: F, config: GithubConfig) -> Self {Self {repo,oauth,- fusion,+ auth,config,}}}-impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> GithubService for GithubServiceImpl<R, U, F> {+impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubService for GithubServiceImpl<R, U, F> {#[tracing::instrument(skip(self), err)]fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(&self,@@ -103,7 +103,7 @@ impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> GithubService for GithubServi}}- self.fusion+ self.auth.link_user(fusionauth_user_id,&self.config.idp_id,@@ -114,7 +114,7 @@ impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> GithubService for GithubServi.await.map_err(|e| GithubError::Internal(e.into()))?;- tracing::trace!("linked fusionauth user");+ tracing::trace!("linked auth user");// create github linklet link = GithubLink {diff --git a/rust/cloud-storage/github/src/outbound.rs b/rust/cloud-storage/github/src/outbound.rsindex 60fe2e9890..f621e1c8bb 100644--- a/rust/cloud-storage/github/src/outbound.rs+++ b/rust/cloud-storage/github/src/outbound.rs@@ -1,5 +1,5 @@//! Outbound adapters for the github domain.-pub mod github_fusionauth_client;+pub mod github_auth_client;pub mod github_oauth_client;pub mod pg_github_repo;diff --git a/rust/cloud-storage/github/src/outbound/github_auth_client.rs b/rust/cloud-storage/github/src/outbound/github_auth_client.rsnew file mode 100644index 0000000000..e391a914a9--- /dev/null+++ b/rust/cloud-storage/github/src/outbound/github_auth_client.rs@@ -0,0 +1,103 @@+//! Github FusionAuth implementation of the [`Auth`] port.++use anyhow::Context;+use fusionauth::{+ FusionAuthClient,+ identity_provider::{IdentityProviderLink, LinkUserRequest},+};+use redis::AsyncCommands;+use redis::aio::MultiplexedConnection;++use crate::domain::{models::GithubAccessToken, ports::Auth};++/// TTL for github tokens: 1 day+const TTL_SECONDS: u64 = 60 * 60 * 24;++/// Generates the key for the github access token in redis+macro_rules! github_access_token_key {+ ($fusionauth_user_id:expr) => {+ format!("github_access_token_key:{}", $fusionauth_user_id)+ };+}++/// Github FusionAuth implementation+#[derive(Clone)]+pub struct GithubAuthImpl {+ /// The fusionauth client+ fusionauth_client: FusionAuthClient,+ /// Redis connection+ conn: MultiplexedConnection,+}++impl GithubAuthImpl {+ /// Create a new instance of GithubAuthImpl+ pub fn new(fusionauth_client: FusionAuthClient, conn: MultiplexedConnection) -> Self {+ Self {+ fusionauth_client,+ conn,+ }+ }+}++impl Auth for GithubAuthImpl {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self), err)]+ 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> {+ 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(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn retreive_access_token(+ &self,+ fusionauth_user_id: &uuid::Uuid,+ github_idp_id: &str,+ ) -> Result<GithubAccessToken, Self::Err> {+ let key = github_access_token_key!(fusionauth_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));+ }++ let links = self+ .fusionauth_client+ .get_links(+ &fusionauth_user_id.to_string(),+ Some(github_idp_id.to_string()),+ )+ .await?;++ if links.is_empty() {+ anyhow::bail!("user does not have a github link")+ }++ // SAFETY: at the moment, we only support 1 github link per user+ 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()))+ }+}diff --git a/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rs b/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rsdeleted file mode 100644index 5e2540d514..0000000000--- a/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rs+++ /dev/null@@ -1,50 +0,0 @@-//! Github FusionAuth implementation of the [`FusionAuth`] port.--use fusionauth::{- FusionAuthClient,- identity_provider::{IdentityProviderLink, LinkUserRequest},-};--use crate::domain::ports::FusionAuth;--/// Github FusionAuth implementation-#[derive(Clone)]-pub struct GithubFusionAuthImpl {- /// The fusionauth client- fusionauth_client: FusionAuthClient,-}--impl GithubFusionAuthImpl {- /// Create a new instance of GithubFusionAuthImpl- pub fn new(fusionauth_client: FusionAuthClient) -> Self {- Self { fusionauth_client }- }-}--impl FusionAuth for GithubFusionAuthImpl {- type Err = anyhow::Error;-- #[tracing::instrument(skip(self), err)]- 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> {- 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(())- }-}