@sanity-labs/client-fake-for-test 0.17.3 → 0.19.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 CHANGED
@@ -7,6 +7,8 @@
7
7
  npm install -D @sanity-labs/client-fake-for-test
8
8
  ```
9
9
 
10
+ `@sanity/client` (7.21 or later, or 8) is a peer dependency: the fake's HTTP errors extend its `ClientError`, so they need the copy your code imports. See [Errors are `ClientError`s](#errors-are-clienterrors).
11
+
10
12
  ## What this is for
11
13
 
12
14
  Any code typed against `SanityClient` (or a narrow subset of its methods) that you want to test without:
@@ -101,7 +103,7 @@ More patterns — passing the fake to code typed against `SanityClient`, asserti
101
103
 
102
104
  `createTestClient({ mutationGuard })` installs a pluggable write interceptor. It runs once for each document's net change in a commit through the document mutation API — `create` / `createOrReplace` / `createIfNotExists` / `patch` / `delete` and the equivalent `transaction()` / `mutate()` operations. Document publish and unpublish actions are expanded into their published and draft mutations. Release and version actions (`releases.*`, `createVersion`, and `unpublishVersion`) are not intercepted.
103
105
 
104
- The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws a 403-shaped `GuardDeniedError` with `type: "guardDeniedError"` and `denials`. Other thrown callback errors propagate unchanged.
106
+ The client owns the _seam_; the caller owns the _policy_. This is the hook a workflow test bench uses to enforce Content Lake **mutation guards** at the write path without re-implementing guard evaluation. Each call receives the original/final image (`before` is `null` on create, `after` is `null` on delete), the `action`, and the acting `identity`. Return every denying guard as `{ guardID, name? }`; the fake evaluates every net document mutation, aggregates the returned denials, deduplicates them by `guardID` in first-observed order, rolls back the commit, and throws `GuardDeniedError`: the Content Lake's 403, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)), with `type: "guardDeniedError"` and `denials` on it. Other thrown callback errors propagate unchanged.
105
107
 
106
108
  ```ts
107
109
  const client = createTestClient({
@@ -151,7 +153,7 @@ The fake tells apart two kinds of bad token:
151
153
  - **Unknown** (never registered): binding it (`createTestClient({ token })`, `withConfig({ token })`) throws at once. That is a mistake in the test setup, not something production answers.
152
154
  - **Revoked** (`client.revokeIdentity(token)`): models a token the platform has no session for any more, because it was revoked, expired or deleted. The token stays registered and still binds, as production clients accept any string. From the next request on, every request made with it on any handle in the family is refused: `fetch`, `getDocument(s)`, every mutation, transaction and action (release and version actions included), `releases.get` / `releases.fetchDocuments`, and `request()` (`/users/me`, the ACL, the project and Access APIs, the History API). Nothing is written, and a write already queued is refused when its turn comes. Requests made before the call keep their answers, so "the first read succeeds, then the token is refused" is `await read(); client.revokeIdentity(token);`. Revocation is permanent; `addIdentity` does not restore the token.
153
155
 
154
- The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError` shaped like `@sanity/client`'s `ClientError`:
156
+ The refusal is the platform's answer, probed on staging and production, raised as a `PlatformHttpError`, a `ClientError` (see [Errors are `ClientError`s](#errors-are-clienterrors)):
155
157
 
156
158
  ```ts
157
159
  {
@@ -164,7 +166,7 @@ The refusal is the platform's answer, probed on staging and production, raised a
164
166
  statusMessage: "Unauthorized",
165
167
  method: "GET", // or "POST" for mutations and actions
166
168
  url: "/data/query/test", // the API path, without host or version
167
- headers: {},
169
+ headers: { "content-type": "application/json; charset=utf-8" },
168
170
  body: { error: "Unauthorized", errorCode: "SIO-401-ANF", message: "Session not found", statusCode: 401 },
169
171
  },
170
172
  }
@@ -172,6 +174,26 @@ The refusal is the platform's answer, probed on staging and production, raised a
172
174
 
173
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.
174
176
 
177
+ #### Project-scoped tokens: membership and refusals
178
+
179
+ A robot token belongs to the project that issued it. Model one with `projectId` on the identity:
180
+
181
+ ```ts
182
+ createTestClient({
183
+ identities: { "t-robot": { user: { id: "p-robot" }, grants, projectId: "p1" } },
184
+ });
185
+ ```
186
+
187
+ Such an identity is a member of `p1` only. Without `projectId` (the default, and how the fake behaved before) an identity is a member of every project and accepted on every host. A project-scoped identity is refused the way staging refuses an Editor robot of another project (EDEX-3204), each as a `PlatformHttpError`:
188
+
189
+ | Request | Answer |
190
+ | --- | --- |
191
+ | Any request on another project's host: a handle with `projectId: "p2"`, project-hosted (queries, documents, writes, actions, `request()`) | 401 `{ statusCode: 401, errorCode: "SIO-401-AWH", error: "Unauthorized", message: "Session does not match project host" }` |
192
+ | `GET /projects/<other or unknown project>/features` (global host) | 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be a member of this project to perform this operation" }` |
193
+ | `/projects/<other project>` and `/projects/<other project>/users/<ids>` | The identity is not listed among the members |
194
+
195
+ Membership of a Media Library or Canvas is not a project matter; their ACLs answer as in [Resource types](#resource-types-media-library-canvas-dashboard).
196
+
175
197
  #### Token grants: filters and paths
176
198
 
177
199
  A grant is either a GROQ `filter`, as a project's ACL serves it, or a `path` glob, as a token carries it (an internal token's `{ s, p }` grant is `{ path: s, permissions: p }`). The Content Lake holds a grant as one or the other and evaluates a path grant as `_id in path("<path>")` (gradient `pkg/security/models.go`): the id's dot-separated elements compare literally, `*` matches one element and a trailing `**` one or more. The fake matches `{ path }` grants the same way. A `path()` call inside a GROQ query or a `{ filter }` grant still runs through groq-js, which matches `.` there as any character:
@@ -210,6 +232,8 @@ Filter grants come from the ACL, not the token, and are not checked. `/users/me`
210
232
 
211
233
  The fake checks every written document the way the Content Lake does (gradient `pkg/security/document_permission_checker.go`): a create needs `create` on the new document; an update, replace or patch needs `update` on the document before the write **and** on the document after it; a delete needs `update` on the document before. So a patch or `createOrReplace` that moves a document out of the identity's `update` grant (a filter it stops matching) is refused with `WriteAccessDeniedError`, and nothing is written. The same holds for `version.create` replacing a version and for the documents `document.publish` / `document.unpublish` write and delete. A transaction, `mutate` or action batch is checked per document on its net change once every mutation is staged, so a document patched out of the grant and back again in one transaction passes, and one created and deleted in it is not checked. Reads inside a write are not checked.
212
234
 
235
+ The refusal is the Content Lake's 403, a `ClientError` with the `insufficientPermissionsError` wrapped in a `mutationError`, as gradient writes it; `message` is `transaction failed: Insufficient permissions; permission "update" required` followed by the item. The error also carries `documentId`, `permission` and `matchingGrants`, which the platform's answer does not name.
236
+
213
237
  #### System-document grants
214
238
 
215
239
  User-issued writes to system document IDs beginning with `_.` require the `manage` permission **in addition to** the `create` or `update` the write needs, each checked on the same documents (before and after the write), as the Content Lake's permission checker does. `create` and `update` alone do not authorize these writes, and neither does `manage` alone; grant `manage` alongside `create` / `update` to identities whose tests intentionally create, replace, patch, delete, transact, mutate, publish, or unpublish system documents. The fake's internal release/version bookkeeping remains outside access-control interception.
@@ -261,7 +285,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
261
285
  | `drafts.` / `versions.` ids, perspectives | ✅ | ✅ | ✅ | ✅ |
262
286
  | `/actions` (releases, version and document actions) | ✅ | ✅, except `release.create` → 403 `releaseLimitExceededError` | 404 `Cannot POST …/actions` | 404 `Cannot POST …/actions` |
263
287
  | History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
264
- | ACL `<data base>/acl` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
288
+ | ACL `<data base>/acl` | ✅ | ✅ with `sanity.media-library.read`, else 401; unknown id 404 `Media library not found` | ✅; unknown id 404 `Resource not found` | 404 `Cannot GET …` |
265
289
  | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
266
290
  | Access API `…/users` | ✅ | ✅ | 403 | 403 |
267
291
  | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
@@ -269,7 +293,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
269
293
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
270
294
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
271
295
 
272
- - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a project member with its project roles. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id the registry does not hold (never seeded, written or addressed) answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
296
+ - **Access API.** Paths are `/access/<type>/<id>/…` with type `organization`, `project`, `media-library`, `canvas` or `dashboard`. An identity's `access` entries, keyed `"<type>:<id>"`, hold its `roles` there (membership) and the `permissions` the `user-permissions` endpoints report. Every identity is a member of every project with its project roles, except a project-scoped one (`projectId`, see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)), which is a member of its own project only. A user row is `{ sanityUserId, profile: { id, displayName, email, provider, createdAt }, memberships: [{ resourceType, resourceId, roleNames }] }`; the fake does not model `provider` or `createdAt`, so they are always `"sanity"` and the epoch, and `email` is `""` where the identity seeds none. Listings come back on one page (`nextCursor: null`); users listings add `totalCount`. `includeImpliedRoles` is accepted and ignored: rows carry the seeded roles only, so seed an implied role explicitly when a test needs it. An unknown type answers 400 `Invalid resource type <type>`. An id the registry does not hold (never seeded, written or addressed) answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. `…/users/<sanityUserId>` is served only on the organization, where the fake checks members read; elsewhere it answers 403 (the reference requires `sanity.<type>.members.read` for it; no type's single-user read was probed on staging, only the media-library listing). The other 403 cells were not proven on staging (no token could list them), so they answer the way the platform refuses a missing permission: `{ statusCode: 403, error: "Forbidden", message: "You do not have permission to access this resource" }`.
273
297
  - **Members.** Every member listing (`/projects/<projectId>`, `…/users`, `…/roles`) sees the registered identities plus, on a handle created with inline `accessControl`, that handle's own actor. Inline config belongs to its handle: a token sibling does not see it.
274
298
  - **Roles.** `…/roles` answers `{ data: [role], nextCursor: null }` and `…/roles/<roleName>` one role (404 `Role not found` for a name no member holds). A role is `{ name, title, description?, resourceType, resourceId, appliesToUsers, appliesToRobots, permissions }`, collected from the roles the members hold on the resource. The fake does not model role definitions, so `title` is the name where the seed gives none, both `appliesTo…` flags are `true` and `permissions` is `[]`. A media library serves its roles only to an actor whose `"media-library:<id>"` entry holds `sanity.media-library.roles.read` in `permissions`, else 403, as the reference requires. Likewise a project serves its roles only to an actor whose `"project:<id>"` entry holds `sanity.project.roles.read` (on staging every stock user role holds it), else 403.
275
299
  - **Project role catalog.** `GET /projects/<projectId>/roles` answers the older projects API's bare array, one row per role the project's members hold: `{ name, title, description?, projectId, appliesToUsers, appliesToRobots }`, with the same unmodelled defaults as the Access API rows. The platform also sends `isCustom` and a `grants` tree per role; the fake does not model role definitions, so it omits both. It needs `sanity.project.roles.read` on the actor's `"project:<projectId>"` entry, else 403 with the Access API's permission body.
@@ -277,9 +301,22 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
277
301
  - **User attributes.** `GET /organizations/<organizationId>/users/me/attributes` answers the caller's own attributes there: `{ sanityUserId, organizationId, attributes: [{ type, key, values: { saml?, sanity? }, activeSource, activeValue }] }`, ordered by key. Seed them as `attributes: [{ key, type, values }]` on the identity's `"organization:<id>"` entry; the Sanity value takes precedence over the SAML one for `activeSource` and `activeValue`, as on the platform. No permission is needed. `limit` (default 50) and `cursor` (the last key of the previous page) page the list. A member with no seeded attributes gets `attributes: []`; a caller without roles in the organization gets 404 `User not found`, and another organization id 404 `Organization not found`.
278
302
  - **History.** Every committed write since the client was created is recorded per resource, authored by the acting identity; seeded documents can be read at their seeded `_rev`. A handle answers for its own resource, and hides documents its grants cannot read, as reads do (a transaction that also touched such a document is served without it). Events model `createLiveDocument` / `updateLiveDocument` only.
279
303
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
280
- - **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Like `/projects/<projectId>`, it answers any project id to any acting identity: the platform lets any project member read it, and every identity is a member of every project.
304
+ - **Project features.** `GET /projects/<projectId>/features` answers the project's feature names as a bare array, sorted and once each, as the project API does. Seed them with `createTestClient({ projectFeatures: { "<projectId>": ["advancedRolesManagement"] } })`; a project without an entry has no features and answers `[]`. Only a project member may read it, as on the platform: an identity without `projectId` reads every project's features, and a project-scoped one only its own project's, with 401 `User must be a member of this project to perform this operation` for any other (see [Project-scoped tokens](#project-scoped-tokens-membership-and-refusals)).
305
+ - **ACL refusals.** A Media Library's ACL needs `sanity.media-library.read` in the actor's `"media-library:<id>"` `permissions`, else 401 `{ statusCode: 401, error: "Unauthorized", message: "User must be able to read media libraries for this organization to perform this operation" }`. A Media Library or Canvas id the registry does not hold (never seeded, written or addressed by a handle) answers 404 `{ statusCode: 404, error: "Not Found", message: "Media library not found" }` / `{ …, message: "Resource not found" }`. That is the platform's answer for an unknown resource on a route it mounts, distinct from the `Cannot GET …` text body of a route it does not mount (a dashboard's ACL). An explicit `accessControl.aclPath` naming one of these ACLs is refused the same way.
281
306
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
282
307
 
308
+ ### Errors are `ClientError`s
309
+
310
+ Every error the fake throws for an HTTP answer of the platform is an instance of `@sanity/client`'s `ClientError`, so code that branches on `error instanceof ClientError` handles it as it handles production's:
311
+
312
+ | Class | Answer |
313
+ | --- | --- |
314
+ | `PlatformHttpError` | the platform's refusals: a revoked token's 401, a token grant the Content Lake cannot parse (400), the Access API's 400/403/404, a route a resource does not mount (404), a Media Library release (403), an action's failed `if…RevisionId` precondition (409 `documentRevisionIDDoesNotMatchError`, or 404 `documentNotFoundError` when the document is missing) |
315
+ | `WriteAccessDeniedError` | a write the grants do not permit (403) |
316
+ | `GuardDeniedError` | a write a mutation guard denies (403) |
317
+
318
+ 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`).
319
+
283
320
  ### Test-only helpers (not on real `SanityClient`)
284
321
 
285
322
  Useful in test bodies, but a giveaway that the code under test isn't using the real client. Keep them in the test file, not in the code being tested.