@sanity-labs/client-fake-for-test 0.18.0 → 0.20.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 +24 -3
- package/dist/index.cjs +103 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +103 -32
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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` | ✅ | ✅ |
|
|
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
|
|
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 that does not exist answers 404 `Media library not found` / `Canvas not found` / `Dashboard not found`, except `…/me/check`, which answers `false` as staging does. A Media Library, Canvas or dashboard exists once it is seeded (`resources`, `documents`, or `seed()` / `add()` on its handle or its `store()`) or written to through the fake; pointing a client at it (`withConfig({ resource })`) does not create it, as on the platform. `…/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 `[]`.
|
|
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 that does not exist (never seeded or written to; a client pointed at it does not create it) 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
|
-
//
|
|
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.
|
|
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
|
-
}),
|
|
876
|
+
}), byId = consistentProjectRecords({ projectId: args.pathProjectId, records });
|
|
831
877
|
return {
|
|
832
878
|
...args.organizationId !== void 0 ? { organizationId: args.organizationId } : {},
|
|
833
|
-
members: [...
|
|
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
|
|
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({
|
|
@@ -1869,7 +1915,16 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
|
|
|
1869
1915
|
function ensureEntry(registry, resource) {
|
|
1870
1916
|
const key = registryKey(resource);
|
|
1871
1917
|
let entry = registry.get(key);
|
|
1872
|
-
return entry === void 0 && (entry = {
|
|
1918
|
+
return entry === void 0 && (entry = {
|
|
1919
|
+
resource,
|
|
1920
|
+
store: createTestStore(),
|
|
1921
|
+
history: createDocumentHistory(),
|
|
1922
|
+
exists: !1
|
|
1923
|
+
}, registry.set(key, entry)), entry;
|
|
1924
|
+
}
|
|
1925
|
+
function seedEntry(registry, resource, documents) {
|
|
1926
|
+
const entry = ensureEntry(registry, resource);
|
|
1927
|
+
entry.store.seed(documents), entry.exists = !0;
|
|
1873
1928
|
}
|
|
1874
1929
|
function createTestClient(options = {}) {
|
|
1875
1930
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
@@ -1886,16 +1941,16 @@ function createTestClient(options = {}) {
|
|
|
1886
1941
|
}, registry = backend.registry;
|
|
1887
1942
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
1888
1943
|
const root = options.resource ?? datasetResource(defaultProjectId, defaultDataset);
|
|
1889
|
-
|
|
1944
|
+
seedEntry(registry, root, options.documents);
|
|
1890
1945
|
}
|
|
1891
1946
|
if (options.datasets)
|
|
1892
1947
|
for (const [key, docs] of Object.entries(options.datasets)) {
|
|
1893
1948
|
const { projectId, dataset } = parseDatasetKey(key);
|
|
1894
|
-
|
|
1949
|
+
seedEntry(registry, datasetResource(projectId, dataset), docs);
|
|
1895
1950
|
}
|
|
1896
1951
|
if (options.resources)
|
|
1897
1952
|
for (const [key, docs] of Object.entries(options.resources))
|
|
1898
|
-
|
|
1953
|
+
seedEntry(registry, parseResourceKey(key), docs);
|
|
1899
1954
|
return makeHandle({
|
|
1900
1955
|
backend,
|
|
1901
1956
|
projectId: defaultProjectId,
|
|
@@ -1987,10 +2042,14 @@ function makeHandle(handleArgs) {
|
|
|
1987
2042
|
if (access === void 0)
|
|
1988
2043
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
1989
2044
|
return access;
|
|
1990
|
-
},
|
|
1991
|
-
if (token
|
|
1992
|
-
|
|
1993
|
-
|
|
2045
|
+
}, projectHosted = useProjectHostname && resource === void 0, refuseSession = (request) => {
|
|
2046
|
+
if (token === void 0) return;
|
|
2047
|
+
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2048
|
+
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
2049
|
+
if (projectHosted && tokenProjectId !== void 0 && tokenProjectId !== projectId)
|
|
2050
|
+
throw sessionHostMismatch(request);
|
|
2051
|
+
}, withSession = (request) => async (opts) => (refuseSession({ method: "GET", path: opts.uri ?? opts.url ?? "" }), request(opts)), admitToLake = (request) => {
|
|
2052
|
+
refuseSession(request);
|
|
1994
2053
|
const access = activeAccess();
|
|
1995
2054
|
if (access === void 0) return;
|
|
1996
2055
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2005,7 +2064,18 @@ function makeHandle(handleArgs) {
|
|
|
2005
2064
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2006
2065
|
}
|
|
2007
2066
|
] : []
|
|
2008
|
-
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id),
|
|
2067
|
+
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, publicStore = {
|
|
2068
|
+
...store,
|
|
2069
|
+
seed: (documents) => {
|
|
2070
|
+
store.seed(documents), targetEntry.exists = !0;
|
|
2071
|
+
},
|
|
2072
|
+
add: (documents) => {
|
|
2073
|
+
store.add(documents), targetEntry.exists = !0;
|
|
2074
|
+
},
|
|
2075
|
+
put: (doc) => {
|
|
2076
|
+
store.put(doc), targetEntry.exists = !0;
|
|
2077
|
+
}
|
|
2078
|
+
}, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
|
|
2009
2079
|
const access = activeAccess();
|
|
2010
2080
|
if (access !== void 0)
|
|
2011
2081
|
return capabilities.identity === "global" ? (access.globalUser ?? access.currentUser).id : access.currentUser.id;
|
|
@@ -2019,7 +2089,7 @@ function makeHandle(handleArgs) {
|
|
|
2019
2089
|
beforeWrite = void 0, writeRequest = DEFAULT_WRITE;
|
|
2020
2090
|
}
|
|
2021
2091
|
}), commitHistory = (transactionId) => {
|
|
2022
|
-
beforeWrite !== void 0 && history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() });
|
|
2092
|
+
beforeWrite !== void 0 && (targetEntry.exists = !0, history.commit({ transactionId, author: actorId(), before: beforeWrite, after: store.all() }));
|
|
2023
2093
|
}, record = (transactionId, mutations, tag) => {
|
|
2024
2094
|
const effectiveTag = effectiveRequestTag(tag);
|
|
2025
2095
|
commitHistory(transactionId), backend.log.push({
|
|
@@ -2175,7 +2245,7 @@ function makeHandle(handleArgs) {
|
|
|
2175
2245
|
);
|
|
2176
2246
|
}, runAction = async (actions) => {
|
|
2177
2247
|
const request = lakeRequest("POST", "actions");
|
|
2178
|
-
if (
|
|
2248
|
+
if (refuseSession(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2179
2249
|
return write(async () => {
|
|
2180
2250
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2181
2251
|
const refused = capabilities.refusedActions[action.actionType];
|
|
@@ -2382,9 +2452,7 @@ function makeHandle(handleArgs) {
|
|
|
2382
2452
|
request: withSession(
|
|
2383
2453
|
makeRequestImpl({
|
|
2384
2454
|
getAccess: requireActiveAccess,
|
|
2385
|
-
|
|
2386
|
-
// client to the global API host.
|
|
2387
|
-
useProjectHostname: useProjectHostname && resource === void 0,
|
|
2455
|
+
useProjectHostname: projectHosted,
|
|
2388
2456
|
organizationId: backend.organizationId,
|
|
2389
2457
|
listIdentities: members,
|
|
2390
2458
|
platform: {
|
|
@@ -2403,8 +2471,11 @@ function makeHandle(handleArgs) {
|
|
|
2403
2471
|
return access.globalUser ?? access.currentUser;
|
|
2404
2472
|
},
|
|
2405
2473
|
actorAccess: () => requireActiveAccess().access,
|
|
2474
|
+
actorProjectId: () => token === void 0 ? void 0 : backend.identities.get(token)?.projectId,
|
|
2406
2475
|
identities: members,
|
|
2407
|
-
|
|
2476
|
+
// A dataset stands for its project, and every project exists in
|
|
2477
|
+
// the fake, so a dataset handle still counts as before.
|
|
2478
|
+
resources: () => [...registry.values()].filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
|
|
2408
2479
|
}
|
|
2409
2480
|
})
|
|
2410
2481
|
)
|
|
@@ -2435,11 +2506,11 @@ function makeHandle(handleArgs) {
|
|
|
2435
2506
|
hasProjectId: hasProjectId || config.projectId !== void 0
|
|
2436
2507
|
});
|
|
2437
2508
|
},
|
|
2438
|
-
seed: (documents) =>
|
|
2439
|
-
add: (documents) =>
|
|
2509
|
+
seed: (documents) => publicStore.seed(documents),
|
|
2510
|
+
add: (documents) => publicStore.add(documents),
|
|
2440
2511
|
reset: () => store.reset(),
|
|
2441
2512
|
snapshot: () => store.snapshot(),
|
|
2442
|
-
store: () =>
|
|
2513
|
+
store: () => publicStore,
|
|
2443
2514
|
simulateConcurrentEdit: (id, count = 1) => {
|
|
2444
2515
|
const editKey = concurrentEditKey(id);
|
|
2445
2516
|
backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
|