-
Notifications
You must be signed in to change notification settings - Fork 296
feat(altoviz): add altoviz pulgin integration #782
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+8,369
−0
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cca0cc3
feat(altoviz): initialize Altoviz plugin with core schema, routing, a…
abhishek-2k23 d130ff8
feat(altoviz): enhance API error handling and improve schema
abhishek-2k23 3df2148
test(altoviz): update URL validation to compare origins instead of ba…
abhishek-2k23 6c6d6fe
feat(altoviz): add validation to reject unsafe path characters in req…
abhishek-2k23 95430f1
Merge branch 'main' of https://github.com/abhishek-2k23/corsair into …
abhishek-2k23 bab2ae8
fix(altoviz): redact search query in logs, fix paging + placeholders
yuvrxj-afk b132139
Merge branch 'main' into feat/altoviz
Dhirenderchoudhary 61e2a78
fix(altoviz): persist official OpenAPI field names
Dhirenderchoudhary dba20fc
fix(altoviz): pass path ids via templates
Dhirenderchoudhary 48371b8
fix(altoviz): redact ids and stop 429 write retries
Dhirenderchoudhary 0b10866
Merge branch 'main' into feat/altoviz
Dhirenderchoudhary 3aa53e3
Update packages/altoviz/endpoints/logging.ts
Dhirenderchoudhary d2acd14
fix(altoviz): redact orderBy and name upload files
Dhirenderchoudhary bdf9e46
Merge remote feat/altoviz
Dhirenderchoudhary 10a13b7
fix(altoviz): retry throttled GETs in the client
Dhirenderchoudhary File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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', | ||
| }, | ||
| }; | ||
|
|
||
| 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'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.