From 3e1909d6581df791bdbb4af2e58ddd9f04e91839 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 22 Jul 2026 09:25:20 +0700 Subject: [PATCH 1/4] fix(webhook): drop dead approve buttons from the leave notification The Discord app that fortress-api posts with is now the Hermes desk bot, whose slash commands are delivered over the gateway. Discord delivers interactions either over the gateway or to an app's HTTP endpoint, never both, so that app cannot also carry the interactions endpoint these buttons were answered on. Rendering them anyway gives the lead a button that fails silently, which is worse than no button. Link the Notion page instead so the request is actionable today; approval moves into conversation with the bot next. The custom_id handlers stay: they hold the approve/reject side effects that the conversational path will call. --- pkg/handler/webhook/notion_leave.go | 40 +++++++++--------------- pkg/handler/webhook/notion_leave_test.go | 30 ++++++++++++++++++ 2 files changed, 45 insertions(+), 25 deletions(-) create mode 100644 pkg/handler/webhook/notion_leave_test.go diff --git a/pkg/handler/webhook/notion_leave.go b/pkg/handler/webhook/notion_leave.go index 1f8de96d..c0927e52 100644 --- a/pkg/handler/webhook/notion_leave.go +++ b/pkg/handler/webhook/notion_leave.go @@ -3,7 +3,7 @@ package webhook import ( "context" "crypto/hmac" -"crypto/sha256" + "crypto/sha256" "encoding/hex" "encoding/json" "errors" @@ -308,6 +308,12 @@ func formatShortDateRange(start, end time.Time) string { end.Month().String()[:3], end.Day(), end.Year()) } +// notionPageURL builds a browser link to a Notion page. The API hands back dashed +// UUIDs; notion.so wants them undashed, and serves the dashed form as a 404. +func notionPageURL(pageID string) string { + return "https://www.notion.so/" + strings.ReplaceAll(pageID, "-", "") +} + // verifyNotionWebhookSignature verifies the HMAC-SHA256 signature of a Notion webhook request func (h *handler) verifyNotionWebhookSignature(body []byte, signature, token string) bool { // Remove "sha256=" prefix if present @@ -690,34 +696,18 @@ func (h *handler) sendLeaveNotification( {Name: "Type", Value: leave.UnavailabilityType, Inline: true}, {Name: "Dates", Value: formatShortDateRange(*leave.StartDate, *leave.EndDate), Inline: true}, {Name: "Details", Value: leave.AdditionalContext, Inline: false}, + {Name: "Approve", Value: fmt.Sprintf("Set **Status** on the [request page](%s).", notionPageURL(leave.PageID)), Inline: false}, }, Timestamp: time.Now().Format("2006-01-02T15:04:05.000-07:00"), } - components := []discordgo.MessageComponent{ - discordgo.ActionsRow{ - Components: []discordgo.MessageComponent{ - discordgo.Button{ - Label: "Approve", - Style: discordgo.SecondaryButton, - CustomID: fmt.Sprintf("notion_leave_approve_%s", leave.PageID), - Emoji: discordgo.ComponentEmoji{ - Name: "✅", - }, - }, - discordgo.Button{ - Label: "Reject", - Style: discordgo.SecondaryButton, - CustomID: fmt.Sprintf("notion_leave_reject_%s", leave.PageID), - Emoji: discordgo.ComponentEmoji{ - Name: "❌", - }, - }, - }, - }, - } - - msg, err := h.service.Discord.SendChannelMessageComplex(channelID, assigneeMentions, []*discordgo.MessageEmbed{embed}, components) + // No Approve/Reject buttons. A button click is an interaction, and Discord delivers + // interactions either over the gateway or to an app's HTTP endpoint, never both. This + // bot's application is the Hermes desk (Neko Bot), whose slash commands need the + // gateway, so it cannot also carry the HTTP endpoint these buttons were answered on. + // Buttons here would render and silently do nothing, which is worse than no buttons. + // The link above is the interim; approval moves into conversation with the bot. + msg, err := h.service.Discord.SendChannelMessageComplex(channelID, assigneeMentions, []*discordgo.MessageEmbed{embed}, nil) if err != nil { l.Error(err, "failed to send leave request message to discord channel") // Fallback to auditlog diff --git a/pkg/handler/webhook/notion_leave_test.go b/pkg/handler/webhook/notion_leave_test.go new file mode 100644 index 00000000..5201cd33 --- /dev/null +++ b/pkg/handler/webhook/notion_leave_test.go @@ -0,0 +1,30 @@ +package webhook + +import "testing" + +func TestNotionPageURL(t *testing.T) { + cases := []struct { + name string + pageID string + want string + }{ + { + name: "dashed uuid from the notion api", + pageID: "2ce64b29-b84c-8164-b9f5-ce5a4797ada5", + want: "https://www.notion.so/2ce64b29b84c8164b9f5ce5a4797ada5", + }, + { + name: "already undashed", + pageID: "2ce64b29b84c8164b9f5ce5a4797ada5", + want: "https://www.notion.so/2ce64b29b84c8164b9f5ce5a4797ada5", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := notionPageURL(tc.pageID); got != tc.want { + t.Errorf("notionPageURL(%q) = %q, want %q", tc.pageID, got, tc.want) + } + }) + } +} From 5fb3ff114f3d4876df04c7fe79c820fe9e5b208f Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 22 Jul 2026 10:49:52 +0700 Subject: [PATCH 2/4] feat(webhook): conversational leave approval endpoints with AM/DL authz Add /webhooks/discord/leave/{list,approve,reject}, called by the fortress MCP behind the Neko Bot desk. These add the authorization the retired Approve/Reject buttons never had: only an Account Manager or Delivery Lead on the requester's active deployment (or an admin) may decide a request; everyone else gets 403. Reuses the existing Notion deployment/stakeholder resolution and the leave side effects (status + calendar), with an idempotency guard so a repeat approval cannot double-book the calendar. Unlike gen-invoice (no HTTP auth, trusts its body), a leave decision is a state change keyed on a claimed approver handle, so the routes are gated by fortress's API-key + permission middleware. Handle comparison is case-folded and discriminator-stripped so a real lead is never refused. The notification now points leads at the bot command instead of a dead button. Companion to dfoundation SPEC-087 (the MCP tools + skill) and the ops-toolkit gateway patch 0009. --- pkg/handler/webhook/interface.go | 3 + pkg/handler/webhook/leave_decision.go | 267 +++++++++++++++++++++ pkg/handler/webhook/leave_decision_test.go | 39 +++ pkg/handler/webhook/notion_leave.go | 2 +- pkg/routes/v1.go | 8 + 5 files changed, 318 insertions(+), 1 deletion(-) create mode 100644 pkg/handler/webhook/leave_decision.go create mode 100644 pkg/handler/webhook/leave_decision_test.go diff --git a/pkg/handler/webhook/interface.go b/pkg/handler/webhook/interface.go index 83e17622..b26435c7 100644 --- a/pkg/handler/webhook/interface.go +++ b/pkg/handler/webhook/interface.go @@ -23,4 +23,7 @@ type IHandler interface { HandleNotionTaskOrderSendEmail(c *gin.Context) HandleDiscordInteraction(c *gin.Context) HandleGenInvoice(c *gin.Context) + HandleLeaveList(c *gin.Context) + HandleLeaveApprove(c *gin.Context) + HandleLeaveReject(c *gin.Context) } diff --git a/pkg/handler/webhook/leave_decision.go b/pkg/handler/webhook/leave_decision.go new file mode 100644 index 00000000..4e517e79 --- /dev/null +++ b/pkg/handler/webhook/leave_decision.go @@ -0,0 +1,267 @@ +package webhook + +// Conversational leave approval (SPEC-087). The Discord Approve/Reject buttons were retired when +// fortress-api's Discord identity became the Hermes desk bot (an app cannot both carry an HTTP +// interactions endpoint and keep its gateway slash commands). Approval now arrives as a call from +// the fortress MCP (behind the desk bot), which resolves the AUTHENTICATED lead's Discord handle +// from a gateway-minted token and calls these endpoints. +// +// These endpoints add the authorization the button flow never had: only an Account Manager or +// Delivery Lead on the requester's active deployment (or an admin) may decide a request. The old +// buttons recorded whoever clicked into "Reviewed By" but authorized nobody. +// +// Auth: unlike /webhooks/discord/gen-invoice (which has no HTTP auth and trusts its body), a leave +// decision is a state change keyed on a CLAIMED approver handle, so an unauthenticated endpoint +// would be a full bypass (POST any AM's handle -> approved). The routes are therefore gated by +// fortress's own API-key + permission middleware (see routes/v1.go); this handler trusts +// approver_handle only because that gate ensures the caller is the MCP behind the desk bot. + +import ( + "context" + "fmt" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "github.com/dwarvesf/fortress-api/pkg/logger" + notionSvc "github.com/dwarvesf/fortress-api/pkg/service/notion" + "github.com/dwarvesf/fortress-api/pkg/view" +) + +// adminApproverEmails may decide any request even with no active deployment (empty AM/DL set), +// mirroring the notification's fallback assignees (SPEC-087 DEC-007). +var adminApproverEmails = []string{"han@d.foundation", "thanhpd@d.foundation"} + +// LeaveDecisionRequest is the body the fortress MCP posts for approve/reject. +type LeaveDecisionRequest struct { + ApproverHandle string `json:"approver_handle"` // the AUTHENTICATED lead handle (from the gateway token, not model text) + RequestID string `json:"request_id"` // the leave request title, e.g. OOO-2026-minhth-YCZT + Reason string `json:"reason"` // optional, reject only +} + +// LeaveListRequest is the body for list_pending_leaves. +type LeaveListRequest struct { + ApproverHandle string `json:"approver_handle"` +} + +// normalizeHandle folds case and drops a legacy #discriminator so the caller's handle and the +// Notion "Discord" field compare equal even when the two sources disagree on format (DEC-006). +func normalizeHandle(h string) string { + h = strings.TrimSpace(strings.ToLower(h)) + if i := strings.IndexByte(h, '#'); i >= 0 { + h = h[:i] + } + return h +} + +// resolveApproverHandles returns the normalized Discord handles allowed to decide this request: +// the AM/DL on the requester's active deployments, plus the admin allowlist. The same resolution +// the notification uses (getAMDLMentionsFromDeployments), but returning handles for a membership +// check rather than mentions. +func (h *handler) resolveApproverHandles(ctx context.Context, l logger.Logger, leaveService *notionSvc.LeaveService, leave notionSvc.LeaveRequest) map[string]bool { + allowed := map[string]bool{} + + contractorPageID, err := leaveService.LookupContractorByEmail(ctx, leave.Email) + if err == nil && contractorPageID != "" { + deployments, err := leaveService.GetActiveDeploymentsForContractor(ctx, contractorPageID) + if err != nil { + l.Warnf("resolveApproverHandles: deployments lookup failed: contractor_id=%s: %v", contractorPageID, err) + } + seen := map[string]bool{} + for _, dep := range deployments { + for _, stakeholderID := range leaveService.ExtractStakeholdersFromDeployment(ctx, dep) { + if stakeholderID == contractorPageID || seen[stakeholderID] { + continue // the requester is not their own approver; dedup across deployments + } + seen[stakeholderID] = true + username, err := leaveService.GetDiscordUsernameFromContractor(ctx, stakeholderID) + if err != nil || username == "" { + continue + } + allowed[normalizeHandle(username)] = true + } + } + } else if err != nil { + l.Warnf("resolveApproverHandles: contractor lookup failed: email=%s: %v", leave.Email, err) + } + + // Admin allowlist: resolve the fallback-assignee emails to handles via the DB. + for _, email := range adminApproverEmails { + if handle := h.discordHandleForEmail(l, email); handle != "" { + allowed[normalizeHandle(handle)] = true + } + } + return allowed +} + +// discordHandleForEmail resolves an employee email to their Discord username via the local mirror. +func (h *handler) discordHandleForEmail(l logger.Logger, email string) string { + db := h.repo.DB() + employee, err := h.store.Employee.OneByEmail(db, email) + if err != nil || employee == nil || employee.DiscordAccountID.String() == "" { + return "" + } + acc, err := h.store.DiscordAccount.One(db, employee.DiscordAccountID.String()) + if err != nil || acc == nil { + return "" + } + return acc.DiscordUsername +} + +// findPendingLeaveByTitle resolves a request id (its title) to the pending LeaveRequest. Titles are +// unique by construction (handle + random suffix). Returns ok=false when no pending request matches. +func (h *handler) findPendingLeaveByTitle(ctx context.Context, leaveService *notionSvc.LeaveService, requestID string) (notionSvc.LeaveRequest, bool, error) { + pending, err := leaveService.QueryPendingLeaveRequests(ctx) + if err != nil { + return notionSvc.LeaveRequest{}, false, err + } + want := strings.TrimSpace(requestID) + for _, lr := range pending { + if strings.EqualFold(strings.TrimSpace(lr.LeaveRequestTitle), want) { + return lr, true, nil + } + } + return notionSvc.LeaveRequest{}, false, nil +} + +// applyLeaveDecision is the side-effect core shared by the endpoints (the button handlers keep +// their own inline copy for now). "approve" -> Status Acknowledged + a calendar event; "reject" -> +// Status Not Applicable, no calendar. Idempotent: if the request is already decided, it does NOT +// re-create the calendar event, so two near-simultaneous approvals cannot double-book (edge case 2). +func (h *handler) applyLeaveDecision(ctx context.Context, l logger.Logger, leaveService *notionSvc.LeaveService, pageID, approverPageID, decision string) { + // Idempotency guard: read current status first; skip the calendar side effect if already decided. + alreadyDecided := false + if cur, err := leaveService.GetLeaveRequest(ctx, pageID); err == nil && cur != nil { + switch cur.Status { + case "Acknowledged", "Not Applicable", "Withdrawn": + alreadyDecided = true + } + } + + status := "Acknowledged" + if decision == "reject" { + status = "Not Applicable" + } + if err := leaveService.UpdateLeaveStatus(ctx, pageID, status, approverPageID); err != nil { + l.Errorf(err, "applyLeaveDecision: UpdateLeaveStatus failed: page_id=%s decision=%s", pageID, decision) + } + if decision == "approve" && !alreadyDecided { + if err := h.createCalendarEventForLeave(ctx, l, leaveService, pageID); err != nil { + l.Errorf(err, "applyLeaveDecision: calendar event failed: page_id=%s", pageID) + } + } +} + +// HandleLeaveList handles POST /webhooks/discord/leave/list: return the pending requests THIS +// caller may decide. ponytail: resolves approvers per pending request (N small Notion queries); +// pending count is a handful, upgrade to a batched rollup only if that stops being true. +func (h *handler) HandleLeaveList(c *gin.Context) { + l := h.logger.Fields(logger.Fields{"handler": "webhook", "method": "HandleLeaveList"}) + var req LeaveListRequest + if err := c.ShouldBindJSON(&req); err != nil || req.ApproverHandle == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "approver_handle required"}) + return + } + ctx := context.Background() + leaveService := notionSvc.NewLeaveService(h.config, h.store, h.repo, h.logger) + if leaveService == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "notion service not configured"}) + return + } + pending, err := leaveService.QueryPendingLeaveRequests(ctx) + if err != nil { + l.Errorf(err, "HandleLeaveList: query pending failed") + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to query leave requests"}) + return + } + caller := normalizeHandle(req.ApproverHandle) + type item struct { + RequestID string `json:"request_id"` + Type string `json:"type"` + Start string `json:"start_date"` + End string `json:"end_date"` + } + out := []item{} + for _, lr := range pending { + if !h.resolveApproverHandles(ctx, l, leaveService, lr)[caller] { + continue + } + it := item{RequestID: lr.LeaveRequestTitle, Type: lr.UnavailabilityType} + if lr.StartDate != nil { + it.Start = lr.StartDate.Format("2006-01-02") + } + if lr.EndDate != nil { + it.End = lr.EndDate.Format("2006-01-02") + } + out = append(out, it) + } + c.JSON(http.StatusOK, gin.H{"requests": out}) +} + +// HandleLeaveApprove handles POST /webhooks/discord/leave/approve. +func (h *handler) HandleLeaveApprove(c *gin.Context) { h.handleLeaveDecision(c, "approve") } + +// HandleLeaveReject handles POST /webhooks/discord/leave/reject. +func (h *handler) HandleLeaveReject(c *gin.Context) { h.handleLeaveDecision(c, "reject") } + +func (h *handler) handleLeaveDecision(c *gin.Context, decision string) { + l := h.logger.Fields(logger.Fields{"handler": "webhook", "method": "handleLeaveDecision", "decision": decision}) + var req LeaveDecisionRequest + if err := c.ShouldBindJSON(&req); err != nil || req.ApproverHandle == "" || req.RequestID == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "approver_handle and request_id required"}) + return + } + ctx := context.Background() + leaveService := notionSvc.NewLeaveService(h.config, h.store, h.repo, h.logger) + if leaveService == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "notion service not configured"}) + return + } + + leave, ok, err := h.findPendingLeaveByTitle(ctx, leaveService, req.RequestID) + if err != nil { + l.Errorf(err, "handleLeaveDecision: lookup failed: request=%s", req.RequestID) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to look up leave request"}) + return + } + if !ok { + c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("no pending leave request: %s", req.RequestID)}) + return + } + + // Authorization: the caller must be an AM/DL on the requester's active deployment (or an admin). + allowed := h.resolveApproverHandles(ctx, l, leaveService, leave) + caller := normalizeHandle(req.ApproverHandle) + if !allowed[caller] { + l.Infof("handleLeaveDecision: refused non-approver: caller=%s request=%s", caller, req.RequestID) + c.JSON(http.StatusForbidden, gin.H{"error": "not an approver (Account Manager or Delivery Lead) for this request"}) + return + } + + // The approver's own contractor page (for "Reviewed By"); empty is acceptable (as in the button + // flow) for an admin who is not a deployment stakeholder. + approverPageID := "" + if pid, err := leaveService.LookupContractorByEmail(ctx, h.emailForDiscordHandle(l, req.ApproverHandle)); err == nil { + approverPageID = pid + } + + // Return immediately; apply the side effects async, matching the gen-invoice pattern. + c.JSON(http.StatusOK, view.CreateResponse[any](gin.H{"request_id": req.RequestID, "decision": decision}, nil, nil, nil, "")) + go h.applyLeaveDecision(context.Background(), l, leaveService, leave.PageID, approverPageID, decision) +} + +// emailForDiscordHandle resolves a Discord handle to the employee's team email via the local mirror +// (the inverse of discordHandleForEmail). Used to find the approver's contractor page. +func (h *handler) emailForDiscordHandle(l logger.Logger, handle string) string { + db := h.repo.DB() + acc, err := h.store.DiscordAccount.OneByUsername(db, strings.TrimSpace(handle)) + if err != nil || acc == nil { + return "" + } + employee, err := h.store.Employee.GetByDiscordID(db, acc.DiscordID, false) + if err != nil || employee == nil { + return "" + } + return employee.TeamEmail +} diff --git a/pkg/handler/webhook/leave_decision_test.go b/pkg/handler/webhook/leave_decision_test.go new file mode 100644 index 00000000..2a50a42b --- /dev/null +++ b/pkg/handler/webhook/leave_decision_test.go @@ -0,0 +1,39 @@ +package webhook + +import "testing" + +// normalizeHandle is the security-critical comparison for leave approval: the caller's handle +// (from the gateway token) is matched against the AM/DL set (from the Notion "Discord" field). A +// format disagreement between the two sources must NOT silently refuse a real lead, and must NOT +// let a near-miss through. (SPEC-087 DEC-006.) +func TestNormalizeHandle(t *testing.T) { + cases := []struct { + in, want string + }{ + {"innno_", "innno_"}, + {"Innno_", "innno_"}, // case fold + {" innno_ ", "innno_"}, // trim + {"innno_#1234", "innno_"}, // legacy discriminator stripped + {"Innno_#0001", "innno_"}, // case + discriminator + {"HAN.d", "han.d"}, // dotted new-style handle + {"", ""}, // empty stays empty (never matches a real handle) + } + for _, c := range cases { + if got := normalizeHandle(c.in); got != c.want { + t.Errorf("normalizeHandle(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// Two handles that differ only by case/discriminator must compare EQUAL after normalization +// (a real lead is not refused), and two genuinely different handles must NOT (an impostor is +// refused). +func TestNormalizeHandle_MembershipSemantics(t *testing.T) { + allowed := map[string]bool{normalizeHandle("Innno_#1234"): true} + if !allowed[normalizeHandle("innno_")] { + t.Fatal("a real lead whose Notion handle carries a discriminator must still match") + } + if allowed[normalizeHandle("innno")] { + t.Fatal("a different handle (innno vs innno_) must NOT match") + } +} diff --git a/pkg/handler/webhook/notion_leave.go b/pkg/handler/webhook/notion_leave.go index c0927e52..1f2b7252 100644 --- a/pkg/handler/webhook/notion_leave.go +++ b/pkg/handler/webhook/notion_leave.go @@ -696,7 +696,7 @@ func (h *handler) sendLeaveNotification( {Name: "Type", Value: leave.UnavailabilityType, Inline: true}, {Name: "Dates", Value: formatShortDateRange(*leave.StartDate, *leave.EndDate), Inline: true}, {Name: "Details", Value: leave.AdditionalContext, Inline: false}, - {Name: "Approve", Value: fmt.Sprintf("Set **Status** on the [request page](%s).", notionPageURL(leave.PageID)), Inline: false}, + {Name: "Approve / Reject", Value: fmt.Sprintf("Message **Neko Bot**: `approve %s` or `reject %s`. Or open the [request page](%s).", leave.LeaveRequestTitle, leave.LeaveRequestTitle, notionPageURL(leave.PageID)), Inline: false}, }, Timestamp: time.Now().Format("2006-01-02T15:04:05.000-07:00"), } diff --git a/pkg/routes/v1.go b/pkg/routes/v1.go index d04b3800..6c572212 100644 --- a/pkg/routes/v1.go +++ b/pkg/routes/v1.go @@ -89,6 +89,14 @@ func loadV1Routes(r *gin.Engine, h *handler.Handler, repo store.DBRepo, s *store webhook.POST("/discord/interaction", h.Webhook.HandleDiscordInteraction) webhook.POST("/discord/gen-invoice", h.Webhook.HandleGenInvoice) + // Conversational leave approval (SPEC-087). Unlike gen-invoice, these are a state change + // keyed on a claimed approver handle, so they are gated by API-key + permission (the caller + // is the fortress MCP behind the Neko Bot desk). PermissionCronjobExecute is the machine-to- + // machine default; a dedicated leave-approve permission is a fortress-team follow-up. + webhook.POST("/discord/leave/list", conditionalAuthMW, conditionalPermMW(model.PermissionCronjobExecute), h.Webhook.HandleLeaveList) + webhook.POST("/discord/leave/approve", conditionalAuthMW, conditionalPermMW(model.PermissionCronjobExecute), h.Webhook.HandleLeaveApprove) + webhook.POST("/discord/leave/reject", conditionalAuthMW, conditionalPermMW(model.PermissionCronjobExecute), h.Webhook.HandleLeaveReject) + basecampGroup := webhook.Group("/basecamp") { expenseGroup := basecampGroup.Group("/expense") From 17f629ccfab3410a5faf45f2db1ad8065c60c416 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 22 Jul 2026 11:25:11 +0700 Subject: [PATCH 3/4] test(webhook): cover leave decision logic (title match, idempotency) Extract the title-resolution and already-decided predicates into pure helpers and test them alongside the handle-normalization authz check. The full handler wiring is proven by the live UAT (a real innno_ leave request posted to #project-talk tagging the AM/DL); a handler-level unit test would need a LeaveService interface refactor, deferred. --- pkg/handler/webhook/leave_decision.go | 25 ++++++++++---- pkg/handler/webhook/leave_decision_test.go | 38 ++++++++++++++++++++++ 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/pkg/handler/webhook/leave_decision.go b/pkg/handler/webhook/leave_decision.go index 4e517e79..c828ed37 100644 --- a/pkg/handler/webhook/leave_decision.go +++ b/pkg/handler/webhook/leave_decision.go @@ -116,15 +116,31 @@ func (h *handler) findPendingLeaveByTitle(ctx context.Context, leaveService *not if err != nil { return notionSvc.LeaveRequest{}, false, err } - want := strings.TrimSpace(requestID) for _, lr := range pending { - if strings.EqualFold(strings.TrimSpace(lr.LeaveRequestTitle), want) { + if leaveTitleMatches(lr.LeaveRequestTitle, requestID) { return lr, true, nil } } return notionSvc.LeaveRequest{}, false, nil } +// leaveTitleMatches compares a candidate leave title against a requested id, tolerant of +// surrounding whitespace and case (the model relays the title as the lead typed it). +func leaveTitleMatches(candidate, requestID string) bool { + return strings.EqualFold(strings.TrimSpace(candidate), strings.TrimSpace(requestID)) +} + +// isLeaveAlreadyDecided reports whether a leave request has already been acted on, so a repeat or +// concurrent decision does not re-run the calendar side effect (SPEC-087 edge case 2). +func isLeaveAlreadyDecided(status string) bool { + switch status { + case "Acknowledged", "Not Applicable", "Withdrawn": + return true + default: + return false + } +} + // applyLeaveDecision is the side-effect core shared by the endpoints (the button handlers keep // their own inline copy for now). "approve" -> Status Acknowledged + a calendar event; "reject" -> // Status Not Applicable, no calendar. Idempotent: if the request is already decided, it does NOT @@ -133,10 +149,7 @@ func (h *handler) applyLeaveDecision(ctx context.Context, l logger.Logger, leave // Idempotency guard: read current status first; skip the calendar side effect if already decided. alreadyDecided := false if cur, err := leaveService.GetLeaveRequest(ctx, pageID); err == nil && cur != nil { - switch cur.Status { - case "Acknowledged", "Not Applicable", "Withdrawn": - alreadyDecided = true - } + alreadyDecided = isLeaveAlreadyDecided(cur.Status) } status := "Acknowledged" diff --git a/pkg/handler/webhook/leave_decision_test.go b/pkg/handler/webhook/leave_decision_test.go index 2a50a42b..6e405d3d 100644 --- a/pkg/handler/webhook/leave_decision_test.go +++ b/pkg/handler/webhook/leave_decision_test.go @@ -37,3 +37,41 @@ func TestNormalizeHandle_MembershipSemantics(t *testing.T) { t.Fatal("a different handle (innno vs innno_) must NOT match") } } + +// leaveTitleMatches resolves the request id (the title the lead typed) to a pending request, +// tolerant of case and surrounding whitespace but not of a genuinely different id. +func TestLeaveTitleMatches(t *testing.T) { + cases := []struct { + candidate, requestID string + want bool + }{ + {"OOO-2026-innno_-HGU4", "OOO-2026-innno_-HGU4", true}, + {"OOO-2026-innno_-HGU4", " OOO-2026-innno_-HGU4 ", true}, // trimmed + {"OOO-2026-innno_-HGU4", "ooo-2026-innno_-hgu4", true}, // case-fold + {"OOO-2026-innno_-HGU4", "OOO-2026-innno_-XXXX", false}, // different code + {"OOO-2026-innno_-HGU4", "OOO-2026-minhth-HGU4", false}, // different person + {"", "", true}, // degenerate; guarded upstream by required-field checks + } + for _, c := range cases { + if got := leaveTitleMatches(c.candidate, c.requestID); got != c.want { + t.Errorf("leaveTitleMatches(%q,%q) = %v, want %v", c.candidate, c.requestID, got, c.want) + } + } +} + +// isLeaveAlreadyDecided drives the idempotency guard: only a still-open (New/pending) request +// gets a fresh calendar event; anything already decided must not double-book. +func TestIsLeaveAlreadyDecided(t *testing.T) { + decided := []string{"Acknowledged", "Not Applicable", "Withdrawn"} + open := []string{"New", "", "Pending", "in review"} + for _, s := range decided { + if !isLeaveAlreadyDecided(s) { + t.Errorf("status %q should count as already decided", s) + } + } + for _, s := range open { + if isLeaveAlreadyDecided(s) { + t.Errorf("status %q should NOT count as already decided", s) + } + } +} From 789aa85e60f4293c10c9d0efa30020bfad8826d3 Mon Sep 17 00:00:00 2001 From: Han Ngo Date: Wed, 22 Jul 2026 11:42:39 +0700 Subject: [PATCH 4/4] feat(webhook): restore approve/reject buttons for the dual approval flow Both front-ends now share one authorized backend: the buttons (handled by the Hermes gateway, patch 0010) and the DM tool both call the leave endpoints. Put the buttons back on the notification and make request_id accept either a page id (button custom_id) or a title (DM). The endpoint's AM/DL authz applies to both. --- pkg/handler/webhook/leave_decision.go | 33 ++++++++++++++-------- pkg/handler/webhook/leave_decision_test.go | 19 +++++++++++++ pkg/handler/webhook/notion_leave.go | 23 +++++++++------ 3 files changed, 56 insertions(+), 19 deletions(-) diff --git a/pkg/handler/webhook/leave_decision.go b/pkg/handler/webhook/leave_decision.go index c828ed37..3b73b36a 100644 --- a/pkg/handler/webhook/leave_decision.go +++ b/pkg/handler/webhook/leave_decision.go @@ -1,12 +1,13 @@ package webhook -// Conversational leave approval (SPEC-087). The Discord Approve/Reject buttons were retired when -// fortress-api's Discord identity became the Hermes desk bot (an app cannot both carry an HTTP -// interactions endpoint and keep its gateway slash commands). Approval now arrives as a call from -// the fortress MCP (behind the desk bot), which resolves the AUTHENTICATED lead's Discord handle -// from a gateway-minted token and calls these endpoints. +// Leave approval backend (SPEC-087), shared by TWO front-ends that both route through the Hermes +// gateway (Neko Bot's interactions can't reach an HTTP endpoint without killing its slash commands): +// - a Discord Approve/Reject BUTTON click -> gateway notion_leave_* handler (hermes patch 0010) +// - a DM "approve " -> the fortress MCP approve_leave tool +// Both authenticate the clicker/sender, mint an identity token, and call these endpoints. request_id +// is a title (DM) or a Notion page id (button); findPendingLeave accepts either. // -// These endpoints add the authorization the button flow never had: only an Account Manager or +// These endpoints add the authorization the old button flow never had: only an Account Manager or // Delivery Lead on the requester's active deployment (or an admin) may decide a request. The old // buttons recorded whoever clicked into "Reviewed By" but authorized nobody. // @@ -109,21 +110,31 @@ func (h *handler) discordHandleForEmail(l logger.Logger, email string) string { return acc.DiscordUsername } -// findPendingLeaveByTitle resolves a request id (its title) to the pending LeaveRequest. Titles are -// unique by construction (handle + random suffix). Returns ok=false when no pending request matches. -func (h *handler) findPendingLeaveByTitle(ctx context.Context, leaveService *notionSvc.LeaveService, requestID string) (notionSvc.LeaveRequest, bool, error) { +// findPendingLeave resolves a request id to the pending LeaveRequest. The id is either the +// human title (from the DM tool, e.g. OOO-2026-innno_-HGU4) or the Notion page id (from a button's +// custom_id). Both front-ends converge here. Returns ok=false when no pending request matches. +func (h *handler) findPendingLeave(ctx context.Context, leaveService *notionSvc.LeaveService, requestID string) (notionSvc.LeaveRequest, bool, error) { pending, err := leaveService.QueryPendingLeaveRequests(ctx) if err != nil { return notionSvc.LeaveRequest{}, false, err } + want := strings.TrimSpace(requestID) for _, lr := range pending { - if leaveTitleMatches(lr.LeaveRequestTitle, requestID) { + if leaveTitleMatches(lr.LeaveRequestTitle, requestID) || leavePageIDMatches(lr.PageID, want) { return lr, true, nil } } return notionSvc.LeaveRequest{}, false, nil } +// leavePageIDMatches compares a Notion page id ignoring dash formatting (the API returns dashed +// UUIDs; a button custom_id may carry the undashed form). +func leavePageIDMatches(candidate, requestID string) bool { + strip := func(s string) string { return strings.ToLower(strings.ReplaceAll(strings.TrimSpace(s), "-", "")) } + c := strip(candidate) + return c != "" && c == strip(requestID) +} + // leaveTitleMatches compares a candidate leave title against a requested id, tolerant of // surrounding whitespace and case (the model relays the title as the lead typed it). func leaveTitleMatches(candidate, requestID string) bool { @@ -232,7 +243,7 @@ func (h *handler) handleLeaveDecision(c *gin.Context, decision string) { return } - leave, ok, err := h.findPendingLeaveByTitle(ctx, leaveService, req.RequestID) + leave, ok, err := h.findPendingLeave(ctx, leaveService, req.RequestID) if err != nil { l.Errorf(err, "handleLeaveDecision: lookup failed: request=%s", req.RequestID) c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to look up leave request"}) diff --git a/pkg/handler/webhook/leave_decision_test.go b/pkg/handler/webhook/leave_decision_test.go index 6e405d3d..a3f5dac7 100644 --- a/pkg/handler/webhook/leave_decision_test.go +++ b/pkg/handler/webhook/leave_decision_test.go @@ -75,3 +75,22 @@ func TestIsLeaveAlreadyDecided(t *testing.T) { } } } + +// A button carries the Notion page id; the DM carries the title. Both must resolve, and dash +// formatting on the page id must not matter. +func TestLeavePageIDMatches(t *testing.T) { + cases := []struct { + candidate, requestID string + want bool + }{ + {"3a564b29-b84c-81a6-bd55-fa785e0c3b1d", "3a564b29-b84c-81a6-bd55-fa785e0c3b1d", true}, + {"3a564b29-b84c-81a6-bd55-fa785e0c3b1d", "3a564b29b84c81a6bd55fa785e0c3b1d", true}, // undashed + {"3a564b29-b84c-81a6-bd55-fa785e0c3b1d", "OOO-2026-innno_-HGU4", false}, // a title, not a page id + {"", "", false}, // empty page id never matches + } + for _, c := range cases { + if got := leavePageIDMatches(c.candidate, c.requestID); got != c.want { + t.Errorf("leavePageIDMatches(%q,%q) = %v, want %v", c.candidate, c.requestID, got, c.want) + } + } +} diff --git a/pkg/handler/webhook/notion_leave.go b/pkg/handler/webhook/notion_leave.go index 1f2b7252..3617d8f5 100644 --- a/pkg/handler/webhook/notion_leave.go +++ b/pkg/handler/webhook/notion_leave.go @@ -696,18 +696,25 @@ func (h *handler) sendLeaveNotification( {Name: "Type", Value: leave.UnavailabilityType, Inline: true}, {Name: "Dates", Value: formatShortDateRange(*leave.StartDate, *leave.EndDate), Inline: true}, {Name: "Details", Value: leave.AdditionalContext, Inline: false}, - {Name: "Approve / Reject", Value: fmt.Sprintf("Message **Neko Bot**: `approve %s` or `reject %s`. Or open the [request page](%s).", leave.LeaveRequestTitle, leave.LeaveRequestTitle, notionPageURL(leave.PageID)), Inline: false}, + {Name: "Approve / Reject", Value: fmt.Sprintf("Tap a button below, or message **Neko Bot** `approve %s` / `reject %s`.", leave.LeaveRequestTitle, leave.LeaveRequestTitle), Inline: false}, }, Timestamp: time.Now().Format("2006-01-02T15:04:05.000-07:00"), } - // No Approve/Reject buttons. A button click is an interaction, and Discord delivers - // interactions either over the gateway or to an app's HTTP endpoint, never both. This - // bot's application is the Hermes desk (Neko Bot), whose slash commands need the - // gateway, so it cannot also carry the HTTP endpoint these buttons were answered on. - // Buttons here would render and silently do nothing, which is worse than no buttons. - // The link above is the interim; approval moves into conversation with the bot. - msg, err := h.service.Discord.SendChannelMessageComplex(channelID, assigneeMentions, []*discordgo.MessageEmbed{embed}, nil) + // Both approval front-ends share one authorized backend (SPEC-087). A button click is a + // component interaction; because this message is posted as Neko Bot, that interaction is + // delivered over the Hermes GATEWAY (not to an HTTP endpoint, which would kill Neko Bot's + // slash commands). The gateway's notion_leave_* handler (hermes patch 0010) authenticates + // the clicker, mints an identity token, and calls the SAME /webhooks/discord/leave endpoint + // the DM tool calls. The custom_id carries the page id; the endpoint accepts a page id or a + // title as request_id, so button and DM converge. + components := []discordgo.MessageComponent{ + discordgo.ActionsRow{Components: []discordgo.MessageComponent{ + discordgo.Button{Label: "Approve", Style: discordgo.SecondaryButton, CustomID: fmt.Sprintf("notion_leave_approve_%s", leave.PageID), Emoji: discordgo.ComponentEmoji{Name: "✅"}}, + discordgo.Button{Label: "Reject", Style: discordgo.SecondaryButton, CustomID: fmt.Sprintf("notion_leave_reject_%s", leave.PageID), Emoji: discordgo.ComponentEmoji{Name: "❌"}}, + }}, + } + msg, err := h.service.Discord.SendChannelMessageComplex(channelID, assigneeMentions, []*discordgo.MessageEmbed{embed}, components) if err != nil { l.Error(err, "failed to send leave request message to discord channel") // Fallback to auditlog