@sanity-labs/client-fake-for-test 0.27.0 → 0.29.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 +49 -2
- package/dist/index.cjs +216 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +37 -6
- package/dist/index.d.ts +37 -6
- package/dist/index.js +217 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -138,6 +138,14 @@ export declare interface CreateTestClientOptions {
|
|
|
138
138
|
* `/projects/<projectId>` answer as `organizationId`.
|
|
139
139
|
*/
|
|
140
140
|
organizationId?: string;
|
|
141
|
+
/**
|
|
142
|
+
* The organization stores that exist, by organization id, and their
|
|
143
|
+
* status: what `GET /internal/organization-stores?organizationId=<id>`
|
|
144
|
+
* answers. The lookup creates a `provisioning` store for an organization
|
|
145
|
+
* without one; {@link TestClient.completeOrganizationStoreProvisioning}
|
|
146
|
+
* sets it `active`. Each key must be `organizationId`.
|
|
147
|
+
*/
|
|
148
|
+
organizationStores?: Record<string, OrganizationStoreStatus>;
|
|
141
149
|
/**
|
|
142
150
|
* The features each project has, keyed by projectId: what
|
|
143
151
|
* `GET /projects/<projectId>/features` answers, sorted. A project
|
|
@@ -196,6 +204,14 @@ export declare interface CreateTestClientOptions {
|
|
|
196
204
|
* whole `withConfig` family.
|
|
197
205
|
*/
|
|
198
206
|
internalTokenKeys?: string[];
|
|
207
|
+
/**
|
|
208
|
+
* Datasets the platform does not have, as `"<projectId>:<dataset>"` keys.
|
|
209
|
+
* Every Content Lake request on one (queries, documents, mutations,
|
|
210
|
+
* actions, the History API) throws the 404 `Dataset not found` the
|
|
211
|
+
* Content Lake answers, after a refused token's 401. A key here must not
|
|
212
|
+
* also be seeded.
|
|
213
|
+
*/
|
|
214
|
+
missingDatasets?: string[];
|
|
199
215
|
/**
|
|
200
216
|
* Token the root handle is bound to — must name an entry in
|
|
201
217
|
* `identities` (unknown tokens throw), or be a JWT when
|
|
@@ -670,6 +686,9 @@ export declare interface MutationOptions {
|
|
|
670
686
|
tag?: string | null;
|
|
671
687
|
}
|
|
672
688
|
|
|
689
|
+
/** The statuses populus serves a store in. */
|
|
690
|
+
declare type OrganizationStoreStatus = "provisioning" | "active";
|
|
691
|
+
|
|
673
692
|
/** Options for `PatchHandle.commit()`. Only `tag` is meaningful to the fake. */
|
|
674
693
|
export declare interface PatchCommitOptions {
|
|
675
694
|
/** Request tag, recorded on the mutation log entry (`null` = explicit suppression). */
|
|
@@ -930,6 +949,16 @@ export declare type ReleaseState =
|
|
|
930
949
|
|
|
931
950
|
export declare type ReleaseType = "asap" | "scheduled" | "undecided";
|
|
932
951
|
|
|
952
|
+
/** The options `client.request()` takes that the fake reads. */
|
|
953
|
+
declare interface RequestOptions {
|
|
954
|
+
url?: string;
|
|
955
|
+
uri?: string;
|
|
956
|
+
/** Query parameters, appended to the URL after the request tag; an array repeats its key. */
|
|
957
|
+
query?: Record<string, string | string[]>;
|
|
958
|
+
signal?: AbortSignal;
|
|
959
|
+
tag?: string | null;
|
|
960
|
+
}
|
|
961
|
+
|
|
933
962
|
/**
|
|
934
963
|
* What the Access API (`/access/<type>/<id>/…`) answers about one actor on
|
|
935
964
|
* one resource: the roles it holds there (served by `…/users` and collected
|
|
@@ -1045,12 +1074,7 @@ export declare interface TestClient {
|
|
|
1045
1074
|
* actor. Also serves the resource's history, ACL, lookup and Access API
|
|
1046
1075
|
* endpoints, or the platform's refusal where the resource has none.
|
|
1047
1076
|
*/
|
|
1048
|
-
request?: <T>(opts:
|
|
1049
|
-
url?: string;
|
|
1050
|
-
uri?: string;
|
|
1051
|
-
signal?: AbortSignal;
|
|
1052
|
-
tag?: string | null;
|
|
1053
|
-
}) => Promise<T>;
|
|
1077
|
+
request?: <T>(opts: RequestOptions) => Promise<T>;
|
|
1054
1078
|
/**
|
|
1055
1079
|
* `@sanity/client`'s `getDataUrl(operation, path)`: `<resource
|
|
1056
1080
|
* base>/<operation>/<path>` on a `resource`-configured handle,
|
|
@@ -1282,6 +1306,13 @@ export declare interface TestClient {
|
|
|
1282
1306
|
* keeps answering. The outage lasts for the rest of the family's life.
|
|
1283
1307
|
*/
|
|
1284
1308
|
simulateOutage: (component: PlatformComponent) => void;
|
|
1309
|
+
/**
|
|
1310
|
+
* Finish provisioning the organization's store, as populus's provisioning
|
|
1311
|
+
* workflow does in the background: from the next lookup on, the store is
|
|
1312
|
+
* `active`. Throws unless the organization has a `provisioning` store. A
|
|
1313
|
+
* store whose provisioning never completes stays `provisioning`.
|
|
1314
|
+
*/
|
|
1315
|
+
completeOrganizationStoreProvisioning: (organizationId: string) => void;
|
|
1285
1316
|
/**
|
|
1286
1317
|
* Every mutation committed through this client's registry, flattened
|
|
1287
1318
|
* and in order — `create` / `createOrReplace` / `createIfNotExists` /
|
package/dist/index.d.ts
CHANGED
|
@@ -138,6 +138,14 @@ export declare interface CreateTestClientOptions {
|
|
|
138
138
|
* `/projects/<projectId>` answer as `organizationId`.
|
|
139
139
|
*/
|
|
140
140
|
organizationId?: string;
|
|
141
|
+
/**
|
|
142
|
+
* The organization stores that exist, by organization id, and their
|
|
143
|
+
* status: what `GET /internal/organization-stores?organizationId=<id>`
|
|
144
|
+
* answers. The lookup creates a `provisioning` store for an organization
|
|
145
|
+
* without one; {@link TestClient.completeOrganizationStoreProvisioning}
|
|
146
|
+
* sets it `active`. Each key must be `organizationId`.
|
|
147
|
+
*/
|
|
148
|
+
organizationStores?: Record<string, OrganizationStoreStatus>;
|
|
141
149
|
/**
|
|
142
150
|
* The features each project has, keyed by projectId: what
|
|
143
151
|
* `GET /projects/<projectId>/features` answers, sorted. A project
|
|
@@ -196,6 +204,14 @@ export declare interface CreateTestClientOptions {
|
|
|
196
204
|
* whole `withConfig` family.
|
|
197
205
|
*/
|
|
198
206
|
internalTokenKeys?: string[];
|
|
207
|
+
/**
|
|
208
|
+
* Datasets the platform does not have, as `"<projectId>:<dataset>"` keys.
|
|
209
|
+
* Every Content Lake request on one (queries, documents, mutations,
|
|
210
|
+
* actions, the History API) throws the 404 `Dataset not found` the
|
|
211
|
+
* Content Lake answers, after a refused token's 401. A key here must not
|
|
212
|
+
* also be seeded.
|
|
213
|
+
*/
|
|
214
|
+
missingDatasets?: string[];
|
|
199
215
|
/**
|
|
200
216
|
* Token the root handle is bound to — must name an entry in
|
|
201
217
|
* `identities` (unknown tokens throw), or be a JWT when
|
|
@@ -670,6 +686,9 @@ export declare interface MutationOptions {
|
|
|
670
686
|
tag?: string | null;
|
|
671
687
|
}
|
|
672
688
|
|
|
689
|
+
/** The statuses populus serves a store in. */
|
|
690
|
+
declare type OrganizationStoreStatus = "provisioning" | "active";
|
|
691
|
+
|
|
673
692
|
/** Options for `PatchHandle.commit()`. Only `tag` is meaningful to the fake. */
|
|
674
693
|
export declare interface PatchCommitOptions {
|
|
675
694
|
/** Request tag, recorded on the mutation log entry (`null` = explicit suppression). */
|
|
@@ -930,6 +949,16 @@ export declare type ReleaseState =
|
|
|
930
949
|
|
|
931
950
|
export declare type ReleaseType = "asap" | "scheduled" | "undecided";
|
|
932
951
|
|
|
952
|
+
/** The options `client.request()` takes that the fake reads. */
|
|
953
|
+
declare interface RequestOptions {
|
|
954
|
+
url?: string;
|
|
955
|
+
uri?: string;
|
|
956
|
+
/** Query parameters, appended to the URL after the request tag; an array repeats its key. */
|
|
957
|
+
query?: Record<string, string | string[]>;
|
|
958
|
+
signal?: AbortSignal;
|
|
959
|
+
tag?: string | null;
|
|
960
|
+
}
|
|
961
|
+
|
|
933
962
|
/**
|
|
934
963
|
* What the Access API (`/access/<type>/<id>/…`) answers about one actor on
|
|
935
964
|
* one resource: the roles it holds there (served by `…/users` and collected
|
|
@@ -1045,12 +1074,7 @@ export declare interface TestClient {
|
|
|
1045
1074
|
* actor. Also serves the resource's history, ACL, lookup and Access API
|
|
1046
1075
|
* endpoints, or the platform's refusal where the resource has none.
|
|
1047
1076
|
*/
|
|
1048
|
-
request?: <T>(opts:
|
|
1049
|
-
url?: string;
|
|
1050
|
-
uri?: string;
|
|
1051
|
-
signal?: AbortSignal;
|
|
1052
|
-
tag?: string | null;
|
|
1053
|
-
}) => Promise<T>;
|
|
1077
|
+
request?: <T>(opts: RequestOptions) => Promise<T>;
|
|
1054
1078
|
/**
|
|
1055
1079
|
* `@sanity/client`'s `getDataUrl(operation, path)`: `<resource
|
|
1056
1080
|
* base>/<operation>/<path>` on a `resource`-configured handle,
|
|
@@ -1282,6 +1306,13 @@ export declare interface TestClient {
|
|
|
1282
1306
|
* keeps answering. The outage lasts for the rest of the family's life.
|
|
1283
1307
|
*/
|
|
1284
1308
|
simulateOutage: (component: PlatformComponent) => void;
|
|
1309
|
+
/**
|
|
1310
|
+
* Finish provisioning the organization's store, as populus's provisioning
|
|
1311
|
+
* workflow does in the background: from the next lookup on, the store is
|
|
1312
|
+
* `active`. Throws unless the organization has a `provisioning` store. A
|
|
1313
|
+
* store whose provisioning never completes stays `provisioning`.
|
|
1314
|
+
*/
|
|
1315
|
+
completeOrganizationStoreProvisioning: (organizationId: string) => void;
|
|
1285
1316
|
/**
|
|
1286
1317
|
* Every mutation committed through this client's registry, flattened
|
|
1287
1318
|
* and in order — `create` / `createOrReplace` / `createIfNotExists` /
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parse, evaluate } from "groq-js";
|
|
2
2
|
import { ClientError, ServerError } from "@sanity/client";
|
|
3
|
-
import { createPublicKey, verify } from "node:crypto";
|
|
3
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
6
6
|
return new Error(`${ERR_PREFIX} ${message}`);
|
|
@@ -98,6 +98,18 @@ function projectApiDown(request) {
|
|
|
98
98
|
}
|
|
99
99
|
});
|
|
100
100
|
}
|
|
101
|
+
function datasetNotFound(request, projectId, dataset) {
|
|
102
|
+
return new PlatformHttpError({
|
|
103
|
+
...request,
|
|
104
|
+
statusCode: 404,
|
|
105
|
+
statusMessage: "Not Found",
|
|
106
|
+
body: {
|
|
107
|
+
error: "Dataset not found",
|
|
108
|
+
message: `Dataset "${dataset}" not found for project ID "${projectId}"`,
|
|
109
|
+
statusCode: 404
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
101
113
|
const mediaLibraryReadRequired = (request) => accessApiError({
|
|
102
114
|
request,
|
|
103
115
|
statusCode: 401,
|
|
@@ -501,6 +513,98 @@ function createDocumentHistory() {
|
|
|
501
513
|
function historyIds(list) {
|
|
502
514
|
return list.split(",").map((id) => decodeURIComponent(id));
|
|
503
515
|
}
|
|
516
|
+
const ORGANIZATION_STORES_PATH = "/internal/organization-stores";
|
|
517
|
+
function serveOrganizationStore(args) {
|
|
518
|
+
const { stores, organizationIds, session, request, query } = args;
|
|
519
|
+
refuseSession(request, session);
|
|
520
|
+
const organizationId = organizationIdOf(request, query);
|
|
521
|
+
if (!organizationIds.includes(organizationId))
|
|
522
|
+
throw boom(request, 404, "Not Found", `Organization ${organizationId} not found`);
|
|
523
|
+
const existing = stores.get(organizationId);
|
|
524
|
+
if (existing !== void 0) return { ...existing };
|
|
525
|
+
const store = {
|
|
526
|
+
id: organizationStoreId(organizationId),
|
|
527
|
+
organizationId,
|
|
528
|
+
status: "provisioning"
|
|
529
|
+
};
|
|
530
|
+
return stores.set(organizationId, store), { ...store };
|
|
531
|
+
}
|
|
532
|
+
function completeProvisioning(stores, organizationId) {
|
|
533
|
+
const store = stores.get(organizationId);
|
|
534
|
+
if (store?.status !== "provisioning")
|
|
535
|
+
throw fakeError(
|
|
536
|
+
`completeOrganizationStoreProvisioning(): organization "${organizationId}" has ` + (store === void 0 ? "no store. Populus creates one on the first GET /internal/organization-stores." : "an active store already.")
|
|
537
|
+
);
|
|
538
|
+
store.status = "active";
|
|
539
|
+
}
|
|
540
|
+
function refuseSession(request, session) {
|
|
541
|
+
const refused = "refused" in session ? session.refused : session.tokenType !== "service" && "A service session is required for this endpoint";
|
|
542
|
+
if (refused) throw boom(request, 401, "Unauthorized", refused);
|
|
543
|
+
}
|
|
544
|
+
function organizationIdOf(request, query) {
|
|
545
|
+
const nested = [...query.keys()].find((key) => key.includes("["));
|
|
546
|
+
if (nested !== void 0)
|
|
547
|
+
throw fakeError(
|
|
548
|
+
`request(): ${request.path} got query key "${nested}"; Express parses bracketed keys into nested values, which the fake does not model. Pass flat query parameters.`
|
|
549
|
+
);
|
|
550
|
+
const unknown = [...new Set(query.keys())].filter((key) => key !== "tag").find((key) => key !== "organizationId"), values = query.getAll("organizationId"), failure = values.length === 0 && {
|
|
551
|
+
key: "organizationId",
|
|
552
|
+
message: '"organizationId" is required'
|
|
553
|
+
} || values.length > 1 && {
|
|
554
|
+
key: "organizationId",
|
|
555
|
+
message: '"organizationId" must be a string'
|
|
556
|
+
} || values[0] === "" && {
|
|
557
|
+
key: "organizationId",
|
|
558
|
+
message: '"organizationId" is not allowed to be empty'
|
|
559
|
+
} || unknown !== void 0 && {
|
|
560
|
+
key: unknown,
|
|
561
|
+
message: `"${unknown}" is not allowed`
|
|
562
|
+
};
|
|
563
|
+
if (failure)
|
|
564
|
+
throw new PlatformHttpError({
|
|
565
|
+
...request,
|
|
566
|
+
statusCode: 400,
|
|
567
|
+
statusMessage: "Bad Request",
|
|
568
|
+
body: {
|
|
569
|
+
statusCode: 400,
|
|
570
|
+
error: "Bad Request",
|
|
571
|
+
message: "Validation failed",
|
|
572
|
+
validation: {
|
|
573
|
+
query: {
|
|
574
|
+
source: "query",
|
|
575
|
+
keys: [escapeHtml(failure.key)],
|
|
576
|
+
message: failure.message
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
return values[0];
|
|
582
|
+
}
|
|
583
|
+
const DISALLOWED_SEGMENTS = ["ad", "api", "xxx"];
|
|
584
|
+
function organizationStoreId(organizationId) {
|
|
585
|
+
for (let attempt = 0; ; attempt++) {
|
|
586
|
+
const id = `os${createHash("sha256").update(`${organizationId}:${attempt}`).digest("hex").slice(0, 10)}`;
|
|
587
|
+
if (!DISALLOWED_SEGMENTS.some((segment) => id.includes(segment))) return id;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
function escapeHtml(text) {
|
|
591
|
+
const entities = {
|
|
592
|
+
'"': """,
|
|
593
|
+
"&": "&",
|
|
594
|
+
"'": "'",
|
|
595
|
+
"<": "<",
|
|
596
|
+
">": ">"
|
|
597
|
+
};
|
|
598
|
+
return text.replace(/["&'<>]/g, (char) => entities[char]);
|
|
599
|
+
}
|
|
600
|
+
function boom(request, statusCode, statusMessage, message) {
|
|
601
|
+
return new PlatformHttpError({
|
|
602
|
+
...request,
|
|
603
|
+
statusCode,
|
|
604
|
+
statusMessage,
|
|
605
|
+
body: { statusCode, error: statusMessage, message }
|
|
606
|
+
});
|
|
607
|
+
}
|
|
504
608
|
const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^\/users\/([^/]+)$/, ACCESS_ROLE_PATH = /^\/roles\/([^/]+)$/, ACCESS_ROBOT_PATH = /^\/robots(?:\/([^/]+))?$/, PROJECT_ROLES_PATH = /^\/projects\/([^/]+)\/roles$/, PROJECT_FEATURES_PATH = /^\/projects\/([^/]+)\/features$/, MY_ATTRIBUTES_PATH = /^\/organizations\/([^/]+)\/users\/me\/attributes$/, DATA_HISTORY_PATH = /^\/data\/history\/([^/]+)(\/.*)$/, ACCESS_API_SINCE = "2025-07-11", PROJECT_API_PATHS = [
|
|
505
609
|
/^\/users\/me$/,
|
|
506
610
|
/^\/projects\/[^/]+$/,
|
|
@@ -508,7 +612,8 @@ const ACCESS_PATH = /^\/access\/([^/]+)\/([^/]+)(\/.*)?$/, ACCESS_USER_PATH = /^
|
|
|
508
612
|
PROJECT_ROLES_PATH,
|
|
509
613
|
PROJECT_FEATURES_PATH,
|
|
510
614
|
MY_ATTRIBUTES_PATH,
|
|
511
|
-
ACCESS_PATH
|
|
615
|
+
ACCESS_PATH,
|
|
616
|
+
new RegExp(`^${ORGANIZATION_STORES_PATH}$`)
|
|
512
617
|
];
|
|
513
618
|
function servedByProjectApi(path) {
|
|
514
619
|
if (PROJECT_API_PATHS.some((pattern) => pattern.test(path))) return !0;
|
|
@@ -524,8 +629,19 @@ function usersPage(data) {
|
|
|
524
629
|
return { ...page(data), totalCount: data.length };
|
|
525
630
|
}
|
|
526
631
|
const UNMODELLED_PROFILE = { provider: "sanity", createdAt: (/* @__PURE__ */ new Date(0)).toISOString() };
|
|
527
|
-
async function servePlatformRequest(ctx,
|
|
528
|
-
const { path } = request, queryStart =
|
|
632
|
+
async function servePlatformRequest(ctx, request) {
|
|
633
|
+
const { path } = request, queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1));
|
|
634
|
+
if (path === ORGANIZATION_STORES_PATH)
|
|
635
|
+
return {
|
|
636
|
+
value: serveOrganizationStore({
|
|
637
|
+
stores: ctx.organizationStores,
|
|
638
|
+
organizationIds: ctx.organizationId === void 0 ? [] : [ctx.organizationId],
|
|
639
|
+
session: ctx.populusSession(),
|
|
640
|
+
request,
|
|
641
|
+
query
|
|
642
|
+
})
|
|
643
|
+
};
|
|
644
|
+
const myAttributes = path.match(MY_ATTRIBUTES_PATH);
|
|
529
645
|
if (myAttributes !== null) {
|
|
530
646
|
const organizationId = decodeURIComponent(myAttributes[1]);
|
|
531
647
|
return serveMyAttributes({ ctx, request, organizationId, query });
|
|
@@ -1016,7 +1132,7 @@ function makeRequestImpl(ctx) {
|
|
|
1016
1132
|
identities: listIdentities(),
|
|
1017
1133
|
organizationId
|
|
1018
1134
|
});
|
|
1019
|
-
const served = path === void 0 ? void 0 : await servePlatformRequest(platform,
|
|
1135
|
+
const served = path === void 0 ? void 0 : await servePlatformRequest(platform, requestFor(opts));
|
|
1020
1136
|
if (served !== void 0) return served.value;
|
|
1021
1137
|
throw fakeError(
|
|
1022
1138
|
`request(): no handler for path "${path}". With access control configured, the fake serves "/users/me", the handle's ACL ("<data base>/acl"), "/projects/<projectId>" (members), "/projects/<projectId>/users/<ids>", "/projects/<projectId>/roles", "/projects/<projectId>/features", the History API (client.getDataUrl("history", \u2026)), resource lookup ("/media-libraries/<id>", "/canvases/<id>", "/dashboards/<id>") and the Access API ("/access/<type>/<id>/roles[/<name>] | users[/<id>] | robots[/<id>] | user-permissions/me[/check]") and the caller's attributes ("/organizations/<id>/users/me/attributes"). For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
@@ -1933,9 +2049,11 @@ function jwtError(token, keys) {
|
|
|
1933
2049
|
function identityOf(claims) {
|
|
1934
2050
|
const unmodelledClaims = UNMODELLED_CLAIMS.filter((key) => key in claims);
|
|
1935
2051
|
if (unmodelledClaims.length > 0)
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
2052
|
+
return {
|
|
2053
|
+
identity: { user: { id: "" }, grants: [] },
|
|
2054
|
+
expiresAt: void 0,
|
|
2055
|
+
unmodelled: `internal token: the Content Lake reads the ${unmodelledClaims.map((key) => `"${key}"`).join(", ")} claim(s), which the fake does not model; it reads "i", "g" and "x".`
|
|
2056
|
+
};
|
|
1939
2057
|
const { i: id, g: grantList = [], x: rawExpiry } = claims;
|
|
1940
2058
|
let expiresAt;
|
|
1941
2059
|
if (rawExpiry != null) {
|
|
@@ -1972,6 +2090,32 @@ function checkInternalToken(token, keys) {
|
|
|
1972
2090
|
const parsed = jwtError(token, keys);
|
|
1973
2091
|
return "error" in parsed ? { refused: `invalid JWT token ${quoted(token)}: ${parsed.error}` } : identityOf(parsed.claims);
|
|
1974
2092
|
}
|
|
2093
|
+
function populusSession(token, keys) {
|
|
2094
|
+
const [headerSegment, claimsSegment, signatureSegment] = token.split(".");
|
|
2095
|
+
if (signatureSegment.trim() === "") {
|
|
2096
|
+
const decoded = [headerSegment, claimsSegment].map(decodeSegment);
|
|
2097
|
+
if (decoded.some((bytes) => typeof bytes == "string"))
|
|
2098
|
+
throw fakeError(
|
|
2099
|
+
"internal token: a segment is not base64url; jsonwebtoken's answer to it is not modelled."
|
|
2100
|
+
);
|
|
2101
|
+
return decoded.forEach(
|
|
2102
|
+
(bytes, index) => jsonObject(bytes, index === 0 ? "header" : "claims segment")
|
|
2103
|
+
), { refused: "jwt signature is required" };
|
|
2104
|
+
}
|
|
2105
|
+
const parsed = jwtError(token, keys);
|
|
2106
|
+
if ("error" in parsed) {
|
|
2107
|
+
if (parsed.error === "crypto/rsa: verification error") return { refused: "invalid signature" };
|
|
2108
|
+
throw fakeError(
|
|
2109
|
+
`internal token: populus refuses it with jsonwebtoken's 401 (gradient's reason: ${parsed.error}), whose message the fake does not model.`
|
|
2110
|
+
);
|
|
2111
|
+
}
|
|
2112
|
+
const { tokenType, x } = parsed.claims;
|
|
2113
|
+
if (x != null && typeof x != "number")
|
|
2114
|
+
throw fakeError(
|
|
2115
|
+
`internal token: "x" must be a number of epoch seconds; got ${JSON.stringify(x)}.`
|
|
2116
|
+
);
|
|
2117
|
+
return x && x < Math.ceil(Date.now() / 1e3) ? { refused: "Session expired" } : { tokenType };
|
|
2118
|
+
}
|
|
1975
2119
|
function goTime(epochSeconds) {
|
|
1976
2120
|
const date = new Date(epochSeconds * 1e3);
|
|
1977
2121
|
if (Number.isNaN(date.getTime()) || date.getUTCFullYear() < 1e3)
|
|
@@ -2251,15 +2395,39 @@ function ensureEntry(registry, resource) {
|
|
|
2251
2395
|
exists: !1
|
|
2252
2396
|
}, registry.set(key, entry)), entry;
|
|
2253
2397
|
}
|
|
2398
|
+
function seededMissingDataset(caller, key) {
|
|
2399
|
+
return fakeError(
|
|
2400
|
+
`${caller}: dataset "${key}" is both seeded and in \`missingDatasets\`; a dataset the platform does not have holds no documents.`
|
|
2401
|
+
);
|
|
2402
|
+
}
|
|
2254
2403
|
function seedEntry(registry, resource, documents) {
|
|
2255
2404
|
const entry = ensureEntry(registry, resource);
|
|
2256
2405
|
entry.store.seed(documents), entry.exists = !0;
|
|
2257
2406
|
}
|
|
2407
|
+
function seedOrganizationStores(options) {
|
|
2408
|
+
const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
|
|
2409
|
+
if (unserved !== void 0)
|
|
2410
|
+
throw fakeError(
|
|
2411
|
+
`createTestClient(): \`organizationStores\` seeds "${unserved[0]}" as ${JSON.stringify(unserved[1])}; populus serves only "provisioning" and "active" stores.`
|
|
2412
|
+
);
|
|
2413
|
+
const stray = seeded.find(([organizationId]) => organizationId !== options.organizationId);
|
|
2414
|
+
if (stray !== void 0)
|
|
2415
|
+
throw fakeError(
|
|
2416
|
+
`createTestClient(): \`organizationStores\` has a store for "${stray[0]}", which is not the configured \`organizationId\`; populus creates stores only for organizations it has.`
|
|
2417
|
+
);
|
|
2418
|
+
return new Map(
|
|
2419
|
+
seeded.map(([organizationId, status]) => [
|
|
2420
|
+
organizationId,
|
|
2421
|
+
{ id: organizationStoreId(organizationId), organizationId, status }
|
|
2422
|
+
])
|
|
2423
|
+
);
|
|
2424
|
+
}
|
|
2258
2425
|
function createTestClient(options = {}) {
|
|
2259
2426
|
const defaultProjectId = options.projectId ?? DEFAULT_PROJECT_ID, defaultDataset = options.dataset ?? DEFAULT_DATASET, backend = {
|
|
2260
2427
|
registry: /* @__PURE__ */ new Map(),
|
|
2261
2428
|
organizationId: options.organizationId,
|
|
2262
2429
|
projectFeatures: options.projectFeatures ?? {},
|
|
2430
|
+
organizationStores: seedOrganizationStores(options),
|
|
2263
2431
|
log: [],
|
|
2264
2432
|
stubs: /* @__PURE__ */ new Map(),
|
|
2265
2433
|
calls: [],
|
|
@@ -2269,6 +2437,7 @@ function createTestClient(options = {}) {
|
|
|
2269
2437
|
internalTokenKeys: parseInternalTokenKeys(options.internalTokenKeys ?? []),
|
|
2270
2438
|
internalTokens: /* @__PURE__ */ new Map(),
|
|
2271
2439
|
outages: /* @__PURE__ */ new Set(),
|
|
2440
|
+
missingDatasets: new Set(options.missingDatasets ?? []),
|
|
2272
2441
|
writeChain: Promise.resolve()
|
|
2273
2442
|
}, registry = backend.registry;
|
|
2274
2443
|
if (rejectAmbiguousIdentity("createTestClient()", options), options.token !== void 0 && requireIdentity(backend, options.token, "createTestClient()"), options.resource !== void 0 && validateResource(options.resource), options.documents) {
|
|
@@ -2283,6 +2452,11 @@ function createTestClient(options = {}) {
|
|
|
2283
2452
|
if (options.resources)
|
|
2284
2453
|
for (const [key, docs] of Object.entries(options.resources))
|
|
2285
2454
|
seedEntry(registry, parseResourceKey(key), docs);
|
|
2455
|
+
for (const key of backend.missingDatasets) {
|
|
2456
|
+
const { projectId, dataset } = parseDatasetKey(key);
|
|
2457
|
+
if (registry.get(registryKey(datasetResource(projectId, dataset)))?.exists)
|
|
2458
|
+
throw seededMissingDataset("createTestClient()", key);
|
|
2459
|
+
}
|
|
2286
2460
|
return makeHandle({
|
|
2287
2461
|
backend,
|
|
2288
2462
|
projectId: defaultProjectId,
|
|
@@ -2385,7 +2559,7 @@ function makeHandle(handleArgs) {
|
|
|
2385
2559
|
if (access === void 0)
|
|
2386
2560
|
throw fakeError("this handle has no acting identity (no token or accessControl bound).");
|
|
2387
2561
|
return access;
|
|
2388
|
-
}, projectHosted = useProjectHostname && resource === void 0,
|
|
2562
|
+
}, projectHosted = useProjectHostname && resource === void 0, refuseSession2 = (request) => {
|
|
2389
2563
|
if (token === void 0 || internal() !== void 0) return;
|
|
2390
2564
|
if (backend.revoked.has(token)) throw sessionNotFound(request);
|
|
2391
2565
|
const tokenProjectId = backend.identities.get(token)?.projectId;
|
|
@@ -2398,15 +2572,19 @@ function makeHandle(handleArgs) {
|
|
|
2398
2572
|
if (refusal !== void 0) throw refusal;
|
|
2399
2573
|
}, withSession = (request) => async (opts) => {
|
|
2400
2574
|
const sent = rawRequest(opts);
|
|
2401
|
-
if (internal() !== void 0 && servedByProjectApi(sent.path))
|
|
2575
|
+
if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
|
|
2402
2576
|
throw fakeError(
|
|
2403
2577
|
`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.`
|
|
2404
2578
|
);
|
|
2405
|
-
if (
|
|
2579
|
+
if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2406
2580
|
throw projectApiDown(sent);
|
|
2407
2581
|
return request(opts);
|
|
2408
2582
|
}, admitToLake = (request) => {
|
|
2409
|
-
|
|
2583
|
+
if (refuseSession2(request), missingKey !== void 0) {
|
|
2584
|
+
const parts = datasetParts(target.id);
|
|
2585
|
+
throw datasetNotFound(request, parts.projectId, parts.dataset);
|
|
2586
|
+
}
|
|
2587
|
+
refuseInternalToken(request);
|
|
2410
2588
|
const access = activeAccess();
|
|
2411
2589
|
if (access === void 0) return;
|
|
2412
2590
|
const refusal = refusedToken(request, access.grants);
|
|
@@ -2459,7 +2637,18 @@ function makeHandle(handleArgs) {
|
|
|
2459
2637
|
["skipCrossDatasetReferenceValidation", options.skipCrossDatasetReferenceValidation]
|
|
2460
2638
|
]
|
|
2461
2639
|
});
|
|
2462
|
-
}, rawRequest = (opts) =>
|
|
2640
|
+
}, rawRequest = (opts) => {
|
|
2641
|
+
if (opts.query !== void 0 && "tag" in opts.query)
|
|
2642
|
+
throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
|
|
2643
|
+
return platformRequest({
|
|
2644
|
+
method: "GET",
|
|
2645
|
+
uri: opts.uri ?? opts.url ?? "",
|
|
2646
|
+
tag: opts.tag,
|
|
2647
|
+
query: Object.entries(opts.query ?? {}).flatMap(
|
|
2648
|
+
([key, value]) => (Array.isArray(value) ? value : [value]).map((one) => [key, one])
|
|
2649
|
+
)
|
|
2650
|
+
});
|
|
2651
|
+
}, members = () => [
|
|
2463
2652
|
...backend.identities.values(),
|
|
2464
2653
|
...token === void 0 && accessControl !== void 0 ? [
|
|
2465
2654
|
{
|
|
@@ -2469,16 +2658,22 @@ function makeHandle(handleArgs) {
|
|
|
2469
2658
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2470
2659
|
}
|
|
2471
2660
|
] : []
|
|
2472
|
-
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry,
|
|
2661
|
+
], capabilities = capabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
|
|
2662
|
+
if (target.type !== "dataset") return;
|
|
2663
|
+
const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
|
|
2664
|
+
return backend.missingDatasets.has(key) ? key : void 0;
|
|
2665
|
+
})(), refuseSeedingMissing = (caller) => {
|
|
2666
|
+
if (missingKey !== void 0) throw seededMissingDataset(caller, missingKey);
|
|
2667
|
+
}, publicStore = {
|
|
2473
2668
|
...store,
|
|
2474
2669
|
seed: (documents) => {
|
|
2475
|
-
store.seed(documents), targetEntry.exists = !0;
|
|
2670
|
+
refuseSeedingMissing("seed()"), store.seed(documents), targetEntry.exists = !0;
|
|
2476
2671
|
},
|
|
2477
2672
|
add: (documents) => {
|
|
2478
|
-
store.add(documents), targetEntry.exists = !0;
|
|
2673
|
+
refuseSeedingMissing("add()"), store.add(documents), targetEntry.exists = !0;
|
|
2479
2674
|
},
|
|
2480
2675
|
put: (doc) => {
|
|
2481
|
-
store.put(doc), targetEntry.exists = !0;
|
|
2676
|
+
refuseSeedingMissing("put()"), store.put(doc), targetEntry.exists = !0;
|
|
2482
2677
|
}
|
|
2483
2678
|
}, concurrentEditKey = (id) => registryKey(target) + " " + id, actorId = () => {
|
|
2484
2679
|
const access = activeAccess();
|
|
@@ -2655,7 +2850,7 @@ function makeHandle(handleArgs) {
|
|
|
2655
2850
|
tag,
|
|
2656
2851
|
canUseCdn: !1
|
|
2657
2852
|
});
|
|
2658
|
-
if (
|
|
2853
|
+
if (refuseSession2(request), capabilities.actions !== "served") throw capabilities.actions(request);
|
|
2659
2854
|
return write(async () => {
|
|
2660
2855
|
for (const action of Array.isArray(actions) ? actions : [actions]) {
|
|
2661
2856
|
const refused = capabilities.refusedActions[action.actionType];
|
|
@@ -2891,6 +3086,9 @@ function makeHandle(handleArgs) {
|
|
|
2891
3086
|
apiVersion,
|
|
2892
3087
|
organizationId: backend.organizationId,
|
|
2893
3088
|
projectFeatures: backend.projectFeatures,
|
|
3089
|
+
organizationStores: backend.organizationStores,
|
|
3090
|
+
// A registered identity's session is a user or robot session, never a service one.
|
|
3091
|
+
populusSession: () => token === void 0 || internal() === void 0 ? { tokenType: void 0 } : populusSession(token, backend.internalTokenKeys),
|
|
2894
3092
|
own: (asked) => registryKey(asked) === registryKey(target) ? {
|
|
2895
3093
|
grants: requireActiveAccess().grants,
|
|
2896
3094
|
documents: () => store.all(),
|
|
@@ -2979,6 +3177,7 @@ function makeHandle(handleArgs) {
|
|
|
2979
3177
|
simulateOutage: (component) => {
|
|
2980
3178
|
backend.outages.add(component);
|
|
2981
3179
|
},
|
|
3180
|
+
completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
|
|
2982
3181
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
2983
3182
|
transactions: () => [...backend.log],
|
|
2984
3183
|
clearLog: () => {
|