Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

28.6 KB
Raw Blame
import { describe, it, expect, beforeEach } from 'bun:test';
import { apiKeyApi, authedApi, type Api, createProject } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { createAgent } from '#tests/helpers/agents';
import { addProjectMember } from '#tests/helpers/members';
import { createRole } from '#tests/helpers/roles';
import type { WebhookEventType } from '../../service';
import { onProjectEvent, type ProjectEvent } from '../../emit';

async function setupOwnerProject() {
  const owner = await signUpTestUser({ name: 'Owner' });
  const asOwner = authedApi(owner.cookie);
  const project = await createProject(asOwner, { key: 'MKT', name: 'Marketing' });
  // createProject seeds five default columns; the first is the target for issues.
  const view = await asOwner.projects({ projectKey: 'MKT' }).get();
  return {
    owner,
    asOwner,
    projectId: project.data!.id,
    teamRef: project.data!.teamRef,
    columnId: view.data!.columns[0].id,
    columns: view.data!.columns,
  };
}

// The payloads queued for a webhook, newest first.
async function payloads(client: Api, webhookId: number) {
  const res = await client.webhooks({ webhookId }).deliveries.get();
  return res.data!.items.map((d) => d.payload as { actor: unknown; data: Record<string, unknown> });
}

// Registers a webhook on MKT and returns its id.
async function createWebhook(
  client: Api,
  events: WebhookEventType[],
  opts: { isActive?: boolean } = {},
): Promise<number> {
  const res = await client.projects({ projectKey: 'MKT' }).webhooks.post({
    url: 'https://example.com/hook',
    events,
    ...opts,
  });
  return res.data!.id;
}

describe('webhooks', () => {
  beforeEach(async () => {
    await resetDb();
  });

  describe('create and list', () => {
    it('creates a webhook with a generated secret and lists it', async () => {
      const { asOwner, projectId } = await setupOwnerProject();

      const created = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://example.com/hook',
        events: ['issue.created', 'issue.updated'],
      });
      expect(created.status).toBe(201);
      expect(created.data).toMatchObject({
        projectId,
        url: 'https://example.com/hook',
        events: ['issue.created', 'issue.updated'],
        isActive: true,
      });
      expect(typeof created.data?.id).toBe('number');
      expect(created.data?.secret).toMatch(/^whsec_/);

      const list = await asOwner.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(list.status).toBe(200);
      expect(list.data).toHaveLength(1);
      expect(list.data?.[0]).toMatchObject({ url: 'https://example.com/hook' });
    });

    it('honors an explicit isActive false', async () => {
      const { asOwner } = await setupOwnerProject();
      const created = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://example.com/hook',
        events: ['issue.created'],
        isActive: false,
      });
      expect(created.status).toBe(201);
      expect(created.data).toMatchObject({ isActive: false });
    });
  });

  describe('validation', () => {
    it('rejects a non-https url', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'http://example.com/hook',
        events: ['issue.created'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects a url pointing at a private address', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://192.168.0.10/hook',
        events: ['issue.created'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects a url pointing at localhost', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://localhost/hook',
        events: ['issue.created'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects an IPv4-mapped IPv6 url pointing at a private address', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://[::ffff:169.254.169.254]/hook',
        events: ['issue.created'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects a hostname that resolves to a private address', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://localtest.me/hook',
        events: ['issue.created'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects an empty events list', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://example.com/hook',
        events: [],
      });
      expect(res.status).toBe(400);
    });

    it('rejects an unknown event type', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://example.com/hook',
        // @ts-expect-error unknown event type is rejected by the schema
        events: ['issue.exploded'],
      });
      expect(res.status).toBe(400);
    });

    it('rejects a non-numeric webhook id', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 'abc' }).patch({ isActive: false });
      expect(res.status).toBe(400);
    });
  });

  describe('update', () => {
    it('updates only the provided fields', async () => {
      const { asOwner } = await setupOwnerProject();
      const id = (
        await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
          url: 'https://example.com/hook',
          events: ['issue.created'],
        })
      ).data!.id;

      const patched = await asOwner.webhooks({ webhookId: id }).patch({
        events: ['issue.deleted', 'comment.created'],
        isActive: false,
      });
      expect(patched.status).toBe(200);
      expect(patched.data).toMatchObject({
        url: 'https://example.com/hook',
        events: ['issue.deleted', 'comment.created'],
        isActive: false,
      });
    });

    it('validates the url on update', async () => {
      const { asOwner } = await setupOwnerProject();
      const id = (
        await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
          url: 'https://example.com/hook',
          events: ['issue.created'],
        })
      ).data!.id;

      const res = await asOwner.webhooks({ webhookId: id }).patch({ url: 'http://example.com/x' });
      expect(res.status).toBe(400);
    });

    it('returns 404 when patching a missing webhook', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 999999 }).patch({ isActive: false });
      expect(res.status).toBe(404);
    });
  });

  describe('rotate secret', () => {
    it('replaces the secret and lists the new one', async () => {
      const { asOwner } = await setupOwnerProject();
      const created = await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://example.com/hook',
        events: ['issue.created'],
      });
      const webhookId = created.data!.id;

      const rotated = await asOwner.webhooks({ webhookId }).secret.post();
      expect(rotated.status).toBe(200);
      expect(rotated.data?.secret).toMatch(/^whsec_/);
      expect(rotated.data?.secret).not.toBe(created.data!.secret);

      const list = await asOwner.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(list.data?.[0].secret).toBe(rotated.data!.secret);
    });

    it('returns 404 for a missing webhook', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 999999 }).secret.post();
      expect(res.status).toBe(404);
    });
  });

  describe('delete', () => {
    it('deletes a webhook', async () => {
      const { asOwner } = await setupOwnerProject();
      const id = (
        await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
          url: 'https://example.com/hook',
          events: ['issue.created'],
        })
      ).data!.id;

      const del = await asOwner.webhooks({ webhookId: id }).delete();
      expect(del.status).toBe(204);

      const list = await asOwner.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(list.data).toHaveLength(0);
    });

    it('returns 404 when deleting a missing webhook', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 999999 }).delete();
      expect(res.status).toBe(404);
    });
  });

  describe('deliveries', () => {
    it('returns an empty page for a webhook with no deliveries', async () => {
      const { asOwner } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.created']);

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      expect(res.status).toBe(200);
      expect(res.data).toMatchObject({ items: [], nextCursor: null });
    });

    it('returns 404 for a missing webhook', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 999999 }).deliveries.get();
      expect(res.status).toBe(404);
    });

    it('rejects a non-numeric webhook id', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.webhooks({ webhookId: 'abc' }).deliveries.get();
      expect(res.status).toBe(400);
    });

    it('paginates newest-first with a keyset cursor', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.created']);

      // Three issue.created events queue three deliveries on this webhook.
      for (const title of ['a', 'b', 'c']) {
        await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title });
      }

      const first = await asOwner
        .webhooks({ webhookId: id })
        .deliveries.get({ query: { limit: 2 } });
      expect(first.status).toBe(200);
      expect(first.data?.items).toHaveLength(2);
      expect(first.data?.nextCursor).not.toBeNull();
      // Newest first: ids strictly descending.
      expect(first.data!.items[0].id).toBeGreaterThan(first.data!.items[1].id);

      const second = await asOwner
        .webhooks({ webhookId: id })
        .deliveries.get({ query: { before: first.data!.nextCursor!, limit: 2 } });
      expect(second.data?.items).toHaveLength(1);
      expect(second.data?.nextCursor).toBeNull();
      // The cursor page continues below the first page's last id.
      expect(second.data!.items[0].id).toBeLessThan(first.data!.items[1].id);
    });
  });

  // emit.ts queues one webhook_delivery per active, subscribed webhook when a
  // domain mutation fires an event. The queued rows are observable through the
  // deliveries endpoint (the delivery worker does not run in tests, so they stay
  // pending). These assert the fan-out selection, not the worker.
  describe('fan-out', () => {
    it('queues a pending delivery for a subscribed active webhook on issue.created', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.created']);

      await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' });

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      expect(res.data?.items).toHaveLength(1);
      expect(res.data!.items[0]).toMatchObject({
        eventType: 'issue.created',
        status: 'pending',
        attempts: 0,
        responseStatus: null,
      });
      // The payload uses the Linear-style envelope: action + resource type, with
      // the granular event kept in `event`.
      expect(res.data!.items[0].payload).toMatchObject({
        action: 'create',
        type: 'Issue',
        event: 'issue.created',
      });
    });

    it('does not queue for an inactive webhook', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.created'], { isActive: false });

      await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' });

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      expect(res.data?.items).toHaveLength(0);
    });

    it('does not queue for an event the webhook is not subscribed to', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['comment.created']);

      await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' });

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      expect(res.data?.items).toHaveLength(0);
    });

    it('fans out to every matching webhook with a shared event id', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const a = await createWebhook(asOwner, ['issue.created']);
      const b = await createWebhook(asOwner, ['issue.created']);

      await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' });

      const da = await asOwner.webhooks({ webhookId: a }).deliveries.get();
      const db = await asOwner.webhooks({ webhookId: b }).deliveries.get();
      expect(da.data?.items).toHaveLength(1);
      expect(db.data?.items).toHaveLength(1);
      // One event, one id shared across both deliveries so a receiver can dedupe.
      expect(da.data!.items[0].eventId).toBe(db.data!.items[0].eventId);
    });

    it('fires the granular issue.state_changed alongside issue.updated on a column move', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const view = await asOwner.projects({ projectKey: 'MKT' }).get();
      const otherColumn = view.data!.columns[1].id;
      const id = await createWebhook(asOwner, ['issue.updated', 'issue.state_changed']);

      const issue = await asOwner
        .projects({ projectKey: 'MKT' })
        .issues.post({ columnId, title: 'Task' });
      await asOwner.issues({ issueId: issue.data!.id }).patch({ columnId: otherColumn });

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      const types = res.data!.items.map((d) => d.eventType).sort();
      expect(types).toEqual(['issue.state_changed', 'issue.updated']);
    });

    it('queues a delivery on comment.created', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['comment.created']);

      const issue = await asOwner
        .projects({ projectKey: 'MKT' })
        .issues.post({ columnId, title: 'Task' });
      await asOwner.issues({ issueId: issue.data!.id }).comments.post({ body: 'looks good' });

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      expect(res.data?.items).toHaveLength(1);
      expect(res.data!.items[0]).toMatchObject({ eventType: 'comment.created' });
    });

    it('queues a delivery on comment.updated and comment.deleted', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['comment.updated', 'comment.deleted']);

      const issue = await asOwner
        .projects({ projectKey: 'MKT' })
        .issues.post({ columnId, title: 'Task' });
      const comment = (
        await asOwner.issues({ issueId: issue.data!.id }).comments.post({ body: 'draft' })
      ).data!;
      await asOwner.comments({ commentId: comment.id }).patch({ body: 'final' });
      await asOwner.comments({ commentId: comment.id }).delete();

      const res = await asOwner.webhooks({ webhookId: id }).deliveries.get();
      const byEvent = Object.fromEntries(res.data!.items.map((d) => [d.eventType, d]));
      expect(byEvent['comment.updated']).toMatchObject({
        payload: expect.objectContaining({ action: 'update', type: 'Comment' }),
      });
      expect(byEvent['comment.deleted']).toMatchObject({
        payload: expect.objectContaining({
          action: 'remove',
          type: 'Comment',
          // A delete carries the comment as it last read.
          data: expect.objectContaining({ id: comment.id, body: 'final' }),
        }),
      });
    });
  });

  describe('payload', () => {
    it('names the actor, state, assignee, type, and labels of an issue event', async () => {
      const { owner, asOwner, columnId, columns } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.assigned']);
      const label = (
        await asOwner.projects({ projectKey: 'MKT' }).labels.post({ name: 'bug', color: '#ff0000' })
      ).data!;
      const issue = (
        await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId, title: 'Task', labelIds: [label.id] })
      ).data!;

      await asOwner.issues({ issueId: issue.id }).patch({ assigneeUserId: owner.userId });

      const [payload] = await payloads(asOwner, id);
      expect(payload.actor).toEqual({ type: 'human', id: owner.userId, name: 'Owner' });
      expect(payload.data).toMatchObject({
        id: issue.id,
        title: 'Task',
        assigneeUserId: owner.userId,
        assignee: { id: owner.userId, name: 'Owner' },
        delegate: null,
        state: { id: columnId, name: columns[0].name, type: columns[0].stateType },
        labels: [{ id: label.id, name: 'bug', color: '#ff0000' }],
      });
    });

    it('names the labels a label change added and removed', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.label_changed']);
      const labels = asOwner.projects({ projectKey: 'MKT' }).labels;
      const bug = (await labels.post({ name: 'bug' })).data!;
      const ui = (await labels.post({ name: 'ui' })).data!;
      const issue = (
        await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId, title: 'Task', labelIds: [bug.id] })
      ).data!;

      await asOwner.issues({ issueId: issue.id }).patch({ labelIds: [ui.id] });

      const [payload] = await payloads(asOwner, id);
      expect(payload.data).toMatchObject({
        labels: [{ id: ui.id, name: 'ui' }],
        labelChange: { added: [{ id: ui.id, name: 'ui' }], removed: [{ id: bug.id, name: 'bug' }] },
      });
    });

    it('marks an agent as the actor of what it does', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.created']);
      const created = (
        await createAgent(asOwner, 'MKT', {
          name: 'Triage Bot',
          username: 'triage',
          kind: 'external',
        })
      ).data!;

      const res = await apiKeyApi(created.apiKey!)
        .projects({ projectKey: 'MKT' })
        .issues.post({ columnId, title: 'Filed by the agent' });
      expect(res.status).toBe(201);

      const [payload] = await payloads(asOwner, id);
      expect(payload.actor).toEqual({
        type: 'agent',
        id: created.agent.userId,
        name: 'Triage Bot',
      });
    });

    it('carries the issue as it last read on issue.deleted', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.deleted']);
      const issue = (
        await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Doomed' })
      ).data!;

      await asOwner.issues({ issueId: issue.id }).delete();

      const [payload] = await payloads(asOwner, id);
      expect(payload).toMatchObject({ action: 'remove', actor: { type: 'human' } });
      expect(payload.data).toMatchObject({
        id: issue.id,
        identifier: issue.identifier,
        title: 'Doomed',
        state: { id: columnId },
      });
    });

    it('names the issue a comment is on', async () => {
      const { asOwner, columnId, teamRef } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['comment.created']);
      const issue = (
        await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })
      ).data!;

      const comment = (
        await asOwner.issues({ issueId: issue.id }).comments.post({ body: 'looks good' })
      ).data!;

      const [payload] = await payloads(asOwner, id);
      const issueLink = `${process.env.APP_URL}/${teamRef}/issue/${issue.identifier}`;
      expect(payload.data.url).toBe(`${issueLink}#comment-${comment.id}`);
      expect(payload.data.issue).toMatchObject({
        id: issue.id,
        identifier: issue.identifier,
        title: 'Task',
        url: issueLink,
      });
    });
  });

  describe('events without a field edit', () => {
    it('fires issue.updated on archive and restore', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const id = await createWebhook(asOwner, ['issue.updated']);
      const issue = (
        await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task' })
      ).data!;

      await asOwner.issues({ issueId: issue.id }).archive.post({});
      await asOwner.issues({ issueId: issue.id }).restore.post();

      const [restored, archived] = await payloads(asOwner, id);
      expect(archived.data.archivedAt).not.toBeNull();
      expect(restored.data.archivedAt).toBeNull();
    });

    it('fires issue.state_changed for the issues a deleted column moves', async () => {
      const { asOwner, columns } = await setupOwnerProject();
      const [from, to] = columns.filter((c) => c.stateType !== 'backlog');
      const id = await createWebhook(asOwner, ['issue.state_changed']);
      const issue = (
        await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId: from.id, title: 'Task' })
      ).data!;

      await asOwner
        .projects({ projectKey: 'MKT' })
        .columns({ columnId: from.id })
        .delete({ mode: 'move', targetColumnId: to.id });

      const [payload] = await payloads(asOwner, id);
      expect(payload.data).toMatchObject({ id: issue.id, state: { id: to.id } });
    });

    it('fires issue.deleted for the issues a deleted column removes', async () => {
      const { asOwner, columns } = await setupOwnerProject();
      const column = columns.find((c) => c.stateType !== 'backlog')!;
      const id = await createWebhook(asOwner, ['issue.deleted']);
      const issue = (
        await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId: column.id, title: 'Task' })
      ).data!;

      await asOwner
        .projects({ projectKey: 'MKT' })
        .columns({ columnId: column.id })
        .delete({ mode: 'delete' });

      const [payload] = await payloads(asOwner, id);
      expect(payload.data).toMatchObject({
        id: issue.id,
        title: 'Task',
        state: { id: column.id, name: column.name },
      });
    });
  });

  describe('listeners', () => {
    it('hands an event to a listener with no webhook subscribed, and loads its payload once', async () => {
      const { owner, asOwner, projectId, columnId } = await setupOwnerProject();
      const events: ProjectEvent[] = [];
      const payloads: unknown[][] = [];
      const offFirst = onProjectEvent(async (event) => {
        events.push(event);
        payloads.push(await event.load());
      });
      const offSecond = onProjectEvent(async (event) => {
        payloads.push(await event.load());
      });
      try {
        const issue = await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId, title: 'Task' });

        expect(events.map((e) => [e.projectId, e.type, e.actor])).toEqual([
          [projectId, 'issue.created', owner.userId],
        ]);
        expect(payloads[0]).toEqual([expect.objectContaining({ id: issue.data!.id })]);
        expect(payloads[1]).toBe(payloads[0]);
      } finally {
        offFirst();
        offSecond();
      }
    });

    it('hands a listener the issues a deleted column removes, with no webhook subscribed', async () => {
      const { asOwner, columns } = await setupOwnerProject();
      const column = columns.find((c) => c.stateType !== 'backlog')!;
      const issue = (
        await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId: column.id, title: 'Task' })
      ).data!;
      const deleted: unknown[] = [];
      const off = onProjectEvent(async (event) => {
        if (event.type === 'issue.deleted') deleted.push(...(await event.load()));
      });
      try {
        await asOwner
          .projects({ projectKey: 'MKT' })
          .columns({ columnId: column.id })
          .delete({ mode: 'delete' });

        expect(deleted).toEqual([expect.objectContaining({ id: issue.id })]);
      } finally {
        off();
      }
    });

    it('keeps the write and the webhooks when a listener throws', async () => {
      const { asOwner, columnId } = await setupOwnerProject();
      const webhookId = await createWebhook(asOwner, ['issue.created']);
      const off = onProjectEvent(async () => {
        throw new Error('listener down');
      });
      try {
        const res = await asOwner
          .projects({ projectKey: 'MKT' })
          .issues.post({ columnId, title: 'Task' });

        expect(res.status).toBe(201);
        expect(await payloads(asOwner, webhookId)).toHaveLength(1);
      } finally {
        off();
      }
    });
  });

  describe('access', () => {
    it('returns 404 for an unknown project', async () => {
      const { asOwner } = await setupOwnerProject();
      const res = await asOwner.projects({ projectKey: 'NOPE' }).webhooks.get();
      expect(res.status).toBe(404);
    });

    it('denies a non-member on project-scoped and entity routes', async () => {
      const { asOwner } = await setupOwnerProject();
      const webhookId = (
        await asOwner.projects({ projectKey: 'MKT' }).webhooks.post({
          url: 'https://example.com/hook',
          events: ['issue.created'],
        })
      ).data!.id;

      const outsider = authedApi((await signUpTestUser()).cookie);

      // Guard-thrown 403 is not in Treaty's inferred error-status union, so
      // assert the top-level HTTP status (typed number) rather than error.status.
      const list = await outsider.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(list.status).toBe(403);

      const create = await outsider.projects({ projectKey: 'MKT' }).webhooks.post({
        url: 'https://evil.example.com/hook',
        events: ['issue.created'],
      });
      expect(create.status).toBe(403);

      const patch = await outsider.webhooks({ webhookId }).patch({ isActive: false });
      expect(patch.status).toBe(403);

      const del = await outsider.webhooks({ webhookId }).delete();
      expect(del.status).toBe(403);

      const rotate = await outsider.webhooks({ webhookId }).secret.post();
      expect(rotate.status).toBe(403);

      const deliveries = await outsider.webhooks({ webhookId }).deliveries.get();
      expect(deliveries.status).toBe(403);
    });

    it('returns the secret only to a caller who may create or edit webhooks', async () => {
      const { asOwner } = await setupOwnerProject();
      const webhookId = await createWebhook(asOwner, ['issue.created']);

      const readRole = await createRole(asOwner, 'MKT', {
        name: 'Webhook reader',
        permissions: { webhooks: { read: true } },
      });
      const asReader = await addProjectMember(asOwner, 'MKT', readRole.data!.id);
      const read = await asReader.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(read.status).toBe(200);
      expect(read.data?.[0]).toMatchObject({ id: webhookId, secret: null });
      expect((await asReader.webhooks({ webhookId }).secret.post()).status).toBe(403);

      const editRole = await createRole(asOwner, 'MKT', {
        name: 'Webhook editor',
        permissions: { webhooks: { read: true, edit: true } },
      });
      const asEditor = await addProjectMember(asOwner, 'MKT', editRole.data!.id);
      const edited = await asEditor.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(edited.data?.[0].secret).toMatch(/^whsec_/);

      const creatorRole = await createRole(asOwner, 'MKT', {
        name: 'Webhook creator',
        permissions: { webhooks: { read: true, create: true } },
      });
      const asCreator = await addProjectMember(asOwner, 'MKT', creatorRole.data!.id);
      const created = await asCreator.projects({ projectKey: 'MKT' }).webhooks.get();
      expect(created.data?.[0].secret).toMatch(/^whsec_/);
    });
  });
});