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
chore(github): split GitHub services (#1763)
Will Hutchinson3f4f94a1771f
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yamlindex 246b4e7f77..1b5342c82f 100644--- a/infra/stacks/authentication-service/Pulumi.dev.yaml+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml@@ -21,7 +21,3 @@ config:authentication-service:github_client_id_key: github-client-id-devauthentication-service:github_client_secret_key: github-client-secret-devauthentication-service:github_idp_id_key: github-idp-id-dev- authentication-service:github_webhook_secret_key: github-webhook-secret-dev- authentication-service:github_sync_app_url: https://github.com/apps/dev-macro-sync- authentication-service:github_sync_app_pem: github-sync-app-pem-dev- authentication-service:github_sync_app_client_id: Iv23livpJoVJw98dlKCkdiff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yamlindex 8e8cbf0f9f..d165fe3936 100644--- a/infra/stacks/authentication-service/Pulumi.prod.yaml+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml@@ -20,8 +20,4 @@ config:authentication-service:fusionauth_tenant_id: a3e53c3d-8d6a-3e92-d64c-fa3bf30a60beauthentication-service:github_client_id_key: github-client-id-prodauthentication-service:github_client_secret_key: github-client-secret-prod- authentication-service:github_idp_id_key: github-idp-id-prod- authentication-service:github_webhook_secret_key: github-webhook-secret-prod- authentication-service:github_sync_app_url: https://github.com/apps/macro-sync- authentication-service:github_sync_app_pem: github-sync-app-pem-prod- authentication-service:github_sync_app_client_id: Iv23ctSZX2wLdqO2iqrS+ authentication-service:github_idp_id_key: github-idp-id-proddiff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex fd58973292..2bb57ba50c 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -41,20 +41,6 @@ const GITHUB_IDP_ID = aws.secretsmanager}).apply((secret) => secret.secretString);-const GITHUB_SYNC_APP_URL = config.require('github_sync_app_url');--const GITHUB_WEBHOOK_SECRET_KEY = config.require('github_webhook_secret_key');-const githubWebhookSecretKeyArn: pulumi.Output<string> = aws.secretsmanager- .getSecretVersionOutput({ secretId: GITHUB_WEBHOOK_SECRET_KEY })- .apply((secret) => secret.arn);--const GITHUB_SYNC_APP_PEM = config.require('github_sync_app_pem');-const githubSyncAppPemArn: pulumi.Output<string> = aws.secretsmanager- .getSecretVersionOutput({ secretId: GITHUB_SYNC_APP_PEM })- .apply((secret) => secret.arn);--const GITHUB_SYNC_APP_CLIENT_ID = config.require('github_sync_app_client_id');-const MACRO_CACHE = aws.secretsmanager.getSecretVersionOutput({secretId: config.require(`macro_cache_secret_key`),@@ -168,8 +154,6 @@ const secretKeyArns = [pulumi.interpolate`${macroApiTokenSecretPrivateKeyArn}`,pulumi.interpolate`${stripeWebhookSecretKeyArn}`,pulumi.interpolate`${stripePriceIdArn}`,- pulumi.interpolate`${githubWebhookSecretKeyArn}`,- pulumi.interpolate`${githubSyncAppPemArn}`,];const vpc = get_coparse_api_vpc();@@ -329,22 +313,6 @@ const service = new AuthenticationService('authentication-service', {name: 'GITHUB_IDP_ID',value: pulumi.interpolate`${GITHUB_IDP_ID}`,},- {- name: 'GITHUB_WEBHOOK_SECRET_KEY',- value: GITHUB_WEBHOOK_SECRET_KEY,- },- {- name: 'GITHUB_SYNC_APP_URL',- value: GITHUB_SYNC_APP_URL,- },- {- name: 'GITHUB_SYNC_APP_PEM',- value: GITHUB_SYNC_APP_PEM,- },- {- name: 'GITHUB_SYNC_APP_CLIENT_ID',- value: GITHUB_SYNC_APP_CLIENT_ID,- },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml b/infra/stacks/cloud-storage-service/Pulumi.dev.yamlindex a93aeeaf1a..7e6f33048a 100644--- a/infra/stacks/cloud-storage-service/Pulumi.dev.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.dev.yaml@@ -13,3 +13,7 @@ config:cloud-storage-service:authentication_service_secret_key: authentication-service-internal-api-key-devcloud-storage-service:opensearch_password_key: macro-opensearch-password-devcloud-storage-service:macro_cache_secret_key: macro-cache-dev+ cloud-storage-service:github_webhook_secret_key: github-webhook-secret-dev+ cloud-storage-service:github_sync_app_url: https://github.com/apps/dev-macro-sync+ cloud-storage-service:github_sync_app_pem: github-sync-app-pem-dev+ cloud-storage-service:github_sync_app_client_id: Iv23livpJoVJw98dlKCkdiff --git a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml b/infra/stacks/cloud-storage-service/Pulumi.prod.yamlindex a2cc7ae655..50525334e0 100644--- a/infra/stacks/cloud-storage-service/Pulumi.prod.yaml+++ b/infra/stacks/cloud-storage-service/Pulumi.prod.yaml@@ -13,3 +13,7 @@ config:cloud-storage-service:authentication_service_secret_key: authentication-service-internal-api-key-prodcloud-storage-service:opensearch_password_key: macro-opensearch-password-prodcloud-storage-service:macro_cache_secret_key: macro-cache-prod+ cloud-storage-service:github_webhook_secret_key: github-webhook-secret-prod+ cloud-storage-service:github_sync_app_url: https://github.com/apps/macro-sync+ cloud-storage-service:github_sync_app_pem: github-sync-app-pem-prod+ cloud-storage-service:github_sync_app_client_id: Iv23ctSZX2wLdqO2iqrSdiff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 688f909228..93590e0955 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -244,6 +244,20 @@ export const deleteChatQueueName = deleteChatHandler.queue.name;const MACRO_API_TOKENS = getMacroApiToken();+const GITHUB_SYNC_APP_URL = config.require('github_sync_app_url');++const GITHUB_WEBHOOK_SECRET_KEY = config.require('github_webhook_secret_key');+const githubWebhookSecretKeyArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: GITHUB_WEBHOOK_SECRET_KEY })+ .apply((secret) => secret.arn);++const GITHUB_SYNC_APP_PEM_SECRET_KEY = config.require('github_sync_app_pem');+const githubSyncAppPemArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: GITHUB_SYNC_APP_PEM_SECRET_KEY })+ .apply((secret) => secret.arn);++const GITHUB_SYNC_APP_CLIENT_ID = config.require('github_sync_app_client_id');+const cloudStorageService = new CloudStorageService(`cloud-storage-service-${stack}`,{@@ -273,6 +287,8 @@ const cloudStorageService = new CloudStorageService(authenticationServiceSecretKeyArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,opensearchPasswordArn,+ githubWebhookSecretKeyArn,+ githubSyncAppPemArn,],containerEnvVars: [{@@ -416,6 +432,22 @@ const cloudStorageService = new CloudStorageService(name: 'CONTACTS_QUEUE',value: pulumi.interpolate`${contactsQueueName}`,},+ {+ name: 'GITHUB_WEBHOOK_SECRET_KEY',+ value: GITHUB_WEBHOOK_SECRET_KEY,+ },+ {+ name: 'GITHUB_SYNC_APP_URL',+ value: GITHUB_SYNC_APP_URL,+ },+ {+ name: 'GITHUB_SYNC_APP_PEM_SECRET_KEY',+ value: GITHUB_SYNC_APP_PEM_SECRET_KEY,+ },+ {+ name: 'GITHUB_SYNC_APP_CLIENT_ID',+ value: GITHUB_SYNC_APP_CLIENT_ID,+ },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex 588f9200b1..a447afd558 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -260,41 +260,6 @@ export const verifyEmailLink = async (} as verifyEmailLinkResponse;};-/**- * @summary Redirects the user to the github sync app installation page.- */-export type installSyncResponse307 = {- data: void;- status: 307;-};-export type installSyncResponseError = installSyncResponse307 & {- headers: Headers;-};--export type installSyncResponse = installSyncResponseError;--export const getInstallSyncUrl = () => {- return `/github/install-sync`;-};--export const installSync = async (- options?: RequestInit-): Promise<installSyncResponse> => {- const res = await fetch(getInstallSyncUrl(), {- ...options,- method: 'GET',- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: installSyncResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as installSyncResponse;-};-/*** @summary Health check*/diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex a3ef08d487..99026b15e1 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -178,18 +178,6 @@}}},- "/github/install-sync": {- "get": {- "tags": ["github::inbound::github_sync_router"],- "summary": "Redirects the user to the github sync app installation page.",- "operationId": "install_sync",- "responses": {- "307": {- "description": "Redirects to the github sync app installation page"- }- }- }- },"/health": {"get": {"tags": ["health"],diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 925cb0944b..3bbe52c0f6 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -2498,6 +2498,18 @@}}},+ "/github/install-sync": {+ "get": {+ "tags": ["github::inbound::github_sync_router"],+ "summary": "Redirects the user to the github sync app installation page.",+ "operationId": "install_sync",+ "responses": {+ "307": {+ "description": "Redirects to the github sync app installation page"+ }+ }+ }+ },"/health": {"get": {"tags": ["health"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex db3fb74b58..310dfe0fed 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2889,6 +2889,7 @@ dependencies = ["entity_access","frecency","futures",+ "github","hex","http-body-util","jsonwebtoken",diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.tomlindex 45f44eb08b..610833d2d7 100644--- a/rust/cloud-storage/authentication_service/Cargo.toml+++ b/rust/cloud-storage/authentication_service/Cargo.toml@@ -43,7 +43,11 @@ doppleganger = { workspace = true }email_validator = { path = "../email_validator" }fusionauth = { path = "../fusionauth" }futures = { workspace = true }-github = { path = "../github" }+github = { path = "../github", default-features = false, features = [+ "axum",+ "link",+ "outbound",+] }http-body-util = { workspace = true }jsonwebtoken = { workspace = true }last_online_tracker = { path = "../last_online_tracker" }diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex 2caf16bbf4..2314a0fbe8 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -1,7 +1,7 @@use std::sync::Arc;use axum::extract::FromRef;-use github::domain::service::GithubServiceImpl;+use github::domain::service::GithubLinkServiceImpl;use github::outbound::github_auth_client::GithubAuthImpl;use github::outbound::github_oauth_client::GithubOauthImpl;use github::outbound::pg_github_repo::PgGithubRepo;@@ -44,13 +44,13 @@ pub(crate) type NotificationIngressType = NotificationIngressService<StateMachine,>;-pub(crate) type GithubServiceType =- GithubServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;+pub(crate) type GithubLinkServiceType =+ GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {pub db: PgPool,- pub github_service: Arc<GithubServiceType>,+ pub github_link_service: Arc<GithubLinkServiceType>,pub auth_client: Arc<fusionauth::FusionAuthClient>,pub macro_cache_client: Arc<MacroCache>,pub stripe_client: Arc<stripe::Client>,diff --git a/rust/cloud-storage/authentication_service/src/api/link/github.rs b/rust/cloud-storage/authentication_service/src/api/link/github.rsindex c7a2797f07..b50f316fd5 100644--- a/rust/cloud-storage/authentication_service/src/api/link/github.rs+++ b/rust/cloud-storage/authentication_service/src/api/link/github.rs@@ -4,7 +4,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Response},};-use github::domain::{models::GithubError, ports::GithubService};+use github::domain::{models::GithubError, ports::GithubLinkService};use crate::api::{context::ApiContext, oauth2::OAuthState};@@ -113,7 +113,7 @@ pub async fn init_github_link_handler(let redirect_uri = crate::api::oauth2::format_redirect_uri("github");let authorization_url = ctx- .github_service+ .github_link_service.construct_oauth_url(&redirect_uri, state).map_err(InitGithubLinkError::GithubServiceError)?;diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rsindex e2c5e4031c..795feadeb9 100644--- a/rust/cloud-storage/authentication_service/src/api/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs@@ -2,7 +2,6 @@ use crate::api::context::ApiContext;use anyhow::Context;use axum::Router;use axum::http::HeaderName;-use github::inbound::github_sync_router::{GithubSyncRouterState, github_sync_router};use macro_auth::constant::MACRO_REFRESH_TOKEN_HEADER;use native_app_service::inbound::RouterState;use tower::ServiceBuilder;@@ -66,17 +65,12 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(}fn api_router(state: ApiContext) -> Router<ApiContext> {- let github_sync_router_state = GithubSyncRouterState {- service: state.github_service.clone(),- };-Router::new().merge(native_app_service::inbound::native_app_router(RouterState {inner: state.native_app_service.clone(),},))- .nest("/github", github_sync_router(github_sync_router_state)).nest("/internal", internal::router()).nest("/permissions", permissions::router(state.jwt_args.clone())).nest("/login", login::router(state.clone()))@@ -107,7 +101,7 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {.nest("/session", session::router()).nest("/webhooks",- webhooks::router(state).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(+ webhooks::router().layer(ServiceBuilder::new().layer(axum::middleware::from_fn(macro_middleware::connection_drop_prevention_handler,))),)diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rsindex b6a6372213..d7510249b9 100644--- a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs@@ -3,7 +3,7 @@ use axum::{Json,response::{Html, IntoResponse, Response},};-use github::domain::{models::GithubError, ports::GithubService};+use github::domain::{models::GithubError, ports::GithubLinkService};use macro_user_id::{cowlike::CowLike, user_id::MacroUserId};use model::response::ErrorResponse;use tower_cookies::Cookies;@@ -78,7 +78,7 @@ async fn link_user(.map(|id| id.into_owned().lowercase()).context("valid macro user id")?;- ctx.github_service+ ctx.github_link_service.link_user(¯o_user_id,&fusionauth_user_id,diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 2f59b0ecf8..315aed03d5 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -122,9 +122,6 @@ use model::user::{/// /mergemerge::create_merge_request::handler,merge::verify_merge_request::handler,-- /// /github- github::inbound::github_sync_router::install_sync_handler,),components(schemas(diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rsindex 04bf922434..c40aea6a0e 100644--- a/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs@@ -1,16 +1,9 @@use crate::api::context::ApiContext;use axum::Router;-use github::inbound::webhook_router::{GithubWebhookRouterState, github_webhook_router};pub(in crate::api) mod user;/// Webhook endpoints that use internal api key authentication-pub fn router(state: ApiContext) -> Router<ApiContext> {- let github_webhook_router_state = GithubWebhookRouterState {- service: state.github_service,- };-- Router::new()- .merge(github_webhook_router(github_webhook_router_state))- .nest("/user", user::router())+pub fn router() -> Router<ApiContext> {+ Router::new().nest("/user", user::router())}diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex fa17925a97..d4310a3c7c 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -68,14 +68,6 @@ pub struct Config {pub github_client_secret: String,/// The github idp idpub github_idp_id: String,- /// The github webhook secret key- pub github_webhook_secret_key: String,- /// The github sync app url- pub github_sync_app_url: String,- /// The github sync app PEM secret key name- pub github_sync_app_pem: String,- /// The github sync app client id- pub github_sync_app_client_id: String,}impl Config {@@ -135,18 +127,6 @@ impl Config {let github_idp_id =std::env::var("GITHUB_IDP_ID").context("GITHUB_IDP_ID must be provided")?;- let github_webhook_secret_key = std::env::var("GITHUB_WEBHOOK_SECRET_KEY")- .context("GITHUB_WEBHOOK_SECRET_KEY must be provided")?;-- let github_sync_app_url =- std::env::var("GITHUB_SYNC_APP_URL").context("GITHUB_SYNC_APP_URL must be provided")?;-- let github_sync_app_pem =- std::env::var("GITHUB_SYNC_APP_PEM").context("GITHUB_SYNC_APP_PEM must be provided")?;-- let github_sync_app_client_id = std::env::var("GITHUB_SYNC_APP_CLIENT_ID")- .context("GITHUB_SYNC_APP_CLIENT_ID must be provided")?;-Ok(Config {base_url,database_url,@@ -170,10 +150,6 @@ impl Config {github_client_id,github_client_secret,github_idp_id,- github_webhook_secret_key,- github_sync_app_url,- github_sync_app_pem,- github_sync_app_client_id,})}}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex c9227f4c82..6af2715a7f 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -2,7 +2,7 @@ use anyhow::Context;use config::{Config, Environment};use document_storage_service_client::DocumentStorageServiceClient;use github::{- domain::service::{GithubConfig, GithubServiceImpl},+ domain::service::{GithubLinkConfig, GithubLinkServiceImpl},outbound::{github_auth_client::GithubAuthImpl, github_oauth_client::GithubOauthImpl,pg_github_repo::PgGithubRepo,@@ -136,24 +136,6 @@ async fn main() -> anyhow::Result<()> {.to_string(),};- let github_webhook_secret = match config.environment {- Environment::Local => config.github_webhook_secret_key.clone(),- _ => secretsmanager_client- .get_secret_value(&config.github_webhook_secret_key)- .await- .context("unable to get secret")?- .to_string(),- };-- let github_sync_app_pem = match config.environment {- Environment::Local => config.github_sync_app_pem.clone(),- _ => secretsmanager_client- .get_secret_value(&config.github_sync_app_pem)- .await- .context("unable to get github sync app pem secret")?- .to_string(),- };-let auth_client = fusionauth::FusionAuthClient::new(config.fusionauth_tenant_id,fusionauth_api_key,@@ -246,25 +228,21 @@ async fn main() -> anyhow::Result<()> {user_roles_and_permissions_service.clone(),);- let github_service_impl = GithubServiceImpl::new(+ let github_link_service_impl = GithubLinkServiceImpl::new(PgGithubRepo::new(db.clone()),GithubOauthImpl::default(),GithubAuthImpl::new(auth_client.clone(), redis_multiplexed_conn),- GithubConfig {+ GithubLinkConfig {client_id: config.github_client_id,client_secret: config.github_client_secret,idp_id: config.github_idp_id,- webhook_secret: github_webhook_secret,- github_sync_app_url: config.github_sync_app_url,- sync_app_pem: github_sync_app_pem,- sync_app_client_id: config.github_sync_app_client_id,},);api::setup_and_serve(ApiContext {db,- github_service: Arc::new(github_service_impl),+ github_link_service: Arc::new(github_link_service_impl),auth_client: Arc::new(auth_client),macro_cache_client: Arc::new(macro_cache_client),stripe_client: Arc::new(stripe_client),diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 24dc38435d..6453e185b5 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -130,6 +130,7 @@ uuid = { workspace = true }zip = { workspace = true }comms_db_client = { path = "../comms_db_client" }comms_service = { path = "../comms_service" }+github = { path = "../github", default-features= false, features = ["inbound", "axum", "sync"]}[dev-dependencies]cool_asserts = "2"diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 1fc9454f70..57f15a3fbd 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -21,6 +21,7 @@ use dynamodb_client::DynamodbClient;use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};+use github::domain::service::GithubSyncServiceImpl;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_sha_count_client::Redis;@@ -117,11 +118,14 @@ pub(crate) type CommsState = CommsRouterState<CommsChannelService>;pub(crate) type DssChannelsState =ChannelsRouterState<ChannelMessagesServiceImpl<PgChannelMessagesRepo>, PgChannelAccessCheck>;+pub(crate) type GithubSyncServiceType = GithubSyncServiceImpl;+#[derive(Clone, FromRef)]pub(crate) struct ApiContext {pub db: PgPool,pub redis_client: Arc<Redis>,pub s3_client: Arc<S3>,+ pub github_sync_service: Arc<GithubSyncServiceType>,pub dynamodb_client: Arc<DynamodbClient>,pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex d733814169..f786ceecb2 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -7,6 +7,7 @@ use axum::http::Method;use axum::middleware::Next;use comms_service::CommsHandlerState;use context::InternalFlag;+use github::inbound::github_sync_router::GithubSyncRouterState;use macro_axum_utils::compose_layers;use model::version::{ServiceNameState, VersionedApiServiceName, validate_api_version};use properties_service::PropertiesHandlerState;@@ -88,7 +89,17 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {}fn api_router(state: ApiContext) -> Router {+ let github_sync_service_router_state = GithubSyncRouterState {+ service: state.github_sync_service.clone(),+ };+let internal_router = Router::new()+ .nest(+ "/github",+ github::inbound::github_sync_router::github_sync_router(+ github_sync_service_router_state,+ ),+ ).nest("/documents",documents::router(state.clone())diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex e0cafbf987..4508cf8702 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -224,6 +224,9 @@ use utoipa::OpenApi;saved_views::delete_view_handler,saved_views::patch_view_handler,saved_views::exclude_default_view_handler,++ // /github+ github::inbound::github_sync_router::install_sync_handler),components(schemas(diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rsindex 8a02bf4aea..65f44c0bc6 100644--- a/rust/cloud-storage/document_storage_service/src/config.rs+++ b/rust/cloud-storage/document_storage_service/src/config.rs@@ -53,6 +53,8 @@ env_var! {pub OpensearchUsername,pub OpensearchPassword,pub ContactsQueue,+ pub GithubSyncAppUrl,+ pub GithubSyncAppClientId,}}@@ -65,6 +67,13 @@ env_var! {#[derive(Clone)]pub struct DocumentPermissionJwtSecretKey;}+env_var! {+ pub struct GithubWebhookSecretKey;+}++env_var! {+ pub struct GithubSyncAppPemSecretKey;+}impl Config {pub fn from_env(diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 7687a60140..9a748efcf1 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -2,6 +2,7 @@ use crate::{api::context::{ApiContext, DocumentStorageServiceAuthKey, TaskPropertiesAdapter},config::{DocumentPermissionJwtSecretKey, DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,+ GithubSyncAppPemSecretKey, GithubWebhookSecretKey,},service::s3::S3,};@@ -26,6 +27,7 @@ use documents_hex::outbound::s3_upload_url::S3UploadUrlAdapter;use dynamodb_client::DynamodbClient;use email::{domain::service::EmailServiceImpl, outbound::EmailPgRepo};use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};+use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_entrypoint::MacroEntrypoint;use macro_middleware::auth::internal_access::InternalApiSecretKey;@@ -312,6 +314,21 @@ async fn main() -> anyhow::Result<()> {db.clone(),);+ let github_webhook_secret = secretsmanager_client+ .get_maybe_secret_value(env, GithubWebhookSecretKey::new()?)+ .await?;++ let github_sync_app_pem = secretsmanager_client+ .get_maybe_secret_value(env, GithubSyncAppPemSecretKey::new()?)+ .await?;++ let github_sync_service_impl = GithubSyncServiceImpl::new(GithubSyncConfig {+ webhook_secret: github_webhook_secret.as_ref().to_string(),+ github_sync_app_url: config.vars.github_sync_app_url.to_string(),+ sync_app_pem: github_sync_app_pem.as_ref().to_string(),+ sync_app_client_id: config.vars.github_sync_app_client_id.to_string(),+ });+let api_context = ApiContext {soup_router_state: SoupRouterState::new(SoupImpl::new(@@ -322,6 +339,7 @@ async fn main() -> anyhow::Result<()> {),email_service,),+ github_sync_service: Arc::new(github_sync_service_impl),db: db.clone(),redis_client: Arc::new(Redis::new(redis_client)),s3_client: s3,diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex b160112a1f..8e97e8a8e3 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -5,8 +5,10 @@ publish = falseversion = "0.1.0"[features]-default = ["ports", "inbound", "outbound", "axum"]+default = ["ports", "sync", "link", "inbound", "outbound", "axum"]ports = []+sync = ["dep:reqwest", "ports"]+link = ["ports"]inbound = ["axum", "ports"]outbound = ["dep:sqlx",diff --git a/rust/cloud-storage/github/src/domain.rs b/rust/cloud-storage/github/src/domain.rsindex a947d9653b..27f5f2daa1 100644--- a/rust/cloud-storage/github/src/domain.rs+++ b/rust/cloud-storage/github/src/domain.rs@@ -5,5 +5,5 @@ pub mod models;#[cfg(feature = "ports")]pub mod ports;-#[cfg(feature = "ports")]+#[cfg(any(feature = "sync", feature = "link"))]pub mod service;diff --git a/rust/cloud-storage/github/src/domain/ports.rs b/rust/cloud-storage/github/src/domain/ports.rsindex dab97f8048..5ddc3457a3 100644--- a/rust/cloud-storage/github/src/domain/ports.rs+++ b/rust/cloud-storage/github/src/domain/ports.rs@@ -106,27 +106,10 @@ pub trait Auth: Send + Sync + 'static {) -> impl Future<Output = Result<GithubAccessToken, Self::Err>>;}-/// Service interface for github operations.+/// Service interface for github sync operations (webhooks and sync app).///-/// Orchestrates business logic using the repository and external services.-pub trait GithubService: Send + Sync + 'static {- /// Constructs the oauth url to authenticate with github- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(- &self,- redirect_uri: &str,- state: T,- ) -> Result<String, GithubError>;-- /// Uses token exchange to link the user to the github account- fn link_user(- &self,- user_id: &MacroUserId<Lowercase<'static>>,- fusionauth_user_id: &uuid::Uuid,- in_progress_user_link: &uuid::Uuid,- redirect_uri: &str,- code: &str,- ) -> impl Future<Output = Result<GithubLink, GithubError>> + Send;-+/// Handles webhook validation/processing and sync app installation token generation.+pub trait GithubSyncService: Send + Sync + 'static {/// Validates the incoming webhook event and returns back the `ValidatedGithubWebhookEvent`fn validate_webhook_event(&self,@@ -150,3 +133,25 @@ pub trait GithubService: Send + Sync + 'static {installation_id: u64,) -> impl Future<Output = Result<GithubInstallationAccessToken, GithubError>> + Send;}++/// Service interface for github link operations (OAuth and account linking).+///+/// Handles OAuth URL construction and user account linking.+pub trait GithubLinkService: Send + Sync + 'static {+ /// Constructs the oauth url to authenticate with github+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(+ &self,+ redirect_uri: &str,+ state: T,+ ) -> Result<String, GithubError>;++ /// Uses token exchange to link the user to the github account+ fn link_user(+ &self,+ user_id: &MacroUserId<Lowercase<'static>>,+ fusionauth_user_id: &uuid::Uuid,+ in_progress_user_link: &uuid::Uuid,+ redirect_uri: &str,+ code: &str,+ ) -> impl Future<Output = Result<GithubLink, GithubError>> + Send;+}diff --git a/rust/cloud-storage/github/src/domain/service/mod.rs b/rust/cloud-storage/github/src/domain/service/mod.rsindex 44a79766ca..91ede3c7c3 100644--- a/rust/cloud-storage/github/src/domain/service/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/mod.rs@@ -3,34 +3,12 @@#[cfg(test)]mod test;-use chrono::Utc;-use macro_user_id::{- lowercased::Lowercase,- user_id::{MacroUserId, MacroUserIdStr},-};--use crate::domain::{- models::{- GithubError, GithubInstallationAccessToken, GithubLink, GithubWebhookEventType,- MacroTaskId, ValidatedGithubWebhookEvent,- },- ports::{Auth, GithubOauth, GithubRepo, GithubService},-};--use hmac::{Hmac, Mac};-use sha2::Sha256;-use subtle::ConstantTimeEq;-type HmacSha256 = Hmac<Sha256>;--/// Github config+use crate::domain::models::GithubError;++/// Github sync config+#[cfg(feature = "sync")]#[derive(Debug)]-pub struct GithubConfig {- /// The github application client id- pub client_id: String,- /// The github application client secret- pub client_secret: String,- /// The id of the github identity provider in fusionauth- pub idp_id: String,+pub struct GithubSyncConfig {/// The webhook secret used to validate github webhook eventspub webhook_secret: String,/// The url to the github sync app installation page@@ -41,260 +19,328 @@ pub struct GithubConfig {pub sync_app_client_id: String,}-/// The concrete github service implementation.-pub struct GithubServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {- repo: R,- oauth: U,- auth: F,- config: GithubConfig,+/// Github link config+#[cfg(feature = "link")]+#[derive(Debug)]+pub struct GithubLinkConfig {+ /// The github application client id+ pub client_id: String,+ /// The github application client secret+ pub client_secret: String,+ /// The id of the github identity provider in fusionauth+ pub idp_id: String,}-impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubServiceImpl<R, U, F> {- /// Create a new github service.- pub fn new(repo: R, oauth: U, auth: F, config: GithubConfig) -> Self {- Self {- repo,- oauth,- auth,- config,- }+// ── Sync service ──────────────────────────────────────────────────────++#[cfg(feature = "sync")]+mod sync_impl {+ use super::*;+ use crate::domain::{+ models::{+ GithubInstallationAccessToken, GithubWebhookEventType, MacroTaskId,+ ValidatedGithubWebhookEvent,+ },+ ports::GithubSyncService,+ };+ use hmac::{Hmac, Mac};+ use sha2::Sha256;+ use subtle::ConstantTimeEq;+ type HmacSha256 = Hmac<Sha256>;++ /// The concrete github sync service implementation.+ pub struct GithubSyncServiceImpl {+ config: super::GithubSyncConfig,}-}-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,- redirect_uri: &str,- state: T,- ) -> Result<String, GithubError> {- self.oauth- .construct_oauth_url(&self.config.client_id, redirect_uri, state)- .map_err(|e| GithubError::Internal(e.into()))+ impl GithubSyncServiceImpl {+ /// Create a new github sync service.+ pub fn new(config: super::GithubSyncConfig) -> Self {+ Self { config }+ }}- #[tracing::instrument(skip(self), err)]- async fn link_user(- &self,- user_id: &MacroUserId<Lowercase<'static>>,- fusionauth_user_id: &uuid::Uuid,- in_progess_link_id: &uuid::Uuid,- redirect_uri: &str,- code: &str,- ) -> Result<GithubLink, GithubError> {- let tokens = self- .oauth- .exchange_oauth_code_for_tokens(- &self.config.client_id,- &self.config.client_secret,- redirect_uri,- code,- )- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let user_info = self- .oauth- .get_user_info(&tokens.access_token)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- tracing::trace!(user_info=?user_info, "got user info");-- // Check if Github account is already linked to a different user- match self- .repo- .get_github_link_by_github_user_id(&user_info.id.to_string())- .await- {- Ok(link) => {- if !link.macro_id.0.eq(user_id) {- return Err(GithubError::AccountAlreadyLinked);- }+ impl GithubSyncService for GithubSyncServiceImpl {+ #[tracing::instrument(skip(self, body), err)]+ async fn validate_webhook_event(+ &self,+ event_type: &str,+ signature: &str,+ body: &[u8],+ ) -> Result<ValidatedGithubWebhookEvent, GithubError> {+ let sig_bytes =+ hex::decode(signature).map_err(|_| GithubError::InvalidWebhookSignature)?;++ let mut mac = HmacSha256::new_from_slice(self.config.webhook_secret.as_bytes())+ .map_err(|e| GithubError::Internal(e.into()))?;++ mac.update(body);+ let expected = mac.finalize().into_bytes();++ // constant-time comparison+ if expected.as_slice().ct_eq(&sig_bytes).into() {+ Ok(ValidatedGithubWebhookEvent::new(+ event_type.to_string(),+ serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,+ ))+ } else {+ Err(GithubError::InvalidWebhookSignature)}- Err(e) => {- let err: anyhow::Error = e.into();- // We should only error if the error is something other- // than the link not existing- if !err.to_string().contains("no rows returned") {- return Err(GithubError::Internal(err));+ }++ #[tracing::instrument(skip(self, webhook_event), err)]+ async fn process_webhook_event(+ &self,+ webhook_event: &ValidatedGithubWebhookEvent,+ ) -> Result<(), GithubError> {+ let event_type = webhook_event.parsed_event_type();+ tracing::info!(event_type=?event_type, "processing github webhook event");++ if let GithubWebhookEventType::Unknown(ref name) = event_type {+ tracing::debug!(event_type=%name, "skipping unknown event type");+ return Ok(());+ }++ let searchable_texts = webhook_event.extract_searchable_text();+ let combined = searchable_texts.join(" ");+ let task_ids = MacroTaskId::extract_from_text(&combined);++ if task_ids.is_empty() {+ tracing::debug!(event_type=?event_type, "no task IDs found in event");+ return Ok(());+ }++ for task_id in &task_ids {+ match task_id.to_uuid() {+ Ok(uuid) => {+ tracing::info!(+ task_id=%task_id,+ uuid=%uuid,+ event_type=?event_type,+ "detected macro task ID in github event"+ );+ }+ Err(e) => {+ tracing::warn!(+ task_id=%task_id,+ error=?e,+ "failed to convert task ID to UUID"+ );+ }}}++ Ok(())+ }++ fn get_github_sync_app_url(&self) -> &str {+ &self.config.github_sync_app_url+ }++ #[tracing::instrument(skip(self), err)]+ async fn generate_installation_access_token(+ &self,+ installation_id: u64,+ ) -> Result<GithubInstallationAccessToken, GithubError> {+ let now = chrono::Utc::now().timestamp() as u64;++ let claims = serde_json::json!({+ "iat": now - 60,+ "exp": now + (10 * 60),+ "iss": self.config.sync_app_client_id,+ });++ let header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);+ let encoding_key =+ jsonwebtoken::EncodingKey::from_rsa_pem(self.config.sync_app_pem.as_bytes())+ .map_err(|e| GithubError::Internal(anyhow::anyhow!("invalid PEM key: {e}")))?;++ let jwt = jsonwebtoken::encode(&header, &claims, &encoding_key)+ .map_err(|e| GithubError::Internal(anyhow::anyhow!("failed to encode JWT: {e}")))?;++ let client = reqwest::Client::new();+ let response = client+ .post(format!(+ "https://api.github.com/app/installations/{installation_id}/access_tokens"+ ))+ .header("Authorization", format!("Bearer {jwt}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Macro-Auth-Service")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .send()+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ let status = response.status();+ if !status.is_success() {+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "unknown error".to_string());+ return Err(GithubError::Internal(anyhow::anyhow!(+ "failed to create installation access token (status {status}): {error_body}"+ )));+ }++ let token: GithubInstallationAccessToken = response+ .json()+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ Ok(token)}+ }+}- self.auth- .link_user(- fusionauth_user_id,- &self.config.idp_id,- &user_info.id.to_string(),- &user_info.login,- &tokens.access_token,- )- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- tracing::trace!("linked auth user");-- // create github link- let link = GithubLink {- id: macro_uuid::generate_uuid_v7(),- macro_id: MacroUserIdStr(user_id.clone()),- fusionauth_user_id: *fusionauth_user_id,- github_username: user_info.login.clone(),- github_user_id: user_info.id.to_string(),- created_at: Utc::now(),- updated_at: Utc::now(),- };-- tracing::debug!(- fusionauth_user_id=%fusionauth_user_id,- github_user_id=%user_info.id,- github_username=%user_info.login,- "creating github_links record"- );-- self.repo- .insert_github_link(&link)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- tracing::trace!("successfully linked github account");-- // SAFETY: this is ok to fail as we have an auto cleanup job for this table- 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"));-- Ok(link)+#[cfg(feature = "sync")]+pub use sync_impl::*;++// ── Link service ──────────────────────────────────────────────────────++#[cfg(feature = "link")]+mod link_impl {+ use super::*;+ use chrono::Utc;+ use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+ };++ use crate::domain::{+ models::GithubLink,+ ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},+ };++ /// The concrete github link service implementation.+ pub struct GithubLinkServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {+ repo: R,+ oauth: U,+ auth: F,+ config: super::GithubLinkConfig,}- #[tracing::instrument(skip(self, body), err)]- async fn validate_webhook_event(- &self,- event_type: &str,- signature: &str,- body: &[u8],- ) -> Result<ValidatedGithubWebhookEvent, GithubError> {- let sig_bytes = hex::decode(signature).map_err(|_| GithubError::InvalidWebhookSignature)?;-- let mut mac = HmacSha256::new_from_slice(self.config.webhook_secret.as_bytes())- .map_err(|e| GithubError::Internal(e.into()))?;-- mac.update(body);- let expected = mac.finalize().into_bytes();-- // constant-time comparison- if expected.as_slice().ct_eq(&sig_bytes).into() {- Ok(ValidatedGithubWebhookEvent::new(- event_type.to_string(),- serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,- ))- } else {- Err(GithubError::InvalidWebhookSignature)+ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {+ /// Create a new github link service.+ pub fn new(repo: R, oauth: U, auth: F, config: super::GithubLinkConfig) -> Self {+ Self {+ repo,+ oauth,+ auth,+ config,+ }}}- #[tracing::instrument(skip(self, webhook_event), err)]- async fn process_webhook_event(- &self,- webhook_event: &ValidatedGithubWebhookEvent,- ) -> Result<(), GithubError> {- let event_type = webhook_event.parsed_event_type();- tracing::info!(event_type=?event_type, "processing github webhook event");-- if let GithubWebhookEventType::Unknown(ref name) = event_type {- tracing::debug!(event_type=%name, "skipping unknown event type");- return Ok(());+ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkServiceImpl<R, U, F> {+ #[tracing::instrument(skip(self), err)]+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(+ &self,+ redirect_uri: &str,+ state: T,+ ) -> Result<String, GithubError> {+ self.oauth+ .construct_oauth_url(&self.config.client_id, redirect_uri, state)+ .map_err(|e| GithubError::Internal(e.into()))}- let searchable_texts = webhook_event.extract_searchable_text();- let combined = searchable_texts.join(" ");- let task_ids = MacroTaskId::extract_from_text(&combined);+ #[tracing::instrument(skip(self), err)]+ async fn link_user(+ &self,+ user_id: &MacroUserId<Lowercase<'static>>,+ fusionauth_user_id: &uuid::Uuid,+ in_progess_link_id: &uuid::Uuid,+ redirect_uri: &str,+ code: &str,+ ) -> Result<GithubLink, GithubError> {+ let tokens = self+ .oauth+ .exchange_oauth_code_for_tokens(+ &self.config.client_id,+ &self.config.client_secret,+ redirect_uri,+ code,+ )+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ let user_info = self+ .oauth+ .get_user_info(&tokens.access_token)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;- if task_ids.is_empty() {- tracing::debug!(event_type=?event_type, "no task IDs found in event");- return Ok(());- }+ tracing::trace!(user_info=?user_info, "got user info");- for task_id in &task_ids {- match task_id.to_uuid() {- Ok(uuid) => {- tracing::info!(- task_id=%task_id,- uuid=%uuid,- event_type=?event_type,- "detected macro task ID in github event"- );+ // Check if Github account is already linked to a different user+ match self+ .repo+ .get_github_link_by_github_user_id(&user_info.id.to_string())+ .await+ {+ Ok(link) => {+ if !link.macro_id.0.eq(user_id) {+ return Err(GithubError::AccountAlreadyLinked);+ }}Err(e) => {- tracing::warn!(- task_id=%task_id,- error=?e,- "failed to convert task ID to UUID"- );+ let err: anyhow::Error = e.into();+ // We should only error if the error is something other+ // than the link not existing+ if !err.to_string().contains("no rows returned") {+ return Err(GithubError::Internal(err));+ }}}- }- Ok(())- }+ self.auth+ .link_user(+ fusionauth_user_id,+ &self.config.idp_id,+ &user_info.id.to_string(),+ &user_info.login,+ &tokens.access_token,+ )+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ tracing::trace!("linked auth user");++ // create github link+ let link = GithubLink {+ id: macro_uuid::generate_uuid_v7(),+ macro_id: MacroUserIdStr(user_id.clone()),+ fusionauth_user_id: *fusionauth_user_id,+ github_username: user_info.login.clone(),+ github_user_id: user_info.id.to_string(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ };++ tracing::debug!(+ fusionauth_user_id=%fusionauth_user_id,+ github_user_id=%user_info.id,+ github_username=%user_info.login,+ "creating github_links record"+ );++ self.repo+ .insert_github_link(&link)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;- fn get_github_sync_app_url(&self) -> &str {- &self.config.github_sync_app_url- }+ tracing::trace!("successfully linked github account");- #[tracing::instrument(skip(self), err)]- async fn generate_installation_access_token(- &self,- installation_id: u64,- ) -> Result<GithubInstallationAccessToken, GithubError> {- let now = chrono::Utc::now().timestamp() as u64;-- let claims = serde_json::json!({- "iat": now - 60,- "exp": now + (10 * 60),- "iss": self.config.sync_app_client_id,- });-- let header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);- let encoding_key =- jsonwebtoken::EncodingKey::from_rsa_pem(self.config.sync_app_pem.as_bytes())- .map_err(|e| GithubError::Internal(anyhow::anyhow!("invalid PEM key: {e}")))?;-- let jwt = jsonwebtoken::encode(&header, &claims, &encoding_key)- .map_err(|e| GithubError::Internal(anyhow::anyhow!("failed to encode JWT: {e}")))?;-- let client = reqwest::Client::new();- let response = client- .post(format!(- "https://api.github.com/app/installations/{installation_id}/access_tokens"- ))- .header("Authorization", format!("Bearer {jwt}"))- .header("Accept", "application/vnd.github+json")- .header("User-Agent", "Macro-Auth-Service")- .header("X-GitHub-Api-Version", "2022-11-28")- .send()- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let status = response.status();- if !status.is_success() {- let error_body = response- .text()+ // SAFETY: this is ok to fail as we have an auto cleanup job for this table+ let _ = self+ .repo+ .delete_in_progress_user_link(in_progess_link_id).await- .unwrap_or_else(|_| "unknown error".to_string());- return Err(GithubError::Internal(anyhow::anyhow!(- "failed to create installation access token (status {status}): {error_body}"- )));- }+ .inspect_err(|e| tracing::error!(error=?e, "unable to delete in progress link id"));- let token: GithubInstallationAccessToken = response- .json()- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- Ok(token)+ Ok(link)+ }}}++#[cfg(feature = "link")]+pub use link_impl::*;diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/test.rsindex 6653d10f41..161e4d8b40 100644--- a/rust/cloud-storage/github/src/domain/service/test.rs+++ b/rust/cloud-storage/github/src/domain/service/test.rs@@ -1,30 +1,19 @@-use crate::domain::{- models::ValidatedGithubWebhookEvent,- ports::{GithubService, MockAuth, MockGithubOauth, MockGithubRepo},-};+use crate::domain::{models::ValidatedGithubWebhookEvent, ports::GithubSyncService};use super::*;-fn make_service() -> GithubServiceImpl<MockGithubRepo, MockGithubOauth, MockAuth> {- GithubServiceImpl::new(- MockGithubRepo::new(),- MockGithubOauth::new(),- MockAuth::new(),- GithubConfig {- client_id: "test-client-id".to_string(),- client_secret: "test-client-secret".to_string(),- idp_id: "test-idp-id".to_string(),- webhook_secret: "test-webhook-secret".to_string(),- github_sync_app_url: "test".to_string(),- sync_app_pem: "test-sync-app-pem".to_string(),- sync_app_client_id: "test-sync-app-client-id".to_string(),- },- )+fn make_sync_service() -> GithubSyncServiceImpl {+ GithubSyncServiceImpl::new(GithubSyncConfig {+ webhook_secret: "test-webhook-secret".to_string(),+ github_sync_app_url: "test".to_string(),+ sync_app_pem: "test-sync-app-pem".to_string(),+ sync_app_client_id: "test-sync-app-client-id".to_string(),+ })}#[tokio::test]async fn pr_with_task_id_in_title() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({@@ -43,7 +32,7 @@ async fn pr_with_task_id_in_title() {#[tokio::test]async fn pr_with_task_id_in_branch_name() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({@@ -62,7 +51,7 @@ async fn pr_with_task_id_in_branch_name() {#[tokio::test]async fn issue_comment_with_task_id() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(),serde_json::json!({@@ -79,7 +68,7 @@ async fn issue_comment_with_task_id() {#[tokio::test]async fn event_with_no_task_ids() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({@@ -98,7 +87,7 @@ async fn event_with_no_task_ids() {#[tokio::test]async fn unknown_event_type_skipped() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("ping".to_string(),serde_json::json!({"zen": "Keep it logically awesome."}),@@ -110,7 +99,7 @@ async fn unknown_event_type_skipped() {#[tokio::test]async fn multiple_task_ids_in_one_event() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(),serde_json::json!({@@ -129,7 +118,7 @@ async fn multiple_task_ids_in_one_event() {#[tokio::test]async fn pull_request_review_with_task_id() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request_review".to_string(),serde_json::json!({@@ -146,7 +135,7 @@ async fn pull_request_review_with_task_id() {#[tokio::test]async fn pull_request_review_comment_with_task_id() {- let service = make_service();+ let service = make_sync_service();let event = ValidatedGithubWebhookEvent::new("pull_request_review_comment".to_string(),serde_json::json!({diff --git a/rust/cloud-storage/github/src/inbound.rs b/rust/cloud-storage/github/src/inbound.rsindex f84d5158c9..df5f284e2e 100644--- a/rust/cloud-storage/github/src/inbound.rs+++ b/rust/cloud-storage/github/src/inbound.rs@@ -3,9 +3,6 @@#[cfg(feature = "axum")]pub mod github_sync_router;-#[cfg(feature = "axum")]-pub mod webhook_router;-#[cfg(feature = "axum")]impl axum::response::IntoResponse for crate::domain::models::GithubError {fn into_response(self) -> axum::response::Response {diff --git a/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs b/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rsindex 5f78c3b981..9e5d87be29 100644--- a/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs+++ b/rust/cloud-storage/github/src/inbound/github_sync_router/mod.rs@@ -2,19 +2,27 @@//!//! Provides the following route(s)://! - `GET /install-sync` - redirects to the github sync app installation page+//! - `POST /webhook` - github event webhook handler#[cfg(test)]mod test;+use axum::{+ Router, async_trait,+ extract::{FromRequest, Request, State},+ response::Redirect,+};+use reqwest::StatusCode;use std::sync::Arc;-use axum::{Router, extract::State, response::Redirect};+use crate::domain::{+ models::{GithubError, ValidatedGithubWebhookEvent},+ ports::GithubSyncService,+};-use crate::domain::ports::GithubService;--/// Router state containing the github service.+/// Router state containing the github sync service.pub struct GithubSyncRouterState<T> {- /// The github service implementation.+ /// The github sync service implementation.pub service: Arc<T>,}@@ -30,11 +38,15 @@ impl<T> Clone for GithubSyncRouterState<T> {/// Build the github sync router.pub fn github_sync_router<T, S>(state: GithubSyncRouterState<T>) -> Router<S>where- T: GithubService,+ T: GithubSyncService,S: Send + Sync + 'static,{Router::new().route("/install-sync", axum::routing::get(install_sync_handler))+ .route(+ "/webhook",+ axum::routing::post(github_webhook_event_handler),+ ).with_state(state)}@@ -48,9 +60,69 @@ where))]#[tracing::instrument(skip(ctx))]-pub async fn install_sync_handler<T: GithubService>(+pub async fn install_sync_handler<T: GithubSyncService>(State(ctx): State<GithubSyncRouterState<T>>,) -> Redirect {let url = ctx.service.get_github_sync_app_url();Redirect::temporary(url)}++/// Extractor that validates an incoming GitHub webhook event.+///+/// Reads the `X-Hub-Signature-256` header and the raw request body, then+/// delegates to [`GithubSyncService::validate_webhook_event`] for HMAC+/// verification. On success the extractor yields a+/// [`ValidatedGithubWebhookEvent`].+pub struct GithubWebhookEventExtractor(pub ValidatedGithubWebhookEvent);++#[async_trait]+impl<T> FromRequest<GithubSyncRouterState<T>> for GithubWebhookEventExtractor+where+ T: GithubSyncService,+{+ type Rejection = GithubError;++ async fn from_request(+ req: Request,+ state: &GithubSyncRouterState<T>,+ ) -> Result<Self, Self::Rejection> {+ let (parts, body) = req.into_parts();++ let event_type = parts+ .headers+ .get("X-GitHub-Event")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("unknown");++ let signature = parts+ .headers+ .get("X-Hub-Signature-256")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("sha256="))+ .ok_or(GithubError::InvalidWebhookSignature)?;++ let body = axum::body::to_bytes(body, usize::MAX)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ let event = state+ .service+ .validate_webhook_event(event_type, signature, &body)+ .await?;++ Ok(GithubWebhookEventExtractor(event))+ }+}++/// The main entrypoint for all github webhook events handling+#[tracing::instrument(err, skip(ctx, event))]+pub async fn github_webhook_event_handler<T: GithubSyncService>(+ State(ctx): State<GithubSyncRouterState<T>>,+ GithubWebhookEventExtractor(event): GithubWebhookEventExtractor,+) -> Result<StatusCode, GithubError> {+ tracing::info!("github_webhook");++ ctx.service.process_webhook_event(&event).await?;++ Ok(StatusCode::OK)+}diff --git a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rsindex 94d0c975e3..2f351a89d2 100644--- a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs+++ b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs@@ -2,40 +2,20 @@ use std::sync::Arc;use axum::{Router, http::Request};use http_body_util::BodyExt;-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};use tower::util::ServiceExt;use crate::domain::{- models::{GithubError, GithubInstallationAccessToken, GithubLink, ValidatedGithubWebhookEvent},- ports::GithubService,+ models::{GithubError, GithubInstallationAccessToken, ValidatedGithubWebhookEvent},+ ports::GithubSyncService,};use super::{GithubSyncRouterState, github_sync_router};-struct MockGithubService {+struct MockGithubSyncService {sync_app_url: String,}-impl GithubService for MockGithubService {- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(- &self,- _redirect_uri: &str,- _state: T,- ) -> Result<String, GithubError> {- unimplemented!()- }-- async fn link_user(- &self,- _user_id: &MacroUserId<Lowercase<'static>>,- _fusionauth_user_id: &uuid::Uuid,- _in_progress_user_link: &uuid::Uuid,- _redirect_uri: &str,- _code: &str,- ) -> Result<GithubLink, GithubError> {- unimplemented!()- }-+impl GithubSyncService for MockGithubSyncService {async fn validate_webhook_event(&self,_event_type: &str,@@ -66,7 +46,7 @@ impl GithubService for MockGithubService {fn mock_router(sync_app_url: &str) -> Router {github_sync_router(GithubSyncRouterState {- service: Arc::new(MockGithubService {+ service: Arc::new(MockGithubSyncService {sync_app_url: sync_app_url.to_string(),}),})diff --git a/rust/cloud-storage/github/src/inbound/webhook_router.rs b/rust/cloud-storage/github/src/inbound/webhook_router.rsdeleted file mode 100644index c0ec27632c..0000000000--- a/rust/cloud-storage/github/src/inbound/webhook_router.rs+++ /dev/null@@ -1,104 +0,0 @@-//! Webhook router for github webhook endpoint.-//!-//! Provides the following route(s):-//! - `POST /github` - github event webhook handler--use std::sync::Arc;--use axum::{- Router, async_trait,- extract::{FromRequest, Request, State},-};--use reqwest::StatusCode;--use crate::domain::{- models::{GithubError, ValidatedGithubWebhookEvent},- ports::GithubService,-};--/// Router state containing the github service.-pub struct GithubWebhookRouterState<T> {- /// The github service implementation.- pub service: Arc<T>,-}--// Manual Clone impl so T and Svc don't need to be Clone (they're behind Arc).-impl<T> Clone for GithubWebhookRouterState<T> {- fn clone(&self) -> Self {- Self {- service: self.service.clone(),- }- }-}--/// Extractor that validates an incoming GitHub webhook event.-///-/// Reads the `X-Hub-Signature-256` header and the raw request body, then-/// delegates to [`GithubService::validate_webhook_event`] for HMAC-/// verification. On success the extractor yields a-/// [`ValidatedGithubWebhookEvent`].-pub struct GithubWebhookEventExtractor(pub ValidatedGithubWebhookEvent);--#[async_trait]-impl<T> FromRequest<GithubWebhookRouterState<T>> for GithubWebhookEventExtractor-where- T: GithubService,-{- type Rejection = GithubError;-- async fn from_request(- req: Request,- state: &GithubWebhookRouterState<T>,- ) -> Result<Self, Self::Rejection> {- let (parts, body) = req.into_parts();-- let event_type = parts- .headers- .get("X-GitHub-Event")- .and_then(|v| v.to_str().ok())- .unwrap_or("unknown");-- let signature = parts- .headers- .get("X-Hub-Signature-256")- .and_then(|v| v.to_str().ok())- .and_then(|v| v.strip_prefix("sha256="))- .ok_or(GithubError::InvalidWebhookSignature)?;-- let body = axum::body::to_bytes(body, usize::MAX)- .await- .map_err(|e| GithubError::Internal(e.into()))?;-- let event = state- .service- .validate_webhook_event(event_type, signature, &body)- .await?;-- Ok(GithubWebhookEventExtractor(event))- }-}--/// Build the github webhook router.-pub fn github_webhook_router<T, S>(state: GithubWebhookRouterState<T>) -> Router<S>-where- T: GithubService,- S: Send + Sync + 'static,-{- Router::new()- .route("/github", axum::routing::post(github_webhook_event_handler))- .with_state(state)-}--/// The main entrypoint for all github webhook events handling-#[tracing::instrument(err, skip(ctx, event))]-pub async fn github_webhook_event_handler<T: GithubService>(- State(ctx): State<GithubWebhookRouterState<T>>,- GithubWebhookEventExtractor(event): GithubWebhookEventExtractor,-) -> Result<StatusCode, GithubError> {- tracing::info!("github_webhook");-- ctx.service.process_webhook_event(&event).await?;-- Ok(StatusCode::OK)-}