ts / test / live / conformance.test.ts
973 words
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
 * Live spec-conformance sweep: call every read endpoint against
 * https://api.ird.ro and validate each response body against the schema
 * `spec/openapi.json` declares for it.
 *
 * The coverage table pins the client to the spec but says nothing about
 * whether the spec still matches the API; this closes that gap. Skipped
 * unless IRD_API_KEY is set; run with `npm run test:live`. Read-only by
 * design: it creates nothing and charges nothing beyond metered reads.
 * Endpoints that need a resource to exist are exercised against whatever
 * the account already has and skipped when it has none.
 *
 * Not covered, because each needs a resource that only exists mid-flight
 * or costs money to create: GET /jobs/{id} and /jobs/{id}/result (run a
 * job), /ipfs/uploads/{id} (start an upload), /pins/{requestid} (add a pin
 * through `pins`), /vps/actions/{id} (any VPS action).
 */
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { test } from 'node:test';
import type { Client } from '../../src/client.js';
import {
  createClient,
  credits,
  dns,
  domains,
  ipfs,
  isApiError,
  p2p,
  pins,
  registrations as reg,
  sharing,
  support,
  transfers,
  tunnels,
  vps,
} from '../../src/index.js';
import { check, responseSchema, type OpenApiSpec } from '../../src/spec-check.js';
import { readApiKey } from '../helpers.js';

type Endpoint = readonly [path: string, expectedStatus: number, call: (() => Promise<unknown>) | undefined];

/** The id of the first item under KEY of a listing, or undefined when the account has none. */
const firstId = async <T extends { id: string }>(list: () => Promise<Record<string, unknown>>, key: string) => {
  try {
    return ((await list())[key] as readonly T[] | undefined)?.[0]?.id;
  } catch {
    return undefined;
  }
};

const endpoints = async (client: Client, anon: Client): Promise<readonly Endpoint[]> => {
  const regId = await firstId(() => reg.list(client), 'registrations');
  const gwId = await firstId(() => ipfs.listDomains(client), 'domains');
  const nameId = await firstId(() => ipfs.listNames(client), 'names');
  const pinId = await firstId(() => ipfs.listPins(client), 'pins');
  const appId = await firstId(() => p2p.listApps(client), 'apps');
  const tunnelId = await firstId(() => tunnels.list(client), 'tunnels');
  const instanceId = await firstId(() => vps.listInstances(client), 'instances');
  const deploymentId = await firstId(() => vps.listAppDeployments(client), 'deployments');
  const actionId = await firstId(() => reg.listActions(client), 'actions');
  const threadId = await firstId(() => support.listThreads(client), 'threads');
  const claimId = await firstId(() => dns.listClaims(client), 'claims');
  const zone = (await dns.listZones(client)).domains?.[0]?.origin?.replace(/\.$/, '');
  const when = <T>(id: string | undefined, f: (id: string) => Promise<T>) => (id ? () => f(id) : undefined);

  return [
    ['/credits/balance', 200, () => credits.balance(client)],
    ['/credits/ledger', 200, () => credits.ledger(client)],
    ['/credits/prices', 200, () => credits.prices(client)],
    ['/contact/threads', 200, () => support.listThreads(client)],
    ['/contact/threads/{id}', 200, when(threadId, (id) => support.getThread(client, id))],
    ['/domains/check', 200, () => domains.check(anon, 'ird.ro')],
    ['/domains/info', 200, () => domains.info(client, 'ird.ro')],
    ['/domains/preflight', 200, () => domains.preflight(client, 'ird.ro')],
    ['/domains/dns-snapshot', 200, () => domains.dnsSnapshot(client, 'ird.ro')],
    ['/domains/search', 200, () => domains.search(client, 'shop')],
    ['/domains/example', 200, () => domains.example(client)],
    ['/domains/directory', 200, () => domains.directory(client, { limit: 20 })],
    ['/domains/directory/{domain}', 200, () => domains.directoryEntry(client, 'ird.ro')],
    ['/domains/registrations', 200, () => reg.list(client, { limit: 100 })],
    ['/domains/registrations/{id}', 200, when(regId, (id) => reg.get(client, id))],
    ['/domains/registrations/{id}/hosts', 200, when(regId, (id) => reg.listHosts(client, id))],
    ['/domains/registrations/{id}/dsdata', 200, when(regId, (id) => reg.listDsData(client, id))],
    ['/domains/registrations/{id}/trade', 200, when(regId, (id) => reg.quoteTrade(client, id))],
    ['/domains/registrations/{id}/dns/dnssec', 200, when(regId, (id) => dns.getDnssec(client, id))],
    ['/domains/registrations/{id}/dns/nameservers', 200, when(regId, (id) => dns.hostedNameservers(client, id))],
    ['/domains/actions', 200, () => reg.listActions(client, { limit: 100 })],
    ['/domains/actions/{id}', 200, when(actionId, (id) => reg.getAction(client, id))],
    ['/dns/domains', 200, () => dns.listZones(client)],
    ['/dns/domains/{domain}', 200, when(zone, (z) => dns.getZone(client, z))],
    ['/dns/claims', 200, () => dns.listClaims(client)],
    ['/dns/claims/{id}', 200, when(claimId, (id) => dns.getClaim(client, id))],
    ['/ipfs/pins', 200, () => ipfs.listPins(client, { limit: 100 })],
    ['/ipfs/pins/{id}', 200, when(pinId, (id) => ipfs.getPin(client, id))],
    ['/ipfs/names', 200, () => ipfs.listNames(client)],
    ['/ipfs/names/{id}', 200, when(nameId, (id) => ipfs.getName(client, id))],
    ['/ipfs/domains', 200, () => ipfs.listDomains(client)],
    ['/ipfs/domains/{id}', 200, when(gwId, (id) => ipfs.getDomain(client, id))],
    ['/ipfs/domains/{id}/pins', 200, when(gwId, (id) => ipfs.listDomainPins(client, id))],
    ['/ipfs/usage', 200, () => ipfs.usage(client)],
    ['/pins', 200, () => pins.list(client, { limit: 100 })],
    ['/p2p/apps', 200, () => p2p.listApps(client)],
    ['/p2p/apps/{id}', 200, when(appId, (id) => p2p.getApp(client, id))],
    ['/p2p/apps/{id}/domains', 200, when(appId, (id) => p2p.listAppDomains(client, id))],
    ['/p2p/usage', 200, () => p2p.usage(client)],
    ['/tunnels', 200, () => tunnels.list(client)],
    ['/tunnels/{id}', 200, when(tunnelId, (id) => tunnels.get(client, id))],
    ['/vps/tiers', 200, () => vps.listTiers(client)],
    ['/vps/system-images', 200, () => vps.listSystemImages(client)],
    ['/vps/ssh-keys', 200, () => vps.listSshKeys(client)],
    ['/vps/availability', 200, () => vps.availability(client)],
    ['/vps/instances', 200, () => vps.listInstances(client)],
    ['/vps/instances/{id}', 200, when(instanceId, (id) => vps.getInstance(client, id))],
    ['/vps/instances/{id}/metrics', 200, when(instanceId, (id) => vps.getMetrics(client, id))],
    ['/vps/instances/{id}/domains', 200, when(instanceId, (id) => vps.listInstanceDomains(client, id))],
    ['/vps/apps', 200, () => vps.appCatalog(client)],
    ['/vps/apps/deployments', 200, () => vps.listAppDeployments(client)],
    ['/vps/apps/deployments/{id}', 200, when(deploymentId, (id) => vps.getAppDeployment(client, id))],
    ['/vps/volumes', 200, () => vps.listVolumes(client)],
    ['/vps/images', 200, () => vps.listImages(client)],
    ['/vps/activity', 200, () => vps.listActivity(client)],
    // account-JWT-only: the 401 envelope is the documented response here
    ['/grants', 401, () => sharing.listGrants(client)],
    ['/domains/registrations/{id}/grants', 401, when(regId, (id) => sharing.listDomainGrants(client, id))],
    ['/vps/transfers', 401, () => transfers.list(client)],
  ];
};

type Result = Readonly<{ path: string; status: number; expected: number; problems: readonly string[] }>;

const sweep = async (spec: OpenApiSpec, client: Client, anon: Client): Promise<readonly Result[]> => {
  const results: Result[] = [];
  for (const [path, expected, call] of await endpoints(client, anon)) {
    if (!call) continue;
    let status = 200;
    let body: unknown;
    try {
      body = await call();
    } catch (e) {
      if (!isApiError(e)) throw e;
      status = e.status;
      body = e.response;
    }
    const problems =
      status === expected
        ? check(responseSchema(spec, 'get', path, status), body)
        : [`expected HTTP ${expected} but got ${status}`];
    results.push({ path, status, expected, problems });
  }
  return results;
};

test('live responses match the spec', async (t) => {
  const key = await readApiKey();
  if (!key) return t.skip('IRD_API_KEY not set');
  const spec = JSON.parse(await readFile('spec/openapi.json', 'utf8')) as OpenApiSpec;
  const results = await sweep(spec, createClient({ apiKey: key }), createClient());
  const drifted = results.filter((r) => r.problems.length > 0);
  for (const { path, problems } of drifted) {
    console.log(`\nDRIFT ${path}`);
    for (const p of problems) console.log(`  - ${p}`);
  }
  console.log(`\nconformance: ${results.length} endpoints, ${results.length - drifted.length} conform, ${drifted.length} drifted`);
  assert.ok(results.length > 0, 'no endpoints were exercised');
  assert.deepEqual(
    drifted.map((r) => r.path),
    [],
    'the spec and the live API disagree; see the report above',
  );
});

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/ts.git