Skip to content
Closed
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
128 changes: 128 additions & 0 deletions clients/typescript/tests/breg-access-reason.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { generate } from '../generate.ts'
import { Transport } from '../core.ts'

test('BReg generated inputs carry the Batch and ingestion reason in the request header', async t => {
const batchPath = '/v1/records/entries:batch'
const listPath = '/v1/records/entries/ingestion-runs'
const run = '00000000-0000-4000-8000-000000000001'
const runPath = listPath + '/{run_id}'
const chunkPath = runPath + '/chunks'
const receiptPath = chunkPath + '/{chunk_index}/receipt'
const cancelPath = runPath + '/cancel'
const reason = {
in: 'header', name: 'Registry-Access-Reason', required: false,
schema: { type: 'string', minLength: 1, maxLength: 684, pattern: '^[A-Za-z0-9_-]+$' },
}
const responses = {
200: { description: 'Accepted', content: { 'application/json': { schema: { type: 'string' } } } },
}
const bodySchema = { required: true, content: {
'application/json': { schema: { type: 'object', properties: {
items: { type: 'array', items: { type: 'string' } },
}, required: ['items'] } },
} }
const requiredReason = { ...reason, required: true }
const runParameter = { in: 'path', name: 'run_id', required: true, schema: { type: 'string', format: 'uuid' } }
const chunkParameter = { in: 'path', name: 'chunk_index', required: true, schema: { type: 'integer', minimum: 0 } }
const document = {
openapi: '3.1.0',
info: { title: 'Reason fixture' },
paths: {
[batchPath]: { post: {
operationId: 'batchEntries',
'x-registry-operation': 'batch',
parameters: [reason, {
in: 'header', name: 'Idempotency-Key', required: true,
schema: { type: 'string', minLength: 1, maxLength: 256 },
}],
requestBody: {
required: true,
content: { 'application/json': { schema: {
type: 'object', required: ['items'],
properties: { items: { type: 'array', items: { type: 'string' } } },
} } },
},
responses,
} },
[listPath]: {
get: { operationId: 'listEntryRuns', parameters: [requiredReason], responses },
post: { operationId: 'createEntryRun', parameters: [requiredReason], requestBody: bodySchema, responses },
},
[runPath]: { get: {
operationId: 'readEntryRun', parameters: [runParameter, requiredReason], responses,
} },
[chunkPath]: { post: {
operationId: 'submitEntryChunk', parameters: [runParameter, requiredReason], requestBody: bodySchema, responses,
} },
[receiptPath]: { get: {
operationId: 'readEntryReceipt', parameters: [runParameter, chunkParameter, requiredReason], responses,
} },
[cancelPath]: { post: {
operationId: 'cancelEntryRun', parameters: [runParameter, requiredReason], responses,
} },
},
}
const output = generate(JSON.stringify(document), {
breg: true,
coreImport: fileURLToPath(new URL('../core.ts', import.meta.url)),
schemaImport: fileURLToPath(new URL('../schema.ts', import.meta.url)),
})
assert.match(output, /"batchEntries": \{ input:.*headers\?: \{ "Registry-Access-Reason"\?: \(string\)/u)
const ingestion = [
'listEntryRuns', 'createEntryRun', 'readEntryRun',
'submitEntryChunk', 'readEntryReceipt', 'cancelEntryRun',
] as const
for (const operation of ingestion) {
const declaration = output.split('\n').find(line => line.includes(`"${operation}": { input:`))
assert.match(declaration ?? '', /headers: \{ "Registry-Access-Reason": \(string\)/u)
}

const dir = mkdtempSync(join(tmpdir(), 'breg-access-reason-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const file = join(dir, 'client.ts')
writeFileSync(file, output)
const { Client } = await import(file)
const seen: Array<{ url: string; headers: Headers; body: BodyInit | null | undefined }> = []
const client = new Client(new Transport({
baseUrl: 'https://registry.example/tenant',
token: () => 'fixture',
fetch: async (url, init) => {
seen.push({ url: String(url), headers: new Headers(init?.headers), body: init?.body })
return Response.json('accepted')
},
}))
const header = 'Registry-Access-Reason'
const encoded = Buffer.from('Review 🧭', 'utf8').toString('base64url')
const body = { items: ['entry'] }
await client.call('batchEntries', { body, idempotencyKey: 'fixture-first', headers: { [header]: encoded } })
await client.call('batchEntries', { body, idempotencyKey: 'fixture-second' })
const headers = { [header]: encoded }
const path = { run_id: run }
await client.call('listEntryRuns', { headers })
await client.call('createEntryRun', { headers, body })
await client.call('readEntryRun', { headers, path })
await client.call('submitEntryChunk', { headers, path, body })
await client.call('readEntryReceipt', { headers, path: { ...path, chunk_index: 0 } })
await client.call('cancelEntryRun', { headers, path })

assert.deepEqual(seen.map(request => request.headers.get(header)), [
encoded, null, encoded, encoded, encoded, encoded, encoded, encoded,
])
assert.deepEqual(seen.map(request => new URL(request.url).pathname), [
'/tenant' + batchPath, '/tenant' + batchPath, '/tenant' + listPath, '/tenant' + listPath,
'/tenant' + runPath.replace('{run_id}', run),
'/tenant' + chunkPath.replace('{run_id}', run),
'/tenant' + receiptPath.replace('{run_id}', run).replace('{chunk_index}', '0'),
'/tenant' + cancelPath.replace('{run_id}', run),
])
assert.ok(seen.every(request => new URL(request.url).search === ''))
for (const request of seen.filter(request => request.body !== undefined)) {
assert.deepEqual(JSON.parse(String(request.body)), body)
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,15 @@ test('native JSON methods preserve values, metadata, cursors and mutation precon
assert.equal(batchDescriptor.request.allowPatch,true);
assert.equal(contract.operations.find(op=>op.kind === 'tombstone').request.allowCreate,null);
const batchResult = await client.batchRecords(batch,{items:[{operation:'create',data:{wide:1}}],
changeContext:{kind:'correction',reasonCode:'verified-source',reasonText:'Correct source',sourceReferences:['case:1']}},'batch-one');
changeContext:{kind:'correction',reasonCode:'verified-source',reasonText:'Correct source',sourceReferences:['case:1']}},'batch-one','Review é');
assert.equal(requests.at(-1).headers['registry-access-reason'], 'UmV2aWV3IMOp');
assert.equal(batchResult.value.results[0].recordId,id);
assert.equal(batchResult.value.results[0].revisionIdentifier,'2');
assert.equal(batchResult.value.results[0].domainData.wide,9007199254740992);
assert.match(requests.at(-1).body,/"reasonCode":"verified-source"/);
const batchPatch = await client.batchRecords(batch,{items:[{operation:'patch',recordId:id,
ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',field:'wide',value:2}]}]},'batch-patch');
assert.equal(requests.at(-1).headers['registry-access-reason'], undefined);
assert.equal(batchPatch.value.results[0].operation,'patch');
assert.deepEqual(JSON.parse(requests.at(-1).body),{items:[{operation:'patch',recordId:id,
ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',path:'/data/wide',value:2}]}]});
Expand All @@ -221,7 +223,8 @@ test('native JSON methods preserve values, metadata, cursors and mutation precon
await assert.rejects(client.batchRecords(batch,{items:[{operation:'patch',recordIdentifier:id,
ifMatch:'"breg-record-000000000001"',patch:[{op:'replace',field:'wide',value:2}]}]},'legacy-record-identifier'),
error=>error.kind === 'invalid-request');
const exactBatch = await client.batchRecordsJson(batch,'{"items":[{"operation":"create","data":{"wide":9007199254740992}}]}','exact-batch');
const exactBatch = await client.batchRecordsJson(batch,'{"items":[{"operation":"create","data":{"wide":9007199254740992}}]}','exact-batch','Review é');
assert.equal(requests.at(-1).headers['registry-access-reason'], 'UmV2aWV3IMOp');
assert.match(exactBatch.valueJson,/"revisionIdentifier":"9007199254740992"/);
assert.match(requests.at(-1).body,/"wide":9007199254740992/);
const tombstone = contract.selectTombstone('item',profile);
Expand Down
52 changes: 51 additions & 1 deletion crates/registry-breg-client-node/__test__/ingestion.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ before(async () => {
const body = Buffer.concat(chunks).toString();
// The fixture mounts the API under a /tenant base path; recorded URLs
// are relative to that base, like the assertions that read them.
seen.push({ url: request.url.replace(/^\/tenant/, ''), method: request.method, contentType: request.headers['content-type'], body });
seen.push({ url: request.url.replace(/^\/tenant/, ''), method: request.method, contentType: request.headers['content-type'], accessReasons: request.headersDistinct['registry-access-reason'], body });
const path = request.url.split('?')[0];
const answer = (status, document) => {
response.setHeader('traceparent', TRACEPARENT);
Expand Down Expand Up @@ -342,3 +342,53 @@ test('ingestionChunkReceipt reads one retained receipt and reports an erased one
&& error.status === 410
));
});

test('each ingestion exchange sends only its explicit reason header', async () => {
const client = new BaseRegistryClient({ baseUrl });
const reason = ' Synthetic review é 🧭 ';
const encoded = Buffer.from(reason, 'utf8').toString('base64url');
const announcement = {
operation: 'create',
profileId: 'importer.v1',
packageRevision: 'revision-1',
schemaFingerprint: 'fingerprint-1',
inputDigest: INPUT_DIGEST,
inputLength: 4321,
itemCount: 10,
chunkCount: 3,
chunkAlgorithmVersion: 'greedy-canonical-http-batch-v1',
};
const chunk = encodeIngestionChunk(0, ITEMS, PREFIX_DIGEST);
await client.createIngestionRun('people', announcement, reason);
await client.listIngestionRuns('people', null, reason);
await client.readIngestionRun('people', RUN_ID, null, reason);
await client.submitIngestionChunk('people', RUN_ID, chunk, 'importer.v1', reason);
await client.ingestionChunkReceipt('people', RUN_ID, 0, 'importer.v1', reason);
await client.cancelIngestionRun('people', RUN_ID, null, reason);
for (const request of seen.slice(-6)) {
assert.deepEqual(request.accessReasons, [encoded]);
for (const canary of [reason, encoded]) {
assert.ok(!request.url.includes(canary));
assert.ok(!request.body.includes(canary));
}
}
await client.listIngestionRuns('people');
assert.equal(seen.at(-1).accessReasons, undefined);

const before = seen.length;
const invalid = 'synthetic\nprivate';
await assert.rejects(client.listIngestionRuns('people', null, invalid), (error) => (
error instanceof BaseRegistryClientError
&& error.kind === 'invalid-request'
&& !error.message.includes('private')
&& !error.message.includes(Buffer.from(invalid).toString('base64url'))
));
for (const malformed of ['canary\uD800', '\uDC00canary']) {
await assert.rejects(async () => client.listIngestionRuns('people', null, malformed), (error) => (
error instanceof BaseRegistryClientError
&& error.kind === 'invalid-request'
&& !error.message.includes('canary')
));
}
assert.equal(seen.length, before);
});
16 changes: 8 additions & 8 deletions crates/registry-breg-client-node/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1046,14 +1046,14 @@ export declare class BaseRegistryClient {
executeRecoveredCreate(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise<CompleteOutcome<RecordEnvelope>>
executeRecoveredCreateJson(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise<JsonOutcome>
patchRecord(binding: BRegPatchBinding, recordId: string, etag: string, operations: ReadonlyArray<PatchOperation | RemovePatchOperation>, idempotencyKey: string, format?: RecordFormat | null): Promise<CompleteOutcome<RecordEnvelope>>
batchRecords(binding: BRegBatchBinding, request: BRegBatchInput, idempotencyKey: string): Promise<CompleteOutcome<BRegBatchReceipt>>
batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string): Promise<JsonOutcome>
createIngestionRun(recordRoute: string, request: BRegIngestionRunInput): Promise<CompleteOutcome<BRegIngestionRun>>
listIngestionRuns(recordRoute: string, query?: BRegIngestionRunListInput | null): Promise<CompleteOutcome<BRegIngestionRunPage>>
readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null): Promise<CompleteOutcome<BRegIngestionRun>>
submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string): Promise<CompleteOutcome<BRegIngestionChunkSubmission>>
cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null): Promise<CompleteOutcome<BRegIngestionRun>>
ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: SafeInteger, profileId: string): Promise<CompleteOutcome<BRegIngestionChunkReceipt>>
batchRecords(binding: BRegBatchBinding, request: BRegBatchInput, idempotencyKey: string, accessReason?: string | null): Promise<CompleteOutcome<BRegBatchReceipt>>
batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string, accessReason?: string | null): Promise<JsonOutcome>
createIngestionRun(recordRoute: string, request: BRegIngestionRunInput, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionRun>>
listIngestionRuns(recordRoute: string, query?: BRegIngestionRunListInput | null, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionRunPage>>
readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionRun>>
submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionChunkSubmission>>
cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | null, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionRun>>
ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: SafeInteger, profileId: string, accessReason?: string | null): Promise<CompleteOutcome<BRegIngestionChunkReceipt>>
tombstoneRecord(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, format?: RecordFormat | null): Promise<CompleteOutcome<RecordEnvelope>>
tombstoneRecordJson(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, format?: RecordFormat | null): Promise<JsonOutcome>
getRecordJson(recordRoute: string, recordId: string, options?: RecordOptions | null, request?: ReadRequestOptions): Promise<JsonOutcome>
Expand Down
16 changes: 8 additions & 8 deletions crates/registry-breg-client-node/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,31 +122,31 @@ export declare class BaseRegistryClient {
* unknown is resent identically under the same key, at most
* `maximumMutationRetries` times.
*/
batchRecords(binding: BRegBatchBinding, request: any, idempotencyKey: string): Promise<CompleteOutcome>
batchRecords(binding: BRegBatchBinding, request: any, idempotencyKey: string, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/**
* Announce one whole input and open a durable ingestion run for it. The
* run request names the access profile, which the client selects for the
* exchange.
*/
createIngestionRun(recordRoute: string, request: any): Promise<CompleteOutcome>
createIngestionRun(recordRoute: string, request: any, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/** Read one bounded page of ingestion runs for one record route. */
listIngestionRuns(recordRoute: string, query?: any | undefined | null): Promise<CompleteOutcome>
listIngestionRuns(recordRoute: string, query?: any | undefined | null, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/** Read the current durable state of one ingestion run. */
readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null): Promise<CompleteOutcome>
readIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/**
* Submit one bounded chunk of an open ingestion run under the run's
* access profile. A resubmitted chunk replays its retained receipt
* instead of executing twice.
*/
submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string): Promise<CompleteOutcome>
submitIngestionChunk(recordRoute: string, runId: string, chunk: BRegIngestionChunk, profileId: string, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/** Cancel an open ingestion run. Committed chunks stay committed. */
cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null): Promise<CompleteOutcome>
cancelIngestionRun(recordRoute: string, runId: string, accessProfile?: string | undefined | null, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/**
* Read the retained receipt of one committed chunk under the run's
* access profile. An erased receipt answers with the
* `ingestion.receipt-erased` problem instead.
*/
ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: number, profileId: string): Promise<CompleteOutcome>
ingestionChunkReceipt(recordRoute: string, runId: string, chunkIndex: number, profileId: string, accessReason?: string | undefined | null): Promise<CompleteOutcome>
/** Tombstone one record against its current strong ETag. */
tombstoneRecord(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise<CompleteOutcome>
getRecordJson(recordRoute: string, recordId: string, options?: any | undefined | null, cancellation?: ReadCancellation | undefined | null): Promise<JsonOutcome>
Expand Down Expand Up @@ -183,7 +183,7 @@ export declare class BaseRegistryClient {
executeRecoveredCreateJson(binding: BRegCreateBinding, recovered: BRegRecoveredCreate): Promise<JsonOutcome>
patchRecordJson(binding: BRegPatchBinding, recordId: string, etag: string, operationsJson: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise<JsonOutcome>
/** Execute one metadata-selected atomic batch from exact JSON. */
batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string): Promise<JsonOutcome>
batchRecordsJson(binding: BRegBatchBinding, requestJson: string, idempotencyKey: string, accessReason?: string | undefined | null): Promise<JsonOutcome>
/** Tombstone one record and preserve exact response values. */
tombstoneRecordJson(binding: BRegTombstoneBinding, recordId: string, etag: string, idempotencyKey: string, formatValue?: string | undefined | null): Promise<JsonOutcome>
}
Expand Down
Loading
Loading