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): webhook event parsing (#1753)

Will Hutchinson19acf78bf58d
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f4d54f6d5c..42a1fdb02e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4174,6 +4174,7 @@ dependencies = [
"mockall",
"model-error-response",
"redis",
+ "regex",
"reqwest",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index e62d05300e..8e2439b8fe 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -9,9 +9,8 @@ default = ["ports", "inbound", "outbound", "axum"]
ports = []
inbound = ["axum", "ports"]
outbound = [
- "dep:sqlx",
+ "dep:sqlx",
"dep:reqwest",
- "dep:serde_json",
"dep:urlencoding",
"dep:redis",
"dep:tokio",
@@ -34,7 +33,8 @@ sqlx = { workspace = true, optional = true }
uuid = { workspace = true }
serde = { workspace = true}
reqwest = {workspace = true, optional = true }
-serde_json = { workspace = true, optional = true }
+serde_json = { workspace = true }
+regex = { workspace = true }
urlencoding = { workspace = true, optional = true }
entity_access = { path = "../entity_access" }
hmac = "0.12.1"
diff --git a/rust/cloud-storage/github/src/domain/models.rs b/rust/cloud-storage/github/src/domain/models.rs
deleted file mode 100644
index 1094468ce6..0000000000
--- a/rust/cloud-storage/github/src/domain/models.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-//! Domain models for the github crate.
-
-use macro_user_id::user_id::MacroUserIdStr;
-use serde::Deserialize;
-
-/// Github access token
-#[derive(Clone)]
-#[allow(dead_code)]
-pub struct GithubAccessToken(String);
-
-impl GithubAccessToken {
- /// Creates a new GithubAccessToken
- pub fn new(token: String) -> Self {
- Self(token)
- }
-}
-
-/// Errors that can occur during github operations.
-#[derive(Debug, thiserror::Error)]
-pub enum GithubError {
- /// 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,
- /// Invalid github webhook signature
- #[error("invalid github webhook signature")]
- InvalidWebhookSignature,
-}
-
-/// 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>,
-}
-
-/// 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/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rs
new file mode 100644
index 0000000000..3f409a359d
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/models/mod.rs
@@ -0,0 +1,265 @@
+//! Domain models for the github crate.
+
+#[cfg(test)]
+mod test;
+
+use std::collections::HashSet;
+use std::fmt;
+use std::sync::LazyLock;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use regex::Regex;
+use serde::Deserialize;
+
+/// Github access token
+#[derive(Clone)]
+#[allow(dead_code)]
+pub struct GithubAccessToken(String);
+
+impl GithubAccessToken {
+ /// Creates a new GithubAccessToken
+ pub fn new(token: String) -> Self {
+ Self(token)
+ }
+}
+
+/// Errors that can occur during github operations.
+#[derive(Debug, thiserror::Error)]
+pub enum GithubError {
+ /// 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,
+ /// Invalid github webhook signature
+ #[error("invalid github webhook signature")]
+ InvalidWebhookSignature,
+}
+
+/// 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>,
+}
+
+/// A validated github webhook event
+#[derive(Debug)]
+pub struct ValidatedGithubWebhookEvent {
+ /// The event type from the `X-GitHub-Event` header
+ pub event_type: String,
+ /// The parsed JSON payload
+ pub payload: serde_json::Value,
+}
+
+impl ValidatedGithubWebhookEvent {
+ /// Create a new ValidatedGithubWebhookEvent
+ pub fn new(event_type: String, payload: serde_json::Value) -> Self {
+ Self {
+ event_type,
+ payload,
+ }
+ }
+
+ /// Parse the raw event type string into a [`GithubWebhookEventType`].
+ pub fn parsed_event_type(&self) -> GithubWebhookEventType {
+ GithubWebhookEventType::from_event_header(&self.event_type)
+ }
+
+ /// Extract all text fields worth searching for task IDs, based on event type.
+ pub fn extract_searchable_text(&self) -> Vec<String> {
+ let mut texts = Vec::new();
+ match self.parsed_event_type() {
+ GithubWebhookEventType::PullRequest => {
+ if let Some(pr) = self.payload.get("pull_request") {
+ if let Some(s) = pr.get("title").and_then(|v| v.as_str()) {
+ texts.push(s.to_string());
+ }
+ if let Some(s) = pr.get("body").and_then(|v| v.as_str()) {
+ texts.push(s.to_string());
+ }
+ if let Some(s) = pr
+ .get("head")
+ .and_then(|h| h.get("ref"))
+ .and_then(|v| v.as_str())
+ {
+ texts.push(s.to_string());
+ }
+ }
+ }
+ GithubWebhookEventType::IssueComment
+ | GithubWebhookEventType::PullRequestReviewComment => {
+ if let Some(s) = self
+ .payload
+ .get("comment")
+ .and_then(|c| c.get("body"))
+ .and_then(|v| v.as_str())
+ {
+ texts.push(s.to_string());
+ }
+ }
+ GithubWebhookEventType::PullRequestReview => {
+ if let Some(s) = self
+ .payload
+ .get("review")
+ .and_then(|r| r.get("body"))
+ .and_then(|v| v.as_str())
+ {
+ texts.push(s.to_string());
+ }
+ }
+ GithubWebhookEventType::Unknown(_) => {}
+ }
+ texts
+ }
+}
+
+/// Known GitHub webhook event types we handle.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum GithubWebhookEventType {
+ /// `pull_request` events
+ PullRequest,
+ /// `issue_comment` events (includes comments on PRs)
+ IssueComment,
+ /// `pull_request_review` events
+ PullRequestReview,
+ /// `pull_request_review_comment` events
+ PullRequestReviewComment,
+ /// Any event type we don't handle
+ Unknown(String),
+}
+
+impl GithubWebhookEventType {
+ /// Map the raw `X-GitHub-Event` header value to a variant.
+ pub fn from_event_header(s: &str) -> Self {
+ match s {
+ "pull_request" => Self::PullRequest,
+ "issue_comment" => Self::IssueComment,
+ "pull_request_review" => Self::PullRequestReview,
+ "pull_request_review_comment" => Self::PullRequestReviewComment,
+ other => Self::Unknown(other.to_string()),
+ }
+ }
+}
+
+/// Regex matching `MACRO-{short_uuid}` (case-insensitive).
+/// The capture group contains only the Flickr base58 short UUID portion.
+static MACRO_TASK_ID_RE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"(?i)macro-([123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ]+)")
+ .expect("valid regex")
+});
+
+/// A Macro task ID in the form `MACRO-{short_uuid}`.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct MacroTaskId {
+ /// The Flickr base58 short UUID portion
+ pub short_uuid: String,
+}
+
+impl MacroTaskId {
+ /// Create from a raw short UUID string, validating that all characters
+ /// are in the Flickr base58 alphabet.
+ pub fn from_short_uuid(s: &str) -> Option<Self> {
+ let converter = macro_uuid::ShortUuidConverter::default();
+ if converter.is_short_uuid(s) {
+ Some(Self {
+ short_uuid: s.to_string(),
+ })
+ } else {
+ None
+ }
+ }
+
+ /// Create from a full UUID by converting to a short UUID.
+ pub fn from_uuid(uuid: &uuid::Uuid) -> Self {
+ let converter = macro_uuid::ShortUuidConverter::default();
+ Self {
+ short_uuid: converter.from_uuid(uuid),
+ }
+ }
+
+ /// Convert back to a full UUID.
+ pub fn to_uuid(&self) -> anyhow::Result<uuid::Uuid> {
+ let converter = macro_uuid::ShortUuidConverter::default();
+ converter.to_uuid(&self.short_uuid)
+ }
+
+ /// Returns the canonical `MACRO-{short_uuid}` string.
+ pub fn to_task_id_string(&self) -> String {
+ format!("MACRO-{}", self.short_uuid)
+ }
+
+ /// Extract all unique `MACRO-{short_uuid}` references from text.
+ /// Matching is case-insensitive on the `MACRO-` prefix; the short UUID
+ /// portion is preserved as captured.
+ pub fn extract_from_text(text: &str) -> Vec<MacroTaskId> {
+ let mut seen = HashSet::new();
+ let mut results = Vec::new();
+
+ for caps in MACRO_TASK_ID_RE.captures_iter(text) {
+ let short = &caps[1];
+ if seen.insert(short.to_string())
+ && let Some(task_id) = Self::from_short_uuid(short)
+ {
+ results.push(task_id);
+ }
+ }
+
+ results
+ }
+}
+
+impl fmt::Display for MacroTaskId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "MACRO-{}", self.short_uuid)
+ }
+}
diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rs
new file mode 100644
index 0000000000..e73196c286
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/models/test.rs
@@ -0,0 +1,243 @@
+use super::*;
+
+// ---------------------------------------------------------------------------
+// MacroTaskId::from_short_uuid
+// ---------------------------------------------------------------------------
+
+#[test]
+fn from_short_uuid_valid() {
+ let task_id = MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap();
+ assert_eq!(task_id.short_uuid, "2BuyvtY3ae");
+}
+
+#[test]
+fn from_short_uuid_rejects_empty() {
+ assert!(MacroTaskId::from_short_uuid("").is_none());
+}
+
+#[test]
+fn from_short_uuid_rejects_invalid_chars() {
+ // 'O', 'I', 'l', '0' are not in Flickr base58
+ assert!(MacroTaskId::from_short_uuid("OOOOO").is_none());
+ assert!(MacroTaskId::from_short_uuid("IIIlll").is_none());
+ assert!(MacroTaskId::from_short_uuid("000abc").is_none());
+}
+
+#[test]
+fn from_short_uuid_rejects_too_long() {
+ let long = "a".repeat(25);
+ assert!(MacroTaskId::from_short_uuid(&long).is_none());
+}
+
+// ---------------------------------------------------------------------------
+// MacroTaskId::from_uuid / to_uuid roundtrip
+// ---------------------------------------------------------------------------
+
+#[test]
+fn roundtrip_uuid_conversion() {
+ let uuid = uuid::Uuid::parse_str("0d0dc589-f301-43f1-8b11-4ab448ca4bb4").unwrap();
+ let task_id = MacroTaskId::from_uuid(&uuid);
+ assert_eq!(task_id.short_uuid, "2BuyvtY3aeEvHx4uG8iD51");
+
+ let recovered = task_id.to_uuid().unwrap();
+ assert_eq!(uuid, recovered);
+}
+
+#[test]
+fn to_task_id_string() {
+ let task_id = MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap();
+ assert_eq!(task_id.to_task_id_string(), "MACRO-2BuyvtY3ae");
+}
+
+#[test]
+fn display_impl() {
+ let task_id = MacroTaskId::from_short_uuid("abc123").unwrap();
+ assert_eq!(format!("{task_id}"), "MACRO-abc123");
+}
+
+// ---------------------------------------------------------------------------
+// MacroTaskId::extract_from_text
+// ---------------------------------------------------------------------------
+
+#[test]
+fn extract_case_insensitive() {
+ let text = "fixes MACRO-2BuyvtY3ae and also macro-abc123 and Macro-XYZ";
+ let ids = MacroTaskId::extract_from_text(text);
+ assert_eq!(ids.len(), 3);
+ assert_eq!(ids[0].short_uuid, "2BuyvtY3ae");
+ assert_eq!(ids[1].short_uuid, "abc123");
+ // "XYZ" is valid base58
+ assert_eq!(ids[2].short_uuid, "XYZ");
+}
+
+#[test]
+fn extract_deduplicates() {
+ let text = "MACRO-abc123 and macro-abc123 again MACRO-abc123";
+ let ids = MacroTaskId::extract_from_text(text);
+ // Same short UUID captured, only first occurrence kept
+ assert_eq!(ids.len(), 1);
+ assert_eq!(ids[0].short_uuid, "abc123");
+}
+
+#[test]
+fn extract_no_match() {
+ let text = "no task ids here, just MACR-123 or MACRO- or MACRO";
+ let ids = MacroTaskId::extract_from_text(text);
+ assert!(ids.is_empty());
+}
+
+#[test]
+fn extract_ignores_invalid_base58_chars() {
+ // '0', 'O', 'I', 'l' are not in Flickr base58
+ // "MACRO-000abc" -> regex captures "000abc" but from_short_uuid rejects it
+ let text = "MACRO-000abc";
+ let ids = MacroTaskId::extract_from_text(text);
+ assert!(ids.is_empty());
+}
+
+#[test]
+fn extract_from_branch_name() {
+ let text = "feature/macro-2BuyvtY3ae";
+ let ids = MacroTaskId::extract_from_text(text);
+ assert_eq!(ids.len(), 1);
+ assert_eq!(ids[0].short_uuid, "2BuyvtY3ae");
+}
+
+#[test]
+fn extract_multiple_in_sentence() {
+ let text = "closes MACRO-aaa111 and MACRO-bbb222";
+ let ids = MacroTaskId::extract_from_text(text);
+ assert_eq!(ids.len(), 2);
+ assert_eq!(ids[0].short_uuid, "aaa111");
+ assert_eq!(ids[1].short_uuid, "bbb222");
+}
+
+// ---------------------------------------------------------------------------
+// GithubWebhookEventType::from_event_header
+// ---------------------------------------------------------------------------
+
+#[test]
+fn event_type_from_known_headers() {
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("pull_request"),
+ GithubWebhookEventType::PullRequest
+ );
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("issue_comment"),
+ GithubWebhookEventType::IssueComment
+ );
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("pull_request_review"),
+ GithubWebhookEventType::PullRequestReview
+ );
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("pull_request_review_comment"),
+ GithubWebhookEventType::PullRequestReviewComment
+ );
+}
+
+#[test]
+fn event_type_unknown() {
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("ping"),
+ GithubWebhookEventType::Unknown("ping".to_string())
+ );
+ assert_eq!(
+ GithubWebhookEventType::from_event_header("push"),
+ GithubWebhookEventType::Unknown("push".to_string())
+ );
+}
+
+// ---------------------------------------------------------------------------
+// ValidatedGithubWebhookEvent::extract_searchable_text
+// ---------------------------------------------------------------------------
+
+#[test]
+fn extract_text_pull_request() {
+ let payload = serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "fixes MACRO-abc123",
+ "body": "This PR closes MACRO-def456",
+ "head": {
+ "ref": "feature/macro-ghi789"
+ }
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 3);
+ assert_eq!(texts[0], "fixes MACRO-abc123");
+ assert_eq!(texts[1], "This PR closes MACRO-def456");
+ assert_eq!(texts[2], "feature/macro-ghi789");
+}
+
+#[test]
+fn extract_text_pull_request_null_body() {
+ let payload = serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "some title",
+ "body": null,
+ "head": {
+ "ref": "main"
+ }
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("pull_request".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 2);
+ assert_eq!(texts[0], "some title");
+ assert_eq!(texts[1], "main");
+}
+
+#[test]
+fn extract_text_issue_comment() {
+ let payload = serde_json::json!({
+ "action": "created",
+ "comment": {
+ "body": "See MACRO-abc123 for details"
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("issue_comment".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 1);
+ assert_eq!(texts[0], "See MACRO-abc123 for details");
+}
+
+#[test]
+fn extract_text_pull_request_review() {
+ let payload = serde_json::json!({
+ "action": "submitted",
+ "review": {
+ "body": "Looks good, relates to MACRO-xyz789"
+ }
+ });
+ let event = ValidatedGithubWebhookEvent::new("pull_request_review".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 1);
+ assert_eq!(texts[0], "Looks good, relates to MACRO-xyz789");
+}
+
+#[test]
+fn extract_text_pull_request_review_comment() {
+ let payload = serde_json::json!({
+ "action": "created",
+ "comment": {
+ "body": "This line relates to MACRO-abc123"
+ }
+ });
+ let event =
+ ValidatedGithubWebhookEvent::new("pull_request_review_comment".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert_eq!(texts.len(), 1);
+ assert_eq!(texts[0], "This line relates to MACRO-abc123");
+}
+
+#[test]
+fn extract_text_unknown_event() {
+ let payload = serde_json::json!({"zen": "Keep it logically awesome."});
+ let event = ValidatedGithubWebhookEvent::new("ping".to_string(), payload);
+ let texts = event.extract_searchable_text();
+ assert!(texts.is_empty());
+}
diff --git a/rust/cloud-storage/github/src/domain/ports.rs b/rust/cloud-storage/github/src/domain/ports.rs
index 45d8adfa8b..f225b9f0ba 100644
--- a/rust/cloud-storage/github/src/domain/ports.rs
+++ b/rust/cloud-storage/github/src/domain/ports.rs
@@ -130,6 +130,7 @@ pub trait GithubService: Send + Sync + 'static {
/// Validates the incoming webhook event and returns back the `ValidatedGithubWebhookEvent`
fn validate_webhook_event(
&self,
+ event_type: &str,
signature: &str,
body: &[u8],
) -> impl Future<Output = Result<ValidatedGithubWebhookEvent, GithubError>> + Send;
diff --git a/rust/cloud-storage/github/src/domain/service.rs b/rust/cloud-storage/github/src/domain/service/mod.rs
similarity index 80%
rename from rust/cloud-storage/github/src/domain/service.rs
rename to rust/cloud-storage/github/src/domain/service/mod.rs
index 538a84192e..4005a57856 100644
--- a/rust/cloud-storage/github/src/domain/service.rs
+++ b/rust/cloud-storage/github/src/domain/service/mod.rs
@@ -1,5 +1,8 @@
//! Github service implementation.
+#[cfg(test)]
+mod test;
+
use chrono::Utc;
use macro_user_id::{
lowercased::Lowercase,
@@ -7,7 +10,9 @@ use macro_user_id::{
};
use crate::domain::{
- models::{GithubError, GithubLink, ValidatedGithubWebhookEvent},
+ models::{
+ GithubError, GithubLink, GithubWebhookEventType, MacroTaskId, ValidatedGithubWebhookEvent,
+ },
ports::{Auth, GithubOauth, GithubRepo, GithubService},
};
@@ -163,6 +168,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubService for GithubServiceImpl
#[tracing::instrument(skip(self, body), err)]
async fn validate_webhook_event(
&self,
+ event_type: &str,
signature: &str,
body: &[u8],
) -> Result<ValidatedGithubWebhookEvent, GithubError> {
@@ -177,6 +183,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubService for GithubServiceImpl
// constant-time comparison
if expected.as_slice().ct_eq(&sig_bytes).into() {
Ok(ValidatedGithubWebhookEvent::new(
+ event_type.to_string(),
serde_json::from_slice(body).map_err(|e| GithubError::Internal(e.into()))?,
))
} else {
@@ -189,7 +196,42 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubService for GithubServiceImpl
&self,
webhook_event: &ValidatedGithubWebhookEvent,
) -> Result<(), GithubError> {
- tracing::trace!(webhook_event=?webhook_event.0, "processing event");
+ let event_type = webhook_event.parsed_event_type();
+ tracing::info!(event_type=?event_type, "processing github webhook event");
+
+ if let GithubWebhookEventType::Unknown(ref name) = event_type {
+ tracing::debug!(event_type=%name, "skipping unknown event type");
+ return Ok(());
+ }
+
+ let searchable_texts = webhook_event.extract_searchable_text();
+ let combined = searchable_texts.join(" ");
+ let task_ids = MacroTaskId::extract_from_text(&combined);
+
+ if task_ids.is_empty() {
+ tracing::debug!(event_type=?event_type, "no task IDs found in event");
+ return Ok(());
+ }
+
+ for task_id in &task_ids {
+ match task_id.to_uuid() {
+ Ok(uuid) => {
+ tracing::info!(
+ task_id=%task_id,
+ uuid=%uuid,
+ event_type=?event_type,
+ "detected macro task ID in github event"
+ );
+ }
+ Err(e) => {
+ tracing::warn!(
+ task_id=%task_id,
+ error=?e,
+ "failed to convert task ID to UUID"
+ );
+ }
+ }
+ }
Ok(())
}
diff --git a/rust/cloud-storage/github/src/domain/service/test.rs b/rust/cloud-storage/github/src/domain/service/test.rs
new file mode 100644
index 0000000000..426e0984b0
--- /dev/null
+++ b/rust/cloud-storage/github/src/domain/service/test.rs
@@ -0,0 +1,160 @@
+use crate::domain::{
+ models::ValidatedGithubWebhookEvent,
+ ports::{GithubService, MockAuth, MockGithubOauth, MockGithubRepo},
+};
+
+use super::*;
+
+fn make_service() -> GithubServiceImpl<MockGithubRepo, MockGithubOauth, MockAuth> {
+ GithubServiceImpl::new(
+ MockGithubRepo::new(),
+ MockGithubOauth::new(),
+ MockAuth::new(),
+ GithubConfig {
+ client_id: "test-client-id".to_string(),
+ client_secret: "test-client-secret".to_string(),
+ idp_id: "test-idp-id".to_string(),
+ webhook_secret: "test-webhook-secret".to_string(),
+ github_sync_app_url: "test".to_string(),
+ },
+ )
+}
+
+#[tokio::test]
+async fn pr_with_task_id_in_title() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",
+ "body": null,
+ "head": { "ref": "feature/some-branch" }
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn pr_with_task_id_in_branch_name() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "some feature",
+ "body": "no task ids here",
+ "head": { "ref": "macro-2BuyvtY3aeEvHx4uG8iD51" }
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn issue_comment_with_task_id() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "issue_comment".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "comment": {
+ "body": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51"
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn event_with_no_task_ids() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "just a normal PR",
+ "body": "nothing special",
+ "head": { "ref": "feature/no-task-id" }
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn unknown_event_type_skipped() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "ping".to_string(),
+ serde_json::json!({"zen": "Keep it logically awesome."}),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn multiple_task_ids_in_one_event() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request".to_string(),
+ serde_json::json!({
+ "action": "opened",
+ "pull_request": {
+ "title": "closes MACRO-abc123",
+ "body": "also relates to MACRO-def456 and MACRO-ghi789",
+ "head": { "ref": "main" }
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn pull_request_review_with_task_id() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request_review".to_string(),
+ serde_json::json!({
+ "action": "submitted",
+ "review": {
+ "body": "Approved, relates to MACRO-2BuyvtY3aeEvHx4uG8iD51"
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn pull_request_review_comment_with_task_id() {
+ let service = make_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "pull_request_review_comment".to_string(),
+ serde_json::json!({
+ "action": "created",
+ "comment": {
+ "body": "This line is related to MACRO-abc123"
+ }
+ }),
+ );
+
+ let result = service.process_webhook_event(&event).await;
+ assert!(result.is_ok());
+}
diff --git a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
index 30024b6324..c7efaa66a2 100644
--- a/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
+++ b/rust/cloud-storage/github/src/inbound/github_sync_router/test.rs
@@ -38,6 +38,7 @@ impl GithubService for MockGithubService {
async fn validate_webhook_event(
&self,
+ _event_type: &str,
_signature: &str,
_body: &[u8],
) -> Result<ValidatedGithubWebhookEvent, GithubError> {
diff --git a/rust/cloud-storage/github/src/inbound/webhook_router.rs b/rust/cloud-storage/github/src/inbound/webhook_router.rs
index 2c644bf6d1..c0ec27632c 100644
--- a/rust/cloud-storage/github/src/inbound/webhook_router.rs
+++ b/rust/cloud-storage/github/src/inbound/webhook_router.rs
@@ -53,6 +53,12 @@ where
) -> Result<Self, Self::Rejection> {
let (parts, body) = req.into_parts();
+ let event_type = parts
+ .headers
+ .get("X-GitHub-Event")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("unknown");
+
let signature = parts
.headers
.get("X-Hub-Signature-256")
@@ -66,7 +72,7 @@ where
let event = state
.service
- .validate_webhook_event(signature, &body)
+ .validate_webhook_event(event_type, signature, &body)
.await?;
Ok(GithubWebhookEventExtractor(event))