@webiny/api-core-testing 0.0.0-unstable.0156a4c312

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @webiny/api-core-testing
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,19 @@
1
+ import { TestHttpEventHandler } from "@webiny/event-handler-core/features/testing";
2
+ import type { EventContext, NextFunction } from "@webiny/event-handler-core";
3
+ import type { IAuthenticationContext } from "@webiny/api-core/features/security/authentication/AuthenticationContext/index.js";
4
+ import type { IIdentityContext } from "@webiny/api-core/features/security/IdentityContext/abstractions.js";
5
+ /**
6
+ * Test-only decorator on the HTTP event handler: authenticates the `authorization` header and sets
7
+ * the resulting identity before the request is dispatched (mirrors the prod identity loader).
8
+ */
9
+ declare class AuthTriggerHandlerImpl implements TestHttpEventHandler.Interface {
10
+ private authCtx;
11
+ private identityCtx;
12
+ private inner;
13
+ constructor(authCtx: IAuthenticationContext, identityCtx: IIdentityContext, inner: TestHttpEventHandler.Interface);
14
+ execute(ctx: EventContext, next: NextFunction): Promise<any>;
15
+ }
16
+ export declare const AuthTriggerHandler: typeof AuthTriggerHandlerImpl & {
17
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/event-handler-core").IEventHandler<any, any>>;
18
+ };
19
+ export {};
@@ -0,0 +1,27 @@
1
+ import { TestHttpEventHandler } from "@webiny/event-handler-core/features/testing";
2
+ import { AuthenticationContext } from "@webiny/api-core/features/security/authentication/AuthenticationContext/index.js";
3
+ import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
4
+ class AuthTriggerHandlerImpl {
5
+ constructor(authCtx, identityCtx, inner){
6
+ this.authCtx = authCtx;
7
+ this.identityCtx = identityCtx;
8
+ this.inner = inner;
9
+ }
10
+ async execute(ctx, next) {
11
+ const headers = ctx.event?.headers ?? {};
12
+ const token = headers["authorization"] ?? "";
13
+ const identity = await this.authCtx.authenticate(token);
14
+ this.identityCtx.setIdentity(identity);
15
+ return this.inner.execute(ctx, next);
16
+ }
17
+ }
18
+ const AuthTriggerHandler = TestHttpEventHandler.createDecorator({
19
+ decorator: AuthTriggerHandlerImpl,
20
+ dependencies: [
21
+ AuthenticationContext,
22
+ IdentityContext
23
+ ]
24
+ });
25
+ export { AuthTriggerHandler };
26
+
27
+ //# sourceMappingURL=AuthTriggerHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers/AuthTriggerHandler.js","sources":["../../src/handlers/AuthTriggerHandler.ts"],"sourcesContent":["import { TestHttpEventHandler } from \"@webiny/event-handler-core/features/testing\";\nimport type { EventContext, NextFunction } from \"@webiny/event-handler-core\";\nimport { AuthenticationContext } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport type { IAuthenticationContext } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport type { IIdentityContext } from \"@webiny/api-core/features/security/IdentityContext/abstractions.js\";\n\n/**\n * Test-only decorator on the HTTP event handler: authenticates the `authorization` header and sets\n * the resulting identity before the request is dispatched (mirrors the prod identity loader).\n */\nclass AuthTriggerHandlerImpl implements TestHttpEventHandler.Interface {\n constructor(\n private authCtx: IAuthenticationContext,\n private identityCtx: IIdentityContext,\n private inner: TestHttpEventHandler.Interface\n ) {}\n\n async execute(ctx: EventContext, next: NextFunction): Promise<any> {\n const headers = ctx.event?.headers ?? {};\n const token = headers[\"authorization\"] ?? \"\";\n const identity = await this.authCtx.authenticate(token);\n this.identityCtx.setIdentity(identity);\n return this.inner.execute(ctx, next);\n }\n}\n\nexport const AuthTriggerHandler = TestHttpEventHandler.createDecorator({\n decorator: AuthTriggerHandlerImpl,\n dependencies: [AuthenticationContext, IdentityContext]\n});\n"],"names":["AuthTriggerHandlerImpl","authCtx","identityCtx","inner","ctx","next","headers","token","identity","AuthTriggerHandler","TestHttpEventHandler","AuthenticationContext","IdentityContext"],"mappings":";;;AAWA,MAAMA;IACF,YACYC,OAA+B,EAC/BC,WAA6B,EAC7BC,KAAqC,CAC/C;aAHUF,OAAO,GAAPA;aACAC,WAAW,GAAXA;aACAC,KAAK,GAALA;IACT;IAEH,MAAM,QAAQC,GAAiB,EAAEC,IAAkB,EAAgB;QAC/D,MAAMC,UAAUF,IAAI,KAAK,EAAE,WAAW,CAAC;QACvC,MAAMG,QAAQD,OAAO,CAAC,gBAAgB,IAAI;QAC1C,MAAME,WAAW,MAAM,IAAI,CAAC,OAAO,CAAC,YAAY,CAACD;QACjD,IAAI,CAAC,WAAW,CAAC,WAAW,CAACC;QAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAACJ,KAAKC;IACnC;AACJ;AAEO,MAAMI,qBAAqBC,qBAAqB,eAAe,CAAC;IACnE,WAAWV;IACX,cAAc;QAACW;QAAuBC;KAAgB;AAC1D"}
@@ -0,0 +1,17 @@
1
+ import { TestHttpEventHandler } from "@webiny/event-handler-core/features/testing";
2
+ import type { EventContext, NextFunction } from "@webiny/event-handler-core";
3
+ import type { ITenantContext } from "@webiny/api-core/features/tenancy/TenantContext/abstractions.js";
4
+ /**
5
+ * Test-only decorator on the HTTP event handler: sets the "root" tenant before the request is
6
+ * dispatched (mirrors the prod tenant loader).
7
+ */
8
+ declare class RootTenantInitializerImpl implements TestHttpEventHandler.Interface {
9
+ private tenantCtx;
10
+ private inner;
11
+ constructor(tenantCtx: ITenantContext, inner: TestHttpEventHandler.Interface);
12
+ execute(ctx: EventContext, next: NextFunction): Promise<any>;
13
+ }
14
+ export declare const RootTenantInitializer: typeof RootTenantInitializerImpl & {
15
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/event-handler-core").IEventHandler<any, any>>;
16
+ };
17
+ export {};
@@ -0,0 +1,40 @@
1
+ import { TestHttpEventHandler } from "@webiny/event-handler-core/features/testing";
2
+ import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/abstractions.js";
3
+ class RootTenantInitializerImpl {
4
+ constructor(tenantCtx, inner){
5
+ this.tenantCtx = tenantCtx;
6
+ this.inner = inner;
7
+ }
8
+ async execute(ctx, next) {
9
+ this.tenantCtx.setTenant({
10
+ id: "root",
11
+ name: "Root",
12
+ description: "",
13
+ status: "enabled",
14
+ isInstalled: false,
15
+ settings: {
16
+ name: {
17
+ full: "Root",
18
+ slug: "root"
19
+ },
20
+ social: {},
21
+ favicon: {},
22
+ logo: {}
23
+ },
24
+ tags: [],
25
+ parent: null,
26
+ createdOn: new Date().toISOString(),
27
+ savedOn: new Date().toISOString()
28
+ });
29
+ return this.inner.execute(ctx, next);
30
+ }
31
+ }
32
+ const RootTenantInitializer = TestHttpEventHandler.createDecorator({
33
+ decorator: RootTenantInitializerImpl,
34
+ dependencies: [
35
+ TenantContext
36
+ ]
37
+ });
38
+ export { RootTenantInitializer };
39
+
40
+ //# sourceMappingURL=RootTenantInitializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers/RootTenantInitializer.js","sources":["../../src/handlers/RootTenantInitializer.ts"],"sourcesContent":["import { TestHttpEventHandler } from \"@webiny/event-handler-core/features/testing\";\nimport type { EventContext, NextFunction } from \"@webiny/event-handler-core\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/abstractions.js\";\nimport type { ITenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/abstractions.js\";\n\n/**\n * Test-only decorator on the HTTP event handler: sets the \"root\" tenant before the request is\n * dispatched (mirrors the prod tenant loader).\n */\nclass RootTenantInitializerImpl implements TestHttpEventHandler.Interface {\n constructor(\n private tenantCtx: ITenantContext,\n private inner: TestHttpEventHandler.Interface\n ) {}\n\n async execute(ctx: EventContext, next: NextFunction): Promise<any> {\n this.tenantCtx.setTenant({\n id: \"root\",\n name: \"Root\",\n description: \"\",\n status: \"enabled\",\n isInstalled: false,\n settings: {\n name: { full: \"Root\", slug: \"root\" },\n social: {},\n favicon: {},\n logo: {}\n } as any,\n tags: [],\n parent: null,\n createdOn: new Date().toISOString(),\n savedOn: new Date().toISOString()\n });\n return this.inner.execute(ctx, next);\n }\n}\n\nexport const RootTenantInitializer = TestHttpEventHandler.createDecorator({\n decorator: RootTenantInitializerImpl,\n dependencies: [TenantContext]\n});\n"],"names":["RootTenantInitializerImpl","tenantCtx","inner","ctx","next","Date","RootTenantInitializer","TestHttpEventHandler","TenantContext"],"mappings":";;AASA,MAAMA;IACF,YACYC,SAAyB,EACzBC,KAAqC,CAC/C;aAFUD,SAAS,GAATA;aACAC,KAAK,GAALA;IACT;IAEH,MAAM,QAAQC,GAAiB,EAAEC,IAAkB,EAAgB;QAC/D,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC;YACrB,IAAI;YACJ,MAAM;YACN,aAAa;YACb,QAAQ;YACR,aAAa;YACb,UAAU;gBACN,MAAM;oBAAE,MAAM;oBAAQ,MAAM;gBAAO;gBACnC,QAAQ,CAAC;gBACT,SAAS,CAAC;gBACV,MAAM,CAAC;YACX;YACA,MAAM,EAAE;YACR,QAAQ;YACR,WAAW,IAAIC,OAAO,WAAW;YACjC,SAAS,IAAIA,OAAO,WAAW;QACnC;QACA,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAACF,KAAKC;IACnC;AACJ;AAEO,MAAME,wBAAwBC,qBAAqB,eAAe,CAAC;IACtE,WAAWP;IACX,cAAc;QAACQ;KAAc;AACjC"}
package/identity.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js";
2
+ import type { SecurityIdentity } from "@webiny/api-core/types/security.js";
3
+ /**
4
+ * Build a test admin identity. Override any field via the partial:
5
+ * `createIdentity({ id: "abc", displayName: "Jane" })`.
6
+ */
7
+ export declare const createIdentity: (identity?: Partial<IdentityData>) => SecurityIdentity;
package/identity.js ADDED
@@ -0,0 +1,10 @@
1
+ import { AuthenticatedIdentity } from "@webiny/api-core/features/security/IdentityContext/index.js";
2
+ const createIdentity = (identity = {})=>new AuthenticatedIdentity({
3
+ id: "12345678",
4
+ type: "admin",
5
+ displayName: "John Doe",
6
+ ...identity
7
+ });
8
+ export { createIdentity };
9
+
10
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","sources":["../src/identity.ts"],"sourcesContent":["import {\n AuthenticatedIdentity,\n type IdentityData\n} from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport type { SecurityIdentity } from \"@webiny/api-core/types/security.js\";\n\n/**\n * Build a test admin identity. Override any field via the partial:\n * `createIdentity({ id: \"abc\", displayName: \"Jane\" })`.\n */\nexport const createIdentity = (identity: Partial<IdentityData> = {}): SecurityIdentity => {\n return new AuthenticatedIdentity({\n id: \"12345678\",\n type: \"admin\",\n displayName: \"John Doe\",\n ...identity\n });\n};\n"],"names":["createIdentity","identity","AuthenticatedIdentity"],"mappings":";AAUO,MAAMA,iBAAiB,CAACC,WAAkC,CAAC,CAAC,GACxD,IAAIC,sBAAsB;QAC7B,IAAI;QACJ,MAAM;QACN,aAAa;QACb,GAAGD,QAAQ;IACf"}
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { TestIdentity, TestAuthenticator } from "./mocks/TestAuthenticator.js";
2
+ export { TestPermissions, TestAuthorizer } from "./mocks/TestAuthorizer.js";
3
+ export type { TestPermissionsHolder } from "./mocks/TestAuthorizer.js";
4
+ export { InlineTaskServiceFeature } from "./mocks/InlineTaskService.js";
5
+ export { AuthTriggerHandler } from "./handlers/AuthTriggerHandler.js";
6
+ export { RootTenantInitializer } from "./handlers/RootTenantInitializer.js";
7
+ export { createIdentity } from "./identity.js";
8
+ export { defaultIdentity, FULL_ACCESS_ROLE_ID, FULL_ACCESS_TEAM_ID, UNKNOWN_TEAM_ID } from "./tenancySecurity.js";
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { TestAuthenticator, TestIdentity } from "./mocks/TestAuthenticator.js";
2
+ export { TestAuthorizer, TestPermissions } from "./mocks/TestAuthorizer.js";
3
+ export { InlineTaskServiceFeature } from "./mocks/InlineTaskService.js";
4
+ export { AuthTriggerHandler } from "./handlers/AuthTriggerHandler.js";
5
+ export { RootTenantInitializer } from "./handlers/RootTenantInitializer.js";
6
+ export { createIdentity } from "./identity.js";
7
+ export { FULL_ACCESS_ROLE_ID, FULL_ACCESS_TEAM_ID, UNKNOWN_TEAM_ID, defaultIdentity } from "./tenancySecurity.js";
@@ -0,0 +1,6 @@
1
+ import type { Container } from "@webiny/di";
2
+ /** Registers a {@link TaskService} that runs every triggered task inline. */
3
+ export declare const InlineTaskServiceFeature: {
4
+ name: string;
5
+ register(container: Container): void;
6
+ };
@@ -0,0 +1,85 @@
1
+ import { Result, createFeature } from "@webiny/feature/api";
2
+ import { TaskService } from "@webiny/api-core/features/task/TaskService/index.js";
3
+ import { TaskDefinition, TaskResultStatus } from "@webiny/api-core/features/task/TaskDefinition/index.js";
4
+ const MAX_RUNS = 100;
5
+ class InlineTaskServiceImpl {
6
+ constructor(container){
7
+ this.container = container;
8
+ this.nextId = 1;
9
+ }
10
+ async trigger(params) {
11
+ const definition = this.container.resolveAll(TaskDefinition).find((candidate)=>candidate.id === params.definition);
12
+ if (!definition) throw new Error(`No task definition "${params.definition}" is registered.`);
13
+ const handler = this.container.resolveImplementation(definition.handler);
14
+ const controller = this.createController();
15
+ let input = params.input ?? {};
16
+ for(let run = 1; run <= MAX_RUNS; run++){
17
+ const result = await handler.run({
18
+ input,
19
+ definition,
20
+ controller
21
+ });
22
+ if (result.status !== TaskResultStatus.CONTINUE) break;
23
+ if (run === MAX_RUNS) throw new Error(`Task "${definition.id}" was still continuing after ${MAX_RUNS} runs.`);
24
+ input = result.input;
25
+ }
26
+ const now = new Date().toISOString();
27
+ return Result.ok({
28
+ id: `inline-task-${this.nextId++}`,
29
+ definitionId: definition.id,
30
+ input,
31
+ createdOn: now,
32
+ savedOn: now
33
+ });
34
+ }
35
+ async abort() {
36
+ throw new Error("Inline tasks finish inside trigger(), so there is nothing to abort.");
37
+ }
38
+ async fetchServiceInfo() {
39
+ return Result.ok({});
40
+ }
41
+ createController() {
42
+ return {
43
+ runtime: {
44
+ isAborted: ()=>false,
45
+ isCloseToTimeout: ()=>false
46
+ },
47
+ response: {
48
+ done: (message, output)=>({
49
+ status: TaskResultStatus.DONE,
50
+ message,
51
+ output
52
+ }),
53
+ continue: (input)=>({
54
+ status: TaskResultStatus.CONTINUE,
55
+ input
56
+ }),
57
+ error: (error)=>({
58
+ status: TaskResultStatus.ERROR,
59
+ error
60
+ }),
61
+ aborted: ()=>({
62
+ status: TaskResultStatus.ABORTED
63
+ })
64
+ },
65
+ task: {
66
+ trigger: (params)=>this.trigger(params)
67
+ },
68
+ logger: {
69
+ info: async ()=>{},
70
+ error: async ()=>{},
71
+ warn: async ()=>{},
72
+ debug: async ()=>{}
73
+ }
74
+ };
75
+ }
76
+ }
77
+ const InlineTaskServiceFeature = createFeature({
78
+ name: "Testing/InlineTaskService",
79
+ register (container) {
80
+ container.registerInstance(TaskService, new InlineTaskServiceImpl(container));
81
+ }
82
+ });
83
+ export { InlineTaskServiceFeature };
84
+
85
+ //# sourceMappingURL=InlineTaskService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mocks/InlineTaskService.js","sources":["../../src/mocks/InlineTaskService.ts"],"sourcesContent":["import type { Container } from \"@webiny/di\";\nimport { createFeature, Result } from \"@webiny/feature/api\";\nimport {\n TaskService,\n type ITaskTriggerParams\n} from \"@webiny/api-core/features/task/TaskService/index.js\";\nimport {\n TaskDefinition,\n TaskResultStatus\n} from \"@webiny/api-core/features/task/TaskDefinition/index.js\";\n\n/** A task that keeps asking to continue is broken; stop it instead of hanging the test. */\nconst MAX_RUNS = 100;\n\n/*\n * A `TaskService` that runs the triggered task right away, inside `trigger`, and keeps calling it\n * while it asks to continue. Tests then see the task's effects as soon as the triggering call\n * returns, with no task records and no step function. The controller covers what the task handlers\n * use: runtime checks (never aborted, never out of time), responses, triggering further tasks and a\n * silent logger.\n */\nclass InlineTaskServiceImpl implements TaskService.Interface {\n private nextId = 1;\n\n constructor(private container: Container) {}\n\n async trigger<I extends TaskDefinition.TaskInput = TaskDefinition.TaskInput>(\n params: ITaskTriggerParams<I>\n ) {\n const definition = this.container\n .resolveAll(TaskDefinition)\n .find(candidate => candidate.id === params.definition);\n if (!definition) {\n throw new Error(`No task definition \"${params.definition}\" is registered.`);\n }\n\n const handler = this.container.resolveImplementation(definition.handler);\n const controller = this.createController();\n\n let input = params.input ?? ({} as I);\n for (let run = 1; run <= MAX_RUNS; run++) {\n const result = await handler.run({ input, definition, controller } as never);\n if (result.status !== TaskResultStatus.CONTINUE) {\n break;\n }\n if (run === MAX_RUNS) {\n throw new Error(\n `Task \"${definition.id}\" was still continuing after ${MAX_RUNS} runs.`\n );\n }\n input = (result as { input: I }).input;\n }\n\n const now = new Date().toISOString();\n return Result.ok({\n id: `inline-task-${this.nextId++}`,\n definitionId: definition.id,\n input,\n createdOn: now,\n savedOn: now\n }) as never;\n }\n\n async abort(): Promise<never> {\n throw new Error(\"Inline tasks finish inside trigger(), so there is nothing to abort.\");\n }\n\n async fetchServiceInfo() {\n return Result.ok({});\n }\n\n private createController() {\n return {\n runtime: {\n isAborted: () => false,\n isCloseToTimeout: () => false\n },\n response: {\n done: (message?: string, output?: unknown) => ({\n status: TaskResultStatus.DONE,\n message,\n output\n }),\n continue: (input: unknown) => ({ status: TaskResultStatus.CONTINUE, input }),\n error: (error: unknown) => ({ status: TaskResultStatus.ERROR, error }),\n aborted: () => ({ status: TaskResultStatus.ABORTED })\n },\n task: {\n trigger: (params: ITaskTriggerParams) => this.trigger(params)\n },\n logger: {\n info: async () => {},\n error: async () => {},\n warn: async () => {},\n debug: async () => {}\n }\n };\n }\n}\n\n/** Registers a {@link TaskService} that runs every triggered task inline. */\nexport const InlineTaskServiceFeature = createFeature({\n name: \"Testing/InlineTaskService\",\n register(container) {\n container.registerInstance(TaskService, new InlineTaskServiceImpl(container));\n }\n});\n"],"names":["MAX_RUNS","InlineTaskServiceImpl","container","params","definition","TaskDefinition","candidate","Error","handler","controller","input","run","result","TaskResultStatus","now","Date","Result","message","output","error","InlineTaskServiceFeature","createFeature","TaskService"],"mappings":";;;AAYA,MAAMA,WAAW;AASjB,MAAMC;IAGF,YAAoBC,SAAoB,CAAE;aAAtBA,SAAS,GAATA;aAFZ,MAAM,GAAG;IAE0B;IAE3C,MAAM,QACFC,MAA6B,EAC/B;QACE,MAAMC,aAAa,IAAI,CAAC,SAAS,CAC5B,UAAU,CAACC,gBACX,IAAI,CAACC,CAAAA,YAAaA,UAAU,EAAE,KAAKH,OAAO,UAAU;QACzD,IAAI,CAACC,YACD,MAAM,IAAIG,MAAM,CAAC,oBAAoB,EAAEJ,OAAO,UAAU,CAAC,gBAAgB,CAAC;QAG9E,MAAMK,UAAU,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAACJ,WAAW,OAAO;QACvE,MAAMK,aAAa,IAAI,CAAC,gBAAgB;QAExC,IAAIC,QAAQP,OAAO,KAAK,IAAK,CAAC;QAC9B,IAAK,IAAIQ,MAAM,GAAGA,OAAOX,UAAUW,MAAO;YACtC,MAAMC,SAAS,MAAMJ,QAAQ,GAAG,CAAC;gBAAEE;gBAAON;gBAAYK;YAAW;YACjE,IAAIG,OAAO,MAAM,KAAKC,iBAAiB,QAAQ,EAC3C;YAEJ,IAAIF,QAAQX,UACR,MAAM,IAAIO,MACN,CAAC,MAAM,EAAEH,WAAW,EAAE,CAAC,6BAA6B,EAAEJ,SAAS,MAAM,CAAC;YAG9EU,QAASE,OAAwB,KAAK;QAC1C;QAEA,MAAME,MAAM,IAAIC,OAAO,WAAW;QAClC,OAAOC,OAAO,EAAE,CAAC;YACb,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,MAAM,IAAI;YAClC,cAAcZ,WAAW,EAAE;YAC3BM;YACA,WAAWI;YACX,SAASA;QACb;IACJ;IAEA,MAAM,QAAwB;QAC1B,MAAM,IAAIP,MAAM;IACpB;IAEA,MAAM,mBAAmB;QACrB,OAAOS,OAAO,EAAE,CAAC,CAAC;IACtB;IAEQ,mBAAmB;QACvB,OAAO;YACH,SAAS;gBACL,WAAW,IAAM;gBACjB,kBAAkB,IAAM;YAC5B;YACA,UAAU;gBACN,MAAM,CAACC,SAAkBC,SAAsB;wBAC3C,QAAQL,iBAAiB,IAAI;wBAC7BI;wBACAC;oBACJ;gBACA,UAAU,CAACR,QAAoB;wBAAE,QAAQG,iBAAiB,QAAQ;wBAAEH;oBAAM;gBAC1E,OAAO,CAACS,QAAoB;wBAAE,QAAQN,iBAAiB,KAAK;wBAAEM;oBAAM;gBACpE,SAAS,IAAO;wBAAE,QAAQN,iBAAiB,OAAO;oBAAC;YACvD;YACA,MAAM;gBACF,SAAS,CAACV,SAA+B,IAAI,CAAC,OAAO,CAACA;YAC1D;YACA,QAAQ;gBACJ,MAAM,WAAa;gBACnB,OAAO,WAAa;gBACpB,MAAM,WAAa;gBACnB,OAAO,WAAa;YACxB;QACJ;IACJ;AACJ;AAGO,MAAMiB,2BAA2BC,cAAc;IAClD,MAAM;IACN,UAASnB,SAAS;QACdA,UAAU,gBAAgB,CAACoB,aAAa,IAAIrB,sBAAsBC;IACtE;AACJ"}
@@ -0,0 +1,17 @@
1
+ import { Abstraction } from "@webiny/di";
2
+ import type { IAuthenticator } from "@webiny/api-core/features/security/authentication/Authenticator/abstractions.js";
3
+ import type { IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js";
4
+ /**
5
+ * The identity a test authenticates as. Register an instance in the (root) container to control
6
+ * who the request runs as: `container.registerInstance(TestIdentity, createIdentity({...}))`.
7
+ */
8
+ export declare const TestIdentity: Abstraction<IdentityData | null>;
9
+ declare class TestAuthenticatorImpl implements IAuthenticator {
10
+ private identity;
11
+ constructor(identity: IdentityData | null);
12
+ authenticate(_token: string): Promise<any>;
13
+ }
14
+ export declare const TestAuthenticator: typeof TestAuthenticatorImpl & {
15
+ __abstraction: Abstraction<IAuthenticator>;
16
+ };
17
+ export {};
@@ -0,0 +1,20 @@
1
+ import { Abstraction } from "@webiny/di";
2
+ import { Authenticator } from "@webiny/api-core/features/security/authentication/Authenticator/abstractions.js";
3
+ const TestIdentity = new Abstraction("TestIdentity");
4
+ class TestAuthenticatorImpl {
5
+ constructor(identity){
6
+ this.identity = identity;
7
+ }
8
+ async authenticate(_token) {
9
+ return this.identity;
10
+ }
11
+ }
12
+ const TestAuthenticator = Authenticator.createImplementation({
13
+ implementation: TestAuthenticatorImpl,
14
+ dependencies: [
15
+ TestIdentity
16
+ ]
17
+ });
18
+ export { TestAuthenticator, TestIdentity };
19
+
20
+ //# sourceMappingURL=TestAuthenticator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mocks/TestAuthenticator.js","sources":["../../src/mocks/TestAuthenticator.ts"],"sourcesContent":["import { Abstraction } from \"@webiny/di\";\nimport { Authenticator } from \"@webiny/api-core/features/security/authentication/Authenticator/abstractions.js\";\nimport type { IAuthenticator } from \"@webiny/api-core/features/security/authentication/Authenticator/abstractions.js\";\nimport type { IdentityData } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\n\n/**\n * The identity a test authenticates as. Register an instance in the (root) container to control\n * who the request runs as: `container.registerInstance(TestIdentity, createIdentity({...}))`.\n */\nexport const TestIdentity = new Abstraction<IdentityData | null>(\"TestIdentity\");\n\nclass TestAuthenticatorImpl implements IAuthenticator {\n constructor(private identity: IdentityData | null) {}\n\n async authenticate(_token: string): Promise<any> {\n return this.identity;\n }\n}\n\nexport const TestAuthenticator = Authenticator.createImplementation({\n implementation: TestAuthenticatorImpl,\n dependencies: [TestIdentity]\n});\n"],"names":["TestIdentity","Abstraction","TestAuthenticatorImpl","identity","_token","TestAuthenticator","Authenticator"],"mappings":";;AASO,MAAMA,eAAe,IAAIC,YAAiC;AAEjE,MAAMC;IACF,YAAoBC,QAA6B,CAAE;aAA/BA,QAAQ,GAARA;IAAgC;IAEpD,MAAM,aAAaC,MAAc,EAAgB;QAC7C,OAAO,IAAI,CAAC,QAAQ;IACxB;AACJ;AAEO,MAAMC,oBAAoBC,cAAc,oBAAoB,CAAC;IAChE,gBAAgBJ;IAChB,cAAc;QAACF;KAAa;AAChC"}
@@ -0,0 +1,29 @@
1
+ import { Abstraction } from "@webiny/di";
2
+ import type { IAuthorizer } from "@webiny/api-core/features/security/authorization/Authorizer/abstractions.js";
3
+ import type { SecurityPermission } from "@webiny/api-core/types/security.js";
4
+ import type { Identity, IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js";
5
+ /**
6
+ * The permissions granted to the test identity, wrapped in a holder so DI treats it as a single
7
+ * value (not a multiple-binding of SecurityPermission):
8
+ * `container.registerInstance(TestPermissions, { list: [{ name: "*" }] })`.
9
+ *
10
+ * `byIdentity` grants other identities their own permissions (by identity id), for code that
11
+ * evaluates another user through `IdentityContext.withIdentity`. Other identities not listed get
12
+ * no permissions.
13
+ */
14
+ export interface TestPermissionsHolder {
15
+ list: SecurityPermission[];
16
+ byIdentity?: Record<string, SecurityPermission[]>;
17
+ }
18
+ export declare const TestPermissions: Abstraction<TestPermissionsHolder>;
19
+ declare class TestAuthorizerImpl implements IAuthorizer {
20
+ private permissions;
21
+ private requestIdentity;
22
+ constructor(permissions: TestPermissionsHolder, requestIdentity: IdentityData | null);
23
+ authorize(identity: Identity): Promise<SecurityPermission[] | null>;
24
+ private isRequestIdentity;
25
+ }
26
+ export declare const TestAuthorizer: typeof TestAuthorizerImpl & {
27
+ __abstraction: Abstraction<IAuthorizer>;
28
+ };
29
+ export {};
@@ -0,0 +1,33 @@
1
+ import { Abstraction } from "@webiny/di";
2
+ import { Authorizer } from "@webiny/api-core/features/security/authorization/Authorizer/abstractions.js";
3
+ import { TestIdentity } from "./TestAuthenticator.js";
4
+ const TestPermissions = new Abstraction("TestPermissions");
5
+ class TestAuthorizerImpl {
6
+ constructor(permissions, requestIdentity){
7
+ this.permissions = permissions;
8
+ this.requestIdentity = requestIdentity;
9
+ }
10
+ async authorize(identity) {
11
+ if (this.isRequestIdentity(identity)) {
12
+ if (this.permissions.list.length > 0) return this.permissions.list;
13
+ if ("api-key" === identity.type) return identity.permissions;
14
+ return this.permissions.list;
15
+ }
16
+ if ("api-key" === identity.type) return null;
17
+ return this.permissions.byIdentity?.[identity.id] ?? [];
18
+ }
19
+ isRequestIdentity(identity) {
20
+ if (!this.requestIdentity) return identity.isAnonymous();
21
+ return identity.id === this.requestIdentity.id;
22
+ }
23
+ }
24
+ const TestAuthorizer = Authorizer.createImplementation({
25
+ implementation: TestAuthorizerImpl,
26
+ dependencies: [
27
+ TestPermissions,
28
+ TestIdentity
29
+ ]
30
+ });
31
+ export { TestAuthorizer, TestPermissions };
32
+
33
+ //# sourceMappingURL=TestAuthorizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mocks/TestAuthorizer.js","sources":["../../src/mocks/TestAuthorizer.ts"],"sourcesContent":["import { Abstraction } from \"@webiny/di\";\nimport { Authorizer } from \"@webiny/api-core/features/security/authorization/Authorizer/abstractions.js\";\nimport type { IAuthorizer } from \"@webiny/api-core/features/security/authorization/Authorizer/abstractions.js\";\nimport type { SecurityPermission } from \"@webiny/api-core/types/security.js\";\nimport type {\n Identity,\n IdentityData\n} from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { TestIdentity } from \"./TestAuthenticator.js\";\n\n/**\n * The permissions granted to the test identity, wrapped in a holder so DI treats it as a single\n * value (not a multiple-binding of SecurityPermission):\n * `container.registerInstance(TestPermissions, { list: [{ name: \"*\" }] })`.\n *\n * `byIdentity` grants other identities their own permissions (by identity id), for code that\n * evaluates another user through `IdentityContext.withIdentity`. Other identities not listed get\n * no permissions.\n */\nexport interface TestPermissionsHolder {\n list: SecurityPermission[];\n byIdentity?: Record<string, SecurityPermission[]>;\n}\n\nexport const TestPermissions = new Abstraction<TestPermissionsHolder>(\"TestPermissions\");\n\nclass TestAuthorizerImpl implements IAuthorizer {\n constructor(\n private permissions: TestPermissionsHolder,\n private requestIdentity: IdentityData | null\n ) {}\n\n async authorize(identity: Identity): Promise<SecurityPermission[] | null> {\n if (this.isRequestIdentity(identity)) {\n if (this.permissions.list.length > 0) {\n return this.permissions.list;\n }\n // An API-key request identity with embedded permissions (mirrors ApiKeyAuthorizer).\n if (identity.type === \"api-key\") {\n return identity.permissions;\n }\n return this.permissions.list;\n }\n // A real API key authenticated during the test: leave it to api-core's ApiKeyAuthorizer.\n if (identity.type === \"api-key\") {\n return null;\n }\n // Another identity (withIdentity): only what the test granted it (R70).\n return this.permissions.byIdentity?.[identity.id] ?? [];\n }\n\n private isRequestIdentity(identity: Identity): boolean {\n if (!this.requestIdentity) {\n return identity.isAnonymous();\n }\n return identity.id === this.requestIdentity.id;\n }\n}\n\nexport const TestAuthorizer = Authorizer.createImplementation({\n implementation: TestAuthorizerImpl,\n dependencies: [TestPermissions, TestIdentity]\n});\n"],"names":["TestPermissions","Abstraction","TestAuthorizerImpl","permissions","requestIdentity","identity","TestAuthorizer","Authorizer","TestIdentity"],"mappings":";;;AAwBO,MAAMA,kBAAkB,IAAIC,YAAmC;AAEtE,MAAMC;IACF,YACYC,WAAkC,EAClCC,eAAoC,CAC9C;aAFUD,WAAW,GAAXA;aACAC,eAAe,GAAfA;IACT;IAEH,MAAM,UAAUC,QAAkB,EAAwC;QACtE,IAAI,IAAI,CAAC,iBAAiB,CAACA,WAAW;YAClC,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,GAAG,GAC/B,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI;YAGhC,IAAIA,AAAkB,cAAlBA,SAAS,IAAI,EACb,OAAOA,SAAS,WAAW;YAE/B,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI;QAChC;QAEA,IAAIA,AAAkB,cAAlBA,SAAS,IAAI,EACb,OAAO;QAGX,OAAO,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,CAACA,SAAS,EAAE,CAAC,IAAI,EAAE;IAC3D;IAEQ,kBAAkBA,QAAkB,EAAW;QACnD,IAAI,CAAC,IAAI,CAAC,eAAe,EACrB,OAAOA,SAAS,WAAW;QAE/B,OAAOA,SAAS,EAAE,KAAK,IAAI,CAAC,eAAe,CAAC,EAAE;IAClD;AACJ;AAEO,MAAMC,iBAAiBC,WAAW,oBAAoB,CAAC;IAC1D,gBAAgBL;IAChB,cAAc;QAACF;QAAiBQ;KAAa;AACjD"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@webiny/api-core-testing",
3
+ "version": "0.0.0-unstable.0156a4c312",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./index.js",
7
+ "./*": "./*"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/webiny/webiny-js.git",
12
+ "directory": "packages/api-testing"
13
+ },
14
+ "description": "Shared test utilities for Webiny API packages (mocks, auth/tenant test decorators, identity helpers).",
15
+ "author": "Webiny Ltd.",
16
+ "license": "MIT",
17
+ "dependencies": {
18
+ "@webiny/api-core": "0.0.0-unstable.0156a4c312",
19
+ "@webiny/di": "2.0.0",
20
+ "@webiny/event-handler-core": "0.0.0-unstable.0156a4c312",
21
+ "@webiny/feature": "0.0.0-unstable.0156a4c312"
22
+ },
23
+ "devDependencies": {
24
+ "@webiny/build-tools": "0.0.0-unstable.0156a4c312",
25
+ "rimraf": "6.1.3",
26
+ "typescript": "7.0.2"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "webiny": {
32
+ "publishFrom": "dist"
33
+ }
34
+ }
@@ -0,0 +1,10 @@
1
+ import { IdentityData } from "@webiny/api-core/features/security/IdentityContext/index.js";
2
+ /**
3
+ * Shared test tenancy/security constants (the default admin identity + full-access role/team ids).
4
+ * Runtime tenancy/security setup is DI-native (TestAuthenticator/TestAuthorizer + the CMS test
5
+ * handler); these plain constants live here in the base test-utils package.
6
+ */
7
+ export declare const defaultIdentity: IdentityData;
8
+ export declare const FULL_ACCESS_ROLE_ID = "full-access-role";
9
+ export declare const FULL_ACCESS_TEAM_ID = "full-access-team";
10
+ export declare const UNKNOWN_TEAM_ID = "unknown-team";
@@ -0,0 +1,11 @@
1
+ const defaultIdentity = {
2
+ id: "id-12345678",
3
+ type: "admin",
4
+ displayName: "John Doe"
5
+ };
6
+ const FULL_ACCESS_ROLE_ID = "full-access-role";
7
+ const FULL_ACCESS_TEAM_ID = "full-access-team";
8
+ const UNKNOWN_TEAM_ID = "unknown-team";
9
+ export { FULL_ACCESS_ROLE_ID, FULL_ACCESS_TEAM_ID, UNKNOWN_TEAM_ID, defaultIdentity };
10
+
11
+ //# sourceMappingURL=tenancySecurity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenancySecurity.js","sources":["../src/tenancySecurity.ts"],"sourcesContent":["import { IdentityData } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\n\n/**\n * Shared test tenancy/security constants (the default admin identity + full-access role/team ids).\n * Runtime tenancy/security setup is DI-native (TestAuthenticator/TestAuthorizer + the CMS test\n * handler); these plain constants live here in the base test-utils package.\n */\nexport const defaultIdentity: IdentityData = {\n id: \"id-12345678\",\n type: \"admin\",\n displayName: \"John Doe\"\n};\n\nexport const FULL_ACCESS_ROLE_ID = \"full-access-role\";\nexport const FULL_ACCESS_TEAM_ID = \"full-access-team\";\nexport const UNKNOWN_TEAM_ID = \"unknown-team\";\n"],"names":["defaultIdentity","FULL_ACCESS_ROLE_ID","FULL_ACCESS_TEAM_ID","UNKNOWN_TEAM_ID"],"mappings":"AAOO,MAAMA,kBAAgC;IACzC,IAAI;IACJ,MAAM;IACN,aAAa;AACjB;AAEO,MAAMC,sBAAsB;AAC5B,MAAMC,sBAAsB;AAC5B,MAAMC,kBAAkB"}