@sanity-labs/client-fake-for-test 0.18.0 → 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
@@ -174,6 +174,26 @@ 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
+ #### 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
+
177
197
  #### Token grants: filters and paths
178
198
 
179
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:
@@ -265,7 +285,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
265
285
  | `drafts.` / `versions.` ids, perspectives | ✅ | ✅ | ✅ | ✅ |
266
286
  | `/actions` (releases, version and document actions) | ✅ | ✅, except `release.create` → 403 `releaseLimitExceededError` | 404 `Cannot POST …/actions` | 404 `Cannot POST …/actions` |
267
287
  | History: `documents/<ids>?revision=`, `transactions/<ids>` (NDJSON), `events/documents/<ids>` | ✅ | ✅ | ✅ | 404 `Cannot GET …` |
268
- | 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 …` |
269
289
  | Access API `…/user-permissions/me`, `…/me/check` | ✅ | ✅ | ✅ | ✅ |
270
290
  | Access API `…/users` | ✅ | ✅ | 403 | 403 |
271
291
  | Access API `…/users/<sanityUserId>` (served on `organization`, below) | 403 | 403 | 403 | 403 |
@@ -273,7 +293,7 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
273
293
  | Project role catalog `/projects/<projectId>/roles` | ✅ with `sanity.project.roles.read`, else 403 | n/a | n/a | n/a |
274
294
  | Org lookup | `/projects/<projectId>` | `GET /media-libraries/<id>` | `GET /canvases/<id>` | `GET /dashboards/<id>` |
275
295
 
276
- - **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" }`.
277
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.
278
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.
279
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.
@@ -281,7 +301,8 @@ await canvas.releases.create({ releaseId: "r1" }); // 404 Cannot POST /canvases/
281
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`.
282
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.
283
303
  - **Org lookup.** `createTestClient({ organizationId })` names the organization every resource of the client belongs to.
284
- - **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.
285
306
  - **Identity.** `@sanity/client` sends a `resource` client's requests to the global host, so `/users/me` answers `globalUser`.
286
307
 
287
308
  ### Errors are `ClientError`s
package/dist/index.cjs CHANGED
@@ -61,6 +61,26 @@ const sessionNotFound = (request) => new PlatformHttpError({
61
61
  message: "Session not found",
62
62
  statusCode: 401
63
63
  }
64
+ }), sessionHostMismatch = (request) => new PlatformHttpError({
65
+ ...request,
66
+ statusCode: 401,
67
+ statusMessage: "Unauthorized",
68
+ body: {
69
+ statusCode: 401,
70
+ errorCode: "SIO-401-AWH",
71
+ error: "Unauthorized",
72
+ message: "Session does not match project host"
73
+ }
74
+ }), projectMembershipRequired = (request) => accessApiError({
75
+ request,
76
+ statusCode: 401,
77
+ statusMessage: "Unauthorized",
78
+ message: "User must be a member of this project to perform this operation"
79
+ }), mediaLibraryReadRequired = (request) => accessApiError({
80
+ request,
81
+ statusCode: 401,
82
+ statusMessage: "Unauthorized",
83
+ message: "User must be able to read media libraries for this organization to perform this operation"
64
84
  }), noPermission = (request) => accessApiError({
65
85
  request,
66
86
  statusCode: 403,
@@ -116,6 +136,9 @@ function datasetParts(id) {
116
136
  const dot = id.indexOf(".");
117
137
  return { projectId: id.slice(0, dot), dataset: id.slice(dot + 1) };
118
138
  }
139
+ function isProjectMember(tokenProjectId, projectId) {
140
+ return tokenProjectId === void 0 || tokenProjectId === projectId;
141
+ }
119
142
  function accessEntryRoles(type) {
120
143
  return ({ identity, id }) => identity.access?.[accessKey(type, id)]?.roles;
121
144
  }
@@ -150,6 +173,10 @@ const RESOURCE_CAPABILITIES = {
150
173
  lookupAtBase: !0,
151
174
  identity: "global",
152
175
  acl: "served",
176
+ aclRefusals: {
177
+ unknown: notFound("Media library"),
178
+ read: { permission: "sanity.media-library.read", refusal: mediaLibraryReadRequired }
179
+ },
153
180
  history: "served",
154
181
  actions: "served",
155
182
  refusedActions: { "sanity.action.release.create": releaseLimitExceeded },
@@ -162,6 +189,7 @@ const RESOURCE_CAPABILITIES = {
162
189
  lookupAtBase: !0,
163
190
  identity: "global",
164
191
  acl: "served",
192
+ aclRefusals: { unknown: notFound("Resource") },
165
193
  history: "served",
166
194
  actions: notMounted,
167
195
  refusedActions: {},
@@ -244,8 +272,8 @@ const ACCESS_CAPABILITIES = {
244
272
  // Single-user reads are served only where the fake checks members read (the
245
273
  // organization); elsewhere they refuse rather than answer unchecked.
246
274
  user: noPermission,
247
- // Every registered identity is a member of every project, with its project roles.
248
- memberRoles: ({ identity, id }) => (identity.usersByProject?.[id] ?? identity.user).roles ?? []
275
+ // A member holds its project roles; see `isProjectMember`.
276
+ memberRoles: ({ identity, id }) => isProjectMember(identity.projectId, id) ? (identity.usersByProject?.[id] ?? identity.user).roles ?? [] : void 0
249
277
  },
250
278
  "media-library": {
251
279
  // Staging refuses it only because no probe token held roles read.
@@ -452,6 +480,8 @@ async function servePlatformRequest(ctx, url) {
452
480
  const projectFeatures = path.match(PROJECT_FEATURES_PATH);
453
481
  if (projectFeatures !== null) {
454
482
  const projectId = decodeURIComponent(projectFeatures[1]);
483
+ if (!isProjectMember(ctx.actorProjectId(), projectId))
484
+ throw projectMembershipRequired(request);
455
485
  return { value: featuresOf(ctx, projectId) };
456
486
  }
457
487
  const access = path.match(ACCESS_PATH);
@@ -470,12 +500,32 @@ async function servePlatformRequest(ctx, url) {
470
500
  if (rest === "") return row.lookupAtBase ? serveLookup(ctx, resource) : void 0;
471
501
  if (rest === "/acl")
472
502
  return serveCapability(row.acl, request, () => {
503
+ refuseAcl({ ctx, request, resource, row });
473
504
  const own = ctx.own(resource);
474
505
  return own === void 0 ? void 0 : { value: own.grants };
475
506
  });
476
507
  if (rest.startsWith("/history/"))
477
508
  return serveHistory({ ctx, request, resource, rest: rest.slice(8), query });
478
509
  }
510
+ function refuseAclRequest(ctx, url) {
511
+ const queryStart = url.indexOf("?"), path = queryStart === -1 ? url : url.slice(0, queryStart), matched = matchResourcePath(path);
512
+ if (matched?.rest !== "/acl") return;
513
+ const row = capabilitiesOf(matched.resource.type), request = { method: "GET", path };
514
+ serveCapability(
515
+ row.acl,
516
+ request,
517
+ () => refuseAcl({ ctx, request, resource: matched.resource, row })
518
+ );
519
+ }
520
+ function refuseAcl(args) {
521
+ const { ctx, request, resource, row } = args;
522
+ if (row.aclRefusals === void 0) return;
523
+ const type = row.access.type, id = row.access.id(resource.id), registry = { organizationId: ctx.organizationId, resources: ctx.resources };
524
+ if (!holdsResource(type)(registry, id)) throw row.aclRefusals.unknown(request);
525
+ const { read } = row.aclRefusals;
526
+ if (read !== void 0 && !(ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? []).includes(read.permission))
527
+ throw read.refusal(request);
528
+ }
479
529
  function featuresOf(ctx, projectId) {
480
530
  const features = Object.hasOwn(ctx.projectFeatures, projectId) ? ctx.projectFeatures[projectId] : [];
481
531
  return [...new Set(features)].toSorted();
@@ -758,12 +808,6 @@ async function enforceWriteAccess(args) {
758
808
  function defaultAclPath(projectId, dataset) {
759
809
  return `/projects/${projectId}/datasets/${dataset}/acl`;
760
810
  }
761
- function refusedAcl(path) {
762
- const matched = matchResourcePath(path);
763
- if (matched?.rest !== "/acl") return;
764
- const { acl } = capabilitiesOf(matched.resource.type);
765
- return acl === "served" ? void 0 : acl({ method: "GET", path });
766
- }
767
811
  function projectUserOf(identity, projectId) {
768
812
  return identity.usersByProject?.[projectId] ?? identity.user;
769
813
  }
@@ -800,7 +844,7 @@ function serveProjectUsers(args) {
800
844
  };
801
845
  }, byId = consistentProjectRecords({
802
846
  projectId: pathProjectId,
803
- records: identities.map(toRecord)
847
+ records: identities.filter((identity) => isProjectMember(identity.projectId, pathProjectId)).map(toRecord)
804
848
  }), ids = requestedIds.split(","), [firstId] = ids;
805
849
  if (ids.length === 1 && firstId !== void 0) {
806
850
  const record = byId.get(firstId);
@@ -820,17 +864,19 @@ function serveProjectUsers(args) {
820
864
  }
821
865
  const PROJECT_USERS_PATH = /^\/projects\/([^/]+)\/users\/([^/]+)$/, PROJECT_PATH = /^\/projects\/([^/]+)$/;
822
866
  function serveProject(args) {
823
- const records = args.identities.map((identity) => {
867
+ const records = args.identities.filter(
868
+ (identity) => isProjectMember(identity.projectId, args.pathProjectId)
869
+ ).map((identity) => {
824
870
  const projectUser = projectUserOf(identity, args.pathProjectId);
825
871
  return {
826
872
  id: projectUser.id,
827
873
  ...projectUser.id.startsWith("p-") ? { isRobot: !0 } : {},
828
874
  ...projectUser.roles !== void 0 ? { roles: canonicalProjectRoles(projectUser.roles) } : {}
829
875
  };
830
- }), members = consistentProjectRecords({ projectId: args.pathProjectId, records });
876
+ }), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
831
877
  return {
832
878
  ...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
833
- members: [...members.values()]
879
+ members: [...byId.values()]
834
880
  };
835
881
  }
836
882
  function makeRequestImpl(ctx) {
@@ -839,8 +885,8 @@ function makeRequestImpl(ctx) {
839
885
  const accessControl = getAccess(), path = opts.uri ?? opts.url;
840
886
  if (path === "/users/me")
841
887
  return useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
842
- if (path !== void 0 && path === accessControl.aclPath && refusedAcl(path) === void 0)
843
- return accessControl.grants;
888
+ if (path !== void 0 && path === accessControl.aclPath)
889
+ return refuseAclRequest(platform, path), accessControl.grants;
844
890
  const projectUsers = path?.match(PROJECT_USERS_PATH), [, pathProjectId, requestedIds] = projectUsers ?? [];
845
891
  if (pathProjectId !== void 0 && requestedIds !== void 0)
846
892
  return serveProjectUsers({
@@ -1987,10 +2033,14 @@ function makeHandle(handleArgs) {
1987
2033
  if (access === void 0)
1988
2034
  throw fakeError("this handle has no acting identity (no token or accessControl bound).");
1989
2035
  return access;
1990
- }, refuseRevoked = (request) => {
1991
- if (token !== void 0 && backend.revoked.has(token)) throw sessionNotFound(request);
1992
- }, withSession = (request) => async (opts) => (refuseRevoked({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
1993
- refuseRevoked(request);
2036
+ }, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
2037
+ if (token === void 0) return;
2038
+ if (backend.revoked.has(token)) throw sessionNotFound(request);
2039
+ const tokenProjectId = backend.identities.get(token)?.projectId;
2040
+ if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
2041
+ throw sessionHostMismatch(request);
2042
+ }, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
2043
+ refuseSession(request);
1994
2044
  const access = activeAccess();
1995
2045
  if (access === void 0) return;
1996
2046
  const refusal = refusedToken(request, access.grants);
@@ -2175,7 +2225,7 @@ function makeHandle(handleArgs) {
2175
2225
  );
2176
2226
  }, runAction = async (actions) => {
2177
2227
  const request = lakeRequest("POST", "actions");
2178
- if (refuseRevoked(request), capabilities.actions !== "served") throw capabilities.actions(request);
2228
+ if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
2179
2229
  return write(async () => {
2180
2230
  for (const action of Array.isArray(actions) ? actions : [actions]) {
2181
2231
  const refused = capabilities.refusedActions[action.actionType];
@@ -2382,9 +2432,7 @@ function makeHandle(handleArgs) {
2382
2432
  request: withSession(
2383
2433
  makeRequestImpl({
2384
2434
  getAccess: requireActiveAccess,
2385
- // `@sanity/client` sends every request of a `resource`-configured
2386
- // client to the global API host.
2387
- useProjectHostname: useProjectHostname && resource === void 0,
2435
+ useProjectHostname: projectHosted,
2388
2436
  organizationId: backend.organizationId,
2389
2437
  listIdentities: members,
2390
2438
  platform: {
@@ -2403,6 +2451,7 @@ function makeHandle(handleArgs) {
2403
2451
  return access.globalUser ?? access.currentUser;
2404
2452
  },
2405
2453
  actorAccess: () => requireActiveAccess().access,
2454
+ actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
2406
2455
  identities: members,
2407
2456
  resources: () => [...registry.values()].map((entry) => entry.resource)
2408
2457
  }