SPB Git

Repository Public

webhooks.spec.ts 11.3 KB 202 lines typescript

1// Console d'administration — webhooks : destination interne permise (réauthentification), création, secret montré une fois,2// événement d'essai signé reçu par un vrai récepteur HTTP local, journal, rejeu, renouvellement du secret, refus SSRF, suppression.3import crypto from "node:crypto"4import http from "node:http"5import type { AddressInfo } from "node:net"6import type { Page } from "@playwright/test"7import { axeBoth, clearReauth, confirmReauth, expect, grantReauth, noOverflow, openAdmin, st, test } from "./fixtures"89interface Hit {10  headers: http.IncomingHttpHeaders11  body: string12}13/** Récepteur local : note les en-têtes et le corps brut de chaque POST, répond 204. */14async function startReceiver(): Promise<{ port: number; hits: Hit[]; close: () => Promise<void> }> {15  const hits: Hit[] = []16  const server = http.createServer((req, res) => {17    const chunks: Buffer[] = []18    req.on("data", (c: Buffer) => chunks.push(c))19    req.on("end", () => {20      hits.push({ headers: req.headers, body: Buffer.concat(chunks).toString("utf8") })21      res.statusCode = 20422      res.end()23    })24  })25  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))26  return { port: (server.address() as AddressInfo).port, hits, close: () => new Promise((resolve) => server.close(() => resolve())) }27}28/** Vérification du récepteur (docs/API.md §11.4) : HMAC-SHA256 de `t + "." + corps brut`, fenêtre de 5 minutes. */29function verify(secret: string, header: string | undefined, raw: string): boolean {30  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? "")31  if (!m) return false32  if (Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false33  const expected = crypto.createHmac("sha256", secret).update(`${m[1]}.${raw}`).digest()34  const given = Buffer.from(m[2], "hex")35  return given.length === expected.length && crypto.timingSafeEqual(given, expected)36}37/** Le dialogue du secret : lit la valeur, confirme l'avoir enregistrée, ferme. */38async function readSecret(page: Page): Promise<string> {39  const dlg = page.getByTestId("secret-dialog")40  await expect(dlg).toBeVisible()41  const secret = await dlg.getByTestId("secret-value").inputValue()42  // impossible de fermer sans cocher43  await expect(dlg.getByRole("button", { name: "Fermer" })).toBeDisabled()44  await dlg.getByRole("checkbox", { name: "J'ai enregistré ce secret en lieu sûr" }).check()45  await dlg.getByRole("button", { name: "Fermer" }).click()46  await expect(dlg).toBeHidden()47  return secret48}4950test("webhooks : destination interne, création, essai signé, journal, rejeu, rotation, refus SSRF, suppression", async ({ page, watch }) => {51  test.setTimeout(240_000)52  // réponses attendues : 403 reauth_required (invite de clé d'accès) et 403 forbidden_destination (URL privée)53  watch.allow.push(/status of 403/)54  const rx = await startReceiver()55  const hostPort = `127.0.0.1:${rx.port}`56  const name = `web-hook-${st.run}-${crypto.randomBytes(2).toString("hex")}`57  const renamed = `${name}-b`58  try {59    await openAdmin(page, "webhooks")60    await expect(page.getByRole("heading", { level: 2, name: "Webhooks" })).toBeVisible()61    const allow = page.getByTestId("webhook-allowlist")62    await expect(allow).toBeVisible()63    await expect(allow).toContainText("Les redirections ne sont jamais suivies")6465    // ---- destination interne : forme refusée sur place, puis ajout avec invite de clé d'accès, rejoué seul66    await allow.getByLabel("Hôte:port à permettre").fill("http://127.0.0.1/hook")67    await allow.getByTestId("allow-add").click()68    await expect(allow.getByTestId("allow-error")).toContainText("Forme attendue")69    clearReauth()70    await allow.getByLabel("Hôte:port à permettre").fill(hostPort)71    await allow.getByLabel("Note (facultative)").fill(`essai ${st.run}`)72    await allow.getByTestId("allow-add").click()73    await confirmReauth(page)74    const allowRow = allow.locator(`[data-testid="allow-row"][data-host-port="${hostPort}"]`)75    await expect(allowRow).toBeVisible()76    await expect(allowRow).toContainText(`essai ${st.run}`)77    await axeBoth(page, "webhooks-liste")78    await noOverflow(page)7980    // ---- refus : URL illisible (sur place), URL privée hors liste (403 du serveur, en phrase claire)81    await page.getByTestId("webhook-new").click()82    const editor = page.getByTestId("webhook-editor")83    await expect(editor.getByRole("heading", { level: 3, name: "Nouveau webhook" })).toBeFocused()84    await editor.getByLabel("Nom", { exact: true }).fill(name)85    await editor.getByLabel("URL de destination").fill("ftp://exemple.org/hook")86    await editor.getByTestId("webhook-events").getByRole("checkbox", { name: /message\.received/ }).check()87    await editor.getByTestId("webhook-save").click()88    await expect(editor.getByTestId("webhook-error")).toContainText("Seules les URL en https")89    await editor.getByLabel("URL de destination").fill("https://10.0.0.1/hook")90    await expect(editor.getByTestId("webhook-url-note")).toContainText("adresse privée ou locale")91    await editor.getByTestId("webhook-save").click()92    await expect(editor.getByTestId("webhook-error")).toContainText("Destination refusée")93    await expect(editor.getByTestId("webhook-error")).toContainText("destinations internes permises")9495    // ---- création vers le récepteur local (hôte:port permis), avertissement de confidentialité, secret montré une fois96    await editor.getByLabel("URL de destination").fill(`http://${hostPort}/hook`)97    await expect(editor.getByTestId("webhook-url-note")).toContainText("figure dans les destinations internes permises")98    await editor.getByTestId("webhook-events").getByRole("checkbox", { name: /message\.sent/ }).check()99    await expect(editor.getByTestId("webhook-events")).toContainText("2 événements sélectionnés")100    await editor.getByLabel("Inclure l'objet et l'aperçu des messages reçus").check()101    await expect(editor.getByTestId("webhook-content-warning")).toContainText("quittent le serveur")102    await axeBoth(page, "webhooks-editeur")103    await noOverflow(page)104    await editor.getByLabel("Inclure l'objet et l'aperçu des messages reçus").uncheck()105    await editor.getByTestId("webhook-save").click()106    const secret1 = await readSecret(page)107    expect(secret1).toMatch(/^whsec_[A-Za-z0-9_-]{20,}$/)108    const card = page.locator('[data-testid="webhook-card"]', { hasText: name })109    await expect(card).toBeVisible()110    await expect(card).toContainText("Actif")111    await expect(card).toContainText("message.received")112    await expect(card).toContainText("Toutes les adresses")113    // le secret n'est plus nulle part dans la page114    expect(await page.content()).not.toContain(secret1)115116    // ---- événement d'essai : reçu, signé avec le secret117    await card.getByRole("button", { name: "Envoyer un événement d'essai" }).click()118    await expect(card.locator('[data-testid="webhook-test-result"] [data-outcome="ok"]')).toContainText("HTTP 204")119    expect(rx.hits.length).toBe(1)120    const first = rx.hits[0]121    expect(first.headers["spmail-event-type"]).toBe("webhook.test")122    expect(JSON.parse(first.body).type).toBe("webhook.test")123    expect(verify(secret1, first.headers["spmail-signature"] as string, first.body)).toBe(true)124    expect(verify("whsec_autre", first.headers["spmail-signature"] as string, first.body)).toBe(false)125    const eventId = first.headers["spmail-event-id"] as string126    expect(eventId).toMatch(/^evt_/)127128    // ---- journal : la livraison est « remise » ; rejeu → même identifiant d'événement, nouvelle signature valide129    await card.getByRole("button", { name: "Livraisons" }).click()130    const log = page.getByTestId("webhook-deliveries")131    await expect(log.getByRole("heading", { level: 3 })).toContainText(name)132    const row = log.locator(`[data-testid="delivery-row"][data-event-id="${eventId}"]`)133    await expect(row).toHaveAttribute("data-status", "delivered")134    await expect(row).toContainText("webhook.test")135    await expect(row).toContainText("Remise")136    await expect(row).toContainText("HTTP 204")137    await axeBoth(page, "webhooks-livraisons")138    await noOverflow(page)139    await row.getByRole("button", { name: "Rejouer" }).click()140    await expect.poll(() => rx.hits.length, { timeout: 45_000 }).toBe(2)141    const again = rx.hits[1]142    expect(again.headers["spmail-event-id"]).toBe(eventId)143    expect(again.body).toBe(first.body)144    expect(verify(secret1, again.headers["spmail-signature"] as string, again.body)).toBe(true)145    await expect(async () => {146      await log.getByTestId("deliveries-refresh").click()147      await expect(row).toHaveAttribute("data-status", "delivered", { timeout: 2000 })148    }).toPass({ timeout: 30_000 })149    // filtre par état : rien en échec définitif150    await log.getByLabel("État").selectOption("failed")151    await expect(log).toContainText("Aucune livraison dans cet état.")152    await log.getByLabel("État").selectOption("")153    await expect(row).toBeVisible()154155    // ---- renouvellement du secret : confirmation, invite de clé d'accès, nouveau secret montré une fois156    await page.getByTestId("webhook-back").click()157    await expect(card).toBeVisible()158    clearReauth()159    await card.getByRole("button", { name: "Renouveler le secret" }).click()160    await page.getByRole("alertdialog").getByRole("button", { name: "Renouveler", exact: true }).click()161    await confirmReauth(page)162    const secret2 = await readSecret(page)163    expect(secret2).toMatch(/^whsec_/)164    expect(secret2).not.toBe(secret1)165    await card.getByRole("button", { name: "Envoyer un événement d'essai" }).click()166    await expect.poll(() => rx.hits.length, { timeout: 30_000 }).toBe(3)167    const third = rx.hits[2]168    expect(verify(secret2, third.headers["spmail-signature"] as string, third.body)).toBe(true)169    expect(verify(secret1, third.headers["spmail-signature"] as string, third.body)).toBe(false)170171    // ---- modification : le nom change, l'URL inchangée n'est pas revérifiée172    await card.getByRole("button", { name: "Modifier" }).click()173    await expect(editor.getByLabel("URL de destination")).toHaveValue(`http://${hostPort}/hook`)174    await editor.getByLabel("Nom", { exact: true }).fill(renamed)175    await editor.getByLabel("Actif (un webhook inactif ne reçoit aucun événement)").uncheck()176    await editor.getByTestId("webhook-save").click()177    const card2 = page.locator('[data-testid="webhook-card"]', { hasText: renamed })178    await expect(card2).toBeVisible()179    await expect(card2).toContainText("Inactif")180181    // ---- téléphone : pas de défilement horizontal182    await page.setViewportSize({ width: 390, height: 844 })183    await noOverflow(page)184    await page.setViewportSize({ width: 1440, height: 900 })185186    // ---- suppression du webhook (nom à retaper), puis de la destination interne187    await card2.getByRole("button", { name: "Supprimer" }).click()188    const del = page.getByRole("alertdialog")189    await expect(del.getByRole("button", { name: "Supprimer le webhook" })).toBeDisabled()190    await del.getByRole("textbox").fill(renamed)191    await del.getByRole("button", { name: "Supprimer le webhook" }).click()192    await expect(card2).toHaveCount(0)193    grantReauth()194    await allowRow.getByRole("button", { name: "Retirer" }).click()195    await page.getByRole("alertdialog").getByRole("button", { name: "Retirer", exact: true }).click()196    await expect(allowRow).toHaveCount(0)197    await noOverflow(page)198  } finally {199    await rx.close()200  }201})202
Files main
Menu

Theme