@webiny/api-core 6.5.2-beta.1 → 6.5.2-beta.2
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/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js +2 -0
- package/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKey/GetApiKeyUseCase.d.ts +2 -2
- package/features/security/apiKeys/GetApiKey/GetApiKeyUseCase.js +7 -1
- package/features/security/apiKeys/GetApiKey/GetApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKey/abstractions.d.ts +3 -3
- package/features/security/apiKeys/GetApiKey/abstractions.js.map +1 -1
- package/features/security/apiKeys/ListApiKeys/ListApiKeysUseCase.d.ts +2 -2
- package/features/security/apiKeys/ListApiKeys/ListApiKeysUseCase.js +4 -1
- package/features/security/apiKeys/ListApiKeys/ListApiKeysUseCase.js.map +1 -1
- package/features/security/apiKeys/ListApiKeys/abstractions.d.ts +3 -4
- package/features/security/apiKeys/ListApiKeys/abstractions.js.map +1 -1
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js +2 -0
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/shared/hideToken.d.ts +8 -0
- package/features/security/apiKeys/shared/hideToken.js +11 -0
- package/features/security/apiKeys/shared/hideToken.js.map +1 -0
- package/features/security/apiKeys/shared/types.d.ts +7 -0
- package/features/security/roles/CreateRole/CreateRoleUseCase.js +6 -0
- package/features/security/roles/CreateRole/CreateRoleUseCase.js.map +1 -1
- package/features/security/roles/DeleteRole/DeleteRoleUseCase.js +2 -1
- package/features/security/roles/DeleteRole/DeleteRoleUseCase.js.map +1 -1
- package/features/security/roles/DeleteRole/abstractions.d.ts +2 -1
- package/features/security/roles/DeleteRole/abstractions.js.map +1 -1
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js +10 -1
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js.map +1 -1
- package/features/security/roles/UpdateRole/abstractions.d.ts +2 -1
- package/features/security/roles/UpdateRole/abstractions.js.map +1 -1
- package/features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.d.ts +5 -2
- package/features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.js +16 -3
- package/features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.js.map +1 -1
- package/features/security/roles/shared/errors.d.ts +8 -0
- package/features/security/roles/shared/errors.js +15 -1
- package/features/security/roles/shared/errors.js.map +1 -1
- package/features/security/teams/CreateTeam/CreateTeamUseCase.d.ts +3 -1
- package/features/security/teams/CreateTeam/CreateTeamUseCase.js +17 -2
- package/features/security/teams/CreateTeam/CreateTeamUseCase.js.map +1 -1
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.d.ts +3 -1
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.js +20 -2
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.js.map +1 -1
- package/features/security/utils/canAssignRolesAndTeams.d.ts +16 -0
- package/features/security/utils/canAssignRolesAndTeams.js +31 -0
- package/features/security/utils/canAssignRolesAndTeams.js.map +1 -0
- package/features/security/utils/canGrantPermissions.d.ts +53 -0
- package/features/security/utils/canGrantPermissions.js +122 -0
- package/features/security/utils/canGrantPermissions.js.map +1 -0
- package/features/security/utils/verifyJwtUsingJwk.d.ts +16 -1
- package/features/security/utils/verifyJwtUsingJwk.js +22 -4
- package/features/security/utils/verifyJwtUsingJwk.js.map +1 -1
- package/features/system/InstallSystem/InstallSystemUseCase.d.ts +1 -1
- package/features/tenancy/CreateTenant/CreateTenantRepository.js +1 -0
- package/features/tenancy/CreateTenant/CreateTenantRepository.js.map +1 -1
- package/features/tenancy/CreateTenant/CreateTenantUseCase.d.ts +5 -3
- package/features/tenancy/CreateTenant/CreateTenantUseCase.js +10 -3
- package/features/tenancy/CreateTenant/CreateTenantUseCase.js.map +1 -1
- package/features/tenancy/CreateTenant/abstractions.d.ts +2 -1
- package/features/tenancy/CreateTenant/abstractions.js.map +1 -1
- package/features/tenancy/CreateTenant/decorators/CreateTenantWithWcpIncrement.d.ts +1 -1
- package/features/tenancy/CreateTenant/errors.d.ts +6 -0
- package/features/tenancy/CreateTenant/errors.js +11 -1
- package/features/tenancy/CreateTenant/errors.js.map +1 -1
- package/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js +1 -0
- package/features/tenancy/DeleteTenant/decorators/DeleteTenantWithWcpDecrement.js.map +1 -1
- package/features/tenancy/TenantContext/TenantContext.d.ts +2 -0
- package/features/tenancy/TenantContext/TenantContext.js +18 -21
- package/features/tenancy/TenantContext/TenantContext.js.map +1 -1
- package/features/tenancy/TenantContext/abstractions.d.ts +5 -0
- package/features/tenancy/TenantContext/abstractions.js.map +1 -1
- package/features/users/CreateUser/CreateUserUseCase.d.ts +5 -1
- package/features/users/CreateUser/CreateUserUseCase.js +18 -2
- package/features/users/CreateUser/CreateUserUseCase.js.map +1 -1
- package/features/users/UpdateUser/UpdateUserUseCase.d.ts +5 -1
- package/features/users/UpdateUser/UpdateUserUseCase.js +24 -2
- package/features/users/UpdateUser/UpdateUserUseCase.js.map +1 -1
- package/graphql/security/apiKey.gql.js +1 -0
- package/graphql/security/apiKey.gql.js.map +1 -1
- package/idp/OidcJwtIdentityProvider.js +4 -1
- package/idp/OidcJwtIdentityProvider.js.map +1 -1
- package/package.json +22 -22
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.js","sources":["../../../../../../src/features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { RolesRepository } from \"../abstractions.js\";\nimport type { Role, GetRoleInput, ListRolesInput } from \"../types.js\";\nimport { ListCache } from \"./ListCache.js\";\n\nclass RolesRepositoryCachingDecoratorImpl implements RolesRepository.Interface {\n private readonly
|
|
1
|
+
{"version":3,"file":"features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.js","sources":["../../../../../../src/features/security/roles/shared/decorators/RolesRepositoryCachingDecorator.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { RolesRepository } from \"../abstractions.js\";\nimport type { Role, GetRoleInput, ListRolesInput } from \"../types.js\";\nimport { ListCache } from \"./ListCache.js\";\nimport { TenantContext } from \"~/features/tenancy/TenantContext/index.js\";\n\nclass RolesRepositoryCachingDecoratorImpl implements RolesRepository.Interface {\n // Security: roles are per tenant, so the cache is too (keyed by tenant ID).\n private readonly caches = new Map<string, ListCache<Role>>();\n\n constructor(\n private tenantContext: TenantContext.Interface,\n private decoratee: RolesRepository.Interface\n ) {}\n\n private get cache(): ListCache<Role> {\n const tenantId = this.tenantContext.getTenant().id;\n let cache = this.caches.get(tenantId);\n if (!cache) {\n cache = new ListCache<Role>();\n this.caches.set(tenantId, cache);\n }\n return cache;\n }\n\n async get(params: GetRoleInput): Promise<Result<Role, RolesRepository.Error>> {\n // Check cache first\n if (this.cache.hasItems()) {\n const cachedRole = this.cache.getItems().find(r => {\n if (params.id && r.id === params.id) {\n return true;\n }\n if (params.slug && r.slug === params.slug) {\n return true;\n }\n return false;\n });\n\n if (cachedRole) {\n return Result.ok(cachedRole);\n }\n }\n\n // Delegate to decoratee\n const result = await this.decoratee.get(params);\n\n // Add to cache on success\n if (result.isOk()) {\n this.cache.addItems([result.value]);\n }\n\n return result;\n }\n\n async list(params: ListRolesInput): Promise<Result<Role[], RolesRepository.Error>> {\n return this.decoratee.list(params);\n }\n\n async create(role: Role): Promise<Result<void, RolesRepository.Error>> {\n const result = await this.decoratee.create(role);\n\n // Add to cache on success\n if (result.isOk()) {\n this.cache.addItems([role]);\n }\n\n return result;\n }\n\n async update(role: Role): Promise<Result<void, RolesRepository.Error>> {\n const result = await this.decoratee.update(role);\n\n // Update in cache on success\n if (result.isOk()) {\n this.cache.updateItems(item => {\n if (item.id === role.id) {\n return role;\n }\n return item;\n });\n }\n\n return result;\n }\n\n async delete(role: Role): Promise<Result<void, RolesRepository.Error>> {\n const result = await this.decoratee.delete(role);\n\n // Remove from cache on success\n if (result.isOk()) {\n this.cache.removeItems(item => item.id === role.id);\n }\n\n return result;\n }\n}\n\nexport const RolesRepositoryCachingDecorator = RolesRepository.createDecorator({\n decorator: RolesRepositoryCachingDecoratorImpl,\n dependencies: [TenantContext]\n});\n"],"names":["RolesRepositoryCachingDecoratorImpl","tenantContext","decoratee","Map","tenantId","cache","ListCache","params","cachedRole","r","Result","result","role","item","RolesRepositoryCachingDecorator","RolesRepository","TenantContext"],"mappings":";;;;AAMA,MAAMA;IAIF,YACYC,aAAsC,EACtCC,SAAoC,CAC9C;aAFUD,aAAa,GAAbA;aACAC,SAAS,GAATA;aAJK,MAAM,GAAG,IAAIC;IAK3B;IAEH,IAAY,QAAyB;QACjC,MAAMC,WAAW,IAAI,CAAC,aAAa,CAAC,SAAS,GAAG,EAAE;QAClD,IAAIC,QAAQ,IAAI,CAAC,MAAM,CAAC,GAAG,CAACD;QAC5B,IAAI,CAACC,OAAO;YACRA,QAAQ,IAAIC;YACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAACF,UAAUC;QAC9B;QACA,OAAOA;IACX;IAEA,MAAM,IAAIE,MAAoB,EAAgD;QAE1E,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,IAAI;YACvB,MAAMC,aAAa,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,IAAI,CAACC,CAAAA;gBAC1C,IAAIF,OAAO,EAAE,IAAIE,EAAE,EAAE,KAAKF,OAAO,EAAE,EAC/B,OAAO;gBAEX,IAAIA,OAAO,IAAI,IAAIE,EAAE,IAAI,KAAKF,OAAO,IAAI,EACrC,OAAO;gBAEX,OAAO;YACX;YAEA,IAAIC,YACA,OAAOE,OAAO,EAAE,CAACF;QAEzB;QAGA,MAAMG,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,CAACJ;QAGxC,IAAII,OAAO,IAAI,IACX,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;YAACA,OAAO,KAAK;SAAC;QAGtC,OAAOA;IACX;IAEA,MAAM,KAAKJ,MAAsB,EAAkD;QAC/E,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAACA;IAC/B;IAEA,MAAM,OAAOK,IAAU,EAAgD;QACnE,MAAMD,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAACC;QAG3C,IAAID,OAAO,IAAI,IACX,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;YAACC;SAAK;QAG9B,OAAOD;IACX;IAEA,MAAM,OAAOC,IAAU,EAAgD;QACnE,MAAMD,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAACC;QAG3C,IAAID,OAAO,IAAI,IACX,IAAI,CAAC,KAAK,CAAC,WAAW,CAACE,CAAAA;YACnB,IAAIA,KAAK,EAAE,KAAKD,KAAK,EAAE,EACnB,OAAOA;YAEX,OAAOC;QACX;QAGJ,OAAOF;IACX;IAEA,MAAM,OAAOC,IAAU,EAAgD;QACnE,MAAMD,SAAS,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAACC;QAG3C,IAAID,OAAO,IAAI,IACX,IAAI,CAAC,KAAK,CAAC,WAAW,CAACE,CAAAA,OAAQA,KAAK,EAAE,KAAKD,KAAK,EAAE;QAGtD,OAAOD;IACX;AACJ;AAEO,MAAMG,kCAAkCC,gBAAgB,eAAe,CAAC;IAC3E,WAAWf;IACX,cAAc;QAACgB;KAAc;AACjC"}
|
|
@@ -29,6 +29,14 @@ export declare class CannotDeletePluginRolesError extends BaseError {
|
|
|
29
29
|
readonly code: "CANNOT_DELETE_PLUGIN_ROLES";
|
|
30
30
|
constructor();
|
|
31
31
|
}
|
|
32
|
+
export declare class CannotUpdateSystemRolesError extends BaseError {
|
|
33
|
+
readonly code: "CANNOT_UPDATE_SYSTEM_ROLES";
|
|
34
|
+
constructor();
|
|
35
|
+
}
|
|
36
|
+
export declare class CannotDeleteSystemRolesError extends BaseError {
|
|
37
|
+
readonly code: "CANNOT_DELETE_SYSTEM_ROLES";
|
|
38
|
+
constructor();
|
|
39
|
+
}
|
|
32
40
|
type RoleValidationErrorData = {
|
|
33
41
|
message: string;
|
|
34
42
|
};
|
|
@@ -45,6 +45,20 @@ class CannotDeletePluginRolesError extends BaseError {
|
|
|
45
45
|
}), this.code = "CANNOT_DELETE_PLUGIN_ROLES";
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
|
+
class CannotUpdateSystemRolesError extends BaseError {
|
|
49
|
+
constructor(){
|
|
50
|
+
super({
|
|
51
|
+
message: "Cannot update system roles."
|
|
52
|
+
}), this.code = "CANNOT_UPDATE_SYSTEM_ROLES";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
class CannotDeleteSystemRolesError extends BaseError {
|
|
56
|
+
constructor(){
|
|
57
|
+
super({
|
|
58
|
+
message: "Cannot delete system roles."
|
|
59
|
+
}), this.code = "CANNOT_DELETE_SYSTEM_ROLES";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
48
62
|
class RoleValidationError extends BaseError {
|
|
49
63
|
constructor(message){
|
|
50
64
|
super({
|
|
@@ -55,6 +69,6 @@ class RoleValidationError extends BaseError {
|
|
|
55
69
|
}), this.code = "ROLE_VALIDATION_ERROR";
|
|
56
70
|
}
|
|
57
71
|
}
|
|
58
|
-
export { CannotDeletePluginRolesError, CannotUpdatePluginRolesError, NotAuthorizedError, RoleExistsError, RoleNotFoundError, RoleStorageError, RoleValidationError };
|
|
72
|
+
export { CannotDeletePluginRolesError, CannotDeleteSystemRolesError, CannotUpdatePluginRolesError, CannotUpdateSystemRolesError, NotAuthorizedError, RoleExistsError, RoleNotFoundError, RoleStorageError, RoleValidationError };
|
|
59
73
|
|
|
60
74
|
//# sourceMappingURL=errors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/roles/shared/errors.js","sources":["../../../../../src/features/security/roles/shared/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class RoleStorageError extends BaseError {\n override readonly code = \"ROLE_STORAGE_ERROR\" as const;\n\n constructor(error: Error) {\n super({\n message: error.message\n });\n }\n}\n\nexport class RoleNotFoundError extends BaseError {\n override readonly code = \"ROLE_NOT_FOUND\" as const;\n\n constructor() {\n super({\n message: `Role was not found!`\n });\n }\n}\n\ntype NotAuthorizedErrorData = {\n message?: string;\n};\n\nexport class NotAuthorizedError extends BaseError<NotAuthorizedErrorData> {\n override readonly code = \"NOT_AUTHORIZED\" as const;\n\n constructor(data: NotAuthorizedErrorData = {}) {\n super({\n message: data.message || \"Not authorized!\",\n data\n });\n }\n}\n\ntype RoleExistsErrorData = {\n slug: string;\n};\n\nexport class RoleExistsError extends BaseError<RoleExistsErrorData> {\n override readonly code = \"ROLE_EXISTS\" as const;\n\n constructor(slug: string) {\n super({\n message: `Role with slug \"${slug}\" already exists.`,\n data: { slug }\n });\n }\n}\n\nexport class CannotUpdatePluginRolesError extends BaseError {\n override readonly code = \"CANNOT_UPDATE_PLUGIN_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot update roles created via plugins.\"\n });\n }\n}\n\nexport class CannotDeletePluginRolesError extends BaseError {\n override readonly code = \"CANNOT_DELETE_PLUGIN_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot delete roles created via plugins.\"\n });\n }\n}\n\ntype RoleValidationErrorData = {\n message: string;\n};\n\nexport class RoleValidationError extends BaseError<RoleValidationErrorData> {\n override readonly code = \"ROLE_VALIDATION_ERROR\" as const;\n\n constructor(message: string) {\n super({\n message,\n data: { message }\n });\n }\n}\n"],"names":["RoleStorageError","BaseError","error","RoleNotFoundError","NotAuthorizedError","data","RoleExistsError","slug","CannotUpdatePluginRolesError","CannotDeletePluginRolesError","RoleValidationError","message"],"mappings":";AAEO,MAAMA,yBAAyBC;IAGlC,YAAYC,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAASA,MAAM,OAAO;QAC1B,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMC,0BAA0BF;IAGnC,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAMO,MAAMG,2BAA2BH;IAGpC,YAAYI,OAA+B,CAAC,CAAC,CAAE;QAC3C,KAAK,CAAC;YACF,SAASA,KAAK,OAAO,IAAI;YACzBA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMC,wBAAwBL;IAGjC,YAAYM,IAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,gBAAgB,EAAEA,KAAK,iBAAiB,CAAC;YACnD,MAAM;gBAAEA;YAAK;QACjB,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAMC,qCAAqCP;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMQ,qCAAqCR;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;
|
|
1
|
+
{"version":3,"file":"features/security/roles/shared/errors.js","sources":["../../../../../src/features/security/roles/shared/errors.ts"],"sourcesContent":["import { BaseError } from \"@webiny/feature/api\";\n\nexport class RoleStorageError extends BaseError {\n override readonly code = \"ROLE_STORAGE_ERROR\" as const;\n\n constructor(error: Error) {\n super({\n message: error.message\n });\n }\n}\n\nexport class RoleNotFoundError extends BaseError {\n override readonly code = \"ROLE_NOT_FOUND\" as const;\n\n constructor() {\n super({\n message: `Role was not found!`\n });\n }\n}\n\ntype NotAuthorizedErrorData = {\n message?: string;\n};\n\nexport class NotAuthorizedError extends BaseError<NotAuthorizedErrorData> {\n override readonly code = \"NOT_AUTHORIZED\" as const;\n\n constructor(data: NotAuthorizedErrorData = {}) {\n super({\n message: data.message || \"Not authorized!\",\n data\n });\n }\n}\n\ntype RoleExistsErrorData = {\n slug: string;\n};\n\nexport class RoleExistsError extends BaseError<RoleExistsErrorData> {\n override readonly code = \"ROLE_EXISTS\" as const;\n\n constructor(slug: string) {\n super({\n message: `Role with slug \"${slug}\" already exists.`,\n data: { slug }\n });\n }\n}\n\nexport class CannotUpdatePluginRolesError extends BaseError {\n override readonly code = \"CANNOT_UPDATE_PLUGIN_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot update roles created via plugins.\"\n });\n }\n}\n\nexport class CannotDeletePluginRolesError extends BaseError {\n override readonly code = \"CANNOT_DELETE_PLUGIN_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot delete roles created via plugins.\"\n });\n }\n}\n\nexport class CannotUpdateSystemRolesError extends BaseError {\n override readonly code = \"CANNOT_UPDATE_SYSTEM_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot update system roles.\"\n });\n }\n}\n\nexport class CannotDeleteSystemRolesError extends BaseError {\n override readonly code = \"CANNOT_DELETE_SYSTEM_ROLES\" as const;\n\n constructor() {\n super({\n message: \"Cannot delete system roles.\"\n });\n }\n}\n\ntype RoleValidationErrorData = {\n message: string;\n};\n\nexport class RoleValidationError extends BaseError<RoleValidationErrorData> {\n override readonly code = \"ROLE_VALIDATION_ERROR\" as const;\n\n constructor(message: string) {\n super({\n message,\n data: { message }\n });\n }\n}\n"],"names":["RoleStorageError","BaseError","error","RoleNotFoundError","NotAuthorizedError","data","RoleExistsError","slug","CannotUpdatePluginRolesError","CannotDeletePluginRolesError","CannotUpdateSystemRolesError","CannotDeleteSystemRolesError","RoleValidationError","message"],"mappings":";AAEO,MAAMA,yBAAyBC;IAGlC,YAAYC,KAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAASA,MAAM,OAAO;QAC1B,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMC,0BAA0BF;IAGnC,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAMO,MAAMG,2BAA2BH;IAGpC,YAAYI,OAA+B,CAAC,CAAC,CAAE;QAC3C,KAAK,CAAC;YACF,SAASA,KAAK,OAAO,IAAI;YACzBA;QACJ,SANc,IAAI,GAAG;IAOzB;AACJ;AAMO,MAAMC,wBAAwBL;IAGjC,YAAYM,IAAY,CAAE;QACtB,KAAK,CAAC;YACF,SAAS,CAAC,gBAAgB,EAAEA,KAAK,iBAAiB,CAAC;YACnD,MAAM;gBAAEA;YAAK;QACjB,SANc,IAAI,GAAG;IAOzB;AACJ;AAEO,MAAMC,qCAAqCP;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMQ,qCAAqCR;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMS,qCAAqCT;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAEO,MAAMU,qCAAqCV;IAG9C,aAAc;QACV,KAAK,CAAC;YACF,SAAS;QACb,SALc,IAAI,GAAG;IAMzB;AACJ;AAMO,MAAMW,4BAA4BX;IAGrC,YAAYY,OAAe,CAAE;QACzB,KAAK,CAAC;YACFA;YACA,MAAM;gBAAEA;YAAQ;QACpB,SANc,IAAI,GAAG;IAOzB;AACJ"}
|
|
@@ -3,12 +3,14 @@ import { EventPublisher } from "../../../../features/eventPublisher/index.js";
|
|
|
3
3
|
import { CreateTeam } from "./abstractions.js";
|
|
4
4
|
import { TeamsRepository } from "../shared/abstractions.js";
|
|
5
5
|
import { IdentityContext } from "../../IdentityContext/abstractions.js";
|
|
6
|
+
import { RolesRepository } from "../../roles/shared/abstractions.js";
|
|
6
7
|
import type { Team, CreateTeamInput } from "../shared/types.js";
|
|
7
8
|
export declare class CreateTeamUseCase implements CreateTeam.Interface {
|
|
8
9
|
private identityContext;
|
|
9
10
|
private eventPublisher;
|
|
10
11
|
private repository;
|
|
11
|
-
|
|
12
|
+
private rolesRepository;
|
|
13
|
+
constructor(identityContext: IdentityContext.Interface, eventPublisher: EventPublisher.Interface, repository: TeamsRepository.Interface, rolesRepository: RolesRepository.Interface);
|
|
12
14
|
execute(input: CreateTeamInput): Promise<Result<Team, CreateTeam.Error>>;
|
|
13
15
|
}
|
|
14
16
|
export declare const CreateTeamUseCaseImpl: import("@webiny/di").Implementation<typeof CreateTeamUseCase>;
|
|
@@ -4,14 +4,18 @@ import { EventPublisher } from "../../../eventPublisher/index.js";
|
|
|
4
4
|
import { CreateTeam } from "./abstractions.js";
|
|
5
5
|
import { TeamsRepository } from "../shared/abstractions.js";
|
|
6
6
|
import { IdentityContext } from "../../IdentityContext/abstractions.js";
|
|
7
|
+
import { RolesRepository } from "../../roles/shared/abstractions.js";
|
|
8
|
+
import { canAssignRolesAndTeams } from "../../utils/canAssignRolesAndTeams.js";
|
|
9
|
+
import { CANNOT_GRANT_PERMISSIONS_MESSAGE } from "../../utils/canGrantPermissions.js";
|
|
7
10
|
import { createTeamValidation } from "./schema.js";
|
|
8
11
|
import { TeamAfterCreateEvent, TeamBeforeCreateEvent } from "./events.js";
|
|
9
12
|
import { NotAuthorizedError, TeamExistsError, TeamValidationError } from "../shared/errors.js";
|
|
10
13
|
class CreateTeamUseCase {
|
|
11
|
-
constructor(identityContext, eventPublisher, repository){
|
|
14
|
+
constructor(identityContext, eventPublisher, repository, rolesRepository){
|
|
12
15
|
this.identityContext = identityContext;
|
|
13
16
|
this.eventPublisher = eventPublisher;
|
|
14
17
|
this.repository = repository;
|
|
18
|
+
this.rolesRepository = rolesRepository;
|
|
15
19
|
}
|
|
16
20
|
async execute(input) {
|
|
17
21
|
const hasPermission = await this.identityContext.getPermission("security.team");
|
|
@@ -20,6 +24,16 @@ class CreateTeamUseCase {
|
|
|
20
24
|
if (!validation.success) return Result.fail(new TeamValidationError(validation.error.issues[0].message));
|
|
21
25
|
const identity = this.identityContext.getIdentity();
|
|
22
26
|
const data = validation.data;
|
|
27
|
+
const canAssign = await canAssignRolesAndTeams({
|
|
28
|
+
identityContext: this.identityContext,
|
|
29
|
+
rolesRepository: this.rolesRepository,
|
|
30
|
+
teamsRepository: this.repository,
|
|
31
|
+
roles: data.roles,
|
|
32
|
+
teams: []
|
|
33
|
+
});
|
|
34
|
+
if (!canAssign) return Result.fail(new NotAuthorizedError({
|
|
35
|
+
message: CANNOT_GRANT_PERMISSIONS_MESSAGE
|
|
36
|
+
}));
|
|
23
37
|
const existingTeamResult = await this.repository.get({
|
|
24
38
|
slug: data.slug
|
|
25
39
|
});
|
|
@@ -58,7 +72,8 @@ const CreateTeamUseCaseImpl = createImplementation({
|
|
|
58
72
|
dependencies: [
|
|
59
73
|
IdentityContext,
|
|
60
74
|
EventPublisher,
|
|
61
|
-
TeamsRepository
|
|
75
|
+
TeamsRepository,
|
|
76
|
+
RolesRepository
|
|
62
77
|
]
|
|
63
78
|
});
|
|
64
79
|
export { CreateTeamUseCase, CreateTeamUseCaseImpl };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/teams/CreateTeam/CreateTeamUseCase.js","sources":["../../../../../src/features/security/teams/CreateTeam/CreateTeamUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateTeam } from \"./abstractions.js\";\nimport { TeamsRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { createTeamValidation } from \"./schema.js\";\nimport { TeamBeforeCreateEvent, TeamAfterCreateEvent } from \"./events.js\";\nimport type { Team, CreateTeamInput } from \"../shared/types.js\";\nimport { NotAuthorizedError, TeamExistsError, TeamValidationError } from \"../shared/errors.js\";\n\nexport class CreateTeamUseCase implements CreateTeam.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: TeamsRepository.Interface\n ) {}\n\n async execute(input: CreateTeamInput): Promise<Result<Team, CreateTeam.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.team\");\n\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = createTeamValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new TeamValidationError(validation.error.issues[0].message));\n }\n\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n // Check if team with same slug already exists\n const existingTeamResult = await this.repository.get({ slug: data.slug });\n if (existingTeamResult.isOk()) {\n return Result.fail(new TeamExistsError(data.slug));\n }\n\n const team: Team = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n roles: data.roles,\n system: input.system || false,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n plugin: false\n };\n\n await this.eventPublisher.publish(\n new TeamBeforeCreateEvent({ team, input: validation.data })\n );\n\n const result = await this.repository.create(team);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new TeamAfterCreateEvent({ team, input: validation.data })\n );\n\n return Result.ok(team);\n }\n}\n\nexport const CreateTeamUseCaseImpl = createImplementation({\n abstraction: CreateTeam,\n implementation: CreateTeamUseCase,\n dependencies: [IdentityContext, EventPublisher, TeamsRepository]\n});\n"],"names":["CreateTeamUseCase","identityContext","eventPublisher","repository","input","hasPermission","Result","NotAuthorizedError","validation","createTeamValidation","TeamValidationError","identity","data","existingTeamResult","TeamExistsError","team","mdbid","Date","TeamBeforeCreateEvent","result","TeamAfterCreateEvent","CreateTeamUseCaseImpl","createImplementation","CreateTeam","IdentityContext","EventPublisher","TeamsRepository"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/teams/CreateTeam/CreateTeamUseCase.js","sources":["../../../../../src/features/security/teams/CreateTeam/CreateTeamUseCase.ts"],"sourcesContent":["import { mdbid } from \"@webiny/utils\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { CreateTeam } from \"./abstractions.js\";\nimport { TeamsRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { RolesRepository } from \"../../roles/shared/abstractions.js\";\nimport { canAssignRolesAndTeams } from \"../../utils/canAssignRolesAndTeams.js\";\nimport { CANNOT_GRANT_PERMISSIONS_MESSAGE } from \"../../utils/canGrantPermissions.js\";\nimport { createTeamValidation } from \"./schema.js\";\nimport { TeamBeforeCreateEvent, TeamAfterCreateEvent } from \"./events.js\";\nimport type { Team, CreateTeamInput } from \"../shared/types.js\";\nimport { NotAuthorizedError, TeamExistsError, TeamValidationError } from \"../shared/errors.js\";\n\nexport class CreateTeamUseCase implements CreateTeam.Interface {\n constructor(\n private identityContext: IdentityContext.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: TeamsRepository.Interface,\n private rolesRepository: RolesRepository.Interface\n ) {}\n\n async execute(input: CreateTeamInput): Promise<Result<Team, CreateTeam.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.team\");\n\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = createTeamValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new TeamValidationError(validation.error.issues[0].message));\n }\n\n const identity = this.identityContext.getIdentity();\n const data = validation.data;\n\n // Security: a team may only carry roles whose permissions the caller holds.\n const canAssign = await canAssignRolesAndTeams({\n identityContext: this.identityContext,\n rolesRepository: this.rolesRepository,\n teamsRepository: this.repository,\n roles: data.roles,\n teams: []\n });\n if (!canAssign) {\n return Result.fail(\n new NotAuthorizedError({ message: CANNOT_GRANT_PERMISSIONS_MESSAGE })\n );\n }\n\n // Check if team with same slug already exists\n const existingTeamResult = await this.repository.get({ slug: data.slug });\n if (existingTeamResult.isOk()) {\n return Result.fail(new TeamExistsError(data.slug));\n }\n\n const team: Team = {\n id: mdbid(),\n name: data.name,\n slug: data.slug,\n description: data.description,\n roles: data.roles,\n system: input.system || false,\n createdOn: new Date().toISOString(),\n createdBy: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n plugin: false\n };\n\n await this.eventPublisher.publish(\n new TeamBeforeCreateEvent({ team, input: validation.data })\n );\n\n const result = await this.repository.create(team);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new TeamAfterCreateEvent({ team, input: validation.data })\n );\n\n return Result.ok(team);\n }\n}\n\nexport const CreateTeamUseCaseImpl = createImplementation({\n abstraction: CreateTeam,\n implementation: CreateTeamUseCase,\n dependencies: [IdentityContext, EventPublisher, TeamsRepository, RolesRepository]\n});\n"],"names":["CreateTeamUseCase","identityContext","eventPublisher","repository","rolesRepository","input","hasPermission","Result","NotAuthorizedError","validation","createTeamValidation","TeamValidationError","identity","data","canAssign","canAssignRolesAndTeams","CANNOT_GRANT_PERMISSIONS_MESSAGE","existingTeamResult","TeamExistsError","team","mdbid","Date","TeamBeforeCreateEvent","result","TeamAfterCreateEvent","CreateTeamUseCaseImpl","createImplementation","CreateTeam","IdentityContext","EventPublisher","TeamsRepository","RolesRepository"],"mappings":";;;;;;;;;;;;AAeO,MAAMA;IACT,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,UAAqC,EACrCC,eAA0C,CACpD;aAJUH,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;aACAC,eAAe,GAAfA;IACT;IAEH,MAAM,QAAQC,KAAsB,EAA2C;QAC3E,MAAMC,gBAAgB,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAE/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,aAAaC,qBAAqB,SAAS,CAACL;QAClD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,oBAAoBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAMG,WAAW,IAAI,CAAC,eAAe,CAAC,WAAW;QACjD,MAAMC,OAAOJ,WAAW,IAAI;QAG5B,MAAMK,YAAY,MAAMC,uBAAuB;YAC3C,iBAAiB,IAAI,CAAC,eAAe;YACrC,iBAAiB,IAAI,CAAC,eAAe;YACrC,iBAAiB,IAAI,CAAC,UAAU;YAChC,OAAOF,KAAK,KAAK;YACjB,OAAO,EAAE;QACb;QACA,IAAI,CAACC,WACD,OAAOP,OAAO,IAAI,CACd,IAAIC,mBAAmB;YAAE,SAASQ;QAAiC;QAK3E,MAAMC,qBAAqB,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,MAAMJ,KAAK,IAAI;QAAC;QACvE,IAAII,mBAAmB,IAAI,IACvB,OAAOV,OAAO,IAAI,CAAC,IAAIW,gBAAgBL,KAAK,IAAI;QAGpD,MAAMM,OAAa;YACf,IAAIC;YACJ,MAAMP,KAAK,IAAI;YACf,MAAMA,KAAK,IAAI;YACf,aAAaA,KAAK,WAAW;YAC7B,OAAOA,KAAK,KAAK;YACjB,QAAQR,MAAM,MAAM,IAAI;YACxB,WAAW,IAAIgB,OAAO,WAAW;YACjC,WAAW;gBACP,IAAIT,SAAS,EAAE;gBACf,aAAaA,SAAS,WAAW;gBACjC,MAAMA,SAAS,IAAI;YACvB;YACA,QAAQ;QACZ;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIU,sBAAsB;YAAEH;YAAM,OAAOV,WAAW,IAAI;QAAC;QAG7D,MAAMc,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAACJ;QAE5C,IAAII,OAAO,MAAM,IACb,OAAOhB,OAAO,IAAI,CAACgB,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,qBAAqB;YAAEL;YAAM,OAAOV,WAAW,IAAI;QAAC;QAG5D,OAAOF,OAAO,EAAE,CAACY;IACrB;AACJ;AAEO,MAAMM,wBAAwBC,qBAAqB;IACtD,aAAaC;IACb,gBAAgB3B;IAChB,cAAc;QAAC4B;QAAiBC;QAAgBC;QAAiBC;KAAgB;AACrF"}
|
|
@@ -2,13 +2,15 @@ import { Result } from "@webiny/feature/api";
|
|
|
2
2
|
import { UpdateTeam } from "./abstractions.js";
|
|
3
3
|
import { TeamsRepository } from "../shared/abstractions.js";
|
|
4
4
|
import { IdentityContext } from "../../IdentityContext/abstractions.js";
|
|
5
|
+
import { RolesRepository } from "../../roles/shared/abstractions.js";
|
|
5
6
|
import { EventPublisher } from "../../../../features/eventPublisher/index.js";
|
|
6
7
|
import type { Team, UpdateTeamInput } from "../shared/types.js";
|
|
7
8
|
export declare class UpdateTeamUseCase {
|
|
8
9
|
private repository;
|
|
9
10
|
private identityContext;
|
|
10
11
|
private eventPublisher;
|
|
11
|
-
|
|
12
|
+
private rolesRepository;
|
|
13
|
+
constructor(repository: TeamsRepository.Interface, identityContext: IdentityContext.Interface, eventPublisher: EventPublisher.Interface, rolesRepository: RolesRepository.Interface);
|
|
12
14
|
execute(id: string, input: UpdateTeamInput): Promise<Result<Team, UpdateTeam.Error>>;
|
|
13
15
|
}
|
|
14
16
|
export declare const UpdateTeamUseCaseImpl: import("@webiny/di").Implementation<typeof UpdateTeamUseCase>;
|
|
@@ -2,15 +2,19 @@ import { Result, createImplementation } from "@webiny/feature/api";
|
|
|
2
2
|
import { UpdateTeam } from "./abstractions.js";
|
|
3
3
|
import { TeamsRepository } from "../shared/abstractions.js";
|
|
4
4
|
import { IdentityContext } from "../../IdentityContext/abstractions.js";
|
|
5
|
+
import { RolesRepository } from "../../roles/shared/abstractions.js";
|
|
6
|
+
import { canAssignRolesAndTeams } from "../../utils/canAssignRolesAndTeams.js";
|
|
7
|
+
import { CANNOT_GRANT_PERMISSIONS_MESSAGE } from "../../utils/canGrantPermissions.js";
|
|
5
8
|
import { EventPublisher } from "../../../eventPublisher/index.js";
|
|
6
9
|
import { updateTeamValidation } from "./schema.js";
|
|
7
10
|
import { TeamAfterUpdateEvent, TeamBeforeUpdateEvent } from "./events.js";
|
|
8
11
|
import { CannotUpdatePluginTeamsError, CannotUpdateSystemTeamsError, NotAuthorizedError, TeamValidationError } from "../shared/errors.js";
|
|
9
12
|
class UpdateTeamUseCase {
|
|
10
|
-
constructor(repository, identityContext, eventPublisher){
|
|
13
|
+
constructor(repository, identityContext, eventPublisher, rolesRepository){
|
|
11
14
|
this.repository = repository;
|
|
12
15
|
this.identityContext = identityContext;
|
|
13
16
|
this.eventPublisher = eventPublisher;
|
|
17
|
+
this.rolesRepository = rolesRepository;
|
|
14
18
|
}
|
|
15
19
|
async execute(id, input) {
|
|
16
20
|
const hasPermission = await this.identityContext.getPermission("security.team");
|
|
@@ -24,6 +28,19 @@ class UpdateTeamUseCase {
|
|
|
24
28
|
const existingTeam = existingResult.value;
|
|
25
29
|
if (existingTeam.system) return Result.fail(new CannotUpdateSystemTeamsError());
|
|
26
30
|
if (existingTeam.plugin) return Result.fail(new CannotUpdatePluginTeamsError());
|
|
31
|
+
const canAssign = await canAssignRolesAndTeams({
|
|
32
|
+
identityContext: this.identityContext,
|
|
33
|
+
rolesRepository: this.rolesRepository,
|
|
34
|
+
teamsRepository: this.repository,
|
|
35
|
+
roles: [
|
|
36
|
+
...existingTeam.roles ?? [],
|
|
37
|
+
...validation.data.roles ?? []
|
|
38
|
+
],
|
|
39
|
+
teams: []
|
|
40
|
+
});
|
|
41
|
+
if (!canAssign) return Result.fail(new NotAuthorizedError({
|
|
42
|
+
message: CANNOT_GRANT_PERMISSIONS_MESSAGE
|
|
43
|
+
}));
|
|
27
44
|
const updatedTeam = {
|
|
28
45
|
...existingTeam,
|
|
29
46
|
...validation.data
|
|
@@ -49,7 +66,8 @@ const UpdateTeamUseCaseImpl = createImplementation({
|
|
|
49
66
|
dependencies: [
|
|
50
67
|
TeamsRepository,
|
|
51
68
|
IdentityContext,
|
|
52
|
-
EventPublisher
|
|
69
|
+
EventPublisher,
|
|
70
|
+
RolesRepository
|
|
53
71
|
]
|
|
54
72
|
});
|
|
55
73
|
export { UpdateTeamUseCase, UpdateTeamUseCaseImpl };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/security/teams/UpdateTeam/UpdateTeamUseCase.js","sources":["../../../../../src/features/security/teams/UpdateTeam/UpdateTeamUseCase.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { UpdateTeam } from \"./abstractions.js\";\nimport { TeamsRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateTeamValidation } from \"./schema.js\";\nimport { TeamBeforeUpdateEvent, TeamAfterUpdateEvent } from \"./events.js\";\nimport type { Team, UpdateTeamInput } from \"../shared/types.js\";\nimport {\n NotAuthorizedError,\n CannotUpdatePluginTeamsError,\n CannotUpdateSystemTeamsError,\n TeamValidationError\n} from \"../shared/errors.js\";\n\nexport class UpdateTeamUseCase {\n private repository: TeamsRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n\n constructor(\n repository: TeamsRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n }\n\n async execute(id: string, input: UpdateTeamInput): Promise<Result<Team, UpdateTeam.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.team\");\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = updateTeamValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new TeamValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get({ id });\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingTeam = existingResult.value;\n\n // Check if team is system team\n if (existingTeam.system) {\n return Result.fail(new CannotUpdateSystemTeamsError());\n }\n\n // Check if team is created via plugin\n if (existingTeam.plugin) {\n return Result.fail(new CannotUpdatePluginTeamsError());\n }\n\n const updatedTeam: Team = {\n ...existingTeam,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new TeamBeforeUpdateEvent({\n original: existingTeam,\n updated: updatedTeam,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedTeam);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new TeamAfterUpdateEvent({\n original: existingTeam,\n updated: updatedTeam,\n input: validation.data\n })\n );\n\n return Result.ok(updatedTeam);\n }\n}\n\nexport const UpdateTeamUseCaseImpl = createImplementation({\n abstraction: UpdateTeam,\n implementation: UpdateTeamUseCase,\n dependencies: [TeamsRepository, IdentityContext, EventPublisher]\n});\n"],"names":["UpdateTeamUseCase","repository","identityContext","eventPublisher","id","input","hasPermission","Result","NotAuthorizedError","validation","updateTeamValidation","TeamValidationError","existingResult","existingTeam","CannotUpdateSystemTeamsError","CannotUpdatePluginTeamsError","updatedTeam","TeamBeforeUpdateEvent","result","TeamAfterUpdateEvent","UpdateTeamUseCaseImpl","createImplementation","UpdateTeam","TeamsRepository","IdentityContext","EventPublisher"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/security/teams/UpdateTeam/UpdateTeamUseCase.js","sources":["../../../../../src/features/security/teams/UpdateTeam/UpdateTeamUseCase.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { Result } from \"@webiny/feature/api\";\nimport { UpdateTeam } from \"./abstractions.js\";\nimport { TeamsRepository } from \"../shared/abstractions.js\";\nimport { IdentityContext } from \"../../IdentityContext/abstractions.js\";\nimport { RolesRepository } from \"../../roles/shared/abstractions.js\";\nimport { canAssignRolesAndTeams } from \"../../utils/canAssignRolesAndTeams.js\";\nimport { CANNOT_GRANT_PERMISSIONS_MESSAGE } from \"../../utils/canGrantPermissions.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport { updateTeamValidation } from \"./schema.js\";\nimport { TeamBeforeUpdateEvent, TeamAfterUpdateEvent } from \"./events.js\";\nimport type { Team, UpdateTeamInput } from \"../shared/types.js\";\nimport {\n NotAuthorizedError,\n CannotUpdatePluginTeamsError,\n CannotUpdateSystemTeamsError,\n TeamValidationError\n} from \"../shared/errors.js\";\n\nexport class UpdateTeamUseCase {\n private repository: TeamsRepository.Interface;\n private identityContext: IdentityContext.Interface;\n private eventPublisher: EventPublisher.Interface;\n private rolesRepository: RolesRepository.Interface;\n\n constructor(\n repository: TeamsRepository.Interface,\n identityContext: IdentityContext.Interface,\n eventPublisher: EventPublisher.Interface,\n rolesRepository: RolesRepository.Interface\n ) {\n this.repository = repository;\n this.identityContext = identityContext;\n this.eventPublisher = eventPublisher;\n this.rolesRepository = rolesRepository;\n }\n\n async execute(id: string, input: UpdateTeamInput): Promise<Result<Team, UpdateTeam.Error>> {\n const hasPermission = await this.identityContext.getPermission(\"security.team\");\n if (!hasPermission) {\n return Result.fail(new NotAuthorizedError());\n }\n\n const validation = updateTeamValidation.safeParse(input);\n if (!validation.success) {\n return Result.fail(new TeamValidationError(validation.error.issues[0].message));\n }\n\n const existingResult = await this.repository.get({ id });\n if (existingResult.isFail()) {\n return Result.fail(existingResult.error);\n }\n\n const existingTeam = existingResult.value;\n\n // Check if team is system team\n if (existingTeam.system) {\n return Result.fail(new CannotUpdateSystemTeamsError());\n }\n\n // Check if team is created via plugin\n if (existingTeam.plugin) {\n return Result.fail(new CannotUpdatePluginTeamsError());\n }\n\n // Security: a team may only carry roles whose permissions the caller holds. The team's\n // current roles are checked too, so the caller can't change a team that has more access.\n const canAssign = await canAssignRolesAndTeams({\n identityContext: this.identityContext,\n rolesRepository: this.rolesRepository,\n teamsRepository: this.repository,\n roles: [...(existingTeam.roles ?? []), ...(validation.data.roles ?? [])],\n teams: []\n });\n if (!canAssign) {\n return Result.fail(\n new NotAuthorizedError({ message: CANNOT_GRANT_PERMISSIONS_MESSAGE })\n );\n }\n\n const updatedTeam: Team = {\n ...existingTeam,\n ...validation.data\n };\n\n await this.eventPublisher.publish(\n new TeamBeforeUpdateEvent({\n original: existingTeam,\n updated: updatedTeam,\n input: validation.data\n })\n );\n\n const result = await this.repository.update(updatedTeam);\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n await this.eventPublisher.publish(\n new TeamAfterUpdateEvent({\n original: existingTeam,\n updated: updatedTeam,\n input: validation.data\n })\n );\n\n return Result.ok(updatedTeam);\n }\n}\n\nexport const UpdateTeamUseCaseImpl = createImplementation({\n abstraction: UpdateTeam,\n implementation: UpdateTeamUseCase,\n dependencies: [TeamsRepository, IdentityContext, EventPublisher, RolesRepository]\n});\n"],"names":["UpdateTeamUseCase","repository","identityContext","eventPublisher","rolesRepository","id","input","hasPermission","Result","NotAuthorizedError","validation","updateTeamValidation","TeamValidationError","existingResult","existingTeam","CannotUpdateSystemTeamsError","CannotUpdatePluginTeamsError","canAssign","canAssignRolesAndTeams","CANNOT_GRANT_PERMISSIONS_MESSAGE","updatedTeam","TeamBeforeUpdateEvent","result","TeamAfterUpdateEvent","UpdateTeamUseCaseImpl","createImplementation","UpdateTeam","TeamsRepository","IdentityContext","EventPublisher","RolesRepository"],"mappings":";;;;;;;;;;;AAmBO,MAAMA;IAMT,YACIC,UAAqC,EACrCC,eAA0C,EAC1CC,cAAwC,EACxCC,eAA0C,CAC5C;QACE,IAAI,CAAC,UAAU,GAAGH;QAClB,IAAI,CAAC,eAAe,GAAGC;QACvB,IAAI,CAAC,cAAc,GAAGC;QACtB,IAAI,CAAC,eAAe,GAAGC;IAC3B;IAEA,MAAM,QAAQC,EAAU,EAAEC,KAAsB,EAA2C;QACvF,MAAMC,gBAAgB,MAAM,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC;QAC/D,IAAI,CAACA,eACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAG3B,MAAMC,aAAaC,qBAAqB,SAAS,CAACL;QAClD,IAAI,CAACI,WAAW,OAAO,EACnB,OAAOF,OAAO,IAAI,CAAC,IAAII,oBAAoBF,WAAW,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO;QAGjF,MAAMG,iBAAiB,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAER;QAAG;QACtD,IAAIQ,eAAe,MAAM,IACrB,OAAOL,OAAO,IAAI,CAACK,eAAe,KAAK;QAG3C,MAAMC,eAAeD,eAAe,KAAK;QAGzC,IAAIC,aAAa,MAAM,EACnB,OAAON,OAAO,IAAI,CAAC,IAAIO;QAI3B,IAAID,aAAa,MAAM,EACnB,OAAON,OAAO,IAAI,CAAC,IAAIQ;QAK3B,MAAMC,YAAY,MAAMC,uBAAuB;YAC3C,iBAAiB,IAAI,CAAC,eAAe;YACrC,iBAAiB,IAAI,CAAC,eAAe;YACrC,iBAAiB,IAAI,CAAC,UAAU;YAChC,OAAO;mBAAKJ,aAAa,KAAK,IAAI,EAAE;mBAAOJ,WAAW,IAAI,CAAC,KAAK,IAAI,EAAE;aAAE;YACxE,OAAO,EAAE;QACb;QACA,IAAI,CAACO,WACD,OAAOT,OAAO,IAAI,CACd,IAAIC,mBAAmB;YAAE,SAASU;QAAiC;QAI3E,MAAMC,cAAoB;YACtB,GAAGN,YAAY;YACf,GAAGJ,WAAW,IAAI;QACtB;QAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIW,sBAAsB;YACtB,UAAUP;YACV,SAASM;YACT,OAAOV,WAAW,IAAI;QAC1B;QAGJ,MAAMY,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,MAAM,CAACF;QAE5C,IAAIE,OAAO,MAAM,IACb,OAAOd,OAAO,IAAI,CAACc,OAAO,KAAK;QAGnC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,qBAAqB;YACrB,UAAUT;YACV,SAASM;YACT,OAAOV,WAAW,IAAI;QAC1B;QAGJ,OAAOF,OAAO,EAAE,CAACY;IACrB;AACJ;AAEO,MAAMI,wBAAwBC,qBAAqB;IACtD,aAAaC;IACb,gBAAgB1B;IAChB,cAAc;QAAC2B;QAAiBC;QAAiBC;QAAgBC;KAAgB;AACrF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { IdentityContext } from "../../../features/security/IdentityContext/abstractions.js";
|
|
2
|
+
import type { RolesRepository } from "../../../features/security/roles/shared/abstractions.js";
|
|
3
|
+
import type { TeamsRepository } from "../../../features/security/teams/shared/abstractions.js";
|
|
4
|
+
export interface CanAssignRolesAndTeamsParams {
|
|
5
|
+
identityContext: IdentityContext.Interface;
|
|
6
|
+
rolesRepository: RolesRepository.Interface;
|
|
7
|
+
teamsRepository: TeamsRepository.Interface;
|
|
8
|
+
roles: (string | undefined | null)[];
|
|
9
|
+
teams: (string | undefined | null)[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Security: a caller may only assign roles and teams (to a user, or roles to a team) whose
|
|
13
|
+
* permissions they hold themselves. See `canGrantPermissions`.
|
|
14
|
+
* Code running without authorization (installers, IdP user sync) and full access may assign anything.
|
|
15
|
+
*/
|
|
16
|
+
export declare const canAssignRolesAndTeams: (params: CanAssignRolesAndTeamsParams) => Promise<boolean>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { canGrantPermissions } from "./canGrantPermissions.js";
|
|
2
|
+
const unique = (ids)=>Array.from(new Set(ids.filter((id)=>Boolean(id))));
|
|
3
|
+
const canAssignRolesAndTeams = async (params)=>{
|
|
4
|
+
const { identityContext, rolesRepository, teamsRepository } = params;
|
|
5
|
+
if (!identityContext.isAuthorizationEnabled()) return true;
|
|
6
|
+
if (await identityContext.hasFullAccess()) return true;
|
|
7
|
+
const roleIds = unique(params.roles);
|
|
8
|
+
const teamIds = unique(params.teams);
|
|
9
|
+
if (teamIds.length > 0) {
|
|
10
|
+
const teamsResult = await teamsRepository.list({
|
|
11
|
+
where: {
|
|
12
|
+
id_in: teamIds
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
if (teamsResult.isFail()) return false;
|
|
16
|
+
for (const team of teamsResult.value)roleIds.push(...unique(team.roles ?? []));
|
|
17
|
+
}
|
|
18
|
+
const dedupedRoleIds = unique(roleIds);
|
|
19
|
+
if (0 === dedupedRoleIds.length) return true;
|
|
20
|
+
const rolesResult = await rolesRepository.list({
|
|
21
|
+
where: {
|
|
22
|
+
id_in: dedupedRoleIds
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
if (rolesResult.isFail()) return false;
|
|
26
|
+
const requested = rolesResult.value.map((role)=>role.permissions ?? []);
|
|
27
|
+
return canGrantPermissions(identityContext, requested);
|
|
28
|
+
};
|
|
29
|
+
export { canAssignRolesAndTeams };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=canAssignRolesAndTeams.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/security/utils/canAssignRolesAndTeams.js","sources":["../../../../src/features/security/utils/canAssignRolesAndTeams.ts"],"sourcesContent":["import type { IdentityContext } from \"~/features/security/IdentityContext/abstractions.js\";\nimport type { RolesRepository } from \"~/features/security/roles/shared/abstractions.js\";\nimport type { TeamsRepository } from \"~/features/security/teams/shared/abstractions.js\";\nimport {\n canGrantPermissions,\n type RequestedPermissions\n} from \"~/features/security/utils/canGrantPermissions.js\";\n\nexport interface CanAssignRolesAndTeamsParams {\n identityContext: IdentityContext.Interface;\n rolesRepository: RolesRepository.Interface;\n teamsRepository: TeamsRepository.Interface;\n roles: (string | undefined | null)[];\n teams: (string | undefined | null)[];\n}\n\nconst unique = (ids: (string | undefined | null)[]) => {\n return Array.from(new Set(ids.filter((id): id is string => Boolean(id))));\n};\n\n/**\n * Security: a caller may only assign roles and teams (to a user, or roles to a team) whose\n * permissions they hold themselves. See `canGrantPermissions`.\n * Code running without authorization (installers, IdP user sync) and full access may assign anything.\n */\nexport const canAssignRolesAndTeams = async (\n params: CanAssignRolesAndTeamsParams\n): Promise<boolean> => {\n const { identityContext, rolesRepository, teamsRepository } = params;\n\n if (!identityContext.isAuthorizationEnabled()) {\n return true;\n }\n\n if (await identityContext.hasFullAccess()) {\n return true;\n }\n\n const roleIds = unique(params.roles);\n const teamIds = unique(params.teams);\n\n if (teamIds.length > 0) {\n const teamsResult = await teamsRepository.list({ where: { id_in: teamIds } });\n if (teamsResult.isFail()) {\n return false;\n }\n for (const team of teamsResult.value) {\n roleIds.push(...unique(team.roles ?? []));\n }\n }\n\n const dedupedRoleIds = unique(roleIds);\n if (dedupedRoleIds.length === 0) {\n return true;\n }\n\n const rolesResult = await rolesRepository.list({ where: { id_in: dedupedRoleIds } });\n if (rolesResult.isFail()) {\n return false;\n }\n\n // Each role is loaded as its own group of permissions (see `getPermissionsFromRoles`).\n // Roles that don't exist grant nothing.\n const requested: RequestedPermissions[] = rolesResult.value.map(role => role.permissions ?? []);\n\n return canGrantPermissions(identityContext, requested);\n};\n"],"names":["unique","ids","Array","Set","id","Boolean","canAssignRolesAndTeams","params","identityContext","rolesRepository","teamsRepository","roleIds","teamIds","teamsResult","team","dedupedRoleIds","rolesResult","requested","role","canGrantPermissions"],"mappings":";AAgBA,MAAMA,SAAS,CAACC,MACLC,MAAM,IAAI,CAAC,IAAIC,IAAIF,IAAI,MAAM,CAAC,CAACG,KAAqBC,QAAQD;AAQhE,MAAME,yBAAyB,OAClCC;IAEA,MAAM,EAAEC,eAAe,EAAEC,eAAe,EAAEC,eAAe,EAAE,GAAGH;IAE9D,IAAI,CAACC,gBAAgB,sBAAsB,IACvC,OAAO;IAGX,IAAI,MAAMA,gBAAgB,aAAa,IACnC,OAAO;IAGX,MAAMG,UAAUX,OAAOO,OAAO,KAAK;IACnC,MAAMK,UAAUZ,OAAOO,OAAO,KAAK;IAEnC,IAAIK,QAAQ,MAAM,GAAG,GAAG;QACpB,MAAMC,cAAc,MAAMH,gBAAgB,IAAI,CAAC;YAAE,OAAO;gBAAE,OAAOE;YAAQ;QAAE;QAC3E,IAAIC,YAAY,MAAM,IAClB,OAAO;QAEX,KAAK,MAAMC,QAAQD,YAAY,KAAK,CAChCF,QAAQ,IAAI,IAAIX,OAAOc,KAAK,KAAK,IAAI,EAAE;IAE/C;IAEA,MAAMC,iBAAiBf,OAAOW;IAC9B,IAAII,AAA0B,MAA1BA,eAAe,MAAM,EACrB,OAAO;IAGX,MAAMC,cAAc,MAAMP,gBAAgB,IAAI,CAAC;QAAE,OAAO;YAAE,OAAOM;QAAe;IAAE;IAClF,IAAIC,YAAY,MAAM,IAClB,OAAO;IAKX,MAAMC,YAAoCD,YAAY,KAAK,CAAC,GAAG,CAACE,CAAAA,OAAQA,KAAK,WAAW,IAAI,EAAE;IAE9F,OAAOC,oBAAoBX,iBAAiBS;AAChD"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { IdentityContext } from "../../../features/security/IdentityContext/abstractions.js";
|
|
2
|
+
import type { SecurityPermission } from "../../../types/security.js";
|
|
3
|
+
/**
|
|
4
|
+
* Security: the "cannot grant more than you hold" rule.
|
|
5
|
+
*
|
|
6
|
+
* A caller may only write (into a role, or onto a user through roles and teams) permissions they
|
|
7
|
+
* themselves hold. The check is conservative: when two permissions can't be compared safely, the
|
|
8
|
+
* requested one must match the held one exactly.
|
|
9
|
+
*
|
|
10
|
+
* A requested permission is covered by a held permission when:
|
|
11
|
+
* - the held name equals the requested name, or is a pattern that matches it (`cms.*`, `*`);
|
|
12
|
+
* a requested name that is itself a pattern (anything beyond a trailing `.*`) must be held verbatim;
|
|
13
|
+
* - `rwd` / `pw`: the held letters are a superset of the requested ones. A missing `rwd` means
|
|
14
|
+
* full access (Headless CMS), so it is only covered by a held permission without `rwd`;
|
|
15
|
+
* a missing or empty `pw` grants nothing;
|
|
16
|
+
* - `own`: a held `own: true` only covers a requested `own: true`;
|
|
17
|
+
* - `models` / `groups`: a held list only covers a requested list that is a subset of it;
|
|
18
|
+
* a missing held list means "no restriction";
|
|
19
|
+
* - any other property must be equal (deep) on both sides, including being absent on both.
|
|
20
|
+
*
|
|
21
|
+
* A held wildcard permission with nothing but a name (e.g. `{ name: "cms.*" }`) is full access to
|
|
22
|
+
* everything it matches.
|
|
23
|
+
*
|
|
24
|
+
* Headless CMS links its group, model and entry permissions through `_src`, which is set to the
|
|
25
|
+
* role a permission comes from when it is loaded. So all `cms.` permissions of one requested
|
|
26
|
+
* role must be covered by the `cms.` permissions of a single held `_src` (one of the caller's
|
|
27
|
+
* roles), and only the first held permission of each name in it counts (that is the one the CMS
|
|
28
|
+
* uses). Other permissions are checked one by one against everything the caller holds.
|
|
29
|
+
*/
|
|
30
|
+
export declare const CANNOT_GRANT_PERMISSIONS_MESSAGE = "Not authorized! You can only grant permissions you have yourself.";
|
|
31
|
+
/**
|
|
32
|
+
* One group of requested permissions that end up together at runtime, i.e. one role.
|
|
33
|
+
*/
|
|
34
|
+
export type RequestedPermissions = SecurityPermission[];
|
|
35
|
+
/**
|
|
36
|
+
* Whether one held permission covers one requested permission.
|
|
37
|
+
*/
|
|
38
|
+
export declare const permissionCovers: (held: SecurityPermission, requested: SecurityPermission) => boolean;
|
|
39
|
+
/**
|
|
40
|
+
* Returns the requested permissions the holder of `held` permissions may not grant.
|
|
41
|
+
* An empty array means everything may be granted.
|
|
42
|
+
*/
|
|
43
|
+
export declare const findUngrantablePermissions: (held: SecurityPermission[], requested: RequestedPermissions[]) => SecurityPermission[];
|
|
44
|
+
/**
|
|
45
|
+
* Whether the current identity may grant everything in `requested`. Code running without
|
|
46
|
+
* authorization (installers, migrations) and full access may grant anything.
|
|
47
|
+
*/
|
|
48
|
+
export declare const canGrantPermissions: (identityContext: IdentityContext.Interface, requested: RequestedPermissions[]) => Promise<boolean>;
|
|
49
|
+
/**
|
|
50
|
+
* Whether the current identity has full access. Code running without authorization
|
|
51
|
+
* (installers, migrations) counts as full access.
|
|
52
|
+
*/
|
|
53
|
+
export declare const hasFullAccessOrNoAuthorization: (identityContext: IdentityContext.Interface) => Promise<boolean>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { minimatch } from "minimatch";
|
|
2
|
+
const CANNOT_GRANT_PERMISSIONS_MESSAGE = "Not authorized! You can only grant permissions you have yourself.";
|
|
3
|
+
const LINKED_PREFIXES = [
|
|
4
|
+
"cms."
|
|
5
|
+
];
|
|
6
|
+
const LETTER_KEYS = [
|
|
7
|
+
"rwd",
|
|
8
|
+
"pw"
|
|
9
|
+
];
|
|
10
|
+
const LIST_KEYS = [
|
|
11
|
+
"models",
|
|
12
|
+
"groups"
|
|
13
|
+
];
|
|
14
|
+
const IGNORED_KEYS = [
|
|
15
|
+
"name",
|
|
16
|
+
"_src"
|
|
17
|
+
];
|
|
18
|
+
const SIMPLE_NAME = /^(\*|[A-Za-z0-9_\-:]+(\.[A-Za-z0-9_\-:]+)*(\.\*)?)$/;
|
|
19
|
+
const isLinked = (permission)=>LINKED_PREFIXES.some((prefix)=>String(permission.name).startsWith(prefix));
|
|
20
|
+
const isPattern = (name)=>name.includes("*");
|
|
21
|
+
const isAbsent = (value)=>null == value;
|
|
22
|
+
const isPureWildcard = (permission)=>{
|
|
23
|
+
if (!isPattern(permission.name)) return false;
|
|
24
|
+
return Object.keys(permission).every((key)=>IGNORED_KEYS.includes(key) || isAbsent(permission[key]));
|
|
25
|
+
};
|
|
26
|
+
const deepEqual = (a, b)=>{
|
|
27
|
+
if (a === b) return true;
|
|
28
|
+
if (isAbsent(a) && isAbsent(b)) return true;
|
|
29
|
+
if ("object" != typeof a || "object" != typeof b || null === a || null === b) return false;
|
|
30
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
31
|
+
const keys = new Set([
|
|
32
|
+
...Object.keys(a),
|
|
33
|
+
...Object.keys(b)
|
|
34
|
+
]);
|
|
35
|
+
for (const key of keys)if (!deepEqual(a[key], b[key])) return false;
|
|
36
|
+
return true;
|
|
37
|
+
};
|
|
38
|
+
const nameCovers = (heldName, requestedName)=>{
|
|
39
|
+
if ("string" != typeof heldName || "string" != typeof requestedName) return false;
|
|
40
|
+
if (heldName === requestedName) return true;
|
|
41
|
+
if ("*" === heldName) return true;
|
|
42
|
+
if (!SIMPLE_NAME.test(requestedName)) return false;
|
|
43
|
+
if (!isPattern(heldName)) return false;
|
|
44
|
+
return minimatch(requestedName, heldName);
|
|
45
|
+
};
|
|
46
|
+
const lettersCover = (held, requested)=>{
|
|
47
|
+
if ("string" != typeof held || "string" != typeof requested) return false;
|
|
48
|
+
return requested.split("").every((letter)=>held.includes(letter));
|
|
49
|
+
};
|
|
50
|
+
const keyCovers = (key, held, requested)=>{
|
|
51
|
+
if ("rwd" === key) {
|
|
52
|
+
if (isAbsent(requested)) return isAbsent(held);
|
|
53
|
+
return lettersCover(held, requested);
|
|
54
|
+
}
|
|
55
|
+
if ("pw" === key) {
|
|
56
|
+
if (isAbsent(requested) || "" === requested) return true;
|
|
57
|
+
return lettersCover(held, requested);
|
|
58
|
+
}
|
|
59
|
+
if ("own" === key) {
|
|
60
|
+
if (true === held) return true === requested;
|
|
61
|
+
if (isAbsent(held) || false === held) return isAbsent(requested) || "boolean" == typeof requested;
|
|
62
|
+
return deepEqual(held, requested);
|
|
63
|
+
}
|
|
64
|
+
if (LIST_KEYS.includes(key)) {
|
|
65
|
+
if (isAbsent(held)) return true;
|
|
66
|
+
if (Array.isArray(held) && Array.isArray(requested)) return requested.every((item)=>held.some((heldItem)=>deepEqual(heldItem, item)));
|
|
67
|
+
}
|
|
68
|
+
return deepEqual(held, requested);
|
|
69
|
+
};
|
|
70
|
+
const permissionCovers = (held, requested)=>{
|
|
71
|
+
if (!nameCovers(held.name, requested.name)) return false;
|
|
72
|
+
if (isPureWildcard(held)) return true;
|
|
73
|
+
const keys = new Set([
|
|
74
|
+
...Object.keys(held),
|
|
75
|
+
...Object.keys(requested),
|
|
76
|
+
...LETTER_KEYS
|
|
77
|
+
]);
|
|
78
|
+
for (const key of keys)if (!IGNORED_KEYS.includes(key)) {
|
|
79
|
+
if (!keyCovers(key, held[key], requested[key])) return false;
|
|
80
|
+
}
|
|
81
|
+
return true;
|
|
82
|
+
};
|
|
83
|
+
const groupBySrc = (permissions)=>{
|
|
84
|
+
const groups = new Map();
|
|
85
|
+
for (const permission of permissions){
|
|
86
|
+
const key = permission._src;
|
|
87
|
+
const group = groups.get(key) ?? [];
|
|
88
|
+
if (!group.some((p)=>p.name === permission.name)) group.push(permission);
|
|
89
|
+
groups.set(key, group);
|
|
90
|
+
}
|
|
91
|
+
return Array.from(groups.values());
|
|
92
|
+
};
|
|
93
|
+
const findUngrantablePermissions = (held, requested)=>{
|
|
94
|
+
if (held.some((permission)=>"*" === permission.name)) return [];
|
|
95
|
+
const pureWildcards = held.filter(isPureWildcard);
|
|
96
|
+
const coveredByWildcard = (permission)=>pureWildcards.some((wildcard)=>nameCovers(wildcard.name, permission.name));
|
|
97
|
+
const heldLinkedGroups = groupBySrc(held.filter(isLinked));
|
|
98
|
+
const ungrantable = [];
|
|
99
|
+
for (const group of requested){
|
|
100
|
+
const permissions = (group ?? []).filter(Boolean);
|
|
101
|
+
for (const permission of permissions.filter((p)=>!isLinked(p)))if (!coveredByWildcard(permission)) {
|
|
102
|
+
if (!held.some((h)=>permissionCovers(h, permission))) ungrantable.push(permission);
|
|
103
|
+
}
|
|
104
|
+
const linked = permissions.filter((p)=>isLinked(p) && !coveredByWildcard(p));
|
|
105
|
+
if (0 === linked.length) continue;
|
|
106
|
+
const covered = heldLinkedGroups.some((heldGroup)=>linked.every((permission)=>heldGroup.some((h)=>permissionCovers(h, permission))));
|
|
107
|
+
if (!covered) ungrantable.push(...linked);
|
|
108
|
+
}
|
|
109
|
+
return ungrantable;
|
|
110
|
+
};
|
|
111
|
+
const canGrantPermissions = async (identityContext, requested)=>{
|
|
112
|
+
if (!identityContext.isAuthorizationEnabled()) return true;
|
|
113
|
+
const held = await identityContext.listPermissions();
|
|
114
|
+
return 0 === findUngrantablePermissions(held, requested).length;
|
|
115
|
+
};
|
|
116
|
+
const hasFullAccessOrNoAuthorization = async (identityContext)=>{
|
|
117
|
+
if (!identityContext.isAuthorizationEnabled()) return true;
|
|
118
|
+
return identityContext.hasFullAccess();
|
|
119
|
+
};
|
|
120
|
+
export { CANNOT_GRANT_PERMISSIONS_MESSAGE, canGrantPermissions, findUngrantablePermissions, hasFullAccessOrNoAuthorization, permissionCovers };
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=canGrantPermissions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/security/utils/canGrantPermissions.js","sources":["../../../../src/features/security/utils/canGrantPermissions.ts"],"sourcesContent":["import { minimatch } from \"minimatch\";\nimport type { IdentityContext } from \"~/features/security/IdentityContext/abstractions.js\";\nimport type { SecurityPermission } from \"~/types/security.js\";\n\n/**\n * Security: the \"cannot grant more than you hold\" rule.\n *\n * A caller may only write (into a role, or onto a user through roles and teams) permissions they\n * themselves hold. The check is conservative: when two permissions can't be compared safely, the\n * requested one must match the held one exactly.\n *\n * A requested permission is covered by a held permission when:\n * - the held name equals the requested name, or is a pattern that matches it (`cms.*`, `*`);\n * a requested name that is itself a pattern (anything beyond a trailing `.*`) must be held verbatim;\n * - `rwd` / `pw`: the held letters are a superset of the requested ones. A missing `rwd` means\n * full access (Headless CMS), so it is only covered by a held permission without `rwd`;\n * a missing or empty `pw` grants nothing;\n * - `own`: a held `own: true` only covers a requested `own: true`;\n * - `models` / `groups`: a held list only covers a requested list that is a subset of it;\n * a missing held list means \"no restriction\";\n * - any other property must be equal (deep) on both sides, including being absent on both.\n *\n * A held wildcard permission with nothing but a name (e.g. `{ name: \"cms.*\" }`) is full access to\n * everything it matches.\n *\n * Headless CMS links its group, model and entry permissions through `_src`, which is set to the\n * role a permission comes from when it is loaded. So all `cms.` permissions of one requested\n * role must be covered by the `cms.` permissions of a single held `_src` (one of the caller's\n * roles), and only the first held permission of each name in it counts (that is the one the CMS\n * uses). Other permissions are checked one by one against everything the caller holds.\n */\n\nexport const CANNOT_GRANT_PERMISSIONS_MESSAGE =\n \"Not authorized! You can only grant permissions you have yourself.\";\n\n/**\n * One group of requested permissions that end up together at runtime, i.e. one role.\n */\nexport type RequestedPermissions = SecurityPermission[];\n\nconst LINKED_PREFIXES = [\"cms.\"];\n\nconst LETTER_KEYS = [\"rwd\", \"pw\"];\nconst LIST_KEYS = [\"models\", \"groups\"];\nconst IGNORED_KEYS = [\"name\", \"_src\"];\n\n// A plain name (`security.role`) optionally ending with `.*`, or a bare `*`.\nconst SIMPLE_NAME = /^(\\*|[A-Za-z0-9_\\-:]+(\\.[A-Za-z0-9_\\-:]+)*(\\.\\*)?)$/;\n\nconst isLinked = (permission: SecurityPermission) => {\n return LINKED_PREFIXES.some(prefix => String(permission.name).startsWith(prefix));\n};\n\nconst isPattern = (name: string) => name.includes(\"*\");\n\nconst isAbsent = (value: unknown) => value === undefined || value === null;\n\nconst isPureWildcard = (permission: SecurityPermission) => {\n if (!isPattern(permission.name)) {\n return false;\n }\n return Object.keys(permission).every(\n key => IGNORED_KEYS.includes(key) || isAbsent(permission[key])\n );\n};\n\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) {\n return true;\n }\n if (isAbsent(a) && isAbsent(b)) {\n return true;\n }\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {\n return false;\n }\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false;\n }\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n if (!deepEqual((a as any)[key], (b as any)[key])) {\n return false;\n }\n }\n return true;\n};\n\nconst nameCovers = (heldName: string, requestedName: string): boolean => {\n if (typeof heldName !== \"string\" || typeof requestedName !== \"string\") {\n return false;\n }\n if (heldName === requestedName) {\n return true;\n }\n if (heldName === \"*\") {\n return true;\n }\n if (!SIMPLE_NAME.test(requestedName)) {\n // A requested pattern we can't reason about must be held verbatim.\n return false;\n }\n if (!isPattern(heldName)) {\n return false;\n }\n return minimatch(requestedName, heldName);\n};\n\nconst lettersCover = (held: unknown, requested: unknown): boolean => {\n if (typeof held !== \"string\" || typeof requested !== \"string\") {\n return false;\n }\n return requested.split(\"\").every(letter => held.includes(letter));\n};\n\nconst keyCovers = (key: string, held: unknown, requested: unknown): boolean => {\n if (key === \"rwd\") {\n if (isAbsent(requested)) {\n // A missing `rwd` means full access.\n return isAbsent(held);\n }\n return lettersCover(held, requested);\n }\n\n if (key === \"pw\") {\n if (isAbsent(requested) || requested === \"\") {\n return true;\n }\n return lettersCover(held, requested);\n }\n\n if (key === \"own\") {\n if (held === true) {\n return requested === true;\n }\n if (isAbsent(held) || held === false) {\n return isAbsent(requested) || typeof requested === \"boolean\";\n }\n return deepEqual(held, requested);\n }\n\n if (LIST_KEYS.includes(key)) {\n if (isAbsent(held)) {\n return true;\n }\n if (Array.isArray(held) && Array.isArray(requested)) {\n return requested.every(item => held.some(heldItem => deepEqual(heldItem, item)));\n }\n return deepEqual(held, requested);\n }\n\n return deepEqual(held, requested);\n};\n\n/**\n * Whether one held permission covers one requested permission.\n */\nexport const permissionCovers = (\n held: SecurityPermission,\n requested: SecurityPermission\n): boolean => {\n if (!nameCovers(held.name, requested.name)) {\n return false;\n }\n\n if (isPureWildcard(held)) {\n return true;\n }\n\n const keys = new Set([...Object.keys(held), ...Object.keys(requested), ...LETTER_KEYS]);\n for (const key of keys) {\n if (IGNORED_KEYS.includes(key)) {\n continue;\n }\n if (!keyCovers(key, held[key], requested[key])) {\n return false;\n }\n }\n\n return true;\n};\n\nconst groupBySrc = (permissions: SecurityPermission[]) => {\n const groups = new Map<unknown, SecurityPermission[]>();\n for (const permission of permissions) {\n const key = permission._src;\n const group = groups.get(key) ?? [];\n // Only the first permission of each name in a linked group is used by the CMS.\n if (!group.some(p => p.name === permission.name)) {\n group.push(permission);\n }\n groups.set(key, group);\n }\n return Array.from(groups.values());\n};\n\n/**\n * Returns the requested permissions the holder of `held` permissions may not grant.\n * An empty array means everything may be granted.\n */\nexport const findUngrantablePermissions = (\n held: SecurityPermission[],\n requested: RequestedPermissions[]\n): SecurityPermission[] => {\n if (held.some(permission => permission.name === \"*\")) {\n return [];\n }\n\n const pureWildcards = held.filter(isPureWildcard);\n const coveredByWildcard = (permission: SecurityPermission) => {\n return pureWildcards.some(wildcard => nameCovers(wildcard.name, permission.name));\n };\n\n const heldLinkedGroups = groupBySrc(held.filter(isLinked));\n\n const ungrantable: SecurityPermission[] = [];\n\n for (const group of requested) {\n const permissions = (group ?? []).filter(Boolean);\n\n // Independent permissions: any held permission may cover them.\n for (const permission of permissions.filter(p => !isLinked(p))) {\n if (coveredByWildcard(permission)) {\n continue;\n }\n if (!held.some(h => permissionCovers(h, permission))) {\n ungrantable.push(permission);\n }\n }\n\n // Linked permissions: one held group must cover all of them.\n const linked = permissions.filter(p => isLinked(p) && !coveredByWildcard(p));\n if (linked.length === 0) {\n continue;\n }\n\n const covered = heldLinkedGroups.some(heldGroup => {\n return linked.every(permission => heldGroup.some(h => permissionCovers(h, permission)));\n });\n\n if (!covered) {\n ungrantable.push(...linked);\n }\n }\n\n return ungrantable;\n};\n\n/**\n * Whether the current identity may grant everything in `requested`. Code running without\n * authorization (installers, migrations) and full access may grant anything.\n */\nexport const canGrantPermissions = async (\n identityContext: IdentityContext.Interface,\n requested: RequestedPermissions[]\n): Promise<boolean> => {\n if (!identityContext.isAuthorizationEnabled()) {\n return true;\n }\n\n const held = await identityContext.listPermissions();\n return findUngrantablePermissions(held, requested).length === 0;\n};\n\n/**\n * Whether the current identity has full access. Code running without authorization\n * (installers, migrations) counts as full access.\n */\nexport const hasFullAccessOrNoAuthorization = async (\n identityContext: IdentityContext.Interface\n): Promise<boolean> => {\n if (!identityContext.isAuthorizationEnabled()) {\n return true;\n }\n return identityContext.hasFullAccess();\n};\n"],"names":["CANNOT_GRANT_PERMISSIONS_MESSAGE","LINKED_PREFIXES","LETTER_KEYS","LIST_KEYS","IGNORED_KEYS","SIMPLE_NAME","isLinked","permission","prefix","String","isPattern","name","isAbsent","value","isPureWildcard","Object","key","deepEqual","a","b","Array","keys","Set","nameCovers","heldName","requestedName","minimatch","lettersCover","held","requested","letter","keyCovers","item","heldItem","permissionCovers","groupBySrc","permissions","groups","Map","group","p","findUngrantablePermissions","pureWildcards","coveredByWildcard","wildcard","heldLinkedGroups","ungrantable","Boolean","h","linked","covered","heldGroup","canGrantPermissions","identityContext","hasFullAccessOrNoAuthorization"],"mappings":"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"}
|
|
@@ -5,4 +5,19 @@ export type Jwt = {
|
|
|
5
5
|
header: jwt.JwtHeader;
|
|
6
6
|
payload: jwt.JwtPayload;
|
|
7
7
|
};
|
|
8
|
-
export
|
|
8
|
+
export interface VerifyJwtUsingJwkOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Expected `iss` claim. Compared ignoring trailing slashes (Auth0 issues `https://x.auth0.com/`).
|
|
11
|
+
* Skipped when not configured.
|
|
12
|
+
*/
|
|
13
|
+
issuer?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Expected `aud` claim (the client ID). Skipped when not configured.
|
|
16
|
+
*/
|
|
17
|
+
audience?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Providers read their config with `String(process.env.X)`, so a missing value becomes "undefined".
|
|
21
|
+
*/
|
|
22
|
+
export declare const isConfiguredJwtOption: (value: string | undefined | null) => value is string;
|
|
23
|
+
export declare const verifyJwtUsingJwk: (token: string, jwk: Jwk, options?: VerifyJwtUsingJwkOptions) => Promise<jwt.JwtPayload>;
|
|
@@ -1,10 +1,28 @@
|
|
|
1
1
|
import jsonwebtoken from "jsonwebtoken";
|
|
2
2
|
import { exportSPKI, importJWK } from "jose";
|
|
3
|
-
const
|
|
4
|
-
|
|
3
|
+
const isConfiguredJwtOption = (value)=>{
|
|
4
|
+
if ("string" != typeof value) return false;
|
|
5
|
+
const trimmed = value.trim();
|
|
6
|
+
return "" !== trimmed && "undefined" !== trimmed && "null" !== trimmed;
|
|
7
|
+
};
|
|
8
|
+
const normalizeIssuer = (value)=>value.trim().replace(/\/+$/, "");
|
|
9
|
+
const verifyJwtUsingJwk = async (token, jwk, options = {})=>{
|
|
10
|
+
const key = await importJWK(jwk, "RS256");
|
|
5
11
|
const pemKey = await exportSPKI(key);
|
|
6
|
-
|
|
12
|
+
const verifyOptions = {
|
|
13
|
+
algorithms: [
|
|
14
|
+
"RS256"
|
|
15
|
+
]
|
|
16
|
+
};
|
|
17
|
+
if (isConfiguredJwtOption(options.audience)) verifyOptions.audience = options.audience.trim();
|
|
18
|
+
const payload = jsonwebtoken.verify(token, pemKey, verifyOptions);
|
|
19
|
+
if (!payload || "string" == typeof payload) throw new jsonwebtoken.JsonWebTokenError("jwt payload is not an object");
|
|
20
|
+
if (isConfiguredJwtOption(options.issuer)) {
|
|
21
|
+
const tokenIssuer = "string" == typeof payload.iss ? normalizeIssuer(payload.iss) : "";
|
|
22
|
+
if (tokenIssuer !== normalizeIssuer(options.issuer)) throw new jsonwebtoken.JsonWebTokenError(`jwt issuer invalid. expected: ${options.issuer}`);
|
|
23
|
+
}
|
|
24
|
+
return payload;
|
|
7
25
|
};
|
|
8
|
-
export { verifyJwtUsingJwk };
|
|
26
|
+
export { isConfiguredJwtOption, verifyJwtUsingJwk };
|
|
9
27
|
|
|
10
28
|
//# sourceMappingURL=verifyJwtUsingJwk.js.map
|