import { beforeAll, describe, expect, test } from "vitest"; import { ServerList, Vanta } from "vanta-auditor-api-sdk"; /** * Live smoke test against a real Vanta API tenant. Run via `npm test` from this * directory when the three SMOKE_* environment variables are populated; * otherwise every test is reported as skipped. See ../SMOKE_TEST.md for * fixture details and CI wiring. */ // Read env at module load — CI populates these via the SMOKE_* GitHub Actions // secrets; locally, export them yourself. When any required var is missing // every test reports as skipped so `npm test` doesn't break for engineers // without demo-account creds. const clientId = process.env["SMOKE_OAUTH_CLIENT_ID"] ?? ""; const clientSecret = process.env["SMOKE_OAUTH_CLIENT_SECRET"] ?? ""; const auditId = process.env["SMOKE_AUDIT_ID"] ?? ""; const missingEnv = !clientId ? "SMOKE_OAUTH_CLIENT_ID" : !clientSecret ? "SMOKE_OAUTH_CLIENT_SECRET" : !auditId ? "SMOKE_AUDIT_ID" : ""; const shouldSkip = missingEnv !== ""; const skipReason = shouldSkip ? `smoke test skipped — ${missingEnv} is not set (CI populates via SMOKE_* env vars)` : ""; let sdk: Vanta; describe.sequential("Vanta SDK smoke", () => { beforeAll(async () => { if (shouldSkip) return; // Single source of truth for the Vanta Commercial host: the SDK's own // ServerList, regenerated by Speakeasy from the spec. OAuth and SDK API // calls share the SAME host — OAuth at /oauth/token, SDK at /v1/* — so // deriving both from one place eliminates the class of drift where // someone updates one and not the other. const sdkServerUrl = ServerList.find((s) => s.includes("api.vanta.com")); if (!sdkServerUrl) { throw new Error( `ServerList contains no Commercial entry — got ${JSON.stringify(ServerList)}. ` + `An overlay regression broke the server list; the smoke test can't ` + `run until the SDK is regenerated correctly.`, ); } const oauthBaseUrl = sdkServerUrl.replace(/\/v[0-9]+$/, ""); const accessToken = await fetchAccessToken(oauthBaseUrl, clientId, clientSecret); sdk = new Vanta({ bearerAuth: accessToken, serverURL: sdkServerUrl, // Intentionally do NOT pass a `debugLogger` option — it would write // request and response detail to stdout and surface in CI logs. }); }); // Catches the case where the Speakeasy overlay regression drops the // Commercial host from the generated ServerList. Deliberately permissive // while the EU/AUS phantom entries are still in the spec — tighten to // exact-match [Commercial, Gov] after the spec cleanup lands and the new // regen produces the post-cleanup server list. test.skipIf(shouldSkip)("ServerList contains Commercial", () => { expect(ServerList.length).toBeGreaterThanOrEqual(1); expect(ServerList[0]).toMatch(/^https:\/\/api\.vanta\.com/); }); test.skipIf(shouldSkip)("listAudits finds fixture audit", async () => { let pageCursor: string | undefined; let found = false; do { const res = await sdk.audits.list({ pageCursor, pageSize: 100 }); const audits = res.results.data; expect(audits).toBeDefined(); if (audits.some((a) => a.id === auditId)) { found = true; break; } const { hasNextPage, endCursor } = res.results.pageInfo; pageCursor = hasNextPage && endCursor != null ? endCursor : undefined; } while (pageCursor !== undefined); expect( found, `fixture audit ${auditId} not found in /audits results — was it deleted? ` + `See SMOKE_TEST.md for recovery steps.`, ).toBe(true); }); test.skipIf(shouldSkip)("listEvidence drills into evidence URLs", async (ctx) => { const listRes = await sdk.audits.listEvidence({ auditId }); const evidence = listRes.results.data; expect(evidence).toBeDefined(); if (evidence.length === 0) { ctx.skip( "fixture audit has no evidence — skipping getEvidenceUrls drill-down " + "(see SMOKE_TEST.md for seeding guidance)", ); } const evidenceId = evidence[0]!.id; try { const urlsRes = await sdk.audits.getEvidenceUrls({ auditId, auditEvidenceId: evidenceId, }); expect(urlsRes.results).toBeDefined(); } catch (e) { // 4xx on a specific evidence usually means that evidence is in a state // without URLs (not uploaded, processing, etc.). The SDK round-tripped // an authenticated request and parsed a structured server response, // which is what this smoke test exists to verify — the business-logic // rejection is fixture state, not an SDK regression. Skip with detail. // // 5xx is re-thrown: a server error is a real signal, not fixture state. // // Duck-typed instead of `instanceof APIError`: when smoke-test installs // the parent via `file:..`, npm's behavior varies between symlink and // hard-copy across environments. A hard-copy gives us two separate // class instances of APIError, and `instanceof` silently misses. The // `statusCode` field is part of the documented VantaError contract. const statusCode = (e as { statusCode?: unknown }).statusCode; const body = (e as { body?: unknown }).body; if (typeof statusCode === "number" && statusCode >= 400 && statusCode < 500) { ctx.skip( `getEvidenceUrls returned HTTP ${statusCode} for evidence ${evidenceId} ` + `— likely fixture state, not an SDK regression. Body: ` + `${typeof body === "string" ? body : ""}`, ); } throw e; } }); test.skipIf(shouldSkip)("listComments succeeds", async () => { const res = await sdk.audits.listComments({ auditId }); expect(res.results.data).toBeDefined(); }); test.skipIf(shouldSkip)("listControls succeeds", async () => { const res = await sdk.audits.listControls({ auditId }); expect(res.results.data).toBeDefined(); }); }); if (shouldSkip) { // Surface the skip reason once at the top of the run so engineers don't // wonder why every test is yellow. console.warn(skipReason); } async function fetchAccessToken( baseUrl: string, oauthClientId: string, oauthClientSecret: string, ): Promise { // Vanta's OAuth requires an explicit `scope` parameter (per the spec's // securitySchemes.oauth.flows.clientCredentials.scopes). v1 only exercises // read endpoints under `audits`, so we request just `auditor-api.audit:read`. // Add `auditor-api.auditor:read` when we add tests for `sdk.auditors.*`, // and the `:write` variants when we add mutation tests. const scope = "auditor-api.audit:read"; const form = new URLSearchParams({ grant_type: "client_credentials", client_id: oauthClientId, client_secret: oauthClientSecret, scope, }); const resp = await fetch(`${baseUrl}/oauth/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", }, body: form.toString(), }); if (resp.status !== 200) { // OAuth 2.0 error responses (RFC 6749 §5.2) contain // {error, error_description} and never include the access_token or // client_secret, so they're safe to log. const raw = await resp.text(); let detail = raw; try { const parsed = JSON.parse(raw) as { error?: string; error_description?: string; }; if (parsed.error !== undefined || parsed.error_description !== undefined) { detail = `error=${parsed.error ?? "?"} error_description=${parsed.error_description ?? "?"}`; } } catch { // body wasn't JSON — fall back to the raw string } throw new Error( `OAuth token endpoint ${baseUrl}/oauth/token returned HTTP ${resp.status} — ${detail}`, ); } const body = (await resp.json()) as { access_token?: string }; if (!body.access_token) { throw new Error("OAuth response missing access_token field"); } return body.access_token; }