Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
fix: resolve pinned slack message created by (#2838)
Maximilian Kaske23bac2532b0e
diff --git a/apps/server/src/routes/slack/handler.test.ts b/apps/server/src/routes/slack/handler.test.tsindex 8b8cd958e..42720c7d5 100644--- a/apps/server/src/routes/slack/handler.test.ts+++ b/apps/server/src/routes/slack/handler.test.ts@@ -5,8 +5,15 @@ import {incident,incidentEvent,integration,+ slackUser,+ user,+ usersToWorkspaces,} from "@openstatus/db/src/schema";-import { createTestWorkspace } from "@openstatus/db/src/test/factories";+import {+ addUserToWorkspace,+ createTestWorkspace,+ createUser,+} from "@openstatus/db/src/test/factories";import {afterEach,beforeEach,@@ -2213,6 +2220,139 @@ describe("incident channel events", () => {);});+ test("the note belongs to the author, not the pinner", async () => {+ const author = await createUser();+ await addUserToWorkspace(author.id, 1, "member");+ const authorSlackId = `U_AUTHOR_${crypto.randomUUID()}`;+ slackTestState.usersInfoImpl = (args) =>+ Promise.resolve({+ ok: true,+ user: {+ profile: {+ email:+ args.user === authorSlackId+ ? author.email+ : "[email protected]",+ },+ },+ });+ slackTestState.historyImpl = () =>+ Promise.resolve({+ messages: [+ { ts: "508.1", text: "I rolled it back", user: authorSlackId },+ ],+ });+ try {+ await pin("508.1");+ await waitForCall("reactions.add");+ const rows = await notes();+ expect(rows).toHaveLength(1);+ expect(rows[0].createdBy).toBe(author.id);+ } finally {+ // The note references the author; drop it before the user.+ await db+ .delete(incidentEvent)+ .where(eq(incidentEvent.incidentId, incidentId));+ await db+ .delete(slackUser)+ .where(eq(slackUser.slackUserId, authorSlackId));+ await db+ .delete(usersToWorkspaces)+ .where(eq(usersToWorkspaces.userId, author.id));+ await db.delete(user).where(eq(user.id, author.id));+ }+ });++ test("a bot message is attributed to the pinner without a lookup", async () => {+ // Apps with a bot user carry both `bot_id` and `user`.+ slackTestState.historyImpl = () =>+ Promise.resolve({+ messages: [+ {+ ts: "509.1",+ text: "[FIRING] api 5xx",+ bot_id: "B1",+ user: "U_BOT",+ },+ ],+ });+ await pin("509.1");+ await waitForCall("reactions.add");+ const rows = await notes();+ expect(rows).toHaveLength(1);+ const [pinner] = await db+ .select({ id: user.id })+ .from(user)+ .where(eq(user.email, "[email protected]"));+ expect(rows[0].createdBy).toBe(pinner.id);+ expect(+ slackTestState.calls.some(+ (m) => m.method === "users.info" && m.args.user === "U_BOT",+ ),+ ).toBe(false);+ });++ test("a failed author lookup releases the pin for a retry", async () => {+ const author = await createUser();+ await addUserToWorkspace(author.id, 1, "member");+ const authorSlackId = `U_AUTHOR_${crypto.randomUUID()}`;+ let flaky = true;+ slackTestState.usersInfoImpl = (args) => {+ if (args.user !== authorSlackId) {+ return Promise.resolve({+ ok: true,+ user: { profile: { email: "[email protected]" } },+ });+ }+ if (flaky) {+ const err = new Error("An API error occurred: ratelimited");+ Object.assign(err, { data: { ok: false, error: "ratelimited" } });+ return Promise.reject(err);+ }+ return Promise.resolve({+ ok: true,+ user: { profile: { email: author.email } },+ });+ };+ slackTestState.historyImpl = () =>+ Promise.resolve({+ messages: [{ ts: "510.1", text: "flaky lookup", user: authorSlackId }],+ });+ try {+ await pin("510.1");+ await settleBackgroundTasks();+ expect(await notes()).toHaveLength(0);+ expect(await waitForCall("reactions.add", 100)).toBeUndefined();+ const notice = await waitForCall("postEphemeral");+ expect(notice?.args.text).toContain("Pin it again");++ // A second failure stays quiet; the pinner was already told.+ await pin("510.1");+ await settleBackgroundTasks();+ expect(+ slackTestState.calls.filter((c) => c.method === "postEphemeral"),+ ).toHaveLength(1);++ flaky = false;+ await pin("510.1");+ await waitForCall("reactions.add");+ const rows = await notes();+ expect(rows).toHaveLength(1);+ expect(rows[0].createdBy).toBe(author.id);+ } finally {+ await db+ .delete(incidentEvent)+ .where(eq(incidentEvent.incidentId, incidentId));+ await db+ .delete(slackUser)+ .where(eq(slackUser.slackUserId, authorSlackId));+ await db+ .delete(usersToWorkspaces)+ .where(eq(usersToWorkspaces.userId, author.id));+ await db.delete(user).where(eq(user.id, author.id));+ }+ });+test("a message with only attachments is noted from their fallback", async () => {slackTestState.historyImpl = () =>Promise.resolve({diff --git a/apps/server/src/routes/slack/incident-events.ts b/apps/server/src/routes/slack/incident-events.tsindex a7467407d..e37f19aba 100644--- a/apps/server/src/routes/slack/incident-events.ts+++ b/apps/server/src/routes/slack/incident-events.ts@@ -18,7 +18,10 @@ import {requireSlackMember,slackAgentAllowed,} from "./require-slack-member";-import { resolveSlackMentionNames } from "./resolve-slack-user";+import {+ resolveSlackMember,+ resolveSlackMentionNames,+} from "./resolve-slack-user";import {collectMentions,mentionLabelsFromText,@@ -35,11 +38,15 @@ type SlackMessage = {ts?: string;text?: string;user?: string;+ bot_id?: string;+ subtype?: string;blocks?: unknown[];attachments?: { text?: string; fallback?: string }[];};const NOTHING_TO_COPY = "Nothing to copy from that message.";+const PIN_FAILED =+ "Couldn't copy that message to the timeline. Pin it again to retry.";const VERB_LAG_MS = 60_000;/**@@ -215,10 +222,31 @@ export async function handlePinReaction(args: {);return;}- const permalink = await slack.chat- .getPermalink({ channel, message_ts: ts })- .then((res) => res.permalink)- .catch(() => undefined);+ // The note belongs to whoever said it; bots and unlinked authors fall+ // back to the pinner. A lookup hiccup throws so the claim is released and+ // Slack retries, rather than pinning the wrong name forever.+ const authorSlackId =+ message?.user &&+ message.user !== slackUserId &&+ !message.bot_id &&+ message.subtype !== "bot_message"+ ? message.user+ : null;+ const [permalink, author] = await Promise.all([+ slack.chat+ .getPermalink({ channel, message_ts: ts })+ .then((res) => res.permalink)+ .catch(() => undefined),+ authorSlackId+ ? resolveSlackMember({+ workspace: resolved.workspace,+ teamId,+ slackUserId: authorSlackId,+ slack,+ strict: true,+ })+ : null,+ ]);const ctx: ServiceContext = { workspace: resolved.workspace, actor };await addIncidentNote({@@ -227,11 +255,32 @@ export async function handlePinReaction(args: {id: bound.id,message: permalink ? `${body}\n\n[From Slack](${permalink})` : body,createdAt: messageDate(ts),+ createdBy: author ?? undefined,},});trackSlackIncident(ctx, "note", { via: "reaction" });} catch (err) {await redis.del(claim).catch(() => undefined);+ // Slack retries the event, but a lost pin should not go unnoticed if it+ // keeps failing; one notice per message is enough.+ const once = await redis+ .set(`slack:pinfail:${channel}:${ts}`, "1", {+ nx: true,+ ex: 24 * 60 * 60,+ })+ .catch(() => null);+ if (once !== null) {+ await slack.chat+ .postEphemeral({+ channel,+ user: slackUserId,+ thread_ts: ts,+ text: PIN_FAILED,+ })+ .catch((error) =>+ logger.warn("slack failed to report a lost pin", { error }),+ );+ }throw err;}await slack.reactionsdiff --git a/apps/server/src/routes/slack/resolve-slack-user.ts b/apps/server/src/routes/slack/resolve-slack-user.tsindex ea3ada793..92b4987a5 100644--- a/apps/server/src/routes/slack/resolve-slack-user.ts+++ b/apps/server/src/routes/slack/resolve-slack-user.ts@@ -21,11 +21,18 @@ const logger = getLogger(["api-server", "slack", "resolve-user"]);* in a pinned message can create the mapping; it is the same rule applied* when they act themselves.*/+function isUserNotFound(err: unknown): boolean {+ const code = (err as { data?: { error?: string } })?.data?.error;+ return code === "user_not_found" || code === "users_not_found";+}+async function lookupSlackMember(args: {workspace: Workspace;teamId: string;slackUserId: string;slack: WebClient;+ /** Rethrow a failed lookup instead of answering "unlinked". */+ strict?: boolean;}): Promise<{ userId: number | null; profileName: string | null }> {const { workspace, teamId, slackUserId, slack } = args;if (!teamId || !slackUserId) return { userId: null, profileName: null };@@ -58,6 +65,9 @@ async function lookupSlackMember(args: {});return { userId, profileName };} catch (err) {+ // A user Slack no longer knows is unlinked for good; anything else+ // (rate limit, DB) is a hiccup the caller may want to retry.+ if (args.strict && !isUserNotFound(err)) throw err;logger.warn("slack user resolution failed", {workspaceId: workspace.id,teamId,@@ -70,12 +80,14 @@ async function lookupSlackMember(args: {/*** The openstatus member linked to a Slack user, or `null`. A missing link is* created on the spot when the Slack profile email matches exactly one member.+ * With `strict`, a failed lookup throws instead of passing for "unlinked".*/export async function resolveSlackMember(args: {workspace: Workspace;teamId: string;slackUserId: string;slack: WebClient;+ strict?: boolean;}): Promise<number | null> {return (await lookupSlackMember(args)).userId;}diff --git a/packages/api/src/router/incident.ts b/packages/api/src/router/incident.tsindex b3b024ef4..b1cd02d37 100644--- a/packages/api/src/router/incident.ts+++ b/packages/api/src/router/incident.ts@@ -284,7 +284,8 @@ export const incidentRouter = createTRPCRouter({addNote: protectedProcedure.meta({ track: Events.AddManagedIncidentNote })- .input(AddIncidentNoteInput)+ // `createdBy` is for trusted callers copying a note in (Slack pins).+ .input(AddIncidentNoteInput.omit({ createdBy: true })).mutation(async ({ ctx, input }) => {try {return await addIncidentNote({ ctx: toServiceCtx(ctx), input });diff --git a/packages/services/src/incident/__tests__/incident.test.ts b/packages/services/src/incident/__tests__/incident.test.tsindex 7dc78c156..6b2384d7f 100644--- a/packages/services/src/incident/__tests__/incident.test.ts+++ b/packages/services/src/incident/__tests__/incident.test.ts@@ -496,6 +496,44 @@ describe("addIncidentNote", () => {});});+ test("createdBy attributes the note to another member, actor stays audited", async () => {+ await withTestTransaction(async (tx) => {+ const row = await declare(tx);+ const note = await addIncidentNote({+ ctx: as(memberId, tx),+ input: { id: row.id, message: "said by admin", createdBy: adminId },+ });+ expect(note.createdBy).toBe(adminId);+ const [audit] = await tx+ .select()+ .from(auditLog)+ .where(+ and(+ eq(auditLog.entityType, "incident_event"),+ eq(auditLog.entityId, String(note.id)),+ ),+ );+ expect(audit?.actorUserId).toBe(memberId);+ const self = await addIncidentNote({+ ctx: as(memberId, tx),+ input: { id: row.id, message: "mine", createdBy: null },+ });+ expect(self.createdBy).toBe(memberId);+ });+ });++ test("rejects a createdBy outside the workspace", async () => {+ await withTestTransaction(async (tx) => {+ const row = await declare(tx);+ await expect(+ addIncidentNote({+ ctx: as(memberId, tx),+ input: { id: row.id, message: "spoofed", createdBy: outsiderId },+ }),+ ).rejects.toThrow(ValidationError);+ });+ });+test("a closed incident takes no notes", async () => {await withTestTransaction(async (tx) => {const row = await createIncident(diff --git a/packages/services/src/incident/add-note.ts b/packages/services/src/incident/add-note.tsindex 106f08425..cec546940 100644--- a/packages/services/src/incident/add-note.ts+++ b/packages/services/src/incident/add-note.ts@@ -4,6 +4,7 @@ import { requireScope } from "../auth";import { type ServiceContext, withTransaction } from "../context";import {appendIncidentEvent,+ assertMember,assertNotClosed,getIncidentInWorkspace,requireIncidentFeature,@@ -28,11 +29,15 @@ export async function addIncidentNote(args: {input.id,);assertNotClosed(existing);+ if (input.createdBy != null) {+ await assertMember(tx, ctx.workspace.id, input.createdBy);+ }return appendIncidentEvent(tx, ctx, {incidentId: existing.id,type: "note",message: input.message,createdAt: input.createdAt ?? undefined,+ createdBy: input.createdBy,});});}diff --git a/packages/services/src/incident/internal.ts b/packages/services/src/incident/internal.tsindex 501168d64..294f53c24 100644--- a/packages/services/src/incident/internal.ts+++ b/packages/services/src/incident/internal.ts@@ -79,6 +79,7 @@ export async function appendIncidentEvent(type: IncidentEventType;message?: string | null;createdAt?: Date;+ createdBy?: number | null;},): Promise<IncidentEvent> {const event = await tx@@ -87,7 +88,7 @@ export async function appendIncidentEvent(incidentId: args.incidentId,type: args.type,message: args.message ?? null,- createdBy: tryGetActorUserId(ctx.actor),+ createdBy: args.createdBy ?? tryGetActorUserId(ctx.actor),createdAt: args.createdAt ?? new Date(),}).returning()diff --git a/packages/services/src/incident/schemas.ts b/packages/services/src/incident/schemas.tsindex 4c6599357..0e9a4e28b 100644--- a/packages/services/src/incident/schemas.ts+++ b/packages/services/src/incident/schemas.ts@@ -66,6 +66,11 @@ export const AddIncidentNoteInput = z.object({"createdAt must be within the last 30 days and at most a minute ahead",}).nullish(),+ // The member who wrote the note when someone else copies it in (a pinned+ // Slack message). The actor stays the one who performed the action. Trusted+ // callers only: a public route must omit it or anyone could speak for a+ // colleague.+ createdBy: id.nullish(),});export type AddIncidentNoteInput = z.infer<typeof AddIncidentNoteInput>;