fix(api): проверять ответы настроек и выпуска сертификатов
This commit is contained in:
1 parent
adb6589816
commit
df89e88f4e
5 files changed
+139
-65
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { test } from "node:test"
|
||||
import { createCertificateIssueJob, getCertificateIssueJob, getAcmeSettings, putAcmeSettings, testAcmeSettings, getCertificateRenewSettings, putCertificateRenewSettings } from "./certificates"
|
||||
const base = "https://api.example.test"
|
||||
const issue = { serverId: "1", certName: "cert", domainNames: ["test.example"] }
|
||||
const acme = { directoryUrl: "https://acme.example.test/directory", tokenConfigured: false }
|
||||
const renew = { enabled: false, intervalSec: 300, renewBeforeDays: 30 }
|
||||
const job = { id: "job-1", serverId: "1", certName: "cert", domainNames: ["test.example"], status: "queued", step: "queued", requestedAt: "2026-10-01T00:00:00Z" }
|
||||
|
||||
test("settings readers reject malformed and empty responses instead of defaults", async () => {
|
||||
const original = globalThis.fetch
|
||||
try {
|
||||
for (const payload of [{}, [], { ...acme, tokenConfigured: "false" }, { ...renew, enabled: "false" }]) {
|
||||
globalThis.fetch = async () => new Response(JSON.stringify(payload), { status: 200 })
|
||||
await assert.rejects(() => getAcmeSettings(base))
|
||||
await assert.rejects(() => getCertificateRenewSettings(base))
|
||||
}
|
||||
globalThis.fetch = async () => new Response(null, { status: 204 })
|
||||
await assert.rejects(() => putAcmeSettings(base, {}))
|
||||
await assert.rejects(() => putCertificateRenewSettings(base, { enabled: true }))
|
||||
} finally { globalThis.fetch = original }
|
||||
})
|
||||
|
||||
test("strict settings preserve false, carry caller cancellation and PUT body", async () => {
|
||||
const original = globalThis.fetch; let init: RequestInit | undefined
|
||||
globalThis.fetch = async (url, options) => { init = options; return new Response(JSON.stringify(String(url).includes("renew") ? renew : acme), { status: 200 }) }
|
||||
try {
|
||||
const abort = new AbortController()
|
||||
assert.equal((await getAcmeSettings(base, { signal: abort.signal })).tokenConfigured, false)
|
||||
const signal = init?.signal; abort.abort(); assert.equal(signal?.aborted, true)
|
||||
assert.equal((await putCertificateRenewSettings(base, { enabled: false })).enabled, false)
|
||||
assert.equal(init?.method, "PUT"); assert.equal(init?.body, JSON.stringify({ enabled: false }))
|
||||
} finally { globalThis.fetch = original }
|
||||
})
|
||||
|
||||
test("invalid request fields fail before sending mutation", async () => {
|
||||
const original = globalThis.fetch; let calls = 0
|
||||
globalThis.fetch = async () => { calls++; return new Response("{}", { status: 200 }) }
|
||||
try {
|
||||
await assert.rejects(() => putAcmeSettings(base, { directoryUrl: "bad" }))
|
||||
await assert.rejects(() => putCertificateRenewSettings(base, { intervalSec: 0 }))
|
||||
await assert.rejects(() => createCertificateIssueJob(base, { ...issue, domainNames: [] }))
|
||||
assert.equal(calls, 0)
|
||||
} finally { globalThis.fetch = original }
|
||||
})
|
||||
|
||||
test("issue acknowledgment and polling require matching job identity", async () => {
|
||||
const original = globalThis.fetch
|
||||
try {
|
||||
for (const payload of [{}, { jobId: "" }, { jobId: " " }]) {
|
||||
globalThis.fetch = async () => new Response(JSON.stringify(payload), { status: 200 })
|
||||
await assert.rejects(() => createCertificateIssueJob(base, issue))
|
||||
}
|
||||
globalThis.fetch = async () => new Response(JSON.stringify(job), { status: 200 })
|
||||
assert.equal((await getCertificateIssueJob(base, "job-1")).status, "queued")
|
||||
await assert.rejects(() => getCertificateIssueJob(base, "job-other"), /другой задаче/)
|
||||
} finally { globalThis.fetch = original }
|
||||
})
|
||||
|
||||
test("Cloudflare failure preserves backend message and malformed success is rejected", async () => {
|
||||
const original = globalThis.fetch
|
||||
try {
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({ ok: false, message: "Cloudflare отказал" }), { status: 400 })
|
||||
await assert.rejects(() => testAcmeSettings(base), /Cloudflare отказал/)
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({}), { status: 200 })
|
||||
await assert.rejects(() => testAcmeSettings(base))
|
||||
globalThis.fetch = async () => new Response(JSON.stringify({ ok: false, message: "denied" }), { status: 200 })
|
||||
assert.equal((await testAcmeSettings(base)).ok, false)
|
||||
} finally { globalThis.fetch = original }
|
||||
})
|
||||
+55
-63
@@ -1,85 +1,77 @@
|
||||
import { certificatesStateSchema } from "@mmapp/contracts/certificates"
|
||||
import type {
|
||||
AcmeCloudflareSettingsDto,
|
||||
CertificateIssueJob,
|
||||
CertificateIssueRequest,
|
||||
CertificateRenewSettingsDto,
|
||||
CertificatesListResponse,
|
||||
import { z } from "zod"
|
||||
import {
|
||||
acmeCloudflareSettingsDtoSchema,
|
||||
certificateIssueJobSchema,
|
||||
certificateIssueRequestSchema,
|
||||
certificateRenewSettingsDtoSchema,
|
||||
certificatesListResponseSchema,
|
||||
certificatesStateSchema,
|
||||
putAcmeCloudflareSettingsSchema,
|
||||
putCertificateRenewSettingsSchema,
|
||||
testAcmeCloudflareSettingsSchema,
|
||||
} from "@mmapp/contracts/certificates"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import type { CertificateIssueRequest } from "@mmapp/contracts/certificates"
|
||||
import { ApiClientError, requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export async function listCertificates(baseUrl: string): Promise<CertificatesListResponse> {
|
||||
return requestJson<CertificatesListResponse>(baseUrl, "/api/certificates")
|
||||
const issueAckSchema = z.object({ jobId: z.string().min(1).refine(value => value.trim() === value) })
|
||||
const acmeTestSchema = z.object({ ok: z.boolean(), message: z.string().optional() })
|
||||
|
||||
function certificateJson(baseUrl: string, path: string, options?: RequestInit) {
|
||||
const signal = AbortSignal.any([...(options?.signal ? [options.signal] : []), AbortSignal.timeout(30_000)])
|
||||
return requestJson<unknown>(baseUrl, path, { ...options, signal })
|
||||
}
|
||||
|
||||
export async function refreshCertificates(baseUrl: string): Promise<CertificatesListResponse> {
|
||||
return requestJson<CertificatesListResponse>(baseUrl, "/api/certificates/refresh", { method: "POST" })
|
||||
export async function listCertificates(baseUrl: string, options?: RequestInit) {
|
||||
return certificatesListResponseSchema.parse(await certificateJson(baseUrl, "/api/certificates", { ...options, method: "GET" }))
|
||||
}
|
||||
|
||||
export async function createCertificateIssueJob(
|
||||
baseUrl: string,
|
||||
payload: CertificateIssueRequest,
|
||||
): Promise<{ jobId: string }> {
|
||||
return requestJson<{ jobId: string }>(baseUrl, "/api/certificates/issue", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
export async function refreshCertificates(baseUrl: string, options?: RequestInit) {
|
||||
return certificatesListResponseSchema.parse(await certificateJson(baseUrl, "/api/certificates/refresh", { ...options, method: "POST" }))
|
||||
}
|
||||
|
||||
export async function getCertificateIssueJob(
|
||||
baseUrl: string,
|
||||
jobId: string,
|
||||
): Promise<CertificateIssueJob> {
|
||||
return requestJson<CertificateIssueJob>(baseUrl, `/api/certificates/issue/${encodeURIComponent(jobId)}`)
|
||||
export async function createCertificateIssueJob(baseUrl: string, payload: CertificateIssueRequest, options?: RequestInit) {
|
||||
const body = certificateIssueRequestSchema.parse(payload)
|
||||
return issueAckSchema.parse(await certificateJson(baseUrl, "/api/certificates/issue", { ...options, method: "POST", body: JSON.stringify(body) }))
|
||||
}
|
||||
|
||||
export async function getAcmeSettings(baseUrl: string): Promise<AcmeCloudflareSettingsDto> {
|
||||
return requestJson<AcmeCloudflareSettingsDto>(baseUrl, "/api/certificates/acme-settings")
|
||||
export async function getCertificateIssueJob(baseUrl: string, jobId: string, options?: RequestInit) {
|
||||
const result = certificateIssueJobSchema.parse(await certificateJson(baseUrl, "/api/certificates/issue/" + encodeURIComponent(jobId), { ...options, method: "GET" }))
|
||||
if (result.id !== jobId) throw new Error("Ответ относится к другой задаче выпуска")
|
||||
return result
|
||||
}
|
||||
|
||||
export async function putAcmeSettings(
|
||||
baseUrl: string,
|
||||
payload: {
|
||||
directoryUrl?: string
|
||||
defaultZoneId?: string | null
|
||||
cloudflareApiToken?: string | null
|
||||
},
|
||||
): Promise<AcmeCloudflareSettingsDto> {
|
||||
return requestJson<AcmeCloudflareSettingsDto>(baseUrl, "/api/certificates/acme-settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
export async function getAcmeSettings(baseUrl: string, options?: RequestInit) {
|
||||
return acmeCloudflareSettingsDtoSchema.parse(await certificateJson(baseUrl, "/api/certificates/acme-settings", { ...options, method: "GET" }))
|
||||
}
|
||||
|
||||
export async function testAcmeSettings(
|
||||
baseUrl: string,
|
||||
payload?: { cloudflareApiToken?: string },
|
||||
): Promise<{ ok: boolean; message?: string }> {
|
||||
return requestJson<{ ok: boolean; message?: string }>(baseUrl, "/api/certificates/acme-settings/test", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload ?? {}),
|
||||
})
|
||||
export async function putAcmeSettings(baseUrl: string, payload: { directoryUrl?: string; defaultZoneId?: string | null; cloudflareApiToken?: string | null }, options?: RequestInit) {
|
||||
const body = putAcmeCloudflareSettingsSchema.parse(payload)
|
||||
return acmeCloudflareSettingsDtoSchema.parse(await certificateJson(baseUrl, "/api/certificates/acme-settings", { ...options, method: "PUT", body: JSON.stringify(body) }))
|
||||
}
|
||||
|
||||
export async function getCertificateRenewSettings(baseUrl: string): Promise<CertificateRenewSettingsDto> {
|
||||
return requestJson<CertificateRenewSettingsDto>(baseUrl, "/api/certificates/renew-settings")
|
||||
export async function testAcmeSettings(baseUrl: string, payload?: { cloudflareApiToken?: string }, options?: RequestInit) {
|
||||
const body = testAcmeCloudflareSettingsSchema.parse(payload ?? {})
|
||||
try {
|
||||
return acmeTestSchema.parse(await certificateJson(baseUrl, "/api/certificates/acme-settings/test", { ...options, method: "POST", body: JSON.stringify(body) }))
|
||||
} catch (error) {
|
||||
// Backend возвращает message для отказа Cloudflare, а не стандартное error.
|
||||
if (error instanceof ApiClientError) {
|
||||
const failure = acmeTestSchema.safeParse(error.payload)
|
||||
if (failure.success && !failure.data.ok && failure.data.message) throw new ApiClientError(failure.data.message, error.status, error.payload)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function putCertificateRenewSettings(
|
||||
baseUrl: string,
|
||||
payload: {
|
||||
enabled?: boolean
|
||||
intervalSec?: number
|
||||
renewBeforeDays?: number
|
||||
},
|
||||
): Promise<CertificateRenewSettingsDto> {
|
||||
return requestJson<CertificateRenewSettingsDto>(baseUrl, "/api/certificates/renew-settings", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
export async function getCertificateRenewSettings(baseUrl: string, options?: RequestInit) {
|
||||
return certificateRenewSettingsDtoSchema.parse(await certificateJson(baseUrl, "/api/certificates/renew-settings", { ...options, method: "GET" }))
|
||||
}
|
||||
|
||||
export async function putCertificateRenewSettings(baseUrl: string, payload: { enabled?: boolean; intervalSec?: number; renewBeforeDays?: number }, options?: RequestInit) {
|
||||
const body = putCertificateRenewSettingsSchema.parse(payload)
|
||||
return certificateRenewSettingsDtoSchema.parse(await certificateJson(baseUrl, "/api/certificates/renew-settings", { ...options, method: "PUT", body: JSON.stringify(body) }))
|
||||
}
|
||||
|
||||
export async function readCertificatesState(baseUrl: string, options?: RequestInit) {
|
||||
const signal = AbortSignal.any([...(options?.signal ? [options.signal] : []), AbortSignal.timeout(30_000)])
|
||||
return certificatesStateSchema.parse(await requestJson<unknown>(baseUrl, "/api/certificates/state", { ...options, method: "GET", signal }))
|
||||
return certificatesStateSchema.parse(await certificateJson(baseUrl, "/api/certificates/state", { ...options, method: "GET" }))
|
||||
}
|
||||
Reference in new issue
Block a user