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): basic webhook event support (#1741)

Will Hutchinsonbf6d5158b8c4
diff --git a/.env-local.enc b/.env-local.enc
index fd22a2ca0a..3fccacb182 100644
--- a/.env-local.enc
+++ b/.env-local.enc
@@ -114,6 +114,7 @@ LOCAL_AWS_URL=ENC[AES256_GCM,data:5Hz1NHrCE5PdPR6yTgFsvanHkad2D40P,iv:74PiL6QEao
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]
+GITHUB_WEBHOOK_SECRET_KEY=ENC[AES256_GCM,data:tWL06eZICn0MEwmC8gL6piEnxV/Z7KTskFNZ6jodkPHDSyHyoqrnAA==,iv:VRg2NGTPzo3GkmjIpDX/Zrh+67JCyZ5YYTZkwl0AlZc=,tag:Qlx7bAmrGGRj6tPz3gycBQ==,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
@@ -122,7 +123,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-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_lastmodified=2026-03-02T19:31:13Z
+sops_mac=ENC[AES256_GCM,data:20e95jDJycmr9Z3W1yx0HPKZEemTKDAID6mJmawpyJPL7gLkjQoOw6J5Qtz1W/V1DG6Y/jhqZk0MHa/QzfNn2NN/y9kPUOX/yJxwowG71/kltmF+VWWyCZsC2ckP2bwhk1G/w73x6eWaQ6pbjuUGojqunGkj1ekh2xIdSAfFMrI=,iv:SpfVrfNqxXALO41Tkl0nP/HVL9j+xnWVS2pxlod/4Sg=,tag:tWsnWpW4+//a6ByFUF1UNg==,type:str]
sops_unencrypted_suffix=_unencrypted
sops_version=3.11.0
diff --git a/.env-localdev.enc b/.env-localdev.enc
index d392e09b34..8a844307fd 100644
--- a/.env-localdev.enc
+++ b/.env-localdev.enc
@@ -121,6 +121,7 @@ XAI_API_KEY=ENC[AES256_GCM,data:ocD6jJf+d84JIhVfZIS+3AKHaDVL5amhYiRtkBa4at/Tl4TD
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]
+GITHUB_WEBHOOK_SECRET_KEY=ENC[AES256_GCM,data:8Jpg/QeIDEpJpCWp2WirEZZpRj65LGuTEwm7BiQfBXxfPQy7Dhe8fQ==,iv:j++tyRf0YdEH1UG3hAaV9S2bmLBkregasm583EuvnJ4=,tag:P1msIGxRkrfq1rd+uGnSGA==,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
@@ -129,7 +130,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-26T17:02:00Z
-sops_mac=ENC[AES256_GCM,data:+ctO2oJ1VkcL+Sc2OLt24thxIC27zSIEH+HIEwptwrMmaxE85CppsEwqoyM4R9uttVt5DcRtUI1eCCPsr/5LifF7sh721/dk+WPoW5FKy64z5zHwjTGx0tOy5j0laZY8vEa3v914XkRRK3BUO13rKfTnWa1C6lZXV4WRVJI044o=,iv:oVwM5t3UdjZzWdV20FOm9bi8lSrCSe7jc8F86KXMzGI=,tag:ls2lUZagZz/NlRi56NI3+Q==,type:str]
+sops_lastmodified=2026-03-02T19:31:18Z
+sops_mac=ENC[AES256_GCM,data:1Z/JDEHcdrWpU62R2LUqmJUbSKiPfiDHu5Rwheh/yv5NmUljg0yEVOBmIR7LMg+f6pVzqqPNBfxZD9IJ0mqkYPWrMAXC8L3B1cFHw8C82UH7MEkLkVDf0pP46CUUMPJEU+A/etV0HrjhiNYEgMdxkco13WpsFVWqkoluHCoIrkY=,iv:LWRV7Uk5J3wKiVqEATKQELxd4WIeCU6rHoDxXTZ8YFY=,tag:Zk9X4dFMQq6UPEMiXl8PtQ==,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 1b5342c82f..9f6abe58f7 100644
--- a/infra/stacks/authentication-service/Pulumi.dev.yaml
+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml
@@ -21,3 +21,4 @@ config:
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
+ authentication-service:github_webhook_secret_key: github-webhook-secret-dev
diff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yaml
index a44ee1a603..5a209db3ce 100644
--- a/infra/stacks/authentication-service/Pulumi.prod.yaml
+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml
@@ -21,3 +21,4 @@ config:
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
+ authentication-service:github_webhook_secret_key: github-webhook-secret-prod
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index 2139c57bb2..af52dda703 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -41,6 +41,11 @@ const GITHUB_IDP_ID = aws.secretsmanager
})
.apply((secret) => secret.secretString);
+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 MACRO_CACHE = aws.secretsmanager
.getSecretVersionOutput({
secretId: config.require(`macro_cache_secret_key`),
@@ -154,6 +159,7 @@ const secretKeyArns = [
pulumi.interpolate`${macroApiTokenSecretPrivateKeyArn}`,
pulumi.interpolate`${stripeWebhookSecretKeyArn}`,
pulumi.interpolate`${stripePriceIdArn}`,
+ pulumi.interpolate`${githubWebhookSecretKeyArn}`,
];
const vpc = get_coparse_api_vpc();
@@ -192,7 +198,7 @@ const service = new AuthenticationService('authentication-service', {
{ name: 'ENVIRONMENT', value: stack },
{
name: 'RUST_LOG',
- value: `authentication_service=${stack === 'prod' ? 'info' : 'trace'},tower_http=${stack === 'prod' ? 'info' : 'debug'},macro_auth=${stack === 'prod' ? 'info' : 'debug'},macro_middleware=${stack === 'prod' ? 'info' : 'debug'}`,
+ value: `authentication_service=${stack === 'prod' ? 'info' : 'trace'},tower_http=${stack === 'prod' ? 'info' : 'debug'},macro_auth=${stack === 'prod' ? 'info' : 'debug'},macro_middleware=${stack === 'prod' ? 'info' : 'debug'},github=${stack === 'prod' ? 'info' : 'debug'}`,
},
{
name: 'DATABASE_URL',
@@ -313,6 +319,10 @@ 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,
+ },
// OpenTelemetry / Datadog tracing configuration
{
name: 'DD_SERVICE',
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 55a53c0d3e..0d70326c3e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4160,17 +4160,25 @@ name = "github"
version = "0.1.0"
dependencies = [
"anyhow",
+ "axum",
+ "axum-extra",
"chrono",
+ "entity_access",
"fusionauth",
+ "hex",
+ "hmac",
"macro_db_migrator",
"macro_user_id",
"macro_uuid",
"mockall",
+ "model-error-response",
"redis",
"reqwest",
"serde",
"serde_json",
+ "sha2",
"sqlx",
+ "subtle",
"thiserror 2.0.17",
"tokio",
"tracing",
diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rs
index 879cbfc1e4..a40bc8beb2 100644
--- a/rust/cloud-storage/authentication_service/src/api/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs
@@ -1,10 +1,7 @@
use crate::api::context::ApiContext;
use anyhow::Context;
use axum::Router;
-use axum::extract::Request;
use axum::http::HeaderName;
-use axum::http::Method;
-use axum::middleware::Next;
use macro_auth::constant::MACRO_REFRESH_TOKEN_HEADER;
use native_app_service::inbound::RouterState;
use tower::ServiceBuilder;
@@ -100,19 +97,12 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
axum::middleware::from_fn(macro_middleware::tracking::attach_ip_context_handler),
)),
)
- .nest("/jwt", jwt::router(state.jwt_args))
+ .nest("/jwt", jwt::router(state.jwt_args.clone()))
.nest("/session", session::router())
.nest(
"/webhooks",
- webhooks::router().layer(ServiceBuilder::new().layer(axum::middleware::from_fn(
- |req: Request, next: Next| async move {
- match req.method() {
- &Method::PUT | &Method::POST | &Method::PATCH | &Method::DELETE => {
- tokio::task::spawn(next.run(req)).await.unwrap()
- }
- _ => next.run(req).await,
- }
- },
+ webhooks::router(state).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(
+ macro_middleware::connection_drop_prevention_handler,
))),
)
}
diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs
index c40aea6a0e..04bf922434 100644
--- a/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs
+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/mod.rs
@@ -1,9 +1,16 @@
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() -> Router<ApiContext> {
- Router::new().nest("/user", user::router())
+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())
}
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index b01d1a7cb9..f45100525a 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -65,9 +65,14 @@ pub struct Config {
/// The stripe price id for the professional subscription
pub stripe_price_id: String,
+ /// The github client id
pub github_client_id: String,
+ /// The github client secret
pub github_client_secret: String,
+ /// The github idp id
pub github_idp_id: String,
+ /// The github webhook secret key
+ pub github_webhook_secret_key: String,
}
impl Config {
@@ -130,6 +135,9 @@ 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")?;
+
Ok(Config {
base_url,
database_url,
@@ -154,6 +162,7 @@ impl Config {
github_client_id,
github_client_secret,
github_idp_id,
+ github_webhook_secret_key,
})
}
}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index a34ae1f99e..5bc5caeab8 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -137,6 +137,15 @@ 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 auth_client = fusionauth::FusionAuthClient::new(
config.fusionauth_tenant_id,
fusionauth_api_key,
@@ -242,6 +251,7 @@ async fn main() -> anyhow::Result<()> {
client_id: config.github_client_id,
client_secret: config.github_client_secret,
idp_id: config.github_idp_id,
+ webhook_secret: github_webhook_secret,
},
);
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index 2241f2f1e3..7f4f9e6b3b 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -5,8 +5,9 @@ publish = false
version = "0.1.0"
[features]
-default = ["ports", "outbound"]
+default = ["ports", "inbound", "outbound", "axum"]
ports = []
+inbound = ["axum", "ports"]
outbound = [
"dep:sqlx",
"dep:reqwest",
@@ -17,6 +18,11 @@ outbound = [
"dep:fusionauth",
"ports"
]
+axum = [
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:model-error-response",
+]
[dependencies]
anyhow = { workspace = true }
@@ -29,6 +35,11 @@ serde = { workspace = true}
reqwest = {workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
urlencoding = { workspace = true, optional = true }
+entity_access = { path = "../entity_access" }
+hmac = "0.12.1"
+sha2 = { workspace = true }
+subtle = "2.6.1"
+hex = { workspace = true }
fusionauth = { path = "../fusionauth", optional = true }
macro_uuid = { path = "../macro_uuid" }
@@ -36,6 +47,10 @@ macro_user_id = { path = "../macro_user_id" }
redis = { workspace = true, features = ["aio", "tokio-comp"], optional = true }
tokio = { workspace = true, features = ["sync"], optional = true }
+axum = { workspace = true, optional = true }
+axum-extra = { workspace = true, optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
+
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
diff --git a/rust/cloud-storage/github/src/domain/models.rs b/rust/cloud-storage/github/src/domain/models.rs
index afb3755910..1094468ce6 100644
--- a/rust/cloud-storage/github/src/domain/models.rs
+++ b/rust/cloud-storage/github/src/domain/models.rs
@@ -30,6 +30,9 @@ pub enum GithubError {
/// No refresh token was provided in the token exchange
#[error("no refresh token provided in token exchange")]
NoRefreshTokenProvided,
+ /// Invalid github webhook signature
+ #[error("invalid github webhook signature")]
+ InvalidWebhookSignature,
}
/// A GitHub link record (as stored in the database)
@@ -80,3 +83,14 @@ pub struct GithubUserInfo {
/// Display name
pub name: Option<String>,
}
+
+/// A validated github webhook event
+#[derive(Debug)]
+pub struct ValidatedGithubWebhookEvent(pub serde_json::Value);
+
+impl ValidatedGithubWebhookEvent {
+ /// Create a new ValidatedGithubWebhookEvent
+ pub fn new(value: serde_json::Value) -> Self {
+ Self(value)
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/ports.rs b/rust/cloud-storage/github/src/domain/ports.rs
index 1c986b7115..2434046f9e 100644
--- a/rust/cloud-storage/github/src/domain/ports.rs
+++ b/rust/cloud-storage/github/src/domain/ports.rs
@@ -6,6 +6,7 @@ use std::future::Future;
use crate::domain::models::{
GithubAccessToken, GithubError, GithubExchangeTokenResponse, GithubUserInfo,
+ ValidatedGithubWebhookEvent,
};
use super::models::GithubLink;
@@ -125,4 +126,17 @@ pub trait GithubService: Send + Sync + 'static {
redirect_uri: &str,
code: &str,
) -> impl Future<Output = Result<GithubLink, GithubError>> + Send;
+
+ /// Validates the incoming webhook event and returns back the `ValidatedGithubWebhookEvent`
+ fn validate_webhook_event(
+ &self,
+ signature: &str,
+ body: &[u8],
+ ) -> impl Future<Output = Result<ValidatedGithubWebhookEvent, GithubError>> + Send;
+
+ /// Processes and incoming github webhook event
+ fn process_webhook_event(
+ &self,
+ webhook_event: &ValidatedGithubWebhookEvent,
+ ) -> impl Future<Output = Result<(), GithubError>> + Send;
}
diff --git a/rust/cloud-storage/github/src/domain/service.rs b/rust/cloud-storage/github/src/domain/service.rs
index f0fd5d5ddc..1defae8290 100644
--- a/rust/cloud-storage/github/src/domain/service.rs
+++ b/rust/cloud-storage/github/src/domain/service.rs
@@ -7,10 +7,15 @@ use macro_user_id::{
};
use crate::domain::{
- models::{GithubError, GithubLink},
+ models::{GithubError, GithubLink, ValidatedGithubWebhookEvent},
ports::{Auth, GithubOauth, GithubRepo, GithubService},
};
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+use subtle::ConstantTimeEq;
+type HmacSha256 = Hmac<Sha256>;
+
/// Github config
#[derive(Debug)]
pub struct GithubConfig {
@@ -20,6 +25,8 @@ pub struct GithubConfig {
pub client_secret: String,
/// The id of the github identity provider in fusionauth
pub idp_id: String,
+ /// The webhook secret used to validate github webhook events
+ pub webhook_secret: String,
}
/// The concrete github service implementation.
@@ -150,4 +157,38 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubService for GithubServiceImpl
Ok(link)
}
+
+ #[tracing::instrument(skip(self, body), err)]
+ async fn validate_webhook_event(
+ &self,
+ 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(
+ serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,
+ ))
+ } else {
+ Err(GithubError::InvalidWebhookSignature)
+ }
+ }
+
+ #[tracing::instrument(skip(self, webhook_event), err)]
+ async fn process_webhook_event(
+ &self,
+ webhook_event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ tracing::trace!(webhook_event=?webhook_event.0, "processing event");
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/github/src/inbound.rs b/rust/cloud-storage/github/src/inbound.rs
new file mode 100644
index 0000000000..690cbc1898
--- /dev/null
+++ b/rust/cloud-storage/github/src/inbound.rs
@@ -0,0 +1,36 @@
+//! Inbound adapters for the github domain.
+
+#[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 {
+ use axum::http::StatusCode;
+ let (status_code, message): (StatusCode, &str) = match self {
+ crate::domain::models::GithubError::Internal(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "internal server error occurred",
+ ),
+ crate::domain::models::GithubError::NoLinkFound => {
+ (StatusCode::FORBIDDEN, "no account link found")
+ }
+ crate::domain::models::GithubError::AccountAlreadyLinked => {
+ (StatusCode::BAD_REQUEST, "account already linked")
+ }
+ crate::domain::models::GithubError::NoRefreshTokenProvided => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "no refresh token was provided",
+ ),
+ crate::domain::models::GithubError::InvalidWebhookSignature => {
+ (StatusCode::UNAUTHORIZED, "unauthenticated")
+ }
+ };
+
+ (
+ status_code,
+ axum::Json(model_error_response::ErrorResponse { message }),
+ )
+ .into_response()
+ }
+}
diff --git a/rust/cloud-storage/github/src/inbound/webhook_router.rs b/rust/cloud-storage/github/src/inbound/webhook_router.rs
new file mode 100644
index 0000000000..2c644bf6d1
--- /dev/null
+++ b/rust/cloud-storage/github/src/inbound/webhook_router.rs
@@ -0,0 +1,98 @@
+//! 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 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(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)
+}
diff --git a/rust/cloud-storage/github/src/lib.rs b/rust/cloud-storage/github/src/lib.rs
index 6ee503a997..4265a28a91 100644
--- a/rust/cloud-storage/github/src/lib.rs
+++ b/rust/cloud-storage/github/src/lib.rs
@@ -6,9 +6,13 @@
//!
//! - **domain**: Contains domain models, ports (traits), and the service implementation
//! - **outbound**: Contains adapters for external dependencies (PostgreSQL, GitHub)
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
#![deny(missing_docs)]
pub mod domain;
#[cfg(feature = "outbound")]
pub mod outbound;
+
+#[cfg(feature = "inbound")]
+pub mod inbound;