From 98dcde93b3b285c4e284dff7f94269d76a9eda6b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 19:58:42 +0000 Subject: [PATCH 1/4] Correct the advice on X-Requested-With for a cookie-session app: with it an ended session answers 403, not 401 Documentation only. The transport's comment advised the header so that the server would answer 401; a consumer who ended a real session saw a 401 without it and a 403 with it. An app sending the header needs unauthorizedStatuses [401, 403] and a session check in its hook. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 25 +++++++++++++++++++++++ README.md | 2 +- examples/09-browser-session.ts | 5 +++++ src/core/fetchTransport.ts | 36 ++++++++++++++++++++++++++++------ 4 files changed, 61 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ef2bba..d9a5b13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## Unreleased (to be 1.0.0-alpha.13) + +### Changed + +- **The advice on `X-Requested-With` for a cookie-session browser app + was wrong and is replaced** (documentation only; no behaviour + changes). `createFetchTransport`'s comment on `credentials` said to + send `X-Requested-With: XMLHttpRequest` "so the server answers 401 + rather than a login page". A browser-app consumer ended a real + session (one product release, OIDC sign-in) and saw the opposite + effect: without the header a 401, with it a 403, both with the same + `WWW-Authenticate: Bearer` challenge and body, neither a redirect. + Since `onUnauthorized` runs for `unauthorizedStatuses`, default + `[401]`, an app that followed the advice never had its hook called + when a session ended. Migration: if you send that header, set + `unauthorizedStatuses: [401, 403]` and have the hook check that the + session is really gone before it prompts (a one-row read with + `reauthorize: false`), because a 403 may also be a permission denial; + or stop sending the header. The built-in transport never sends it by + itself. A write refused with that 403 was not applied and landed once + when replayed, so what is known about `"retry-write"` extends to it. + Not checked: other releases, other ways of signing in, and whether a + 403 for a genuine permission denial carries the same challenge (so the + SDK still classifies every 403 as `kind: "forbidden"`). + ## 1.0.0-alpha.12 ### Breaking diff --git a/README.md b/README.md index d0c26bc..e947a3e 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `normalizeQuery(q)` - a query written with rest-1's spellings (`sel`, a textual `where`, comma-joined lists, a `"size,start"` page) as the `QueryBody` every read takes - Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded -- `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one +- `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once; an app that sends `X-Requested-With: XMLHttpRequest` gets a 403 for an ended session and needs `unauthorizedStatuses: [401, 403]`, see the option's comment), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline - Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. A guarded write (`sendGuarded`) is a write here too: it is never sent again by the client, because a second send of one that landed applies nothing and reports a conflict, which would tell you someone else changed the asset when the change was yours. When one gets no answer (`outcome: "unknown"`), read the asset again: you see your change or you do not, and the guard makes sending it again safe. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) - A config key that is not one the factory takes (`new AgilityApiClient`, `createFetchTransport`, `new FakeAgilityClient`) is refused at construction with a `UsageError` naming it, with the nearest known key when it looks like a typo. Nothing is ignored silently, and no value is repeated in the message. diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts index a542d2d..82ab2ab 100644 --- a/examples/09-browser-session.ts +++ b/examples/09-browser-session.ts @@ -37,6 +37,11 @@ async function signInAgain(): Promise { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/MyInstance", credentials: "include", // send the session cookie; no accessToken + // No `X-Requested-With` header here, so an ended session answers 401 and + // the hook below runs. An app that sends `X-Requested-With: + // XMLHttpRequest` was seen to get a 403 for an ended session instead: it + // adds `unauthorizedStatuses: [401, 403]`, and its hook first checks that + // the session is really gone, since a 403 may also be a permission denial. onUnauthorized: async ({ retryable }) => { if (!(await signInAgain())) return "fail"; // "retry" resends what is safe to send twice: a GET, a read. Never a diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index b27e562..bde84ab 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -43,9 +43,21 @@ export interface FetchTransportConfig { /** * fetch's credentials mode. A browser app on the instance's own origin * that authenticates with the session cookie sets "same-origin" or - * "include" (pair it with defaultHeaders { "X-Requested-With": - * "XMLHttpRequest" } so the server answers 401 rather than a login page). - * Left unset, fetch's default applies. + * "include". Left unset, fetch's default applies. + * + * Whether to also send `X-Requested-With: XMLHttpRequest` (through + * `defaultHeaders`; this transport never sends it by itself) decides + * which status an ended session answers with. A consumer saw, on one + * product release with OIDC sign-in, a session that had expired answer + * 401 without that header and 403 with it, both with the same + * `WWW-Authenticate: Bearer` challenge and the same body, and neither + * with a redirect to a login page. So: without the header, an ended + * session is a 401 and `onUnauthorized` runs by default; with it, set + * `unauthorizedStatuses: [401, 403]`, or the hook is never called. + * (Earlier releases of this comment advised the header "so the server + * answers 401 rather than a login page"; that is not what was seen.) + * Not checked: other releases, other ways of signing in, and whether a + * 403 for a genuine permission denial carries the same challenge. */ credentials?: RequestCredentials; /** @@ -65,7 +77,16 @@ export interface FetchTransportConfig { * again: it means "retry-write" is the answer that resumes it. */ onUnauthorized?: (context: UnauthorizedContext) => UnauthorizedDecision | Promise; - /** Which statuses call onUnauthorized. Default [401]; a cookie-session app may add 403. */ + /** + * Which statuses call onUnauthorized. Default [401]. An app that sends + * `X-Requested-With: XMLHttpRequest` needs [401, 403]: an ended session + * was seen to answer 403 to a request with that header (see + * `credentials`). A 403 is also what a permission denial may answer, + * and it is not known whether the response tells the two apart, so a + * hook called for a 403 should ask whether the session is still alive + * (a one-row read sent with `reauthorize: false`) before it prompts + * anyone, and answer "fail" when it is. + */ unauthorizedStatuses?: readonly number[]; } @@ -88,8 +109,11 @@ export interface FetchTransportConfig { * an exact-name query afterwards); with the expired * credential a rest-1 attribute write was refused the * same way and not applied, and a query.v1 read got the - * same 401. No 403 and no redirect was seen. What is - * not known: a 403, other releases, and other ways of + * same 401. With `X-Requested-With: XMLHttpRequest` + * on the request the same ended session answered 403, + * and a write refused so was not applied either. No + * redirect was seen. What is not known: a 403 for a + * permission denial, other releases, and other ways of * signing in. The SDK's own tests run where every * request is authenticated and check none of it, so * beyond those cases it remains your assertion. Answer it From b689ea0a62b3c81c6b282636b6d3b27413471ea9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:07:28 +0000 Subject: [PATCH 2/4] README: a test serving meta.v1 types must serve the whole chain to List for client.lists Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e947a3e..1f22afd 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ await client.send([{ from: "Story:1077", update: { Status: done._oid } }]); - **Resolve before you write.** A team's process IS enforced on a write: a status outside it is refused, as a command failure `Violation'PrimaryWorkitemCannotHaveInvalidStatus`. A scheme's selection is NOT: a status the project's scheme does not select is accepted, with no violation at all. Nothing but this lookup stops a write from setting a value the project does not use. - **`lists.value` matches the whole name**, ignoring case and surrounding space. `match: "prefix"` also accepts the start of the name or of a word in it ("prog" finds "In Progress") when no name matches whole. It never picks among several: no match is an `ApiError` coded `NO_SUCH_VALUE`, more than one is `AMBIGUOUS_VALUE`, and both carry the candidates as rows in `error.details.values` (every valid value, or the ones that matched), ready to offer. - **Only lists.** The server's endpoint takes no page and no filter and would answer every member, team or iteration in the project, so for `Owners`, `Team`, `Timebox` and any relation that is not to a list type, `client.lists` throws a `UsageError` before sending anything. There is no "valid values" call for those: read them with `client.query({ from: "Member", filter, page })`, bounded like every other read. -- **Costs and limits.** One request per attribute, sent one after another, and on a cold schema cache the type loads that tell a list from another relation (for Status: `StoryStatus`, `Status`, `List`); nothing is cached, because an administrator can change a scheme at any time. `select` takes attributes of the value itself (`Order`, `RollupState`), not paths and not dates, and every value arrives as a string. On an instance without the endpoint the call fails as the server's 404; it does not fall back to every value of the list type, which would be a different answer. +- **Costs and limits.** One request per attribute, sent one after another, and on a cold schema cache the type loads that tell a list from another relation (for Status: `StoryStatus`, `Status`, `List`; a test that serves captured meta.v1 types must serve that whole chain, and the error names the type it could not load when one is missing); nothing is cached, because an administrator can change a scheme at any time. `select` takes attributes of the value itself (`Order`, `RollupState`), not paths and not dates, and every value arrives as a string. On an instance without the endpoint the call fails as the server's 404; it does not fall back to every value of the list type, which would be a different answer. - `client.fields.describe(type, scope).lists` says which of a form's attributes are list-typed and to which list type each points. ### Reference From 3031d9369a29d47e00a793537545f818a9dc4848 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:25:45 +0000 Subject: [PATCH 3/4] A 403 that challenges is an auth failure; a write refused for want of rights is said so to a person An ended session answers 403, with the same WWW-Authenticate challenge as its 401, to a request sent with X-Requested-With. apiErrorFromResponse takes the response's headers and classifies that 403 as kind auth; the built-in transport passes them, calls onUnauthorized for it by default and hands the hook the headers. unauthorizedStatuses lists statuses in addition to those. A custom transport passes the headers too, and the conformance suite asks for it. A permission denial was never a 403 where it was looked at: api/asset reports it per command inside a 200 and rest-1 as a 400. rest-1's is now kind forbidden, and explain says "not allowed" to a person for both. From a consumer's captured responses; not reproducible where the SDK's live tier runs, where every request is an administrator's. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 67 ++++++++++++--- README.md | 3 +- examples/09-browser-session.ts | 10 +-- examples/11-axios-transport.ts | 3 +- specs/000-layers.md | 7 ++ src/core/errors.ts | 48 ++++++++++- src/core/fetchTransport.ts | 50 +++++++----- src/index.ts | 1 + src/services/explain.ts | 15 +++- src/testing/index.ts | 6 +- src/testing/transportConformance.ts | 16 +++- src/wire/queryV1.ts | 3 +- test/unit/auth403.test.ts | 121 ++++++++++++++++++++++++++++ 13 files changed, 297 insertions(+), 53 deletions(-) create mode 100644 test/unit/auth403.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d9a5b13..fb39bf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,57 @@ ## Unreleased (to be 1.0.0-alpha.13) +### Breaking + +- **A 403 that carries a `WWW-Authenticate` challenge is an auth + failure, and a custom transport must pass the response's headers to + say so.** `apiErrorFromResponse(status, body, headers)` takes the + headers as an optional third argument (a `Headers`, anything with + `get(name)`, or a plain record). With them, a 403 that challenges is + `kind: "auth"`, like a 401: it is what an ended session answers to a + request sent with `X-Requested-With: XMLHttpRequest`. A 403 without a + challenge, or with no headers given, is `kind: "forbidden"` as before. + - The built-in transport passes them, so nothing changes in how you + call it: `onUnauthorized` now runs for such a 403 by default + ("retry" and "retry-write" as for a 401), `explain` gives the + sign-in sentence instead of "not allowed", and the hook's context + has `headers`. + - `unauthorizedStatuses` now lists statuses that call the hook in + addition to those two (a 401; a challenged 403), which always do. A + consumer that set `[401, 403]` loses nothing: a 403 without a + challenge still reaches its hook. + - `transportConformance` has the case, and a control. Migration for a + custom transport: where it builds a refusal, pass the response's + headers as the third argument, e.g. with axios + `apiErrorFromResponse(response.status, response.data, + response.headers)`. A transport that does not is told so by the + suite and keeps calling a challenged 403 "forbidden". + - What this rests on, from a consumer's checks on one product release + with OIDC sign-in: every 401 and 403 seen carried the challenge and + was a session problem (missing, invalid, expired), and a genuine + permission denial was never a 401 or a 403 (next entry). It could + not be reproduced where this SDK's live tier runs, where every + request is authenticated as an administrator. Not checked: + administration endpoints that might answer 403 for rights, other + releases, other ways of signing in. So a hook that prompts a person + should still check that the session is gone before it prompts. + ### Changed +- **A write the member has no right to make is said so, to a person, on + both write paths.** On the same release it was never a 403: api/asset + reports it per command inside a 200 (`Violation'Security'Story`), and + rest-1 answers a 400 whose first exception is that violation. + - rest-1's 400 is now `kind: "forbidden"`, worded by the violation; it + was `kind: "invalid"` with the message "Bad Request". A branch on + `kind === "invalid"` no longer sees it. + - `client.explain` says "Agility refused: this member is not allowed + to do that." (audience "user") for both, with the asset type's label + in `typeLabel`; it said "Refused (security)." to a developer for the + command failure and echoed "Bad Request" for rest-1. `outcome` is + `"notApplied"` for both, as before. - **The advice on `X-Requested-With` for a cookie-session browser app - was wrong and is replaced** (documentation only; no behaviour - changes). `createFetchTransport`'s comment on `credentials` said to + was wrong and is replaced.** `createFetchTransport`'s comment on `credentials` said to send `X-Requested-With: XMLHttpRequest` "so the server answers 401 rather than a login page". A browser-app consumer ended a real session (one product release, OIDC sign-in) and saw the opposite @@ -14,16 +60,13 @@ `WWW-Authenticate: Bearer` challenge and body, neither a redirect. Since `onUnauthorized` runs for `unauthorizedStatuses`, default `[401]`, an app that followed the advice never had its hook called - when a session ended. Migration: if you send that header, set - `unauthorizedStatuses: [401, 403]` and have the hook check that the - session is really gone before it prompts (a one-row read with - `reauthorize: false`), because a 403 may also be a permission denial; - or stop sending the header. The built-in transport never sends it by - itself. A write refused with that 403 was not applied and landed once - when replayed, so what is known about `"retry-write"` extends to it. - Not checked: other releases, other ways of signing in, and whether a - 403 for a genuine permission denial carries the same challenge (so the - SDK still classifies every 403 as `kind: "forbidden"`). + when a session ended. With the entry under Breaking above, the + built-in transport now calls the hook for that 403 without any + configuration, so there is nothing to migrate for it; the transport + never sends the header by itself. A write refused with that 403 was + not applied and landed once when replayed, so what is known about + `"retry-write"` extends to it. Not checked: other releases and other + ways of signing in. ## 1.0.0-alpha.12 diff --git a/README.md b/README.md index 1f22afd..3e7b87b 100644 --- a/README.md +++ b/README.md @@ -171,9 +171,10 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `normalizeQuery(q)` - a query written with rest-1's spellings (`sel`, a textual `where`, comma-joined lists, a `"size,start"` page) as the `QueryBody` every read takes - Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded -- `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once; an app that sends `X-Requested-With: XMLHttpRequest` gets a 403 for an ended session and needs `unauthorizedStatuses: [401, 403]`, see the option's comment), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one +- `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401, or on a 403 that carries a `WWW-Authenticate` challenge, which is what an ended session answers to a request sent with `X-Requested-With: XMLHttpRequest` (resends idempotent requests once; `unauthorizedStatuses` adds other statuses), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline - Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. A guarded write (`sendGuarded`) is a write here too: it is never sent again by the client, because a second send of one that landed applies nothing and reports a conflict, which would tell you someone else changed the asset when the change was yours. When one gets no answer (`outcome: "unknown"`), read the asset again: you see your change or you do not, and the guard makes sending it again safe. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- A custom transport builds a refusal with `apiErrorFromResponse(status, body, headers)`. The headers matter: a 403 that carries a `WWW-Authenticate` challenge is `kind: "auth"` (an ended session), one without is `kind: "forbidden"`. A write the member has no right to make is never a 403 as far as has been seen: api/asset reports it per command inside a 200 and rest-1 as a 400, and `client.explain` says "Agility refused: this member is not allowed to do that." for both. - A config key that is not one the factory takes (`new AgilityApiClient`, `createFetchTransport`, `new FakeAgilityClient`) is refused at construction with a `UsageError` naming it, with the nearest known key when it looks like a typo. Nothing is ignored silently, and no value is repeated in the message. - A `fetch` of your own goes in the client's config (`fetchImpl`). A transport you make yourself with `createFetchTransport` and hand to the client keeps its own `retries` and `timeoutMs` and is not given the client's rules a second time; a wrapper of yours around it is a custom transport and is, so make the inner one with `retries: 0, timeoutMs: 0`. - Resends and failures are the client's business with any transport: an idempotent request (a GET, a read; never a write, guarded or not) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts index 82ab2ab..545c4d6 100644 --- a/examples/09-browser-session.ts +++ b/examples/09-browser-session.ts @@ -37,11 +37,11 @@ async function signInAgain(): Promise { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/MyInstance", credentials: "include", // send the session cookie; no accessToken - // No `X-Requested-With` header here, so an ended session answers 401 and - // the hook below runs. An app that sends `X-Requested-With: - // XMLHttpRequest` was seen to get a 403 for an ended session instead: it - // adds `unauthorizedStatuses: [401, 403]`, and its hook first checks that - // the session is really gone, since a 403 may also be a permission denial. + // An ended session answers 401, or, to an app that sends + // `X-Requested-With: XMLHttpRequest`, a 403 that carries the same + // WWW-Authenticate challenge. The hook below runs for both. A hook that + // shows a person a sign-in prompt should first check that the session is + // really gone (a one-row read sent with `reauthorize: false`). onUnauthorized: async ({ retryable }) => { if (!(await signInAgain())) return "fail"; // "retry" resends what is safe to send twice: a GET, a read. Never a diff --git a/examples/11-axios-transport.ts b/examples/11-axios-transport.ts index 7922f24..903f341 100644 --- a/examples/11-axios-transport.ts +++ b/examples/11-axios-transport.ts @@ -65,7 +65,8 @@ export function createAxiosTransport(http: AxiosInstance): Transport { if (axios.isCancel(error) || options.signal?.aborted) throw aborted(error); if (error instanceof AxiosError && error.response) { // A refusal: the same error, word for word, as the SDK's own transport throws. - throw apiErrorFromResponse(error.response.status, readable(error.response.data, String(error.response.headers["content-type"] ?? ""))); + // The headers go too: a 403 that carries a WWW-Authenticate challenge is an ended session, not a refusal of rights. + throw apiErrorFromResponse(error.response.status, readable(error.response.data, String(error.response.headers["content-type"] ?? "")), error.response.headers); } // No answer at all. Timing is the client's business, not this transport's: the client's `timeoutMs` hands // over a `signal` that fires at the deadline, and honouring it (above) is all a transport owes. diff --git a/specs/000-layers.md b/specs/000-layers.md index a1f1901..e7bff7a 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -365,6 +365,13 @@ Everything the SDK throws is an `ApiError` (`src/core/errors.ts`), and every `ApiError` has a `kind`: `auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage` or `unknown`. `status` and `code` say what happened; `kind` says what to do. +The status decides the kind except where the server's answer says more +than its status does, and then `apiErrorFromResponse` reads the answer: +a 403 that carries a `WWW-Authenticate` challenge is `auth` (an ended +session, to a request sent with `X-Requested-With`), so a transport passes +it the response's headers; a 400 whose first exception begins +`Violation'Security` is `forbidden` (rest-1 refusing a write the member has +no right to); a server-side SQL timeout is `SERVER_TIMEOUT`. A mistake the SDK catches before any request (an unpaged read, an empty batch, a bad OID token, a config object with a key its factory does not know: named in the message, never with its value) is a `UsageError` (`kind: "usage"`, `status: 0`), diff --git a/src/core/errors.ts b/src/core/errors.ts index c0547f9..17f3f48 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -112,11 +112,55 @@ function messageOf(data: unknown, status: number): string { * gets a code: a server-side SQL execution timeout, as an instance answers * it, is `SERVER_TIMEOUT` (kind transient, never resent), worded by the * exception that says so. + * + * Two refusals are classified by more than their status, so pass the + * response's `headers` when you have them: + * - a 403 that carries a `WWW-Authenticate` challenge is kind "auth", + * like a 401: an ended session answers so to a request sent with + * `X-Requested-With: XMLHttpRequest`. A 403 without a challenge, or + * with no headers given, is kind "forbidden" as before; + * - a refusal whose first exception begins `Violation'Security` (how + * rest-1 refuses a write the member has no right to: a 400) is kind + * "forbidden", worded by the violation. */ -export function apiErrorFromResponse(status: number, data?: unknown): ApiError { +export function apiErrorFromResponse(status: number, data?: unknown, headers?: ResponseHeaders): ApiError { const gaveUp = serverTimeoutIn(data); // "Server Error" says nothing; the exception's own words say what happened. - return gaveUp === null ? new ApiError(messageOf(data, status), status, undefined, data) : new ApiError(gaveUp, status, "SERVER_TIMEOUT", data); + if (gaveUp !== null) return new ApiError(gaveUp, status, "SERVER_TIMEOUT", data); + // A 403 that challenges the caller to authenticate is about the sign-in, not about rights. + if (status === 403 && challengeIn(headers)) return new ApiError(messageOf(data, status), status, undefined, data, "auth"); + // rest-1 refuses a write the member has no right to with a 400 whose first exception is a Security violation. + const denied = securityViolationIn(data); + if (denied !== null) return new ApiError(denied, status, undefined, data, "forbidden"); + return new ApiError(messageOf(data, status), status, undefined, data); +} + +/** + * A response's headers, as far as the SDK reads them: a `Headers`, anything + * with a `get(name)` (an axios response's `headers`), or a plain record of + * header names to values (names compared without regard to case). Only a + * string value counts as a header's value. + */ +export type ResponseHeaders = { get(name: string): unknown } | Readonly>; + +/** One header's value, whichever form the headers came in; null when absent. */ +export function headerOf(headers: ResponseHeaders | undefined, name: string): string | null { + if (!headers) return null; + if (typeof (headers as { get?: unknown }).get === "function") { const value = (headers as { get(name: string): unknown }).get(name); return typeof value === "string" ? value : null; } + const wanted = name.toLowerCase(); + for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === wanted && typeof value === "string") return value; + return null; +} + +/** Does the response challenge the caller to authenticate (a `WWW-Authenticate` header with something in it)? */ +const challengeIn = (headers: ResponseHeaders | undefined): boolean => !!headerOf(headers, "www-authenticate")?.trim(); + +/** The Security violation a refusal's first exception names (`Violation'Security'Story`), or null. */ +function securityViolationIn(data: unknown): string | null { + if (!data || typeof data !== "object") return null; + const first = Array.isArray((data as { exceptions?: unknown }).exceptions) ? ((data as { exceptions: unknown[] }).exceptions[0] as { message?: unknown } | undefined) : undefined; + const message = typeof first?.message === "string" ? first.message.trim() : ""; + return message.startsWith("Violation'Security") ? message : null; } /** diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index bde84ab..884f432 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -51,13 +51,16 @@ export interface FetchTransportConfig { * product release with OIDC sign-in, a session that had expired answer * 401 without that header and 403 with it, both with the same * `WWW-Authenticate: Bearer` challenge and the same body, and neither - * with a redirect to a login page. So: without the header, an ended - * session is a 401 and `onUnauthorized` runs by default; with it, set - * `unauthorizedStatuses: [401, 403]`, or the hook is never called. - * (Earlier releases of this comment advised the header "so the server - * answers 401 rather than a login page"; that is not what was seen.) - * Not checked: other releases, other ways of signing in, and whether a - * 403 for a genuine permission denial carries the same challenge. + * with a redirect to a login page. Either way it is kind "auth" and + * `onUnauthorized` runs: this transport reads the challenge, so a 403 + * that carries one is treated as the 401 it stands for. On the same + * release a genuine permission denial was never a 403: api/asset + * reported it per command inside a 200, and rest-1 as a 400, neither + * with a challenge. (Earlier releases of this comment advised the + * header "so the server answers 401 rather than a login page"; that + * is not what was seen.) Not checked: administration endpoints that + * might answer 403 for rights, other releases, other ways of signing + * in. */ credentials?: RequestCredentials; /** @@ -78,14 +81,16 @@ export interface FetchTransportConfig { */ onUnauthorized?: (context: UnauthorizedContext) => UnauthorizedDecision | Promise; /** - * Which statuses call onUnauthorized. Default [401]. An app that sends - * `X-Requested-With: XMLHttpRequest` needs [401, 403]: an ended session - * was seen to answer 403 to a request with that header (see - * `credentials`). A 403 is also what a permission denial may answer, - * and it is not known whether the response tells the two apart, so a - * hook called for a 403 should ask whether the session is still alive - * (a one-row read sent with `reauthorize: false`) before it prompts - * anyone, and answer "fail" when it is. + * Statuses that call onUnauthorized IN ADDITION to every refusal that + * is about the sign-in: a 401, and a 403 that carries a + * `WWW-Authenticate` challenge (kind "auth"; what an ended session + * answers to a request sent with `X-Requested-With: XMLHttpRequest`). + * Those two always call the hook, whatever this lists. Default [401]. + * Listing 403 here also sends a 403 WITHOUT a challenge to the hook, + * which nothing seen so far requires. A hook that prompts a person + * should first ask whether the session is still alive (a one-row read + * sent with `reauthorize: false`) and answer "fail" when it is: a + * prompt is cheap to guard and costly to show by mistake. */ unauthorizedStatuses?: readonly number[]; } @@ -112,9 +117,10 @@ export interface FetchTransportConfig { * same 401. With `X-Requested-With: XMLHttpRequest` * on the request the same ended session answered 403, * and a write refused so was not applied either. No - * redirect was seen. What is not known: a 403 for a - * permission denial, other releases, and other ways of - * signing in. The SDK's own tests run where every + * redirect was seen. A permission denial, on that + * release, was never a 401 or a 403. What is not known: + * administration endpoints, other releases, and other + * ways of signing in. The SDK's own tests run where every * request is authenticated and check none of it, so * beyond those cases it remains your assertion. Answer it * only where it holds (a missing or lapsed sign-in; not a @@ -128,6 +134,8 @@ export interface UnauthorizedContext { request: RequestOptions; /** Whether a "retry" will be honoured: false for any write, guarded or plain (which only "retry-write" resends). */ retryable: boolean; + /** The refusal's response headers: `headers.get("www-authenticate")` is the challenge, when the server sent one. */ + headers: { get(name: string): string | null }; } /** The ApiError a caller's abort turns into. */ @@ -268,7 +276,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { // An answer, not a failure to get one. 5xx may be retried when // idempotent; anything else is final. const data = await readBody(response, responseType === "bytes" ? "text" : responseType === "json" ? "auto" : responseType); - lastError = apiErrorFromResponse(response.status, data); + lastError = apiErrorFromResponse(response.status, data, response.headers); } catch (error) { if (callerSignal?.aborted) throw abortedError(callerSignal); // The deadline passed while the body was still arriving: a timeout like any other. @@ -278,10 +286,10 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { settle(); } - if (config.onUnauthorized && options.reauthorize !== false && !reauthorized && unauthorizedStatuses.includes(response.status)) { + if (config.onUnauthorized && options.reauthorize !== false && !reauthorized && (unauthorizedStatuses.includes(response.status) || (lastError as ApiError).kind === "auth")) { // One re-authentication per request: a second refusal is final. reauthorized = true; - const decision = await config.onUnauthorized({ error: lastError as ApiError, request: options, retryable: idempotent }); + const decision = await config.onUnauthorized({ error: lastError as ApiError, request: options, retryable: idempotent, headers: response.headers }); if (callerSignal?.aborted) throw abortedError(callerSignal); if ((decision === "retry" && idempotent) || decision === "retry-write") { // Not counted against `retries`: those are for failures to get an answer. diff --git a/src/index.ts b/src/index.ts index f8e963f..1e9c8ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ export { AgilityApiClient } from "./client"; export type { ClientOptions, Me, Page, PagesOptions } from "./client"; export { ApiError, UsageError, WrappedError, apiErrorFromResponse, kindOf } from "./core/errors"; +export type { ResponseHeaders } from "./core/errors"; export type { ErrorKind } from "./core/errors"; export { createFetchTransport } from "./core/fetchTransport"; export { withRetry } from "./core/retry"; diff --git a/src/services/explain.ts b/src/services/explain.ts index 5a517be..c7f34e8 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -111,12 +111,15 @@ export interface Explanation { message: string; } -interface Problem { rule: string | null; attribute: AttributeTokenRef | null; related: string | null } +interface Problem { rule: string | null; attribute: AttributeTokenRef | null; related: string | null; /** The asset type a violation names without an attribute (Violation'Security'Story). */ type?: string | null } /** What a failure message says went wrong: a Violation (parseViolation), a Resolution, or nothing readable. */ function problemOf(message: string): Problem { const violation = parseViolation(message); - if (violation) return { rule: violation.rule, attribute: violation.attribute, related: null }; + if (violation) { + const named = message.trim().split("'")[2]; + return { rule: violation.rule, attribute: violation.attribute, related: null, type: !violation.attribute && named && /^[A-Za-z]\w*$/.test(named) && named !== "AttributeDefinition" ? named : null }; + } const parts = message.trim().split("'"); if (parts[0] === "Resolution" && parts[1] && /^[A-Za-z]\w*\.[A-Za-z]\w*$/.test(parts[2] ?? "")) return { rule: parts[1], attribute: parts[2] as AttributeTokenRef, related: parts[3] || null }; return { rule: null, attribute: null, related: null }; @@ -127,6 +130,7 @@ const typeTag = (type: string): string => `AssetType'${type}`; /** A token that looks like one loc-2 would know: no spaces, apostrophe-delimited. A plain sentence is not asked about. */ const isTag = (message: string): boolean => /^[A-Za-z]\w*'[^\s]+$/.test(message.trim()); +const NOT_ALLOWED = "Agility refused: this member is not allowed to do that."; type Said = Pick; /** What is known of the change an error's request asked for. See `Explanation.outcome`. */ @@ -142,6 +146,8 @@ const forUser = (sentence: string, retrySafe: boolean | null = null): Said => ({ const forDeveloper = (sentence: string, echoed: boolean): Said => ({ sentence, audience: "developer", echoed, retrySafe: null }); function sentenceOf(problem: Problem, label: string | null, related: string | null, localized: string | null, message: string): Said { + // The member has no right to do it: what api/asset reports per command (Violation'Security'Story) and rest-1 as a 400. + if (problem.rule === "Security") return forUser(NOT_ALLOWED); if (label) { switch (problem.rule) { case "Required": return forUser(`${label} is required.`); @@ -205,7 +211,7 @@ function sentenceForError(error: unknown): Said { if (!(error instanceof ApiError)) return forDeveloper(error instanceof Error ? error.message : String(error), true); switch (error.kind) { case "auth": return forUser("Agility did not accept the sign-in: the token is missing, wrong or no longer valid."); - case "forbidden": return forUser("Agility refused: this member is not allowed to do that."); + case "forbidden": return forUser(NOT_ALLOWED); case "transient": return unanswered(error); case "aborted": return forUser("The request was cancelled."); case "conflict": return forUser("Someone else changed this since it was read; nothing was applied. Look at it again and decide."); @@ -230,6 +236,7 @@ export async function explain(transport: Transport, input: unknown, options: loc const p = problems[i]!; if (isTag(f.message)) tags.add(f.message.trim()); if (p.attribute) { tags.add(attributeTag(p.attribute)); tags.add(typeTag(p.attribute.split(".")[0]!)); } + if (p.type) tags.add(typeTag(p.type)); if (p.related) tags.add(typeTag(p.related)); }); let labels: loc2.Localizations = {}; @@ -240,7 +247,7 @@ export async function explain(transport: Transport, input: unknown, options: loc const label = (tag: string): string | null => { const l = labels[tag]; return typeof l === "string" && l && l !== tag ? l : null; }; return failures.map((f, i) => { const p = problems[i]!; - const [type, name] = p.attribute ? p.attribute.split(".") : [null, null]; + const [type, name] = p.attribute ? p.attribute.split(".") : [p.type ?? null, null]; const attributeLabel = p.attribute ? label(attributeTag(p.attribute)) ?? name! : null; const typeLabel = type ? label(typeTag(type)) ?? type : null; const related = p.related ? label(typeTag(p.related)) ?? p.related : null; diff --git a/src/testing/index.ts b/src/testing/index.ts index ef4e77c..a3e9eaf 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -428,8 +428,10 @@ function toAssetDocument(row: FakeRow): Record { * over everything above. With `new FakeAgilityClient({ metamodel })` a * captured query response reads as it would live: translated. * - An `Error` as an answer is thrown: `new ApiError("Unauthorized", 401)`, - * or `apiErrorFromResponse(status, body)` for a refusal as the fetch - * transport words it. + * or `apiErrorFromResponse(status, body, headers)` for a refusal as the + * fetch transport makes it; the headers script a response header, as + * in `apiErrorFromResponse(403, { error: "Unauthorized" }, { + * "www-authenticate": "Bearer" })` for an ended session. */ export class FakeAgilityClient extends AgilityApiClient { /** Every request the client made, in order, as a Transport sees it (the client's own unscripted meta.v1 type loads left out). */ diff --git a/src/testing/transportConformance.ts b/src/testing/transportConformance.ts index d80e00e..6b0c438 100644 --- a/src/testing/transportConformance.ts +++ b/src/testing/transportConformance.ts @@ -152,7 +152,7 @@ export function transportConformance(make: (server: ConformanceServer) => Transp expect(error instanceof ApiError && error.status === 304, "without acceptNotModified a 304 must reject with an ApiError carrying the status"); } }, { name: "a refused response rejects with the ApiError that apiErrorFromResponse makes: the status, the server's own words, the body as details", run: async () => { - const bodies: [number, unknown][] = [ + const bodies: [number, unknown, Record?][] = [ [400, { _type: "Error", error: "Invalid WHERE parameter", exceptions: [{ type: "FormatException", message: "Invalid QueryFilter2 token Nope=1" }] }], [400, { Exceptions: ["The request body is not valid JSON."] }], // A server-side SQL execution timeout, as an instance answers it: told by its body, coded SERVER_TIMEOUT. @@ -163,12 +163,20 @@ export function transportConformance(make: (server: ConformanceServer) => Transp // As query.v1 and rest-1 refuse an expired credential: a 401 with a body. Still kind "auth". [401, { error: "Unauthorized" }], [401, { _type: "Error", error: "Unauthorized" }], + // An ended session, to a request sent with X-Requested-With: a 403 that challenges. Kind "auth", which only the + // response's headers can tell: pass them to apiErrorFromResponse(status, body, headers). + [403, { error: "Unauthorized" }, { "www-authenticate": "Bearer realm=\"conformance\"" }], + // Control: a 403 with no challenge is kind "forbidden". + [403, { error: "Forbidden" }], + // As rest-1 refuses a write the member has no right to: a 400 whose first exception is a Security violation. Kind "forbidden". + [400, { _type: "Error", error: "Bad Request", exceptions: [{ type: "DataException", message: "Violation'Security'Story" }] }], [503, ""] ]; - for (const [status, data] of bodies) { - const response: ConformanceResponse = typeof data === "string" ? { status, headers: { "content-type": "text/plain" }, body: data } : json(data, status); + for (const [status, data, extra] of bodies) { + const headers: Record = { "content-type": typeof data === "string" ? "text/plain" : "application/json; charset=utf-8", ...extra }; + const response: ConformanceResponse = { status, headers, body: typeof data === "string" ? data : JSON.stringify(data) }; const error = await rejection(scripted(response).transport.request({ method: "GET", path: "/x" })); - const expected = apiErrorFromResponse(status, data); + const expected = apiErrorFromResponse(status, data, headers); expect(error instanceof ApiError, `a ${status} must reject with an ApiError`); expect(error.status === status && error.kind === expected.kind, `a ${status} must carry its status and the kind it implies (${expected.kind})`); expect(error.message === expected.message, `a ${status} must be worded as apiErrorFromResponse words it ("${expected.message}"), got "${error.message}"`); diff --git a/src/wire/queryV1.ts b/src/wire/queryV1.ts index cfc9718..9c5697e 100644 --- a/src/wire/queryV1.ts +++ b/src/wire/queryV1.ts @@ -41,7 +41,8 @@ export function rejected(error: ApiError): ApiError { const details = error.details as { error?: unknown; exceptions?: { type?: unknown; message?: unknown }[] } | undefined; const rejections: QueryRejection[] = (details?.exceptions ?? []).filter((e) => e && typeof e.message === "string" && e.message).map((e) => ({ type: typeof e.type === "string" ? e.type : null, message: e.message as string })); // The server's own timeout is not a refusal of the query, whatever status it came with. - if (!rejections.length || error.code === "SERVER_TIMEOUT") return error; + // Nor is a write refused for want of rights (rest-1's 400 with a Security violation): it keeps its kind. + if (!rejections.length || error.code === "SERVER_TIMEOUT" || error.kind === "forbidden") return error; // rest-1 names what it refused in `error` ("Invalid WHERE parameter"); query.v1 says only "Bad Request", which adds nothing. const lead = typeof details?.error === "string" && details.error && details.error !== "Bad Request" ? [details.error] : []; return new ApiError([...lead, ...rejections.map((r) => r.message)].join("; "), error.status, "QUERY_REJECTED", rejections); diff --git a/test/unit/auth403.test.ts b/test/unit/auth403.test.ts new file mode 100644 index 0000000..162be7a --- /dev/null +++ b/test/unit/auth403.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { ApiError, apiErrorFromResponse } from "../../src/core/errors"; +import { createFetchTransport, type UnauthorizedContext } from "../../src/core/fetchTransport"; +import { FakeAgilityClient } from "../../src/testing"; +import { assetApi, rest1 } from "../../src/wire"; + +/** + * Two refusals that the status alone misnames, as a browser-app consumer + * saw them on one product release (OIDC sign-in), identities replaced: + * - an ended session answers 401 to a plain request and 403 to one sent + * with X-Requested-With: XMLHttpRequest, both with the same Bearer + * challenge and body. The 403 is about the sign-in; + * - a write the member has no right to is never a 403: api/asset + * reports it per command inside a 200, and rest-1 as a 400. Neither + * carries a challenge. + * None of it can be reproduced where the SDK's own live tier runs: every + * request there is authenticated, as an administrator. + */ +const CHALLENGE = { "www-authenticate": "Bearer realm=\"agility.example.com\"" }; +const ENDED = { error: "Unauthorized" }; +const DENIED_REST1 = { _type: "Error", error: "Bad Request", exceptions: [{ type: "DataException", message: "Violation'Security'Story" }, { type: "SecurityException", message: "Violation'Security'Story" }] }; +const response = (status: number, body: unknown, headers: Record = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } }); +const envelope = (over: Record = {}) => ({ requestId: "r", assetsCreated: { oidTokens: [], count: 0 }, assetsModified: { oidTokens: [], count: 0 }, assetsOperatedOn: { oidTokens: [], count: 0 }, commandFailures: { commands: [], count: 0 }, queryResult: { results: [], resultMetaData: [], count: -1 }, ...over }); + +describe("a 403 that challenges is about the sign-in", () => { + it("apiErrorFromResponse: a 403 with a WWW-Authenticate challenge is kind auth; without one, or with no headers given, forbidden; a 401 is auth either way", () => { + expect(apiErrorFromResponse(403, ENDED, CHALLENGE)).toMatchObject({ kind: "auth", status: 403, message: "Unauthorized", details: ENDED }); + // Headers in any of the forms a transport has them: a Headers, something with get, a plain record in any case. + expect(apiErrorFromResponse(403, ENDED, new Headers(CHALLENGE)).kind).toBe("auth"); + expect(apiErrorFromResponse(403, ENDED, { "WWW-Authenticate": "Bearer" }).kind).toBe("auth"); + expect(apiErrorFromResponse(403, ENDED, { get: (name) => (name.toLowerCase() === "www-authenticate" ? "Bearer" : null) }).kind).toBe("auth"); + // Controls. + expect(apiErrorFromResponse(403, { error: "Forbidden" }).kind).toBe("forbidden"); + expect(apiErrorFromResponse(403, ENDED).kind).toBe("forbidden"); + expect(apiErrorFromResponse(403, ENDED, { "www-authenticate": " " }).kind).toBe("forbidden"); + expect(apiErrorFromResponse(403, ENDED, { "content-type": "application/json" }).kind).toBe("forbidden"); + expect(apiErrorFromResponse(401, ENDED).kind).toBe("auth"); + expect(apiErrorFromResponse(401, ENDED, CHALLENGE).kind).toBe("auth"); + // A challenge changes nothing about any other status. + expect(apiErrorFromResponse(400, { error: "Bad Request" }, CHALLENGE).kind).toBe("invalid"); + expect(apiErrorFromResponse(500, { error: "Server Error" }, CHALLENGE).kind).toBe("transient"); + }); + + it("the built-in transport calls onUnauthorized for it by default, hands the hook the headers, and resends as for a 401: a read on retry, a write only on retry-write", async () => { + const seen: UnauthorizedContext[] = []; + const ended = () => response(403, ENDED, CHALLENGE); + const fetchImpl = vi.fn().mockResolvedValueOnce(ended()).mockResolvedValueOnce(response(200, { ok: true })); + const transport = createFetchTransport({ baseUrl: "https://x", fetchImpl, onUnauthorized: (context) => { seen.push(context); return "retry"; } }); + expect(await transport.request({ method: "GET", path: "/meta.v1/Story" })).toEqual({ ok: true }); + expect(fetchImpl).toHaveBeenCalledTimes(2); + expect(seen[0]).toMatchObject({ retryable: true, error: { kind: "auth", status: 403 } }); + expect(seen[0]!.headers.get("www-authenticate")).toBe(CHALLENGE["www-authenticate"]); + // A write: "retry" does not resend it, "retry-write" does, once. + for (const [answer, sends] of [["retry", 1], ["retry-write", 2]] as const) { + const write = vi.fn().mockResolvedValueOnce(ended()).mockResolvedValueOnce(response(200, envelope())); + const sending = createFetchTransport({ baseUrl: "https://x", fetchImpl: write, onUnauthorized: () => answer }).request({ method: "POST", path: "/api/asset", body: [] }); + if (sends === 1) await expect(sending).rejects.toMatchObject({ kind: "auth", status: 403 }); else await sending; + expect(write).toHaveBeenCalledTimes(sends); + } + // The hook is still called once per request: a second challenged 403 is final. + const always = vi.fn().mockImplementation(() => Promise.resolve(ended())); + const hook = vi.fn(() => "retry" as const); + await expect(createFetchTransport({ baseUrl: "https://x", fetchImpl: always, onUnauthorized: hook }).request({ method: "GET", path: "/meta.v1/Story" })).rejects.toMatchObject({ kind: "auth" }); + expect(hook).toHaveBeenCalledOnce(); + }); + + it("unauthorizedStatuses lists statuses in addition to those: a 403 without a challenge reaches the hook only when listed, and a consumer that lists [401, 403] gets nothing worse than before", async () => { + const plain403 = () => response(403, { error: "Forbidden" }); + const hook = vi.fn(() => "fail" as const); + await expect(createFetchTransport({ baseUrl: "https://x", fetchImpl: vi.fn().mockImplementation(() => Promise.resolve(plain403())), onUnauthorized: hook }).request({ method: "GET", path: "/x" })).rejects.toMatchObject({ kind: "forbidden" }); + expect(hook).not.toHaveBeenCalled(); + const listed = vi.fn(() => "fail" as const); + const both = createFetchTransport({ baseUrl: "https://x", fetchImpl: vi.fn().mockResolvedValueOnce(plain403()).mockResolvedValueOnce(response(403, ENDED, CHALLENGE)).mockResolvedValueOnce(response(401, ENDED)), onUnauthorized: listed, unauthorizedStatuses: [401, 403] }); + for (const kind of ["forbidden", "auth", "auth"]) await expect(both.request({ method: "GET", path: "/x" })).rejects.toMatchObject({ kind }); + expect(listed).toHaveBeenCalledTimes(3); + // A request sent with reauthorize: false (the hook's own session check) is refused straight away, challenged or not. + const quiet = vi.fn(() => "retry" as const); + await expect(createFetchTransport({ baseUrl: "https://x", fetchImpl: vi.fn().mockImplementation(() => Promise.resolve(response(403, ENDED, CHALLENGE))), onUnauthorized: quiet }).request({ method: "GET", path: "/x", reauthorize: false })).rejects.toMatchObject({ kind: "auth" }); + expect(quiet).not.toHaveBeenCalled(); + }); + + it("explain says the sign-in sentence for it, and a write refused so was not applied", async () => { + const fetchImpl = (async (url: string | URL) => (new URL(String(url)).pathname.startsWith("/meta.v1/") ? response(404, {}) : response(403, ENDED, CHALLENGE))) as typeof fetch; + const client = new AgilityApiClient({ baseUrl: "https://x", fetchImpl }); + const error = await client.send([{ from: "Story:1", update: { Name: "x" } }]).catch((e: unknown) => e); + expect((await client.explain(error))[0]).toMatchObject({ sentence: "Agility did not accept the sign-in: the token is missing, wrong or no longer valid.", audience: "user", outcome: "notApplied" }); + // The fake scripts it as the transport makes it: the headers are the factory's third argument. + const fake = new FakeAgilityClient().onSend(apiErrorFromResponse(403, ENDED, CHALLENGE)); + await expect(fake.send([{ from: "Story:1", update: { Name: "x" } }])).rejects.toMatchObject({ kind: "auth", status: 403 }); + }); +}); + +describe("a write the member has no right to", () => { + it("rest-1's refusal, a 400 whose first exception is a Security violation, is kind forbidden and worded by the violation; other 400s are as they were", async () => { + expect(apiErrorFromResponse(400, DENIED_REST1)).toMatchObject({ kind: "forbidden", status: 400, message: "Violation'Security'Story", details: DENIED_REST1 }); + // Controls: another violation, and a Security violation that is not the first exception. + expect(apiErrorFromResponse(400, { error: "Bad Request", exceptions: [{ type: "DataException", message: "Violation'Required'AttributeDefinition'Name'Story" }] })).toMatchObject({ kind: "invalid", message: "Bad Request" }); + expect(apiErrorFromResponse(400, { error: "Bad Request", exceptions: [{ message: "Something else" }, { message: "Violation'Security'Story" }] }).kind).toBe("invalid"); + // Through the wire module and a client: not re-coded as a rejected query, and explained to a person. + const fetchImpl = (async (url: string | URL) => (new URL(String(url)).pathname.startsWith("/meta.v1/") ? response(404, {}) : response(400, DENIED_REST1))) as typeof fetch; + const client = new AgilityApiClient({ baseUrl: "https://x", fetchImpl }); + const refused = await rest1.operate(client.transport, "Story:1", "QuickClose").catch((e: unknown) => e as ApiError); + expect(refused).toMatchObject({ kind: "forbidden", status: 400, request: { method: "POST", idempotent: false } }); + expect((await client.explain(refused))[0]).toMatchObject({ sentence: "Agility refused: this member is not allowed to do that.", audience: "user", echoed: false, outcome: "notApplied", retrySafe: null }); + await expect(rest1.list(client.transport, "Story", { page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "forbidden", code: undefined }); + }); + + it("api/asset's refusal, a Security command failure inside a 200, gets the same sentence for a person, and that command was not applied", async () => { + // As api/asset answered a create by a read-only member: nothing created, the command failed for Security. + const failed = envelope({ commandFailures: { commands: [{ "@a": { AssetType: "Story", Name: "n", Scope: "Scope:0" }, error: { message: "Violation'Security'Story", sourceCommandIndex: 0 } }], count: 1 } }); + const fetchImpl = (async (url: string | URL) => { const path = new URL(String(url)).pathname; return path.startsWith("/meta.v1/") ? response(404, {}) : path.startsWith("/loc-2.v1") ? response(200, { "Violation'Security'Story": "Violation'Security'Story", "AssetType'Story": "Backlog Item" }) : response(200, failed); }) as typeof fetch; + const client = new AgilityApiClient({ baseUrl: "https://x", fetchImpl }); + const outcome = assetApi.outcomeOf(await assetApi.send(client.transport, [{ AssetType: "Story", Name: "n", Scope: "Scope:0" }])); + expect(outcome).toMatchObject({ created: [], failures: [{ index: 0, message: "Violation'Security'Story" }] }); + const [said] = await client.explain(outcome); + expect(said).toMatchObject({ sentence: "Agility refused: this member is not allowed to do that.", audience: "user", echoed: false, rule: "Security", typeLabel: "Backlog Item", attribute: null, outcome: "notApplied", index: 0, message: "Violation'Security'Story" }); + // Control: another rule the instance has no sentence for stays a developer's. + expect((await client.explain([{ index: 0, message: "Violation'MessageMustNotBeSent" }]))[0]).toMatchObject({ audience: "developer", sentence: "Refused (message must not be sent)." }); + }); +}); From ff3e4adadcc67fb8ae4464529321eff923d4df03 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:26:45 +0000 Subject: [PATCH 4/4] Changelog: unauthorizedStatuses adds to a 401 and a challenged 403, which always call the hook Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb39bf4..ad9b6c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,11 @@ - `unauthorizedStatuses` now lists statuses that call the hook in addition to those two (a 401; a challenged 403), which always do. A consumer that set `[401, 403]` loses nothing: a 403 without a - challenge still reaches its hook. + challenge still reaches its hook. But the list was the whole rule + before, and no longer is: a 401 calls the hook even when the list + leaves 401 out (`[403]`, or `[]`). Migration: `unauthorizedStatuses` + now adds to a 401 and a challenged 403; to stop the hook for those, + do not supply it. - `transportConformance` has the case, and a control. Migration for a custom transport: where it builds a refusal, pass the response's headers as the third argument, e.g. with axios