Files

199 lines
7.0 KiB
TypeScript

import test from "node:test"
import assert from "node:assert/strict"
import { redactRequestOptionsForLog } from "../../lib/api-request-log"
import { logger } from "../../lib/logger"
const loadApiClient = () => import(new URL("../../lib/api-client.ts", import.meta.url).href)
test("permission bodies reach the transport while user tag values stay out of logs", async (t) => {
const { ApiClient } = await loadApiClient()
const logged: unknown[][] = []
t.mock.method(logger, "log", (...args: unknown[]) => logged.push(args))
let sent: RequestInit | undefined
const client = new ApiClient({
fetch: async (_input: string | Request, options?: RequestInit) => {
sent = options
return Response.json({ results: [] })
},
})
await client.post(
"https://console.test/account/permissions",
{ checks: [{ requestTags: { owner: "private-owner" } }] },
{ suppressBodyLogging: true },
)
assert.match(String(sent?.body), /private-owner/)
assert.equal(Object.hasOwn(sent ?? {}, "suppressBodyLogging"), false)
assert.doesNotMatch(JSON.stringify(logged), /private-owner/)
assert.match(JSON.stringify(logged), /\[REDACTED\]/)
})
test("ApiClient does not mutate request options and preserves existing query parameters", async () => {
const { ApiClient } = await loadApiClient()
const urls: string[] = []
const transport = {
fetch: async (input: string | Request) => {
urls.push(String(input))
return Response.json({ ok: true })
},
}
const client = new ApiClient(transport, { baseUrl: "https://console.test/api" })
const options = { params: { page: "2" }, headers: { "X-Request": "one" } }
await client.get("/objects?prefix=photos", options)
await client.get("/objects?prefix=photos", options)
assert.deepEqual(options, { params: { page: "2" }, headers: { "X-Request": "one" } })
assert.deepEqual(urls, [
"https://console.test/api/objects?prefix=photos&page=2",
"https://console.test/api/objects?prefix=photos&page=2",
])
})
test("ApiClient rejects 401 and 403 responses after invoking global handlers", async () => {
const { ApiClient } = await loadApiClient()
const handled: number[] = []
const errorHandler = {
handle401: async () => {
handled.push(401)
},
handle403: async () => {
handled.push(403)
},
handleServerError: async () => {},
handleByStatus: async () => {},
}
const statuses = [401, 403]
const client = new ApiClient(
{
fetch: async () => {
const status = statuses.shift() ?? 500
return Response.json({ message: `HTTP ${status}` }, { status })
},
},
{ errorHandler },
)
await assert.rejects(client.get("https://console.test/unauthorized"), { message: "HTTP 401", status: 401 })
await assert.rejects(client.get("https://console.test/forbidden"), { message: "HTTP 403", status: 403 })
assert.deepEqual(handled, [401, 403])
})
test("ApiClient preserves an explicitly resolved same-origin admin path", async () => {
const { ApiClient } = await loadApiClient()
const urls: string[] = []
const client = new ApiClient(
{
fetch: async (input: string | Request) => {
urls.push(String(input))
return Response.json({ ok: true })
},
},
{ baseUrl: "https://console.test/rustfs/admin/v3" },
)
await client.get(client.resolveUrl("/rustfs/admin/v4/cluster/snapshot"))
assert.deepEqual(urls, ["https://console.test/rustfs/admin/v4/cluster/snapshot"])
})
test("ApiClient redacts sensitive headers and request bodies from development logs", () => {
const redacted = redactRequestOptionsForLog({
headers: { Authorization: "Bearer header-secret", Cookie: "session=cookie-secret" },
body: JSON.stringify({
password: "body-secret",
secretKey: "tier-secret-key",
profile: { apiKey: "nested-secret" },
creds: '{"private_key":"gcs-private-key"}',
account_key: "azure-account-key",
service_account_json: '{"private_key":"native-gcs-private-key"}',
}),
})
const serialized = JSON.stringify(redacted)
assert.doesNotMatch(
serialized,
/body-secret|tier-secret-key|nested-secret|header-secret|cookie-secret|gcs-private-key|azure-account-key|native-gcs-private-key/,
)
assert.match(serialized, /\[REDACTED\]/)
})
test("ApiClient exposes structured service codes without losing the safe message", async () => {
const { ApiClient } = await loadApiClient()
const client = new ApiClient({
fetch: async () =>
new Response(
"<Error><Code>NoSuchConfiguration</Code><Message>on-demand migration is not configured</Message></Error>",
{ status: 404 },
),
})
await assert.rejects(client.get("https://console.test/on-demand-migration/photos"), {
code: "NoSuchConfiguration",
message: "on-demand migration is not configured",
status: 404,
})
})
for (const format of ["json", "nested-json", "xml"]) {
for (const [status, code] of [
[403, "InvalidAccessKeyId"],
[403, "ExpiredToken"],
[400, "ExpiredToken"],
] as const) {
for (const suppress403Redirect of [false, true]) {
test(`ApiClient expires ${format} ${status} ${code} with suppression=${suppress403Redirect}`, async () => {
const { ApiClient } = await loadApiClient()
const handled: string[] = []
const payload = { Code: code, Message: "Session expired" }
const response =
format === "xml"
? new Response(`<Error><Code>${code}</Code><Message>Session expired</Message></Error>`, { status })
: Response.json(format === "nested-json" ? { error: payload } : payload, { status })
const client = new ApiClient(
{ fetch: async () => response },
{
errorHandler: {
handle401: async () => {
handled.push("session")
},
handle403: async () => {
handled.push("permission")
},
handleServerError: async () => {},
handleByStatus: async () => {},
},
},
)
await assert.rejects(client.get("https://console.test/access-keys", { suppress403Redirect }), { status, code })
assert.deepEqual(handled, ["session"])
})
}
}
}
for (const suppress403Redirect of [false, true]) {
test(`ApiClient preserves ordinary permission handling with suppression=${suppress403Redirect}`, async () => {
const { ApiClient } = await loadApiClient()
const handled: string[] = []
const client = new ApiClient(
{ fetch: async () => Response.json({ Code: "AccessDenied" }, { status: 403 }) },
{
errorHandler: {
handle401: async () => {
handled.push("session")
},
handle403: async () => {
handled.push("permission")
},
handleServerError: async () => {},
handleByStatus: async () => {},
},
},
)
await assert.rejects(client.get("https://console.test/accountinfo", { suppress403Redirect }), {
code: "AccessDenied",
})
assert.deepEqual(handled, suppress403Redirect ? [] : ["permission"])
})
}