Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
433 changes: 433 additions & 0 deletions packages/altoviz/behaviour.test.ts

Large diffs are not rendered by default.

144 changes: 144 additions & 0 deletions packages/altoviz/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import type {
ApiRequestOptions,
OpenAPIConfig,
RateLimitConfig,
} from 'corsair/http';
import { ApiError, request } from 'corsair/http';

const ALTOVIZ_API_BASE = 'https://api.altoviz.com';

/**
* Measured live: quota is 100 requests over a rolling window. The 429 carries
* `Retry-After` in milliseconds (13_000 / 36_000), not HTTP-spec seconds.
* corsair/http multiplies that value by 1000, so transport-level retries would
* sleep for hours and would also replay POSTs. maxRetries is 0 here.
*
* GET retries happen in `makeAltovizRequest` instead of corsair's bind layer:
* bind awaits a successful retry then still throws the original error
* (`packages/corsair/core/endpoints/bind.ts`). This plugin PR cannot change
* that file.
*/
const ALTOVIZ_RATE_LIMIT_CONFIG: RateLimitConfig = {
enabled: true,
maxRetries: 0,
initialRetryDelay: 1000,
backoffMultiplier: 2,
headerNames: {
retryAfter: 'retry-after',
},
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const GET_RETRY_LIMIT = 3;

function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

function getRetryDelayMs(error: unknown): number | undefined {
if (error instanceof ApiError && error.status === 429) {
return error.retryAfter != null ? error.retryAfter / 1000 : 1000;
}
return undefined;
}

export class AltovizAPIError extends Error {
public readonly status?: number;
public readonly body?: unknown;

constructor(
message: string,
options?: { cause?: Error; status?: number; body?: unknown },
) {
super(message, options?.cause ? { cause: options.cause } : undefined);
this.name = 'AltovizAPIError';
this.status = options?.status;
this.body = options?.body;
}
}

/**
* Path ids go through `options.path` and a constant `{id}` template, never
* concatenated into the URL string. That keeps caller values off the
* `{(.*?)}` placeholder regex in `corsair/http` (CodeQL js/polynomial-redos).
*/
export type AltovizRequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
body?: Record<string, unknown> | unknown[];
query?: Record<string, string | number | boolean | undefined>;
path?: Record<string, string | number>;
/**
* For the one multipart operation in the surface (purchase invoice upload).
* A plain record — the shared transport builds the actual `FormData` and
* accepts string or Blob values per field.
*/
formData?: Record<string, unknown>;
};

/**
* Issues an Altoviz request with the X-API-KEY header, this plugin's rate-limit
* retry policy, and error handlers.
*
* Three routes (the PDF downloads) answer with `application/pdf`, which the
* shared transport's `getResponseBody` decodes with `response.text()` — lossless
* for the JSON/text paths every other operation here uses, lossy for those
* three. That is a `corsair/async-core` limitation flagged in the PR rather
* than fixed here (see `packages/googledrive`'s `filesDownload` for the same
* caveat on another plugin), so `download` responses in this plugin type their
* body as an opaque string and document that it may not be byte-exact.
*/
export async function makeAltovizRequest<T>(
url: string,
apiKey: string,
options: AltovizRequestOptions = {},
): Promise<T> {
const { method = 'GET', body, query, formData, path } = options;

const config: OpenAPIConfig = {
BASE: ALTOVIZ_API_BASE,
VERSION: '1',
WITH_CREDENTIALS: false,
CREDENTIALS: 'omit',
TOKEN: undefined,
ENCODE_PATH: encodeURIComponent,
HEADERS: {
'X-API-KEY': apiKey,
...(formData ? {} : { 'Content-Type': 'application/json' }),
},
};

const requestOptions: ApiRequestOptions = {
method,
url: url.startsWith('/') ? url : `/${url}`,
path,
body: formData ? undefined : body,
formData,
mediaType: formData ? undefined : 'application/json; charset=utf-8',
query,
};

const retrySafe = method === 'GET';
let lastError: unknown;
for (let attempt = 1; attempt <= GET_RETRY_LIMIT + 1; attempt++) {
try {
return await request<T>(config, requestOptions, {
rateLimitConfig: ALTOVIZ_RATE_LIMIT_CONFIG,
});
} catch (error) {
lastError = error;
const delay = retrySafe ? getRetryDelayMs(error) : undefined;
if (delay == null || attempt > GET_RETRY_LIMIT) break;
await sleep(delay);
}
}

if (lastError instanceof Error) {
const status = (lastError as { status?: number }).status;
const body = (lastError as { body?: unknown }).body;
throw new AltovizAPIError(lastError.message, {
cause: lastError,
status,
body,
});
}
throw new AltovizAPIError('Unknown error');
}
223 changes: 223 additions & 0 deletions packages/altoviz/endpoints.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
/**
* Registry invariants: risk levels agree with the endpoint tree, the
* non-idempotent set is exactly the non-read operations (nothing more,
* nothing less), the UNREGISTER_WEBHOOK guard rejects a call with neither id
* nor url, and the audit-payload allow-list cannot admit anything that looks
* like personal or financial content.
*/

import { ALLOWED_FIELDS, auditPayload } from './endpoints/logging';
import { AltovizEndpointInputSchemas } from './endpoints/types';
import { isNonIdempotent, NON_IDEMPOTENT_OPERATIONS } from './error-handlers';
import { altovizEndpointMeta, altovizEndpointsNested } from './index';

function registeredPaths(): string[] {
const paths: string[] = [];
for (const [group, ops] of Object.entries(altovizEndpointsNested)) {
for (const op of Object.keys(ops as Record<string, unknown>)) {
paths.push(`${group}.${op}`);
}
}
return paths;
}

describe('registry invariants', () => {
test('every registered operation has metadata', () => {
const paths = registeredPaths();
expect(paths.length).toBe(67);
for (const path of paths) {
// toHaveProperty splits on '.' by default; these keys ARE dotted literals.
expect(altovizEndpointMeta).toHaveProperty([path]);
}
});

test('risk levels are only read, write or destructive, matching totals: 41 read, 15 write, 11 destructive', () => {
const counts = { read: 0, write: 0, destructive: 0 };
for (const meta of Object.values(altovizEndpointMeta)) {
expect(['read', 'write', 'destructive']).toContain(meta.riskLevel);
counts[meta.riskLevel as keyof typeof counts]++;
}
expect(counts).toEqual({ read: 41, write: 15, destructive: 11 });
});

test('every destructive operation is marked irreversible', () => {
const entries = Object.entries(altovizEndpointMeta) as Array<
[string, { riskLevel: string; irreversible?: boolean }]
>;
const destructive = entries.filter(
([, m]) => m.riskLevel === 'destructive',
);
expect(destructive.length).toBe(11);
for (const [, meta] of destructive) {
expect(meta.irreversible).toBe(true);
}
});
});

describe('the non-idempotent set is exactly the non-read operations', () => {
test('coverage sweep: the set is non-empty and matches the registry size class', () => {
expect(NON_IDEMPOTENT_OPERATIONS.size).toBe(26);
});

test('every non-idempotent path is registered and is not a read', () => {
const meta = altovizEndpointMeta as Record<string, { riskLevel: string }>;
for (const path of NON_IDEMPOTENT_OPERATIONS) {
expect(meta).toHaveProperty([path]);
expect(meta[path]?.riskLevel).not.toBe('read');
}
});

test('every non-read operation is in the non-idempotent set - nothing slips through silently', () => {
const nonRead = Object.entries(altovizEndpointMeta)
.filter(([, m]) => m.riskLevel !== 'read')
.map(([path]) => path);
expect(nonRead.length).toBe(26);
expect([...nonRead].sort()).toEqual([...NON_IDEMPOTENT_OPERATIONS].sort());
});

test('isNonIdempotent agrees with the set', () => {
expect(isNonIdempotent('customers.create')).toBe(true);
expect(isNonIdempotent('customers.get')).toBe(false);
expect(isNonIdempotent('not.a.real.operation')).toBe(false);
});
});

describe('the UNREGISTER_WEBHOOK guard', () => {
const schema = AltovizEndpointInputSchemas.webhookSubscriptionsUnregister;

test('rejects a call with neither id nor url', () => {
expect(schema.safeParse({}).success).toBe(false);
});

test('accepts a call with only webhookId', () => {
expect(schema.safeParse({ webhookId: 1 }).success).toBe(true);
});

test('accepts a call with only url', () => {
expect(schema.safeParse({ url: 'https://example.com/wh' }).success).toBe(
true,
);
});

test('rejects a call with both id and url', () => {
expect(
schema.safeParse({ webhookId: 1, url: 'https://example.com/wh' }).success,
).toBe(false);
});
});

describe('documented input constraints', () => {
const listSchema = AltovizEndpointInputSchemas.customersList;
const createInvoiceSchema = AltovizEndpointInputSchemas.saleInvoicesCreate;

test('accepts page sizes from 1 through 100 only', () => {
expect(listSchema.safeParse({ pageSize: 1 }).success).toBe(true);
expect(listSchema.safeParse({ pageSize: 100 }).success).toBe(true);
expect(listSchema.safeParse({ pageSize: 0 }).success).toBe(false);
expect(listSchema.safeParse({ pageSize: 101 }).success).toBe(false);
});

test('requires YYYY-MM-DD calendar dates before making a request', () => {
const base = { customerId: 1, lines: [{ description: 'Service' }] };
expect(
createInvoiceSchema.safeParse({ ...base, date: '2026-08-15' }).success,
).toBe(true);
expect(
createInvoiceSchema.safeParse({ ...base, date: '15/08/2026' }).success,
).toBe(false);
});

test('products.find rejects an empty call the API would 400', () => {
const schema = AltovizEndpointInputSchemas.productsFind;
expect(schema.safeParse({}).success).toBe(false);
expect(schema.safeParse({ number: 'ABC' }).success).toBe(true);
});
});

describe('audit payload: deny-by-default allow-list', () => {
test('the allow-list admits no field name that looks like personal or financial content', () => {
const forbidden = [
'email',
'phone',
'address',
'name',
'note',
'description',
'subject',
'amount',
'price',
'quantity',
'iban',
'siret',
'secret',
'signature',
];
const hits: string[] = [];
for (const field of ALLOWED_FIELDS) {
const lower = field.toLowerCase();
for (const stem of forbidden) {
if (lower.includes(stem)) hits.push(`${field}~${stem}`);
}
}
expect(hits).toEqual([]);
});

test('an allowed field is recorded by value', () => {
const payload = auditPayload({ customerId: 42, companyName: 'Acme Corp' });
expect(payload.customerId).toBe(42);
});

test('a not-allowed field is recorded by name only, never by value', () => {
const payload = auditPayload({
customerId: 42,
companyName: 'Acme Corp',
email: 'a@example.com',
});
expect(payload).not.toHaveProperty('companyName');
expect(payload).not.toHaveProperty('email');
expect(payload.fields).toEqual(
expect.arrayContaining(['companyName', 'email', 'customerId']),
);
});

test('free-text search query is recorded by name only, never by value', () => {
const payload = auditPayload({ pageIndex: 1, query: 'jane@example.com' });
expect(payload).not.toHaveProperty('query');
expect(payload.pageIndex).toBe(1);
expect(payload.fields).toEqual(expect.arrayContaining(['query']));
});

test('orderBy is recorded by name only, never by value', () => {
const payload = auditPayload({
pageIndex: 1,
orderBy: 'email,iban,siret',
});
expect(payload).not.toHaveProperty('orderBy');
expect(payload.pageIndex).toBe(1);
expect(payload.fields).toEqual(expect.arrayContaining(['orderBy']));
});

test('caller-chosen identifiers are recorded by name only, never by value', () => {
const payload = auditPayload({
customerId: 42,
internalId: 'ssn-shaped',
number: 'FR-iban-lookalike',
});
expect(payload.customerId).toBe(42);
expect(payload).not.toHaveProperty('internalId');
expect(payload).not.toHaveProperty('number');
expect(payload.fields).toEqual(
expect.arrayContaining(['internalId', 'number']),
);
});

test('undefined fields are not recorded at all, not even by name', () => {
const payload = auditPayload({ customerId: 42, email: undefined });
expect(payload.fields).not.toContain('email');
});

test('extra fields passed by the endpoint author bypass the allow-list (they are not raw caller input)', () => {
const payload = auditPayload({}, { linesCount: 3 });
expect(payload.linesCount).toBe(3);
});
});
Loading
Loading