Skip to content

Commit 7c16585

Browse files
committed
wip(spec): one walk judges a connector entry's URLs at the write door and on the read
The write door's refinement and the read redactor now run the same traversal (findConnectorUrlCredentials); the redactor maps each URL it returns to the position it can address. Nested-key test assertions pin the issue shape instead of message wording; the dogfood pins that a row stored with a credential part in a providerConfig URL keeps dispatching with its stored URL. Claude-Session: https://claude.ai/code/session_01Q4EjjP1K353tLKWRMajLsE Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9880548 commit 7c16585

9 files changed

Lines changed: 187 additions & 93 deletions

‎.changeset/connector-entry-nested-undeclared-key-refused.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Metadata-protocol: narrowed
1313

1414
- **Before.** The entry refused an undeclared top-level key, but its two nested shapes were plain objects: an undeclared key inside `retryConfig` or inside an `actions` element parsed green and meant nothing to the runtime.
1515
- **Now.** Each is refused by name, in one `unrecognized_keys` issue located at the container (`retryConfig`, `actions.N`) that lists every undeclared key; at the save door `422 INVALID_METADATA`, and nothing is stored. An execution binding on an action (`method`, `path`, `url`) is refused the same way: an action carries none (ADR-0097 §5).
16-
- **Unchanged.** The published open shapes — `ConnectorSchema`, `RetryConfigSchema`, `ConnectorActionSchema` — keep their posture: the def a plugin hands to `registerConnector`, the actions a provider derives, and the retry policy the runtime parses at materialization. A row stored before this refusal keeps working: the read withholds the undeclared key, and a save of the served form keeps it at rest.
16+
- **Unchanged.** The published open shapes — `ConnectorSchema`, `RetryConfigSchema`, `ConnectorActionSchema` — keep their posture: the def a plugin hands to `registerConnector`, the actions a provider derives, and the retry policy the runtime parses at materialization. A row stored before this refusal keeps working: the runtime parses its policy with the open `RetryConfigSchema`, the read withholds the undeclared key, and a save of the served form keeps it at rest; a save that leaves `retryConfig` out removes it, the withheld keys with it.
1717

1818
## FROM → TO
1919

‎.changeset/connector-entry-url-credential-refused.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22
'@objectstack/spec': minor
33
---
44

5-
feat(spec)!: an authored connector URL holds no credential part; the connector read withholds the credential parts of an `auth` endpoint too
5+
feat(spec)!: an authored connector URL holds no credential part, and the connector read judges every `providerConfig` and `auth` URL by the same walk
66

77
Clause-②: no (narrowing)
88
Metadata-protocol: narrowed
99

1010
<!-- adr-0087: registered connector-entry-url-credential-refused -->
1111

12-
**BREAKING** accept-set narrowing on an authored connector entry (`DeclarativeConnectorEntrySchema`), at every door that parses it: `defineStack({ connectors })`, `os validate` / `os compile`, the metadata plugin's artifact load at boot and on reload, and the metadata save door `PUT /api/v1/meta/connector/:name`.
12+
**BREAKING** accept-set narrowing on an authored connector instance (`DeclarativeConnectorEntrySchema`), at every door that runs its refinement: `defineStack({ connectors })`, `os validate` / `os compile`, the metadata plugin's artifact load at boot and on reload, and the metadata save door `PUT /api/v1/meta/connector/:name`.
1313

1414
- **Before.** A URL under `providerConfig` or `auth` parsed green whatever it held.
15-
- **Now.** A URL holding a userinfo (`user@` or `user:password@` before the host) or a credential query parameter with a value (`api_key`, `token`, `access_token`, `key`, `secret`, `signature` and the rest of the connector redactor's list, matched case-insensitively on the decoded name, plus the instance's own `auth.paramName`) is refused: one issue per URL, located at the URL (`providerConfig.baseUrl`, `providerConfig.transport.url`, `providerConfig.spec`, `auth.tokenUrl`, `auth.authorizationUrl`, `auth.resource`, and any other URL at any depth under `providerConfig`, array elements included), naming the parts it holds and prescribing `auth: { type, credentialRef }`; at the save door `422 INVALID_METADATA`, and nothing is stored. There is no rule per provider: a URL is recognised by its value.
16-
- **One judgement, both doors.** The write door and the read redactor share one definition of a URL credential part, so the door refuses exactly what the read withholds. A URL inside a header or environment map (`providerConfig.headers`, `defaultHeaders`, `transport.headers`, `transport.env`) is judged by neither: the read withholds those maps whole.
17-
- **Read half.** The built-in `connector` redactor now also rewrites the credential parts out of the `auth` endpoints (`tokenUrl`, `authorizationUrl`, `resource`), the rest of each URL served byte for byte and the position named in `redactedKeys`, as it already did under `providerConfig`.
18-
- **Unchanged.** `ConnectorSchema` — the def a plugin hands to `registerConnector` — keeps its posture. A stored row is never re-judged at materialization, so a connector stored before this refusal keeps dispatching; a save of its served form keeps the stored URL (the metadata protocol's carry-forward), and an edit of the served URL stores exactly the edit.
15+
- **Now.** A URL holding a userinfo (`user@` or `user:password@` before the host) or a credential query parameter with a value (`api_key`, `token`, `access_token`, `key`, `secret`, `signature` and the rest of the connector redactor's list, matched case-insensitively on the decoded name, plus the instance's own `auth.paramName`) is refused: one issue per URL, located at the URL (`providerConfig.baseUrl`, `providerConfig.transport.url`, `providerConfig.spec`, `auth.tokenUrl`, `auth.authorizationUrl`, `auth.resource`, and any other URL at any depth under `providerConfig`, array elements included), naming the parts it holds — never the URL — and prescribing `auth: { type, credentialRef }`; at the save door `422 INVALID_METADATA`, and nothing is stored. There is no rule per provider: a URL is recognised by its value.
16+
- **One judgement, one walk, both doors.** The write door and the read redactor run one walk over an entry's URLs with one definition of a credential part, so the door refuses exactly the URLs the read rewrites or withholds. A URL inside a header or environment map (`providerConfig.headers`, `defaultHeaders`, `transport.headers`, `transport.env`) is judged by neither: the read withholds those maps whole.
17+
- **Read.** The built-in `connector` redactor rewrites the credential parts out of every URL that walk returns, the `auth` endpoints (`tokenUrl`, `authorizationUrl`, `resource`) as well as `providerConfig`, the rest of each URL served byte for byte and the position named in `redactedKeys`.
18+
- **Unchanged.** `ConnectorSchema` — the def a plugin hands to `registerConnector` — keeps its posture. The runtime materializes a stored row as it is stored and never re-judges it, so a connector stored before this refusal keeps dispatching with its stored URL; a save of its served form keeps the stored URL (the metadata protocol's carry-forward), and an edit of the served URL stores exactly the edit.
1919

2020
## FROM → TO
2121

‎packages/qa/dogfood/test/connector-meta-door-url-and-nested-keys.dogfood.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@
2020
// row is never touched.
2121
// - CARRY-FORWARD: a save of the served form keeps the stored values; an
2222
// author's own edit of a served URL is stored as the author wrote it; a
23-
// `retryConfig` the author removes is removed with its stored keys.
23+
// `retryConfig` the author removes is removed with its stored keys. A row
24+
// stored with a credential part in a `providerConfig` URL keeps
25+
// dispatching: the runtime materializes the stored row as it is, never
26+
// re-judged by the entry's refinement.
2427
//
2528
// Every credential below is an obviously-fake placeholder, and every assertion
2629
// on one is its absence from what a door served or stored, or its presence at
@@ -40,6 +43,7 @@ const PLACEHOLDERS = {
4043
urlQuery: 'TEST_PLACEHOLDER_CUN_URL_QUERY',
4144
nested: 'TEST_PLACEHOLDER_CUN_NESTED',
4245
authEndpoint: 'TEST_PLACEHOLDER_CUN_AUTH_ENDPOINT',
46+
legacyQuery: 'TEST_PLACEHOLDER_CUN_LEGACY_QUERY',
4347
resolvedRef: 'TEST_PLACEHOLDER_CUN_RESOLVED_REFERENCE',
4448
} as const;
4549
const NEVER_SERVED = Object.values(PLACEHOLDERS).filter((p) => p !== PLACEHOLDERS.resolvedRef);
@@ -51,6 +55,7 @@ const DESCRIPTOR = 'cun_descriptor';
5155
const EXISTING = 'cun_existing';
5256
const OAUTH_ROW = 'cun_oauth_stored';
5357
const RETRY_ROW = 'cun_retry_stored';
58+
const LEGACY_ROW = 'cun_legacy_url_stored';
5459

5560
const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.records) ? r.records : Array.isArray(r?.value) ? r.value : []);
5661
const bodyOf = (row: any): Record<string, any> =>
@@ -179,6 +184,12 @@ describe('connector metadata doors: an authored connector keeps no credential in
179184
instance(RETRY_ROW, { retryConfig: { maxAttempts: 2 } }),
180185
instance(RETRY_ROW, { retryConfig: { maxAttempts: 2, secret: PLACEHOLDERS.nested } }),
181186
);
187+
// Saved disabled, so nothing materializes before the seeded form is the row.
188+
await seedOver(
189+
LEGACY_ROW,
190+
instance(LEGACY_ROW, { enabled: false }),
191+
instance(LEGACY_ROW, { providerConfig: { baseUrl: `${upstreamUrl}/v1?region=eu&token=${PLACEHOLDERS.legacyQuery}` } }),
192+
);
182193
}, 180_000);
183194

184195
afterAll(async () => {
@@ -331,5 +342,29 @@ describe('connector metadata doors: an authored connector keeps no credential in
331342
expect(cleared.status, await cleared.clone().text()).toBe(200);
332343
expect(bodyOf((await stored(RETRY_ROW))[0])).not.toHaveProperty('retryConfig');
333344
});
345+
346+
it('a row stored with a credential part in its URL keeps dispatching: served without it, saved keeping it, materialized as stored', async () => {
347+
const { text, item } = await read(member, LEGACY_ROW);
348+
expect(holdsAPlaceholder(text)).toBe(false);
349+
expect(item.providerConfig).toEqual({ baseUrl: `${upstreamUrl}/v1?region=eu` });
350+
351+
const served = authorable((await read(admin, LEGACY_ROW)).item);
352+
const res = await stack.apiAs(admin, 'PUT', `/meta/connector/${LEGACY_ROW}`, { ...served, label: 'CUN legacy (edited)' });
353+
expect(res.status, await res.clone().text()).toBe(200);
354+
const atRest = bodyOf((await stored(LEGACY_ROW))[0]);
355+
expect(atRest.label).toBe('CUN legacy (edited)');
356+
expect(atRest.providerConfig.baseUrl).toBe(`${upstreamUrl}/v1?region=eu&token=${PLACEHOLDERS.legacyQuery}`);
357+
358+
await waitReady(LEGACY_ROW);
359+
const handler = automation.resolveConnectorAction(LEGACY_ROW, 'request');
360+
expect(handler, `${LEGACY_ROW} is materialized with its request action`).toBeTypeOf('function');
361+
const before = received.length;
362+
const out = await handler({ method: 'GET', path: '/probe' }, {});
363+
expect(out?.status, JSON.stringify(out)).toBe(200);
364+
expect(received.length).toBe(before + 1);
365+
const sent = new URL(received[received.length - 1]!, 'http://upstream.invalid');
366+
expect(sent.pathname).toBe('/v1/probe');
367+
expect(sent.searchParams.get('token'), 'the stored URL is the one dispatched').toBe(PLACEHOLDERS.legacyQuery);
368+
});
334369
});
335370
});

‎packages/spec/src/integration/connector-credential-redaction.ts‎

Lines changed: 26 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,11 @@
6161
* an OBJECT depth of `providerConfig`; and the endpoints an instance-auth
6262
* kind declares (`auth.tokenUrl`, `auth.authorizationUrl`, `auth.resource`)
6363
* and any URL a kind declares later. A string is judged when it starts
64-
* with `scheme://`. What a credential part is lives in ONE place,
64+
* with `scheme://`. What a credential part is, and the walk that finds
65+
* every URL holding one, live in ONE place,
6566
* `./connector-url-credentials.ts`, which the write door's refinement
66-
* judges by too: an authored URL holding one is refused, so only a row
67-
* stored before that refusal can carry one to this read.
67+
* runs too: an authored URL holding one is refused, so only a row stored
68+
* before that refusal can carry one to this read.
6869
* 6. **An array under `providerConfig` that holds such a URL, WHOLE**, and
6970
* **a key under `providerConfig` whose own name carries a dot that holds
7071
* such a URL at any depth, WHOLE.** The carry-forward cannot address an
@@ -132,10 +133,10 @@ import { redactUrlCredentialQueryParams } from '../data/datasource-credential-re
132133
import {
133134
CONNECTOR_CREDENTIAL_MAP_PATHS,
134135
CONNECTOR_CREDENTIAL_URL_QUERY_PARAM_NAMES,
135-
CONNECTOR_URL_ROOTS,
136136
URL_USERINFO_RE,
137137
connectorCredentialQueryParamsOf,
138-
connectorUrlCredentialPartsOf,
138+
connectorUrlCredentialPositionOf,
139+
findConnectorUrlCredentials,
139140
} from './connector-url-credentials';
140141
import { objectShapeOf, wrapperChainOf, zodDefOf } from '../kernel/metadata-credential-fields';
141142
import type { MetadataRedactionResult } from '../kernel/metadata-type-redaction';
@@ -363,56 +364,34 @@ function withValueAt(item: Record<string, unknown>, path: readonly string[], val
363364
return { ...item, [head]: withValueAt(item[head] as Record<string, unknown>, rest, value) };
364365
}
365366

366-
/** Whether `value` is a URL holding a credential part — the parts {@link redactConnectorUrl} removes. */
367-
function isCredentialUrl(value: string, params: readonly string[]): boolean {
368-
return connectorUrlCredentialPartsOf(value, params) !== undefined;
369-
}
370-
371-
/** Whether `value` holds, at any depth, a URL {@link isCredentialUrl} judges (item 6). */
372-
function holdsCredentialUrl(value: unknown, params: readonly string[]): boolean {
373-
if (typeof value === 'string') return isCredentialUrl(value, params);
374-
if (Array.isArray(value)) return value.some((element) => holdsCredentialUrl(element, params));
375-
if (isPlainRecord(value)) return Object.values(value).some((child) => holdsCredentialUrl(child, params));
376-
return false;
377-
}
378-
379367
/**
380-
* Items 5 and 6: every URL under `providerConfig` and `auth`
381-
* ({@link CONNECTOR_URL_ROOTS}), at object depth, whose credential parts
382-
* {@link redactConnectorUrl} removes — the path and the rewritten value — and
383-
* every array there holding such a URL, withheld whole (`value` absent).
368+
* Items 5 and 6: every URL the write door's own walk returns
369+
* ({@link findConnectorUrlCredentials} — the one traversal both doors run), at
370+
* the position {@link connectorUrlCredentialPositionOf} names. A URL reached
371+
* through object keys alone is rewritten in place — the path and the value
372+
* {@link redactConnectorUrl} leaves. An array holding such a URL, and a key
373+
* whose own name carries a dot holding one at any depth, cannot be addressed
374+
* part for part, so each is withheld WHOLE (`value` absent), once however many
375+
* URLs it holds: fail closed, and the carry-forward keeps the stored value at
376+
* rest by the whole-string fallback. Item 5's "avoid silent deletion" yields to
377+
* item 7's fail-closed there.
384378
*/
385379
function credentialUrlRewritesOf(
386380
item: Record<string, unknown>,
387381
): Array<{ path: string[]; value?: string }> {
388382
const rewrites: Array<{ path: string[]; value?: string }> = [];
383+
const withheld = new Set<string>();
389384
const params = connectorCredentialQueryParamsOf(item);
390-
const walk = (node: Record<string, unknown>, prefix: readonly string[]): void => {
391-
for (const [key, value] of Object.entries(node)) {
392-
const path = [...prefix, key];
393-
// A key whose own name carries a dot cannot be addressed segment by
394-
// segment (its dotted name is indistinguishable from a nested path once
395-
// `redactedKeys` joins on dots), so it is never rewritten in place or
396-
// descended into. Fail closed instead: if it holds a credential URL at
397-
// any depth, withhold the key WHOLE — the carry-forward keeps the stored
398-
// value at rest by the whole-string fallback. Item 5's "avoid silent
399-
// deletion" yields to item 7's fail-closed here.
400-
if (key.includes('.')) {
401-
if (holdsCredentialUrl(value, params)) rewrites.push({ path });
402-
continue;
403-
}
404-
if (typeof value === 'string') {
405-
if (isCredentialUrl(value, params)) rewrites.push({ path, value: redactConnectorUrl(value, params) });
406-
} else if (Array.isArray(value)) {
407-
if (holdsCredentialUrl(value, params)) rewrites.push({ path });
408-
} else if (isPlainRecord(value)) {
409-
walk(value, path);
410-
}
385+
for (const found of findConnectorUrlCredentials(item)) {
386+
const position = connectorUrlCredentialPositionOf(found.path);
387+
if (position.rewrite) {
388+
rewrites.push({ path: position.path, value: redactConnectorUrl(found.url, params) });
389+
continue;
411390
}
412-
};
413-
for (const root of CONNECTOR_URL_ROOTS) {
414-
const node = item[root];
415-
if (isPlainRecord(node)) walk(node, [root]);
391+
const key = JSON.stringify(position.path);
392+
if (withheld.has(key)) continue;
393+
withheld.add(key);
394+
rewrites.push({ path: position.path });
416395
}
417396
return rewrites;
418397
}

‎packages/spec/src/integration/connector-entry-nested-keys.test.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
// never echo it.
1515

1616
import { describe, it, expect } from 'vitest';
17+
import { ZodError } from 'zod';
1718
import {
1819
ConnectorActionSchema,
1920
ConnectorSchema,
@@ -64,7 +65,6 @@ describe('an authored connector entry refuses a key its nested shapes do not dec
6465
] as const)('`retryConfig` with %s is refused at `retryConfig`', (_label, extra, keys) => {
6566
const { located, message } = refusal({ ...INSTANCE, retryConfig: { ...RETRY, ...extra } });
6667
expect(located).toEqual(['unrecognized_keys', 'retryConfig', keys]);
67-
expect(message).toContain("connector entry's `retryConfig`");
6868
expect(message).not.toContain(PLACEHOLDER);
6969
});
7070

@@ -74,7 +74,6 @@ describe('an authored connector entry refuses a key its nested shapes do not dec
7474
] as const)('an `actions` element with %s is refused at that element', (_label, extra, keys) => {
7575
const { located, message } = refusal({ ...DESCRIPTOR, actions: [{ key: 'list', label: 'List' }, { ...ACTION, ...extra }] });
7676
expect(located).toEqual(['unrecognized_keys', 'actions.1', keys]);
77-
expect(message).toContain('this connector action');
7877
expect(message).not.toContain(PLACEHOLDER);
7978
});
8079

@@ -88,7 +87,15 @@ describe('an authored connector entry refuses a key its nested shapes do not dec
8887
});
8988

9089
it('`defineConnector()` refuses it too, and accepts the declared keys', () => {
91-
expect(() => defineConnector({ ...DESCRIPTOR, actions: [{ ...ACTION, token: PLACEHOLDER } as never] })).toThrow(/this connector action/);
90+
let thrown: unknown;
91+
try {
92+
defineConnector({ ...DESCRIPTOR, actions: [{ ...ACTION, token: PLACEHOLDER } as never] });
93+
} catch (error) {
94+
thrown = error;
95+
}
96+
expect(thrown, 'defineConnector must refuse the undeclared action key').toBeInstanceOf(ZodError);
97+
expect((thrown as ZodError).issues.map((issue) => [issue.code, issue.path.join('.'), (issue as { keys?: unknown }).keys]))
98+
.toEqual([['unrecognized_keys', 'actions.0', ['token']]]);
9299
expect(() => defineConnector({ ...DESCRIPTOR, actions: [ACTION] })).not.toThrow();
93100
});
94101

‎packages/spec/src/integration/connector-entry-url-credentials.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,5 +185,42 @@ describe('an authored connector URL holds no credential part', () => {
185185
expect(refused, `${url}: refused ⇔ rewritten`).toBe(rewritten);
186186
}
187187
});
188+
189+
it('at every depth, one walk: each refused URL is withheld by the read, at the position it can address', () => {
190+
const entry = {
191+
...rest('https://api.vendor.example.com'),
192+
providerConfig: {
193+
baseUrl: `https://u:${PLACEHOLDER}@api.vendor.example.com`,
194+
mirrors: [
195+
'https://eu.vendor.example.com',
196+
`https://us.vendor.example.com?sig=${PLACEHOLDER}`,
197+
`https://ap.vendor.example.com?token=${PLACEHOLDER}`,
198+
],
199+
'x.callback': { url: `https://hooks.vendor.example.com?secret=${PLACEHOLDER}` },
200+
nested: { deeper: { url: `https://u:${PLACEHOLDER}@deep.vendor.example.com` }, plain: 'https://plain.vendor.example.com' },
201+
headers: { Referer: `https://u:${PLACEHOLDER}@app.example.com` },
202+
},
203+
};
204+
expect(refusals(entry).located.map(([, path]) => path)).toEqual([
205+
'providerConfig.baseUrl',
206+
'providerConfig.mirrors.1',
207+
'providerConfig.mirrors.2',
208+
'providerConfig.x.callback.url',
209+
'providerConfig.nested.deeper.url',
210+
]);
211+
const { item: served, redactedKeys } = redactConnectorItem(entry);
212+
// An array and a dotted key are withheld whole, once; the header map is
213+
// withheld whole by its own rule (item 3), the one position the write
214+
// door leaves to the map's own rules.
215+
expect(redactedKeys).toEqual([
216+
'providerConfig.baseUrl',
217+
'providerConfig.headers',
218+
'providerConfig.mirrors',
219+
'providerConfig.nested.deeper.url',
220+
'providerConfig.x.callback',
221+
]);
222+
expect(JSON.stringify(served)).not.toContain(PLACEHOLDER);
223+
expect((served.providerConfig as Record<string, any>).nested.plain).toBe('https://plain.vendor.example.com');
224+
});
188225
});
189226
});

0 commit comments

Comments
 (0)