Repository Public
1import assert from "node:assert/strict"2import { test } from "node:test"3import {4 blocking, buildRequest, callerFromKey, callerFromMe, checkPermission, classifyDanger, deref, fieldOf, fieldToJson, groupByTag, initialValue, jsonToField, namedAddresses,5 parseOperations, resolvePointer, searchOperations, unwrapNullable, type Field, type FormValues, type OpenApiDoc, type Operation, type Problem,6} from "./openapi"78// Document écrit à la main, à l'image de celui que produit server/src/v1/registry.ts (buildOpenApi) : paramètres dérivés de zod,9// corps avec anyOf / nullable / énumérations / tableaux, `x-required-scopes`, étiquettes, enveloppe d'erreur par $ref.10const zRecipients = { maxItems: 100, type: "array", items: { anyOf: [{ type: "string", maxLength: 254 }, { type: "object", properties: { email: { type: "string" }, name: { type: "string" } }, required: ["email"] }] } }11const errorRef = { description: "Error", content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } }12const secured = [{ apiKey: [] }, { session: [] }]13const idem = { name: "Idempotency-Key", in: "header", required: false, description: "Replays the stored response for 24 h", schema: { type: "string", maxLength: 200 } }14const doc: OpenApiDoc = {15 openapi: "3.1.0",16 info: { title: "SP Mail API", version: "1.0.0" },17 servers: [{ url: "https://mail.example/api/v1" }],18 tags: [{ name: "Introspection" }, { name: "Sending" }, { name: "Messages" }, { name: "Attachments" }, { name: "Addresses" }, { name: "Webhooks" }],19 paths: {20 "/addresses/{id}": {21 patch: {22 operationId: "patchAddressesId", tags: ["Addresses"], summary: "Update an address",23 parameters: [{ name: "id", in: "path", required: true, description: "Address id (uuid) or the address itself", schema: { type: "string", maxLength: 254 } }],24 requestBody: { required: true, content: { "application/json": { schema: {25 type: "object",26 properties: {27 display_name: { type: "string", maxLength: 120, example: "Alertes" },28 can_send: { type: "boolean" },29 expires_at: { anyOf: [{ type: "string" }, { type: "null" }] },30 quota_bytes: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] },31 reply_policy: { type: "string", enum: ["reject", "accept", "discard"] },32 extra_destinations: { type: "array", items: { type: "string", maxLength: 254 } },33 retention: { type: "object", properties: { days: { type: "integer" }, trash: { type: "object", properties: { days: { type: "number" }, deep: { type: "object", properties: { deeper: { type: "object", properties: { x: { type: "string" } } } } } } } } },34 variables: { type: "object", propertyNames: { type: "string" }, additionalProperties: { type: "string" } },35 },36 additionalProperties: false,37 } } } },38 responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, "403": { description: "protected_address" }, default: errorRef },39 security: secured, "x-required-scopes": ["mail.addresses.manage"],40 },41 delete: {42 operationId: "deleteAddressesId", tags: ["Addresses"], summary: "Delete an alias, or detach / purge a mailbox",43 parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }, { name: "purge", in: "query", required: false, schema: { type: "string", const: "delete-all-mail" } }],44 responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, default: errorRef },45 security: secured, "x-required-scopes": ["mail.addresses.manage", "mail.aliases.manage"],46 },47 },48 "/files": {49 post: {50 operationId: "postFiles", tags: ["Attachments"], summary: "Upload a file to attach later (raw body)",51 parameters: [{ name: "filename", in: "query", required: false, schema: { default: "file", type: "string", maxLength: 200 } }, { name: "address", in: "query", required: false, schema: { type: "string", maxLength: 254 } }],52 requestBody: { required: true, content: { "application/octet-stream": { schema: { type: "string", format: "binary" } } } },53 responses: { "201": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, "413": { description: "file_too_large" }, default: errorRef },54 security: secured, "x-required-scopes": ["mail.attachments.write"],55 },56 },57 "/health": {58 get: { operationId: "getHealth", tags: ["Introspection"], summary: "Liveness of the API, database and mail server", responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, "503": { description: "Database or mail server unreachable (same body)" }, default: errorRef }, security: [], "x-required-scopes": [] },59 },60 "/me": {61 get: { operationId: "getMe", tags: ["Introspection"], summary: "Who am I: scopes, allowed addresses, limits, usage today", responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, default: errorRef }, security: secured, "x-required-scopes": [] },62 },63 "/messages": {64 get: {65 operationId: "getMessages", tags: ["Messages"], summary: "List / search messages (unified across mailboxes)",66 parameters: [67 { name: "address", in: "query", required: false, description: "Comma-separated addresses to read", schema: { type: "string", maxLength: 2000 } },68 { name: "mailbox", in: "query", required: false, schema: { type: "string" } },69 { name: "from", in: "query", required: false, schema: { type: "string" } },70 { name: "unread", in: "query", required: false, schema: { type: "boolean" } },71 { name: "limit", in: "query", required: false, schema: { default: 25, type: "integer", minimum: 1, maximum: 100 } },72 ],73 responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, default: errorRef },74 security: secured, "x-required-scopes": ["mail.read", "mail.search"],75 },76 },77 "/messages/{id}/attachments/{attachment_id}": {78 get: {79 operationId: "getMessagesIdAttachmentsAttachment_id", tags: ["Attachments"], summary: "Download one attachment",80 parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }, { name: "attachment_id", in: "path", required: true, schema: { type: "string" } }],81 responses: { "200": { description: "Binary content", content: { "application/octet-stream": { schema: { type: "string", format: "binary" } } } }, default: errorRef },82 security: secured, "x-required-scopes": ["mail.attachments.read"],83 },84 },85 "/messages/send": {86 post: {87 operationId: "postMessagesSend", tags: ["Sending"], summary: "Send a message (or schedule it, or save it as a draft)", description: "200 = handed to the mail server.",88 parameters: [idem],89 requestBody: { required: true, content: { "application/json": { schema: {90 type: "object",91 properties: {92 from: { description: "Sender address; must be in the caller's allowlist", type: "string", maxLength: 254 },93 to: zRecipients, cc: zRecipients,94 subject: { default: "", type: "string", maxLength: 998 },95 text: { type: "string", maxLength: 2000000 },96 attachments: { default: [], maxItems: 30, type: "array", items: { type: "object", properties: { file_id: { type: "string" } }, required: ["file_id"], additionalProperties: false } },97 priority: { type: "string", enum: ["high", "normal", "low"] },98 draft: { description: "Save as a draft only; nothing is sent", type: "boolean" },99 },100 required: ["from"], additionalProperties: false,101 } } } },102 responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, "202": { description: "Accepted" }, "201": { description: "Draft" }, default: errorRef },103 security: secured, "x-required-scopes": ["mail.send", "mail.drafts"],104 },105 },106 "/messages/send-batch": {107 post: {108 operationId: "postMessagesSendBatch", tags: ["Sending"], summary: "Send up to 50 messages",109 requestBody: { required: true, content: { "application/json": { schema: { type: "object", properties: { messages: { type: "array", items: { type: "object", properties: { from: { type: "string" } } } } }, required: ["messages"] } } } },110 responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, default: errorRef },111 security: secured, "x-required-scopes": ["mail.send"],112 },113 },114 "/webhooks/{id}/test": {115 post: { operationId: "postWebhooksIdTest", tags: ["Webhooks"], summary: "Send a signed `webhook.test` event to this webhook now", parameters: [{ name: "id", in: "path", required: true, schema: { type: "string", format: "uuid" } }], responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "object" } } } }, default: errorRef }, security: secured, "x-required-scopes": ["mail.webhooks.manage"] },116 },117 },118 components: {119 securitySchemes: { apiKey: { type: "http", scheme: "bearer" } },120 schemas: {121 Error: { type: "object", properties: { error: { type: "object", properties: { code: { type: "string" }, message: { type: "string" }, details: {} }, required: ["code", "message"] } }, required: ["error"] },122 Loop: { $ref: "#/components/schemas/Loop" },123 },124 },125}126const ops = parseOperations(doc)127const op = (id: string): Operation => {128 const o = ops.find((x) => x.id === id)129 assert.ok(o, `opération ${id}`)130 return o131}132const noValues = { path: {}, query: {}, header: {} }133const child = (f: Field, name: string): Field => {134 const c = f.children.find((x) => x.name === name)135 assert.ok(c, `champ ${name}`)136 return c137}138const bodyField = (o: Operation): Field => {139 assert.equal(o.body.kind, "json")140 return (o.body as { field: Field }).field141}142143// ---------------------------------------------------------------- $ref144test("openapi : pointeur JSON local, $ref résolu, cycle arrêté, pointeur externe ignoré", () => {145 assert.equal((resolvePointer(doc, "#/components/schemas/Error") as { type: string }).type, "object")146 assert.equal(resolvePointer(doc, "#/components/schemas/Absent"), null)147 assert.equal(resolvePointer(doc, "https://ailleurs.example/x.json#/a"), null)148 assert.equal(resolvePointer({ "a/b": { "c~d": 1 } }, "#/a~1b/c~0d"), 1)149 assert.deepEqual(Object.keys(deref(doc, { $ref: "#/components/schemas/Error" }).properties as object), ["error"])150 assert.deepEqual(deref(doc, { $ref: "#/components/schemas/Loop" }), {})151 assert.equal(deref(doc, { $ref: "#/components/schemas/Error", description: "à côté" }).description, "à côté")152})153154test("openapi : nullable (anyOf avec null, type en liste) déballé", () => {155 const a = unwrapNullable(doc, { anyOf: [{ type: "string", maxLength: 3 }, { type: "null" }], description: "d" })156 assert.equal(a.nullable, true)157 assert.equal(a.schema.type, "string")158 assert.equal(a.schema.description, "d")159 const b = unwrapNullable(doc, { type: ["integer", "null"] })160 assert.deepEqual([b.nullable, b.schema.type], [true, "integer"])161 assert.equal(unwrapNullable(doc, { type: "string" }).nullable, false)162})163164// ---------------------------------------------------------------- opérations165test("openapi : opérations triées par étiquette déclarée, groupées, avec méthode, scopes, public", () => {166 assert.equal(ops.length, 10)167 assert.deepEqual(groupByTag(ops).map((g) => g.tag), ["Introspection", "Sending", "Messages", "Attachments", "Addresses", "Webhooks"])168 assert.deepEqual(groupByTag(ops)[0].operations.map((o) => o.id), ["GET /health", "GET /me"])169 assert.deepEqual(groupByTag(ops)[4].operations.map((o) => o.id), ["PATCH /addresses/{id}", "DELETE /addresses/{id}"])170 assert.equal(op("GET /health").public, true)171 assert.equal(op("GET /me").public, false)172 assert.deepEqual(op("GET /me").scopes, [])173 assert.deepEqual(op("POST /messages/send").scopes, ["mail.send", "mail.drafts"])174 assert.equal(op("POST /messages/send").description, "200 = handed to the mail server.")175 assert.equal(op("POST /messages/send").operationId, "postMessagesSend")176})177178test("openapi : codes d'erreur tirés des réponses, succès, réponse binaire", () => {179 assert.deepEqual(op("POST /files").errors, [{ status: "413", description: "file_too_large" }])180 assert.deepEqual(op("GET /health").errors, [{ status: "503", description: "Database or mail server unreachable (same body)" }])181 assert.deepEqual(op("POST /messages/send").success.sort(), ["200", "201", "202"])182 assert.equal(op("POST /messages/send").errorEnvelope, true)183 assert.equal(op("GET /messages/{id}/attachments/{attachment_id}").binaryResponse, true)184 assert.equal(op("GET /me").binaryResponse, false)185})186187test("openapi : paramètres (chemin obligatoire, requête, en-tête), types et valeur par défaut", () => {188 const list = op("GET /messages")189 assert.deepEqual(list.params.map((p) => `${p.in}.${p.name}:${p.field.kind}`), ["query.address:string", "query.mailbox:string", "query.from:string", "query.unread:boolean", "query.limit:integer"])190 assert.equal(list.params[4].field.defaultValue, 25)191 assert.equal(list.params[0].field.description, "Comma-separated addresses to read")192 const patch = op("PATCH /addresses/{id}")193 assert.deepEqual([patch.params[0].in, patch.params[0].field.required], ["path", true])194 assert.deepEqual(op("POST /messages/send").params.map((p) => [p.in, p.name, p.field.required]), [["header", "Idempotency-Key", false]])195 assert.deepEqual(op("DELETE /addresses/{id}").params[1].field.options, ["delete-all-mail"])196})197198test("openapi : corps → modèle de formulaire (obligatoire, énumération, booléen, liste, nullable, objet imbriqué, repli JSON)", () => {199 const send = bodyField(op("POST /messages/send"))200 assert.equal(send.kind, "object")201 assert.deepEqual(send.children.map((c) => `${c.name}:${c.kind}${c.required ? "*" : ""}`), ["from:string*", "to:stringList", "cc:stringList", "subject:string", "text:string", "attachments:json", "priority:enum", "draft:boolean"])202 assert.equal(child(send, "text").multiline, true)203 assert.equal(child(send, "subject").multiline, false)204 assert.equal(child(send, "subject").defaultValue, "")205 assert.deepEqual(child(send, "priority").options, ["high", "normal", "low"])206 assert.equal(child(send, "from").description, "Sender address; must be in the caller's allowlist")207208 const patch = bodyField(op("PATCH /addresses/{id}"))209 assert.deepEqual([child(patch, "expires_at").kind, child(patch, "expires_at").nullable], ["string", true])210 assert.deepEqual([child(patch, "quota_bytes").kind, child(patch, "quota_bytes").nullable], ["integer", true])211 assert.equal(child(patch, "extra_destinations").kind, "stringList")212 assert.equal(child(patch, "variables").kind, "json") // dictionnaire libre : JSON brut213 assert.equal(child(patch, "display_name").example, "Alertes")214 // objets imbriqués jusqu'à une profondeur raisonnable, puis JSON brut215 const retention = child(patch, "retention")216 assert.equal(retention.kind, "object")217 const trash = child(retention, "trash")218 assert.equal(trash.kind, "object")219 assert.equal(child(trash, "deep").kind, "json")220221 assert.equal(op("POST /files").body.kind, "binary")222 assert.equal(op("GET /me").body.kind, "none")223 assert.equal(fieldOf(doc, "x", { anyOf: [{ type: "string" }, { type: "object", properties: { a: { type: "string" } } }] }).kind, "json")224 assert.equal(fieldOf(doc, "x", { anyOf: [{ type: "string" }, { type: "number" }] }).kind, "string")225 assert.equal(fieldOf(doc, "x", {}).kind, "json")226 assert.equal(fieldOf(doc, "x", { $ref: "#/components/schemas/Error" }).kind, "object")227})228229test("openapi : recherche par chemin, résumé, méthode ; plusieurs mots ; casse et accents ignorés", () => {230 assert.deepEqual(searchOperations(ops, "outbound"), [])231 assert.deepEqual(searchOperations(ops, "/me").map((o) => o.id), ["GET /me", "GET /messages", "GET /messages/{id}/attachments/{attachment_id}", "POST /messages/send", "POST /messages/send-batch"].sort((a, b) => ops.findIndex((o) => o.id === a) - ops.findIndex((o) => o.id === b)))232 assert.deepEqual(searchOperations(ops, "LIVENESS").map((o) => o.id), ["GET /health"])233 assert.deepEqual(searchOperations(ops, "delete addresses").map((o) => o.id), ["DELETE /addresses/{id}"])234 assert.deepEqual(searchOperations(ops, "téléchargé"), [])235 assert.deepEqual(searchOperations(ops, "Úpload").map((o) => o.id), ["POST /files"])236 assert.equal(searchOperations(ops, " ").length, ops.length)237})238239// ---------------------------------------------------------------- danger240test("openapi : classement des opérations risquées", () => {241 assert.equal(classifyDanger("GET", "/messages"), "none")242 for (const p of ["/messages/send", "/messages/send-batch", "/messages/{id}/reply", "/messages/{id}/forward", "/drafts/{id}/send", "/webhooks/{id}/test"]) assert.equal(classifyDanger("POST", p), "send", p)243 assert.equal(classifyDanger("delete", "/messages/{id}"), "delete")244 assert.equal(classifyDanger("DELETE", "/webhooks/{id}"), "delete")245 for (const [m, p] of [["POST", "/drafts"], ["PATCH", "/messages/{id}"], ["PUT", "/addresses/{id}/automation"], ["POST", "/messages/{id}/move"], ["POST", "/files"], ["POST", "/templates/{id}/render"], ["GET", "/messages/send"]] as const) assert.notEqual(classifyDanger(m, p), "send", `${m} ${p}`)246 assert.equal(classifyDanger("POST", "/drafts"), "write")247 assert.equal(op("POST /messages/send").danger, "send")248 assert.equal(op("DELETE /addresses/{id}").danger, "delete")249 assert.equal(op("PATCH /addresses/{id}").danger, "write")250 assert.equal(op("POST /webhooks/{id}/test").danger, "send")251 assert.equal(op("GET /me").danger, "none")252})253254// ---------------------------------------------------------------- valeurs → requête255test("requête : interpolation du chemin avec encodage, chaîne de requête, champs vides omis", () => {256 const r = buildRequest(op("GET /messages"), { ...noValues, query: { address: "a+b@stg.example, c@stg.example", mailbox: "", unread: true, limit: "5" } })257 assert.equal(r.method, "GET")258 assert.equal(r.url, "/api/v1/messages?address=a%2Bb%40stg.example%2C%20c%40stg.example&unread=true&limit=5")259 assert.deepEqual(r.problems, [])260 assert.equal(r.body, undefined)261262 const a = buildRequest(op("GET /messages/{id}/attachments/{attachment_id}"), { ...noValues, path: { id: "msg_a/b?c#d", attachment_id: "é 1" } })263 assert.equal(a.path, "/messages/msg_a%2Fb%3Fc%23d/attachments/%C3%A9%201")264 assert.equal(a.url, "/api/v1/messages/msg_a%2Fb%3Fc%23d/attachments/%C3%A9%201")265266 const f = buildRequest(op("POST /files"), { ...noValues, query: { filename: "rapport final.pdf", address: "a@stg.example" } })267 assert.equal(f.url, "/api/v1/files?filename=rapport%20final.pdf&address=a%40stg.example")268 assert.deepEqual([f.binary, f.body], [true, undefined])269})270271test("requête : paramètre de chemin manquant → bloquant ; nombre illisible → bloquant ; champ obligatoire du corps → laissé au serveur", () => {272 const miss = buildRequest(op("PATCH /addresses/{id}"), { ...noValues, body: {} })273 assert.deepEqual(miss.problems, [{ path: "path.id", kind: "required" }])274 assert.equal(miss.path, "/addresses/{id}")275 assert.equal(blocking(miss.problems).length, 1)276277 const num = buildRequest(op("GET /messages"), { ...noValues, query: { limit: "douze" } })278 assert.deepEqual(blocking(num.problems), [{ path: "query.limit", kind: "number" }])279 assert.deepEqual(buildRequest(op("GET /messages"), { ...noValues, query: { limit: "2.5" } }).problems, [{ path: "query.limit", kind: "number" }])280281 const send = buildRequest(op("POST /messages/send"), { ...noValues, body: { subject: "s" } })282 assert.deepEqual(send.problems, [{ path: "body.from", kind: "required" }])283 assert.deepEqual(blocking(send.problems), [])284 assert.deepEqual(send.body, { subject: "s" })285})286287test("requête : corps JSON du formulaire — facultatifs vides omis, listes une par ligne, booléens, objets imbriqués, en-tête", () => {288 const values: FormValues = { from: "a@stg.example", to: " b@stg.example \n\n c@stg.example\r\n", cc: "", subject: "Bonjour", text: " ligne 1\nligne 2 ", attachments: "", priority: "", draft: undefined }289 const r = buildRequest(op("POST /messages/send"), { ...noValues, header: { "Idempotency-Key": "k-1" }, body: values })290 assert.deepEqual(r.body, { from: "a@stg.example", to: ["b@stg.example", "c@stg.example"], subject: "Bonjour", text: " ligne 1\nligne 2 " })291 assert.deepEqual(r.headers, { "Idempotency-Key": "k-1" })292 assert.equal(r.url, "/api/v1/messages/send")293 assert.deepEqual(buildRequest(op("POST /messages/send"), { ...noValues, body: { ...values, draft: false, priority: "low", attachments: '[{"file_id":"file_1"}]' } }).body, {294 from: "a@stg.example", to: ["b@stg.example", "c@stg.example"], subject: "Bonjour", text: " ligne 1\nligne 2 ", attachments: [{ file_id: "file_1" }], priority: "low", draft: false,295 })296 // formulaire vide : le serveur valide un objet, on envoie {}297 assert.deepEqual(buildRequest(op("PATCH /addresses/{id}"), { ...noValues, path: { id: "x" }, body: {} }).body, {})298 // objets imbriqués : un objet facultatif entièrement vide est omis299 const nested = buildRequest(op("PATCH /addresses/{id}"), { ...noValues, path: { id: "x" }, body: { quota_bytes: "1024", retention: { days: "", trash: { days: "7,5", deep: "" } }, variables: '{"a":"b"}' } })300 assert.deepEqual(nested.body, { quota_bytes: 1024, retention: { trash: { days: 7.5 } }, variables: { a: "b" } })301 assert.deepEqual(buildRequest(op("PATCH /addresses/{id}"), { ...noValues, path: { id: "x" }, body: { retention: { days: "", trash: { days: "" } } } }).body, {})302 const bad = buildRequest(op("PATCH /addresses/{id}"), { ...noValues, path: { id: "x" }, body: { variables: "{oups" } })303 assert.deepEqual(blocking(bad.problems), [{ path: "body.variables", kind: "json" }])304})305306test("requête : JSON brut — valide tel quel, invalide bloquant, vide = aucun corps", () => {307 const o = op("POST /messages/send")308 assert.deepEqual(buildRequest(o, { ...noValues, raw: '{"from":"a@stg.example","to":[{"email":"b@stg.example"}]}' }).body, { from: "a@stg.example", to: [{ email: "b@stg.example" }] })309 assert.deepEqual(blocking(buildRequest(o, { ...noValues, raw: '{"from": ' }).problems), [{ path: "body", kind: "json" }])310 const empty = buildRequest(o, { ...noValues, raw: " " })311 assert.equal(empty.body, undefined)312 assert.deepEqual(blocking(empty.problems), [])313})314315test("formulaire : valeur initiale = exemple ; aller-retour formulaire → JSON → formulaire", () => {316 const patch = bodyField(op("PATCH /addresses/{id}"))317 const init = initialValue(patch) as FormValues318 assert.equal(init.display_name, "Alertes")319 assert.equal(init.can_send, undefined)320 assert.equal(init.reply_policy, "")321 assert.deepEqual(init.retention, { days: "", trash: { days: "", deep: "" } })322 assert.equal(initialValue(fieldOf(doc, "l", { type: "array", items: { type: "string" }, example: ["a", "b"] })), "a\nb")323 assert.equal(initialValue(fieldOf(doc, "n", { type: "integer", example: 3 })), "3")324 assert.equal(initialValue(fieldOf(doc, "n", { type: "integer", default: 3 })), "") // la valeur par défaut n'est pas renvoyée325326 const send = bodyField(op("POST /messages/send"))327 const values: FormValues = { from: "a@stg.example", to: "b@stg.example\nc@stg.example", cc: "", subject: "Objet", text: "Corps", attachments: "", priority: "high", draft: true }328 const problems: Problem[] = []329 const json = fieldToJson(send, values, "body", problems)330 assert.deepEqual(problems, [])331 const back = jsonToField(send, json)332 assert.equal(back.lossy, false)333 assert.deepEqual(back.value, values)334 assert.deepEqual(fieldToJson(send, back.value, "body", []), json)335})336337test("formulaire : JSON que le formulaire ne sait pas porter → lossy (on reste en JSON brut)", () => {338 const send = bodyField(op("POST /messages/send"))339 assert.equal(jsonToField(send, { from: "a@stg.example", to: [{ email: "b@stg.example" }] }).lossy, true)340 assert.equal(jsonToField(send, { from: "a@stg.example", inconnu: 1 }).lossy, true)341 assert.equal(jsonToField(send, { from: 12 }).lossy, true)342 assert.equal(jsonToField(send, { from: "a@stg.example", to: [] }).lossy, true)343 assert.equal(jsonToField(send, { from: "a@stg.example", subject: "" }).lossy, true)344 assert.equal(jsonToField(send, ["a"]).lossy, true)345 assert.equal(jsonToField(send, { from: "a@stg.example", attachments: [{ file_id: "file_1" }] }).lossy, false)346 assert.equal(jsonToField(send, {}).lossy, false)347})348349// ---------------------------------------------------------------- permissions350const book = [{ id: "11111111-1111-4111-8111-111111111111", address: "a@stg.example" }, { id: "22222222-2222-4222-8222-222222222222", address: "b@stg.example" }]351const keyA = callerFromKey({ scopes: ["mail.read"], address_ids: [book[0].id], all_addresses: false })352const sendReq = (from: string) => buildRequest(op("POST /messages/send"), { ...noValues, body: { from, to: "x@stg.example" } })353354test("permissions : adresses nommées par la requête (from, lot, address / mailbox ; pas le filtre de recherche `from`)", () => {355 assert.deepEqual(namedAddresses(sendReq("A@stg.example")), [{ address: "a@stg.example", where: "from" }])356 assert.deepEqual(namedAddresses({ query: [["address", "a@x, b@x"], ["mailbox", "c@x"], ["from", "expediteur@ailleurs.example"], ["address", "a@x"]], body: undefined }).map((x) => x.address), ["a@x", "b@x", "c@x"])357 assert.deepEqual(namedAddresses({ query: [], body: { messages: [{ from: "a@x" }, { from: "b@x" }, { from: "a@x" }, {}] } }).map((x) => x.address), ["a@x", "b@x"])358 assert.deepEqual(namedAddresses({ query: [], body: { subject: "s" } }), [])359})360361test("permissions : scope manquant et adresse hors liste → refusé (les deux raisons)", () => {362 const c = checkPermission(keyA, op("POST /messages/send"), sendReq("b@stg.example"), book)363 assert.equal(c.verdict, "denied")364 assert.deepEqual(c.scope, { ok: false, required: ["mail.send", "mail.drafts"], missing: ["mail.send", "mail.drafts"] })365 assert.deepEqual(c.addresses, [{ address: "b@stg.example", where: "from", verdict: "not_allowed" }])366})367368test("permissions : scope présent (l'un des scopes suffit ; mail.admin les vaut tous) et adresse permise → autorisé", () => {369 const drafts = callerFromKey({ scopes: ["mail.drafts"], address_ids: [book[0].id] })370 const ok = checkPermission(drafts, op("POST /messages/send"), sendReq("A@STG.example"), book)371 assert.equal(ok.verdict, "allowed")372 assert.deepEqual(ok.scope.missing, [])373 assert.equal(ok.resource, false)374 assert.equal(checkPermission(callerFromKey({ scopes: ["mail.admin"], address_ids: [book[0].id] }), op("POST /messages/send"), sendReq("a@stg.example"), book).verdict, "allowed")375 // l'adresse peut être désignée par son identifiant376 assert.equal(checkPermission(keyA, op("GET /messages"), buildRequest(op("GET /messages"), { ...noValues, query: { address: book[0].id } }), book).verdict, "allowed")377 assert.equal(checkPermission(keyA, op("GET /messages"), buildRequest(op("GET /messages"), { ...noValues, query: { address: "a@stg.example,b@stg.example" } }), book).verdict, "denied")378 // aucun scope requis, aucune adresse : autorisé379 assert.equal(checkPermission(keyA, op("GET /me"), buildRequest(op("GET /me"), noValues), book).verdict, "allowed")380})381382test("permissions : all_addresses ne vaut qu'avec mail.admin (comme le serveur)", () => {383 const admin = callerFromKey({ scopes: ["mail.admin"], address_ids: [], all_addresses: true })384 assert.equal(checkPermission(admin, op("POST /messages/send"), sendReq("inconnue@stg.example"), book).verdict, "allowed")385 const fake = callerFromKey({ scopes: ["mail.send"], address_ids: [], all_addresses: true })386 assert.equal(checkPermission(fake, op("POST /messages/send"), sendReq("a@stg.example"), book).verdict, "denied")387})388389test("permissions : inconnu avant l'exécution (annuaire incomplet, appelant inconnu) ; ressource par identifiant signalée", () => {390 // la clé a une adresse que l'annuaire de la console ne connaît pas : une adresse inconnue pourrait être celle-là391 const partial = callerFromKey({ scopes: ["mail.send"], address_ids: [book[0].id, "33333333-3333-4333-8333-333333333333"] })392 const u = checkPermission(partial, op("POST /messages/send"), sendReq("ailleurs@stg.example"), book)393 assert.equal(u.verdict, "unknown")394 assert.equal(u.addresses[0].verdict, "unknown")395 // … mais une adresse connue de l'annuaire et absente de la liste est refusée396 assert.equal(checkPermission(partial, op("POST /messages/send"), sendReq("b@stg.example"), book).verdict, "denied")397 // liste entièrement connue : toute autre adresse est refusée, même hors annuaire398 assert.equal(checkPermission(callerFromKey({ scopes: ["mail.send"], address_ids: [book[0].id] }), op("POST /messages/send"), sendReq("ailleurs@stg.example"), book).verdict, "denied")399 const none = checkPermission(null, op("POST /messages/send"), sendReq("a@stg.example"), book)400 assert.equal(none.verdict, "unknown")401 const res = checkPermission(callerFromKey({ scopes: ["mail.attachments.read"], address_ids: [book[0].id] }), op("GET /messages/{id}/attachments/{attachment_id}"), buildRequest(op("GET /messages/{id}/attachments/{attachment_id}"), { ...noValues, path: { id: "m", attachment_id: "a" } }), book)402 assert.deepEqual([res.verdict, res.resource], ["allowed", true])403})404405test("permissions : appelant décrit par /me (session ou jeton d'exploration) ; route publique", () => {406 const me = callerFromMe({ scopes: ["mail.send", "mail.read"], all_addresses: false, addresses: [{ id: book[0].id, address: "a@stg.example" }] })407 assert.equal(checkPermission(me, op("POST /messages/send"), sendReq("a@stg.example")).verdict, "allowed")408 const no = checkPermission(me, op("POST /messages/send"), sendReq("b@stg.example"))409 assert.deepEqual([no.verdict, no.scope.ok, no.addresses[0].verdict], ["denied", true, "not_allowed"])410 const pub = checkPermission(null, op("GET /health"), buildRequest(op("GET /health"), noValues))411 assert.deepEqual([pub.verdict, pub.public], ["allowed", true])412})413