SPB Git

Repository Public

explorer.spec.ts 14.9 KB 290 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Mail8 * File             : tests/e2e/admin/explorer.spec.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/sp-mail11 * Project Website  : https://mail.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Explorateur d'API : appel avec une clé (jeton d'exploration jamais visible), pré-vérification des permissions, confirmation44// avant un envoi, recherche, bascule formulaire / JSON brut, accessibilité. Aucun message n'est réellement envoyé par cet essai.45import type { Page } from "@playwright/test"46import crypto from "node:crypto"47import { api, axeBoth, expect, grantReauth, noOverflow, openAdmin, st, test } from "./fixtures"4849const rand = () => crypto.randomBytes(3).toString("hex")5051/** Clé de lecture seule limitée à st.addrA ; son vrai jeton ne sert qu'à vérifier qu'il n'apparaît nulle part. */52async function seedKey(): Promise<{ id: string; name: string; token: string }> {53  grantReauth()54  const list = await api<{ data: { id: string; address: string }[] }>("GET", "/api/v1/addresses")55  const a = list.body.data.find((x) => x.address === st.addrA)56  if (!a) throw new Error(`adresse ${st.addrA} introuvable`)57  const name = `web-explorer-${st.run}-${rand()}`58  const r = await api<{ key: { id: string }; token: string }>("POST", "/api/admin/api-keys", { name, scopes: ["mail.read"], address_ids: [a.id] })59  if (!r.ok) throw new Error(`création de la clé : ${r.status} ${JSON.stringify(r.body)}`)60  return { id: r.body.key.id, name, token: r.body.token }61}6263const opButton = (page: Page, id: string) => page.locator(`.adm-explorer-side [data-testid="explorer-op"][data-op="${id}"]`)64async function chooseOp(page: Page, id: string) {65  await opButton(page, id).click()66  await expect(page.getByTestId("explorer-current")).toHaveAttribute("data-op", id)67}68async function ready(page: Page) {69  await openAdmin(page, "explorer")70  await expect(page.getByTestId("explorer-caller")).toBeVisible()71  await expect(opButton(page, "GET /me")).toBeVisible()72}7374/** Ni jeton d'exploration ni jeton de la clé : texte de la page, HTML, valeurs des champs, stockages, URL. */75async function expectNoSecret(page: Page, token: string) {76  const seen = await page.evaluate(() => ({77    text: document.body.innerText,78    html: document.documentElement.outerHTML,79    values: Array.from(document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>("input, textarea, select")).map((el) => el.value).join("\n"),80    local: JSON.stringify(Object.entries(localStorage)),81    session: JSON.stringify(Object.entries(sessionStorage)),82    url: location.href,83  }))84  for (const [where, content] of Object.entries(seen)) {85    expect(content.includes("spx_"), `jeton d'exploration visible (${where})`).toBe(false)86    expect(content.includes(token), `jeton de la clé visible (${where})`).toBe(false)87  }88}8990test("explorateur : appel avec une clé — GET /me, jeton jamais visible, exemple cURL sans secret", async ({ page }) => {91  const key = await seedKey()92  await ready(page)93  await axeBoth(page, "explorer-idle")94  await noOverflow(page)9596  await page.getByTestId("explorer-caller").selectOption(key.id)97  await expect(page.getByTestId("explorer-token-state")).toContainText("Un jeton d'exploration sera créé")98  await chooseOp(page, "GET /me")99  await expect(page.getByTestId("explorer-doc")).toContainText("Who am I")100  await expect(page.getByTestId("explorer-precheck")).toHaveAttribute("data-verdict", "allowed")101102  await page.getByTestId("explorer-run").click()103  await expect(page.getByTestId("explorer-status")).toContainText("200")104  const body = page.getByTestId("explorer-body")105  await expect(body).toContainText('"type": "key"')106  await expect(body).toContainText('"explorer": true')107  // l'adresse permise est au troisième niveau, replié d'emblée : on le déplie108  await expect(body).not.toContainText(st.addrA)109  await body.getByRole("button", { name: "Déplier [0]" }).click()110  await expect(body).toContainText(st.addrA)111  await expect(page.getByTestId("explorer-headers")).toContainText("X-Request-Id")112  await expect(page.getByTestId("explorer-headers")).toContainText("X-RateLimit-Remaining")113  await expect(page.getByTestId("explorer-token-state")).toContainText(/Jeton d'exploration valide jusqu'à \d{1,2}\s?[h:]\s?\d{2}/)114  await expect(page.getByTestId("explorer-history")).toContainText("/me")115  await expect(page.getByTestId("explorer-history")).toContainText(key.name)116117  // nœuds repliables : la racine se replie et se redéplie118  await body.getByRole("button", { name: "Replier la racine" }).click()119  await expect(body).not.toContainText('"type": "key"')120  await body.getByRole("button", { name: "Déplier la racine" }).click()121  await expect(body).toContainText('"type": "key"')122123  // exemples de code : la variable d'environnement, jamais un jeton124  const snippet = page.getByTestId("explorer-snippet")125  await expect(snippet).toContainText("$SPMAIL_API_KEY")126  await expect(snippet).toContainText("/api/v1/me")127  for (const lang of ["ts", "python", "curl"]) {128    await page.getByTestId(`explorer-lang-${lang}`).click()129    await expect(snippet).toContainText("SPMAIL_API_KEY")130    const code = (await snippet.textContent()) ?? ""131    expect(code.includes("spx_")).toBe(false)132    expect(code.includes(key.token)).toBe(false)133  }134  await expectNoSecret(page, key.token)135136  await axeBoth(page, "explorer-response")137  await noOverflow(page)138})139140test("explorateur : pré-vérification en échec (scope et adresse), confirmation d'envoi, 403 insufficient_scope affiché", async ({ page, watch }) => {141  const key = await seedKey()142  await ready(page)143  await page.getByTestId("explorer-caller").selectOption(key.id)144  await chooseOp(page, "POST /messages/send")145  await page.getByTestId("f-body.from").fill(st.addrB)146147  const pre = page.getByTestId("explorer-precheck")148  await expect(pre).toHaveAttribute("data-verdict", "denied")149  await expect(pre).toContainText("Refus probable")150  await expect(pre).toContainText("Scope manquant")151  await expect(pre).toContainText("mail.send")152  await expect(pre).toContainText(st.addrB)153  await expect(pre).toContainText("hors de la liste d'autorisation")154  await expect(pre).toContainText("Le serveur reste l'autorité")155156  // avec l'adresse permise à la clé, seule la raison « scope » demeure157  await page.getByTestId("f-body.from").fill(st.addrA)158  await expect(pre).toContainText("dans la liste d'autorisation")159  await expect(pre).toHaveAttribute("data-verdict", "denied")160  await page.getByTestId("f-body.from").fill(st.addrB)161162  // exécuter quand même : l'avertissement d'envoi exige une confirmation explicite163  await page.getByTestId("explorer-run").click()164  const guard = page.getByTestId("explorer-guard")165  await expect(guard).toBeVisible()166  await expect(guard).toHaveAttribute("data-danger", "send")167  await expect(guard).toContainText("Un vrai message")168  const confirm = page.getByTestId("explorer-guard-confirm")169  await expect(confirm).toBeDisabled()170  await page.getByTestId("explorer-guard-check").check()171  watch.allow.push(/status of 403/)172  await confirm.click()173  await expect(guard).toBeHidden()174175  // le serveur, seule autorité, refuse : affiché tel quel176  await expect(page.getByTestId("explorer-status")).toContainText("403")177  await expect(page.getByTestId("explorer-code")).toHaveText("insufficient_scope")178  await expect(page.getByTestId("explorer-response")).toContainText("Scope insuffisant")179  await expect(page.getByTestId("explorer-body")).toContainText('"code": "insufficient_scope"')180  await expect(page.getByTestId("explorer-headers")).toContainText("X-Request-Id")181  await expectNoSecret(page, key.token)182})183184test("explorateur : « ma session » — formulaire généré, avertissement avant l'envoi, annuler n'envoie rien", async ({ page }) => {185  const outbound = async () => (await api<{ data: { id: string; from: string }[] }>("GET", "/api/v1/messages/outbound?limit=100")).body.data.filter((o) => o.from === st.addrA).map((o) => o.id).sort()186  const before = await outbound()187  await ready(page)188  await expect(page.getByTestId("explorer-caller")).toHaveValue("session")189  await chooseOp(page, "POST /messages/send")190  const subject = `Explorateur ${st.run} ${rand()}`191  await page.getByTestId("f-body.from").fill(st.addrA)192  await page.getByTestId("f-body.to").fill(st.addrB)193  await page.getByTestId("f-body.subject").fill(subject)194  await page.getByTestId("f-body.text").fill("Ce message ne doit jamais partir.")195  await expect(page.getByTestId("explorer-precheck")).toHaveAttribute("data-verdict", "allowed")196  await expect(page.getByTestId("explorer-snippet")).toContainText(subject)197198  await page.getByTestId("explorer-run").click()199  const guard = page.getByTestId("explorer-guard")200  await expect(guard).toBeVisible()201  await expect(page.getByRole("alertdialog", { name: "Cette requête envoie du courrier" })).toBeVisible()202  await expect(guard).toContainText("Un vrai message")203  await expect(page.getByTestId("explorer-guard-confirm")).toBeDisabled()204  await axeBoth(page, "explorer-guard")205  await page.getByRole("button", { name: "Annuler" }).click()206  await expect(guard).toBeHidden()207208  // rien n'est parti : ni réponse, ni historique, ni envoi suivi côté serveur209  await expect(page.getByTestId("explorer-response")).toHaveCount(0)210  await expect(page.getByTestId("explorer-history")).toHaveCount(0)211  await page.waitForTimeout(600)212  expect(await outbound()).toEqual(before)213})214215test("explorateur : la recherche filtre les points de terminaison", async ({ page }) => {216  await ready(page)217  const side = page.locator(".adm-explorer-side")218  const ops = side.getByTestId("explorer-op")219  const total = await ops.count()220  expect(total).toBeGreaterThan(40)221  await side.getByTestId("explorer-search").fill("webhooks")222  await expect(opButton(page, "GET /me")).toHaveCount(0)223  await expect(opButton(page, "POST /webhooks/{id}/test")).toBeVisible()224  const shown = await ops.evaluateAll((els) => els.map((el) => el.getAttribute("data-op") ?? ""))225  expect(shown.length).toBeGreaterThan(0)226  expect(shown.length).toBeLessThan(total)227  expect(shown.filter((id) => id.includes("/webhook")).length).toBeGreaterThan(5)228  expect(shown).not.toContain("POST /messages/send")229  await expect(side.getByTestId("explorer-count")).toContainText(`${shown.length} point`)230231  // par résumé, et plusieurs mots (méthode + chemin)232  await side.getByTestId("explorer-search").fill("who am i")233  await expect(ops).toHaveCount(1)234  await expect(opButton(page, "GET /me")).toBeVisible()235  await side.getByTestId("explorer-search").fill("delete drafts")236  await expect(opButton(page, "DELETE /drafts/{id}")).toBeVisible()237  await expect(ops).toHaveCount(1)238  await side.getByTestId("explorer-search").fill("zzz-aucun")239  await expect(ops).toHaveCount(0)240  await expect(side).toContainText("Aucun point de terminaison ne correspond.")241  await side.getByTestId("explorer-search").fill("")242  await expect(ops).toHaveCount(total)243  await noOverflow(page)244})245246test("explorateur : bascule Formulaire / JSON brut aller-retour ; un JSON invalide bloque l'exécution", async ({ page }) => {247  await ready(page)248  await chooseOp(page, "POST /messages/send")249  await page.getByTestId("f-body.from").fill(st.addrA)250  await page.getByTestId("f-body.to").fill(`${st.addrB}\n${st.addrA}`)251  await page.getByTestId("f-body.subject").fill("Aller-retour")252  await page.getByTestId("f-body.text").fill("Ligne 1\nLigne 2")253  await page.getByTestId("f-body.priority").selectOption("high")254  await page.getByTestId("f-body.draft").check()255256  await page.getByTestId("explorer-mode-raw").click()257  const raw = page.getByTestId("explorer-raw")258  await expect(raw).toBeVisible()259  expect(JSON.parse(await raw.inputValue())).toEqual({ from: st.addrA, to: [st.addrB, st.addrA], subject: "Aller-retour", text: "Ligne 1\nLigne 2", priority: "high", draft: true })260261  // modifié en JSON brut, puis retour au formulaire : les champs suivent262  await raw.fill(JSON.stringify({ from: st.addrB, to: [st.addrA], subject: "Modifié en JSON", text: "Ligne 1\nLigne 2", priority: "low", draft: false }, null, 2))263  await page.getByTestId("explorer-mode-form").click()264  await expect(page.getByTestId("f-body.from")).toHaveValue(st.addrB)265  await expect(page.getByTestId("f-body.to")).toHaveValue(st.addrA)266  await expect(page.getByTestId("f-body.subject")).toHaveValue("Modifié en JSON")267  await expect(page.getByTestId("f-body.text")).toHaveValue("Ligne 1\nLigne 2")268  await expect(page.getByTestId("f-body.priority")).toHaveValue("low")269  await expect(page.getByTestId("f-body.draft")).not.toBeChecked()270  await expect(page.getByTestId("explorer-url")).toContainText("POST /api/v1/messages/send")271272  // un JSON que le formulaire ne sait pas porter reste en JSON brut273  await page.getByTestId("explorer-mode-raw").click()274  await raw.fill(JSON.stringify({ from: st.addrA, to: [{ email: st.addrB, name: "B" }] }))275  await page.getByTestId("explorer-mode-form").click()276  await expect(page.getByTestId("explorer-mode-note")).toContainText("il reste en JSON brut")277  await expect(raw).toBeVisible()278279  // JSON invalide : message clair, aucune confirmation, aucune requête280  await raw.fill('{"from": "oups"')281  await expect(page.getByTestId("explorer-raw-state")).toContainText("JSON invalide")282  await page.getByTestId("explorer-mode-form").click()283  await expect(page.getByTestId("explorer-mode-note")).toContainText("JSON invalide")284  await page.getByTestId("explorer-run").click()285  await expect(page.getByTestId("explorer-notice")).toContainText("Le JSON du corps est invalide")286  await expect(page.getByTestId("explorer-guard")).toHaveCount(0)287  await expect(page.getByTestId("explorer-response")).toHaveCount(0)288  await noOverflow(page)289})290
Files main
Menu

Theme