@sanity-labs/client-fake-for-test 0.22.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/dist/index.cjs +246 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -1
- package/dist/index.d.ts +38 -1
- package/dist/index.js +247 -16
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -174,6 +174,54 @@ The refusal is the platform's answer, probed on staging and production, raised a
|
|
|
174
174
|
|
|
175
175
|
The platform checks the session before it routes, so the 401 comes before a resource's 404 for a route it does not mount.
|
|
176
176
|
|
|
177
|
+
#### Internal tokens
|
|
178
|
+
|
|
179
|
+
A Sanity service can mint its own token: an RS256 JWT whose claims are `i` (the identity), `g` (grants as `{ s: path, p: permissions }`) and `x` (expiry, epoch seconds). The Content Lake verifies it against its public key instead of looking up a session. Give the fake that public key, and a test can hand it the token the code under test really mints:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
const client = createTestClient({
|
|
183
|
+
documents,
|
|
184
|
+
internalTokenKeys: [publicKeyPem], // RSA public key PEMs; shared by the whole withConfig family
|
|
185
|
+
});
|
|
186
|
+
const service = client.withConfig({ token: mintedJwt });
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
A bearer that is not a registered identity, has a JWT's three segments and verifies against any of the keys acts as `{ user: { id: i }, grants: g }`. Each `{ s, p }` grant is the path grant `{ path: s, permissions: p }`, read and refused exactly as in [Token grants](#token-grants-filters-and-paths). The header's `kid` is not read: gradient holds one key. A token without `x` does not expire.
|
|
190
|
+
|
|
191
|
+
The Content Lake refuses the token on every request it serves (queries, documents, mutations, actions, the History API), as gradient does (`pkg/server/httpapi/middlewares/sessions/session.go`), each as a `PlatformHttpError`:
|
|
192
|
+
|
|
193
|
+
| Token | Answer |
|
|
194
|
+
| --- | --- |
|
|
195
|
+
| Signed by another key | 400 `{ error: { type: "httpBadRequest", description: 'invalid JWT token "<token>": crypto/rsa: verification error' } }` |
|
|
196
|
+
| `alg` other than `RS256` | 400, `invalid JWT token "<token>": token uses algorithm "<alg>", expected "RS256"` |
|
|
197
|
+
| A segment that is not base64url | 400, `invalid JWT token "<token>": illegal base64 data at input byte <n>` |
|
|
198
|
+
| A grant the Content Lake cannot parse | 400, the grant's own `description` (no `invalid JWT token` prefix) |
|
|
199
|
+
| `x` that is not an int64 (`1.0`, `4.1e9`, over 2^63 - 1) | 400, `invalid expiry: expected int64: strconv.ParseInt: parsing "<x>": <reason>` (`invalid syntax` / `value out of range`) |
|
|
200
|
+
| `i` that is not a string | 400, `token field "i" must be a string` |
|
|
201
|
+
| `x` at or before now | 403 `{ error: { type: "permissionDeniedError", description: "Token has expired (at 2026-11-20 12:00:30 +0000 UTC)" } }` |
|
|
202
|
+
|
|
203
|
+
A JWT that does not verify still binds, as production clients accept any string; the refusal comes on the first request. Without `internalTokenKeys` a JWT is an unknown token, as before. An internal token has no session, so `revokeIdentity` throws for one: mint one whose `x` has passed instead. The project API (populus) verifies internal tokens with its own key and answers differently; the fake does not model that, so `request()` of `/users/me`, `/projects/…`, the Access API or an ACL throws a fake error with an internal token. Claims the fake does not model (`tokenType`, `guid`, `s`, `z`, `audit`, `act`, `exp`, `iat`, `nbf`, or a claims segment that is not a JSON object) throw a fake error instead of a guessed answer. A missing `i`, or a `g…` global user id other than `god` (which gradient maps to a project user), throws its fake error on a request, after the 400 and 403 checks above.
|
|
204
|
+
|
|
205
|
+
#### Platform outages
|
|
206
|
+
|
|
207
|
+
`client.simulateOutage("project-api")` takes the project API (populus) down, as in an outage. From the next request on, every `request()` it serves throws a `PlatformServerError`, on every handle of the family, siblings made before and after the call alike: `/users/me`, `/projects/<projectId>` and everything under it (members, users, roles, features, the dataset ACL), `/organizations/<id>/users/me/attributes`, the Access API, resource lookup (`/canvases/<id>`, …) and a Media Library's or Canvas's ACL. `PlatformServerError` extends `@sanity/client`'s `ServerError`, which the client throws for a status of 500 or more, not `ClientError`, and the client does not retry it:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
{
|
|
211
|
+
statusCode: 500,
|
|
212
|
+
message: "Internal Server Error - An internal server error occurred",
|
|
213
|
+
response: {
|
|
214
|
+
statusCode: 500,
|
|
215
|
+
statusMessage: "Internal Server Error",
|
|
216
|
+
url: "https://p1.api.sanity.io/v2025-02-19/projects/p1/features", // the URL @sanity/client requests
|
|
217
|
+
body: { statusCode: 500, error: "Internal Server Error", message: "An internal server error occurred" },
|
|
218
|
+
// method, headers
|
|
219
|
+
},
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
That is the body populus sends for an unexpected error: its error handler sends Boom's payload, and Boom hides the error's own message behind a fixed one. The Content Lake keeps answering (queries, documents, mutations, actions, the History API), as does a route a resource does not mount (Express's 404). A token without a session is still refused with its 401 first, as the gateway checks the session before it routes. The call is recorded in `client.calls()` with its error. `"project-api"` is the only component so far, and an outage lasts for the rest of the family's life; create a new client for a healthy platform.
|
|
224
|
+
|
|
177
225
|
#### Project-scoped tokens: membership and refusals
|
|
178
226
|
|
|
179
227
|
A robot token belongs to the project that issued it. Model one with `projectId` on the identity:
|
|
@@ -315,6 +363,8 @@ Every error the fake throws for an HTTP answer of the platform is an instance of
|
|
|
315
363
|
| `WriteAccessDeniedError` | a write the grants do not permit (403) |
|
|
316
364
|
| `GuardDeniedError` | a write a mutation guard denies (403) |
|
|
317
365
|
|
|
366
|
+
A project API outage (see [Platform outages](#platform-outages)) throws `PlatformServerError` instead, an instance of `@sanity/client`'s `ServerError`, as the client raises a 500.
|
|
367
|
+
|
|
318
368
|
`response.url` is the URL `@sanity/client` would have requested, as its errors carry it: the project host (`https://<projectId>.api.sanity.io`, or `apicdn` for a GET of the data API with `useCdn` on) or the global host for a `resource` or `useProjectHostname: false` client, then `/v<apiVersion>`, the path, and the query string the client sends (the tag with its `requestTagPrefix`, a GROQ query and its params, the perspective, the mutation options). A JSON body keeps it out of `message`, as in `@sanity/client`; a text body's message names it. For example, `createTestClient({ projectId: "p1", dataset: "production", apiVersion: "2025-02-19", useCdn: false })` names `https://p1.api.sanity.io/v2025-02-19/data/doc/production/x?tag=t` for a refused `getDocument("x", { tag: "t" })`.
|
|
319
369
|
|
|
320
370
|
The fake hands `ClientError` the response the platform sends, and `ClientError` derives `statusCode`, `message`, `responseBody` and `details` from it, exactly as for a real response. `instanceof` needs the fake and your code to share one `@sanity/client`, so it is a peer dependency (7.21 or later, or 8); with several copies installed, dedupe them. Mistakes in a test's setup (an unknown token, a document without `_id`, an unimplemented member) stay plain `Error`s prefixed `[client-fake-for-test]`, as do refusals whose platform answer the fake does not model yet (a mutation's existing id, missing target or `ifRevisionId` mismatch, an unknown id at `/projects/<projectId>/users/<id>`, which carries `statusCode: 404`).
|
|
@@ -343,6 +393,8 @@ Useful in test bodies, but a giveaway that the code under test isn't using the r
|
|
|
343
393
|
| `client.addIdentity(token, identity)` | Register (upsert) a token→identity entry in the family-shared registry |
|
|
344
394
|
| `client.identities()` | Snapshot of the registered token→identity entries |
|
|
345
395
|
| `client.revokeIdentity(token)` | Make every later request on a registered token answer 401 `Session not found` (see [Unknown tokens and revoked tokens](#unknown-tokens-and-revoked-tokens)) |
|
|
396
|
+
| `createTestClient({ internalTokenKeys: [publicKeyPem] })` | Verify JWT bearers as the Content Lake does (see [Internal tokens](#internal-tokens)) |
|
|
397
|
+
| `client.simulateOutage("project-api")` | Make every later project API request answer populus's 500 (see [Platform outages](#platform-outages)) |
|
|
346
398
|
| `createTestClient({ datasets: { "p:d": [...] } })` | Seed multiple `(projectId, dataset)` stores up front |
|
|
347
399
|
| `createTestClient({ resources: { "media-library:ml1": [...] } })` | Seed any resource type up front; keys are `"<type>:<id>"` |
|
|
348
400
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: !0 });
|
|
3
|
-
var groqJs = require("groq-js"), client = require("@sanity/client");
|
|
3
|
+
var groqJs = require("groq-js"), client = require("@sanity/client"), node_crypto = require("node:crypto");
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
@@ -10,6 +10,11 @@ class PlatformHttpError extends client.ClientError {
|
|
|
10
10
|
super(platformResponse(args)), this.name = "PlatformHttpError";
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
+
class PlatformServerError extends client.ServerError {
|
|
14
|
+
constructor(args) {
|
|
15
|
+
super(platformResponse(args)), this.name = "PlatformServerError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
13
18
|
function platformResponse(args) {
|
|
14
19
|
const { method, url, statusCode, statusMessage, body } = args;
|
|
15
20
|
return {
|
|
@@ -80,7 +85,20 @@ const sessionNotFound = (request) => new PlatformHttpError({
|
|
|
80
85
|
statusCode: 401,
|
|
81
86
|
statusMessage: "Unauthorized",
|
|
82
87
|
message: "User must be a member of this project to perform this operation"
|
|
83
|
-
})
|
|
88
|
+
});
|
|
89
|
+
function projectApiDown(request) {
|
|
90
|
+
return new PlatformServerError({
|
|
91
|
+
...request,
|
|
92
|
+
statusCode: 500,
|
|
93
|
+
statusMessage: "Internal Server Error",
|
|
94
|
+
body: {
|
|
95
|
+
statusCode: 500,
|
|
96
|
+
error: "Internal Server Error",
|
|
97
|
+
message: "An internal server error occurred"
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
const mediaLibraryReadRequired = (request) => accessApiError({
|
|
84
102
|
request,
|
|
85
103
|
statusCode: 401,
|
|
86
104
|
statusMessage: "Unauthorized",
|
|
@@ -393,13 +411,15 @@ function grantsError(grants) {
|
|
|
393
411
|
}
|
|
394
412
|
function refusedToken(request, grants) {
|
|
395
413
|
const description = grantsError(grants);
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
414
|
+
return description === void 0 ? void 0 : badRequest(request, description);
|
|
415
|
+
}
|
|
416
|
+
function badRequest(request, description) {
|
|
417
|
+
return new PlatformHttpError({
|
|
418
|
+
...request,
|
|
419
|
+
statusCode: 400,
|
|
420
|
+
statusMessage: "Bad Request",
|
|
421
|
+
body: { error: { description, type: "httpBadRequest" } }
|
|
422
|
+
});
|
|
403
423
|
}
|
|
404
424
|
function createDocumentHistory() {
|
|
405
425
|
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
@@ -462,7 +482,22 @@ function createDocumentHistory() {
|
|
|
462
482
|
function historyIds(list) {
|
|
463
483
|
return list.split(",").map((id) => decodeURIComponent(id));
|
|
464
484
|
}
|
|
465
|
-
const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)
|
|
485
|
+
const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, PROJECT_API_PATHS = [
|
|
486
|
+
/^\/users\/me$/,
|
|
487
|
+
/^\/projects\/[^/]+$/,
|
|
488
|
+
/^\/projects\/[^/]+\/users\/[^/]+$/,
|
|
489
|
+
PROJECT_ROLES_PATH,
|
|
490
|
+
PROJECT_FEATURES_PATH,
|
|
491
|
+
MY_ATTRIBUTES_PATH,
|
|
492
|
+
ACCESS_PATH
|
|
493
|
+
];
|
|
494
|
+
function servedByProjectApi(path) {
|
|
495
|
+
if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
|
|
496
|
+
const matched = matchResourcePath(path);
|
|
497
|
+
if (matched === void 0) return !1;
|
|
498
|
+
const row = capabilitiesOf(matched.resource.type);
|
|
499
|
+
return matched.rest === "" ? row.lookupAtBase : matched.rest === "/acl" && row.acl === "served";
|
|
500
|
+
}
|
|
466
501
|
function page(data) {
|
|
467
502
|
return { data, nextCursor: null };
|
|
468
503
|
}
|
|
@@ -1725,6 +1760,169 @@ function encodeGroqQuery(query, params = {}) {
|
|
|
1725
1760
|
value !== void 0 && search.append(`$${key}`, JSON.stringify(value));
|
|
1726
1761
|
return `?${search}`;
|
|
1727
1762
|
}
|
|
1763
|
+
const SIGNING_METHODS = /* @__PURE__ */ new Set([
|
|
1764
|
+
...["HS", "RS", "PS", "ES"].flatMap((family) => ["256", "384", "512"].map((n) => family + n)),
|
|
1765
|
+
"EdDSA",
|
|
1766
|
+
"none"
|
|
1767
|
+
]), BASE64_URL = /^[A-Za-z0-9_-]$/, TIMED_CLAIMS = ["exp", "iat", "nbf"], UNMODELLED_CLAIMS = ["tokenType", "guid", "s", "z", "audit", "act"];
|
|
1768
|
+
function parseInternalTokenKeys(pems) {
|
|
1769
|
+
return pems.map((pem, index) => {
|
|
1770
|
+
let key;
|
|
1771
|
+
try {
|
|
1772
|
+
key = node_crypto.createPublicKey(pem);
|
|
1773
|
+
} catch {
|
|
1774
|
+
key = void 0;
|
|
1775
|
+
}
|
|
1776
|
+
if (key?.asymmetricKeyType !== "rsa")
|
|
1777
|
+
throw fakeError(
|
|
1778
|
+
`createTestClient(): \`internalTokenKeys[${index}]\` is not an RSA public key PEM.`
|
|
1779
|
+
);
|
|
1780
|
+
return key;
|
|
1781
|
+
});
|
|
1782
|
+
}
|
|
1783
|
+
function isJwtShaped(token) {
|
|
1784
|
+
return token.split(".").length === 3;
|
|
1785
|
+
}
|
|
1786
|
+
function decodeSegment(segment) {
|
|
1787
|
+
const bytes = Buffer.from(segment, "utf8");
|
|
1788
|
+
let digits = 0;
|
|
1789
|
+
for (const [index, byte] of bytes.entries()) {
|
|
1790
|
+
const char = String.fromCharCode(byte);
|
|
1791
|
+
if (!(char === `
|
|
1792
|
+
` || char === "\r")) {
|
|
1793
|
+
if (!BASE64_URL.test(char)) return `illegal base64 data at input byte ${index}`;
|
|
1794
|
+
digits++;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
return digits % 4 === 1 ? `illegal base64 data at input byte ${bytes.length - 1}` : Buffer.from(segment.replace(/[\r\n]/g, ""), "base64url");
|
|
1798
|
+
}
|
|
1799
|
+
const NUMBER_SOURCES = /* @__PURE__ */ new WeakMap();
|
|
1800
|
+
function jsonObject(bytes, segment) {
|
|
1801
|
+
let value;
|
|
1802
|
+
try {
|
|
1803
|
+
value = JSON.parse(bytes.toString("utf8"), function(key, parsed, context) {
|
|
1804
|
+
if (typeof parsed == "number" && context?.source !== void 0) {
|
|
1805
|
+
const holder = this, sources = NUMBER_SOURCES.get(holder) ?? /* @__PURE__ */ new Map();
|
|
1806
|
+
sources.set(key, context.source), NUMBER_SOURCES.set(holder, sources);
|
|
1807
|
+
}
|
|
1808
|
+
return parsed;
|
|
1809
|
+
});
|
|
1810
|
+
} catch {
|
|
1811
|
+
value = void 0;
|
|
1812
|
+
}
|
|
1813
|
+
if (typeof value != "object" || value === null || Array.isArray(value))
|
|
1814
|
+
throw fakeError(
|
|
1815
|
+
`internal token: its ${segment} is not a JSON object. Gradient answers with Go's JSON decoder error there, which the fake does not model.`
|
|
1816
|
+
);
|
|
1817
|
+
return value;
|
|
1818
|
+
}
|
|
1819
|
+
function int64Of(source) {
|
|
1820
|
+
const failed = (reason) => `invalid expiry: expected int64: strconv.ParseInt: parsing ${quoted(source)}: ${reason}`;
|
|
1821
|
+
if (!/^[+-]?[0-9]+$/.test(source)) return failed("invalid syntax");
|
|
1822
|
+
const value = BigInt(source);
|
|
1823
|
+
return value > 2n ** 63n - 1n || value < -(2n ** 63n) ? failed("value out of range") : Number(value);
|
|
1824
|
+
}
|
|
1825
|
+
function signedByAny(signed, signature, keys) {
|
|
1826
|
+
return keys.some((key) => {
|
|
1827
|
+
try {
|
|
1828
|
+
return node_crypto.verify("RSA-SHA256", Buffer.from(signed), key, signature);
|
|
1829
|
+
} catch {
|
|
1830
|
+
return !1;
|
|
1831
|
+
}
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
function jwtError(token, keys) {
|
|
1835
|
+
const [headerSegment, claimsSegment, signatureSegment] = token.split("."), headerBytes = decodeSegment(headerSegment);
|
|
1836
|
+
if (typeof headerBytes == "string")
|
|
1837
|
+
return {
|
|
1838
|
+
error: token.toLowerCase().startsWith("bearer ") ? "tokenstring should not contain 'bearer '" : headerBytes
|
|
1839
|
+
};
|
|
1840
|
+
const header = jsonObject(headerBytes, "header"), claimsBytes = decodeSegment(claimsSegment);
|
|
1841
|
+
if (typeof claimsBytes == "string") return { error: claimsBytes };
|
|
1842
|
+
const claims = jsonObject(claimsBytes, "claims segment"), alg = header.alg;
|
|
1843
|
+
if (typeof alg != "string") return { error: "signing method (alg) is unspecified." };
|
|
1844
|
+
if (!SIGNING_METHODS.has(alg)) return { error: "signing method (alg) is unavailable." };
|
|
1845
|
+
if (alg !== "RS256") return { error: `token uses algorithm ${quoted(alg)}, expected "RS256"` };
|
|
1846
|
+
const signature = decodeSegment(signatureSegment);
|
|
1847
|
+
if (typeof signature == "string") return { error: signature };
|
|
1848
|
+
if (!signedByAny(`${headerSegment}.${claimsSegment}`, signature, keys))
|
|
1849
|
+
return { error: "crypto/rsa: verification error" };
|
|
1850
|
+
const timed = TIMED_CLAIMS.filter((key) => key in claims);
|
|
1851
|
+
if (timed.length > 0)
|
|
1852
|
+
throw fakeError(
|
|
1853
|
+
`internal token: the fake does not model jwt-go's ${timed.map((key) => `"${key}"`).join(", ")} check(s); gradient's tokens expire through "x".`
|
|
1854
|
+
);
|
|
1855
|
+
return { claims };
|
|
1856
|
+
}
|
|
1857
|
+
function identityOf(claims) {
|
|
1858
|
+
const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
|
|
1859
|
+
if (unmodelledClaims.length > 0)
|
|
1860
|
+
throw fakeError(
|
|
1861
|
+
`internal token: the fake does not model the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s); it reads "i", "g" and "x".`
|
|
1862
|
+
);
|
|
1863
|
+
const { i: id, g: grantList = [], x: rawExpiry } = claims;
|
|
1864
|
+
let expiresAt;
|
|
1865
|
+
if (rawExpiry != null) {
|
|
1866
|
+
if (typeof rawExpiry != "number")
|
|
1867
|
+
throw fakeError(
|
|
1868
|
+
`internal token: "x" must be a number of epoch seconds; got ${JSON.stringify(rawExpiry)}. Gradient's answer names Go's type for it, which the fake does not model.`
|
|
1869
|
+
);
|
|
1870
|
+
const parsed = int64Of(NUMBER_SOURCES.get(claims)?.get("x") ?? String(rawExpiry));
|
|
1871
|
+
if (typeof parsed == "string") return { refused: parsed };
|
|
1872
|
+
expiresAt = parsed;
|
|
1873
|
+
}
|
|
1874
|
+
if (id != null && typeof id != "string")
|
|
1875
|
+
return { refused: 'token field "i" must be a string' };
|
|
1876
|
+
let unmodelled;
|
|
1877
|
+
if (typeof id != "string" || id === "" ? unmodelled = `internal token: "i" is ${JSON.stringify(id)}; the fake models a token with an identity only.` : id.startsWith("g") && id !== "god" && (unmodelled = `internal token: identity "${id}" starts with "g", which gradient resolves to a project user through its claims transfer; the fake does not model that.`), !Array.isArray(grantList))
|
|
1878
|
+
throw fakeError(
|
|
1879
|
+
`internal token: "g" must be a list of { s, p } grants; got ${JSON.stringify(grantList)}.`
|
|
1880
|
+
);
|
|
1881
|
+
const grants = grantList.map((entry) => {
|
|
1882
|
+
const { s: path, p: permissions } = entry ?? {};
|
|
1883
|
+
if (typeof path != "string" || !Array.isArray(permissions) || !permissions.every((permission) => typeof permission == "string"))
|
|
1884
|
+
throw fakeError(
|
|
1885
|
+
`internal token: each grant must be { s: string, p: string[] }; got ${JSON.stringify(entry)}.`
|
|
1886
|
+
);
|
|
1887
|
+
return { path, permissions };
|
|
1888
|
+
}), refused = grantsError(grants);
|
|
1889
|
+
return refused !== void 0 ? { refused } : {
|
|
1890
|
+
identity: { user: { id: typeof id == "string" ? id : "" }, grants },
|
|
1891
|
+
expiresAt,
|
|
1892
|
+
...unmodelled !== void 0 ? { unmodelled } : {}
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
function checkInternalToken(token, keys) {
|
|
1896
|
+
const parsed = jwtError(token, keys);
|
|
1897
|
+
return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
|
|
1898
|
+
}
|
|
1899
|
+
function goTime(epochSeconds) {
|
|
1900
|
+
const date = new Date(epochSeconds * 1e3);
|
|
1901
|
+
if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
|
|
1902
|
+
throw fakeError(
|
|
1903
|
+
`internal token: "x" ${epochSeconds} is before year 1000; Go's formatting of it is not modelled.`
|
|
1904
|
+
);
|
|
1905
|
+
const iso = date.toISOString();
|
|
1906
|
+
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} +0000 UTC`;
|
|
1907
|
+
}
|
|
1908
|
+
function internalTokenRefusal(request, check) {
|
|
1909
|
+
if ("refused" in check) return badRequest(request, check.refused);
|
|
1910
|
+
if (check.expiresAt === void 0 || Date.now() < check.expiresAt * 1e3) {
|
|
1911
|
+
if (check.unmodelled !== void 0) throw fakeError(check.unmodelled);
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
return new PlatformHttpError({
|
|
1915
|
+
...request,
|
|
1916
|
+
statusCode: 403,
|
|
1917
|
+
statusMessage: "Forbidden",
|
|
1918
|
+
body: {
|
|
1919
|
+
error: {
|
|
1920
|
+
description: `Token has expired (at ${goTime(check.expiresAt)})`,
|
|
1921
|
+
type: "permissionDeniedError"
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1728
1926
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
1729
1927
|
"fetch",
|
|
1730
1928
|
"getDocument",
|
|
@@ -1932,11 +2130,16 @@ function serializeWrite(backend, run) {
|
|
|
1932
2130
|
}
|
|
1933
2131
|
), result;
|
|
1934
2132
|
}
|
|
2133
|
+
function internalToken(backend, token) {
|
|
2134
|
+
if (backend.identities.has(token) || backend.internalTokenKeys.length === 0 || !isJwtShaped(token)) return;
|
|
2135
|
+
let check = backend.internalTokens.get(token);
|
|
2136
|
+
return check === void 0 && (check = checkInternalToken(token, backend.internalTokenKeys), backend.internalTokens.set(token, check)), check;
|
|
2137
|
+
}
|
|
1935
2138
|
function requireIdentity(backend, token, site) {
|
|
1936
|
-
if (backend.identities.has(token)) return;
|
|
2139
|
+
if (backend.identities.has(token) || internalToken(backend, token) !== void 0) return;
|
|
1937
2140
|
const known = [...backend.identities.keys()];
|
|
1938
2141
|
throw fakeError(
|
|
1939
|
-
`${site}: unknown token "${token}" \u2014 no identity is registered for it. ` + (known.length > 0 ? `Registered tokens: ${known.map((t) => `"${t}"`).join(", ")}. ` : "No identities are registered. ") + "Register identities via createTestClient({ identities }) or client.addIdentity(token, identity)."
|
|
2142
|
+
`${site}: unknown token "${token}" \u2014 no identity is registered for it. ` + (known.length > 0 ? `Registered tokens: ${known.map((t) => `"${t}"`).join(", ")}. ` : "No identities are registered. ") + "Register identities via createTestClient({ identities }) or client.addIdentity(token, identity)" + (backend.internalTokenKeys.length > 0 ? ", or pass a JWT for the internal-token keys." : ", or set createTestClient({ internalTokenKeys }) to verify JWTs.")
|
|
1940
2143
|
);
|
|
1941
2144
|
}
|
|
1942
2145
|
function rejectAmbiguousIdentity(site, config) {
|
|
@@ -1987,6 +2190,9 @@ function createTestClient(options = {}) {
|
|
|
1987
2190
|
concurrentEdits: /* @__PURE__ */ new Map(),
|
|
1988
2191
|
identities: new Map(Object.entries(options.identities ?? {})),
|
|
1989
2192
|
revoked: /* @__PURE__ */ new Set(),
|
|
2193
|
+
internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
|
|
2194
|
+
internalTokens: /* @__PURE__ */ new Map(),
|
|
2195
|
+
outages: /* @__PURE__ */ new Set(),
|
|
1990
2196
|
writeChain: Promise.resolve()
|
|
1991
2197
|
}, registry = backend.registry;
|
|
1992
2198
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -2085,7 +2291,9 @@ function makeHandle(handleArgs) {
|
|
|
2085
2291
|
configuredPerspective
|
|
2086
2292
|
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
2087
2293
|
if (token === void 0) return accessControl;
|
|
2088
|
-
const identity = backend.identities.get(token);
|
|
2294
|
+
const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
|
|
2295
|
+
if (verified !== void 0 && "refused" in verified)
|
|
2296
|
+
return { currentUser: { id: "" }, grants: [] };
|
|
2089
2297
|
if (identity === void 0)
|
|
2090
2298
|
throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
|
|
2091
2299
|
return {
|
|
@@ -2101,13 +2309,27 @@ function makeHandle(handleArgs) {
|
|
|
2101
2309
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
2102
2310
|
return access;
|
|
2103
2311
|
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2104
|
-
if (token === void 0) return;
|
|
2312
|
+
if (token === void 0 || internal() !== void 0) return;
|
|
2105
2313
|
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2106
2314
|
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2107
2315
|
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2108
2316
|
throw sessionHostMismatch(request);
|
|
2109
|
-
},
|
|
2110
|
-
|
|
2317
|
+
}, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
|
|
2318
|
+
const check = internal();
|
|
2319
|
+
if (check === void 0) return;
|
|
2320
|
+
const refusal = internalTokenRefusal(request, check);
|
|
2321
|
+
if (refusal !== void 0) throw refusal;
|
|
2322
|
+
}, withSession = (request) => async (opts) => {
|
|
2323
|
+
const sent = rawRequest(opts);
|
|
2324
|
+
if (internal() !== void 0 && servedByProjectApi(sent.path))
|
|
2325
|
+
throw fakeError(
|
|
2326
|
+
`request(): "${sent.path}" with an internal token. The project API (populus) verifies internal tokens with its own key and answers differently from the Content Lake; the fake does not model that. Use a registered identity's token there.`
|
|
2327
|
+
);
|
|
2328
|
+
if (refuseSession(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2329
|
+
throw projectApiDown(sent);
|
|
2330
|
+
return request(opts);
|
|
2331
|
+
}, admitToLake = (request) => {
|
|
2332
|
+
refuseSession(request), refuseInternalToken(request);
|
|
2111
2333
|
const access = activeAccess();
|
|
2112
2334
|
if (access === void 0) return;
|
|
2113
2335
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2670,8 +2892,15 @@ function makeHandle(handleArgs) {
|
|
|
2670
2892
|
},
|
|
2671
2893
|
identities: () => Object.fromEntries(backend.identities),
|
|
2672
2894
|
revokeIdentity: (revokedToken) => {
|
|
2895
|
+
if (!backend.identities.has(revokedToken) && internalToken(backend, revokedToken) !== void 0)
|
|
2896
|
+
throw fakeError(
|
|
2897
|
+
"revokeIdentity(): an internal token has no session to revoke; mint one whose `x` has passed to get the Content Lake's expired-token answer."
|
|
2898
|
+
);
|
|
2673
2899
|
requireIdentity(backend, revokedToken, "revokeIdentity()"), backend.revoked.add(revokedToken);
|
|
2674
2900
|
},
|
|
2901
|
+
simulateOutage: (component) => {
|
|
2902
|
+
backend.outages.add(component);
|
|
2903
|
+
},
|
|
2675
2904
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2676
2905
|
transactions: () => [...backend.log],
|
|
2677
2906
|
clearLog: () => {
|
|
@@ -2705,6 +2934,7 @@ function makeHandle(handleArgs) {
|
|
|
2705
2934
|
exports.ERR_PREFIX = ERR_PREFIX;
|
|
2706
2935
|
exports.GuardDeniedError = GuardDeniedError;
|
|
2707
2936
|
exports.PlatformHttpError = PlatformHttpError;
|
|
2937
|
+
exports.PlatformServerError = PlatformServerError;
|
|
2708
2938
|
exports.SUPPORTED_SURFACE = SUPPORTED_SURFACE;
|
|
2709
2939
|
exports.UNSUPPORTED_MEMBERS = UNSUPPORTED_MEMBERS;
|
|
2710
2940
|
exports.WriteAccessDeniedError = WriteAccessDeniedError;
|