Repository Public
1// Clés d'API : assistant de création (profil, adresses permises, envoi externe, limites) avec réauthentification2// transparente, secret montré une seule fois et jamais conservé, usage réel du jeton, modification, journal d'utilisation3// et ses filtres, rotation, révocation. Deux envois au plus (un seul remis : vers la boîte B de la recette).4import type { Page } from "@playwright/test"5import crypto from "node:crypto"6import { api, apiKey, axeBoth, clearReauth, confirmReauth, expect, grantReauth, noOverflow, openAdmin, st, test, toastText, waitForMessage } from "./fixtures"78const TOKEN_RE = /^spm_[a-z0-9]{10}_[A-Za-z0-9_-]{43}$/9const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")10/** Partie secrète du jeton spm_<préfixe de 10>_<secret> (le secret, en base64url, peut lui-même contenir « _ »). */11const secretOf = (token: string) => token.slice("spm_".length + 10 + 1)12const wizard = (page: Page) => page.getByTestId("key-wizard")13const next = (page: Page) => page.getByTestId("key-next").click()14const keyRow = (page: Page, name: string) => page.locator(`tr[data-key-name="${name}"]`)1516/** Le dialogue du secret : ni Échap ni clic à côté ne le ferment ; « Fermer » attend la case cochée. Rend le jeton lu à l'écran. */17async function readSecretOnce(page: Page): Promise<string> {18 const dlg = page.getByTestId("secret-dialog")19 await expect(dlg).toBeVisible()20 await page.keyboard.press("Escape")21 await expect(dlg).toBeVisible()22 await page.mouse.click(4, 4) // clic sur le voile, hors du dialogue23 await expect(dlg).toBeVisible()24 const close = dlg.getByRole("button", { name: "Fermer" })25 await expect(close).toBeDisabled()26 const token = await page.getByTestId("secret-value").inputValue()27 expect(token).toMatch(TOKEN_RE)28 // affiché, mais déjà absent de tout stockage et de l'adresse29 await expectNotStored(page, token)30 await dlg.getByRole("checkbox", { name: /J'ai enregistré ce secret/ }).check()31 await expect(close).toBeEnabled()32 await close.click()33 await expect(dlg).toBeHidden()34 return token35}36async function expectNotStored(page: Page, token: string) {37 const secret = secretOf(token)38 const stores = await page.evaluate(() => JSON.stringify({ ...localStorage }) + JSON.stringify({ ...sessionStorage }))39 expect(stores).not.toContain(secret)40 expect(page.url()).not.toContain(secret)41}42/** Après la fermeture : plus aucune trace du jeton dans le document (texte, attributs, valeurs de champs), ni dans les stockages. */43async function expectGone(page: Page, token: string) {44 const secret = secretOf(token)45 expect(await page.content()).not.toContain(secret)46 expect(await page.evaluate((s) => document.documentElement.innerText.includes(s) || [...document.querySelectorAll("input, textarea")].some((e) => (e as HTMLInputElement).value.includes(s)), secret)).toBe(false)47 await expectNotStored(page, token)48}4950test("clé d'API : création par l'assistant, secret unique, usage, modification, journal, rotation, révocation", async ({ page, watch }) => {51 test.setTimeout(300_000)52 // 403 attendus (réauthentification exigée à la création et à la rotation, puis reprise) ; aucune autre erreur de console n'est tolérée53 watch.allow.push(/status of 403/)54 const name = `web-cle-${st.run}-${crypto.randomBytes(2).toString("hex")}`55 const subject = `Clé ${name} : notification`5657 await openAdmin(page, "keys")58 await expect(page.getByTestId("key-new")).toBeEnabled()59 await axeBoth(page, "keys-liste")60 await noOverflow(page)6162 // ---------------------------------------------------------------- assistant63 await page.getByTestId("key-new").click()64 const dlg = page.getByRole("dialog", { name: "Nouvelle clé d'API" })65 await expect(dlg).toBeVisible()66 await expect(wizard(page)).toHaveAttribute("data-step", "identity")67 await next(page) // sans nom : on reste à l'étape, l'erreur est dite68 await expect(page.getByTestId("key-errors")).toContainText("Donnez un nom à la clé.")69 await dlg.getByLabel("Nom de la clé").fill(name)70 await dlg.getByLabel("Description (facultative)").fill("Essai de la console")71 await axeBoth(page, "keys-assistant-nom")72 await next(page)7374 await expect(wizard(page)).toHaveAttribute("data-step", "scopes")75 await next(page) // aucune portée76 await expect(page.getByTestId("key-errors")).toContainText("Choisissez un profil ou cochez au moins une portée.")77 for (const preset of ["Envoi seul (notifications)", "Lecture seule (agent)", "Agent : lecture + brouillons", "Agent : envoi avec approbation", "Administration"]) await expect(dlg.getByRole("radio", { name: new RegExp(`^${esc(preset)}`) })).toBeVisible()78 await dlg.getByRole("radio", { name: /^Envoi seul \(notifications\)/ }).check()79 await expect(dlg.getByRole("checkbox", { name: /^Envoyer/ })).toBeChecked()80 await expect(dlg.getByRole("checkbox", { name: /^Lire mail\.read/ })).not.toBeChecked()81 await expect(dlg.getByText("Profil retenu : Envoi seul (notifications).")).toBeVisible()82 await axeBoth(page, "keys-assistant-portees")83 await noOverflow(page)84 await next(page)8586 await expect(wizard(page)).toHaveAttribute("data-step", "addresses")87 // jamais de « toutes » implicite : rien n'est coché, « toutes les adresses » n'est pas offert sans mail.admin88 await expect(page.getByTestId("all-addresses")).toHaveCount(0)89 await expect(page.getByTestId("address-picker").getByRole("checkbox", { checked: true })).toHaveCount(0)90 await next(page)91 await expect(page.getByTestId("key-errors")).toContainText("Cochez au moins une adresse")92 await page.getByTestId("address-picker").getByRole("checkbox", { name: new RegExp(`^${esc(st.addrA)}`) }).check()93 await axeBoth(page, "keys-assistant-adresses")94 await next(page)9596 await expect(wizard(page)).toHaveAttribute("data-step", "policy")97 await expect(dlg.getByRole("radio", { name: /^Avec approbation \(recommandé\)/ })).toBeChecked() // défaut prudent98 await dlg.getByRole("radio", { name: /^Interdit/ }).check()99 await dlg.getByLabel("Domaines de destinataires permis (facultatif)").fill("pas un domaine")100 await next(page)101 await expect(page.getByTestId("key-errors")).toContainText("Un des domaines n'est pas valide")102 await dlg.getByLabel("Domaines de destinataires permis (facultatif)").fill("STG.spboucher.ai")103 await axeBoth(page, "keys-assistant-envoi-externe")104 await next(page)105106 await expect(wizard(page)).toHaveAttribute("data-step", "limits")107 await dlg.getByLabel("Requêtes par minute").fill("0")108 await next(page)109 await expect(page.getByTestId("key-errors")).toContainText("entier de 1 à 6 000")110 await dlg.getByLabel("Requêtes par minute").fill("30")111 await dlg.getByLabel("Envois par jour").fill("5")112 await axeBoth(page, "keys-assistant-limites")113 await next(page)114115 await expect(wizard(page)).toHaveAttribute("data-step", "review")116 const review = page.getByTestId("key-review")117 await expect(review).toContainText(name)118 await expect(review).toContainText("Envoi seul (notifications)")119 await expect(review).toContainText(st.addrA)120 await expect(review).toContainText("Interdit")121 await expect(review).toContainText("stg.spboucher.ai")122 await expect(review).toContainText("30 requêtes/min · 5 envois/jour")123 await expect(review).toContainText("Sans expiration")124 await axeBoth(page, "keys-assistant-recapitulatif")125 await noOverflow(page)126127 // ---------------------------------------------------------------- création : clé d'accès exigée, puis reprise transparente128 clearReauth()129 await page.getByTestId("key-submit").click()130 await confirmReauth(page)131 let token = await readSecretOnce(page)132 await expect(dlg).toBeHidden()133 await expectGone(page, token)134135 // ---------------------------------------------------------------- le jeton fonctionne, avec exactement les droits choisis136 const me = await apiKey(token, "GET", "/me")137 expect(me.status).toBe(200)138 expect(me.body.type).toBe("key")139 expect(me.body.name).toBe(name)140 expect(me.body.scopes).toEqual(["mail.send"])141 expect(me.body.all_addresses).toBe(false)142 expect(me.body.addresses.map((a: { address: string }) => a.address)).toEqual([st.addrA])143 expect(me.body.limits).toMatchObject({ rate_per_minute: 30, daily_send_limit: 5, external_send_policy: "deny", allowed_recipient_domains: ["stg.spboucher.ai"] })144 const keyId: string = me.body.id145 // une adresse hors de la liste d'autorisation est refusée (rien ne part)146 const refused = await apiKey(token, "POST", "/messages/send", { from: st.addrB, to: [{ email: st.addrA }], subject: `${subject} (refusé)`, text: "Ne doit pas partir." })147 expect(refused.status).toBe(403)148 expect(refused.body.error.code).toBe("from_not_allowed")149 const sent = await apiKey(token, "POST", "/messages/send", { from: st.addrA, to: [{ email: st.addrB }], subject, text: "Notification envoyée avec une clé créée dans la console." })150 expect(sent.status).toBe(200)151 await waitForMessage(st.addrB, subject)152153 // ---------------------------------------------------------------- la liste154 await page.getByRole("button", { name: "Actualiser" }).click()155 const row = keyRow(page, name)156 await expect(row).toHaveCount(1)157 await expect(row).toHaveAttribute("data-key-id", keyId)158 await expect(row.getByTestId("key-prefix")).toHaveText(`${token.slice(0, 14)}…`)159 await expect(row).toContainText("Envoi seul (notifications)")160 await expect(row).toContainText(st.addrA)161 await expect(row).toContainText("Interdit")162 await expect(row).toContainText("30 requêtes/min · 5 envois/jour")163 await expect(row).toContainText("Active")164 await expect(row).not.toContainText("Jamais") // dernière utilisation renseignée165 await axeBoth(page, "keys-liste-avec-cle")166167 // ---------------------------------------------------------------- modification des droits (PATCH ; réauthentification récente, posée ici pour ne pas dépendre des délais)168 grantReauth()169 await row.getByRole("button", { name: `Modifier la clé ${name}` }).click()170 const edit = page.getByRole("dialog", { name: `Modifier la clé ${name}` })171 await expect(edit).toBeVisible()172 await edit.getByRole("button", { name: /Limites$/ }).click()173 await expect(wizard(page)).toHaveAttribute("data-step", "limits")174 await edit.getByLabel("Envois par jour").fill("7")175 await next(page)176 await expect(page.getByTestId("key-review")).toContainText("30 requêtes/min · 7 envois/jour")177 await page.getByTestId("key-submit").click()178 await expect(toastText(page, `La clé ${name} a été mise à jour`)).toBeVisible()179 await expect(edit).toBeHidden()180 await expect(keyRow(page, name)).toContainText("30 requêtes/min · 7 envois/jour")181 // seul le champ modifié a changé : adresses, politique, domaines et débit sont intacts182 const after = (await apiKey(token, "GET", "/me")).body183 expect(after.limits).toMatchObject({ rate_per_minute: 30, daily_send_limit: 7, external_send_policy: "deny", allowed_recipient_domains: ["stg.spboucher.ai"] })184 expect(after.scopes).toEqual(["mail.send"])185 expect(after.addresses.map((a: { address: string }) => a.address)).toEqual([st.addrA])186187 // ---------------------------------------------------------------- journal d'utilisation188 await keyRow(page, name).getByRole("link", { name: `Utilisation de la clé ${name}` }).click()189 await expect(page).toHaveURL(new RegExp(`/admin/usage\\?key=${keyId}$`))190 await expect(page.getByRole("heading", { level: 2, name: "Journal d'utilisation" })).toBeVisible()191 await expect(page.getByTestId("usage-key")).toHaveValue(keyId)192 const usage = page.getByTestId("usage-view")193 await expect(usage).toHaveAttribute("data-key-id", keyId)194 const recent = page.getByTestId("usage-recent")195 // l'écriture du journal est asynchrone côté serveur : on actualise jusqu'à voir les quatre appels196 await expect(async () => {197 await page.getByRole("button", { name: "Actualiser" }).click()198 await expect(recent.locator("tbody tr")).toHaveCount(4, { timeout: 2_000 })199 }).toPass({ timeout: 20_000 })200 await expect(usage.getByRole("heading", { level: 3, name: `Utilisation de la clé ${name}` })).toBeVisible()201 await expect(page.getByTestId("usage-requests")).toHaveText("4")202 await expect(recent.locator('tr[data-route="/api/v1/me"][data-status="200"][data-method="GET"]')).toHaveCount(2)203 await expect(recent.locator('tr[data-route="/api/v1/messages/send"][data-status="200"]')).toHaveCount(1)204 await expect(recent.locator('tr[data-route="/api/v1/messages/send"][data-status="403"]')).toContainText("from_not_allowed")205 await expect(page.getByTestId("usage-by-route")).toContainText("/api/v1/me")206 await expect(page.getByTestId("usage-sends")).toContainText(/sent|delivered/)207 await expect(page.getByTestId("usage-count")).toHaveText("4 appels affichés sur 4")208 // filtres : classe d'état, méthode, origine, période209 await page.getByTestId("usage-filter-status").selectOption("4xx")210 await expect(recent.locator("tbody tr")).toHaveCount(1)211 await expect(recent.locator("tbody tr")).toHaveAttribute("data-status", "403")212 await expect(page.getByTestId("usage-count")).toHaveText("1 appel affiché sur 4")213 await page.getByTestId("usage-filter-status").selectOption("2xx")214 await page.getByTestId("usage-filter-method").selectOption("GET")215 await expect(recent.locator("tbody tr")).toHaveCount(2)216 await expect(recent.locator('tr[data-route="/api/v1/messages/send"]')).toHaveCount(0)217 await page.getByTestId("usage-filter-method").selectOption("POST")218 await expect(recent.locator("tbody tr")).toHaveCount(1)219 await page.getByTestId("usage-filter-status").selectOption("all")220 await page.getByTestId("usage-filter-method").selectOption("all")221 await page.getByTestId("usage-filter-explorer").selectOption("only")222 await expect(usage.getByText("Aucun appel ne correspond à ces filtres.")).toBeVisible()223 await page.getByTestId("usage-filter-explorer").selectOption("without")224 await expect(recent.locator("tbody tr")).toHaveCount(4)225 await page.getByTestId("usage-period").selectOption("30")226 await expect(usage.getByText("Sur les 30 derniers jours.")).toBeVisible()227 await expect(recent.locator("tbody tr")).toHaveCount(4)228 await axeBoth(page, "keys-utilisation")229 await noOverflow(page)230231 // ---------------------------------------------------------------- rotation : nouveau secret montré une fois, l'ancien est refusé232 await openAdmin(page, "keys")233 await keyRow(page, name).getByRole("button", { name: `Rotation de la clé ${name}` }).click()234 await expect(page.getByTestId("rotate-dialog")).toBeVisible()235 await axeBoth(page, "keys-rotation")236 clearReauth() // la rotation exige elle aussi la clé d'accès : invite, puis reprise237 await page.getByTestId("rotate-submit").click()238 // invite empilée sur le dialogue de rotation : le focus y reste piégé, Échap ne referme qu'elle239 const prompt = page.getByTestId("reauth-dialog")240 await expect(prompt).toBeVisible()241 const inPrompt = () => page.evaluate(() => !!document.activeElement?.closest('[aria-modal="true"]')?.querySelector('[data-testid="reauth-dialog"]'))242 for (const key of ["Shift+Tab", "Shift+Tab", "Tab", "Tab", "Tab"]) {243 await page.keyboard.press(key)244 expect(await inPrompt(), `focus dans l'invite après ${key}`).toBe(true)245 }246 await page.keyboard.press("Escape")247 await expect(prompt).toBeHidden()248 await expect(page.getByTestId("rotate-dialog")).toBeVisible()249 await expect(page.getByTestId("secret-dialog")).toHaveCount(0)250 await page.getByTestId("rotate-submit").click()251 await confirmReauth(page)252 const rotated = await readSecretOnce(page)253 expect(rotated).not.toBe(token)254 await expectGone(page, rotated)255 await expectGone(page, token)256 const old = await apiKey(token, "GET", "/me")257 expect(old.status).toBe(401)258 expect(old.body.error.code).toBe("key_revoked")259 const fresh = await apiKey(rotated, "GET", "/me")260 expect(fresh.status).toBe(200)261 expect(fresh.body.name).toBe(name)262 expect(fresh.body.limits.daily_send_limit).toBe(7) // mêmes droits263 expect(fresh.body.id).not.toBe(keyId)264 token = rotated265 // seule la nouvelle clé reste active dans la liste266 await expect(keyRow(page, name)).toHaveCount(1)267 await expect(keyRow(page, name)).toHaveAttribute("data-key-id", fresh.body.id)268 await expect(keyRow(page, name)).toContainText("Issue d'une rotation")269270 // ---------------------------------------------------------------- révocation : immédiate, après avoir retapé le nom271 await keyRow(page, name).getByRole("button", { name: `Révoquer la clé ${name}` }).click()272 const confirm = page.getByRole("alertdialog", { name: `Révoquer la clé ${name} ?` })273 await expect(confirm).toBeVisible()274 const doRevoke = confirm.getByRole("button", { name: "Révoquer la clé", exact: true })275 await expect(doRevoke).toBeDisabled()276 await axeBoth(page, "keys-revocation")277 await confirm.getByRole("textbox").fill(name)278 await doRevoke.click()279 await expect(toastText(page, `La clé ${name} est révoquée.`)).toBeVisible()280 const dead = await apiKey(token, "GET", "/me")281 expect(dead.status).toBe(401)282 expect(dead.body.error.code).toBe("key_revoked")283 await expect(keyRow(page, name)).toHaveCount(0)284 await page.getByRole("checkbox", { name: "Afficher les clés révoquées ou expirées" }).check()285 await expect(keyRow(page, name)).toHaveCount(2)286 for (const r of await keyRow(page, name).all()) {287 await expect(r).toHaveAttribute("data-state", "revoked")288 await expect(r).toContainText("Révoquée")289 await expect(r.getByRole("button")).toHaveCount(0) // plus rien à modifier, faire tourner ou révoquer290 }291 // la clé est bien révoquée côté serveur aussi292 const listed = (await api("GET", "/api/admin/api-keys")).body as { name: string; state: string }[]293 expect(listed.filter((k) => k.name === name).map((k) => k.state)).toEqual(["revoked", "revoked"])294 await noOverflow(page)295})296297test("clé d'API : « toutes les adresses » n'existe qu'avec Administration, comme choix explicite et averti ; abandon de la saisie", async ({ page }) => {298 await openAdmin(page, "keys")299 await page.getByTestId("key-new").click()300 const dlg = page.getByRole("dialog", { name: "Nouvelle clé d'API" })301 await dlg.getByLabel("Nom de la clé").fill(`web-cle-admin-${st.run}`)302 await next(page)303 await dlg.getByRole("radio", { name: /^Administration/ }).check()304 await expect(dlg.getByText("« Administration » inclut toutes les autres portées")).toBeVisible()305 await next(page)306 // offert, mais pas coché : il faut le choisir307 const all = page.getByTestId("all-addresses").getByRole("checkbox")308 await expect(all).not.toBeChecked()309 await next(page)310 await expect(page.getByTestId("key-errors")).toContainText("Cochez au moins une adresse")311 await all.check()312 await expect(dlg.getByText("Cette clé agira pour toutes les boîtes et tous les alias")).toBeVisible()313 await expect(page.getByTestId("address-picker")).toHaveCount(0)314 await axeBoth(page, "keys-assistant-toutes-les-adresses")315 // retirer « Administration » retire aussi « toutes les adresses »316 await dlg.getByRole("button", { name: /Portées$/ }).click()317 await dlg.getByRole("radio", { name: /^Lecture seule \(agent\)/ }).check()318 await next(page)319 await expect(page.getByTestId("all-addresses")).toHaveCount(0)320 await expect(page.getByTestId("address-picker")).toBeVisible()321 await next(page)322 await expect(page.getByTestId("key-errors")).toContainText("Cochez au moins une adresse")323 // un profil qui ne peut pas envoyer : l'envoi externe est proposé « interdit », et c'est dit324 await page.getByTestId("address-picker").getByRole("checkbox", { name: new RegExp(`^${esc(st.addrA)}`) }).check()325 await next(page)326 await expect(dlg.getByRole("radio", { name: /^Interdit/ })).toBeChecked()327 await expect(dlg.getByText("Cette clé ne peut pas envoyer")).toBeVisible()328 // Échap ne jette pas une saisie commencée sans le demander329 await page.keyboard.press("Escape")330 await expect(dlg.getByText("Abandonner la saisie ?")).toBeVisible()331 await dlg.getByRole("button", { name: "Continuer la saisie" }).click()332 await expect(wizard(page)).toHaveAttribute("data-step", "policy")333 await dlg.getByRole("button", { name: "Annuler" }).click()334 await dlg.getByRole("button", { name: "Abandonner", exact: true }).click()335 await expect(dlg).toBeHidden()336 // rien n'a été créé337 const listed = (await api("GET", "/api/admin/api-keys")).body as { name: string }[]338 expect(listed.some((k) => k.name === `web-cle-admin-${st.run}`)).toBe(false)339 // téléphone : la liste tient dans 390 px, sans défilement horizontal340 await page.setViewportSize({ width: 390, height: 844 })341 await expect(page.getByTestId("key-new")).toBeVisible()342 await noOverflow(page)343 await page.getByTestId("key-new").click()344 await expect(wizard(page)).toBeVisible()345 await noOverflow(page)346})347