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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,77 @@
# Changelog

## 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. 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
`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.** `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. 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

### Breaking
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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), 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
Expand Down
5 changes: 5 additions & 0 deletions examples/09-browser-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ async function signInAgain(): Promise<boolean> {
const client = new AgilityApiClient({
baseUrl: "https://agility.example.com/MyInstance",
credentials: "include", // send the session cookie; no accessToken
// 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
Expand Down
3 changes: 2 additions & 1 deletion examples/11-axios-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions specs/000-layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`),
Expand Down
48 changes: 46 additions & 2 deletions src/core/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<string, unknown>>;

/** 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;
}

/**
Expand Down
Loading