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): account link (#1689)

Will Hutchinsonb0e93ac5ebc3
diff --git a/.env-local.enc b/.env-local.enc
index 9ad042a166..fd22a2ca0a 100644
--- a/.env-local.enc
+++ b/.env-local.enc
@@ -111,6 +111,9 @@ UPLOAD_STAGING_BUCKET=ENC[AES256_GCM,data:ASHagESORsY4QmOeWZPkJzeACPaQ,iv:N+XLH1
WEB_SOCKET_RESPONSE_LAMBDA=ENC[AES256_GCM,data:URkQ9NZGXr0fSm7dOs8UwXBXykXz+rk2GZdtBHVSHA==,iv:ViweUSflVusTKUyJ6p0rscoFFwsPk5eR1LxknpGWuaI=,tag:LTfK4XjbqakpGK7lI4q8vw==,type:str]
XAI_API_KEY=ENC[AES256_GCM,data:+eZ6pftcmKf/kwn0VHfx4CesEIwKBW9yB1VmrapPVpHV1CRMHxPQFC95mXQwwcpy/0mW1IY9gZGgM9UlSLUqdRHk7oQFhq2J5ccXHAGJIbbt39KJ4oY=,iv:K0MppoAokAnWapBvzUxNnjo8JhXyGhbgkwpLI5SvIdo=,tag:0SbjWtEbe7A52WniSexLSg==,type:str]
LOCAL_AWS_URL=ENC[AES256_GCM,data:5Hz1NHrCE5PdPR6yTgFsvanHkad2D40P,iv:74PiL6QEaojA1fm32fXOgTJi9glKatjsy//Sa8kBMNU=,tag:NdteMC7dwpoIArEtOdWBbQ==,type:str]
+GITHUB_CLIENT_ID=ENC[AES256_GCM,data:nkmCK+VXg4lVXED/b7yuyNPJOKOMcw==,iv:Mt5y4n5knetuYCEZrU+EBj8CHPV6n7KHhlb4J6eYVUE=,tag:BwApGD/p7cpinF8AYNBTxA==,type:str]
+GITHUB_CLIENT_SECRET=ENC[AES256_GCM,data:TIiBV2M+SxxjpLxbUl/FKLQYHVDpvQKu4mr1mZIMbGpvFjYFUpMojeqC,iv:lXcGPgT7zWQkDxLvJ6Vm2ce/vkm5uUXQdL8XCOXHGOw=,tag:dY2NOQLmdaoi+PaHBunEiQ==,type:str]
+GITHUB_IDP_ID=ENC[AES256_GCM,data:VYpBXEr6t920d4BehwQK1Brgbf6OWpfTdjWmhOK+QYG7a+7+YRQ=,iv:JcZwmRchvWFDQCC2g9pvAMiaKXbiCas7LSBAxdcV6Dw=,tag:vIenBnCQBSkF9U7o29jvxA==,type:str]
sops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93
sops_kms__list_0__map_aws_profile=
sops_kms__list_0__map_created_at=2026-02-03T14:47:22Z
@@ -119,7 +122,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480
sops_kms__list_1__map_aws_profile=
sops_kms__list_1__map_created_at=2026-02-03T14:47:22Z
sops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wGvSsy0EhK25Hy2hdoR6HqoAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMHViQzKBwIGY72CWCAgEQgDtKthF4DIo1QiM2scSmXVBT624sUjTxO+jwAUipQ5Xc50oLOUa/tbaIiwNN1wE5AI48o8NPmyh2OoAeZw==
-sops_lastmodified=2026-02-19T20:43:28Z
-sops_mac=ENC[AES256_GCM,data:51dEnuinm4Jh8RlvMuhMB2ST2uxVHGCigXMeJmrZjJOPxxTNCasrTDlafvGeBmAfc/wIp6xZhiGvoNjHzfl9rck2+4vjKNKYG7BC/gYonrpzvEkR+Zlj5+Xq+IoPL2feGkIAUGN6mU5/wJnZq0tayUv6bzTO7b8QfslM1JgKkSw=,iv:zO+Oo+Pb099IQ4EXLti3mfAnW0QK/YUphyhUReVDMLg=,tag:4DlegTv9hEG3foOLnExrfQ==,type:str]
+sops_lastmodified=2026-02-26T17:02:14Z
+sops_mac=ENC[AES256_GCM,data:gZ57STpI10+c8+c5h4nQbxtwF+mTHQKN1Tvf21axyuFRsfxOsvBzCFB7zecG7rLajt3kKtvpw7z36nOkhFLmj1rfrMd/vKrDidMjv43ABy5q/lXONjLnfP7V7OCSx29PiCG/n1zAz+q3JqwS/5mFBwBUHX+Y8JYwvt0C760gWm4=,iv:F4p5KM2P1Zgu5gCYkNAbpHjcA7YbPVsmZXL8cv1el8k=,tag:8BmNABBa1uxw3nw37FQpQA==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.11.0
diff --git a/.env-localdev.enc b/.env-localdev.enc
index 8d45c2b0c3..d392e09b34 100644
--- a/.env-localdev.enc
+++ b/.env-localdev.enc
@@ -118,6 +118,9 @@ SYNC_SERVICE_URL=ENC[AES256_GCM,data:KWmCQxYHmL4PJwRNOdss6Kx2e0Katd5oXjY=,iv:IxZ
UPLOAD_STAGING_BUCKET=ENC[AES256_GCM,data:J1PE039DMk/v13uNiAYFpqEDUzaETe7UoA==,iv:cpc+i+SWyBqV9CH3a1X2UyqcL6eToyKi8KIgX/ZIRRw=,tag:4GuNPzKg18vPQm5mEVSe7A==,type:str]
WEB_SOCKET_RESPONSE_LAMBDA=ENC[AES256_GCM,data:v46szNX7HyM/4iZ9sJet/bR4BvcXsfYDMpXUYEjWOA==,iv:g/bU4Tna6vohAgSiCKYkJ9T5EBmWX3hN2tU/9pDtxGg=,tag:EmLe4u8/xWlAiRJn1pk8Nw==,type:str]
XAI_API_KEY=ENC[AES256_GCM,data:ocD6jJf+d84JIhVfZIS+3AKHaDVL5amhYiRtkBa4at/Tl4TDQvgbTI7tXBXZAuX9F4+cVhGdm2mnA6V4x/IEj2zfQXchgQ7eB5/TytwVx+i1msvqh9E=,iv:cOsBMifYU9QqaIHbReXRNbeqovpPBpPhs/JikWjtOGA=,tag:2HTKDcpvj2kIo0Y80qWlkQ==,type:str]
+GITHUB_CLIENT_ID=ENC[AES256_GCM,data:C8i5F0P6n+j/FOe3dGDj/yX6v8zwWg==,iv:sl3QzoUWd+RtcOh206MiBXc7CiehD+xpv7Hmj/EvTUM=,tag:YxUgtFDbQ6sruIGpwBIaMA==,type:str]
+GITHUB_CLIENT_SECRET=ENC[AES256_GCM,data:3A3q6gS9z7DIMFmfVCsChXc50oL0t2XX9vilJtn3EGHtC02ag/fIfuz+,iv:7odbNLbmJVHr78u8youUwjqbjEENZBgcRoCU2eOGw8g=,tag:XRU17JozUB7L4ka+z0QMyA==,type:str]
+GITHUB_IDP_ID=ENC[AES256_GCM,data:AcC8ZijM9UYlkVtcfF0GhGAhp5p5DemZ6oL9bdVNH4ReJrYrZUE=,iv:oaUl2oO7yZUtcxIm4kRHAM5Up83oCVrgPkJdhmHl40o=,tag:Me5wLb4xTuBcSRq5dOA6iA==,type:str]
sops_kms__list_0__map_arn=arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93
sops_kms__list_0__map_aws_profile=
sops_kms__list_0__map_created_at=2026-02-03T14:46:45Z
@@ -126,7 +129,7 @@ sops_kms__list_1__map_arn=arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf9480
sops_kms__list_1__map_aws_profile=
sops_kms__list_1__map_created_at=2026-02-03T14:46:45Z
sops_kms__list_1__map_enc=AQICAHjuYcSMsjB0lKJtZ3DIAvxF8N3RNRn5KZaAN74Et6122wEgw9B5bWVjFVnU2kvvYrAsAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMjqkFO5E+NmhMEFLfAgEQgDtgSVqvR4m1awQFs/oq8iNeI/6jS3IXs7bQiUUTyQySXE6/kjPJLdYITJlXCzu7t/eXd4nMFCLcDMwYqg==
-sops_lastmodified=2026-02-20T21:38:28Z
-sops_mac=ENC[AES256_GCM,data:TC6n1t5d17etdwo+UcOHGFZotWOx7QdLVEgIqHBsBcNRp6oHb6l1cMqM2uWVqxJlaX8HLPGVlJ78jKqYEncStnFY08wjUATqgHuCuMGrmCYxkiku9xPNwcSHdEShzqWM+wVCsp1rPDc0JB6prJc2FDj/OfRZrkjJ/3kGfkc5zMI=,iv:Fh8d2lb3wE6GHKHxpW/QnckAZs0TivGWehbApRKb9BI=,tag:nBOmNW43u17Hj5SDYwQ/Rw==,type:str]
+sops_lastmodified=2026-02-26T17:02:00Z
+sops_mac=ENC[AES256_GCM,data:+ctO2oJ1VkcL+Sc2OLt24thxIC27zSIEH+HIEwptwrMmaxE85CppsEwqoyM4R9uttVt5DcRtUI1eCCPsr/5LifF7sh721/dk+WPoW5FKy64z5zHwjTGx0tOy5j0laZY8vEa3v914XkRRK3BUO13rKfTnWa1C6lZXV4WRVJI044o=,iv:oVwM5t3UdjZzWdV20FOm9bi8lSrCSe7jc8F86KXMzGI=,tag:ls2lUZagZz/NlRi56NI3+Q==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.11.0
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yaml
index f30add0e75..1b5342c82f 100644
--- a/infra/stacks/authentication-service/Pulumi.dev.yaml
+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml
@@ -18,3 +18,6 @@ config:
authentication-service:stripe_webhook_secret_key: stripe-webhook-secret-dev
authentication-service:stripe_price_id: stripe-price-id-dev
authentication-service:fusionauth_tenant_id: 5e13f524-8d32-0454-81f8-061936256aa4
+ authentication-service:github_client_id_key: github-client-id-dev
+ authentication-service:github_client_secret_key: github-client-secret-dev
+ authentication-service:github_idp_id_key: github-idp-id-dev
diff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yaml
index f9c8348989..a44ee1a603 100644
--- a/infra/stacks/authentication-service/Pulumi.prod.yaml
+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml
@@ -18,3 +18,6 @@ config:
authentication-service:stripe_webhook_secret_key: stripe-webhook-secret-prod
authentication-service:stripe_price_id: stripe-price-id-prod
authentication-service:fusionauth_tenant_id: a3e53c3d-8d6a-3e92-d64c-fa3bf30a60be
+ authentication-service:github_client_id_key: github-client-id-prod
+ authentication-service:github_client_secret_key: github-client-secret-prod
+ authentication-service:github_idp_id_key: github-idp-id-prod
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index c749ed658a..2139c57bb2 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -23,6 +23,24 @@ const DATABASE_URL = aws.secretsmanager
})
.apply((secret) => secret.secretString);
+const GITHUB_CLIENT_ID = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require(`github_client_id_key`),
+ })
+ .apply((secret) => secret.secretString);
+
+const GITHUB_CLIENT_SECRET = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require(`github_client_secret_key`),
+ })
+ .apply((secret) => secret.secretString);
+
+const GITHUB_IDP_ID = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require(`github_idp_id_key`),
+ })
+ .apply((secret) => secret.secretString);
+
const MACRO_CACHE = aws.secretsmanager
.getSecretVersionOutput({
secretId: config.require(`macro_cache_secret_key`),
@@ -283,6 +301,18 @@ const service = new AuthenticationService('authentication-service', {
name: 'STRIPE_PREMIUM_PRICE_ID',
value: pulumi.interpolate`${STRIPE_PREMIUM_PRICE_ID}`,
},
+ {
+ name: 'GITHUB_CLIENT_ID',
+ value: pulumi.interpolate`${GITHUB_CLIENT_ID}`,
+ },
+ {
+ name: 'GITHUB_CLIENT_SECRET',
+ value: pulumi.interpolate`${GITHUB_CLIENT_SECRET}`,
+ },
+ {
+ name: 'GITHUB_IDP_ID',
+ value: pulumi.interpolate`${GITHUB_IDP_ID}`,
+ },
// OpenTelemetry / Datadog tracing configuration
{
name: 'DD_SERVICE',
diff --git a/infra/stacks/fusionauth-instance/origins.ts b/infra/stacks/fusionauth-instance/origins.ts
index e4bd685908..474e95fe39 100644
--- a/infra/stacks/fusionauth-instance/origins.ts
+++ b/infra/stacks/fusionauth-instance/origins.ts
@@ -12,6 +12,7 @@ export const ALLOWED_ORIGINS = () => {
...allowedOrigins,
'http://localhost:3000',
'http://localhost:5173',
+ 'https://github.com',
];
case 'dev':
return [
@@ -21,6 +22,7 @@ export const ALLOWED_ORIGINS = () => {
'http://localhost:8084',
'http://localhost:5173',
'https://dashboarddev.macro.com',
+ 'https://github.com',
];
case 'prod':
return [
@@ -30,6 +32,7 @@ export const ALLOWED_ORIGINS = () => {
'https://staging.macro.com',
'https://www.macro.com',
'https://pdf.macro.com',
+ 'https://github.com',
];
}
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 7cbe9c4eac..a447afd558 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -21,6 +21,7 @@ import type {
GetProfilePicturesRequestBody,
GetUserInfo,
GetUserLinkExistsParams,
+ InitGithubLinkResponse,
InviteToTeamRequest,
MacroApiTokenParams,
MacroApiTokenResponse,
@@ -500,6 +501,72 @@ export const createInProgressLink = async (
} as createInProgressLinkResponse;
};
+/**
+ * @summary Initiates a link for a user
+ */
+export type initGithubLinkResponse200 = {
+ data: InitGithubLinkResponse;
+ status: 200;
+};
+
+export type initGithubLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type initGithubLinkResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type initGithubLinkResponse429 = {
+ data: ErrorResponse;
+ status: 429;
+};
+
+export type initGithubLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type initGithubLinkResponseSuccess = initGithubLinkResponse200 & {
+ headers: Headers;
+};
+export type initGithubLinkResponseError = (
+ | initGithubLinkResponse400
+ | initGithubLinkResponse401
+ | initGithubLinkResponse429
+ | initGithubLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type initGithubLinkResponse =
+ | initGithubLinkResponseSuccess
+ | initGithubLinkResponseError;
+
+export const getInitGithubLinkUrl = () => {
+ return `/link/github`;
+};
+
+export const initGithubLink = async (
+ options?: RequestInit
+): Promise<initGithubLinkResponse> => {
+ const res = await fetch(getInitGithubLinkUrl(), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: initGithubLinkResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as initGithubLinkResponse;
+};
+
/**
* @summary Completes the apple login flow
*/
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 1af6fe6e27..c5ad53684d 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
@@ -26,6 +26,7 @@ export * from './getProfilePicturesRequestBody';
export * from './getUserInfo';
export * from './getUserInfoOrganizationId';
export * from './getUserLinkExistsParams';
+export * from './initGithubLinkResponse';
export * from './inviteToTeamRequest';
export * from './macroApiTokenParams';
export * from './macroApiTokenResponse';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/initGithubLinkResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/initGithubLinkResponse.ts
new file mode 100644
index 0000000000..32a264e497
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/initGithubLinkResponse.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface InitGithubLinkResponse {
+ /** The OAuth authorization URL to redirect the user to */
+ authorization_url: string;
+ /** The link ID for tracking the OAuth flow */
+ link_id: string;
+}
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index e26d1a60d6..99026b15e1 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -365,6 +365,65 @@
}
}
},
+ "/link/github": {
+ "post": {
+ "tags": ["link::github"],
+ "summary": "Initiates a link for a user",
+ "operationId": "init_github_link",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InitGithubLinkResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/login/apple": {
"post": {
"tags": ["login::apple"],
@@ -3057,6 +3116,21 @@
}
}
},
+ "InitGithubLinkResponse": {
+ "type": "object",
+ "required": ["authorization_url", "link_id"],
+ "properties": {
+ "authorization_url": {
+ "type": "string",
+ "description": "The OAuth authorization URL to redirect the user to"
+ },
+ "link_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The link ID for tracking the OAuth flow"
+ }
+ }
+ },
"InviteToTeamRequest": {
"type": "object",
"description": "The request body to invite a user to a team",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index c9e19e6f6d..02f9db13dc 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -527,6 +527,7 @@ dependencies = [
"email_validator",
"fusionauth",
"futures",
+ "github",
"http-body-util",
"jsonwebtoken",
"last_online_tracker",
@@ -4046,6 +4047,27 @@ dependencies = [
"weezl",
]
+[[package]]
+name = "github"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "fusionauth",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "mockall",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tracing",
+ "urlencoding",
+ "uuid",
+]
+
[[package]]
name = "glob"
version = "0.3.2"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 2275b0506e..227a152368 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -44,6 +44,7 @@ members = [
"entity_access",
"frecency",
"fusionauth",
+ "github",
"gmail_client",
"integration_tests/*",
"lambda_client",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 08ab053545..05a2c5744b 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -111,6 +111,7 @@ user_quota = { path = "../user_quota" }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
uuid = { workspace = true }
+github = { path = "../github" }
[dev-dependencies]
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index e6a64ffcc1..b937f6a411 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -1,6 +1,10 @@
use std::sync::Arc;
use axum::extract::FromRef;
+use github::domain::service::GithubServiceImpl;
+use github::outbound::github_fusionauth_client::GithubFusionAuthImpl;
+use github::outbound::github_oauth_client::GithubOauthImpl;
+use github::outbound::pg_github_repo::PgGithubRepo;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_cache_client::MacroCache;
use macro_env::Environment;
@@ -40,9 +44,13 @@ pub(crate) type NotificationIngressType = NotificationIngressService<
StateMachine,
>;
+pub(crate) type GithubServiceType =
+ GithubServiceImpl<PgGithubRepo, GithubOauthImpl, GithubFusionAuthImpl>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
+ pub github_service: Arc<GithubServiceType>,
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.rs
new file mode 100644
index 0000000000..c7a2797f07
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/link/github.rs
@@ -0,0 +1,124 @@
+use axum::{
+ Extension, Json,
+ extract::State,
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use github::domain::{models::GithubError, ports::GithubService};
+
+use crate::api::{context::ApiContext, oauth2::OAuthState};
+
+use model::{response::ErrorResponse, tracking::IPContext, user::UserContext};
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, utoipa::ToSchema)]
+pub struct InitGithubLinkResponse {
+ /// The OAuth authorization URL to redirect the user to
+ pub authorization_url: String,
+ /// The link ID for tracking the OAuth flow
+ pub link_id: uuid::Uuid,
+}
+
+/// Error type for init Github operations
+#[derive(thiserror::Error, Debug)]
+pub enum InitGithubLinkError {
+ /// Invalid user ID format
+ #[error("invalid user ID format")]
+ InvalidUserId(#[from] uuid::Error),
+ /// Too many in-progress links
+ #[error("too many in progress links")]
+ TooManyInProgressLinks,
+ /// Internal error
+ #[error("internal error occurred")]
+ InternalError(#[from] anyhow::Error),
+ /// Internal github error
+ #[error("internal error occurred")]
+ GithubServiceError(#[from] GithubError),
+ /// The identity provider was not found
+ #[error("identity provider not found")]
+ IdentityProviderNotFound,
+}
+
+impl IntoResponse for InitGithubLinkError {
+ fn into_response(self) -> Response {
+ let message: &str = &self.to_string();
+ let status_code: StatusCode = match &self {
+ InitGithubLinkError::InvalidUserId(_) => StatusCode::BAD_REQUEST,
+ InitGithubLinkError::TooManyInProgressLinks => StatusCode::TOO_MANY_REQUESTS,
+ InitGithubLinkError::InternalError(_)
+ | InitGithubLinkError::GithubServiceError(_)
+ | InitGithubLinkError::IdentityProviderNotFound => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (status_code, Json(ErrorResponse { message })).into_response()
+ }
+}
+
+/// Initiates a link for a user
+#[utoipa::path(
+ post,
+ operation_id = "init_github_link",
+ path = "/link/github",
+ responses(
+ (status = 200, body=InitGithubLinkResponse),
+ (status = 400, body=ErrorResponse),
+ (status = 429, body=ErrorResponse),
+ (status = 401, body=ErrorResponse),
+ (status = 500, body=ErrorResponse),
+ )
+ )]
+#[tracing::instrument(skip(ctx, ip_context, user_context), fields(client_ip=%ip_context.client_ip, user_id=%user_context.user_id, fusion_user_id=%user_context.fusion_user_id))]
+pub async fn init_github_link_handler(
+ State(ctx): State<ApiContext>,
+ ip_context: Extension<IPContext>,
+ user_context: Extension<UserContext>,
+) -> Result<Json<InitGithubLinkResponse>, InitGithubLinkError> {
+ // TODO: this should probably be a middleware or extractor
+ // Check count of in-progress links
+ let count =
+ macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ )
+ .await?;
+
+ if count >= 5 {
+ return Err(InitGithubLinkError::TooManyInProgressLinks);
+ }
+
+ // Create in-progress link
+ let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
+ &ctx.db,
+ &user_context.fusion_user_id,
+ )
+ .await?;
+
+ // Get Github integration identity provider ID from context
+ let github_idp_id = &ctx
+ .auth_client
+ .get_identity_provider_id_by_name("github")
+ .await
+ .map_err(|_| InitGithubLinkError::IdentityProviderNotFound)?;
+
+ // Build OAuth state
+ let state = OAuthState {
+ identity_provider_id: github_idp_id.clone(),
+ link_id: Some(link_id),
+ // TODO: support
+ original_url: None,
+ // TODO: support
+ is_mobile: None,
+ };
+
+ // Build Github OAuth URL
+ let redirect_uri = crate::api::oauth2::format_redirect_uri("github");
+
+ let authorization_url = ctx
+ .github_service
+ .construct_oauth_url(&redirect_uri, state)
+ .map_err(InitGithubLinkError::GithubServiceError)?;
+
+ Ok(Json(InitGithubLinkResponse {
+ authorization_url,
+ link_id,
+ }))
+}
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 ce5cd21bff..bd01418ffd 100644
--- a/rust/cloud-storage/authentication_service/src/api/link/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/link/mod.rs
@@ -1,8 +1,13 @@
use crate::api::context::ApiContext;
use axum::{Router, routing::post};
pub(in crate::api) mod create_in_progress_link;
+pub(in crate::api) mod github;
-#[allow(dead_code)]
-pub fn router() -> Router<ApiContext> {
- Router::new().route("/", post(create_in_progress_link::handler))
+/// The link router
+/// All routes have IPContext attached via the `macro_middleware::tracking::attach_ip_context_handler`.
+/// We ensure the user is logged in with the `macro_middleware::auth::decode_jwt::handler`.
+pub fn router(_state: ApiContext) -> Router<ApiContext> {
+ Router::new()
+ .route("/", post(create_in_progress_link::handler))
+ .route("/github", post(github::init_github_link_handler))
}
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index 83376dfb40..879cbfc1e4 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -18,7 +18,6 @@ pub(crate) mod context;
// Routes
#[allow(unused_imports)]
mod email;
-#[allow(unused_imports)]
mod link;
#[allow(unused_imports)]
mod merge;
@@ -82,6 +81,19 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
.nest("/oauth", oauth::router(state.clone()))
.nest("/oauth2", oauth2::router())
.nest("/user", user::router(state.clone(), state.jwt_args.clone()))
+ .nest(
+ "/link",
+ link::router(state.clone()).layer(
+ ServiceBuilder::new()
+ .layer(axum::middleware::from_fn(
+ macro_middleware::tracking::attach_ip_context_handler,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ state.jwt_args.clone(),
+ macro_middleware::auth::decode_jwt::handler,
+ )),
+ ),
+ )
.nest(
"/team",
team::router(state.jwt_args.clone()).layer(ServiceBuilder::new().layer(
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs
new file mode 100644
index 0000000000..b6a6372213
--- /dev/null
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/github.rs
@@ -0,0 +1,144 @@
+use anyhow::Context;
+use axum::{
+ Json,
+ response::{Html, IntoResponse, Response},
+};
+use github::domain::{models::GithubError, ports::GithubService};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserId};
+use model::response::ErrorResponse;
+use tower_cookies::Cookies;
+
+use crate::api::{
+ context::ApiContext,
+ oauth2::{
+ OAuthState, format_redirect_uri,
+ login::{self},
+ },
+};
+
+/// Error type for Github Link operations
+#[derive(thiserror::Error, Debug)]
+pub enum GithubLinkError {
+ /// Internal error
+ #[error("internal error occurred")]
+ InternalError(#[from] anyhow::Error),
+ /// Internal github error
+ #[error("internal error occurred")]
+ GithubServiceError(#[from] GithubError),
+}
+
+impl IntoResponse for GithubLinkError {
+ fn into_response(self) -> Response {
+ Json(ErrorResponse {
+ message: &self.to_string(),
+ })
+ .into_response()
+ }
+}
+
+/// Success response for Github OAuth handler
+pub enum GithubOAuthSuccess {
+ /// HTML response for account linking flow
+ Html(Html<&'static str>),
+ /// Response for login flow (redirect or status)
+ Login(Response),
+}
+
+impl IntoResponse for GithubOAuthSuccess {
+ fn into_response(self) -> Response {
+ match self {
+ GithubOAuthSuccess::Html(html) => html.into_response(),
+ GithubOAuthSuccess::Login(response) => response,
+ }
+ }
+}
+
+/// Links the users github to an existing fusionauth account
+#[tracing::instrument(skip(ctx), err)]
+async fn link_user(
+ ctx: &ApiContext,
+ link_id: &uuid::Uuid,
+ code: &str,
+) -> Result<(), GithubLinkError> {
+ let fusionauth_user_id =
+ macro_db_client::in_progress_user_link::get_macro_user_id_by_link_id(&ctx.db, link_id)
+ .await?;
+
+ // SAFETY: we don't support multi-profile at this time but we do need to support the method for
+ // fetching
+ let macro_user_id = macro_db_client::user::get::get_user_profiles_by_fusionauth_user_id(
+ &ctx.db,
+ &fusionauth_user_id.to_string(),
+ )
+ .await?;
+
+ let macro_user_id = macro_user_id.first().context("expected user profile")?;
+
+ let macro_user_id = MacroUserId::parse_from_str(macro_user_id)
+ .map(|id| id.into_owned().lowercase())
+ .context("valid macro user id")?;
+
+ ctx.github_service
+ .link_user(
+ &macro_user_id,
+ &fusionauth_user_id,
+ link_id,
+ &format_redirect_uri("github"),
+ code,
+ )
+ .await?;
+
+ Ok(())
+}
+
+pub(in crate::api::oauth2) async fn handler(
+ ctx: &ApiContext,
+ cookies: Cookies,
+ code: &str,
+ state: &OAuthState,
+) -> Result<GithubOAuthSuccess, GithubLinkError> {
+ // if the link id is provided, this user is already logged in to an account. therefore, we
+ // don't need to handle completing the login through fusionauth
+ if let Some(link_id) = state.link_id.as_ref() {
+ link_user(ctx, link_id, code).await?;
+
+ // Return HTML that notifies the opener window and closes the popup
+ let html = Html(
+ r#"
+ <!DOCTYPE html>
+ <html>
+ <head><title>Github Connected</title></head>
+ <body>
+ <script>
+ console.log('OAuth callback received');
+ if (window.opener) {
+ console.log('Sending message to opener window');
+ window.opener.postMessage({ type: 'github-linked', success: true }, '*');
+ console.log('Message sent, closing in 500ms');
+ setTimeout(() => {
+ window.close();
+ }, 500);
+ } else {
+ console.log('No opener window found');
+ window.close();
+ }
+ </script>
+ <p>Github account connected successfully. This window will close automatically...</p>
+ </body>
+ </html>
+ "#,
+ );
+ return Ok(GithubOAuthSuccess::Html(html));
+ }
+
+ // The user does not need a link, complete the standard idp login
+ tracing::trace!("no link provided handling login normally");
+
+ let response = login::handler(ctx, cookies, code, "github", state)
+ .await
+ .map_err(|_response| {
+ GithubLinkError::InternalError(anyhow::anyhow!("login handler failed"))
+ })?;
+
+ Ok(GithubOAuthSuccess::Login(response))
+}
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
index a606f6edf6..37dbef1ab9 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs
@@ -24,7 +24,7 @@ async fn link_user(
ctx: &ApiContext,
identity_provider_id: &str,
code: &str,
- link_id: &str,
+ link_id: &uuid::Uuid,
) -> Result<(), (StatusCode, String)> {
// Get existing macro user id from link id
let macro_user_id =
diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/mod.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/mod.rs
index 8a21bf5a9f..bd5b4d9e4d 100644
--- a/rust/cloud-storage/authentication_service/src/api/oauth2/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/mod.rs
@@ -2,6 +2,7 @@ use crate::config::BASE_URL;
use axum::{Router, extract::State, routing::get};
use tower_cookies::CookieManagerLayer;
+mod github;
mod google;
mod login;
@@ -21,21 +22,24 @@ use axum::{
use model::response::ErrorResponse;
use tower_cookies::Cookies;
-pub(in crate::api::oauth2) fn format_redirect_uri(provider: &str) -> String {
+pub(in crate::api) fn format_redirect_uri(provider: &str) -> String {
format!("{}/oauth2/{provider}/callback", *BASE_URL)
}
-#[derive(Debug, serde::Deserialize)]
-pub(in crate::api::oauth2) struct OAuthState {
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub(in crate::api) struct OAuthState {
/// The identity provider id to use to complete the login
- identity_provider_id: String,
+ pub identity_provider_id: String,
/// The link id to use to complete the login
/// If the link id is provided, this means we need to link this idp to a specific user before
/// performing the login process
- link_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub link_id: Option<uuid::Uuid>,
/// The original url you came from
+ #[serde(skip_serializing_if = "Option::is_none")]
pub original_url: Option<String>,
/// If the authentication request is from a mobile device
+ #[serde(skip_serializing_if = "Option::is_none")]
pub is_mobile: Option<bool>,
}
@@ -91,6 +95,10 @@ pub(in crate::api) async fn handler(
match provider.as_str() {
"google" => google::handler(&ctx, cookies, &params.code, &state).await,
+ "github" => github::handler(&ctx, cookies, &params.code, &state)
+ .await
+ .map(|r| r.into_response())
+ .map_err(|e| e.into_response()),
_ => Err((
StatusCode::NOT_IMPLEMENTED,
Json(ErrorResponse {
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index a20021fca1..315aed03d5 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -10,6 +10,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::merge::create_merge_request::CreateAccountMergeRequest;
use crate::api::team::create_team::CreateTeamRequest;
use crate::api::team::get_team_invites::TeamInvitesResponse;
@@ -62,6 +63,7 @@ use model::user::{
/// /link
link::create_in_progress_link::handler,
+ link::github::init_github_link_handler,
/// /oauth
oauth::oauth_redirect::handler,
@@ -146,6 +148,7 @@ use model::user::{
ResendFusionauthVerifyUserEmailRequest,
GenerateEmailLinkRequest,
CreateInProgressLinkResponse,
+ InitGithubLinkResponse,
UserQuota,
UserOrganizationResponse,
GetLegacyUserPermissionsResponse,
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index 9586ad7043..b01d1a7cb9 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -64,6 +64,10 @@ pub struct Config {
/// The stripe price id for the professional subscription
pub stripe_price_id: String,
+
+ pub github_client_id: String,
+ pub github_client_secret: String,
+ pub github_idp_id: String,
}
impl Config {
@@ -119,6 +123,13 @@ impl Config {
let stripe_price_id =
std::env::var("STRIPE_PRICE_ID").context("STRIPE_PRICE_ID must be provided")?;
+ let github_client_id =
+ std::env::var("GITHUB_CLIENT_ID").context("GITHUB_CLIENT_ID must be provided")?;
+ let github_client_secret = std::env::var("GITHUB_CLIENT_SECRET")
+ .context("GITHUB_CLIENT_SECRET must be provided")?;
+ let github_idp_id =
+ std::env::var("GITHUB_IDP_ID").context("GITHUB_IDP_ID must be provided")?;
+
Ok(Config {
base_url,
database_url,
@@ -140,6 +151,9 @@ impl Config {
search_event_queue,
stripe_price_id,
environment,
+ github_client_id,
+ github_client_secret,
+ github_idp_id,
})
}
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index b092ecd6e6..7f182f1291 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -1,6 +1,13 @@
use anyhow::Context;
use config::{Config, Environment};
use document_storage_service_client::DocumentStorageServiceClient;
+use github::{
+ domain::service::{GithubConfig, GithubServiceImpl},
+ outbound::{
+ github_fusionauth_client::GithubFusionAuthImpl, github_oauth_client::GithubOauthImpl,
+ pg_github_repo::PgGithubRepo,
+ },
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
@@ -227,9 +234,21 @@ async fn main() -> anyhow::Result<()> {
user_roles_and_permissions_service.clone(),
);
+ let github_service_impl = GithubServiceImpl::new(
+ PgGithubRepo::new(db.clone()),
+ GithubOauthImpl::default(),
+ GithubFusionAuthImpl::new(auth_client.clone()),
+ GithubConfig {
+ client_id: config.github_client_id,
+ client_secret: config.github_client_secret,
+ idp_id: config.github_idp_id,
+ },
+ );
+
api::setup_and_serve(
ApiContext {
db,
+ github_service: Arc::new(github_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/github/.sqlx/query-0a1f3835d8dd57e120b0378134d98858f2ba5ed410765ffca1b03abb05c7b098.json b/rust/cloud-storage/github/.sqlx/query-0a1f3835d8dd57e120b0378134d98858f2ba5ed410765ffca1b03abb05c7b098.json
new file mode 100644
index 0000000000..a13e3d6b24
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-0a1f3835d8dd57e120b0378134d98858f2ba5ed410765ffca1b03abb05c7b098.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM\n in_progress_user_link\n WHERE\n id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0a1f3835d8dd57e120b0378134d98858f2ba5ed410765ffca1b03abb05c7b098"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-4942eda5f2d8832fc43c02a17aae1ec8ed06a16fc14ae6d4046eb75bc427fb69.json b/rust/cloud-storage/github/.sqlx/query-4942eda5f2d8832fc43c02a17aae1ec8ed06a16fc14ae6d4046eb75bc427fb69.json
new file mode 100644
index 0000000000..b4e8c85aaf
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-4942eda5f2d8832fc43c02a17aae1ec8ed06a16fc14ae6d4046eb75bc427fb69.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id as \"fusionauth_user_id: Uuid\", github_username, github_user_id, created_at, updated_at\n FROM github_links\n WHERE macro_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "github_username",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "github_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "4942eda5f2d8832fc43c02a17aae1ec8ed06a16fc14ae6d4046eb75bc427fb69"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.json b/rust/cloud-storage/github/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.json
new file mode 100644
index 0000000000..c06c14d875
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id as \"fusionauth_user_id: Uuid\", github_username, github_user_id, created_at, updated_at\n FROM github_links\n WHERE github_user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "github_username",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "github_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "594849eb57f03099052b5415a963968dd31da940638917a96ab12dfc5a98bfa4"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-799422134794f3c4b9c5867b136262c2f639f313f14fd56da967a74d91aa1c88.json b/rust/cloud-storage/github/.sqlx/query-799422134794f3c4b9c5867b136262c2f639f313f14fd56da967a74d91aa1c88.json
new file mode 100644
index 0000000000..8f474872bd
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-799422134794f3c4b9c5867b136262c2f639f313f14fd56da967a74d91aa1c88.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Varchar",
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "799422134794f3c4b9c5867b136262c2f639f313f14fd56da967a74d91aa1c88"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-e17994ebc0589faabde0aa239f24c542292d06b39c744f2055038ac46c41bbdc.json b/rust/cloud-storage/github/.sqlx/query-e17994ebc0589faabde0aa239f24c542292d06b39c744f2055038ac46c41bbdc.json
new file mode 100644
index 0000000000..996b2268bd
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-e17994ebc0589faabde0aa239f24c542292d06b39c744f2055038ac46c41bbdc.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id as \"fusionauth_user_id: Uuid\", github_username, github_user_id, created_at, updated_at\n FROM github_links\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "github_username",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "github_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "e17994ebc0589faabde0aa239f24c542292d06b39c744f2055038ac46c41bbdc"
+}
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
new file mode 100644
index 0000000000..9c0f841687
--- /dev/null
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -0,0 +1,37 @@
+[package]
+edition = "2024"
+name = "github"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["ports", "outbound"]
+ports = []
+outbound = [
+ "dep:sqlx",
+ "dep:reqwest",
+ "dep:serde_json",
+ "dep:urlencoding",
+ "dep:fusionauth",
+ "ports"
+]
+
+[dependencies]
+anyhow = { workspace = true }
+tracing = { workspace = true }
+thiserror = { workspace = true }
+chrono = { workspace = true }
+sqlx = { workspace = true, optional = true }
+uuid = { workspace = true }
+serde = { workspace = true}
+reqwest = {workspace = true, optional = true }
+serde_json = { workspace = true, optional = true }
+urlencoding = { workspace = true, optional = true }
+
+fusionauth = { path = "../fusionauth", optional = true }
+macro_uuid = { path = "../macro_uuid" }
+macro_user_id = { path = "../macro_user_id" }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
+mockall = { workspace = true }
diff --git a/rust/cloud-storage/github/fixtures/github_insert_test_data.sql b/rust/cloud-storage/github/fixtures/github_insert_test_data.sql
new file mode 100644
index 0000000000..f3f06b13d5
--- /dev/null
+++ b/rust/cloud-storage/github/fixtures/github_insert_test_data.sql
@@ -0,0 +1,9 @@
+INSERT INTO
+ public.macro_user (id, username, email, stripe_customer_id)
+VALUES
+ ('ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid, 'newuser', '[email protected]', 'cus_new');
+
+INSERT INTO
+ public."User" (id, email, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid);
diff --git a/rust/cloud-storage/github/fixtures/github_test_data.sql b/rust/cloud-storage/github/fixtures/github_test_data.sql
new file mode 100644
index 0000000000..a282d2bfa8
--- /dev/null
+++ b/rust/cloud-storage/github/fixtures/github_test_data.sql
@@ -0,0 +1,26 @@
+INSERT INTO
+ public.macro_user (id, username, email, stripe_customer_id)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test');
+
+INSERT INTO
+ public."User" (id, email, macro_user_id)
+VALUES
+ ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid);
+
+INSERT INTO
+ public.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id) (
+ SELECT
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid,
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid,
+ 'testuser',
+ '12345'
+ );
+
+INSERT INTO
+ public.in_progress_user_link (id, macro_user_id) (
+ SELECT
+ 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid,
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid
+ );
diff --git a/rust/cloud-storage/github/justfile b/rust/cloud-storage/github/justfile
new file mode 100644
index 0000000000..d7f13030d3
--- /dev/null
+++ b/rust/cloud-storage/github/justfile
@@ -0,0 +1,9 @@
+DATABASE_URL := "postgres://user:password@localhost:5432/macrodb"
+
+mod sqlx '../sqlx.just'
+
+prepare_db:
+ just sqlx::prepare_db {{ DATABASE_URL }}
+
+check:
+ cargo check --all-features
diff --git a/rust/cloud-storage/github/src/domain.rs b/rust/cloud-storage/github/src/domain.rs
new file mode 100644
index 0000000000..a947d9653b
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports (trait interfaces), and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/github/src/domain/models.rs b/rust/cloud-storage/github/src/domain/models.rs
new file mode 100644
index 0000000000..eec19c0f52
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/models.rs
@@ -0,0 +1,70 @@
+//! Domain models for the github crate.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::Deserialize;
+
+/// Errors that can occur during github operations.
+#[derive(Debug, thiserror::Error)]
+pub enum GithubError {
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+ /// No Github link was found
+ #[error("no link found")]
+ NoLinkFound,
+ /// Github account is already linked
+ #[error("github account is already linked with another")]
+ AccountAlreadyLinked,
+ /// No refresh token was provided in the token exchange
+ #[error("no refresh token provided in token exchange")]
+ NoRefreshTokenProvided,
+}
+
+/// A GitHub link record (as stored in the database)
+#[derive(Debug, Clone)]
+pub struct GithubLink {
+ /// Unique ID for this link
+ pub id: uuid::Uuid,
+ /// Macro user ID
+ pub macro_id: MacroUserIdStr<'static>,
+ /// FusionAuth user ID
+ pub fusionauth_user_id: uuid::Uuid,
+ /// GitHub username
+ pub github_username: String,
+ /// GitHub user ID (as string)
+ pub github_user_id: String,
+ /// When the link was created
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// When the link was last updated
+ pub updated_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// GitHub OAuth token exchange response
+#[derive(Debug, Deserialize)]
+pub struct GithubExchangeTokenResponse {
+ /// The access token for Github API calls
+ pub access_token: String,
+ /// The type of token (usually "bearer")
+ pub token_type: String,
+ /// The scopes granted to this token
+ pub scope: String,
+ /// The refresh token (only present if token expiration is enabled in Github App settings)
+ pub refresh_token: Option<String>,
+ /// Seconds until access token expires (only present if token expiration is enabled)
+ pub expires_in: Option<i64>,
+ /// Seconds until refresh token expires (only present if token expiration is enabled)
+ pub refresh_token_expires_in: Option<i64>,
+}
+
+/// Github user information retrieved from Github API
+#[derive(Debug, Deserialize)]
+pub struct GithubUserInfo {
+ /// Github user ID (numeric)
+ pub id: u64,
+ /// Github username
+ pub login: String,
+ /// Primary email (may be null if private)
+ pub email: Option<String>,
+ /// Display name
+ pub name: Option<String>,
+}
diff --git a/rust/cloud-storage/github/src/domain/ports.rs b/rust/cloud-storage/github/src/domain/ports.rs
new file mode 100644
index 0000000000..217faf168f
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/ports.rs
@@ -0,0 +1,119 @@
+//! Port definitions for the github domain.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use std::future::Future;
+
+use crate::domain::models::{GithubError, GithubExchangeTokenResponse, GithubUserInfo};
+
+use super::models::GithubLink;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+/// Repository for accessing github link data from the database.
+///
+/// All methods perform database operations — SQL queries are written
+/// directly in the outbound adapter implementation.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait GithubRepo: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Gets the github link by the macro user id
+ fn get_github_link_by_user_id<'a>(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;
+
+ /// Gets the github link by the github user id
+ fn get_github_link_by_github_user_id(
+ &self,
+ github_user_id: &str,
+ ) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;
+
+ /// Gets the github link by id
+ fn get_github_link_by_id(
+ &self,
+ id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<GithubLink, Self::Err>> + Send;
+
+ /// Inserts a github link
+ fn insert_github_link(
+ &self,
+ link: &GithubLink,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// deletes the in progress user link
+ fn delete_in_progress_user_link(
+ &self,
+ in_progress_link_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Repository for handling github oauth related actions.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait GithubOauth: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Constructs the oauth url to authenticate with github
+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ &self,
+ client_id: &str,
+ redirect_uri: &str,
+ state: T,
+ ) -> Result<String, Self::Err>;
+
+ /// Exchanges the oauth code for tokens
+ fn exchange_oauth_code_for_tokens(
+ &self,
+ client_id: &str,
+ client_secret: &str,
+ redirect_uri: &str,
+ code: &str,
+ ) -> impl Future<Output = Result<GithubExchangeTokenResponse, Self::Err>> + Send;
+
+ /// Gets the user info using the access token
+ fn get_user_info(
+ &self,
+ access_token: &str,
+ ) -> impl Future<Output = Result<GithubUserInfo, Self::Err>> + Send;
+}
+
+/// Repository for handling fusionauth related actions.
+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]
+pub trait FusionAuth: 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
+ fn link_user(
+ &self,
+ fusionauth_user_id: &uuid::Uuid,
+ idp_id: &str,
+ github_user_id: &str,
+ username: &str,
+ access_token: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Service interface for github operations.
+///
+/// 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;
+}
diff --git a/rust/cloud-storage/github/src/domain/service.rs b/rust/cloud-storage/github/src/domain/service.rs
new file mode 100644
index 0000000000..6a38331241
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service.rs
@@ -0,0 +1,153 @@
+//! Github service implementation.
+
+use chrono::Utc;
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+
+use crate::domain::{
+ models::{GithubError, GithubLink},
+ ports::{FusionAuth, GithubOauth, GithubRepo, GithubService},
+};
+
+/// Github config
+#[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,
+}
+
+/// The concrete github service implementation.
+pub struct GithubServiceImpl<R: GithubRepo, U: GithubOauth, F: FusionAuth> {
+ repo: R,
+ oauth: U,
+ fusion: F,
+ config: GithubConfig,
+}
+
+impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> GithubServiceImpl<R, U, F> {
+ /// Create a new github service.
+ pub fn new(repo: R, oauth: U, fusion: F, config: GithubConfig) -> Self {
+ Self {
+ repo,
+ oauth,
+ fusion,
+ config,
+ }
+ }
+}
+
+impl<R: GithubRepo, U: GithubOauth, F: FusionAuth> 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()))
+ }
+
+ #[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);
+ }
+ }
+ 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));
+ }
+ }
+ }
+
+ self.fusion
+ .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 fusionauth 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)
+ }
+}
diff --git a/rust/cloud-storage/github/src/lib.rs b/rust/cloud-storage/github/src/lib.rs
new file mode 100644
index 0000000000..6ee503a997
--- /dev/null
+++ b/rust/cloud-storage/github/src/lib.rs
@@ -0,0 +1,14 @@
+//! Documents hexagonal architecture crate.
+//!
+//! Encapsulates document CRUD operations using a ports-and-adapters pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies (PostgreSQL, GitHub)
+
+#![deny(missing_docs)]
+pub mod domain;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/github/src/outbound.rs b/rust/cloud-storage/github/src/outbound.rs
new file mode 100644
index 0000000000..60fe2e9890
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound.rs
@@ -0,0 +1,5 @@
+//! Outbound adapters for the github domain.
+
+pub mod github_fusionauth_client;
+pub mod github_oauth_client;
+pub mod pg_github_repo;
diff --git a/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rs b/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rs
new file mode 100644
index 0000000000..5e2540d514
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound/github_fusionauth_client.rs
@@ -0,0 +1,50 @@
+//! 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(())
+ }
+}
diff --git a/rust/cloud-storage/github/src/outbound/github_oauth_client.rs b/rust/cloud-storage/github/src/outbound/github_oauth_client.rs
new file mode 100644
index 0000000000..cd428de6ee
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound/github_oauth_client.rs
@@ -0,0 +1,183 @@
+//! Github Oauth Client implementation of the [`GithubOauth`] port.
+
+use std::time::Duration;
+
+use crate::domain::{
+ models::{GithubExchangeTokenResponse, GithubUserInfo},
+ ports::GithubOauth,
+};
+
+/// Github email information from /user/emails endpoint
+#[derive(Debug, serde::Deserialize)]
+struct GithubEmail {
+ /// The email
+ email: String,
+ /// If the email is primary
+ primary: bool,
+ /// If the email is verified
+ verified: bool,
+}
+
+/// Github Oauth implementation
+#[derive(Clone, Default)]
+pub struct GithubOauthImpl {
+ /// The reqwest client
+ client: reqwest::Client,
+}
+
+impl GithubOauth for GithubOauthImpl {
+ type Err = anyhow::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ &self,
+ client_id: &str,
+ redirect_uri: &str,
+ state: T,
+ ) -> Result<String, Self::Err> {
+ let state_str = serde_json::to_string(&state)?;
+
+ let url = format!(
+ "https://github.com/login/oauth/authorize?client_id={}&redirect_uri={}&scope={}&state={}",
+ client_id,
+ urlencoding::encode(redirect_uri),
+ urlencoding::encode("repo user:email"),
+ urlencoding::encode(&state_str)
+ );
+
+ Ok(url)
+ }
+
+ #[tracing::instrument(skip(self, client_secret), err)]
+ async fn exchange_oauth_code_for_tokens(
+ &self,
+ client_id: &str,
+ client_secret: &str,
+ redirect_uri: &str,
+ code: &str,
+ ) -> Result<GithubExchangeTokenResponse, Self::Err> {
+ #[derive(serde::Serialize)]
+ struct TokenRequest<'a> {
+ client_id: &'a str,
+ client_secret: &'a str,
+ code: &'a str,
+ redirect_uri: &'a str,
+ }
+
+ let token_request = TokenRequest {
+ client_id,
+ client_secret,
+ code,
+ redirect_uri,
+ };
+
+ let response = self
+ .client
+ .post("https://github.com/login/oauth/access_token")
+ .header("Accept", "application/json")
+ .json(&token_request)
+ .timeout(Duration::from_secs(30))
+ .send()
+ .await?;
+
+ let status = response.status();
+
+ if !status.is_success() {
+ let error_body = response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+ anyhow::bail!("token exchange failed {}", error_body)
+ }
+
+ let token_response: GithubExchangeTokenResponse = response.json().await?;
+
+ Ok(token_response)
+ }
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn get_user_info(&self, access_token: &str) -> Result<GithubUserInfo, Self::Err> {
+ // Get basic user info
+ 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.is_success() {
+ let error_body = user_response
+ .text()
+ .await
+ .unwrap_or_else(|_| "unknown error".to_string());
+
+ // Check for 401 Unauthorized - token expired or invalid
+ if status.as_u16() == 401 {
+ tracing::warn!(error_body=%error_body, "GitHub token expired or invalid");
+ anyhow::bail!("token expired")
+ }
+
+ anyhow::bail!("failed to get user info {}", error_body)
+ }
+
+ let mut user_info: GithubUserInfo = user_response.json().await?;
+
+ // If email is not public, try to fetch from emails endpoint (optional)
+ if user_info.email.is_none() {
+ tracing::debug!("Email not in public profile, attempting to fetch from /user/emails");
+
+ match self
+ .client
+ .get("https://api.github.com/user/emails")
+ .header("Authorization", format!("Bearer {}", access_token))
+ .header("User-Agent", "Macro-Auth-Service")
+ .timeout(Duration::from_secs(30))
+ .send()
+ .await
+ {
+ Ok(emails_response) => {
+ let status = emails_response.status();
+ tracing::trace!(status=?status, "received response from /user/emails");
+
+ if status.is_success() {
+ match emails_response.json::<Vec<GithubEmail>>().await {
+ Ok(emails) => {
+ tracing::debug!(
+ email_count = emails.len(),
+ "Fetched emails from GitHub"
+ );
+
+ // Find the primary verified email
+ if let Some(primary_email) = emails
+ .iter()
+ .find(|e| e.primary && e.verified)
+ .or_else(|| emails.iter().find(|e| e.verified))
+ {
+ tracing::debug!(email=?primary_email.email, "Found verified email");
+ user_info.email = Some(primary_email.email.clone());
+ } else {
+ tracing::debug!("No verified email found in GitHub account");
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "Failed to parse emails response");
+ }
+ }
+ } else {
+ let error_body = emails_response.text().await.unwrap_or_default();
+ tracing::warn!(status=?status, error=?error_body, "Failed to fetch user emails from GitHub (non-critical)");
+ }
+ }
+ Err(e) => {
+ tracing::debug!(error=?e, "Failed to fetch user emails (non-critical)");
+ }
+ }
+ }
+
+ Ok(user_info)
+ }
+}
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_repo.rs
new file mode 100644
index 0000000000..1cae05f817
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound/pg_github_repo.rs
@@ -0,0 +1,168 @@
+//! PostgreSQL implementation of the [`GithubRepo`] port.
+
+#[cfg(test)]
+mod test;
+
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::{
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::{models::GithubLink, ports::GithubRepo};
+
+/// PostgreSQL-backed github repository.
+#[derive(Clone)]
+pub struct PgGithubRepo {
+ pool: PgPool,
+}
+
+impl PgGithubRepo {
+ /// Create a new repository backed by the given connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl GithubRepo for PgGithubRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_github_link_by_user_id<'a>(
+ &self,
+ macro_user_id: &MacroUserId<Lowercase<'a>>,
+ ) -> Result<GithubLink, Self::Err> {
+ let link = sqlx::query!(
+ r#"
+ SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
+ FROM github_links
+ WHERE macro_id = $1
+ "#,
+ macro_user_id.as_ref()
+ )
+ .try_map(|r| Ok(GithubLink{
+ id: r.id,
+ macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ fusionauth_user_id: r.fusionauth_user_id,
+ github_username: r.github_username,
+ github_user_id: r.github_user_id,
+ created_at: r.created_at,
+ updated_at: r.updated_at,
+ }))
+ .fetch_optional(&self.pool)
+ .await?;
+
+ match link {
+ Some(l) => Ok(l),
+ None => Err(sqlx::Error::RowNotFound),
+ }
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_github_link_by_github_user_id(
+ &self,
+ github_user_id: &str,
+ ) -> Result<GithubLink, Self::Err> {
+ let link = sqlx::query!(
+ r#"
+ SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
+ FROM github_links
+ WHERE github_user_id = $1
+ "#,
+ github_user_id
+ )
+ .try_map(|r| Ok(GithubLink{
+ id: r.id,
+ macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ fusionauth_user_id: r.fusionauth_user_id,
+ github_username: r.github_username,
+ github_user_id: r.github_user_id,
+ created_at: r.created_at,
+ updated_at: r.updated_at,
+ }))
+ .fetch_optional(&self.pool)
+ .await?;
+
+ match link {
+ Some(l) => Ok(l),
+ None => Err(sqlx::Error::RowNotFound),
+ }
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_github_link_by_id(&self, id: &uuid::Uuid) -> Result<GithubLink, Self::Err> {
+ let link = sqlx::query!(
+ r#"
+ SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
+ FROM github_links
+ WHERE id = $1
+ "#,
+ id
+ )
+ .try_map(|r| Ok(GithubLink{
+ id: r.id,
+ macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ fusionauth_user_id: r.fusionauth_user_id,
+ github_username: r.github_username,
+ github_user_id: r.github_user_id,
+ created_at: r.created_at,
+ updated_at: r.updated_at,
+ }))
+ .fetch_optional(&self.pool)
+ .await?;
+
+ match link {
+ Some(l) => Ok(l),
+ None => Err(sqlx::Error::RowNotFound),
+ }
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn insert_github_link(&self, link: &GithubLink) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id, created_at, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ "#,
+ link.id,
+ link.macro_id.as_ref(),
+ link.fusionauth_user_id,
+ link.github_username,
+ link.github_user_id,
+ link.created_at,
+ link.updated_at,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete_in_progress_user_link(
+ &self,
+ in_progress_link_id: &uuid::Uuid,
+ ) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ DELETE FROM
+ in_progress_user_link
+ WHERE
+ id = $1
+ "#,
+ in_progress_link_id
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs
new file mode 100644
index 0000000000..17eaa004a1
--- /dev/null
+++ b/rust/cloud-storage/github/src/outbound/pg_github_repo/test.rs
@@ -0,0 +1,182 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use sqlx::{Pool, Postgres};
+
+use crate::domain::models::GithubLink;
+use crate::domain::ports::GithubRepo;
+use crate::outbound::pg_github_repo::PgGithubRepo;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_user_id(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let link = repo.get_github_link_by_user_id(&user_id.0).await.unwrap();
+
+ assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
+ assert_eq!(link.github_username, "testuser");
+ assert_eq!(link.github_user_id, "12345");
+ assert_eq!(
+ link.fusionauth_user_id.to_string(),
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_user_id_not_found(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let result = repo.get_github_link_by_user_id(&user_id.0).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_github_user_id(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let link = repo
+ .get_github_link_by_github_user_id("12345")
+ .await
+ .unwrap();
+
+ assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
+ assert_eq!(link.github_username, "testuser");
+ assert_eq!(link.github_user_id, "12345");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_github_user_id_not_found(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let result = repo.get_github_link_by_github_user_id("99999").await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_id(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let id = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let link = repo.get_github_link_by_id(&id).await.unwrap();
+
+ assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
+ assert_eq!(link.github_username, "testuser");
+ assert_eq!(link.github_user_id, "12345");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_get_github_link_by_id_not_found(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
+ let result = repo.get_github_link_by_id(&id).await;
+
+ assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_insert_test_data"))
+)]
+async fn test_insert_github_link(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool.clone());
+
+ let now = chrono::Utc::now();
+ let link = GithubLink {
+ id: uuid::Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee").unwrap(),
+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ fusionauth_user_id: uuid::Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").unwrap(),
+ github_username: "newuser".to_string(),
+ github_user_id: "67890".to_string(),
+ created_at: now,
+ updated_at: now,
+ };
+
+ repo.insert_github_link(&link).await.unwrap();
+
+ // Verify it was inserted by reading it back
+ let fetched = repo.get_github_link_by_id(&link.id).await.unwrap();
+ assert_eq!(fetched.macro_id.as_ref(), "macro|[email protected]");
+ assert_eq!(fetched.github_username, "newuser");
+ assert_eq!(fetched.github_user_id, "67890");
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_insert_github_link_duplicate_github_user_id(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let now = chrono::Utc::now();
+ let link = GithubLink {
+ id: uuid::Uuid::new_v4(),
+ macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ fusionauth_user_id: uuid::Uuid::new_v4(),
+ github_username: "otheruser".to_string(),
+ github_user_id: "12345".to_string(), // same as fixture
+ created_at: now,
+ updated_at: now,
+ };
+
+ let result = repo.insert_github_link(&link).await;
+ assert!(result.is_err());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_test_data"))
+)]
+async fn test_delete_in_progress_user_link(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool.clone());
+
+ let id = uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
+
+ repo.delete_in_progress_user_link(&id).await.unwrap();
+
+ // Verify it was deleted
+ let row = sqlx::query!("SELECT id FROM in_progress_user_link WHERE id = $1", id)
+ .fetch_optional(&pool)
+ .await
+ .unwrap();
+ assert!(row.is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_delete_in_progress_user_link_nonexistent(pool: Pool<Postgres>) {
+ let repo = PgGithubRepo::new(pool);
+
+ let id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
+
+ // Deleting a nonexistent row should not error (DELETE affects 0 rows)
+ repo.delete_in_progress_user_link(&id).await.unwrap();
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index ac6d1763ae..60e9ce2e52 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -84,6 +84,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./stream/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./macro_project_utils/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./entity_access/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./github/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260226142003_add_github_link_table.sql b/rust/cloud-storage/macro_db_client/migrations/20260226142003_add_github_link_table.sql
new file mode 100644
index 0000000000..3c7507771a
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260226142003_add_github_link_table.sql
@@ -0,0 +1,27 @@
+-- Add migration script here
+CREATE TABLE public.github_links
+(
+ id UUID NOT NULL,
+ macro_id TEXT NOT NULL REFERENCES "User" ("id") ON DELETE CASCADE,
+ fusionauth_user_id UUID NOT NULL,
+ github_username VARCHAR(255) NOT NULL,
+ github_user_id TEXT NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
+
+ CONSTRAINT github_links_pkey PRIMARY KEY (id)
+);
+
+-- Prevent GitHub account sharing across users
+CREATE UNIQUE INDEX uq_github_links_github_user_id
+ ON public.github_links (github_user_id);
+
+-- Lookup indices
+CREATE INDEX idx_github_links_macro_id
+ ON public.github_links (macro_id);
+
+CREATE INDEX idx_github_links_fusionauth_user_id
+ ON public.github_links(fusionauth_user_id);
+
+CREATE INDEX idx_github_links_github_username
+ ON public.github_links (github_username);
diff --git a/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs b/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
index 8fdc555f88..eff95c218a 100644
--- a/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
+++ b/rust/cloud-storage/macro_db_client/src/in_progress_user_link.rs
@@ -46,9 +46,8 @@ pub async fn create_in_progress_user_link(
pub async fn delete_in_progress_user_link(
db: &sqlx::Pool<sqlx::Postgres>,
- link_id: &str,
+ link_id: &uuid::Uuid,
) -> anyhow::Result<()> {
- let link_id = macro_uuid::string_to_uuid(link_id)?;
sqlx::query!(
r#"
DELETE FROM
@@ -56,7 +55,7 @@ pub async fn delete_in_progress_user_link(
WHERE
id = $1
"#,
- &link_id
+ link_id
)
.execute(db)
.await?;
@@ -89,9 +88,8 @@ pub async fn delete_day_old_in_progress_user_links(
pub async fn get_macro_user_id_by_link_id(
db: &sqlx::Pool<sqlx::Postgres>,
- link_id: &str,
+ link_id: &uuid::Uuid,
) -> anyhow::Result<Uuid> {
- let link_id = macro_uuid::string_to_uuid(link_id)?;
let link = sqlx::query!(
r#"
SELECT
@@ -102,7 +100,7 @@ pub async fn get_macro_user_id_by_link_id(
WHERE
id = $1
"#,
- &link_id
+ link_id
)
.map(|row| row.macro_user_id)
.fetch_one(db)
diff --git a/rust/cloud-storage/macro_entrypoint/src/lib.rs b/rust/cloud-storage/macro_entrypoint/src/lib.rs
index 74492e70d6..4df45ffc7f 100644
--- a/rust/cloud-storage/macro_entrypoint/src/lib.rs
+++ b/rust/cloud-storage/macro_entrypoint/src/lib.rs
@@ -21,6 +21,8 @@ pub struct MacroEntrypoint {
impl Default for MacroEntrypoint {
fn default() -> Self {
+ // Load .env file if it exists, but don't fail if it doesn't
+ let _ = dotenvy::dotenv();
MacroEntrypoint {
env: Environment::new_or_prod(),
local: Default::default(),
@@ -57,7 +59,6 @@ impl MacroEntrypoint {
/// consume self, initialize this binary, and return a proof that it was initialized [InitializedEntrypoint]
pub fn init(self) -> InitializedEntrypoint {
- // Load .env file if it exists, but don't fail if it doesn't
let _ = dotenvy::dotenv();
std::panic::set_hook(Box::new(tracing_panic::panic_hook));