mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-11-27 10:56:44 +00:00
Merge pull request #2615 from akhilmhdh/feat/permission-phase-2
Feat/permission phase 2
This commit is contained in:
@@ -56,7 +56,10 @@ describe("Secret expansion", () => {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
await Promise.all(secrets.map((el) => createSecretV2(el)));
|
for (const secret of secrets) {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await createSecretV2(secret);
|
||||||
|
}
|
||||||
|
|
||||||
const expandedSecret = await getSecretByNameV2({
|
const expandedSecret = await getSecretByNameV2({
|
||||||
environmentSlug: seedData1.environment.slug,
|
environmentSlug: seedData1.environment.slug,
|
||||||
@@ -123,7 +126,10 @@ describe("Secret expansion", () => {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
await Promise.all(secrets.map((el) => createSecretV2(el)));
|
for (const secret of secrets) {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await createSecretV2(secret);
|
||||||
|
}
|
||||||
|
|
||||||
const expandedSecret = await getSecretByNameV2({
|
const expandedSecret = await getSecretByNameV2({
|
||||||
environmentSlug: seedData1.environment.slug,
|
environmentSlug: seedData1.environment.slug,
|
||||||
@@ -190,7 +196,11 @@ describe("Secret expansion", () => {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
await Promise.all(secrets.map((el) => createSecretV2(el)));
|
for (const secret of secrets) {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await createSecretV2(secret);
|
||||||
|
}
|
||||||
|
|
||||||
const secretImportFromProdToDev = await createSecretImport({
|
const secretImportFromProdToDev = await createSecretImport({
|
||||||
environmentSlug: seedData1.environment.slug,
|
environmentSlug: seedData1.environment.slug,
|
||||||
workspaceId: projectId,
|
workspaceId: projectId,
|
||||||
@@ -275,7 +285,11 @@ describe("Secret expansion", () => {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
await Promise.all(secrets.map((el) => createSecretV2(el)));
|
for (const secret of secrets) {
|
||||||
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
await createSecretV2(secret);
|
||||||
|
}
|
||||||
|
|
||||||
const secretImportFromProdToDev = await createSecretImport({
|
const secretImportFromProdToDev = await createSecretImport({
|
||||||
environmentSlug: seedData1.environment.slug,
|
environmentSlug: seedData1.environment.slug,
|
||||||
workspaceId: projectId,
|
workspaceId: projectId,
|
||||||
|
|||||||
Generated
+348
-266
File diff suppressed because it is too large
Load Diff
Vendored
+2
@@ -13,6 +13,7 @@ import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secr
|
|||||||
import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
|
import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
|
||||||
import { TGroupServiceFactory } from "@app/ee/services/group/group-service";
|
import { TGroupServiceFactory } from "@app/ee/services/group/group-service";
|
||||||
import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
||||||
|
import { TIdentityProjectAdditionalPrivilegeV2ServiceFactory } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-service";
|
||||||
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
||||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||||
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
|
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
|
||||||
@@ -177,6 +178,7 @@ declare module "fastify" {
|
|||||||
dynamicSecretLease: TDynamicSecretLeaseServiceFactory;
|
dynamicSecretLease: TDynamicSecretLeaseServiceFactory;
|
||||||
projectUserAdditionalPrivilege: TProjectUserAdditionalPrivilegeServiceFactory;
|
projectUserAdditionalPrivilege: TProjectUserAdditionalPrivilegeServiceFactory;
|
||||||
identityProjectAdditionalPrivilege: TIdentityProjectAdditionalPrivilegeServiceFactory;
|
identityProjectAdditionalPrivilege: TIdentityProjectAdditionalPrivilegeServiceFactory;
|
||||||
|
identityProjectAdditionalPrivilegeV2: TIdentityProjectAdditionalPrivilegeV2ServiceFactory;
|
||||||
secretSharing: TSecretSharingServiceFactory;
|
secretSharing: TSecretSharingServiceFactory;
|
||||||
rateLimit: TRateLimitServiceFactory;
|
rateLimit: TRateLimitServiceFactory;
|
||||||
userEngagement: TUserEngagementServiceFactory;
|
userEngagement: TUserEngagementServiceFactory;
|
||||||
|
|||||||
@@ -4,27 +4,40 @@ import { TableName } from "../schemas";
|
|||||||
|
|
||||||
export async function up(knex: Knex): Promise<void> {
|
export async function up(knex: Knex): Promise<void> {
|
||||||
if (await knex.schema.hasTable(TableName.SecretSharing)) {
|
if (await knex.schema.hasTable(TableName.SecretSharing)) {
|
||||||
|
const hasEncryptedSecret = await knex.schema.hasColumn(TableName.SecretSharing, "encryptedSecret");
|
||||||
|
const hasIdentifier = await knex.schema.hasColumn(TableName.SecretSharing, "identifier");
|
||||||
|
|
||||||
await knex.schema.alterTable(TableName.SecretSharing, (t) => {
|
await knex.schema.alterTable(TableName.SecretSharing, (t) => {
|
||||||
t.string("iv").nullable().alter();
|
t.string("iv").nullable().alter();
|
||||||
t.string("tag").nullable().alter();
|
t.string("tag").nullable().alter();
|
||||||
t.string("encryptedValue").nullable().alter();
|
t.string("encryptedValue").nullable().alter();
|
||||||
|
|
||||||
t.binary("encryptedSecret").nullable();
|
if (!hasEncryptedSecret) {
|
||||||
|
t.binary("encryptedSecret").nullable();
|
||||||
|
}
|
||||||
t.string("hashedHex").nullable().alter();
|
t.string("hashedHex").nullable().alter();
|
||||||
|
|
||||||
t.string("identifier", 64).nullable();
|
if (!hasIdentifier) {
|
||||||
t.unique("identifier");
|
t.string("identifier", 64).nullable();
|
||||||
t.index("identifier");
|
t.unique("identifier");
|
||||||
|
t.index("identifier");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function down(knex: Knex): Promise<void> {
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasEncryptedSecret = await knex.schema.hasColumn(TableName.SecretSharing, "encryptedSecret");
|
||||||
|
const hasIdentifier = await knex.schema.hasColumn(TableName.SecretSharing, "identifier");
|
||||||
if (await knex.schema.hasTable(TableName.SecretSharing)) {
|
if (await knex.schema.hasTable(TableName.SecretSharing)) {
|
||||||
await knex.schema.alterTable(TableName.SecretSharing, (t) => {
|
await knex.schema.alterTable(TableName.SecretSharing, (t) => {
|
||||||
t.dropColumn("encryptedSecret");
|
if (hasEncryptedSecret) {
|
||||||
|
t.dropColumn("encryptedSecret");
|
||||||
|
}
|
||||||
|
|
||||||
t.dropColumn("identifier");
|
if (hasIdentifier) {
|
||||||
|
t.dropColumn("identifier");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,15 +7,18 @@ export async function up(knex: Knex): Promise<void> {
|
|||||||
if (await knex.schema.hasTable(TableName.KmsKey)) {
|
if (await knex.schema.hasTable(TableName.KmsKey)) {
|
||||||
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
||||||
const hasSlug = await knex.schema.hasColumn(TableName.KmsKey, "slug");
|
const hasSlug = await knex.schema.hasColumn(TableName.KmsKey, "slug");
|
||||||
|
const hasProjectId = await knex.schema.hasColumn(TableName.KmsKey, "projectId");
|
||||||
|
|
||||||
// drop constraint if exists (won't exist if rolled back, see below)
|
// drop constraint if exists (won't exist if rolled back, see below)
|
||||||
await dropConstraintIfExists(TableName.KmsKey, "kms_keys_orgid_slug_unique", knex);
|
await dropConstraintIfExists(TableName.KmsKey, "kms_keys_orgid_slug_unique", knex);
|
||||||
|
|
||||||
// projectId for CMEK functionality
|
// projectId for CMEK functionality
|
||||||
await knex.schema.alterTable(TableName.KmsKey, (table) => {
|
await knex.schema.alterTable(TableName.KmsKey, (table) => {
|
||||||
table.string("projectId").nullable().references("id").inTable(TableName.Project).onDelete("CASCADE");
|
if (!hasProjectId) {
|
||||||
|
table.string("projectId").nullable().references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||||
|
}
|
||||||
|
|
||||||
if (hasOrgId) {
|
if (hasOrgId && hasSlug) {
|
||||||
table.unique(["orgId", "projectId", "slug"]);
|
table.unique(["orgId", "projectId", "slug"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +33,7 @@ export async function down(knex: Knex): Promise<void> {
|
|||||||
if (await knex.schema.hasTable(TableName.KmsKey)) {
|
if (await knex.schema.hasTable(TableName.KmsKey)) {
|
||||||
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
||||||
const hasName = await knex.schema.hasColumn(TableName.KmsKey, "name");
|
const hasName = await knex.schema.hasColumn(TableName.KmsKey, "name");
|
||||||
|
const hasProjectId = await knex.schema.hasColumn(TableName.KmsKey, "projectId");
|
||||||
|
|
||||||
// remove projectId for CMEK functionality
|
// remove projectId for CMEK functionality
|
||||||
await knex.schema.alterTable(TableName.KmsKey, (table) => {
|
await knex.schema.alterTable(TableName.KmsKey, (table) => {
|
||||||
@@ -40,7 +44,9 @@ export async function down(knex: Knex): Promise<void> {
|
|||||||
if (hasOrgId) {
|
if (hasOrgId) {
|
||||||
table.dropUnique(["orgId", "projectId", "slug"]);
|
table.dropUnique(["orgId", "projectId", "slug"]);
|
||||||
}
|
}
|
||||||
table.dropColumn("projectId");
|
if (hasProjectId) {
|
||||||
|
table.dropColumn("projectId");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
/* eslint-disable no-await-in-loop */
|
||||||
|
import { packRules, unpackRules } from "@casl/ability/extra";
|
||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import {
|
||||||
|
backfillPermissionV1SchemaToV2Schema,
|
||||||
|
ProjectPermissionSub
|
||||||
|
} from "@app/ee/services/permission/project-permission";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
const CHUNK_SIZE = 1000;
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
const hasVersion = await knex.schema.hasColumn(TableName.ProjectRoles, "version");
|
||||||
|
if (!hasVersion) {
|
||||||
|
await knex.schema.alterTable(TableName.ProjectRoles, (t) => {
|
||||||
|
t.integer("version").defaultTo(1).notNullable();
|
||||||
|
});
|
||||||
|
|
||||||
|
const docs = await knex(TableName.ProjectRoles).select("*");
|
||||||
|
const updatedDocs = docs
|
||||||
|
.filter((i) => {
|
||||||
|
const permissionString = JSON.stringify(i.permissions || []);
|
||||||
|
return (
|
||||||
|
!permissionString.includes(ProjectPermissionSub.SecretImports) &&
|
||||||
|
!permissionString.includes(ProjectPermissionSub.DynamicSecrets)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.map((el) => ({
|
||||||
|
...el,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(unpackRules(el.permissions), true)))
|
||||||
|
}));
|
||||||
|
if (updatedDocs.length) {
|
||||||
|
for (let i = 0; i < updatedDocs.length; i += CHUNK_SIZE) {
|
||||||
|
const chunk = updatedDocs.slice(i, i + CHUNK_SIZE);
|
||||||
|
await knex(TableName.ProjectRoles).insert(chunk).onConflict("id").merge();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// secret permission is split into multiple ones like secrets, folders, imports and dynamic-secrets
|
||||||
|
// so we just find all the privileges with respective mapping and map it as needed
|
||||||
|
const identityPrivileges = await knex(TableName.IdentityProjectAdditionalPrivilege).select("*");
|
||||||
|
const updatedIdentityPrivilegesDocs = identityPrivileges
|
||||||
|
.filter((i) => {
|
||||||
|
const permissionString = JSON.stringify(i.permissions || []);
|
||||||
|
return (
|
||||||
|
!permissionString.includes(ProjectPermissionSub.SecretImports) &&
|
||||||
|
!permissionString.includes(ProjectPermissionSub.DynamicSecrets) &&
|
||||||
|
!permissionString.includes(ProjectPermissionSub.SecretFolders)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.map((el) => ({
|
||||||
|
...el,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(unpackRules(el.permissions))))
|
||||||
|
}));
|
||||||
|
if (updatedIdentityPrivilegesDocs.length) {
|
||||||
|
for (let i = 0; i < updatedIdentityPrivilegesDocs.length; i += CHUNK_SIZE) {
|
||||||
|
const chunk = updatedIdentityPrivilegesDocs.slice(i, i + CHUNK_SIZE);
|
||||||
|
await knex(TableName.IdentityProjectAdditionalPrivilege).insert(chunk).onConflict("id").merge();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const userPrivileges = await knex(TableName.ProjectUserAdditionalPrivilege).select("*");
|
||||||
|
const updatedUserPrivilegeDocs = userPrivileges
|
||||||
|
.filter((i) => {
|
||||||
|
const permissionString = JSON.stringify(i.permissions || []);
|
||||||
|
return (
|
||||||
|
!permissionString.includes(ProjectPermissionSub.SecretImports) &&
|
||||||
|
!permissionString.includes(ProjectPermissionSub.DynamicSecrets) &&
|
||||||
|
!permissionString.includes(ProjectPermissionSub.SecretFolders)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.map((el) => ({
|
||||||
|
...el,
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(unpackRules(el.permissions))))
|
||||||
|
}));
|
||||||
|
if (docs.length) {
|
||||||
|
for (let i = 0; i < updatedUserPrivilegeDocs.length; i += CHUNK_SIZE) {
|
||||||
|
const chunk = updatedUserPrivilegeDocs.slice(i, i + CHUNK_SIZE);
|
||||||
|
await knex(TableName.ProjectUserAdditionalPrivilege).insert(chunk).onConflict("id").merge();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasVersion = await knex.schema.hasColumn(TableName.ProjectRoles, "version");
|
||||||
|
if (hasVersion) {
|
||||||
|
await knex.schema.alterTable(TableName.ProjectRoles, (t) => {
|
||||||
|
t.dropColumn("version");
|
||||||
|
});
|
||||||
|
|
||||||
|
// permission change can be ignored
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import { packRules } from "@casl/ability/extra";
|
|
||||||
import slugify from "@sindresorhus/slugify";
|
import slugify from "@sindresorhus/slugify";
|
||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-types";
|
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-types";
|
||||||
|
import { backfillPermissionV1SchemaToV2Schema } from "@app/ee/services/permission/project-permission";
|
||||||
import { IDENTITY_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
import { IDENTITY_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
||||||
import { UnauthorizedError } from "@app/lib/errors";
|
import { UnauthorizedError } from "@app/lib/errors";
|
||||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
@@ -79,7 +79,9 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
|||||||
...req.body,
|
...req.body,
|
||||||
slug: req.body.slug ? slugify(req.body.slug) : slugify(alphaNumericNanoId(12)),
|
slug: req.body.slug ? slugify(req.body.slug) : slugify(alphaNumericNanoId(12)),
|
||||||
isTemporary: false,
|
isTemporary: false,
|
||||||
permissions: JSON.stringify(packRules(permission))
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||||
});
|
});
|
||||||
return { privilege };
|
return { privilege };
|
||||||
}
|
}
|
||||||
@@ -159,7 +161,9 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
|||||||
...req.body,
|
...req.body,
|
||||||
slug: req.body.slug ? slugify(req.body.slug) : slugify(alphaNumericNanoId(12)),
|
slug: req.body.slug ? slugify(req.body.slug) : slugify(alphaNumericNanoId(12)),
|
||||||
isTemporary: true,
|
isTemporary: true,
|
||||||
permissions: JSON.stringify(packRules(permission))
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||||
});
|
});
|
||||||
return { privilege };
|
return { privilege };
|
||||||
}
|
}
|
||||||
@@ -244,7 +248,13 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
|||||||
projectSlug: req.body.projectSlug,
|
projectSlug: req.body.projectSlug,
|
||||||
data: {
|
data: {
|
||||||
...updatedInfo,
|
...updatedInfo,
|
||||||
permissions: permission ? JSON.stringify(packRules(permission)) : undefined
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
permissions: permission
|
||||||
|
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
backfillPermissionV1SchemaToV2Schema(permission)
|
||||||
|
: undefined
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return { privilege };
|
return { privilege };
|
||||||
|
|||||||
@@ -81,9 +81,9 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
|
|||||||
await server.register(registerSecretVersionRouter, { prefix: "/secret" });
|
await server.register(registerSecretVersionRouter, { prefix: "/secret" });
|
||||||
await server.register(registerGroupRouter, { prefix: "/groups" });
|
await server.register(registerGroupRouter, { prefix: "/groups" });
|
||||||
await server.register(registerAuditLogStreamRouter, { prefix: "/audit-log-streams" });
|
await server.register(registerAuditLogStreamRouter, { prefix: "/audit-log-streams" });
|
||||||
|
await server.register(registerUserAdditionalPrivilegeRouter, { prefix: "/user-project-additional-privilege" });
|
||||||
await server.register(
|
await server.register(
|
||||||
async (privilegeRouter) => {
|
async (privilegeRouter) => {
|
||||||
await privilegeRouter.register(registerUserAdditionalPrivilegeRouter, { prefix: "/users" });
|
|
||||||
await privilegeRouter.register(registerIdentityProjectAdditionalPrivilegeRouter, { prefix: "/identity" });
|
await privilegeRouter.register(registerIdentityProjectAdditionalPrivilegeRouter, { prefix: "/identity" });
|
||||||
},
|
},
|
||||||
{ prefix: "/additional-privilege" }
|
{ prefix: "/additional-privilege" }
|
||||||
|
|||||||
@@ -3,12 +3,16 @@ import slugify from "@sindresorhus/slugify";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { ProjectMembershipRole, ProjectMembershipsSchema, ProjectRolesSchema } from "@app/db/schemas";
|
import { ProjectMembershipRole, ProjectMembershipsSchema, ProjectRolesSchema } from "@app/db/schemas";
|
||||||
import { ProjectPermissionSchema } from "@app/ee/services/permission/project-permission";
|
import {
|
||||||
|
backfillPermissionV1SchemaToV2Schema,
|
||||||
|
ProjectPermissionV1Schema
|
||||||
|
} from "@app/ee/services/permission/project-permission";
|
||||||
import { PROJECT_ROLE } from "@app/lib/api-docs";
|
import { PROJECT_ROLE } from "@app/lib/api-docs";
|
||||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
|
import { SanitizedRoleSchemaV1 } from "@app/server/routes/sanitizedSchemas";
|
||||||
import { AuthMode } from "@app/services/auth/auth-type";
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
|
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
|
||||||
|
|
||||||
export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||||
server.route({
|
server.route({
|
||||||
@@ -43,11 +47,11 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
.describe(PROJECT_ROLE.CREATE.slug),
|
.describe(PROJECT_ROLE.CREATE.slug),
|
||||||
name: z.string().min(1).trim().describe(PROJECT_ROLE.CREATE.name),
|
name: z.string().min(1).trim().describe(PROJECT_ROLE.CREATE.name),
|
||||||
description: z.string().trim().optional().describe(PROJECT_ROLE.CREATE.description),
|
description: z.string().trim().optional().describe(PROJECT_ROLE.CREATE.description),
|
||||||
permissions: ProjectPermissionSchema.array().describe(PROJECT_ROLE.CREATE.permissions)
|
permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.CREATE.permissions)
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
role: SanitizedRoleSchema
|
role: SanitizedRoleSchemaV1
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -58,12 +62,16 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
projectSlug: req.params.projectSlug,
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||||
|
projectSlug: req.params.projectSlug
|
||||||
|
},
|
||||||
data: {
|
data: {
|
||||||
...req.body,
|
...req.body,
|
||||||
permissions: JSON.stringify(packRules(req.body.permissions))
|
permissions: JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return { role };
|
return { role };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -103,11 +111,11 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
}),
|
}),
|
||||||
name: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.name),
|
name: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.name),
|
||||||
description: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.description),
|
description: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.description),
|
||||||
permissions: ProjectPermissionSchema.array().describe(PROJECT_ROLE.UPDATE.permissions).optional()
|
permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.UPDATE.permissions).optional()
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
role: SanitizedRoleSchema
|
role: SanitizedRoleSchemaV1
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -118,11 +126,12 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
projectSlug: req.params.projectSlug,
|
|
||||||
roleId: req.params.roleId,
|
roleId: req.params.roleId,
|
||||||
data: {
|
data: {
|
||||||
...req.body,
|
...req.body,
|
||||||
permissions: req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined
|
permissions: req.body.permissions
|
||||||
|
? JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
|
||||||
|
: undefined
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return { role };
|
return { role };
|
||||||
@@ -148,7 +157,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
role: SanitizedRoleSchema
|
role: SanitizedRoleSchemaV1
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -159,7 +168,6 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
projectSlug: req.params.projectSlug,
|
|
||||||
roleId: req.params.roleId
|
roleId: req.params.roleId
|
||||||
});
|
});
|
||||||
return { role };
|
return { role };
|
||||||
@@ -195,7 +203,10 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
projectSlug: req.params.projectSlug
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||||
|
projectSlug: req.params.projectSlug
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return { roles };
|
return { roles };
|
||||||
}
|
}
|
||||||
@@ -214,7 +225,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
role: SanitizedRoleSchema
|
role: SanitizedRoleSchemaV1
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -225,9 +236,13 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
projectSlug: req.params.projectSlug,
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||||
|
projectSlug: req.params.projectSlug
|
||||||
|
},
|
||||||
roleSlug: req.params.slug
|
roleSlug: req.params.slug
|
||||||
});
|
});
|
||||||
|
|
||||||
return { role };
|
return { role };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,17 +2,18 @@ import slugify from "@sindresorhus/slugify";
|
|||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { ProjectUserAdditionalPrivilegeSchema } from "@app/db/schemas";
|
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||||
import { ProjectUserAdditionalPrivilegeTemporaryMode } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-types";
|
import { ProjectUserAdditionalPrivilegeTemporaryMode } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-types";
|
||||||
import { PROJECT_USER_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
import { PROJECT_USER_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
||||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
|
import { SanitizedUserProjectAdditionalPrivilegeSchema } from "@app/server/routes/santizedSchemas/user-additional-privilege";
|
||||||
import { AuthMode } from "@app/services/auth/auth-type";
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
|
|
||||||
export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
||||||
server.route({
|
server.route({
|
||||||
url: "/permanent",
|
url: "/",
|
||||||
method: "POST",
|
method: "POST",
|
||||||
config: {
|
config: {
|
||||||
rateLimit: writeLimit
|
rateLimit: writeLimit
|
||||||
@@ -31,66 +32,30 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
})
|
})
|
||||||
.optional()
|
.optional()
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.slug),
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.slug),
|
||||||
permissions: z.any().array().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.permissions)
|
permissions: ProjectPermissionV2Schema.array().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.permissions),
|
||||||
}),
|
type: z.discriminatedUnion("isTemporary", [
|
||||||
response: {
|
z.object({
|
||||||
200: z.object({
|
isTemporary: z.literal(false)
|
||||||
privilege: ProjectUserAdditionalPrivilegeSchema
|
}),
|
||||||
})
|
z.object({
|
||||||
}
|
isTemporary: z.literal(true),
|
||||||
},
|
temporaryMode: z
|
||||||
onRequest: verifyAuth([AuthMode.JWT]),
|
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
||||||
handler: async (req) => {
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryMode),
|
||||||
const privilege = await server.services.projectUserAdditionalPrivilege.create({
|
temporaryRange: z
|
||||||
actorId: req.permission.id,
|
.string()
|
||||||
actor: req.permission.type,
|
.refine((val) => ms(val) > 0, "Temporary range must be a positive number")
|
||||||
actorOrgId: req.permission.orgId,
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryRange),
|
||||||
actorAuthMethod: req.permission.authMethod,
|
temporaryAccessStartTime: z
|
||||||
...req.body,
|
.string()
|
||||||
slug: req.body.slug ? slugify(req.body.slug) : slugify(alphaNumericNanoId(12)),
|
.datetime()
|
||||||
isTemporary: false,
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryAccessStartTime)
|
||||||
permissions: JSON.stringify(req.body.permissions)
|
|
||||||
});
|
|
||||||
return { privilege };
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
server.route({
|
|
||||||
method: "POST",
|
|
||||||
url: "/temporary",
|
|
||||||
config: {
|
|
||||||
rateLimit: writeLimit
|
|
||||||
},
|
|
||||||
schema: {
|
|
||||||
body: z.object({
|
|
||||||
projectMembershipId: z.string().min(1).describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.projectMembershipId),
|
|
||||||
slug: z
|
|
||||||
.string()
|
|
||||||
.min(1)
|
|
||||||
.max(60)
|
|
||||||
.trim()
|
|
||||||
.refine((v) => v.toLowerCase() === v, "Slug must be lowercase")
|
|
||||||
.refine((v) => slugify(v) === v, {
|
|
||||||
message: "Slug must be a valid slug"
|
|
||||||
})
|
})
|
||||||
.optional()
|
])
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.slug),
|
|
||||||
permissions: z.any().array().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.permissions),
|
|
||||||
temporaryMode: z
|
|
||||||
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryMode),
|
|
||||||
temporaryRange: z
|
|
||||||
.string()
|
|
||||||
.refine((val) => ms(val) > 0, "Temporary range must be a positive number")
|
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryRange),
|
|
||||||
temporaryAccessStartTime: z
|
|
||||||
.string()
|
|
||||||
.datetime()
|
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryAccessStartTime)
|
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
privilege: ProjectUserAdditionalPrivilegeSchema
|
privilege: SanitizedUserProjectAdditionalPrivilegeSchema
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -101,10 +66,10 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
...req.body,
|
projectMembershipId: req.body.projectMembershipId,
|
||||||
slug: req.body.slug ? slugify(req.body.slug) : `privilege-${slugify(alphaNumericNanoId(12))}`,
|
...req.body.type,
|
||||||
isTemporary: true,
|
slug: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||||
permissions: JSON.stringify(req.body.permissions)
|
permissions: req.body.permissions
|
||||||
});
|
});
|
||||||
return { privilege };
|
return { privilege };
|
||||||
}
|
}
|
||||||
@@ -131,24 +96,31 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
message: "Slug must be a valid slug"
|
message: "Slug must be a valid slug"
|
||||||
})
|
})
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.slug),
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.slug),
|
||||||
permissions: z.any().array().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.permissions),
|
permissions: ProjectPermissionV2Schema.array()
|
||||||
isTemporary: z.boolean().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.isTemporary),
|
.optional()
|
||||||
temporaryMode: z
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.permissions),
|
||||||
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
type: z.discriminatedUnion("isTemporary", [
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryMode),
|
z.object({ isTemporary: z.literal(false).describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.isTemporary) }),
|
||||||
temporaryRange: z
|
z.object({
|
||||||
.string()
|
isTemporary: z.literal(true).describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.isTemporary),
|
||||||
.refine((val) => ms(val) > 0, "Temporary range must be a positive number")
|
temporaryMode: z
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryRange),
|
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
||||||
temporaryAccessStartTime: z
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryMode),
|
||||||
.string()
|
temporaryRange: z
|
||||||
.datetime()
|
.string()
|
||||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryAccessStartTime)
|
.refine((val) => typeof val === "undefined" || ms(val) > 0, "Temporary range must be a positive number")
|
||||||
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryRange),
|
||||||
|
temporaryAccessStartTime: z
|
||||||
|
.string()
|
||||||
|
.datetime()
|
||||||
|
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryAccessStartTime)
|
||||||
|
})
|
||||||
|
])
|
||||||
})
|
})
|
||||||
.partial(),
|
.partial(),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
privilege: ProjectUserAdditionalPrivilegeSchema
|
privilege: SanitizedUserProjectAdditionalPrivilegeSchema
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -160,7 +132,12 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
...req.body,
|
...req.body,
|
||||||
permissions: req.body.permissions ? JSON.stringify(req.body.permissions) : undefined,
|
...req.body.type,
|
||||||
|
permissions: req.body.permissions
|
||||||
|
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
req.body.permissions
|
||||||
|
: undefined,
|
||||||
privilegeId: req.params.privilegeId
|
privilegeId: req.params.privilegeId
|
||||||
});
|
});
|
||||||
return { privilege };
|
return { privilege };
|
||||||
@@ -179,7 +156,7 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
privilege: ProjectUserAdditionalPrivilegeSchema
|
privilege: SanitizedUserProjectAdditionalPrivilegeSchema
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -208,7 +185,7 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
privileges: ProjectUserAdditionalPrivilegeSchema.array()
|
privileges: SanitizedUserProjectAdditionalPrivilegeSchema.omit({ permissions: true }).array()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -233,11 +210,11 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
|||||||
},
|
},
|
||||||
schema: {
|
schema: {
|
||||||
params: z.object({
|
params: z.object({
|
||||||
privilegeId: z.string().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.GET_BY_PRIVILEGEID.privilegeId)
|
privilegeId: z.string().describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.GET_BY_PRIVILEGE_ID.privilegeId)
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
privilege: ProjectUserAdditionalPrivilegeSchema
|
privilege: SanitizedUserProjectAdditionalPrivilegeSchema
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
import slugify from "@sindresorhus/slugify";
|
||||||
|
import ms from "ms";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-types";
|
||||||
|
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||||
|
import { IDENTITY_ADDITIONAL_PRIVILEGE_V2 } from "@app/lib/api-docs";
|
||||||
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
|
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
|
import { SanitizedIdentityPrivilegeSchema } from "@app/server/routes/santizedSchemas/identitiy-additional-privilege";
|
||||||
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
|
|
||||||
|
export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
||||||
|
server.route({
|
||||||
|
method: "POST",
|
||||||
|
url: "/",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Add an additional privilege for identity.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
body: z.object({
|
||||||
|
identityId: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.identityId),
|
||||||
|
projectId: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.projectId),
|
||||||
|
slug: z
|
||||||
|
.string()
|
||||||
|
.min(1)
|
||||||
|
.max(60)
|
||||||
|
.trim()
|
||||||
|
.refine((val) => val.toLowerCase() === val, "Must be lowercase")
|
||||||
|
.refine((v) => slugify(v) === v, {
|
||||||
|
message: "Slug must be a valid slug"
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.slug),
|
||||||
|
permissions: ProjectPermissionV2Schema.array().describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.permission),
|
||||||
|
type: z.discriminatedUnion("isTemporary", [
|
||||||
|
z.object({
|
||||||
|
isTemporary: z.literal(false)
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
isTemporary: z.literal(true),
|
||||||
|
temporaryMode: z
|
||||||
|
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.temporaryMode),
|
||||||
|
temporaryRange: z
|
||||||
|
.string()
|
||||||
|
.refine((val) => ms(val) > 0, "Temporary range must be a positive number")
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.temporaryRange),
|
||||||
|
temporaryAccessStartTime: z
|
||||||
|
.string()
|
||||||
|
.datetime()
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.temporaryAccessStartTime)
|
||||||
|
})
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privilege: SanitizedIdentityPrivilegeSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.create({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
projectId: req.body.projectId,
|
||||||
|
identityId: req.body.identityId,
|
||||||
|
...req.body.type,
|
||||||
|
slug: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||||
|
permissions: req.body.permissions
|
||||||
|
});
|
||||||
|
return { privilege };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "PATCH",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Update a specific identity privilege.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.id)
|
||||||
|
}),
|
||||||
|
body: z.object({
|
||||||
|
slug: z
|
||||||
|
.string()
|
||||||
|
.min(1)
|
||||||
|
.max(60)
|
||||||
|
.trim()
|
||||||
|
.refine((val) => val.toLowerCase() === val, "Must be lowercase")
|
||||||
|
.refine((v) => slugify(v) === v, {
|
||||||
|
message: "Slug must be a valid slug"
|
||||||
|
})
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.slug),
|
||||||
|
permissions: ProjectPermissionV2Schema.array()
|
||||||
|
.optional()
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.privilegePermission),
|
||||||
|
type: z.discriminatedUnion("isTemporary", [
|
||||||
|
z.object({ isTemporary: z.literal(false).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.isTemporary) }),
|
||||||
|
z.object({
|
||||||
|
isTemporary: z.literal(true).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.isTemporary),
|
||||||
|
temporaryMode: z
|
||||||
|
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.temporaryMode),
|
||||||
|
temporaryRange: z
|
||||||
|
.string()
|
||||||
|
.refine((val) => typeof val === "undefined" || ms(val) > 0, "Temporary range must be a positive number")
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.temporaryRange),
|
||||||
|
temporaryAccessStartTime: z
|
||||||
|
.string()
|
||||||
|
.datetime()
|
||||||
|
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.temporaryAccessStartTime)
|
||||||
|
})
|
||||||
|
])
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privilege: SanitizedIdentityPrivilegeSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.updateById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
id: req.params.id,
|
||||||
|
data: {
|
||||||
|
...req.body,
|
||||||
|
...req.body.type,
|
||||||
|
permissions: req.body.permissions || undefined
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { privilege };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "DELETE",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Delete the specified identity privilege.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.DELETE.id)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privilege: SanitizedIdentityPrivilegeSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.deleteById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { privilege };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Retrieve details of a specific privilege by id.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.GET_BY_ID.id)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privilege: SanitizedIdentityPrivilegeSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.getPrivilegeDetailsById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { privilege };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/slug/:privilegeSlug",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Retrieve details of a specific privilege by slug.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
privilegeSlug: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.GET_BY_SLUG.slug)
|
||||||
|
}),
|
||||||
|
querystring: z.object({
|
||||||
|
identityId: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.GET_BY_SLUG.identityId),
|
||||||
|
projectSlug: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.GET_BY_SLUG.projectSlug)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privilege: SanitizedIdentityPrivilegeSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.getPrivilegeDetailsBySlug({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
slug: req.params.privilegeSlug,
|
||||||
|
...req.query
|
||||||
|
});
|
||||||
|
return { privilege };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "List privileges for the specified identity by project.",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
querystring: z.object({
|
||||||
|
identityId: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.LIST.identityId),
|
||||||
|
projectId: z.string().min(1).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.LIST.projectId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
privileges: SanitizedIdentityPrivilegeSchema.omit({ permissions: true }).array()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const privileges = await server.services.identityProjectAdditionalPrivilegeV2.listIdentityProjectPrivileges({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
...req.query
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
privileges
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { registerIdentityProjectAdditionalPrivilegeRouter } from "./identity-project-additional-privilege-router";
|
||||||
|
import { registerProjectRoleRouter } from "./project-role-router";
|
||||||
|
|
||||||
|
export const registerV2EERoutes = async (server: FastifyZodProvider) => {
|
||||||
|
// org role starts with organization
|
||||||
|
await server.register(
|
||||||
|
async (projectRouter) => {
|
||||||
|
await projectRouter.register(registerProjectRoleRouter);
|
||||||
|
},
|
||||||
|
{ prefix: "/workspace" }
|
||||||
|
);
|
||||||
|
|
||||||
|
await server.register(registerIdentityProjectAdditionalPrivilegeRouter, {
|
||||||
|
prefix: "/identity-project-additional-privilege"
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
import { packRules } from "@casl/ability/extra";
|
||||||
|
import slugify from "@sindresorhus/slugify";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||||
|
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||||
|
import { PROJECT_ROLE } from "@app/lib/api-docs";
|
||||||
|
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
|
import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
|
||||||
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
|
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
|
||||||
|
|
||||||
|
export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||||
|
server.route({
|
||||||
|
method: "POST",
|
||||||
|
url: "/:projectId/roles",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Create a project role",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
projectId: z.string().trim().describe(PROJECT_ROLE.CREATE.projectId)
|
||||||
|
}),
|
||||||
|
body: z.object({
|
||||||
|
slug: z
|
||||||
|
.string()
|
||||||
|
.toLowerCase()
|
||||||
|
.trim()
|
||||||
|
.min(1)
|
||||||
|
.refine(
|
||||||
|
(val) => !Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
|
||||||
|
"Please choose a different slug, the slug you have entered is reserved"
|
||||||
|
)
|
||||||
|
.refine((v) => slugify(v) === v, {
|
||||||
|
message: "Slug must be a valid"
|
||||||
|
})
|
||||||
|
.describe(PROJECT_ROLE.CREATE.slug),
|
||||||
|
name: z.string().min(1).trim().describe(PROJECT_ROLE.CREATE.name),
|
||||||
|
description: z.string().trim().optional().describe(PROJECT_ROLE.CREATE.description),
|
||||||
|
permissions: ProjectPermissionV2Schema.array().describe(PROJECT_ROLE.CREATE.permissions)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
role: SanitizedRoleSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const role = await server.services.projectRole.createRole({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.ID,
|
||||||
|
projectId: req.params.projectId
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
...req.body,
|
||||||
|
permissions: JSON.stringify(packRules(req.body.permissions))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { role };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "PATCH",
|
||||||
|
url: "/:projectId/roles/:roleId",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Update a project role",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
projectId: z.string().trim().describe(PROJECT_ROLE.UPDATE.projectId),
|
||||||
|
roleId: z.string().trim().describe(PROJECT_ROLE.UPDATE.roleId)
|
||||||
|
}),
|
||||||
|
body: z.object({
|
||||||
|
slug: z
|
||||||
|
.string()
|
||||||
|
.toLowerCase()
|
||||||
|
.trim()
|
||||||
|
.optional()
|
||||||
|
.describe(PROJECT_ROLE.UPDATE.slug)
|
||||||
|
.refine(
|
||||||
|
(val) =>
|
||||||
|
typeof val === "undefined" ||
|
||||||
|
!Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
|
||||||
|
"Please choose a different slug, the slug you have entered is reserved"
|
||||||
|
)
|
||||||
|
.refine((val) => typeof val === "undefined" || slugify(val) === val, {
|
||||||
|
message: "Slug must be a valid"
|
||||||
|
}),
|
||||||
|
name: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.name),
|
||||||
|
description: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.description),
|
||||||
|
permissions: ProjectPermissionV2Schema.array().describe(PROJECT_ROLE.UPDATE.permissions).optional()
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
role: SanitizedRoleSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const role = await server.services.projectRole.updateRole({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
roleId: req.params.roleId,
|
||||||
|
data: {
|
||||||
|
...req.body,
|
||||||
|
permissions: req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { role };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "DELETE",
|
||||||
|
url: "/:projectId/roles/:roleId",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Delete a project role",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
projectId: z.string().trim().describe(PROJECT_ROLE.DELETE.projectId),
|
||||||
|
roleId: z.string().trim().describe(PROJECT_ROLE.DELETE.roleId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
role: SanitizedRoleSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const role = await server.services.projectRole.deleteRole({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
roleId: req.params.roleId
|
||||||
|
});
|
||||||
|
return { role };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:projectId/roles",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "List project role",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
projectId: z.string().trim().describe(PROJECT_ROLE.LIST.projectId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
roles: ProjectRolesSchema.omit({ permissions: true }).array()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const roles = await server.services.projectRole.listRoles({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.ID,
|
||||||
|
projectId: req.params.projectId
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { roles };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:projectId/roles/slug/:roleSlug",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
projectId: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.projectId),
|
||||||
|
roleSlug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.roleSlug)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
role: SanitizedRoleSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const role = await server.services.projectRole.getRoleBySlug({
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actor: req.permission.type,
|
||||||
|
filter: {
|
||||||
|
type: ProjectRoleServiceIdentifierType.ID,
|
||||||
|
projectId: req.params.projectId
|
||||||
|
},
|
||||||
|
roleSlug: req.params.roleSlug
|
||||||
|
});
|
||||||
|
return { role };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -14,7 +14,7 @@ export const accessApprovalPolicyDALFactory = (db: TDbClient) => {
|
|||||||
|
|
||||||
const accessApprovalPolicyFindQuery = async (
|
const accessApprovalPolicyFindQuery = async (
|
||||||
tx: Knex,
|
tx: Knex,
|
||||||
filter: TFindFilter<TAccessApprovalPolicies>,
|
filter: TFindFilter<TAccessApprovalPolicies & { projectId: string }>,
|
||||||
customFilter?: {
|
customFilter?: {
|
||||||
policyId?: string;
|
policyId?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
import { ForbiddenError, subject } from "@casl/ability";
|
|
||||||
|
|
||||||
import { ActorType } from "@app/services/auth/auth-type";
|
|
||||||
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
|
|
||||||
import { TIsApproversValid } from "./access-approval-policy-types";
|
|
||||||
|
|
||||||
export const isApproversValid = async ({
|
|
||||||
userIds,
|
|
||||||
projectId,
|
|
||||||
orgId,
|
|
||||||
envSlug,
|
|
||||||
actorAuthMethod,
|
|
||||||
secretPath,
|
|
||||||
permissionService
|
|
||||||
}: TIsApproversValid) => {
|
|
||||||
try {
|
|
||||||
for await (const userId of userIds) {
|
|
||||||
const { permission: approverPermission } = await permissionService.getProjectPermission(
|
|
||||||
ActorType.USER,
|
|
||||||
userId,
|
|
||||||
projectId,
|
|
||||||
actorAuthMethod,
|
|
||||||
orgId
|
|
||||||
);
|
|
||||||
|
|
||||||
ForbiddenError.from(approverPermission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Create,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: envSlug, secretPath })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
@@ -11,7 +11,6 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
|
|||||||
import { TGroupDALFactory } from "../group/group-dal";
|
import { TGroupDALFactory } from "../group/group-dal";
|
||||||
import { TAccessApprovalPolicyApproverDALFactory } from "./access-approval-policy-approver-dal";
|
import { TAccessApprovalPolicyApproverDALFactory } from "./access-approval-policy-approver-dal";
|
||||||
import { TAccessApprovalPolicyDALFactory } from "./access-approval-policy-dal";
|
import { TAccessApprovalPolicyDALFactory } from "./access-approval-policy-dal";
|
||||||
import { isApproversValid } from "./access-approval-policy-fns";
|
|
||||||
import {
|
import {
|
||||||
ApproverType,
|
ApproverType,
|
||||||
TCreateAccessApprovalPolicy,
|
TCreateAccessApprovalPolicy,
|
||||||
@@ -134,22 +133,6 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
.map((user) => user.id);
|
.map((user) => user.id);
|
||||||
verifyAllApprovers.push(...verifyGroupApprovers);
|
verifyAllApprovers.push(...verifyGroupApprovers);
|
||||||
|
|
||||||
const approversValid = await isApproversValid({
|
|
||||||
projectId: project.id,
|
|
||||||
orgId: actorOrgId,
|
|
||||||
envSlug: environment,
|
|
||||||
secretPath,
|
|
||||||
actorAuthMethod,
|
|
||||||
permissionService,
|
|
||||||
userIds: verifyAllApprovers
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!approversValid) {
|
|
||||||
throw new BadRequestError({
|
|
||||||
message: "One or more approvers doesn't have access to be specified secret path"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const accessApproval = await accessApprovalPolicyDAL.transaction(async (tx) => {
|
const accessApproval = await accessApprovalPolicyDAL.transaction(async (tx) => {
|
||||||
const doc = await accessApprovalPolicyDAL.create(
|
const doc = await accessApprovalPolicyDAL.create(
|
||||||
{
|
{
|
||||||
@@ -293,22 +276,6 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
userApproverIds = userApproverIds.concat(approverUsers.map((user) => user.id));
|
userApproverIds = userApproverIds.concat(approverUsers.map((user) => user.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
const approversValid = await isApproversValid({
|
|
||||||
projectId: accessApprovalPolicy.projectId,
|
|
||||||
orgId: actorOrgId,
|
|
||||||
envSlug: accessApprovalPolicy.environment.slug,
|
|
||||||
secretPath: doc.secretPath!,
|
|
||||||
actorAuthMethod,
|
|
||||||
permissionService,
|
|
||||||
userIds: userApproverIds
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!approversValid) {
|
|
||||||
throw new BadRequestError({
|
|
||||||
message: "One or more approvers doesn't have access to be specified secret path"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await accessApprovalPolicyApproverDAL.insertMany(
|
await accessApprovalPolicyApproverDAL.insertMany(
|
||||||
userApproverIds.map((userId) => ({
|
userApproverIds.map((userId) => ({
|
||||||
approverUserId: userId,
|
approverUserId: userId,
|
||||||
@@ -319,45 +286,6 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (groupApprovers) {
|
if (groupApprovers) {
|
||||||
const usersPromises: Promise<
|
|
||||||
{
|
|
||||||
id: string;
|
|
||||||
email: string | null | undefined;
|
|
||||||
username: string;
|
|
||||||
firstName: string | null | undefined;
|
|
||||||
lastName: string | null | undefined;
|
|
||||||
isPartOfGroup: boolean;
|
|
||||||
}[]
|
|
||||||
>[] = [];
|
|
||||||
|
|
||||||
for (const groupId of groupApprovers) {
|
|
||||||
usersPromises.push(
|
|
||||||
groupDAL
|
|
||||||
.findAllGroupPossibleMembers({ orgId: actorOrgId, groupId, offset: 0 })
|
|
||||||
.then((group) => group.members)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const verifyGroupApprovers = (await Promise.all(usersPromises))
|
|
||||||
.flat()
|
|
||||||
.filter((user) => user.isPartOfGroup)
|
|
||||||
.map((user) => user.id);
|
|
||||||
|
|
||||||
const approversValid = await isApproversValid({
|
|
||||||
projectId: accessApprovalPolicy.projectId,
|
|
||||||
orgId: actorOrgId,
|
|
||||||
envSlug: accessApprovalPolicy.environment.slug,
|
|
||||||
secretPath: doc.secretPath!,
|
|
||||||
actorAuthMethod,
|
|
||||||
permissionService,
|
|
||||||
userIds: verifyGroupApprovers
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!approversValid) {
|
|
||||||
throw new BadRequestError({
|
|
||||||
message: "One or more approvers doesn't have access to be specified secret path"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await accessApprovalPolicyApproverDAL.insertMany(
|
await accessApprovalPolicyApproverDAL.insertMany(
|
||||||
groupApprovers.map((groupId) => ({
|
groupApprovers.map((groupId) => ({
|
||||||
approverGroupId: groupId,
|
approverGroupId: groupId,
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import { TUserDALFactory } from "@app/services/user/user-dal";
|
|||||||
|
|
||||||
import { TAccessApprovalPolicyApproverDALFactory } from "../access-approval-policy/access-approval-policy-approver-dal";
|
import { TAccessApprovalPolicyApproverDALFactory } from "../access-approval-policy/access-approval-policy-approver-dal";
|
||||||
import { TAccessApprovalPolicyDALFactory } from "../access-approval-policy/access-approval-policy-dal";
|
import { TAccessApprovalPolicyDALFactory } from "../access-approval-policy/access-approval-policy-dal";
|
||||||
import { isApproversValid } from "../access-approval-policy/access-approval-policy-fns";
|
|
||||||
import { TGroupDALFactory } from "../group/group-dal";
|
import { TGroupDALFactory } from "../group/group-dal";
|
||||||
import { TPermissionServiceFactory } from "../permission/permission-service";
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
import { TProjectUserAdditionalPrivilegeDALFactory } from "../project-user-additional-privilege/project-user-additional-privilege-dal";
|
import { TProjectUserAdditionalPrivilegeDALFactory } from "../project-user-additional-privilege/project-user-additional-privilege-dal";
|
||||||
@@ -78,7 +77,6 @@ export const accessApprovalRequestServiceFactory = ({
|
|||||||
permissionService,
|
permissionService,
|
||||||
accessApprovalRequestDAL,
|
accessApprovalRequestDAL,
|
||||||
accessApprovalRequestReviewerDAL,
|
accessApprovalRequestReviewerDAL,
|
||||||
projectMembershipDAL,
|
|
||||||
accessApprovalPolicyDAL,
|
accessApprovalPolicyDAL,
|
||||||
accessApprovalPolicyApproverDAL,
|
accessApprovalPolicyApproverDAL,
|
||||||
additionalPrivilegeDAL,
|
additionalPrivilegeDAL,
|
||||||
@@ -331,22 +329,6 @@ export const accessApprovalRequestServiceFactory = ({
|
|||||||
throw new ForbiddenRequestError({ message: "You are not authorized to approve this request" });
|
throw new ForbiddenRequestError({ message: "You are not authorized to approve this request" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const reviewerProjectMembership = await projectMembershipDAL.findById(membership.id);
|
|
||||||
|
|
||||||
const approversValid = await isApproversValid({
|
|
||||||
projectId: accessApprovalRequest.projectId,
|
|
||||||
orgId: actorOrgId,
|
|
||||||
envSlug: accessApprovalRequest.environment,
|
|
||||||
secretPath: accessApprovalRequest.policy.secretPath!,
|
|
||||||
actorAuthMethod,
|
|
||||||
permissionService,
|
|
||||||
userIds: [reviewerProjectMembership.userId]
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!approversValid) {
|
|
||||||
throw new ForbiddenRequestError({ message: "You don't have access to approve this request" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingReviews = await accessApprovalRequestReviewerDAL.find({ requestId: accessApprovalRequest.id });
|
const existingReviews = await accessApprovalRequestReviewerDAL.find({ requestId: accessApprovalRequest.id });
|
||||||
if (existingReviews.some((review) => review.status === ApprovalStatus.REJECTED)) {
|
if (existingReviews.some((review) => review.status === ApprovalStatus.REJECTED)) {
|
||||||
throw new BadRequestError({ message: "The request has already been rejected by another reviewer" });
|
throw new BadRequestError({ message: "The request has already been rejected by another reviewer" });
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ import ms from "ms";
|
|||||||
import { SecretKeyEncoding } from "@app/db/schemas";
|
import { SecretKeyEncoding } from "@app/db/schemas";
|
||||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import {
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
|
ProjectPermissionSub
|
||||||
|
} from "@app/ee/services/permission/project-permission";
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { infisicalSymmetricDecrypt } from "@app/lib/crypto/encryption";
|
import { infisicalSymmetricDecrypt } from "@app/lib/crypto/encryption";
|
||||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
@@ -72,8 +75,8 @@ export const dynamicSecretLeaseServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(actorOrgId);
|
const plan = await licenseService.getPlan(actorOrgId);
|
||||||
@@ -151,8 +154,8 @@ export const dynamicSecretLeaseServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(actorOrgId);
|
const plan = await licenseService.getPlan(actorOrgId);
|
||||||
@@ -230,8 +233,8 @@ export const dynamicSecretLeaseServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -299,8 +302,8 @@ export const dynamicSecretLeaseServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -341,8 +344,8 @@ export const dynamicSecretLeaseServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ import { ForbiddenError, subject } from "@casl/ability";
|
|||||||
import { SecretKeyEncoding } from "@app/db/schemas";
|
import { SecretKeyEncoding } from "@app/db/schemas";
|
||||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import {
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
|
ProjectPermissionSub
|
||||||
|
} from "@app/ee/services/permission/project-permission";
|
||||||
import { infisicalSymmetricDecrypt, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
import { infisicalSymmetricDecrypt, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
||||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
import { OrderByDirection } from "@app/lib/types";
|
import { OrderByDirection } from "@app/lib/types";
|
||||||
@@ -77,8 +80,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionDynamicSecretActions.CreateRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(actorOrgId);
|
const plan = await licenseService.getPlan(actorOrgId);
|
||||||
@@ -148,8 +151,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionDynamicSecretActions.EditRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(actorOrgId);
|
const plan = await licenseService.getPlan(actorOrgId);
|
||||||
@@ -231,8 +234,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionDynamicSecretActions.DeleteRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -291,8 +294,12 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
|
ProjectPermissionDynamicSecretActions.EditRootCredential,
|
||||||
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -340,8 +347,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
// verify user has access to each env in request
|
// verify user has access to each env in request
|
||||||
environmentSlugs.forEach((environmentSlug) =>
|
environmentSlugs.forEach((environmentSlug) =>
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -380,8 +387,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -428,8 +435,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
const folder = await folderDAL.findBySecretPath(projectId, environmentSlug, path);
|
||||||
@@ -471,8 +478,8 @@ export const dynamicSecretServiceFactory = ({
|
|||||||
// verify user has access to each env in request
|
// verify user has access to each env in request
|
||||||
environmentSlugs.forEach((environmentSlug) =>
|
environmentSlugs.forEach((environmentSlug) =>
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: environmentSlug, secretPath: path })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment: environmentSlug, secretPath: path })
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
import { TDbClient } from "@app/db";
|
||||||
|
import { TableName } from "@app/db/schemas";
|
||||||
|
import { ormify } from "@app/lib/knex";
|
||||||
|
|
||||||
|
export type TIdentityProjectAdditionalPrivilegeV2DALFactory = ReturnType<
|
||||||
|
typeof identityProjectAdditionalPrivilegeV2DALFactory
|
||||||
|
>;
|
||||||
|
|
||||||
|
export const identityProjectAdditionalPrivilegeV2DALFactory = (db: TDbClient) => {
|
||||||
|
const orm = ormify(db, TableName.IdentityProjectAdditionalPrivilege);
|
||||||
|
return orm;
|
||||||
|
};
|
||||||
+343
@@ -0,0 +1,343 @@
|
|||||||
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
import { packRules } from "@casl/ability/extra";
|
||||||
|
import ms from "ms";
|
||||||
|
|
||||||
|
import { TableName } from "@app/db/schemas";
|
||||||
|
import { isAtLeastAsPrivileged } from "@app/lib/casl";
|
||||||
|
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
|
import { unpackPermissions } from "@app/server/routes/santizedSchemas/permission";
|
||||||
|
import { ActorType } from "@app/services/auth/auth-type";
|
||||||
|
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
|
||||||
|
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||||
|
|
||||||
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
|
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
|
||||||
|
import { TIdentityProjectAdditionalPrivilegeV2DALFactory } from "./identity-project-additional-privilege-v2-dal";
|
||||||
|
import {
|
||||||
|
IdentityProjectAdditionalPrivilegeTemporaryMode,
|
||||||
|
TCreateIdentityPrivilegeDTO,
|
||||||
|
TDeleteIdentityPrivilegeByIdDTO,
|
||||||
|
TGetIdentityPrivilegeDetailsByIdDTO,
|
||||||
|
TGetIdentityPrivilegeDetailsBySlugDTO,
|
||||||
|
TListIdentityPrivilegesDTO,
|
||||||
|
TUpdateIdentityPrivilegeByIdDTO
|
||||||
|
} from "./identity-project-additional-privilege-v2-types";
|
||||||
|
|
||||||
|
type TIdentityProjectAdditionalPrivilegeV2ServiceFactoryDep = {
|
||||||
|
identityProjectAdditionalPrivilegeDAL: TIdentityProjectAdditionalPrivilegeV2DALFactory;
|
||||||
|
identityProjectDAL: Pick<TIdentityProjectDALFactory, "findOne" | "findById">;
|
||||||
|
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug">;
|
||||||
|
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TIdentityProjectAdditionalPrivilegeV2ServiceFactory = ReturnType<
|
||||||
|
typeof identityProjectAdditionalPrivilegeV2ServiceFactory
|
||||||
|
>;
|
||||||
|
|
||||||
|
export const identityProjectAdditionalPrivilegeV2ServiceFactory = ({
|
||||||
|
identityProjectAdditionalPrivilegeDAL,
|
||||||
|
identityProjectDAL,
|
||||||
|
projectDAL,
|
||||||
|
permissionService
|
||||||
|
}: TIdentityProjectAdditionalPrivilegeV2ServiceFactoryDep) => {
|
||||||
|
const create = async ({
|
||||||
|
slug,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
projectId,
|
||||||
|
actorOrgId,
|
||||||
|
identityId,
|
||||||
|
permissions: customPermission,
|
||||||
|
actorAuthMethod,
|
||||||
|
...dto
|
||||||
|
}: TCreateIdentityPrivilegeDTO) => {
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({ message: `Failed to find identity with id ${identityId}` });
|
||||||
|
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||||
|
const { permission: targetIdentityPermission } = await permissionService.getProjectPermission(
|
||||||
|
ActorType.IDENTITY,
|
||||||
|
identityId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetIdentityPermission.update(targetIdentityPermission.rules.concat(customPermission));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetIdentityPermission);
|
||||||
|
if (!hasRequiredPriviledges)
|
||||||
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
|
const existingSlug = await identityProjectAdditionalPrivilegeDAL.findOne({
|
||||||
|
slug,
|
||||||
|
projectMembershipId: identityProjectMembership.id
|
||||||
|
});
|
||||||
|
if (existingSlug) throw new BadRequestError({ message: "Additional privilege with provided slug already exists" });
|
||||||
|
|
||||||
|
const packedPermission = JSON.stringify(packRules(customPermission));
|
||||||
|
if (!dto.isTemporary) {
|
||||||
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
||||||
|
projectMembershipId: identityProjectMembership.id,
|
||||||
|
slug,
|
||||||
|
permissions: packedPermission
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const relativeTempAllocatedTimeInMs = ms(dto.temporaryRange);
|
||||||
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
||||||
|
projectMembershipId: identityProjectMembership.id,
|
||||||
|
slug,
|
||||||
|
permissions: packedPermission,
|
||||||
|
isTemporary: true,
|
||||||
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative,
|
||||||
|
temporaryRange: dto.temporaryRange,
|
||||||
|
temporaryAccessStartTime: new Date(dto.temporaryAccessStartTime),
|
||||||
|
temporaryAccessEndTime: new Date(new Date(dto.temporaryAccessStartTime).getTime() + relativeTempAllocatedTimeInMs)
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateById = async ({
|
||||||
|
id,
|
||||||
|
data,
|
||||||
|
actorOrgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod
|
||||||
|
}: TUpdateIdentityPrivilegeByIdDTO) => {
|
||||||
|
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findById(id);
|
||||||
|
if (!identityPrivilege) throw new NotFoundError({ message: `Identity privilege with ${id} not found` });
|
||||||
|
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ id: identityPrivilege.projectMembershipId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({
|
||||||
|
message: `Failed to find identity with membership ${identityPrivilege.projectMembershipId}`
|
||||||
|
});
|
||||||
|
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||||
|
const { permission: targetIdentityPermission } = await permissionService.getProjectPermission(
|
||||||
|
ActorType.IDENTITY,
|
||||||
|
identityProjectMembership.identityId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetIdentityPermission.update(targetIdentityPermission.rules.concat(data.permissions || []));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetIdentityPermission);
|
||||||
|
if (!hasRequiredPriviledges)
|
||||||
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
|
if (data?.slug) {
|
||||||
|
const existingSlug = await identityProjectAdditionalPrivilegeDAL.findOne({
|
||||||
|
slug: data.slug,
|
||||||
|
projectMembershipId: identityProjectMembership.id
|
||||||
|
});
|
||||||
|
if (existingSlug && existingSlug.id !== identityPrivilege.id)
|
||||||
|
throw new BadRequestError({ message: "Additional privilege with provided slug already exists" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isTemporary = typeof data?.isTemporary !== "undefined" ? data.isTemporary : identityPrivilege.isTemporary;
|
||||||
|
const packedPermission = data.permissions ? JSON.stringify(packRules(data.permissions)) : undefined;
|
||||||
|
if (isTemporary) {
|
||||||
|
const temporaryAccessStartTime = data?.temporaryAccessStartTime || identityPrivilege?.temporaryAccessStartTime;
|
||||||
|
const temporaryRange = data?.temporaryRange || identityPrivilege?.temporaryRange;
|
||||||
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
||||||
|
slug: data.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
|
isTemporary: data.isTemporary,
|
||||||
|
temporaryRange: data.temporaryRange,
|
||||||
|
temporaryMode: data.temporaryMode,
|
||||||
|
temporaryAccessStartTime: new Date(temporaryAccessStartTime || ""),
|
||||||
|
temporaryAccessEndTime: new Date(new Date(temporaryAccessStartTime || "").getTime() + ms(temporaryRange || ""))
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
||||||
|
slug: data.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
|
isTemporary: false,
|
||||||
|
temporaryAccessStartTime: null,
|
||||||
|
temporaryAccessEndTime: null,
|
||||||
|
temporaryRange: null,
|
||||||
|
temporaryMode: null
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteById = async ({ actorId, id, actor, actorOrgId, actorAuthMethod }: TDeleteIdentityPrivilegeByIdDTO) => {
|
||||||
|
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findById(id);
|
||||||
|
if (!identityPrivilege) throw new NotFoundError({ message: `Identity privilege with ${id} not found` });
|
||||||
|
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ id: identityPrivilege.projectMembershipId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({
|
||||||
|
message: `Failed to find identity with membership ${identityPrivilege.projectMembershipId}`
|
||||||
|
});
|
||||||
|
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.Identity);
|
||||||
|
const { permission: identityRolePermission } = await permissionService.getProjectPermission(
|
||||||
|
ActorType.IDENTITY,
|
||||||
|
identityProjectMembership.identityId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, identityRolePermission);
|
||||||
|
if (!hasRequiredPriviledges)
|
||||||
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
|
const deletedPrivilege = await identityProjectAdditionalPrivilegeDAL.deleteById(identityPrivilege.id);
|
||||||
|
return {
|
||||||
|
...deletedPrivilege,
|
||||||
|
permissions: unpackPermissions(deletedPrivilege.permissions)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getPrivilegeDetailsById = async ({
|
||||||
|
id,
|
||||||
|
actorOrgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod
|
||||||
|
}: TGetIdentityPrivilegeDetailsByIdDTO) => {
|
||||||
|
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findById(id);
|
||||||
|
if (!identityPrivilege) throw new NotFoundError({ message: `Identity privilege with ${id} not found` });
|
||||||
|
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ id: identityPrivilege.projectMembershipId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({
|
||||||
|
message: `Failed to find identity with membership ${identityPrivilege.projectMembershipId}`
|
||||||
|
});
|
||||||
|
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...identityPrivilege,
|
||||||
|
permissions: unpackPermissions(identityPrivilege.permissions)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getPrivilegeDetailsBySlug = async ({
|
||||||
|
identityId,
|
||||||
|
slug,
|
||||||
|
projectSlug,
|
||||||
|
actorOrgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod
|
||||||
|
}: TGetIdentityPrivilegeDetailsBySlugDTO) => {
|
||||||
|
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
||||||
|
if (!project) throw new NotFoundError({ message: `Project with slug ${slug} not found` });
|
||||||
|
const projectId = project.id;
|
||||||
|
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({ message: `Failed to find identity with id ${identityId}` });
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||||
|
|
||||||
|
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findOne({
|
||||||
|
slug,
|
||||||
|
projectMembershipId: identityProjectMembership.id
|
||||||
|
});
|
||||||
|
if (!identityPrivilege) throw new NotFoundError({ message: "Identity additional privilege not found" });
|
||||||
|
|
||||||
|
return {
|
||||||
|
...identityPrivilege,
|
||||||
|
permissions: unpackPermissions(identityPrivilege.permissions)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const listIdentityProjectPrivileges = async ({
|
||||||
|
identityId,
|
||||||
|
actorOrgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod,
|
||||||
|
projectId
|
||||||
|
}: TListIdentityPrivilegesDTO) => {
|
||||||
|
const identityProjectMembership = await identityProjectDAL.findOne({ identityId, projectId });
|
||||||
|
if (!identityProjectMembership)
|
||||||
|
throw new NotFoundError({ message: `Failed to find identity with id ${identityId}` });
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
identityProjectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||||
|
|
||||||
|
const identityPrivileges = await identityProjectAdditionalPrivilegeDAL.find(
|
||||||
|
{
|
||||||
|
projectMembershipId: identityProjectMembership.id
|
||||||
|
},
|
||||||
|
{ sort: [[`${TableName.IdentityProjectAdditionalPrivilege}.slug` as "slug", "asc"]] }
|
||||||
|
);
|
||||||
|
return identityPrivileges;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
getPrivilegeDetailsById,
|
||||||
|
getPrivilegeDetailsBySlug,
|
||||||
|
listIdentityProjectPrivileges,
|
||||||
|
create,
|
||||||
|
updateById,
|
||||||
|
deleteById
|
||||||
|
};
|
||||||
|
};
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
import { TProjectPermission } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TProjectPermissionV2Schema } from "../permission/project-permission";
|
||||||
|
|
||||||
|
export enum IdentityProjectAdditionalPrivilegeTemporaryMode {
|
||||||
|
Relative = "relative"
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TCreateIdentityPrivilegeDTO = {
|
||||||
|
permissions: TProjectPermissionV2Schema[];
|
||||||
|
identityId: string;
|
||||||
|
projectId: string;
|
||||||
|
slug: string;
|
||||||
|
} & (
|
||||||
|
| {
|
||||||
|
isTemporary: false;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
isTemporary: true;
|
||||||
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative;
|
||||||
|
temporaryRange: string;
|
||||||
|
temporaryAccessStartTime: string;
|
||||||
|
}
|
||||||
|
) &
|
||||||
|
Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
|
export type TUpdateIdentityPrivilegeByIdDTO = { id: string } & Omit<TProjectPermission, "projectId"> & {
|
||||||
|
data: Partial<{
|
||||||
|
permissions: TProjectPermissionV2Schema[];
|
||||||
|
slug: string;
|
||||||
|
isTemporary: boolean;
|
||||||
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative;
|
||||||
|
temporaryRange: string;
|
||||||
|
temporaryAccessStartTime: string;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TDeleteIdentityPrivilegeByIdDTO = Omit<TProjectPermission, "projectId"> & {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TGetIdentityPrivilegeDetailsByIdDTO = Omit<TProjectPermission, "projectId"> & {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TListIdentityPrivilegesDTO = Omit<TProjectPermission, "projectId"> & {
|
||||||
|
identityId: string;
|
||||||
|
projectId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TGetIdentityPrivilegeDetailsBySlugDTO = Omit<TProjectPermission, "projectId"> & {
|
||||||
|
slug: string;
|
||||||
|
identityId: string;
|
||||||
|
projectSlug: string;
|
||||||
|
};
|
||||||
+28
-24
@@ -1,10 +1,10 @@
|
|||||||
import { ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
|
import { ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
|
||||||
import { PackRule, unpackRules } from "@casl/ability/extra";
|
import { PackRule, packRules, unpackRules } from "@casl/ability/extra";
|
||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
import { isAtLeastAsPrivileged } from "@app/lib/casl";
|
import { isAtLeastAsPrivileged } from "@app/lib/casl";
|
||||||
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
|
import { UnpackedPermissionSchema } from "@app/server/routes/santizedSchemas/permission";
|
||||||
import { ActorType } from "@app/services/auth/auth-type";
|
import { ActorType } from "@app/services/auth/auth-type";
|
||||||
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
|
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
|
||||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||||
@@ -32,16 +32,6 @@ export type TIdentityProjectAdditionalPrivilegeServiceFactory = ReturnType<
|
|||||||
typeof identityProjectAdditionalPrivilegeServiceFactory
|
typeof identityProjectAdditionalPrivilegeServiceFactory
|
||||||
>;
|
>;
|
||||||
|
|
||||||
// TODO(akhilmhdh): move this to more centralized
|
|
||||||
export const UnpackedPermissionSchema = z.object({
|
|
||||||
subject: z
|
|
||||||
.union([z.string().min(1), z.string().array()])
|
|
||||||
.transform((el) => (typeof el !== "string" ? el[0] : el))
|
|
||||||
.optional(),
|
|
||||||
action: z.union([z.string().min(1), z.string().array()]).transform((el) => (typeof el === "string" ? [el] : el)),
|
|
||||||
conditions: z.unknown().optional()
|
|
||||||
});
|
|
||||||
|
|
||||||
const unpackPermissions = (permissions: unknown) =>
|
const unpackPermissions = (permissions: unknown) =>
|
||||||
UnpackedPermissionSchema.array().parse(
|
UnpackedPermissionSchema.array().parse(
|
||||||
unpackRules((permissions || []) as PackRule<RawRuleOf<MongoAbility<ProjectPermissionSet>>>[])
|
unpackRules((permissions || []) as PackRule<RawRuleOf<MongoAbility<ProjectPermissionSet>>>[])
|
||||||
@@ -80,14 +70,18 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||||
const { permission: identityRolePermission } = await permissionService.getProjectPermission(
|
const { permission: targetIdentityPermission } = await permissionService.getProjectPermission(
|
||||||
ActorType.IDENTITY,
|
ActorType.IDENTITY,
|
||||||
identityId,
|
identityId,
|
||||||
identityProjectMembership.projectId,
|
identityProjectMembership.projectId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, identityRolePermission);
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetIdentityPermission.update(targetIdentityPermission.rules.concat(customPermission));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetIdentityPermission);
|
||||||
if (!hasRequiredPriviledges)
|
if (!hasRequiredPriviledges)
|
||||||
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
@@ -97,11 +91,12 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
});
|
});
|
||||||
if (existingSlug) throw new BadRequestError({ message: "Additional privilege of provided slug exist" });
|
if (existingSlug) throw new BadRequestError({ message: "Additional privilege of provided slug exist" });
|
||||||
|
|
||||||
|
const packedPermission = JSON.stringify(packRules(customPermission));
|
||||||
if (!dto.isTemporary) {
|
if (!dto.isTemporary) {
|
||||||
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
||||||
projectMembershipId: identityProjectMembership.id,
|
projectMembershipId: identityProjectMembership.id,
|
||||||
slug,
|
slug,
|
||||||
permissions: customPermission
|
permissions: packedPermission
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
...additionalPrivilege,
|
...additionalPrivilege,
|
||||||
@@ -113,7 +108,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.create({
|
||||||
projectMembershipId: identityProjectMembership.id,
|
projectMembershipId: identityProjectMembership.id,
|
||||||
slug,
|
slug,
|
||||||
permissions: customPermission,
|
permissions: packedPermission,
|
||||||
isTemporary: true,
|
isTemporary: true,
|
||||||
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative,
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative,
|
||||||
temporaryRange: dto.temporaryRange,
|
temporaryRange: dto.temporaryRange,
|
||||||
@@ -152,14 +147,19 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||||
const { permission: identityRolePermission } = await permissionService.getProjectPermission(
|
|
||||||
|
const { permission: targetIdentityPermission } = await permissionService.getProjectPermission(
|
||||||
ActorType.IDENTITY,
|
ActorType.IDENTITY,
|
||||||
identityProjectMembership.identityId,
|
identityProjectMembership.identityId,
|
||||||
identityProjectMembership.projectId,
|
identityProjectMembership.projectId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, identityRolePermission);
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetIdentityPermission.update(targetIdentityPermission.rules.concat(data.permissions || []));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetIdentityPermission);
|
||||||
if (!hasRequiredPriviledges)
|
if (!hasRequiredPriviledges)
|
||||||
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
@@ -182,23 +182,29 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isTemporary = typeof data?.isTemporary !== "undefined" ? data.isTemporary : identityPrivilege.isTemporary;
|
const isTemporary = typeof data?.isTemporary !== "undefined" ? data.isTemporary : identityPrivilege.isTemporary;
|
||||||
|
|
||||||
|
const packedPermission = data.permissions ? JSON.stringify(packRules(data.permissions)) : undefined;
|
||||||
if (isTemporary) {
|
if (isTemporary) {
|
||||||
const temporaryAccessStartTime = data?.temporaryAccessStartTime || identityPrivilege?.temporaryAccessStartTime;
|
const temporaryAccessStartTime = data?.temporaryAccessStartTime || identityPrivilege?.temporaryAccessStartTime;
|
||||||
const temporaryRange = data?.temporaryRange || identityPrivilege?.temporaryRange;
|
const temporaryRange = data?.temporaryRange || identityPrivilege?.temporaryRange;
|
||||||
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
||||||
...data,
|
slug: data.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
|
isTemporary: data.isTemporary,
|
||||||
|
temporaryRange: data.temporaryRange,
|
||||||
|
temporaryMode: data.temporaryMode,
|
||||||
temporaryAccessStartTime: new Date(temporaryAccessStartTime || ""),
|
temporaryAccessStartTime: new Date(temporaryAccessStartTime || ""),
|
||||||
temporaryAccessEndTime: new Date(new Date(temporaryAccessStartTime || "").getTime() + ms(temporaryRange || ""))
|
temporaryAccessEndTime: new Date(new Date(temporaryAccessStartTime || "").getTime() + ms(temporaryRange || ""))
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
...additionalPrivilege,
|
...additionalPrivilege,
|
||||||
|
|
||||||
permissions: unpackPermissions(additionalPrivilege.permissions)
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
const additionalPrivilege = await identityProjectAdditionalPrivilegeDAL.updateById(identityPrivilege.id, {
|
||||||
...data,
|
slug: data.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
isTemporary: false,
|
isTemporary: false,
|
||||||
temporaryAccessStartTime: null,
|
temporaryAccessStartTime: null,
|
||||||
temporaryAccessEndTime: null,
|
temporaryAccessEndTime: null,
|
||||||
@@ -207,7 +213,6 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
...additionalPrivilege,
|
...additionalPrivilege,
|
||||||
|
|
||||||
permissions: unpackPermissions(additionalPrivilege.permissions)
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -289,7 +294,7 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||||
|
|
||||||
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findOne({
|
const identityPrivilege = await identityProjectAdditionalPrivilegeDAL.findOne({
|
||||||
slug,
|
slug,
|
||||||
@@ -335,7 +340,6 @@ export const identityProjectAdditionalPrivilegeServiceFactory = ({
|
|||||||
});
|
});
|
||||||
return identityPrivileges.map((el) => ({
|
return identityPrivileges.map((el) => ({
|
||||||
...el,
|
...el,
|
||||||
|
|
||||||
permissions: unpackPermissions(el.permissions)
|
permissions: unpackPermissions(el.permissions)
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-2
@@ -1,11 +1,13 @@
|
|||||||
import { TProjectPermission } from "@app/lib/types";
|
import { TProjectPermission } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TProjectPermissionV2Schema } from "../permission/project-permission";
|
||||||
|
|
||||||
export enum IdentityProjectAdditionalPrivilegeTemporaryMode {
|
export enum IdentityProjectAdditionalPrivilegeTemporaryMode {
|
||||||
Relative = "relative"
|
Relative = "relative"
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TCreateIdentityPrivilegeDTO = {
|
export type TCreateIdentityPrivilegeDTO = {
|
||||||
permissions: unknown;
|
permissions: TProjectPermissionV2Schema[];
|
||||||
identityId: string;
|
identityId: string;
|
||||||
projectSlug: string;
|
projectSlug: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -27,7 +29,7 @@ export type TUpdateIdentityPrivilegeDTO = { slug: string; identityId: string; pr
|
|||||||
"projectId"
|
"projectId"
|
||||||
> & {
|
> & {
|
||||||
data: Partial<{
|
data: Partial<{
|
||||||
permissions: unknown;
|
permissions: TProjectPermissionV2Schema[];
|
||||||
slug: string;
|
slug: string;
|
||||||
isTemporary: boolean;
|
isTemporary: boolean;
|
||||||
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative;
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative;
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ export const permissionServiceFactory = ({
|
|||||||
throw new NotFoundError({ name: "OrgRoleInvalid", message: `Organization role '${role}' not found` });
|
throw new NotFoundError({ name: "OrgRoleInvalid", message: `Organization role '${role}' not found` });
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.reduce((curr, prev) => prev.concat(curr), []);
|
.reduce((prev, curr) => prev.concat(curr), []);
|
||||||
|
|
||||||
return createMongoAbility<OrgPermissionSet>(rules, {
|
return createMongoAbility<OrgPermissionSet>(rules, {
|
||||||
conditionsMatcher
|
conditionsMatcher
|
||||||
@@ -98,7 +98,7 @@ export const permissionServiceFactory = ({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.reduce((curr, prev) => prev.concat(curr), []);
|
.reduce((prev, curr) => prev.concat(curr), []);
|
||||||
|
|
||||||
return rules;
|
return rules;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ export enum PermissionConditionOperators {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const PermissionConditionSchema = {
|
export const PermissionConditionSchema = {
|
||||||
[PermissionConditionOperators.$IN]: z.string().min(1).array(),
|
[PermissionConditionOperators.$IN]: z.string().trim().min(1).array(),
|
||||||
[PermissionConditionOperators.$ALL]: z.string().min(1).array(),
|
[PermissionConditionOperators.$ALL]: z.string().trim().min(1).array(),
|
||||||
[PermissionConditionOperators.$REGEX]: z
|
[PermissionConditionOperators.$REGEX]: z
|
||||||
.string()
|
.string()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { AbilityBuilder, createMongoAbility, ForcedSubject, MongoAbility } from "@casl/ability";
|
import { AbilityBuilder, createMongoAbility, ForcedSubject, MongoAbility } from "@casl/ability";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { TableName } from "@app/db/schemas";
|
|
||||||
import { conditionsMatcher } from "@app/lib/casl";
|
import { conditionsMatcher } from "@app/lib/casl";
|
||||||
import { BadRequestError } from "@app/lib/errors";
|
import { UnpackedPermissionSchema } from "@app/server/routes/santizedSchemas/permission";
|
||||||
|
|
||||||
import { PermissionConditionOperators, PermissionConditionSchema } from "./permission-types";
|
import { PermissionConditionOperators, PermissionConditionSchema } from "./permission-types";
|
||||||
|
|
||||||
@@ -23,6 +22,14 @@ export enum ProjectPermissionCmekActions {
|
|||||||
Decrypt = "decrypt"
|
Decrypt = "decrypt"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum ProjectPermissionDynamicSecretActions {
|
||||||
|
ReadRootCredential = "read-root-credential",
|
||||||
|
CreateRootCredential = "create-root-credential",
|
||||||
|
EditRootCredential = "edit-root-credential",
|
||||||
|
DeleteRootCredential = "delete-root-credential",
|
||||||
|
Lease = "lease"
|
||||||
|
}
|
||||||
|
|
||||||
export enum ProjectPermissionSub {
|
export enum ProjectPermissionSub {
|
||||||
Role = "role",
|
Role = "role",
|
||||||
Member = "member",
|
Member = "member",
|
||||||
@@ -38,6 +45,8 @@ export enum ProjectPermissionSub {
|
|||||||
Project = "workspace",
|
Project = "workspace",
|
||||||
Secrets = "secrets",
|
Secrets = "secrets",
|
||||||
SecretFolders = "secret-folders",
|
SecretFolders = "secret-folders",
|
||||||
|
SecretImports = "secret-imports",
|
||||||
|
DynamicSecrets = "dynamic-secrets",
|
||||||
SecretRollback = "secret-rollback",
|
SecretRollback = "secret-rollback",
|
||||||
SecretApproval = "secret-approval",
|
SecretApproval = "secret-approval",
|
||||||
SecretRotation = "secret-rotation",
|
SecretRotation = "secret-rotation",
|
||||||
@@ -54,19 +63,8 @@ export enum ProjectPermissionSub {
|
|||||||
export type SecretSubjectFields = {
|
export type SecretSubjectFields = {
|
||||||
environment: string;
|
environment: string;
|
||||||
secretPath: string;
|
secretPath: string;
|
||||||
// secretName: string;
|
secretName?: string;
|
||||||
// secretTags: string[];
|
secretTags?: string[];
|
||||||
};
|
|
||||||
|
|
||||||
export const CaslSecretsV2SubjectKnexMapper = (field: string) => {
|
|
||||||
switch (field) {
|
|
||||||
case "secretName":
|
|
||||||
return `${TableName.SecretV2}.key`;
|
|
||||||
case "secretTags":
|
|
||||||
return `${TableName.SecretTag}.slug`;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SecretFolderSubjectFields = {
|
export type SecretFolderSubjectFields = {
|
||||||
@@ -74,6 +72,16 @@ export type SecretFolderSubjectFields = {
|
|||||||
secretPath: string;
|
secretPath: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type DynamicSecretSubjectFields = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SecretImportSubjectFields = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type ProjectPermissionSet =
|
export type ProjectPermissionSet =
|
||||||
| [
|
| [
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
@@ -86,6 +94,20 @@ export type ProjectPermissionSet =
|
|||||||
| (ForcedSubject<ProjectPermissionSub.SecretFolders> & SecretFolderSubjectFields)
|
| (ForcedSubject<ProjectPermissionSub.SecretFolders> & SecretFolderSubjectFields)
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
| [
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
|
(
|
||||||
|
| ProjectPermissionSub.DynamicSecrets
|
||||||
|
| (ForcedSubject<ProjectPermissionSub.DynamicSecrets> & DynamicSecretSubjectFields)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
| [
|
||||||
|
ProjectPermissionActions,
|
||||||
|
(
|
||||||
|
| ProjectPermissionSub.SecretImports
|
||||||
|
| (ForcedSubject<ProjectPermissionSub.SecretImports> & SecretImportSubjectFields)
|
||||||
|
)
|
||||||
|
]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Role]
|
| [ProjectPermissionActions, ProjectPermissionSub.Role]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Tags]
|
| [ProjectPermissionActions, ProjectPermissionSub.Tags]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Member]
|
| [ProjectPermissionActions, ProjectPermissionSub.Member]
|
||||||
@@ -120,7 +142,9 @@ const CASL_ACTION_SCHEMA_NATIVE_ENUM = <ACTION extends z.EnumLike>(actions: ACTI
|
|||||||
const CASL_ACTION_SCHEMA_ENUM = <ACTION extends z.EnumValues>(actions: ACTION) =>
|
const CASL_ACTION_SCHEMA_ENUM = <ACTION extends z.EnumValues>(actions: ACTION) =>
|
||||||
z.union([z.enum(actions), z.enum(actions).array().min(1)]).transform((el) => (typeof el === "string" ? [el] : el));
|
z.union([z.enum(actions), z.enum(actions).array().min(1)]).transform((el) => (typeof el === "string" ? [el] : el));
|
||||||
|
|
||||||
const SecretConditionSchema = z
|
// akhilmhdh: don't modify this for v2
|
||||||
|
// if you want to update create a new schema
|
||||||
|
const SecretConditionV1Schema = z
|
||||||
.object({
|
.object({
|
||||||
environment: z.union([
|
environment: z.union([
|
||||||
z.string(),
|
z.string(),
|
||||||
@@ -146,16 +170,50 @@ const SecretConditionSchema = z
|
|||||||
})
|
})
|
||||||
.partial();
|
.partial();
|
||||||
|
|
||||||
export const ProjectPermissionSchema = z.discriminatedUnion("subject", [
|
const SecretConditionV2Schema = z
|
||||||
z.object({
|
.object({
|
||||||
subject: z.literal(ProjectPermissionSub.Secrets).describe("The entity this permission pertains to."),
|
environment: z.union([
|
||||||
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
z.string(),
|
||||||
"Describe what action an entity can take."
|
z
|
||||||
),
|
.object({
|
||||||
conditions: SecretConditionSchema.describe(
|
[PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],
|
||||||
"When specified, only matching conditions will be allowed to access given resource."
|
[PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],
|
||||||
).optional()
|
[PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],
|
||||||
}),
|
[PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]
|
||||||
|
})
|
||||||
|
.partial()
|
||||||
|
]),
|
||||||
|
secretPath: z.union([
|
||||||
|
z.string(),
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
[PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],
|
||||||
|
[PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],
|
||||||
|
[PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],
|
||||||
|
[PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]
|
||||||
|
})
|
||||||
|
.partial()
|
||||||
|
]),
|
||||||
|
secretName: z.union([
|
||||||
|
z.string(),
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
[PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],
|
||||||
|
[PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],
|
||||||
|
[PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN],
|
||||||
|
[PermissionConditionOperators.$GLOB]: PermissionConditionSchema[PermissionConditionOperators.$GLOB]
|
||||||
|
})
|
||||||
|
.partial()
|
||||||
|
]),
|
||||||
|
secretTags: z
|
||||||
|
.object({
|
||||||
|
[PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]
|
||||||
|
})
|
||||||
|
.partial()
|
||||||
|
})
|
||||||
|
.partial();
|
||||||
|
|
||||||
|
const GeneralPermissionSchema = [
|
||||||
z.object({
|
z.object({
|
||||||
subject: z.literal(ProjectPermissionSub.SecretApproval).describe("The entity this permission pertains to."),
|
subject: z.literal(ProjectPermissionSub.SecretApproval).describe("The entity this permission pertains to."),
|
||||||
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
@@ -259,7 +317,7 @@ export const ProjectPermissionSchema = z.discriminatedUnion("subject", [
|
|||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
z.object({
|
z.object({
|
||||||
subject: z.literal(ProjectPermissionSub.CertificateTemplates).describe("The entity this permission pertains to. "),
|
subject: z.literal(ProjectPermissionSub.CertificateTemplates).describe("The entity this permission pertains to."),
|
||||||
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
"Describe what action an entity can take."
|
"Describe what action an entity can take."
|
||||||
)
|
)
|
||||||
@@ -288,26 +346,90 @@ export const ProjectPermissionSchema = z.discriminatedUnion("subject", [
|
|||||||
"Describe what action an entity can take."
|
"Describe what action an entity can take."
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
z.object({
|
|
||||||
subject: z.literal(ProjectPermissionSub.SecretFolders).describe("The entity this permission pertains to."),
|
|
||||||
action: CASL_ACTION_SCHEMA_ENUM([ProjectPermissionActions.Read]).describe(
|
|
||||||
"Describe what action an entity can take."
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
z.object({
|
z.object({
|
||||||
subject: z.literal(ProjectPermissionSub.Cmek).describe("The entity this permission pertains to."),
|
subject: z.literal(ProjectPermissionSub.Cmek).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionCmekActions).describe(
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionCmekActions).describe(
|
||||||
"Describe what action an entity can take."
|
"Describe what action an entity can take."
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ProjectPermissionV1Schema = z.discriminatedUnion("subject", [
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.Secrets).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
),
|
||||||
|
conditions: SecretConditionV1Schema.describe(
|
||||||
|
"When specified, only matching conditions will be allowed to access given resource."
|
||||||
|
).optional()
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.SecretFolders).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_ENUM([ProjectPermissionActions.Read]).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
...GeneralPermissionSchema
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
export const ProjectPermissionV2Schema = z.discriminatedUnion("subject", [
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.Secrets).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
),
|
||||||
|
conditions: SecretConditionV2Schema.describe(
|
||||||
|
"When specified, only matching conditions will be allowed to access given resource."
|
||||||
|
).optional()
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.SecretFolders).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
),
|
||||||
|
conditions: SecretConditionV1Schema.describe(
|
||||||
|
"When specified, only matching conditions will be allowed to access given resource."
|
||||||
|
).optional()
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.SecretImports).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionActions).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
),
|
||||||
|
conditions: SecretConditionV1Schema.describe(
|
||||||
|
"When specified, only matching conditions will be allowed to access given resource."
|
||||||
|
).optional()
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
subject: z.literal(ProjectPermissionSub.DynamicSecrets).describe("The entity this permission pertains to."),
|
||||||
|
inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
|
||||||
|
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionDynamicSecretActions).describe(
|
||||||
|
"Describe what action an entity can take."
|
||||||
|
),
|
||||||
|
conditions: SecretConditionV1Schema.describe(
|
||||||
|
"When specified, only matching conditions will be allowed to access given resource."
|
||||||
|
).optional()
|
||||||
|
}),
|
||||||
|
...GeneralPermissionSchema
|
||||||
|
]);
|
||||||
|
|
||||||
|
export type TProjectPermissionV2Schema = z.infer<typeof ProjectPermissionV2Schema>;
|
||||||
|
|
||||||
const buildAdminPermissionRules = () => {
|
const buildAdminPermissionRules = () => {
|
||||||
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
|
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
|
||||||
|
|
||||||
// Admins get full access to everything
|
// Admins get full access to everything
|
||||||
[
|
[
|
||||||
ProjectPermissionSub.Secrets,
|
ProjectPermissionSub.Secrets,
|
||||||
|
ProjectPermissionSub.SecretFolders,
|
||||||
|
ProjectPermissionSub.SecretImports,
|
||||||
ProjectPermissionSub.SecretApproval,
|
ProjectPermissionSub.SecretApproval,
|
||||||
ProjectPermissionSub.SecretRotation,
|
ProjectPermissionSub.SecretRotation,
|
||||||
ProjectPermissionSub.Member,
|
ProjectPermissionSub.Member,
|
||||||
@@ -339,6 +461,17 @@ const buildAdminPermissionRules = () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
can(
|
||||||
|
[
|
||||||
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.EditRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.CreateRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.DeleteRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.Lease
|
||||||
|
],
|
||||||
|
ProjectPermissionSub.DynamicSecrets
|
||||||
|
);
|
||||||
|
|
||||||
can([ProjectPermissionActions.Edit, ProjectPermissionActions.Delete], ProjectPermissionSub.Project);
|
can([ProjectPermissionActions.Edit, ProjectPermissionActions.Delete], ProjectPermissionSub.Project);
|
||||||
can([ProjectPermissionActions.Read, ProjectPermissionActions.Create], ProjectPermissionSub.SecretRollback);
|
can([ProjectPermissionActions.Read, ProjectPermissionActions.Create], ProjectPermissionSub.SecretRollback);
|
||||||
can([ProjectPermissionActions.Edit], ProjectPermissionSub.Kms);
|
can([ProjectPermissionActions.Edit], ProjectPermissionSub.Kms);
|
||||||
@@ -370,6 +503,34 @@ const buildMemberPermissionRules = () => {
|
|||||||
],
|
],
|
||||||
ProjectPermissionSub.Secrets
|
ProjectPermissionSub.Secrets
|
||||||
);
|
);
|
||||||
|
can(
|
||||||
|
[
|
||||||
|
ProjectPermissionActions.Read,
|
||||||
|
ProjectPermissionActions.Edit,
|
||||||
|
ProjectPermissionActions.Create,
|
||||||
|
ProjectPermissionActions.Delete
|
||||||
|
],
|
||||||
|
ProjectPermissionSub.SecretFolders
|
||||||
|
);
|
||||||
|
can(
|
||||||
|
[
|
||||||
|
ProjectPermissionDynamicSecretActions.ReadRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.EditRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.CreateRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.DeleteRootCredential,
|
||||||
|
ProjectPermissionDynamicSecretActions.Lease
|
||||||
|
],
|
||||||
|
ProjectPermissionSub.DynamicSecrets
|
||||||
|
);
|
||||||
|
can(
|
||||||
|
[
|
||||||
|
ProjectPermissionActions.Read,
|
||||||
|
ProjectPermissionActions.Edit,
|
||||||
|
ProjectPermissionActions.Create,
|
||||||
|
ProjectPermissionActions.Delete
|
||||||
|
],
|
||||||
|
ProjectPermissionSub.SecretImports
|
||||||
|
);
|
||||||
|
|
||||||
can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretApproval);
|
can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretApproval);
|
||||||
can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretRotation);
|
can([ProjectPermissionActions.Read], ProjectPermissionSub.SecretRotation);
|
||||||
@@ -493,6 +654,9 @@ const buildViewerPermissionRules = () => {
|
|||||||
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
|
const { can, rules } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
|
||||||
|
|
||||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets);
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets);
|
||||||
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretFolders);
|
||||||
|
can(ProjectPermissionDynamicSecretActions.ReadRootCredential, ProjectPermissionSub.DynamicSecrets);
|
||||||
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretImports);
|
||||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval);
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval);
|
||||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
|
||||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRotation);
|
can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRotation);
|
||||||
@@ -595,17 +759,63 @@ export const isAtLeastAsPrivilegedWorkspace = (
|
|||||||
};
|
};
|
||||||
/* eslint-enable */
|
/* eslint-enable */
|
||||||
|
|
||||||
export const SecretV2SubjectFieldMapper = (arg: string) => {
|
export const backfillPermissionV1SchemaToV2Schema = (
|
||||||
switch (arg) {
|
data: z.infer<typeof ProjectPermissionV1Schema>[],
|
||||||
case "environment":
|
dontRemoveReadFolderPermission?: boolean
|
||||||
return null;
|
) => {
|
||||||
case "secretPath":
|
let formattedData = UnpackedPermissionSchema.array().parse(data);
|
||||||
return null;
|
const secretSubjects = formattedData.filter((el) => el.subject === ProjectPermissionSub.Secrets);
|
||||||
case "secretName":
|
|
||||||
return `${TableName.SecretV2}.key`;
|
// this means the folder permission as readonly is set
|
||||||
case "secretTags":
|
const hasReadOnlyFolder = formattedData.filter((el) => el.subject === ProjectPermissionSub.SecretFolders);
|
||||||
return `${TableName.SecretTag}.slug`;
|
const secretImportPolicies = secretSubjects.map(({ subject, ...el }) => ({
|
||||||
default:
|
...el,
|
||||||
throw new BadRequestError({ message: `Invalid dynamic knex operator field: ${arg}` });
|
subject: ProjectPermissionSub.SecretImports as const
|
||||||
|
}));
|
||||||
|
|
||||||
|
const secretFolderPolicies = secretSubjects
|
||||||
|
.map(({ subject, ...el }) => ({
|
||||||
|
...el,
|
||||||
|
// read permission is not needed anymore
|
||||||
|
action: el.action.filter((caslAction) => caslAction !== ProjectPermissionActions.Read),
|
||||||
|
subject: ProjectPermissionSub.SecretFolders
|
||||||
|
}))
|
||||||
|
.filter((el) => el.action?.length > 0);
|
||||||
|
|
||||||
|
const dynamicSecretPolicies = secretSubjects.map(({ subject, ...el }) => {
|
||||||
|
const action = el.action.map((e) => {
|
||||||
|
switch (e) {
|
||||||
|
case ProjectPermissionActions.Edit:
|
||||||
|
return ProjectPermissionDynamicSecretActions.EditRootCredential;
|
||||||
|
case ProjectPermissionActions.Create:
|
||||||
|
return ProjectPermissionDynamicSecretActions.CreateRootCredential;
|
||||||
|
case ProjectPermissionActions.Delete:
|
||||||
|
return ProjectPermissionDynamicSecretActions.DeleteRootCredential;
|
||||||
|
case ProjectPermissionActions.Read:
|
||||||
|
return ProjectPermissionDynamicSecretActions.ReadRootCredential;
|
||||||
|
default:
|
||||||
|
return ProjectPermissionDynamicSecretActions.ReadRootCredential;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
...el,
|
||||||
|
action: el.action.includes(ProjectPermissionActions.Edit)
|
||||||
|
? [...action, ProjectPermissionDynamicSecretActions.Lease]
|
||||||
|
: action,
|
||||||
|
subject: ProjectPermissionSub.DynamicSecrets
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!dontRemoveReadFolderPermission) {
|
||||||
|
formattedData = formattedData.filter((i) => i.subject !== ProjectPermissionSub.SecretFolders);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return formattedData.concat(
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore-error this is valid ts
|
||||||
|
secretImportPolicies,
|
||||||
|
dynamicSecretPolicies,
|
||||||
|
hasReadOnlyFolder.length ? [] : secretFolderPolicies
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+93
-24
@@ -1,11 +1,16 @@
|
|||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
|
||||||
|
import { PackRule, packRules, unpackRules } from "@casl/ability/extra";
|
||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
|
|
||||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
import { TableName } from "@app/db/schemas";
|
||||||
|
import { isAtLeastAsPrivileged } from "@app/lib/casl";
|
||||||
|
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
|
import { UnpackedPermissionSchema } from "@app/server/routes/santizedSchemas/permission";
|
||||||
|
import { ActorType } from "@app/services/auth/auth-type";
|
||||||
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
|
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
|
||||||
|
|
||||||
import { TPermissionServiceFactory } from "../permission/permission-service";
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
|
import { ProjectPermissionActions, ProjectPermissionSet, ProjectPermissionSub } from "../permission/project-permission";
|
||||||
import { TProjectUserAdditionalPrivilegeDALFactory } from "./project-user-additional-privilege-dal";
|
import { TProjectUserAdditionalPrivilegeDALFactory } from "./project-user-additional-privilege-dal";
|
||||||
import {
|
import {
|
||||||
ProjectUserAdditionalPrivilegeTemporaryMode,
|
ProjectUserAdditionalPrivilegeTemporaryMode,
|
||||||
@@ -26,6 +31,11 @@ export type TProjectUserAdditionalPrivilegeServiceFactory = ReturnType<
|
|||||||
typeof projectUserAdditionalPrivilegeServiceFactory
|
typeof projectUserAdditionalPrivilegeServiceFactory
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
const unpackPermissions = (permissions: unknown) =>
|
||||||
|
UnpackedPermissionSchema.array().parse(
|
||||||
|
unpackRules((permissions || []) as PackRule<RawRuleOf<MongoAbility<ProjectPermissionSet>>>[])
|
||||||
|
);
|
||||||
|
|
||||||
export const projectUserAdditionalPrivilegeServiceFactory = ({
|
export const projectUserAdditionalPrivilegeServiceFactory = ({
|
||||||
projectUserAdditionalPrivilegeDAL,
|
projectUserAdditionalPrivilegeDAL,
|
||||||
projectMembershipDAL,
|
projectMembershipDAL,
|
||||||
@@ -43,7 +53,7 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
}: TCreateUserPrivilegeDTO) => {
|
}: TCreateUserPrivilegeDTO) => {
|
||||||
const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
|
const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
|
||||||
if (!projectMembership)
|
if (!projectMembership)
|
||||||
throw new NotFoundError({ message: `Project membership with ID '${projectMembershipId}' not found` });
|
throw new NotFoundError({ message: `Project membership with ID ${projectMembershipId} found` });
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
@@ -53,22 +63,41 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
||||||
|
const { permission: targetUserPermission } = await permissionService.getProjectPermission(
|
||||||
|
ActorType.USER,
|
||||||
|
projectMembership.userId,
|
||||||
|
projectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetUserPermission.update(targetUserPermission.rules.concat(customPermission));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetUserPermission);
|
||||||
|
if (!hasRequiredPriviledges)
|
||||||
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
const existingSlug = await projectUserAdditionalPrivilegeDAL.findOne({
|
const existingSlug = await projectUserAdditionalPrivilegeDAL.findOne({
|
||||||
slug,
|
slug,
|
||||||
projectId: projectMembership.projectId,
|
projectId: projectMembership.projectId,
|
||||||
userId: projectMembership.userId
|
userId: projectMembership.userId
|
||||||
});
|
});
|
||||||
if (existingSlug) throw new BadRequestError({ message: "Additional privilege of provided slug exist" });
|
if (existingSlug)
|
||||||
|
throw new BadRequestError({ message: `Additional privilege with provided slug ${slug} already exists` });
|
||||||
|
|
||||||
|
const packedPermission = JSON.stringify(packRules(customPermission));
|
||||||
if (!dto.isTemporary) {
|
if (!dto.isTemporary) {
|
||||||
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.create({
|
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.create({
|
||||||
userId: projectMembership.userId,
|
userId: projectMembership.userId,
|
||||||
projectId: projectMembership.projectId,
|
projectId: projectMembership.projectId,
|
||||||
slug,
|
slug,
|
||||||
permissions: customPermission
|
permissions: packedPermission
|
||||||
});
|
});
|
||||||
return additionalPrivilege;
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const relativeTempAllocatedTimeInMs = ms(dto.temporaryRange);
|
const relativeTempAllocatedTimeInMs = ms(dto.temporaryRange);
|
||||||
@@ -76,14 +105,17 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
projectId: projectMembership.projectId,
|
projectId: projectMembership.projectId,
|
||||||
userId: projectMembership.userId,
|
userId: projectMembership.userId,
|
||||||
slug,
|
slug,
|
||||||
permissions: customPermission,
|
permissions: packedPermission,
|
||||||
isTemporary: true,
|
isTemporary: true,
|
||||||
temporaryMode: ProjectUserAdditionalPrivilegeTemporaryMode.Relative,
|
temporaryMode: ProjectUserAdditionalPrivilegeTemporaryMode.Relative,
|
||||||
temporaryRange: dto.temporaryRange,
|
temporaryRange: dto.temporaryRange,
|
||||||
temporaryAccessStartTime: new Date(dto.temporaryAccessStartTime),
|
temporaryAccessStartTime: new Date(dto.temporaryAccessStartTime),
|
||||||
temporaryAccessEndTime: new Date(new Date(dto.temporaryAccessStartTime).getTime() + relativeTempAllocatedTimeInMs)
|
temporaryAccessEndTime: new Date(new Date(dto.temporaryAccessStartTime).getTime() + relativeTempAllocatedTimeInMs)
|
||||||
});
|
});
|
||||||
return additionalPrivilege;
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateById = async ({
|
const updateById = async ({
|
||||||
@@ -96,7 +128,7 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
}: TUpdateUserPrivilegeDTO) => {
|
}: TUpdateUserPrivilegeDTO) => {
|
||||||
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
||||||
if (!userPrivilege)
|
if (!userPrivilege)
|
||||||
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
|
throw new NotFoundError({ message: `User additional privilege with ID ${privilegeId} not found` });
|
||||||
|
|
||||||
const projectMembership = await projectMembershipDAL.findOne({
|
const projectMembership = await projectMembershipDAL.findOne({
|
||||||
userId: userPrivilege.userId,
|
userId: userPrivilege.userId,
|
||||||
@@ -116,6 +148,20 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
||||||
|
const { permission: targetUserPermission } = await permissionService.getProjectPermission(
|
||||||
|
ActorType.USER,
|
||||||
|
projectMembership.userId,
|
||||||
|
projectMembership.projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
|
||||||
|
// we need to validate that the privilege given is not higher than the assigning users permission
|
||||||
|
// @ts-expect-error this is expected error because of one being really accurate rule definition other being a bit more broader. Both are valid casl rules
|
||||||
|
targetUserPermission.update(targetUserPermission.rules.concat(dto.permissions || []));
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, targetUserPermission);
|
||||||
|
if (!hasRequiredPriviledges)
|
||||||
|
throw new ForbiddenRequestError({ message: "Failed to update more privileged identity" });
|
||||||
|
|
||||||
if (dto?.slug) {
|
if (dto?.slug) {
|
||||||
const existingSlug = await projectUserAdditionalPrivilegeDAL.findOne({
|
const existingSlug = await projectUserAdditionalPrivilegeDAL.findOne({
|
||||||
@@ -124,36 +170,50 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
projectId: projectMembership.projectId
|
projectId: projectMembership.projectId
|
||||||
});
|
});
|
||||||
if (existingSlug && existingSlug.id !== userPrivilege.id)
|
if (existingSlug && existingSlug.id !== userPrivilege.id)
|
||||||
throw new BadRequestError({ message: "Additional privilege of provided slug exist" });
|
throw new BadRequestError({ message: `Additional privilege with provided slug ${dto.slug} already exists` });
|
||||||
}
|
}
|
||||||
|
|
||||||
const isTemporary = typeof dto?.isTemporary !== "undefined" ? dto.isTemporary : userPrivilege.isTemporary;
|
const isTemporary = typeof dto?.isTemporary !== "undefined" ? dto.isTemporary : userPrivilege.isTemporary;
|
||||||
|
|
||||||
|
const packedPermission = dto.permissions && JSON.stringify(packRules(dto.permissions));
|
||||||
if (isTemporary) {
|
if (isTemporary) {
|
||||||
const temporaryAccessStartTime = dto?.temporaryAccessStartTime || userPrivilege?.temporaryAccessStartTime;
|
const temporaryAccessStartTime = dto?.temporaryAccessStartTime || userPrivilege?.temporaryAccessStartTime;
|
||||||
const temporaryRange = dto?.temporaryRange || userPrivilege?.temporaryRange;
|
const temporaryRange = dto?.temporaryRange || userPrivilege?.temporaryRange;
|
||||||
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.updateById(userPrivilege.id, {
|
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.updateById(userPrivilege.id, {
|
||||||
...dto,
|
slug: dto.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
|
isTemporary: dto.isTemporary,
|
||||||
|
temporaryRange: dto.temporaryRange,
|
||||||
|
temporaryMode: dto.temporaryMode,
|
||||||
temporaryAccessStartTime: new Date(temporaryAccessStartTime || ""),
|
temporaryAccessStartTime: new Date(temporaryAccessStartTime || ""),
|
||||||
temporaryAccessEndTime: new Date(new Date(temporaryAccessStartTime || "").getTime() + ms(temporaryRange || ""))
|
temporaryAccessEndTime: new Date(new Date(temporaryAccessStartTime || "").getTime() + ms(temporaryRange || ""))
|
||||||
});
|
});
|
||||||
return additionalPrivilege;
|
|
||||||
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.updateById(userPrivilege.id, {
|
const additionalPrivilege = await projectUserAdditionalPrivilegeDAL.updateById(userPrivilege.id, {
|
||||||
...dto,
|
slug: dto.slug,
|
||||||
|
permissions: packedPermission,
|
||||||
isTemporary: false,
|
isTemporary: false,
|
||||||
temporaryAccessStartTime: null,
|
temporaryAccessStartTime: null,
|
||||||
temporaryAccessEndTime: null,
|
temporaryAccessEndTime: null,
|
||||||
temporaryRange: null,
|
temporaryRange: null,
|
||||||
temporaryMode: null
|
temporaryMode: null
|
||||||
});
|
});
|
||||||
return additionalPrivilege;
|
return {
|
||||||
|
...additionalPrivilege,
|
||||||
|
permissions: unpackPermissions(additionalPrivilege.permissions)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteById = async ({ actorId, actor, actorOrgId, actorAuthMethod, privilegeId }: TDeleteUserPrivilegeDTO) => {
|
const deleteById = async ({ actorId, actor, actorOrgId, actorAuthMethod, privilegeId }: TDeleteUserPrivilegeDTO) => {
|
||||||
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
||||||
if (!userPrivilege)
|
if (!userPrivilege)
|
||||||
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
|
throw new NotFoundError({ message: `User additional privilege with ID ${privilegeId} not found` });
|
||||||
|
|
||||||
const projectMembership = await projectMembershipDAL.findOne({
|
const projectMembership = await projectMembershipDAL.findOne({
|
||||||
userId: userPrivilege.userId,
|
userId: userPrivilege.userId,
|
||||||
@@ -174,7 +234,10 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Member);
|
||||||
|
|
||||||
const deletedPrivilege = await projectUserAdditionalPrivilegeDAL.deleteById(userPrivilege.id);
|
const deletedPrivilege = await projectUserAdditionalPrivilegeDAL.deleteById(userPrivilege.id);
|
||||||
return deletedPrivilege;
|
return {
|
||||||
|
...deletedPrivilege,
|
||||||
|
permissions: unpackPermissions(deletedPrivilege.permissions)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPrivilegeDetailsById = async ({
|
const getPrivilegeDetailsById = async ({
|
||||||
@@ -186,7 +249,7 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
}: TGetUserPrivilegeDetailsDTO) => {
|
}: TGetUserPrivilegeDetailsDTO) => {
|
||||||
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
const userPrivilege = await projectUserAdditionalPrivilegeDAL.findById(privilegeId);
|
||||||
if (!userPrivilege)
|
if (!userPrivilege)
|
||||||
throw new NotFoundError({ message: `User additional privilege with ID '${privilegeId}' not found` });
|
throw new NotFoundError({ message: `User additional privilege with ID ${privilegeId} not found` });
|
||||||
|
|
||||||
const projectMembership = await projectMembershipDAL.findOne({
|
const projectMembership = await projectMembershipDAL.findOne({
|
||||||
userId: userPrivilege.userId,
|
userId: userPrivilege.userId,
|
||||||
@@ -206,7 +269,10 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
|
||||||
|
|
||||||
return userPrivilege;
|
return {
|
||||||
|
...userPrivilege,
|
||||||
|
permissions: unpackPermissions(userPrivilege.permissions)
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const listPrivileges = async ({
|
const listPrivileges = async ({
|
||||||
@@ -218,7 +284,7 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
}: TListUserPrivilegesDTO) => {
|
}: TListUserPrivilegesDTO) => {
|
||||||
const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
|
const projectMembership = await projectMembershipDAL.findById(projectMembershipId);
|
||||||
if (!projectMembership)
|
if (!projectMembership)
|
||||||
throw new NotFoundError({ message: `Project membership with ID '${projectMembershipId}' not found` });
|
throw new NotFoundError({ message: `Project membership with ID ${projectMembershipId} not found` });
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
@@ -229,10 +295,13 @@ export const projectUserAdditionalPrivilegeServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
|
||||||
|
|
||||||
const userPrivileges = await projectUserAdditionalPrivilegeDAL.find({
|
const userPrivileges = await projectUserAdditionalPrivilegeDAL.find(
|
||||||
userId: projectMembership.userId,
|
{
|
||||||
projectId: projectMembership.projectId
|
userId: projectMembership.userId,
|
||||||
});
|
projectId: projectMembership.projectId
|
||||||
|
},
|
||||||
|
{ sort: [[`${TableName.ProjectUserAdditionalPrivilege}.slug` as "slug", "asc"]] }
|
||||||
|
);
|
||||||
return userPrivileges;
|
return userPrivileges;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -1,18 +1,20 @@
|
|||||||
import { TProjectPermission } from "@app/lib/types";
|
import { TProjectPermission } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TProjectPermissionV2Schema } from "../permission/project-permission";
|
||||||
|
|
||||||
export enum ProjectUserAdditionalPrivilegeTemporaryMode {
|
export enum ProjectUserAdditionalPrivilegeTemporaryMode {
|
||||||
Relative = "relative"
|
Relative = "relative"
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TCreateUserPrivilegeDTO = (
|
export type TCreateUserPrivilegeDTO = (
|
||||||
| {
|
| {
|
||||||
permissions: unknown;
|
permissions: TProjectPermissionV2Schema[];
|
||||||
projectMembershipId: string;
|
projectMembershipId: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
isTemporary: false;
|
isTemporary: false;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
permissions: unknown;
|
permissions: TProjectPermissionV2Schema[];
|
||||||
projectMembershipId: string;
|
projectMembershipId: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
isTemporary: true;
|
isTemporary: true;
|
||||||
@@ -25,7 +27,7 @@ export type TCreateUserPrivilegeDTO = (
|
|||||||
|
|
||||||
export type TUpdateUserPrivilegeDTO = { privilegeId: string } & Omit<TProjectPermission, "projectId"> &
|
export type TUpdateUserPrivilegeDTO = { privilegeId: string } & Omit<TProjectPermission, "projectId"> &
|
||||||
Partial<{
|
Partial<{
|
||||||
permissions: unknown;
|
permissions: TProjectPermissionV2Schema[];
|
||||||
slug: string;
|
slug: string;
|
||||||
isTemporary: boolean;
|
isTemporary: boolean;
|
||||||
temporaryMode: ProjectUserAdditionalPrivilegeTemporaryMode.Relative;
|
temporaryMode: ProjectUserAdditionalPrivilegeTemporaryMode.Relative;
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export const secretApprovalPolicyDALFactory = (db: TDbClient) => {
|
|||||||
|
|
||||||
const secretApprovalPolicyFindQuery = (
|
const secretApprovalPolicyFindQuery = (
|
||||||
tx: Knex,
|
tx: Knex,
|
||||||
filter: TFindFilter<TSecretApprovalPolicies>,
|
filter: TFindFilter<TSecretApprovalPolicies & { projectId: string }>,
|
||||||
customFilter?: {
|
customFilter?: {
|
||||||
sapId?: string;
|
sapId?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import picomatch from "picomatch";
|
import picomatch from "picomatch";
|
||||||
|
|
||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
@@ -356,17 +356,8 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
environment,
|
environment,
|
||||||
secretPath
|
secretPath
|
||||||
}: TGetBoardSapDTO) => {
|
}: TGetBoardSapDTO) => {
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
await permissionService.getProjectPermission(actor, actorId, projectId, actorAuthMethod, actorOrgId);
|
||||||
actor,
|
|
||||||
actorId,
|
|
||||||
projectId,
|
|
||||||
actorAuthMethod,
|
|
||||||
actorOrgId
|
|
||||||
);
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Read,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { secretPath, environment })
|
|
||||||
);
|
|
||||||
return getSecretApprovalPolicy(projectId, environment, secretPath);
|
return getSecretApprovalPolicy(projectId, environment, secretPath);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+23
-10
@@ -43,7 +43,7 @@ import {
|
|||||||
fnSecretBulkDelete as fnSecretV2BridgeBulkDelete,
|
fnSecretBulkDelete as fnSecretV2BridgeBulkDelete,
|
||||||
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
||||||
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
||||||
getAllNestedSecretReferences as getAllNestedSecretReferencesV2Bridge
|
getAllSecretReferences as getAllSecretReferencesV2Bridge
|
||||||
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
||||||
import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
|
import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
|
||||||
import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
|
import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
|
||||||
@@ -531,11 +531,11 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
skipMultilineEncoding: el.skipMultilineEncoding,
|
skipMultilineEncoding: el.skipMultilineEncoding,
|
||||||
key: el.key,
|
key: el.key,
|
||||||
references: el.encryptedValue
|
references: el.encryptedValue
|
||||||
? getAllNestedSecretReferencesV2Bridge(
|
? getAllSecretReferencesV2Bridge(
|
||||||
secretManagerDecryptor({
|
secretManagerDecryptor({
|
||||||
cipherTextBlob: el.encryptedValue
|
cipherTextBlob: el.encryptedValue
|
||||||
}).toString()
|
}).toString()
|
||||||
)
|
).nestedReferences
|
||||||
: [],
|
: [],
|
||||||
type: SecretType.Shared
|
type: SecretType.Shared
|
||||||
})),
|
})),
|
||||||
@@ -555,11 +555,11 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
? {
|
? {
|
||||||
encryptedValue: el.encryptedValue as Buffer,
|
encryptedValue: el.encryptedValue as Buffer,
|
||||||
references: el.encryptedValue
|
references: el.encryptedValue
|
||||||
? getAllNestedSecretReferencesV2Bridge(
|
? getAllSecretReferencesV2Bridge(
|
||||||
secretManagerDecryptor({
|
secretManagerDecryptor({
|
||||||
cipherTextBlob: el.encryptedValue
|
cipherTextBlob: el.encryptedValue
|
||||||
}).toString()
|
}).toString()
|
||||||
)
|
).nestedReferences
|
||||||
: []
|
: []
|
||||||
}
|
}
|
||||||
: {};
|
: {};
|
||||||
@@ -1143,10 +1143,6 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Read,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
|
||||||
);
|
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
if (!folder)
|
if (!folder)
|
||||||
@@ -1309,7 +1305,24 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
|
|
||||||
const tagIds = unique(Object.values(commitTagIds).flat());
|
const tagIds = unique(Object.values(commitTagIds).flat());
|
||||||
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
|
const tags = tagIds.length ? await secretTagDAL.findManyTagsById(projectId, tagIds) : [];
|
||||||
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "One or more tags not found" });
|
if (tagIds.length !== tags.length) throw new NotFoundError({ message: "Tag not found" });
|
||||||
|
const tagsGroupById = groupBy(tags, (i) => i.id);
|
||||||
|
|
||||||
|
commits.forEach((commit) => {
|
||||||
|
let action = ProjectPermissionActions.Create;
|
||||||
|
if (commit.op === SecretOperations.Update) action = ProjectPermissionActions.Edit;
|
||||||
|
if (commit.op === SecretOperations.Delete) action = ProjectPermissionActions.Delete;
|
||||||
|
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
|
action,
|
||||||
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment,
|
||||||
|
secretPath,
|
||||||
|
secretName: commit.key,
|
||||||
|
secretTags: commitTagIds?.[commit.key]?.map((secretTagId) => tagsGroupById[secretTagId][0].slug)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => {
|
const secretApprovalRequest = await secretApprovalRequestDAL.transaction(async (tx) => {
|
||||||
const doc = await secretApprovalRequestDAL.create(
|
const doc = await secretApprovalRequestDAL.create(
|
||||||
|
|||||||
@@ -28,8 +28,7 @@ import { TSecretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret
|
|||||||
import {
|
import {
|
||||||
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
||||||
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
||||||
getAllNestedSecretReferences,
|
getAllSecretReferences
|
||||||
getAllNestedSecretReferences as getAllNestedSecretReferencesV2Bridge
|
|
||||||
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
||||||
import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
|
import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
|
||||||
import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
|
import { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";
|
||||||
@@ -253,11 +252,12 @@ export const secretReplicationServiceFactory = ({
|
|||||||
const sourceLocalSecrets = await secretV2BridgeDAL.find({ folderId: folder.id, type: SecretType.Shared });
|
const sourceLocalSecrets = await secretV2BridgeDAL.find({ folderId: folder.id, type: SecretType.Shared });
|
||||||
const sourceSecretImports = await secretImportDAL.find({ folderId: folder.id });
|
const sourceSecretImports = await secretImportDAL.find({ folderId: folder.id });
|
||||||
const sourceImportedSecrets = await fnSecretsV2FromImports({
|
const sourceImportedSecrets = await fnSecretsV2FromImports({
|
||||||
allowedImports: sourceSecretImports,
|
secretImports: sourceSecretImports,
|
||||||
secretDAL: secretV2BridgeDAL,
|
secretDAL: secretV2BridgeDAL,
|
||||||
folderDAL,
|
folderDAL,
|
||||||
secretImportDAL,
|
secretImportDAL,
|
||||||
decryptor: (value) => (value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : "")
|
decryptor: (value) => (value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : ""),
|
||||||
|
hasSecretAccess: () => true
|
||||||
});
|
});
|
||||||
// secrets that gets replicated across imports
|
// secrets that gets replicated across imports
|
||||||
const sourceDecryptedLocalSecrets = sourceLocalSecrets.map((el) => ({
|
const sourceDecryptedLocalSecrets = sourceLocalSecrets.map((el) => ({
|
||||||
@@ -419,7 +419,7 @@ export const secretReplicationServiceFactory = ({
|
|||||||
encryptedValue: doc.encryptedValue,
|
encryptedValue: doc.encryptedValue,
|
||||||
encryptedComment: doc.encryptedComment,
|
encryptedComment: doc.encryptedComment,
|
||||||
skipMultilineEncoding: doc.skipMultilineEncoding,
|
skipMultilineEncoding: doc.skipMultilineEncoding,
|
||||||
references: doc.secretValue ? getAllNestedSecretReferencesV2Bridge(doc.secretValue) : []
|
references: doc.secretValue ? getAllSecretReferences(doc.secretValue).nestedReferences : []
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -445,7 +445,7 @@ export const secretReplicationServiceFactory = ({
|
|||||||
encryptedValue: doc.encryptedValue as Buffer,
|
encryptedValue: doc.encryptedValue as Buffer,
|
||||||
encryptedComment: doc.encryptedComment,
|
encryptedComment: doc.encryptedComment,
|
||||||
skipMultilineEncoding: doc.skipMultilineEncoding,
|
skipMultilineEncoding: doc.skipMultilineEncoding,
|
||||||
references: doc.secretValue ? getAllNestedSecretReferencesV2Bridge(doc.secretValue) : []
|
references: doc.secretValue ? getAllSecretReferences(doc.secretValue).nestedReferences : []
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
@@ -694,7 +694,7 @@ export const secretReplicationServiceFactory = ({
|
|||||||
secretCommentTag: doc.secretCommentTag,
|
secretCommentTag: doc.secretCommentTag,
|
||||||
secretCommentCiphertext: doc.secretCommentCiphertext,
|
secretCommentCiphertext: doc.secretCommentCiphertext,
|
||||||
skipMultilineEncoding: doc.skipMultilineEncoding,
|
skipMultilineEncoding: doc.skipMultilineEncoding,
|
||||||
references: getAllNestedSecretReferences(doc.secretValue)
|
references: getAllSecretReferences(doc.secretValue).nestedReferences
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
@@ -730,7 +730,7 @@ export const secretReplicationServiceFactory = ({
|
|||||||
secretCommentTag: doc.secretCommentTag,
|
secretCommentTag: doc.secretCommentTag,
|
||||||
secretCommentCiphertext: doc.secretCommentCiphertext,
|
secretCommentCiphertext: doc.secretCommentCiphertext,
|
||||||
skipMultilineEncoding: doc.skipMultilineEncoding,
|
skipMultilineEncoding: doc.skipMultilineEncoding,
|
||||||
references: getAllNestedSecretReferences(doc.secretValue)
|
references: getAllSecretReferences(doc.secretValue).nestedReferences
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
import Ajv from "ajv";
|
import Ajv from "ajv";
|
||||||
|
|
||||||
import { ProjectVersion } from "@app/db/schemas";
|
import { ProjectVersion, TableName } from "@app/db/schemas";
|
||||||
import { decryptSymmetric128BitHexKeyUTF8, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
import { decryptSymmetric128BitHexKeyUTF8, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
||||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
import { TProjectPermission } from "@app/lib/types";
|
import { TProjectPermission } from "@app/lib/types";
|
||||||
@@ -103,13 +103,14 @@ export const secretRotationServiceFactory = ({
|
|||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const project = await projectDAL.findById(projectId);
|
const project = await projectDAL.findById(projectId);
|
||||||
const shouldUseBridge = project.version === ProjectVersion.V3;
|
const shouldUseBridge = project.version === ProjectVersion.V3;
|
||||||
|
|
||||||
if (shouldUseBridge) {
|
if (shouldUseBridge) {
|
||||||
const selectedSecrets = await secretV2BridgeDAL.find({
|
const selectedSecrets = await secretV2BridgeDAL.find({
|
||||||
folderId: folder.id,
|
folderId: folder.id,
|
||||||
$in: { id: Object.values(outputs) }
|
$in: { [`${TableName.SecretV2}.id` as "id"]: Object.values(outputs) }
|
||||||
});
|
});
|
||||||
if (selectedSecrets.length !== Object.values(outputs).length)
|
if (selectedSecrets.length !== Object.values(outputs).length)
|
||||||
throw new NotFoundError({ message: `Secrets not found in folder with ID '${folder.id}'` });
|
throw new NotFoundError({ message: `Secrets not found in folder with ID '${folder.id}'` });
|
||||||
|
|||||||
@@ -5,31 +5,31 @@ export const GROUPS = {
|
|||||||
role: "The role of the group to create."
|
role: "The role of the group to create."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
id: "The id of the group to update",
|
id: "The ID of the group to update.",
|
||||||
name: "The new name of the group to update to.",
|
name: "The new name of the group to update to.",
|
||||||
slug: "The new slug of the group to update to.",
|
slug: "The new slug of the group to update to.",
|
||||||
role: "The new role of the group to update to."
|
role: "The new role of the group to update to."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
id: "The id of the group to delete",
|
id: "The ID of the group to delete.",
|
||||||
slug: "The slug of the group to delete"
|
slug: "The slug of the group to delete."
|
||||||
},
|
},
|
||||||
LIST_USERS: {
|
LIST_USERS: {
|
||||||
id: "The id of the group to list users for",
|
id: "The ID of the group to list users for.",
|
||||||
offset: "The offset to start from. If you enter 10, it will start from the 10th user.",
|
offset: "The offset to start from. If you enter 10, it will start from the 10th user.",
|
||||||
limit: "The number of users to return.",
|
limit: "The number of users to return.",
|
||||||
username: "The username to search for.",
|
username: "The username to search for.",
|
||||||
search: "The text string that user email or name will be filtered by."
|
search: "The text string that user email or name will be filtered by."
|
||||||
},
|
},
|
||||||
ADD_USER: {
|
ADD_USER: {
|
||||||
id: "The id of the group to add the user to.",
|
id: "The ID of the group to add the user to.",
|
||||||
username: "The username of the user to add to the group."
|
username: "The username of the user to add to the group."
|
||||||
},
|
},
|
||||||
GET_BY_ID: {
|
GET_BY_ID: {
|
||||||
id: "The id of the group to fetch"
|
id: "The ID of the group to fetch."
|
||||||
},
|
},
|
||||||
DELETE_USER: {
|
DELETE_USER: {
|
||||||
id: "The id of the group to remove the user from.",
|
id: "The ID of the group to remove the user from.",
|
||||||
username: "The username of the user to remove from the group."
|
username: "The username of the user to remove from the group."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
@@ -119,7 +119,7 @@ export const AWS_AUTH = {
|
|||||||
identityId: "The ID of the identity to login.",
|
identityId: "The ID of the identity to login.",
|
||||||
iamHttpRequestMethod: "The HTTP request method used in the signed request.",
|
iamHttpRequestMethod: "The HTTP request method used in the signed request.",
|
||||||
iamRequestUrl:
|
iamRequestUrl:
|
||||||
"The base64-encoded HTTP URL used in the signed request. Most likely, the base64-encoding of https://sts.amazonaws.com/",
|
"The base64-encoded HTTP URL used in the signed request. Most likely, the base64-encoding of https://sts.amazonaws.com/.",
|
||||||
iamRequestBody:
|
iamRequestBody:
|
||||||
"The base64-encoded body of the signed request. Most likely, the base64-encoding of Action=GetCallerIdentity&Version=2011-06-15.",
|
"The base64-encoded body of the signed request. Most likely, the base64-encoding of Action=GetCallerIdentity&Version=2011-06-15.",
|
||||||
iamRequestHeaders: "The base64-encoded headers of the sts:GetCallerIdentity signed request."
|
iamRequestHeaders: "The base64-encoded headers of the sts:GetCallerIdentity signed request."
|
||||||
@@ -130,8 +130,8 @@ export const AWS_AUTH = {
|
|||||||
"The comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Infisical.",
|
"The comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Infisical.",
|
||||||
allowedAccountIds:
|
allowedAccountIds:
|
||||||
"The comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical.",
|
"The comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
stsEndpoint: "The endpoint URL for the AWS STS API.",
|
stsEndpoint: "The endpoint URL for the AWS STS API.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used.",
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from."
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from."
|
||||||
@@ -142,8 +142,8 @@ export const AWS_AUTH = {
|
|||||||
"The new comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Infisical.",
|
"The new comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Infisical.",
|
||||||
allowedAccountIds:
|
allowedAccountIds:
|
||||||
"The new comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical.",
|
"The new comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical.",
|
||||||
accessTokenTTL: "The new lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The new lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The new maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||||
stsEndpoint: "The new endpoint URL for the AWS STS API.",
|
stsEndpoint: "The new endpoint URL for the AWS STS API.",
|
||||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used.",
|
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used.",
|
||||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from."
|
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from."
|
||||||
@@ -167,8 +167,8 @@ export const AZURE_AUTH = {
|
|||||||
allowedServicePrincipalIds:
|
allowedServicePrincipalIds:
|
||||||
"The comma-separated list of Azure AD service principal IDs that are allowed to authenticate with Infisical.",
|
"The comma-separated list of Azure AD service principal IDs that are allowed to authenticate with Infisical.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -178,8 +178,8 @@ export const AZURE_AUTH = {
|
|||||||
allowedServicePrincipalIds:
|
allowedServicePrincipalIds:
|
||||||
"The new comma-separated list of Azure AD service principal IDs that are allowed to authenticate with Infisical.",
|
"The new comma-separated list of Azure AD service principal IDs that are allowed to authenticate with Infisical.",
|
||||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The new lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The new lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The new maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
RETRIEVE: {
|
RETRIEVE: {
|
||||||
@@ -203,8 +203,8 @@ export const GCP_AUTH = {
|
|||||||
allowedZones:
|
allowedZones:
|
||||||
"The comma-separated list of trusted zones that the GCE instances must belong to authenticate with Infisical.",
|
"The comma-separated list of trusted zones that the GCE instances must belong to authenticate with Infisical.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -216,8 +216,8 @@ export const GCP_AUTH = {
|
|||||||
allowedZones:
|
allowedZones:
|
||||||
"The new comma-separated list of trusted zones that the GCE instances must belong to authenticate with Infisical.",
|
"The new comma-separated list of trusted zones that the GCE instances must belong to authenticate with Infisical.",
|
||||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The new lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The new lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The new maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
RETRIEVE: {
|
RETRIEVE: {
|
||||||
@@ -244,8 +244,8 @@ export const KUBERNETES_AUTH = {
|
|||||||
allowedAudience:
|
allowedAudience:
|
||||||
"The optional audience claim that the service account JWT token must have to authenticate with Infisical.",
|
"The optional audience claim that the service account JWT token must have to authenticate with Infisical.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -276,15 +276,15 @@ export const TOKEN_AUTH = {
|
|||||||
ATTACH: {
|
ATTACH: {
|
||||||
identityId: "The ID of the identity to attach the configuration onto.",
|
identityId: "The ID of the identity to attach the configuration onto.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
identityId: "The ID of the identity to update the auth method for.",
|
identityId: "The ID of the identity to update the auth method for.",
|
||||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The new lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The new lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The new maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
RETRIEVE: {
|
RETRIEVE: {
|
||||||
@@ -296,18 +296,18 @@ export const TOKEN_AUTH = {
|
|||||||
GET_TOKENS: {
|
GET_TOKENS: {
|
||||||
identityId: "The ID of the identity to list token metadata for.",
|
identityId: "The ID of the identity to list token metadata for.",
|
||||||
offset: "The offset to start from. If you enter 10, it will start from the 10th token.",
|
offset: "The offset to start from. If you enter 10, it will start from the 10th token.",
|
||||||
limit: "The number of tokens to return"
|
limit: "The number of tokens to return."
|
||||||
},
|
},
|
||||||
CREATE_TOKEN: {
|
CREATE_TOKEN: {
|
||||||
identityId: "The ID of the identity to create the token for.",
|
identityId: "The ID of the identity to create the token for.",
|
||||||
name: "The name of the token to create"
|
name: "The name of the token to create."
|
||||||
},
|
},
|
||||||
UPDATE_TOKEN: {
|
UPDATE_TOKEN: {
|
||||||
tokenId: "The ID of the token to update metadata for",
|
tokenId: "The ID of the token to update metadata for.",
|
||||||
name: "The name of the token to update to"
|
name: "The name of the token to update to."
|
||||||
},
|
},
|
||||||
REVOKE_TOKEN: {
|
REVOKE_TOKEN: {
|
||||||
tokenId: "The ID of the token to revoke"
|
tokenId: "The ID of the token to revoke."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -324,8 +324,8 @@ export const OIDC_AUTH = {
|
|||||||
boundClaims: "The attributes that should be present in the JWT for it to be valid.",
|
boundClaims: "The attributes that should be present in the JWT for it to be valid.",
|
||||||
boundSubject: "The expected principal that is the subject of the JWT.",
|
boundSubject: "The expected principal that is the subject of the JWT.",
|
||||||
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -337,8 +337,8 @@ export const OIDC_AUTH = {
|
|||||||
boundClaims: "The new attributes that should be present in the JWT for it to be valid.",
|
boundClaims: "The new attributes that should be present in the JWT for it to be valid.",
|
||||||
boundSubject: "The new expected principal that is the subject of the JWT.",
|
boundSubject: "The new expected principal that is the subject of the JWT.",
|
||||||
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
|
||||||
accessTokenTTL: "The new lifetime for an acccess token in seconds.",
|
accessTokenTTL: "The new lifetime for an access token in seconds.",
|
||||||
accessTokenMaxTTL: "The new maximum lifetime for an acccess token in seconds.",
|
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
|
||||||
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used."
|
||||||
},
|
},
|
||||||
RETRIEVE: {
|
RETRIEVE: {
|
||||||
@@ -475,6 +475,7 @@ export const PROJECT_USERS = {
|
|||||||
},
|
},
|
||||||
GET_USER_MEMBERSHIP: {
|
GET_USER_MEMBERSHIP: {
|
||||||
workspaceId: "The ID of the project to get memberships from.",
|
workspaceId: "The ID of the project to get memberships from.",
|
||||||
|
membershipId: "The ID of the user's project membership.",
|
||||||
username: "The username to get project membership of. Email is the default username."
|
username: "The username to get project membership of. Email is the default username."
|
||||||
},
|
},
|
||||||
UPDATE_USER_MEMBERSHIP: {
|
UPDATE_USER_MEMBERSHIP: {
|
||||||
@@ -506,8 +507,8 @@ export const PROJECT_IDENTITIES = {
|
|||||||
isTemporary:
|
isTemporary:
|
||||||
"Whether the assigned role is temporary. If isTemporary is set true, must provide temporaryMode, temporaryRange and temporaryAccessStartTime.",
|
"Whether the assigned role is temporary. If isTemporary is set true, must provide temporaryMode, temporaryRange and temporaryAccessStartTime.",
|
||||||
temporaryMode: "Type of temporary expiry.",
|
temporaryMode: "Type of temporary expiry.",
|
||||||
temporaryRange: "Expiry time for temporary access. In relative mode it could be 1s,2m,3h",
|
temporaryRange: "Expiry time for temporary access. In relative mode it could be 1s, 2m ,3h, etc.",
|
||||||
temporaryAccessStartTime: "Time to which the temporary access starts"
|
temporaryAccessStartTime: "Time to which the temporary access starts."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
DELETE_IDENTITY_MEMBERSHIP: {
|
DELETE_IDENTITY_MEMBERSHIP: {
|
||||||
@@ -524,8 +525,8 @@ export const PROJECT_IDENTITIES = {
|
|||||||
isTemporary:
|
isTemporary:
|
||||||
"Whether the assigned role is temporary. If isTemporary is set true, must provide temporaryMode, temporaryRange and temporaryAccessStartTime.",
|
"Whether the assigned role is temporary. If isTemporary is set true, must provide temporaryMode, temporaryRange and temporaryAccessStartTime.",
|
||||||
temporaryMode: "Type of temporary expiry.",
|
temporaryMode: "Type of temporary expiry.",
|
||||||
temporaryRange: "Expiry time for temporary access. In relative mode it could be 1s,2m,3h",
|
temporaryRange: "Expiry time for temporary access. In relative mode it could be 1s, 2m, 3h, etc.",
|
||||||
temporaryAccessStartTime: "Time to which the temporary access starts"
|
temporaryAccessStartTime: "Time to which the temporary access starts."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -562,7 +563,7 @@ export const FOLDERS = {
|
|||||||
directory: "The directory to list folders from. (Deprecated in favor of path)"
|
directory: "The directory to list folders from. (Deprecated in favor of path)"
|
||||||
},
|
},
|
||||||
GET_BY_ID: {
|
GET_BY_ID: {
|
||||||
folderId: "The id of the folder to get details."
|
folderId: "The ID of the folder to get details."
|
||||||
},
|
},
|
||||||
CREATE: {
|
CREATE: {
|
||||||
workspaceId: "The ID of the project to create the folder in.",
|
workspaceId: "The ID of the project to create the folder in.",
|
||||||
@@ -595,22 +596,22 @@ export const SECRETS = {
|
|||||||
secretPath: "The path of the secret to attach tags to.",
|
secretPath: "The path of the secret to attach tags to.",
|
||||||
type: "The type of the secret to attach tags to. (shared/personal)",
|
type: "The type of the secret to attach tags to. (shared/personal)",
|
||||||
environment: "The slug of the environment where the secret is located",
|
environment: "The slug of the environment where the secret is located",
|
||||||
projectSlug: "The slug of the project where the secret is located",
|
projectSlug: "The slug of the project where the secret is located.",
|
||||||
tagSlugs: "An array of existing tag slugs to attach to the secret."
|
tagSlugs: "An array of existing tag slugs to attach to the secret."
|
||||||
},
|
},
|
||||||
DETACH_TAGS: {
|
DETACH_TAGS: {
|
||||||
secretName: "The name of the secret to detach tags from.",
|
secretName: "The name of the secret to detach tags from.",
|
||||||
secretPath: "The path of the secret to detach tags from.",
|
secretPath: "The path of the secret to detach tags from.",
|
||||||
type: "The type of the secret to attach tags to. (shared/personal)",
|
type: "The type of the secret to attach tags to. (shared/personal)",
|
||||||
environment: "The slug of the environment where the secret is located",
|
environment: "The slug of the environment where the secret is located.",
|
||||||
projectSlug: "The slug of the project where the secret is located",
|
projectSlug: "The slug of the project where the secret is located.",
|
||||||
tagSlugs: "An array of existing tag slugs to detach from the secret."
|
tagSlugs: "An array of existing tag slugs to detach from the secret."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const RAW_SECRETS = {
|
export const RAW_SECRETS = {
|
||||||
LIST: {
|
LIST: {
|
||||||
expand: "Whether or not to expand secret references",
|
expand: "Whether or not to expand secret references.",
|
||||||
recursive:
|
recursive:
|
||||||
"Whether or not to fetch all secrets from the specified base path, and all of its subdirectories. Note, the max depth is 20 deep.",
|
"Whether or not to fetch all secrets from the specified base path, and all of its subdirectories. Note, the max depth is 20 deep.",
|
||||||
workspaceId: "The ID of the project to list secrets from.",
|
workspaceId: "The ID of the project to list secrets from.",
|
||||||
@@ -619,7 +620,7 @@ export const RAW_SECRETS = {
|
|||||||
environment: "The slug of the environment to list secrets from.",
|
environment: "The slug of the environment to list secrets from.",
|
||||||
secretPath: "The secret path to list secrets from.",
|
secretPath: "The secret path to list secrets from.",
|
||||||
includeImports: "Weather to include imported secrets or not.",
|
includeImports: "Weather to include imported secrets or not.",
|
||||||
tagSlugs: "The comma separated tag slugs to filter secrets"
|
tagSlugs: "The comma separated tag slugs to filter secrets."
|
||||||
},
|
},
|
||||||
CREATE: {
|
CREATE: {
|
||||||
secretName: "The name of the secret to create.",
|
secretName: "The name of the secret to create.",
|
||||||
@@ -632,11 +633,11 @@ export const RAW_SECRETS = {
|
|||||||
type: "The type of the secret to create.",
|
type: "The type of the secret to create.",
|
||||||
workspaceId: "The ID of the project to create the secret in.",
|
workspaceId: "The ID of the project to create the secret in.",
|
||||||
tagIds: "The ID of the tags to be attached to the created secret.",
|
tagIds: "The ID of the tags to be attached to the created secret.",
|
||||||
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days",
|
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days.",
|
||||||
secretReminderNote: "Note to be attached in notification email"
|
secretReminderNote: "Note to be attached in notification email."
|
||||||
},
|
},
|
||||||
GET: {
|
GET: {
|
||||||
expand: "Whether or not to expand secret references",
|
expand: "Whether or not to expand secret references.",
|
||||||
secretName: "The name of the secret to get.",
|
secretName: "The name of the secret to get.",
|
||||||
workspaceId: "The ID of the project to get the secret from.",
|
workspaceId: "The ID of the project to get the secret from.",
|
||||||
workspaceSlug: "The slug of the project to get the secret from.",
|
workspaceSlug: "The slug of the project to get the secret from.",
|
||||||
@@ -650,16 +651,16 @@ export const RAW_SECRETS = {
|
|||||||
secretName: "The name of the secret to update.",
|
secretName: "The name of the secret to update.",
|
||||||
secretComment: "Update comment to the secret.",
|
secretComment: "Update comment to the secret.",
|
||||||
environment: "The slug of the environment where the secret is located.",
|
environment: "The slug of the environment where the secret is located.",
|
||||||
secretPath: "The path of the secret to update",
|
secretPath: "The path of the secret to update.",
|
||||||
secretValue: "The new value of the secret.",
|
secretValue: "The new value of the secret.",
|
||||||
skipMultilineEncoding: "Skip multiline encoding for the secret value.",
|
skipMultilineEncoding: "Skip multiline encoding for the secret value.",
|
||||||
type: "The type of the secret to update.",
|
type: "The type of the secret to update.",
|
||||||
projectSlug: "The slug of the project to update the secret in.",
|
projectSlug: "The slug of the project to update the secret in.",
|
||||||
workspaceId: "The ID of the project to update the secret in.",
|
workspaceId: "The ID of the project to update the secret in.",
|
||||||
tagIds: "The ID of the tags to be attached to the updated secret.",
|
tagIds: "The ID of the tags to be attached to the updated secret.",
|
||||||
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days",
|
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days.",
|
||||||
secretReminderNote: "Note to be attached in notification email",
|
secretReminderNote: "Note to be attached in notification email.",
|
||||||
newSecretName: "The new name for the secret"
|
newSecretName: "The new name for the secret."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
secretName: "The name of the secret to delete.",
|
secretName: "The name of the secret to delete.",
|
||||||
@@ -790,7 +791,7 @@ export const DYNAMIC_SECRETS = {
|
|||||||
environmentSlug: "The slug of the environment to update the dynamic secret in.",
|
environmentSlug: "The slug of the environment to update the dynamic secret in.",
|
||||||
path: "The path to update the dynamic secret in.",
|
path: "The path to update the dynamic secret in.",
|
||||||
name: "The name of the dynamic secret.",
|
name: "The name of the dynamic secret.",
|
||||||
inputs: "The new partial values for the configurated provider of the dynamic secret",
|
inputs: "The new partial values for the configured provider of the dynamic secret",
|
||||||
defaultTTL: "The default TTL that will be applied for all the leases.",
|
defaultTTL: "The default TTL that will be applied for all the leases.",
|
||||||
maxTTL: "The maximum limit a TTL can be leases or renewed.",
|
maxTTL: "The maximum limit a TTL can be leases or renewed.",
|
||||||
newName: "The new name for the dynamic secret."
|
newName: "The new name for the dynamic secret."
|
||||||
@@ -801,7 +802,7 @@ export const DYNAMIC_SECRETS = {
|
|||||||
path: "The path to delete the dynamic secret in.",
|
path: "The path to delete the dynamic secret in.",
|
||||||
name: "The name of the dynamic secret.",
|
name: "The name of the dynamic secret.",
|
||||||
isForced:
|
isForced:
|
||||||
"A boolean flag to delete the the dynamic secret from infisical without trying to remove it from external provider. Used when the dynamic secret got modified externally."
|
"A boolean flag to delete the the dynamic secret from Infisical without trying to remove it from external provider. Used when the dynamic secret got modified externally."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@@ -817,7 +818,7 @@ export const DYNAMIC_SECRET_LEASES = {
|
|||||||
environmentSlug: "The slug of the environment of the dynamic secret in.",
|
environmentSlug: "The slug of the environment of the dynamic secret in.",
|
||||||
path: "The path of the dynamic secret in.",
|
path: "The path of the dynamic secret in.",
|
||||||
dynamicSecretName: "The name of the dynamic secret.",
|
dynamicSecretName: "The name of the dynamic secret.",
|
||||||
ttl: "The lease lifetime ttl. If not provided the default TTL of dynamic secret will be used."
|
ttl: "The lease lifetime TTL. If not provided the default TTL of dynamic secret will be used."
|
||||||
},
|
},
|
||||||
RENEW: {
|
RENEW: {
|
||||||
projectSlug: "The slug of the project of the dynamic secret in.",
|
projectSlug: "The slug of the project of the dynamic secret in.",
|
||||||
@@ -832,7 +833,7 @@ export const DYNAMIC_SECRET_LEASES = {
|
|||||||
path: "The path of the dynamic secret in.",
|
path: "The path of the dynamic secret in.",
|
||||||
leaseId: "The ID of the dynamic secret lease.",
|
leaseId: "The ID of the dynamic secret lease.",
|
||||||
isForced:
|
isForced:
|
||||||
"A boolean flag to delete the the dynamic secret from infisical without trying to remove it from external provider. Used when the dynamic secret got modified externally."
|
"A boolean flag to delete the the dynamic secret from Infisical without trying to remove it from external provider. Used when the dynamic secret got modified externally."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
export const SECRET_TAGS = {
|
export const SECRET_TAGS = {
|
||||||
@@ -841,11 +842,11 @@ export const SECRET_TAGS = {
|
|||||||
},
|
},
|
||||||
GET_TAG_BY_ID: {
|
GET_TAG_BY_ID: {
|
||||||
projectId: "The ID of the project to get tags from.",
|
projectId: "The ID of the project to get tags from.",
|
||||||
tagId: "The ID of the tag to get details"
|
tagId: "The ID of the tag to get details."
|
||||||
},
|
},
|
||||||
GET_TAG_BY_SLUG: {
|
GET_TAG_BY_SLUG: {
|
||||||
projectId: "The ID of the project to get tags from.",
|
projectId: "The ID of the project to get tags from.",
|
||||||
tagSlug: "The slug of the tag to get details"
|
tagSlug: "The slug of the tag to get details."
|
||||||
},
|
},
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectId: "The ID of the project to create the tag in.",
|
projectId: "The ID of the project to create the tag in.",
|
||||||
@@ -855,7 +856,7 @@ export const SECRET_TAGS = {
|
|||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
projectId: "The ID of the project to update the tag in.",
|
projectId: "The ID of the project to update the tag in.",
|
||||||
tagId: "The ID of the tag to get details",
|
tagId: "The ID of the tag to get details.",
|
||||||
name: "The name of the tag to update.",
|
name: "The name of the tag to update.",
|
||||||
slug: "The slug of the tag to update.",
|
slug: "The slug of the tag to update.",
|
||||||
color: "The color of the tag to update."
|
color: "The color of the tag to update."
|
||||||
@@ -889,8 +890,8 @@ The permission object for the privilege.
|
|||||||
privilegePermission: "The permission object for the privilege.",
|
privilegePermission: "The permission object for the privilege.",
|
||||||
isPackPermission: "Whether the server should pack(compact) the permission object.",
|
isPackPermission: "Whether the server should pack(compact) the permission object.",
|
||||||
isTemporary: "Whether the privilege is temporary.",
|
isTemporary: "Whether the privilege is temporary.",
|
||||||
temporaryMode: "Type of temporary access given. Types: relative",
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
temporaryRange: "TTL for the temporay time. Eg: 1m, 1h, 1d",
|
temporaryRange: "TTL for the temporary time. Eg: 1m, 1h, 1d.",
|
||||||
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -915,8 +916,8 @@ The permission object for the privilege.
|
|||||||
`,
|
`,
|
||||||
privilegePermission: "The permission object for the privilege.",
|
privilegePermission: "The permission object for the privilege.",
|
||||||
isTemporary: "Whether the privilege is temporary.",
|
isTemporary: "Whether the privilege is temporary.",
|
||||||
temporaryMode: "Type of temporary access given. Types: relative",
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
temporaryRange: "TTL for the temporay time. Eg: 1m, 1h, 1d",
|
temporaryRange: "TTL for the temporary time. Eg: 1m, 1h, 1d.",
|
||||||
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
@@ -932,62 +933,102 @@ The permission object for the privilege.
|
|||||||
LIST: {
|
LIST: {
|
||||||
projectSlug: "The slug of the project of the identity in.",
|
projectSlug: "The slug of the project of the identity in.",
|
||||||
identityId: "The ID of the identity to list.",
|
identityId: "The ID of the identity to list.",
|
||||||
unpacked: "Whether the system should send the permissions as unpacked"
|
unpacked: "Whether the system should send the permissions as unpacked."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PROJECT_USER_ADDITIONAL_PRIVILEGE = {
|
export const PROJECT_USER_ADDITIONAL_PRIVILEGE = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectMembershipId: "Project membership id of user",
|
projectMembershipId: "Project membership ID of user.",
|
||||||
slug: "The slug of the privilege to create.",
|
slug: "The slug of the privilege to create.",
|
||||||
permissions:
|
permissions:
|
||||||
"The permission object for the privilege. Refer https://casl.js.org/v6/en/guide/define-rules#the-shape-of-raw-rule to understand the shape",
|
"The permission object for the privilege. Refer https://casl.js.org/v6/en/guide/define-rules#the-shape-of-raw-rule to understand the shape.",
|
||||||
isPackPermission: "Whether the server should pack(compact) the permission object.",
|
isPackPermission: "Whether the server should pack (compact) the permission object.",
|
||||||
isTemporary: "Whether the privilege is temporary.",
|
isTemporary: "Whether the privilege is temporary.",
|
||||||
temporaryMode: "Type of temporary access given. Types: relative",
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
temporaryRange: "TTL for the temporay time. Eg: 1m, 1h, 1d",
|
temporaryRange: "TTL for the temporary time. Eg: 1m, 1h, 1d.",
|
||||||
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
privilegeId: "The id of privilege object",
|
privilegeId: "The ID of privilege object.",
|
||||||
slug: "The slug of the privilege to create.",
|
slug: "The slug of the privilege to create.",
|
||||||
newSlug: "The new slug of the privilege to create.",
|
newSlug: "The new slug of the privilege to create.",
|
||||||
permissions:
|
permissions:
|
||||||
"The permission object for the privilege. Refer https://casl.js.org/v6/en/guide/define-rules#the-shape-of-raw-rule to understand the shape",
|
"The permission object for the privilege. Refer https://casl.js.org/v6/en/guide/define-rules#the-shape-of-raw-rule to understand the shape.",
|
||||||
isPackPermission: "Whether the server should pack(compact) the permission object.",
|
isPackPermission: "Whether the server should pack (compact) the permission object.",
|
||||||
isTemporary: "Whether the privilege is temporary.",
|
isTemporary: "Whether the privilege is temporary.",
|
||||||
temporaryMode: "Type of temporary access given. Types: relative",
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
temporaryRange: "TTL for the temporay time. Eg: 1m, 1h, 1d",
|
temporaryRange: "TTL for the temporary time. Eg: 1m, 1h, 1d.",
|
||||||
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
temporaryAccessStartTime: "ISO time for which temporary access should begin."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
privilegeId: "The id of privilege object"
|
privilegeId: "The ID of privilege object."
|
||||||
},
|
},
|
||||||
GET_BY_PRIVILEGEID: {
|
GET_BY_PRIVILEGE_ID: {
|
||||||
privilegeId: "The id of privilege object"
|
privilegeId: "The ID of privilege object."
|
||||||
},
|
},
|
||||||
LIST: {
|
LIST: {
|
||||||
projectMembershipId: "Project membership id of user"
|
projectMembershipId: "Project membership ID of user."
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const IDENTITY_ADDITIONAL_PRIVILEGE_V2 = {
|
||||||
|
CREATE: {
|
||||||
|
identityId: "The ID of the identity to create the privilege for.",
|
||||||
|
projectId: "The ID of the project of the identity in.",
|
||||||
|
slug: "The slug of the privilege to create.",
|
||||||
|
permission: "The permission for the privilege.",
|
||||||
|
isTemporary: "Whether the privilege is temporary or permanent.",
|
||||||
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
|
temporaryRange: "The TTL for the temporary access given. Eg: 1m, 1h, 1d.",
|
||||||
|
temporaryAccessStartTime: "The start time in ISO format when the temporary access should begin."
|
||||||
|
},
|
||||||
|
UPDATE: {
|
||||||
|
id: "The ID of the identity privilege.",
|
||||||
|
identityId: "The ID of the identity to update.",
|
||||||
|
slug: "The slug of the privilege to update.",
|
||||||
|
privilegePermission: "The permission for the privilege.",
|
||||||
|
isTemporary: "Whether the privilege is temporary.",
|
||||||
|
temporaryMode: "Type of temporary access given. Types: relative.",
|
||||||
|
temporaryRange: "The TTL for the temporary access given. Eg: 1m, 1h, 1d.",
|
||||||
|
temporaryAccessStartTime: "The start time in ISO format when the temporary access should begin."
|
||||||
|
},
|
||||||
|
DELETE: {
|
||||||
|
id: "The ID of the identity privilege.",
|
||||||
|
identityId: "The ID of the identity to delete.",
|
||||||
|
slug: "The slug of the privilege to delete."
|
||||||
|
},
|
||||||
|
GET_BY_SLUG: {
|
||||||
|
projectSlug: "The slug of the project of the identity in.",
|
||||||
|
identityId: "The ID of the identity to list.",
|
||||||
|
slug: "The slug of the privilege."
|
||||||
|
},
|
||||||
|
GET_BY_ID: {
|
||||||
|
id: "The ID of the identity privilege."
|
||||||
|
},
|
||||||
|
LIST: {
|
||||||
|
projectId: "The ID of the project that the identity is in.",
|
||||||
|
identityId: "The ID of the identity to list."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const INTEGRATION_AUTH = {
|
export const INTEGRATION_AUTH = {
|
||||||
GET: {
|
GET: {
|
||||||
integrationAuthId: "The id of integration authentication object."
|
integrationAuthId: "The ID of integration authentication object."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
integration: "The slug of the integration to be unauthorized.",
|
integration: "The slug of the integration to be unauthorized.",
|
||||||
projectId: "The ID of the project to delete the integration auth from."
|
projectId: "The ID of the project to delete the integration auth from."
|
||||||
},
|
},
|
||||||
DELETE_BY_ID: {
|
DELETE_BY_ID: {
|
||||||
integrationAuthId: "The id of integration authentication object to delete."
|
integrationAuthId: "The ID of integration authentication object to delete."
|
||||||
},
|
},
|
||||||
CREATE_ACCESS_TOKEN: {
|
CREATE_ACCESS_TOKEN: {
|
||||||
workspaceId: "The ID of the project to create the integration auth for.",
|
workspaceId: "The ID of the project to create the integration auth for.",
|
||||||
integration: "The slug of integration for the auth object.",
|
integration: "The slug of integration for the auth object.",
|
||||||
accessId: "The unique authorized access id of the external integration provider.",
|
accessId: "The unique authorized access ID of the external integration provider.",
|
||||||
accessToken: "The unique authorized access token of the external integration provider.",
|
accessToken: "The unique authorized access token of the external integration provider.",
|
||||||
awsAssumeIamRoleArn: "The AWS IAM Role to be assumed by Infisical",
|
awsAssumeIamRoleArn: "The AWS IAM Role to be assumed by Infisical.",
|
||||||
url: "",
|
url: "",
|
||||||
namespace: "",
|
namespace: "",
|
||||||
refreshToken: "The refresh token for integration authorization."
|
refreshToken: "The refresh token for integration authorization."
|
||||||
@@ -1006,16 +1047,16 @@ export const INTEGRATION = {
|
|||||||
targetEnvironment:
|
targetEnvironment:
|
||||||
"The target environment of the integration provider. Used in cloudflare pages, TeamCity, Gitlab integrations.",
|
"The target environment of the integration provider. Used in cloudflare pages, TeamCity, Gitlab integrations.",
|
||||||
targetEnvironmentId:
|
targetEnvironmentId:
|
||||||
"The target environment id of the integration provider. Used in cloudflare pages, teamcity, gitlab integrations.",
|
"The target environment ID of the integration provider. Used in cloudflare pages, teamcity, gitlab integrations.",
|
||||||
targetService:
|
targetService:
|
||||||
"The service based grouping identifier of the external provider. Used in Terraform cloud, Checkly, Railway and NorthFlank",
|
"The service based grouping identifier of the external provider. Used in Terraform cloud, Checkly, Railway and NorthFlank.",
|
||||||
targetServiceId:
|
targetServiceId:
|
||||||
"The service based grouping identifier ID of the external provider. Used in Terraform cloud, Checkly, Railway and NorthFlank",
|
"The service based grouping identifier ID of the external provider. Used in Terraform cloud, Checkly, Railway and NorthFlank.",
|
||||||
owner: "External integration providers service entity owner. Used in Github.",
|
owner: "External integration providers service entity owner. Used in Github.",
|
||||||
url: "The self-hosted URL of the platform to integrate with",
|
url: "The self-hosted URL of the platform to integrate with.",
|
||||||
path: "Path to save the synced secrets. Used by Gitlab, AWS Parameter Store, Vault",
|
path: "Path to save the synced secrets. Used by Gitlab, AWS Parameter Store, Vault.",
|
||||||
region: "AWS region to sync secrets to.",
|
region: "AWS region to sync secrets to.",
|
||||||
scope: "Scope of the provider. Used by Github, Qovery",
|
scope: "Scope of the provider. Used by Github, Qovery.",
|
||||||
metadata: {
|
metadata: {
|
||||||
secretPrefix: "The prefix for the saved secret. Used by GCP.",
|
secretPrefix: "The prefix for the saved secret. Used by GCP.",
|
||||||
secretSuffix: "The suffix for the saved secret. Used by GCP.",
|
secretSuffix: "The suffix for the saved secret. Used by GCP.",
|
||||||
@@ -1027,12 +1068,12 @@ export const INTEGRATION = {
|
|||||||
githubVisibility:
|
githubVisibility:
|
||||||
"Define where the secrets from the Github Integration should be visible. Option 'selected' lets you directly define which repositories to sync secrets to.",
|
"Define where the secrets from the Github Integration should be visible. Option 'selected' lets you directly define which repositories to sync secrets to.",
|
||||||
githubVisibilityRepoIds:
|
githubVisibilityRepoIds:
|
||||||
"The repository IDs to sync secrets to when using the Github Integration. Only applicable when using Organization scope, and visibility is set to 'selected'",
|
"The repository IDs to sync secrets to when using the Github Integration. Only applicable when using Organization scope, and visibility is set to 'selected'.",
|
||||||
kmsKeyId: "The ID of the encryption key from AWS KMS.",
|
kmsKeyId: "The ID of the encryption key from AWS KMS.",
|
||||||
shouldDisableDelete: "The flag to disable deletion of secrets in AWS Parameter Store.",
|
shouldDisableDelete: "The flag to disable deletion of secrets in AWS Parameter Store.",
|
||||||
shouldMaskSecrets: "Specifies if the secrets synced from Infisical to Gitlab should be marked as 'Masked'.",
|
shouldMaskSecrets: "Specifies if the secrets synced from Infisical to Gitlab should be marked as 'Masked'.",
|
||||||
shouldProtectSecrets: "Specifies if the secrets synced from Infisical to Gitlab should be marked as 'Protected'.",
|
shouldProtectSecrets: "Specifies if the secrets synced from Infisical to Gitlab should be marked as 'Protected'.",
|
||||||
shouldEnableDelete: "The flag to enable deletion of secrets"
|
shouldEnableDelete: "The flag to enable deletion of secrets."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
@@ -1051,7 +1092,7 @@ export const INTEGRATION = {
|
|||||||
integrationId: "The ID of the integration object."
|
integrationId: "The ID of the integration object."
|
||||||
},
|
},
|
||||||
SYNC: {
|
SYNC: {
|
||||||
integrationId: "The ID of the integration object to manually sync"
|
integrationId: "The ID of the integration object to manually sync."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1059,7 +1100,7 @@ export const AUDIT_LOG_STREAMS = {
|
|||||||
CREATE: {
|
CREATE: {
|
||||||
url: "The HTTP URL to push logs to.",
|
url: "The HTTP URL to push logs to.",
|
||||||
headers: {
|
headers: {
|
||||||
desc: "The HTTP headers attached for the external prrovider requests.",
|
desc: "The HTTP headers attached for the external provider requests.",
|
||||||
key: "The HTTP header key name.",
|
key: "The HTTP header key name.",
|
||||||
value: "The HTTP header value."
|
value: "The HTTP header value."
|
||||||
}
|
}
|
||||||
@@ -1068,7 +1109,7 @@ export const AUDIT_LOG_STREAMS = {
|
|||||||
id: "The ID of the audit log stream to update.",
|
id: "The ID of the audit log stream to update.",
|
||||||
url: "The HTTP URL to push logs to.",
|
url: "The HTTP URL to push logs to.",
|
||||||
headers: {
|
headers: {
|
||||||
desc: "The HTTP headers attached for the external prrovider requests.",
|
desc: "The HTTP headers attached for the external provider requests.",
|
||||||
key: "The HTTP header key name.",
|
key: "The HTTP header key name.",
|
||||||
value: "The HTTP header value."
|
value: "The HTTP header value."
|
||||||
}
|
}
|
||||||
@@ -1084,16 +1125,16 @@ export const AUDIT_LOG_STREAMS = {
|
|||||||
export const CERTIFICATE_AUTHORITIES = {
|
export const CERTIFICATE_AUTHORITIES = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectSlug: "Slug of the project to create the CA in.",
|
projectSlug: "Slug of the project to create the CA in.",
|
||||||
type: "The type of CA to create",
|
type: "The type of CA to create.",
|
||||||
friendlyName: "A friendly name for the CA",
|
friendlyName: "A friendly name for the CA.",
|
||||||
organization: "The organization (O) for the CA",
|
organization: "The organization (O) for the CA.",
|
||||||
ou: "The organization unit (OU) for the CA",
|
ou: "The organization unit (OU) for the CA.",
|
||||||
country: "The country name (C) for the CA",
|
country: "The country name (C) for the CA.",
|
||||||
province: "The state of province name for the CA",
|
province: "The state of province name for the CA.",
|
||||||
locality: "The locality name for the CA",
|
locality: "The locality name for the CA.",
|
||||||
commonName: "The common name (CN) for the CA",
|
commonName: "The common name (CN) for the CA.",
|
||||||
notBefore: "The date and time when the CA becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notBefore: "The date and time when the CA becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
notAfter: "The date and time when the CA expires in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notAfter: "The date and time when the CA expires in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
maxPathLength:
|
maxPathLength:
|
||||||
"The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
|
"The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
|
||||||
keyAlgorithm:
|
keyAlgorithm:
|
||||||
@@ -1102,238 +1143,240 @@ export const CERTIFICATE_AUTHORITIES = {
|
|||||||
"Whether or not certificates for this CA can only be issued through certificate templates."
|
"Whether or not certificates for this CA can only be issued through certificate templates."
|
||||||
},
|
},
|
||||||
GET: {
|
GET: {
|
||||||
caId: "The ID of the CA to get"
|
caId: "The ID of the CA to get."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
caId: "The ID of the CA to update",
|
caId: "The ID of the CA to update.",
|
||||||
status: "The status of the CA to update to. This can be one of active or disabled",
|
status: "The status of the CA to update to. This can be one of active or disabled.",
|
||||||
requireTemplateForIssuance:
|
requireTemplateForIssuance:
|
||||||
"Whether or not certificates for this CA can only be issued through certificate templates."
|
"Whether or not certificates for this CA can only be issued through certificate templates."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
caId: "The ID of the CA to delete"
|
caId: "The ID of the CA to delete."
|
||||||
},
|
},
|
||||||
GET_CSR: {
|
GET_CSR: {
|
||||||
caId: "The ID of the CA to generate CSR from",
|
caId: "The ID of the CA to generate CSR from.",
|
||||||
csr: "The generated CSR from the CA"
|
csr: "The generated CSR from the CA."
|
||||||
},
|
},
|
||||||
RENEW_CA_CERT: {
|
RENEW_CA_CERT: {
|
||||||
caId: "The ID of the CA to renew the CA certificate for",
|
caId: "The ID of the CA to renew the CA certificate for.",
|
||||||
type: "The type of behavior to use for the renewal operation. Currently Infisical is only able to renew a CA certificate with the same key pair.",
|
type: "The type of behavior to use for the renewal operation. Currently Infisical is only able to renew a CA certificate with the same key pair.",
|
||||||
notAfter: "The expiry date and time for the renewed CA certificate in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notAfter: "The expiry date and time for the renewed CA certificate in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
certificate: "The renewed CA certificate body",
|
certificate: "The renewed CA certificate body.",
|
||||||
certificateChain: "The certificate chain of the CA",
|
certificateChain: "The certificate chain of the CA.",
|
||||||
serialNumber: "The serial number of the renewed CA certificate"
|
serialNumber: "The serial number of the renewed CA certificate."
|
||||||
},
|
},
|
||||||
GET_CERT: {
|
GET_CERT: {
|
||||||
caId: "The ID of the CA to get the certificate body and certificate chain from",
|
caId: "The ID of the CA to get the certificate body and certificate chain from.",
|
||||||
certificate: "The certificate body of the CA",
|
certificate: "The certificate body of the CA.",
|
||||||
certificateChain: "The certificate chain of the CA",
|
certificateChain: "The certificate chain of the CA.",
|
||||||
serialNumber: "The serial number of the CA certificate"
|
serialNumber: "The serial number of the CA certificate."
|
||||||
},
|
},
|
||||||
GET_CERT_BY_ID: {
|
GET_CERT_BY_ID: {
|
||||||
caId: "The ID of the CA to get the CA certificate from",
|
caId: "The ID of the CA to get the CA certificate from.",
|
||||||
caCertId: "The ID of the CA certificate to get"
|
caCertId: "The ID of the CA certificate to get."
|
||||||
},
|
},
|
||||||
GET_CA_CERTS: {
|
GET_CA_CERTS: {
|
||||||
caId: "The ID of the CA to get the CA certificates for",
|
caId: "The ID of the CA to get the CA certificates for.",
|
||||||
certificate: "The certificate body of the CA certificate",
|
certificate: "The certificate body of the CA certificate.",
|
||||||
certificateChain: "The certificate chain of the CA certificate",
|
certificateChain: "The certificate chain of the CA certificate.",
|
||||||
serialNumber: "The serial number of the CA certificate",
|
serialNumber: "The serial number of the CA certificate.",
|
||||||
version: "The version of the CA certificate. The version is incremented for each CA renewal operation."
|
version: "The version of the CA certificate. The version is incremented for each CA renewal operation."
|
||||||
},
|
},
|
||||||
SIGN_INTERMEDIATE: {
|
SIGN_INTERMEDIATE: {
|
||||||
caId: "The ID of the CA to sign the intermediate certificate with",
|
caId: "The ID of the CA to sign the intermediate certificate with.",
|
||||||
csr: "The pem-encoded CSR to sign with the CA",
|
csr: "The pem-encoded CSR to sign with the CA.",
|
||||||
notBefore: "The date and time when the intermediate CA becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notBefore: "The date and time when the intermediate CA becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
notAfter: "The date and time when the intermediate CA expires in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notAfter: "The date and time when the intermediate CA expires in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
maxPathLength:
|
maxPathLength:
|
||||||
"The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
|
"The maximum number of intermediate CAs that may follow this CA in the certificate / CA chain. A maxPathLength of -1 implies no path limit on the chain.",
|
||||||
certificate: "The signed intermediate certificate",
|
certificate: "The signed intermediate certificate.",
|
||||||
certificateChain: "The certificate chain of the intermediate certificate",
|
certificateChain: "The certificate chain of the intermediate certificate.",
|
||||||
issuingCaCertificate: "The certificate of the issuing CA",
|
issuingCaCertificate: "The certificate of the issuing CA.",
|
||||||
serialNumber: "The serial number of the intermediate certificate"
|
serialNumber: "The serial number of the intermediate certificate."
|
||||||
},
|
},
|
||||||
IMPORT_CERT: {
|
IMPORT_CERT: {
|
||||||
caId: "The ID of the CA to import the certificate for",
|
caId: "The ID of the CA to import the certificate for.",
|
||||||
certificate: "The certificate body to import",
|
certificate: "The certificate body to import.",
|
||||||
certificateChain: "The certificate chain to import"
|
certificateChain: "The certificate chain to import."
|
||||||
},
|
},
|
||||||
ISSUE_CERT: {
|
ISSUE_CERT: {
|
||||||
caId: "The ID of the CA to issue the certificate from",
|
caId: "The ID of the CA to issue the certificate from.",
|
||||||
certificateTemplateId: "The ID of the certificate template to issue the certificate from",
|
certificateTemplateId: "The ID of the certificate template to issue the certificate from.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to add the certificate to",
|
pkiCollectionId: "The ID of the PKI collection to add the certificate to.",
|
||||||
friendlyName: "A friendly name for the certificate",
|
friendlyName: "A friendly name for the certificate.",
|
||||||
commonName: "The common name (CN) for the certificate",
|
commonName: "The common name (CN) for the certificate.",
|
||||||
altNames:
|
altNames:
|
||||||
"A comma-delimited list of Subject Alternative Names (SANs) for the certificate; these can be host names or email addresses.",
|
"A comma-delimited list of Subject Alternative Names (SANs) for the certificate; these can be host names or email addresses.",
|
||||||
ttl: "The time to live for the certificate such as 1m, 1h, 1d, 1y, ...",
|
ttl: "The time to live for the certificate such as 1m, 1h, 1d, 1y, ...",
|
||||||
notBefore: "The date and time when the certificate becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notBefore: "The date and time when the certificate becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
notAfter: "The date and time when the certificate expires in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notAfter: "The date and time when the certificate expires in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
certificate: "The issued certificate",
|
certificate: "The issued certificate.",
|
||||||
issuingCaCertificate: "The certificate of the issuing CA",
|
issuingCaCertificate: "The certificate of the issuing CA.",
|
||||||
certificateChain: "The certificate chain of the issued certificate",
|
certificateChain: "The certificate chain of the issued certificate.",
|
||||||
privateKey: "The private key of the issued certificate",
|
privateKey: "The private key of the issued certificate.",
|
||||||
serialNumber: "The serial number of the issued certificate",
|
serialNumber: "The serial number of the issued certificate.",
|
||||||
keyUsages: "The key usage extension of the certificate",
|
keyUsages: "The key usage extension of the certificate.",
|
||||||
extendedKeyUsages: "The extended key usage extension of the certificate"
|
extendedKeyUsages: "The extended key usage extension of the certificate."
|
||||||
},
|
},
|
||||||
SIGN_CERT: {
|
SIGN_CERT: {
|
||||||
caId: "The ID of the CA to issue the certificate from",
|
caId: "The ID of the CA to issue the certificate from.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to add the certificate to",
|
pkiCollectionId: "The ID of the PKI collection to add the certificate to.",
|
||||||
keyUsages: "The key usage extension of the certificate",
|
keyUsages: "The key usage extension of the certificate.",
|
||||||
extendedKeyUsages: "The extended key usage extension of the certificate",
|
extendedKeyUsages: "The extended key usage extension of the certificate.",
|
||||||
csr: "The pem-encoded CSR to sign with the CA to be used for certificate issuance",
|
csr: "The pem-encoded CSR to sign with the CA to be used for certificate issuance.",
|
||||||
friendlyName: "A friendly name for the certificate",
|
friendlyName: "A friendly name for the certificate.",
|
||||||
commonName: "The common name (CN) for the certificate",
|
commonName: "The common name (CN) for the certificate.",
|
||||||
altNames:
|
altNames:
|
||||||
"A comma-delimited list of Subject Alternative Names (SANs) for the certificate; these can be host names or email addresses.",
|
"A comma-delimited list of Subject Alternative Names (SANs) for the certificate; these can be host names or email addresses.",
|
||||||
ttl: "The time to live for the certificate such as 1m, 1h, 1d, 1y, ...",
|
ttl: "The time to live for the certificate such as 1m, 1h, 1d, 1y, ...",
|
||||||
notBefore: "The date and time when the certificate becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notBefore: "The date and time when the certificate becomes valid in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
notAfter: "The date and time when the certificate expires in YYYY-MM-DDTHH:mm:ss.sssZ format",
|
notAfter: "The date and time when the certificate expires in YYYY-MM-DDTHH:mm:ss.sssZ format.",
|
||||||
certificate: "The issued certificate",
|
certificate: "The issued certificate.",
|
||||||
issuingCaCertificate: "The certificate of the issuing CA",
|
issuingCaCertificate: "The certificate of the issuing CA.",
|
||||||
certificateChain: "The certificate chain of the issued certificate",
|
certificateChain: "The certificate chain of the issued certificate.",
|
||||||
serialNumber: "The serial number of the issued certificate"
|
serialNumber: "The serial number of the issued certificate."
|
||||||
},
|
},
|
||||||
GET_CRLS: {
|
GET_CRLS: {
|
||||||
caId: "The ID of the CA to get the certificate revocation lists (CRLs) for",
|
caId: "The ID of the CA to get the certificate revocation lists (CRLs) for.",
|
||||||
id: "The ID of certificate revocation list (CRL)",
|
id: "The ID of certificate revocation list (CRL).",
|
||||||
crl: "The certificate revocation list (CRL)"
|
crl: "The certificate revocation list (CRL)."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CERTIFICATES = {
|
export const CERTIFICATES = {
|
||||||
GET: {
|
GET: {
|
||||||
serialNumber: "The serial number of the certificate to get"
|
serialNumber: "The serial number of the certificate to get."
|
||||||
},
|
},
|
||||||
REVOKE: {
|
REVOKE: {
|
||||||
serialNumber:
|
serialNumber:
|
||||||
"The serial number of the certificate to revoke. The revoked certificate will be added to the certificate revocation list (CRL) of the CA.",
|
"The serial number of the certificate to revoke. The revoked certificate will be added to the certificate revocation list (CRL) of the CA.",
|
||||||
revocationReason: "The reason for revoking the certificate.",
|
revocationReason: "The reason for revoking the certificate.",
|
||||||
revokedAt: "The date and time when the certificate was revoked",
|
revokedAt: "The date and time when the certificate was revoked.",
|
||||||
serialNumberRes: "The serial number of the revoked certificate."
|
serialNumberRes: "The serial number of the revoked certificate."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
serialNumber: "The serial number of the certificate to delete"
|
serialNumber: "The serial number of the certificate to delete."
|
||||||
},
|
},
|
||||||
GET_CERT: {
|
GET_CERT: {
|
||||||
serialNumber: "The serial number of the certificate to get the certificate body and certificate chain for",
|
serialNumber: "The serial number of the certificate to get the certificate body and certificate chain for.",
|
||||||
certificate: "The certificate body of the certificate",
|
certificate: "The certificate body of the certificate.",
|
||||||
certificateChain: "The certificate chain of the certificate",
|
certificateChain: "The certificate chain of the certificate.",
|
||||||
serialNumberRes: "The serial number of the certificate"
|
serialNumberRes: "The serial number of the certificate."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CERTIFICATE_TEMPLATES = {
|
export const CERTIFICATE_TEMPLATES = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
caId: "The ID of the certificate authority to associate the template with",
|
caId: "The ID of the certificate authority to associate the template with.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to bind to the template",
|
pkiCollectionId: "The ID of the PKI collection to bind to the template.",
|
||||||
name: "The name of the template",
|
name: "The name of the template.",
|
||||||
commonName: "The regular expression string to use for validating common names",
|
commonName: "The regular expression string to use for validating common names.",
|
||||||
subjectAlternativeName: "The regular expression string to use for validating subject alternative names",
|
subjectAlternativeName: "The regular expression string to use for validating subject alternative names.",
|
||||||
ttl: "The max TTL for the template",
|
ttl: "The max TTL for the template.",
|
||||||
keyUsages: "The key usage constraint or default value for when template is used during certificate issuance",
|
keyUsages: "The key usage constraint or default value for when template is used during certificate issuance.",
|
||||||
extendedKeyUsages:
|
extendedKeyUsages:
|
||||||
"The extended key usage constraint or default value for when template is used during certificate issuance"
|
"The extended key usage constraint or default value for when template is used during certificate issuance."
|
||||||
},
|
},
|
||||||
GET: {
|
GET: {
|
||||||
certificateTemplateId: "The ID of the certificate template to get"
|
certificateTemplateId: "The ID of the certificate template to get."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
certificateTemplateId: "The ID of the certificate template to update",
|
certificateTemplateId: "The ID of the certificate template to update.",
|
||||||
caId: "The ID of the certificate authority to update the association with the template",
|
caId: "The ID of the certificate authority to update the association with the template.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to update the binding to the template",
|
pkiCollectionId: "The ID of the PKI collection to update the binding to the template.",
|
||||||
name: "The updated name of the template",
|
name: "The updated name of the template.",
|
||||||
commonName: "The updated regular expression string for validating common names",
|
commonName: "The updated regular expression string for validating common names.",
|
||||||
subjectAlternativeName: "The updated regular expression string for validating subject alternative names",
|
subjectAlternativeName: "The updated regular expression string for validating subject alternative names.",
|
||||||
ttl: "The updated max TTL for the template",
|
ttl: "The updated max TTL for the template.",
|
||||||
keyUsages:
|
keyUsages:
|
||||||
"The updated key usage constraint or default value for when template is used during certificate issuance",
|
"The updated key usage constraint or default value for when template is used during certificate issuance.",
|
||||||
extendedKeyUsages:
|
extendedKeyUsages:
|
||||||
"The updated extended key usage constraint or default value for when template is used during certificate issuance"
|
"The updated extended key usage constraint or default value for when template is used during certificate issuance."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
certificateTemplateId: "The ID of the certificate template to delete"
|
certificateTemplateId: "The ID of the certificate template to delete."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CA_CRLS = {
|
export const CA_CRLS = {
|
||||||
GET: {
|
GET: {
|
||||||
crlId: "The ID of the certificate revocation list (CRL) to get",
|
crlId: "The ID of the certificate revocation list (CRL) to get.",
|
||||||
crl: "The certificate revocation list (CRL)"
|
crl: "The certificate revocation list (CRL)."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ALERTS = {
|
export const ALERTS = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectId: "The ID of the project to create the alert in",
|
projectId: "The ID of the project to create the alert in.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to bind to the alert",
|
pkiCollectionId: "The ID of the PKI collection to bind to the alert.",
|
||||||
name: "The name of the alert",
|
name: "The name of the alert.",
|
||||||
alertBeforeDays: "The number of days before the certificate expires to trigger the alert",
|
alertBeforeDays: "The number of days before the certificate expires to trigger the alert.",
|
||||||
emails: "The email addresses to send the alert email to"
|
emails: "The email addresses to send the alert email to."
|
||||||
},
|
},
|
||||||
GET: {
|
GET: {
|
||||||
alertId: "The ID of the alert to get"
|
alertId: "The ID of the alert to get."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
alertId: "The ID of the alert to update",
|
alertId: "The ID of the alert to update.",
|
||||||
name: "The name of the alert to update to",
|
name: "The name of the alert to update to.",
|
||||||
alertBeforeDays: "The number of days before the certificate expires to trigger the alert to update to",
|
alertBeforeDays: "The number of days before the certificate expires to trigger the alert to update to.",
|
||||||
pkiCollectionId: "The ID of the PKI collection to bind to the alert to update to",
|
pkiCollectionId: "The ID of the PKI collection to bind to the alert to update to.",
|
||||||
emails: "The email addresses to send the alert email to update to"
|
emails: "The email addresses to send the alert email to update to."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
alertId: "The ID of the alert to delete"
|
alertId: "The ID of the alert to delete."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PKI_COLLECTIONS = {
|
export const PKI_COLLECTIONS = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectId: "The ID of the project to create the PKI collection in",
|
projectId: "The ID of the project to create the PKI collection in.",
|
||||||
name: "The name of the PKI collection",
|
name: "The name of the PKI collection.",
|
||||||
description: "A description for the PKI collection"
|
description: "A description for the PKI collection."
|
||||||
},
|
},
|
||||||
GET: {
|
GET: {
|
||||||
collectionId: "The ID of the PKI collection to get"
|
collectionId: "The ID of the PKI collection to get."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
collectionId: "The ID of the PKI collection to update",
|
collectionId: "The ID of the PKI collection to update.",
|
||||||
name: "The name of the PKI collection to update to",
|
name: "The name of the PKI collection to update to.",
|
||||||
description: "The description for the PKI collection to update to"
|
description: "The description for the PKI collection to update to."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
collectionId: "The ID of the PKI collection to delete"
|
collectionId: "The ID of the PKI collection to delete."
|
||||||
},
|
},
|
||||||
LIST_ITEMS: {
|
LIST_ITEMS: {
|
||||||
collectionId: "The ID of the PKI collection to list items from",
|
collectionId: "The ID of the PKI collection to list items from.",
|
||||||
type: "The type of the PKI collection item to list",
|
type: "The type of the PKI collection item to list.",
|
||||||
offset: "The offset to start from",
|
offset: "The offset to start from.",
|
||||||
limit: "The number of items to return"
|
limit: "The number of items to return."
|
||||||
},
|
},
|
||||||
ADD_ITEM: {
|
ADD_ITEM: {
|
||||||
collectionId: "The ID of the PKI collection to add the item to",
|
collectionId: "The ID of the PKI collection to add the item to.",
|
||||||
type: "The type of the PKI collection item to add",
|
type: "The type of the PKI collection item to add.",
|
||||||
itemId: "The resource ID of the PKI collection item to add"
|
itemId: "The resource ID of the PKI collection item to add."
|
||||||
},
|
},
|
||||||
DELETE_ITEM: {
|
DELETE_ITEM: {
|
||||||
collectionId: "The ID of the PKI collection to delete the item from",
|
collectionId: "The ID of the PKI collection to delete the item from.",
|
||||||
collectionItemId: "The ID of the PKI collection item to delete",
|
collectionItemId: "The ID of the PKI collection item to delete.",
|
||||||
type: "The type of the deleted PKI collection item",
|
type: "The type of the deleted PKI collection item.",
|
||||||
itemId: "The resource ID of the deleted PKI collection item"
|
itemId: "The resource ID of the deleted PKI collection item."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PROJECT_ROLE = {
|
export const PROJECT_ROLE = {
|
||||||
CREATE: {
|
CREATE: {
|
||||||
projectSlug: "Slug of the project to create the role for.",
|
projectSlug: "Slug of the project to create the role for.",
|
||||||
|
projectId: "Id of the project to create the role for.",
|
||||||
slug: "The slug of the role.",
|
slug: "The slug of the role.",
|
||||||
name: "The name of the role.",
|
name: "The name of the role.",
|
||||||
description: "The description for the role.",
|
description: "The description for the role.",
|
||||||
permissions: "The permissions assigned to the role."
|
permissions: "The permissions assigned to the role."
|
||||||
},
|
},
|
||||||
UPDATE: {
|
UPDATE: {
|
||||||
projectSlug: "Slug of the project to update the role for.",
|
projectSlug: "The slug of the project to update the role for.",
|
||||||
|
projectId: "The ID of the project to update the role for.",
|
||||||
roleId: "The ID of the role to update",
|
roleId: "The ID of the role to update",
|
||||||
slug: "The slug of the role.",
|
slug: "The slug of the role.",
|
||||||
name: "The name of the role.",
|
name: "The name of the role.",
|
||||||
@@ -1341,15 +1384,18 @@ export const PROJECT_ROLE = {
|
|||||||
permissions: "The permissions assigned to the role."
|
permissions: "The permissions assigned to the role."
|
||||||
},
|
},
|
||||||
DELETE: {
|
DELETE: {
|
||||||
projectSlug: "Slug of the project to delete this role for.",
|
projectSlug: "The slug of the project to delete this role for.",
|
||||||
|
projectId: "The ID of the project to delete the role for.",
|
||||||
roleId: "The ID of the role to update"
|
roleId: "The ID of the role to update"
|
||||||
},
|
},
|
||||||
GET_ROLE_BY_SLUG: {
|
GET_ROLE_BY_SLUG: {
|
||||||
projectSlug: "The slug of the project.",
|
projectSlug: "The slug of the project.",
|
||||||
roleSlug: "The slug of the role to get details"
|
projectId: "The ID of the project.",
|
||||||
|
roleSlug: "The slug of the role to get details."
|
||||||
},
|
},
|
||||||
LIST: {
|
LIST: {
|
||||||
projectSlug: "The slug of the project to list the roles of."
|
projectSlug: "The slug of the project to list the roles of.",
|
||||||
|
projectId: "The ID of the project."
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
import { AnyAbility, ExtractSubjectType } from "@casl/ability";
|
|
||||||
import { AbilityQuery, rulesToQuery } from "@casl/ability/extra";
|
|
||||||
import { Tables } from "knex/types/tables";
|
|
||||||
|
|
||||||
import { BadRequestError, UnauthorizedError } from "../errors";
|
|
||||||
import { TKnexDynamicOperator } from "../knex/dynamic";
|
|
||||||
|
|
||||||
type TBuildKnexQueryFromCaslDTO<K extends AnyAbility> = {
|
|
||||||
ability: K;
|
|
||||||
subject: ExtractSubjectType<Parameters<K["rulesFor"]>[1]>;
|
|
||||||
action: Parameters<K["rulesFor"]>[0];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const buildKnexQueryFromCaslOperators = <K extends AnyAbility>({
|
|
||||||
ability,
|
|
||||||
subject,
|
|
||||||
action
|
|
||||||
}: TBuildKnexQueryFromCaslDTO<K>) => {
|
|
||||||
const query = rulesToQuery(ability, action, subject, (rule) => {
|
|
||||||
if (!rule.ast) throw new Error("Ast not defined");
|
|
||||||
return rule.ast;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (query === null) throw new UnauthorizedError({ message: `You don't have permission to do ${action} ${subject}` });
|
|
||||||
return query;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TFieldMapper<T extends keyof Tables> = {
|
|
||||||
[K in T]: `${K}.${Exclude<keyof Tables[K]["base"], symbol>}`;
|
|
||||||
}[T];
|
|
||||||
|
|
||||||
type TFormatCaslFieldsWithTableNames<T extends keyof Tables> = {
|
|
||||||
// handle if any missing operator else throw error let the app break because this is executing again the db
|
|
||||||
missingOperatorCallback?: (operator: string) => void;
|
|
||||||
fieldMapping: (arg: string) => TFieldMapper<T> | null;
|
|
||||||
dynamicQuery: TKnexDynamicOperator;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const formatCaslOperatorFieldsWithTableNames = <T extends keyof Tables>({
|
|
||||||
missingOperatorCallback = (arg) => {
|
|
||||||
throw new BadRequestError({ message: `Unknown permission operator: ${arg}` });
|
|
||||||
},
|
|
||||||
dynamicQuery: dynamicQueryAst,
|
|
||||||
fieldMapping
|
|
||||||
}: TFormatCaslFieldsWithTableNames<T>) => {
|
|
||||||
const stack: [TKnexDynamicOperator, TKnexDynamicOperator | null][] = [[dynamicQueryAst, null]];
|
|
||||||
|
|
||||||
while (stack.length) {
|
|
||||||
const [filterAst, parentAst] = stack.pop()!;
|
|
||||||
|
|
||||||
if (filterAst.operator === "and" || filterAst.operator === "or" || filterAst.operator === "not") {
|
|
||||||
filterAst.value.forEach((el) => {
|
|
||||||
stack.push([el, filterAst]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// eslint-disable-next-line no-continue
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
filterAst.operator === "eq" ||
|
|
||||||
filterAst.operator === "ne" ||
|
|
||||||
filterAst.operator === "in" ||
|
|
||||||
filterAst.operator === "endsWith" ||
|
|
||||||
filterAst.operator === "startsWith"
|
|
||||||
) {
|
|
||||||
const attrPath = fieldMapping(filterAst.field);
|
|
||||||
if (attrPath) {
|
|
||||||
filterAst.field = attrPath;
|
|
||||||
} else if (parentAst && Array.isArray(parentAst.value)) {
|
|
||||||
parentAst.value = parentAst.value.filter((childAst) => childAst !== filterAst) as string[];
|
|
||||||
} else throw new Error("Unknown casl field");
|
|
||||||
// eslint-disable-next-line no-continue
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parentAst && Array.isArray(parentAst.value)) {
|
|
||||||
parentAst.value = parentAst.value.filter((childAst) => childAst !== filterAst) as string[];
|
|
||||||
} else {
|
|
||||||
missingOperatorCallback?.(filterAst.operator);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return dynamicQueryAst;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const convertCaslOperatorToKnexOperator = <T extends keyof Tables>(
|
|
||||||
caslKnexOperators: AbilityQuery,
|
|
||||||
fieldMapping: (arg: string) => TFieldMapper<T> | null
|
|
||||||
) => {
|
|
||||||
const value = [];
|
|
||||||
if (caslKnexOperators.$and) {
|
|
||||||
value.push({
|
|
||||||
operator: "not" as const,
|
|
||||||
value: caslKnexOperators.$and as TKnexDynamicOperator[]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (caslKnexOperators.$or) {
|
|
||||||
value.push({
|
|
||||||
operator: "or" as const,
|
|
||||||
value: caslKnexOperators.$or as TKnexDynamicOperator[]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return formatCaslOperatorFieldsWithTableNames({
|
|
||||||
dynamicQuery: {
|
|
||||||
operator: "and",
|
|
||||||
value
|
|
||||||
},
|
|
||||||
fieldMapping
|
|
||||||
});
|
|
||||||
};
|
|
||||||
@@ -81,3 +81,25 @@ export const chunkArray = <T>(array: T[], chunkSize: number): T[][] => {
|
|||||||
}
|
}
|
||||||
return chunks;
|
return chunks;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns all items from the first list that
|
||||||
|
* do not exist in the second list.
|
||||||
|
*/
|
||||||
|
export const diff = <T>(
|
||||||
|
root: readonly T[],
|
||||||
|
other: readonly T[],
|
||||||
|
identity: (item: T) => string | number | symbol = (t: T) => t as unknown as string | number | symbol
|
||||||
|
): T[] => {
|
||||||
|
if (!root?.length && !other?.length) return [];
|
||||||
|
if (root?.length === undefined) return [...other];
|
||||||
|
if (!other?.length) return [...root];
|
||||||
|
const bKeys = other.reduce(
|
||||||
|
(acc, item) => {
|
||||||
|
acc[identity(item)] = true;
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{} as Record<string | number | symbol, boolean>
|
||||||
|
);
|
||||||
|
return root.filter((a) => !bKeys[identity(a)]);
|
||||||
|
};
|
||||||
|
|||||||
@@ -2,32 +2,31 @@ import { Knex } from "knex";
|
|||||||
|
|
||||||
import { UnauthorizedError } from "../errors";
|
import { UnauthorizedError } from "../errors";
|
||||||
|
|
||||||
type TKnexDynamicPrimitiveOperator = {
|
type TKnexDynamicPrimitiveOperator<T extends object> = {
|
||||||
operator: "eq" | "ne" | "startsWith" | "endsWith";
|
operator: "eq" | "ne" | "startsWith" | "endsWith";
|
||||||
value: string;
|
value: string;
|
||||||
field: string;
|
field: Extract<keyof T, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
type TKnexDynamicInOperator = {
|
type TKnexDynamicInOperator<T extends object> = {
|
||||||
operator: "in";
|
operator: "in";
|
||||||
value: string[] | number[];
|
value: string[] | number[];
|
||||||
field: string;
|
field: Extract<keyof T, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
type TKnexNonGroupOperator = TKnexDynamicInOperator | TKnexDynamicPrimitiveOperator;
|
type TKnexNonGroupOperator<T extends object> = TKnexDynamicInOperator<T> | TKnexDynamicPrimitiveOperator<T>;
|
||||||
|
|
||||||
type TKnexGroupOperator = {
|
type TKnexGroupOperator<T extends object> = {
|
||||||
operator: "and" | "or" | "not";
|
operator: "and" | "or" | "not";
|
||||||
value: (TKnexNonGroupOperator | TKnexGroupOperator)[];
|
value: (TKnexNonGroupOperator<T> | TKnexGroupOperator<T>)[];
|
||||||
};
|
};
|
||||||
|
|
||||||
// akhilmhdh: This is still in pending state and not yet ready. If you want to use it ping me.
|
export type TKnexDynamicOperator<T extends object> = TKnexGroupOperator<T> | TKnexNonGroupOperator<T>;
|
||||||
// used when you need to write a complex query with the orm
|
|
||||||
// use it when you need complex or and and condition - most of the time not needed
|
|
||||||
// majorly used with casl permission to filter data based on permission
|
|
||||||
export type TKnexDynamicOperator = TKnexGroupOperator | TKnexNonGroupOperator;
|
|
||||||
|
|
||||||
export const buildDynamicKnexQuery = (dynamicQuery: TKnexDynamicOperator, rootQueryBuild: Knex.QueryBuilder) => {
|
export const buildDynamicKnexQuery = <T extends object>(
|
||||||
|
rootQueryBuild: Knex.QueryBuilder,
|
||||||
|
dynamicQuery: TKnexDynamicOperator<T>
|
||||||
|
) => {
|
||||||
const stack = [{ filterAst: dynamicQuery, queryBuilder: rootQueryBuild }];
|
const stack = [{ filterAst: dynamicQuery, queryBuilder: rootQueryBuild }];
|
||||||
|
|
||||||
while (stack.length) {
|
while (stack.length) {
|
||||||
@@ -50,34 +49,25 @@ export const buildDynamicKnexQuery = (dynamicQuery: TKnexDynamicOperator, rootQu
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "and": {
|
case "and": {
|
||||||
void queryBuilder.andWhere((subQueryBuilder) => {
|
filterAst.value.forEach((el) => {
|
||||||
filterAst.value.forEach((el) => {
|
void queryBuilder.andWhere((subQueryBuilder) => {
|
||||||
stack.push({
|
buildDynamicKnexQuery(subQueryBuilder, el);
|
||||||
queryBuilder: subQueryBuilder,
|
|
||||||
filterAst: el
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "or": {
|
case "or": {
|
||||||
void queryBuilder.orWhere((subQueryBuilder) => {
|
filterAst.value.forEach((el) => {
|
||||||
filterAst.value.forEach((el) => {
|
void queryBuilder.orWhere((subQueryBuilder) => {
|
||||||
stack.push({
|
buildDynamicKnexQuery(subQueryBuilder, el);
|
||||||
queryBuilder: subQueryBuilder,
|
|
||||||
filterAst: el
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "not": {
|
case "not": {
|
||||||
void queryBuilder.whereNot((subQueryBuilder) => {
|
filterAst.value.forEach((el) => {
|
||||||
filterAst.value.forEach((el) => {
|
void queryBuilder.whereNot((subQueryBuilder) => {
|
||||||
stack.push({
|
buildDynamicKnexQuery(subQueryBuilder, el);
|
||||||
queryBuilder: subQueryBuilder,
|
|
||||||
filterAst: el
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Knex } from "knex";
|
|||||||
import { Tables } from "knex/types/tables";
|
import { Tables } from "knex/types/tables";
|
||||||
|
|
||||||
import { DatabaseError } from "../errors";
|
import { DatabaseError } from "../errors";
|
||||||
|
import { buildDynamicKnexQuery, TKnexDynamicOperator } from "./dynamic";
|
||||||
|
|
||||||
export * from "./connection";
|
export * from "./connection";
|
||||||
export * from "./join";
|
export * from "./join";
|
||||||
@@ -20,9 +21,10 @@ export const withTransaction = <K extends object>(db: Knex, dal: K) => ({
|
|||||||
export type TFindFilter<R extends object = object> = Partial<R> & {
|
export type TFindFilter<R extends object = object> = Partial<R> & {
|
||||||
$in?: Partial<{ [k in keyof R]: R[k][] }>;
|
$in?: Partial<{ [k in keyof R]: R[k][] }>;
|
||||||
$search?: Partial<{ [k in keyof R]: R[k] }>;
|
$search?: Partial<{ [k in keyof R]: R[k] }>;
|
||||||
|
$complex?: TKnexDynamicOperator<R>;
|
||||||
};
|
};
|
||||||
export const buildFindFilter =
|
export const buildFindFilter =
|
||||||
<R extends object = object>({ $in, $search, ...filter }: TFindFilter<R>) =>
|
<R extends object = object>({ $in, $search, $complex, ...filter }: TFindFilter<R>) =>
|
||||||
(bd: Knex.QueryBuilder<R, R>) => {
|
(bd: Knex.QueryBuilder<R, R>) => {
|
||||||
void bd.where(filter);
|
void bd.where(filter);
|
||||||
if ($in) {
|
if ($in) {
|
||||||
@@ -39,6 +41,9 @@ export const buildFindFilter =
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if ($complex) {
|
||||||
|
return buildDynamicKnexQuery(bd, $complex);
|
||||||
|
}
|
||||||
return bd;
|
return bd;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
|
|||||||
void res.status(HttpStatusCodes.Forbidden).send({
|
void res.status(HttpStatusCodes.Forbidden).send({
|
||||||
statusCode: HttpStatusCodes.Forbidden,
|
statusCode: HttpStatusCodes.Forbidden,
|
||||||
error: "PermissionDenied",
|
error: "PermissionDenied",
|
||||||
message: `You are not allowed to ${error.action} on ${error.subjectType}`
|
message: `You are not allowed to ${error.action} on ${error.subjectType} - ${JSON.stringify(error.subject)}`
|
||||||
});
|
});
|
||||||
} else if (error instanceof ForbiddenRequestError) {
|
} else if (error instanceof ForbiddenRequestError) {
|
||||||
void res.status(HttpStatusCodes.Forbidden).send({
|
void res.status(HttpStatusCodes.Forbidden).send({
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { z } from "zod";
|
|||||||
|
|
||||||
import { registerCertificateEstRouter } from "@app/ee/routes/est/certificate-est-router";
|
import { registerCertificateEstRouter } from "@app/ee/routes/est/certificate-est-router";
|
||||||
import { registerV1EERoutes } from "@app/ee/routes/v1";
|
import { registerV1EERoutes } from "@app/ee/routes/v1";
|
||||||
|
import { registerV2EERoutes } from "@app/ee/routes/v2";
|
||||||
import { accessApprovalPolicyApproverDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-approver-dal";
|
import { accessApprovalPolicyApproverDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-approver-dal";
|
||||||
import { accessApprovalPolicyDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-dal";
|
import { accessApprovalPolicyDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-dal";
|
||||||
import { accessApprovalPolicyServiceFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-service";
|
import { accessApprovalPolicyServiceFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-service";
|
||||||
@@ -32,6 +33,7 @@ import { groupServiceFactory } from "@app/ee/services/group/group-service";
|
|||||||
import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
||||||
import { identityProjectAdditionalPrivilegeDALFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-dal";
|
import { identityProjectAdditionalPrivilegeDALFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-dal";
|
||||||
import { identityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
import { identityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
||||||
|
import { identityProjectAdditionalPrivilegeV2ServiceFactory } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-service";
|
||||||
import { ldapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";
|
import { ldapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dal";
|
||||||
import { ldapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
import { ldapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
||||||
import { ldapGroupMapDALFactory } from "@app/ee/services/ldap-config/ldap-group-map-dal";
|
import { ldapGroupMapDALFactory } from "@app/ee/services/ldap-config/ldap-group-map-dal";
|
||||||
@@ -1075,6 +1077,14 @@ export const registerRoutes = async (
|
|||||||
permissionService,
|
permissionService,
|
||||||
identityProjectDAL
|
identityProjectDAL
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const identityProjectAdditionalPrivilegeV2Service = identityProjectAdditionalPrivilegeV2ServiceFactory({
|
||||||
|
projectDAL,
|
||||||
|
identityProjectAdditionalPrivilegeDAL,
|
||||||
|
permissionService,
|
||||||
|
identityProjectDAL
|
||||||
|
});
|
||||||
|
|
||||||
const identityTokenAuthService = identityTokenAuthServiceFactory({
|
const identityTokenAuthService = identityTokenAuthServiceFactory({
|
||||||
identityTokenAuthDAL,
|
identityTokenAuthDAL,
|
||||||
identityDAL,
|
identityDAL,
|
||||||
@@ -1324,6 +1334,7 @@ export const registerRoutes = async (
|
|||||||
telemetry: telemetryService,
|
telemetry: telemetryService,
|
||||||
projectUserAdditionalPrivilege: projectUserAdditionalPrivilegeService,
|
projectUserAdditionalPrivilege: projectUserAdditionalPrivilegeService,
|
||||||
identityProjectAdditionalPrivilege: identityProjectAdditionalPrivilegeService,
|
identityProjectAdditionalPrivilege: identityProjectAdditionalPrivilegeService,
|
||||||
|
identityProjectAdditionalPrivilegeV2: identityProjectAdditionalPrivilegeV2Service,
|
||||||
secretSharing: secretSharingService,
|
secretSharing: secretSharingService,
|
||||||
userEngagement: userEngagementService,
|
userEngagement: userEngagementService,
|
||||||
externalKms: externalKmsService,
|
externalKms: externalKmsService,
|
||||||
@@ -1422,7 +1433,13 @@ export const registerRoutes = async (
|
|||||||
},
|
},
|
||||||
{ prefix: "/api/v1" }
|
{ prefix: "/api/v1" }
|
||||||
);
|
);
|
||||||
await server.register(registerV2Routes, { prefix: "/api/v2" });
|
await server.register(
|
||||||
|
async (v2Server) => {
|
||||||
|
await v2Server.register(registerV2EERoutes);
|
||||||
|
await v2Server.register(registerV2Routes);
|
||||||
|
},
|
||||||
|
{ prefix: "/api/v2" }
|
||||||
|
);
|
||||||
await server.register(registerV3Routes, { prefix: "/api/v3" });
|
await server.register(registerV3Routes, { prefix: "/api/v3" });
|
||||||
|
|
||||||
server.addHook("onClose", async () => {
|
server.addHook("onClose", async () => {
|
||||||
|
|||||||
@@ -9,9 +9,10 @@ import {
|
|||||||
SecretApprovalPoliciesSchema,
|
SecretApprovalPoliciesSchema,
|
||||||
UsersSchema
|
UsersSchema
|
||||||
} from "@app/db/schemas";
|
} from "@app/db/schemas";
|
||||||
import { UnpackedPermissionSchema } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||||
|
|
||||||
|
import { UnpackedPermissionSchema } from "./santizedSchemas/permission";
|
||||||
|
|
||||||
// sometimes the return data must be santizied to avoid leaking important values
|
// sometimes the return data must be santizied to avoid leaking important values
|
||||||
// always prefer pick over omit in zod
|
// always prefer pick over omit in zod
|
||||||
export const integrationAuthPubSchema = IntegrationAuthsSchema.pick({
|
export const integrationAuthPubSchema = IntegrationAuthsSchema.pick({
|
||||||
@@ -149,13 +150,44 @@ export const ProjectSpecificPrivilegePermissionSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const SanitizedIdentityPrivilegeSchema = IdentityProjectAdditionalPrivilegeSchema.extend({
|
export const SanitizedIdentityPrivilegeSchema = IdentityProjectAdditionalPrivilegeSchema.extend({
|
||||||
permissions: UnpackedPermissionSchema.array()
|
permissions: UnpackedPermissionSchema.array().transform((permissions) =>
|
||||||
|
permissions.filter(
|
||||||
|
(caslRule) =>
|
||||||
|
![
|
||||||
|
ProjectPermissionSub.DynamicSecrets,
|
||||||
|
ProjectPermissionSub.SecretImports,
|
||||||
|
ProjectPermissionSub.SecretFolders
|
||||||
|
].includes((caslRule?.subject as ProjectPermissionSub) || "")
|
||||||
|
)
|
||||||
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
export const SanitizedRoleSchema = ProjectRolesSchema.extend({
|
export const SanitizedRoleSchema = ProjectRolesSchema.extend({
|
||||||
permissions: UnpackedPermissionSchema.array()
|
permissions: UnpackedPermissionSchema.array()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const SanitizedRoleSchemaV1 = ProjectRolesSchema.extend({
|
||||||
|
permissions: UnpackedPermissionSchema.array().transform((caslPermission) =>
|
||||||
|
// first map and remove other actions of folder permission
|
||||||
|
caslPermission
|
||||||
|
.map((caslRule) =>
|
||||||
|
caslRule.subject === ProjectPermissionSub.SecretFolders
|
||||||
|
? {
|
||||||
|
...caslRule,
|
||||||
|
action: caslRule.action.filter((caslAction) => caslAction === ProjectPermissionActions.Read)
|
||||||
|
}
|
||||||
|
: caslRule
|
||||||
|
)
|
||||||
|
// now filter out dynamic secret, secret import permission
|
||||||
|
.filter(
|
||||||
|
(caslRule) =>
|
||||||
|
![ProjectPermissionSub.DynamicSecrets, ProjectPermissionSub.SecretImports].includes(
|
||||||
|
(caslRule?.subject as ProjectPermissionSub) || ""
|
||||||
|
) && caslRule.action.length > 0
|
||||||
|
)
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
export const SanitizedDynamicSecretSchema = DynamicSecretsSchema.omit({
|
export const SanitizedDynamicSecretSchema = DynamicSecretsSchema.omit({
|
||||||
inputIV: true,
|
inputIV: true,
|
||||||
inputTag: true,
|
inputTag: true,
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { IdentityProjectAdditionalPrivilegeSchema } from "@app/db/schemas";
|
||||||
|
|
||||||
|
import { UnpackedPermissionSchema } from "./permission";
|
||||||
|
|
||||||
|
export const SanitizedIdentityPrivilegeSchema = IdentityProjectAdditionalPrivilegeSchema.extend({
|
||||||
|
permissions: UnpackedPermissionSchema.array()
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { MongoAbility, RawRuleOf } from "@casl/ability";
|
||||||
|
import { PackRule, unpackRules } from "@casl/ability/extra";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export const UnpackedPermissionSchema = z.object({
|
||||||
|
subject: z
|
||||||
|
.union([z.string().min(1), z.string().array()])
|
||||||
|
.transform((el) => (typeof el !== "string" ? el[0] : el))
|
||||||
|
.optional(),
|
||||||
|
action: z.union([z.string().min(1), z.string().array()]).transform((el) => (typeof el === "string" ? [el] : el)),
|
||||||
|
conditions: z.unknown().optional(),
|
||||||
|
inverted: z.boolean().optional()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const unpackPermissions = (permissions: unknown) =>
|
||||||
|
UnpackedPermissionSchema.array().parse(unpackRules((permissions || []) as PackRule<RawRuleOf<MongoAbility>>[]));
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { ProjectUserAdditionalPrivilegeSchema } from "@app/db/schemas";
|
||||||
|
|
||||||
|
import { UnpackedPermissionSchema } from "./permission";
|
||||||
|
|
||||||
|
export const SanitizedUserProjectAdditionalPrivilegeSchema = ProjectUserAdditionalPrivilegeSchema.extend({
|
||||||
|
permissions: UnpackedPermissionSchema.array()
|
||||||
|
});
|
||||||
@@ -3,7 +3,10 @@ import { z } from "zod";
|
|||||||
|
|
||||||
import { SecretFoldersSchema, SecretImportsSchema, SecretTagsSchema } from "@app/db/schemas";
|
import { SecretFoldersSchema, SecretImportsSchema, SecretTagsSchema } from "@app/db/schemas";
|
||||||
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
|
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import {
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
|
ProjectPermissionSub
|
||||||
|
} from "@app/ee/services/permission/project-permission";
|
||||||
import { DASHBOARD } from "@app/lib/api-docs";
|
import { DASHBOARD } from "@app/lib/api-docs";
|
||||||
import { BadRequestError } from "@app/lib/errors";
|
import { BadRequestError } from "@app/lib/errors";
|
||||||
import { removeTrailingSlash } from "@app/lib/fn";
|
import { removeTrailingSlash } from "@app/lib/fn";
|
||||||
@@ -192,15 +195,15 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
req.permission.orgId
|
req.permission.orgId
|
||||||
);
|
);
|
||||||
|
|
||||||
const permissiveEnvs = // filter envs user has access to
|
const allowedDynamicSecretEnvironments = // filter envs user has access to
|
||||||
environments.filter((environment) =>
|
environments.filter((environment) =>
|
||||||
permission.can(
|
permission.can(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionDynamicSecretActions.Lease,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.DynamicSecrets, { environment, secretPath })
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (includeDynamicSecrets && permissiveEnvs.length) {
|
if (includeDynamicSecrets && allowedDynamicSecretEnvironments.length) {
|
||||||
// this is the unique count, ie duplicate secrets across envs only count as 1
|
// this is the unique count, ie duplicate secrets across envs only count as 1
|
||||||
totalDynamicSecretCount = await server.services.dynamicSecret.getCountMultiEnv({
|
totalDynamicSecretCount = await server.services.dynamicSecret.getCountMultiEnv({
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
@@ -209,7 +212,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
projectId,
|
projectId,
|
||||||
search,
|
search,
|
||||||
environmentSlugs: permissiveEnvs,
|
environmentSlugs: allowedDynamicSecretEnvironments,
|
||||||
path: secretPath,
|
path: secretPath,
|
||||||
isInternal: true
|
isInternal: true
|
||||||
});
|
});
|
||||||
@@ -224,7 +227,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
search,
|
search,
|
||||||
orderBy,
|
orderBy,
|
||||||
orderDirection,
|
orderDirection,
|
||||||
environmentSlugs: permissiveEnvs,
|
environmentSlugs: allowedDynamicSecretEnvironments,
|
||||||
path: secretPath,
|
path: secretPath,
|
||||||
limit: remainingLimit,
|
limit: remainingLimit,
|
||||||
offset: adjustedOffset,
|
offset: adjustedOffset,
|
||||||
@@ -241,13 +244,13 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (includeSecrets && permissiveEnvs.length) {
|
if (includeSecrets) {
|
||||||
// this is the unique count, ie duplicate secrets across envs only count as 1
|
// this is the unique count, ie duplicate secrets across envs only count as 1
|
||||||
totalSecretCount = await server.services.secret.getSecretsCountMultiEnv({
|
totalSecretCount = await server.services.secret.getSecretsCountMultiEnv({
|
||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
environments: permissiveEnvs,
|
environments,
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
projectId,
|
projectId,
|
||||||
path: secretPath,
|
path: secretPath,
|
||||||
@@ -260,7 +263,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
actorId: req.permission.id,
|
actorId: req.permission.id,
|
||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
environments: permissiveEnvs,
|
environments,
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
projectId,
|
projectId,
|
||||||
path: secretPath,
|
path: secretPath,
|
||||||
@@ -272,7 +275,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
|||||||
isInternal: true
|
isInternal: true
|
||||||
});
|
});
|
||||||
|
|
||||||
for await (const environment of permissiveEnvs) {
|
for await (const environment of environments) {
|
||||||
const secretCountFromEnv = secrets.filter((secret) => secret.environment === environment).length;
|
const secretCountFromEnv = secrets.filter((secret) => secret.environment === environment).length;
|
||||||
|
|
||||||
if (secretCountFromEnv) {
|
if (secretCountFromEnv) {
|
||||||
|
|||||||
@@ -39,7 +39,8 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
|
|||||||
email: true,
|
email: true,
|
||||||
firstName: true,
|
firstName: true,
|
||||||
lastName: true,
|
lastName: true,
|
||||||
id: true
|
id: true,
|
||||||
|
username: true
|
||||||
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
||||||
roles: z.array(
|
roles: z.array(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -56,7 +57,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.omit({ createdAt: true, updatedAt: true })
|
.omit({ updatedAt: true })
|
||||||
.array()
|
.array()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -74,6 +75,65 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:workspaceId/memberships/:membershipId",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Return project user membership",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
workspaceId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.workspaceId),
|
||||||
|
membershipId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.membershipId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
membership: ProjectMembershipsSchema.extend({
|
||||||
|
user: UsersSchema.pick({
|
||||||
|
email: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
id: true,
|
||||||
|
username: true
|
||||||
|
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
||||||
|
roles: z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
role: z.string(),
|
||||||
|
customRoleId: z.string().optional().nullable(),
|
||||||
|
customRoleName: z.string().optional().nullable(),
|
||||||
|
customRoleSlug: z.string().optional().nullable(),
|
||||||
|
isTemporary: z.boolean(),
|
||||||
|
temporaryMode: z.string().optional().nullable(),
|
||||||
|
temporaryRange: z.string().nullable().optional(),
|
||||||
|
temporaryAccessStartTime: z.date().nullable().optional(),
|
||||||
|
temporaryAccessEndTime: z.date().nullable().optional()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}).omit({ updatedAt: true })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const membership = await server.services.projectMembership.getProjectMembershipById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
projectId: req.params.workspaceId,
|
||||||
|
id: req.params.membershipId
|
||||||
|
});
|
||||||
|
return { membership };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/:workspaceId/memberships/details",
|
url: "/:workspaceId/memberships/details",
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import { TProjectEnvServiceFactory } from "../project-env/project-env-service";
|
|||||||
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
|
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
|
||||||
import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
|
import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
|
||||||
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
|
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
|
||||||
import { fnSecretBulkInsert, getAllNestedSecretReferences } from "../secret-v2-bridge/secret-v2-bridge-fns";
|
import { fnSecretBulkInsert, getAllSecretReferences } from "../secret-v2-bridge/secret-v2-bridge-fns";
|
||||||
import type { TSecretV2BridgeServiceFactory } from "../secret-v2-bridge/secret-v2-bridge-service";
|
import type { TSecretV2BridgeServiceFactory } from "../secret-v2-bridge/secret-v2-bridge-service";
|
||||||
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
|
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
|
||||||
import { TSecretVersionV2TagDALFactory } from "../secret-v2-bridge/secret-version-tag-dal";
|
import { TSecretVersionV2TagDALFactory } from "../secret-v2-bridge/secret-version-tag-dal";
|
||||||
@@ -242,7 +242,7 @@ export const importDataIntoInfisicalFn = async ({
|
|||||||
}
|
}
|
||||||
await fnSecretBulkInsert({
|
await fnSecretBulkInsert({
|
||||||
inputSecrets: secretBatch.map((el) => {
|
inputSecrets: secretBatch.map((el) => {
|
||||||
const references = getAllNestedSecretReferences(el.secretValue);
|
const references = getAllSecretReferences(el.secretValue).nestedReferences;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
version: 1,
|
version: 1,
|
||||||
|
|||||||
@@ -158,6 +158,7 @@ export const groupProjectDALFactory = (db: TDbClient) => {
|
|||||||
)
|
)
|
||||||
.select(
|
.select(
|
||||||
db.ref("id").withSchema(TableName.UserGroupMembership),
|
db.ref("id").withSchema(TableName.UserGroupMembership),
|
||||||
|
db.ref("createdAt").withSchema(TableName.UserGroupMembership),
|
||||||
db.ref("isGhost").withSchema(TableName.Users),
|
db.ref("isGhost").withSchema(TableName.Users),
|
||||||
db.ref("username").withSchema(TableName.Users),
|
db.ref("username").withSchema(TableName.Users),
|
||||||
db.ref("email").withSchema(TableName.Users),
|
db.ref("email").withSchema(TableName.Users),
|
||||||
@@ -181,7 +182,18 @@ export const groupProjectDALFactory = (db: TDbClient) => {
|
|||||||
|
|
||||||
const members = sqlNestRelationships({
|
const members = sqlNestRelationships({
|
||||||
data: docs,
|
data: docs,
|
||||||
parentMapper: ({ email, firstName, username, lastName, publicKey, isGhost, id, userId, projectName }) => ({
|
parentMapper: ({
|
||||||
|
email,
|
||||||
|
firstName,
|
||||||
|
username,
|
||||||
|
lastName,
|
||||||
|
publicKey,
|
||||||
|
isGhost,
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
projectName,
|
||||||
|
createdAt
|
||||||
|
}) => ({
|
||||||
isGroupMember: true,
|
isGroupMember: true,
|
||||||
id,
|
id,
|
||||||
userId,
|
userId,
|
||||||
@@ -190,7 +202,8 @@ export const groupProjectDALFactory = (db: TDbClient) => {
|
|||||||
id: projectId,
|
id: projectId,
|
||||||
name: projectName
|
name: projectName
|
||||||
},
|
},
|
||||||
user: { email, username, firstName, lastName, id: userId, publicKey, isGhost }
|
user: { email, username, firstName, lastName, id: userId, publicKey, isGhost },
|
||||||
|
createdAt
|
||||||
}),
|
}),
|
||||||
key: "id",
|
key: "id",
|
||||||
childrenMapper: [
|
childrenMapper: [
|
||||||
|
|||||||
@@ -67,7 +67,8 @@ const getIntegrationSecretsV2 = async (
|
|||||||
folderDAL,
|
folderDAL,
|
||||||
secretDAL: secretV2BridgeDAL,
|
secretDAL: secretV2BridgeDAL,
|
||||||
secretImportDAL,
|
secretImportDAL,
|
||||||
allowedImports: secretImports
|
secretImports,
|
||||||
|
hasSecretAccess: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
|
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
|
||||||
|
|||||||
@@ -90,7 +90,10 @@ export const integrationServiceFactory = ({
|
|||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: sourceEnvironment, secretPath })
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: sourceEnvironment,
|
||||||
|
secretPath
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(integrationAuth.projectId, sourceEnvironment, secretPath);
|
const folder = await folderDAL.findBySecretPath(integrationAuth.projectId, sourceEnvironment, secretPath);
|
||||||
@@ -167,7 +170,10 @@ export const integrationServiceFactory = ({
|
|||||||
if (environment || secretPath) {
|
if (environment || secretPath) {
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: newEnvironment, secretPath: newSecretPath })
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: newEnvironment,
|
||||||
|
secretPath: newSecretPath
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
const projectMemberOrm = ormify(db, TableName.ProjectMembership);
|
const projectMemberOrm = ormify(db, TableName.ProjectMembership);
|
||||||
|
|
||||||
// special query
|
// special query
|
||||||
const findAllProjectMembers = async (projectId: string, filter: { usernames?: string[]; username?: string } = {}) => {
|
const findAllProjectMembers = async (
|
||||||
|
projectId: string,
|
||||||
|
filter: { usernames?: string[]; username?: string; id?: string } = {}
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
const docs = await db
|
const docs = await db
|
||||||
.replicaNode()(TableName.ProjectMembership)
|
.replicaNode()(TableName.ProjectMembership)
|
||||||
@@ -25,6 +28,9 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
if (filter.username) {
|
if (filter.username) {
|
||||||
void qb.where("username", filter.username);
|
void qb.where("username", filter.username);
|
||||||
}
|
}
|
||||||
|
if (filter.id) {
|
||||||
|
void qb.where(`${TableName.ProjectMembership}.id`, filter.id);
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.join<TUserEncryptionKeys>(
|
.join<TUserEncryptionKeys>(
|
||||||
TableName.UserEncryptionKey,
|
TableName.UserEncryptionKey,
|
||||||
@@ -43,6 +49,7 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
)
|
)
|
||||||
.select(
|
.select(
|
||||||
db.ref("id").withSchema(TableName.ProjectMembership),
|
db.ref("id").withSchema(TableName.ProjectMembership),
|
||||||
|
db.ref("createdAt").withSchema(TableName.ProjectMembership),
|
||||||
db.ref("isGhost").withSchema(TableName.Users),
|
db.ref("isGhost").withSchema(TableName.Users),
|
||||||
db.ref("username").withSchema(TableName.Users),
|
db.ref("username").withSchema(TableName.Users),
|
||||||
db.ref("email").withSchema(TableName.Users),
|
db.ref("email").withSchema(TableName.Users),
|
||||||
@@ -66,7 +73,18 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
|
|
||||||
const members = sqlNestRelationships({
|
const members = sqlNestRelationships({
|
||||||
data: docs,
|
data: docs,
|
||||||
parentMapper: ({ email, firstName, username, lastName, publicKey, isGhost, id, userId, projectName }) => ({
|
parentMapper: ({
|
||||||
|
email,
|
||||||
|
firstName,
|
||||||
|
username,
|
||||||
|
lastName,
|
||||||
|
publicKey,
|
||||||
|
isGhost,
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
projectName,
|
||||||
|
createdAt
|
||||||
|
}) => ({
|
||||||
id,
|
id,
|
||||||
userId,
|
userId,
|
||||||
projectId,
|
projectId,
|
||||||
@@ -74,7 +92,8 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
project: {
|
project: {
|
||||||
id: projectId,
|
id: projectId,
|
||||||
name: projectName
|
name: projectName
|
||||||
}
|
},
|
||||||
|
createdAt
|
||||||
}),
|
}),
|
||||||
key: "id",
|
key: "id",
|
||||||
childrenMapper: [
|
childrenMapper: [
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-service
|
|||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||||
import { TProjectUserAdditionalPrivilegeDALFactory } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-dal";
|
import { TProjectUserAdditionalPrivilegeDALFactory } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-dal";
|
||||||
|
import { isAtLeastAsPrivileged } from "@app/lib/casl";
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
import { groupBy } from "@app/lib/fn";
|
import { groupBy } from "@app/lib/fn";
|
||||||
@@ -27,6 +28,7 @@ import {
|
|||||||
TAddUsersToWorkspaceDTO,
|
TAddUsersToWorkspaceDTO,
|
||||||
TDeleteProjectMembershipOldDTO,
|
TDeleteProjectMembershipOldDTO,
|
||||||
TDeleteProjectMembershipsDTO,
|
TDeleteProjectMembershipsDTO,
|
||||||
|
TGetProjectMembershipByIdDTO,
|
||||||
TGetProjectMembershipByUsernameDTO,
|
TGetProjectMembershipByUsernameDTO,
|
||||||
TGetProjectMembershipDTO,
|
TGetProjectMembershipDTO,
|
||||||
TLeaveProjectDTO,
|
TLeaveProjectDTO,
|
||||||
@@ -35,7 +37,7 @@ import {
|
|||||||
import { TProjectUserMembershipRoleDALFactory } from "./project-user-membership-role-dal";
|
import { TProjectUserMembershipRoleDALFactory } from "./project-user-membership-role-dal";
|
||||||
|
|
||||||
type TProjectMembershipServiceFactoryDep = {
|
type TProjectMembershipServiceFactoryDep = {
|
||||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getProjectPermissionByRole">;
|
||||||
smtpService: TSmtpService;
|
smtpService: TSmtpService;
|
||||||
projectBotDAL: TProjectBotDALFactory;
|
projectBotDAL: TProjectBotDALFactory;
|
||||||
projectMembershipDAL: TProjectMembershipDALFactory;
|
projectMembershipDAL: TProjectMembershipDALFactory;
|
||||||
@@ -133,6 +135,28 @@ export const projectMembershipServiceFactory = ({
|
|||||||
return membership;
|
return membership;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getProjectMembershipById = async ({
|
||||||
|
actorId,
|
||||||
|
actor,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
projectId,
|
||||||
|
id
|
||||||
|
}: TGetProjectMembershipByIdDTO) => {
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Member);
|
||||||
|
|
||||||
|
const [membership] = await projectMembershipDAL.findAllProjectMembers(projectId, { id });
|
||||||
|
if (!membership) throw new NotFoundError({ message: `Project membership not found for user ${id}` });
|
||||||
|
return membership;
|
||||||
|
};
|
||||||
|
|
||||||
const addUsersToProject = async ({
|
const addUsersToProject = async ({
|
||||||
projectId,
|
projectId,
|
||||||
actorId,
|
actorId,
|
||||||
@@ -239,6 +263,21 @@ export const projectMembershipServiceFactory = ({
|
|||||||
throw new ForbiddenRequestError({ message: "Forbidden member update" });
|
throw new ForbiddenRequestError({ message: "Forbidden member update" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for await (const { role: requestedRoleChange } of roles) {
|
||||||
|
const { permission: rolePermission } = await permissionService.getProjectPermissionByRole(
|
||||||
|
requestedRoleChange,
|
||||||
|
projectId
|
||||||
|
);
|
||||||
|
|
||||||
|
const hasRequiredPriviledges = isAtLeastAsPrivileged(permission, rolePermission);
|
||||||
|
|
||||||
|
if (!hasRequiredPriviledges) {
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: `Failed to change to a more privileged role ${requestedRoleChange}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// validate custom roles input
|
// validate custom roles input
|
||||||
const customInputRoles = roles.filter(
|
const customInputRoles = roles.filter(
|
||||||
({ role }) => !Object.values(ProjectMembershipRole).includes(role as ProjectMembershipRole)
|
({ role }) => !Object.values(ProjectMembershipRole).includes(role as ProjectMembershipRole)
|
||||||
@@ -487,6 +526,7 @@ export const projectMembershipServiceFactory = ({
|
|||||||
deleteProjectMemberships,
|
deleteProjectMemberships,
|
||||||
deleteProjectMembership, // TODO: Remove this
|
deleteProjectMembership, // TODO: Remove this
|
||||||
addUsersToProject,
|
addUsersToProject,
|
||||||
leaveProject
|
leaveProject,
|
||||||
|
getProjectMembershipById
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ export type TGetProjectMembershipByUsernameDTO = {
|
|||||||
username: string;
|
username: string;
|
||||||
} & TProjectPermission;
|
} & TProjectPermission;
|
||||||
|
|
||||||
|
export type TGetProjectMembershipByIdDTO = {
|
||||||
|
id: string;
|
||||||
|
} & TProjectPermission;
|
||||||
|
|
||||||
export type TUpdateProjectMembershipDTO = {
|
export type TUpdateProjectMembershipDTO = {
|
||||||
membershipId: string;
|
membershipId: string;
|
||||||
roles: (
|
roles: (
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
|
import { ForbiddenError, MongoAbility, RawRuleOf } from "@casl/ability";
|
||||||
import { PackRule, packRules, unpackRules } from "@casl/ability/extra";
|
import { PackRule, packRules, unpackRules } from "@casl/ability/extra";
|
||||||
|
|
||||||
import { ProjectMembershipRole } from "@app/db/schemas";
|
import { ProjectMembershipRole, TableName } from "@app/db/schemas";
|
||||||
import { UnpackedPermissionSchema } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
|
||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
@@ -10,6 +9,7 @@ import {
|
|||||||
ProjectPermissionSub
|
ProjectPermissionSub
|
||||||
} from "@app/ee/services/permission/project-permission";
|
} from "@app/ee/services/permission/project-permission";
|
||||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
|
import { UnpackedPermissionSchema } from "@app/server/routes/santizedSchemas/permission";
|
||||||
|
|
||||||
import { ActorAuthMethod } from "../auth/auth-type";
|
import { ActorAuthMethod } from "../auth/auth-type";
|
||||||
import { TIdentityProjectMembershipRoleDALFactory } from "../identity-project/identity-project-membership-role-dal";
|
import { TIdentityProjectMembershipRoleDALFactory } from "../identity-project/identity-project-membership-role-dal";
|
||||||
@@ -17,7 +17,14 @@ import { TProjectDALFactory } from "../project/project-dal";
|
|||||||
import { TProjectUserMembershipRoleDALFactory } from "../project-membership/project-user-membership-role-dal";
|
import { TProjectUserMembershipRoleDALFactory } from "../project-membership/project-user-membership-role-dal";
|
||||||
import { TProjectRoleDALFactory } from "./project-role-dal";
|
import { TProjectRoleDALFactory } from "./project-role-dal";
|
||||||
import { getPredefinedRoles } from "./project-role-fns";
|
import { getPredefinedRoles } from "./project-role-fns";
|
||||||
import { TCreateRoleDTO, TDeleteRoleDTO, TGetRoleBySlugDTO, TListRolesDTO, TUpdateRoleDTO } from "./project-role-types";
|
import {
|
||||||
|
ProjectRoleServiceIdentifierType,
|
||||||
|
TCreateRoleDTO,
|
||||||
|
TDeleteRoleDTO,
|
||||||
|
TGetRoleDetailsDTO,
|
||||||
|
TListRolesDTO,
|
||||||
|
TUpdateRoleDTO
|
||||||
|
} from "./project-role-types";
|
||||||
|
|
||||||
type TProjectRoleServiceFactoryDep = {
|
type TProjectRoleServiceFactoryDep = {
|
||||||
projectRoleDAL: TProjectRoleDALFactory;
|
projectRoleDAL: TProjectRoleDALFactory;
|
||||||
@@ -41,10 +48,15 @@ export const projectRoleServiceFactory = ({
|
|||||||
projectUserMembershipRoleDAL,
|
projectUserMembershipRoleDAL,
|
||||||
projectDAL
|
projectDAL
|
||||||
}: TProjectRoleServiceFactoryDep) => {
|
}: TProjectRoleServiceFactoryDep) => {
|
||||||
const createRole = async ({ projectSlug, data, actor, actorId, actorAuthMethod, actorOrgId }: TCreateRoleDTO) => {
|
const createRole = async ({ data, actor, actorId, actorAuthMethod, actorOrgId, filter }: TCreateRoleDTO) => {
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
let projectId = "";
|
||||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
if (filter.type === ProjectRoleServiceIdentifierType.SLUG) {
|
||||||
const projectId = project.id;
|
const project = await projectDAL.findProjectBySlug(filter.projectSlug, actorOrgId);
|
||||||
|
if (!project) throw new NotFoundError({ message: "Project not found" });
|
||||||
|
projectId = project.id;
|
||||||
|
} else {
|
||||||
|
projectId = filter.projectId;
|
||||||
|
}
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
@@ -69,14 +81,19 @@ export const projectRoleServiceFactory = ({
|
|||||||
const getRoleBySlug = async ({
|
const getRoleBySlug = async ({
|
||||||
actor,
|
actor,
|
||||||
actorId,
|
actorId,
|
||||||
projectSlug,
|
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId,
|
actorOrgId,
|
||||||
roleSlug
|
roleSlug,
|
||||||
}: TGetRoleBySlugDTO) => {
|
filter
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
}: TGetRoleDetailsDTO) => {
|
||||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
let projectId = "";
|
||||||
const projectId = project.id;
|
if (filter.type === ProjectRoleServiceIdentifierType.SLUG) {
|
||||||
|
const project = await projectDAL.findProjectBySlug(filter.projectSlug, actorOrgId);
|
||||||
|
if (!project) throw new NotFoundError({ message: "Project not found" });
|
||||||
|
projectId = project.id;
|
||||||
|
} else {
|
||||||
|
projectId = filter.projectId;
|
||||||
|
}
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
@@ -96,58 +113,41 @@ export const projectRoleServiceFactory = ({
|
|||||||
return { ...customRole, permissions: unpackPermissions(customRole.permissions) };
|
return { ...customRole, permissions: unpackPermissions(customRole.permissions) };
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateRole = async ({
|
const updateRole = async ({ roleId, actorOrgId, actorAuthMethod, actorId, actor, data }: TUpdateRoleDTO) => {
|
||||||
roleId,
|
const projectRole = await projectRoleDAL.findById(roleId);
|
||||||
projectSlug,
|
if (!projectRole) throw new NotFoundError({ message: "Project role not found", name: "Delete role" });
|
||||||
actorOrgId,
|
|
||||||
actorAuthMethod,
|
|
||||||
actorId,
|
|
||||||
actor,
|
|
||||||
data
|
|
||||||
}: TUpdateRoleDTO) => {
|
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
|
||||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
|
||||||
const projectId = project.id;
|
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
actorId,
|
actorId,
|
||||||
projectId,
|
projectRole.projectId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Role);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Role);
|
||||||
|
|
||||||
if (data?.slug) {
|
if (data?.slug) {
|
||||||
const existingRole = await projectRoleDAL.findOne({ slug: data.slug, projectId });
|
const existingRole = await projectRoleDAL.findOne({ slug: data.slug, projectId: projectRole.projectId });
|
||||||
if (existingRole && existingRole.id !== roleId)
|
if (existingRole && existingRole.id !== roleId)
|
||||||
throw new BadRequestError({ name: "Update Role", message: "Project role with the same slug already exists" });
|
throw new BadRequestError({ name: "Update Role", message: "Project role with the same slug already exists" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const [updatedRole] = await projectRoleDAL.update(
|
const updatedRole = await projectRoleDAL.updateById(projectRole.id, {
|
||||||
{ id: roleId, projectId },
|
...data,
|
||||||
{
|
permissions: data.permissions ? data.permissions : undefined
|
||||||
...data,
|
});
|
||||||
permissions: data.permissions ? data.permissions : undefined
|
if (!updatedRole) throw new NotFoundError({ message: "Project role not found", name: "Update role" });
|
||||||
}
|
|
||||||
);
|
|
||||||
if (!updatedRole) {
|
|
||||||
throw new NotFoundError({
|
|
||||||
message: `Project role with ID '${roleId}' in project with ID '${projectId}' not found`
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return { ...updatedRole, permissions: unpackPermissions(updatedRole.permissions) };
|
return { ...updatedRole, permissions: unpackPermissions(updatedRole.permissions) };
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteRole = async ({ actor, actorId, actorAuthMethod, actorOrgId, projectSlug, roleId }: TDeleteRoleDTO) => {
|
const deleteRole = async ({ actor, actorId, actorAuthMethod, actorOrgId, roleId }: TDeleteRoleDTO) => {
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
const projectRole = await projectRoleDAL.findById(roleId);
|
||||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
if (!projectRole) throw new NotFoundError({ message: "Project role not found", name: "Delete role" });
|
||||||
const projectId = project.id;
|
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
actorId,
|
actorId,
|
||||||
projectId,
|
projectRole.projectId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
@@ -169,21 +169,21 @@ export const projectRoleServiceFactory = ({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const [deletedRole] = await projectRoleDAL.delete({ id: roleId, projectId });
|
const deletedRole = await projectRoleDAL.deleteById(roleId);
|
||||||
if (!deletedRole) {
|
if (!deletedRole) throw new NotFoundError({ message: "Project role not found", name: "Delete role" });
|
||||||
throw new NotFoundError({
|
|
||||||
message: `Project role with ID '${roleId}' in project with ID '${projectId}' not found`,
|
|
||||||
name: "DeleteRole"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ...deletedRole, permissions: unpackPermissions(deletedRole.permissions) };
|
return { ...deletedRole, permissions: unpackPermissions(deletedRole.permissions) };
|
||||||
};
|
};
|
||||||
|
|
||||||
const listRoles = async ({ projectSlug, actorOrgId, actorAuthMethod, actorId, actor }: TListRolesDTO) => {
|
const listRoles = async ({ actorOrgId, actorAuthMethod, actorId, actor, filter }: TListRolesDTO) => {
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
let projectId = "";
|
||||||
if (!project) throw new BadRequestError({ message: "Project not found" });
|
if (filter.type === ProjectRoleServiceIdentifierType.SLUG) {
|
||||||
const projectId = project.id;
|
const project = await projectDAL.findProjectBySlug(filter.projectSlug, actorOrgId);
|
||||||
|
if (!project) throw new BadRequestError({ message: "Project not found" });
|
||||||
|
projectId = project.id;
|
||||||
|
} else {
|
||||||
|
projectId = filter.projectId;
|
||||||
|
}
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
actor,
|
actor,
|
||||||
@@ -193,7 +193,10 @@ export const projectRoleServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Role);
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Role);
|
||||||
const customRoles = await projectRoleDAL.find({ projectId });
|
const customRoles = await projectRoleDAL.find(
|
||||||
|
{ projectId },
|
||||||
|
{ sort: [[`${TableName.ProjectRoles}.slug` as "slug", "asc"]] }
|
||||||
|
);
|
||||||
const roles = [...getPredefinedRoles(projectId), ...(customRoles || [])];
|
const roles = [...getPredefinedRoles(projectId), ...(customRoles || [])];
|
||||||
|
|
||||||
return roles;
|
return roles;
|
||||||
|
|||||||
@@ -1,27 +1,36 @@
|
|||||||
import { TOrgRolesUpdate, TProjectRolesInsert } from "@app/db/schemas";
|
import { TOrgRolesUpdate, TProjectRolesInsert } from "@app/db/schemas";
|
||||||
import { TProjectPermission } from "@app/lib/types";
|
import { TProjectPermission } from "@app/lib/types";
|
||||||
|
|
||||||
|
export enum ProjectRoleServiceIdentifierType {
|
||||||
|
ID = "id",
|
||||||
|
SLUG = "slug"
|
||||||
|
}
|
||||||
|
|
||||||
export type TCreateRoleDTO = {
|
export type TCreateRoleDTO = {
|
||||||
data: Omit<TProjectRolesInsert, "projectId">;
|
data: Omit<TProjectRolesInsert, "projectId">;
|
||||||
projectSlug: string;
|
filter:
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.SLUG; projectSlug: string }
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.ID; projectId: string };
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TGetRoleBySlugDTO = {
|
export type TGetRoleDetailsDTO = {
|
||||||
roleSlug: string;
|
roleSlug: string;
|
||||||
projectSlug: string;
|
filter:
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.SLUG; projectSlug: string }
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.ID; projectId: string };
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TUpdateRoleDTO = {
|
export type TUpdateRoleDTO = {
|
||||||
roleId: string;
|
roleId: string;
|
||||||
data: Omit<TOrgRolesUpdate, "orgId">;
|
data: Omit<TOrgRolesUpdate, "orgId">;
|
||||||
projectSlug: string;
|
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TDeleteRoleDTO = {
|
export type TDeleteRoleDTO = {
|
||||||
roleId: string;
|
roleId: string;
|
||||||
projectSlug: string;
|
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TListRolesDTO = {
|
export type TListRolesDTO = {
|
||||||
projectSlug: string;
|
filter:
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.SLUG; projectSlug: string }
|
||||||
|
| { type: ProjectRoleServiceIdentifierType.ID; projectId: string };
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
import { RawRule } from "@casl/ability";
|
|
||||||
|
|
||||||
import { ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
|
||||||
|
|
||||||
export const shouldCheckFolderPermission = (rules: RawRule[]) =>
|
|
||||||
rules.some((rule) => (rule.subject as ProjectPermissionSub[]).includes(ProjectPermissionSub.SecretFolders));
|
|
||||||
@@ -12,7 +12,6 @@ import { OrderByDirection } from "@app/lib/types";
|
|||||||
import { TProjectDALFactory } from "../project/project-dal";
|
import { TProjectDALFactory } from "../project/project-dal";
|
||||||
import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
|
import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
|
||||||
import { TSecretFolderDALFactory } from "./secret-folder-dal";
|
import { TSecretFolderDALFactory } from "./secret-folder-dal";
|
||||||
import { shouldCheckFolderPermission } from "./secret-folder-fns";
|
|
||||||
import {
|
import {
|
||||||
TCreateFolderDTO,
|
TCreateFolderDTO,
|
||||||
TDeleteFolderDTO,
|
TDeleteFolderDTO,
|
||||||
@@ -60,20 +59,10 @@ export const secretFolderServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
|
|
||||||
// we do this because we've split Secret and SecretFolder resources
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
// previously, if one can create/update/read/delete secrets then they can do the same for folders
|
ProjectPermissionActions.Create,
|
||||||
// for backwards compatibility, we handle authorization only when SecretFolders subject is used
|
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
||||||
if (shouldCheckFolderPermission(permission.rules)) {
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Create,
|
|
||||||
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Create,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const env = await projectEnvDAL.findOne({ projectId, slug: environment });
|
const env = await projectEnvDAL.findOne({ projectId, slug: environment });
|
||||||
if (!env) {
|
if (!env) {
|
||||||
@@ -169,20 +158,10 @@ export const secretFolderServiceFactory = ({
|
|||||||
);
|
);
|
||||||
|
|
||||||
folders.forEach(({ environment, path: secretPath }) => {
|
folders.forEach(({ environment, path: secretPath }) => {
|
||||||
// we do this because we've split Secret and SecretFolder resources
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
// previously, if one can create/update/read/delete secrets then they can do the same for folders
|
ProjectPermissionActions.Edit,
|
||||||
// for backwards compatibility, we handle authorization only when SecretFolders subject is used
|
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
||||||
if (shouldCheckFolderPermission(permission.rules)) {
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Edit,
|
|
||||||
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Edit,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await folderDAL.transaction(async (tx) =>
|
const result = await folderDAL.transaction(async (tx) =>
|
||||||
@@ -287,20 +266,10 @@ export const secretFolderServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
|
|
||||||
// we do this because we've split Secret and SecretFolder resources
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
// previously, if one can create/update/read/delete secrets then they can do the same for folders
|
ProjectPermissionActions.Edit,
|
||||||
// for backwards compatibility, we handle authorization differently only when SecretFolders subject is used
|
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
||||||
if (shouldCheckFolderPermission(permission.rules)) {
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Edit,
|
|
||||||
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Edit,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const parentFolder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
if (!parentFolder)
|
if (!parentFolder)
|
||||||
@@ -377,20 +346,10 @@ export const secretFolderServiceFactory = ({
|
|||||||
actorOrgId
|
actorOrgId
|
||||||
);
|
);
|
||||||
|
|
||||||
// we do this because we've split Secret and SecretFolder resources
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
// previously, if one can create/update/read/delete secrets then they can do the same for folders
|
ProjectPermissionActions.Delete,
|
||||||
// for backwards compatibility, we handle authorization differently only when SecretFolders subject is used
|
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
||||||
if (shouldCheckFolderPermission(permission.rules)) {
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Delete,
|
|
||||||
subject(ProjectPermissionSub.SecretFolders, { environment, secretPath })
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
|
||||||
ProjectPermissionActions.Delete,
|
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const env = await projectEnvDAL.findOne({ projectId, slug: environment });
|
const env = await projectEnvDAL.findOne({ projectId, slug: environment });
|
||||||
if (!env) throw new NotFoundError({ message: `Environment with slug '${environment}' not found` });
|
if (!env) throw new NotFoundError({ message: `Environment with slug '${environment}' not found` });
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ type TSecretImportSecretsV2 = {
|
|||||||
slug: string;
|
slug: string;
|
||||||
name: string;
|
name: string;
|
||||||
};
|
};
|
||||||
|
id: string;
|
||||||
folderId: string | undefined;
|
folderId: string | undefined;
|
||||||
importFolderId: string;
|
importFolderId: string;
|
||||||
secrets: (TSecretsV2 & {
|
secrets: (TSecretsV2 & {
|
||||||
@@ -139,24 +140,22 @@ export const fnSecretsFromImports = async ({
|
|||||||
return secrets;
|
return secrets;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* eslint-disable no-await-in-loop, no-continue */
|
||||||
export const fnSecretsV2FromImports = async ({
|
export const fnSecretsV2FromImports = async ({
|
||||||
allowedImports: possibleCyclicImports,
|
secretImports: rootSecretImports,
|
||||||
folderDAL,
|
folderDAL,
|
||||||
secretDAL,
|
secretDAL,
|
||||||
secretImportDAL,
|
secretImportDAL,
|
||||||
depth = 0,
|
|
||||||
cyclicDetector = new Set(),
|
|
||||||
decryptor,
|
decryptor,
|
||||||
expandSecretReferences
|
expandSecretReferences,
|
||||||
|
hasSecretAccess
|
||||||
}: {
|
}: {
|
||||||
allowedImports: (Omit<TSecretImports, "importEnv"> & {
|
secretImports: (Omit<TSecretImports, "importEnv"> & {
|
||||||
importEnv: { id: string; slug: string; name: string };
|
importEnv: { id: string; slug: string; name: string };
|
||||||
})[];
|
})[];
|
||||||
folderDAL: Pick<TSecretFolderDALFactory, "findByManySecretPath">;
|
folderDAL: Pick<TSecretFolderDALFactory, "findByManySecretPath">;
|
||||||
secretDAL: Pick<TSecretV2BridgeDALFactory, "find">;
|
secretDAL: Pick<TSecretV2BridgeDALFactory, "find">;
|
||||||
secretImportDAL: Pick<TSecretImportDALFactory, "findByFolderIds">;
|
secretImportDAL: Pick<TSecretImportDALFactory, "findByFolderIds">;
|
||||||
depth?: number;
|
|
||||||
cyclicDetector?: Set<string>;
|
|
||||||
decryptor: (value?: Buffer | null) => string;
|
decryptor: (value?: Buffer | null) => string;
|
||||||
expandSecretReferences?: (inputSecret: {
|
expandSecretReferences?: (inputSecret: {
|
||||||
value?: string;
|
value?: string;
|
||||||
@@ -164,92 +163,107 @@ export const fnSecretsV2FromImports = async ({
|
|||||||
secretPath: string;
|
secretPath: string;
|
||||||
environment: string;
|
environment: string;
|
||||||
}) => Promise<string | undefined>;
|
}) => Promise<string | undefined>;
|
||||||
|
hasSecretAccess: (environment: string, secretPath: string, secretName: string, secretTagSlugs: string[]) => boolean;
|
||||||
}) => {
|
}) => {
|
||||||
// avoid going more than a depth
|
const cyclicDetector = new Set();
|
||||||
if (depth >= LEVEL_BREAK) return [];
|
const stack: { secretImports: typeof rootSecretImports; depth: number; parentImportedSecrets: TSecretsV2[] }[] = [
|
||||||
|
{ secretImports: rootSecretImports, depth: 0, parentImportedSecrets: [] }
|
||||||
|
];
|
||||||
|
|
||||||
const allowedImports = possibleCyclicImports.filter(
|
const processedImports: TSecretImportSecretsV2[] = [];
|
||||||
({ importPath, importEnv }) => !cyclicDetector.has(getImportUniqKey(importEnv.slug, importPath))
|
|
||||||
);
|
|
||||||
|
|
||||||
const importedFolders = (
|
while (stack.length) {
|
||||||
await folderDAL.findByManySecretPath(
|
const { secretImports, depth, parentImportedSecrets } = stack.pop()!;
|
||||||
allowedImports.map(({ importEnv, importPath }) => ({
|
|
||||||
|
if (depth > LEVEL_BREAK) continue;
|
||||||
|
const sanitizedImports = secretImports.filter(
|
||||||
|
({ importPath, importEnv }) => !cyclicDetector.has(getImportUniqKey(importEnv.slug, importPath))
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!sanitizedImports.length) continue;
|
||||||
|
|
||||||
|
const importedFolders = await folderDAL.findByManySecretPath(
|
||||||
|
sanitizedImports.map(({ importEnv, importPath }) => ({
|
||||||
envId: importEnv.id,
|
envId: importEnv.id,
|
||||||
secretPath: importPath
|
secretPath: importPath
|
||||||
}))
|
}))
|
||||||
)
|
);
|
||||||
).filter(Boolean); // remove undefined ones
|
if (!importedFolders.length) continue;
|
||||||
if (!importedFolders.length) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const importedFolderIds = importedFolders.map((el) => el?.id) as string[];
|
const importedFolderIds = importedFolders.map((el) => el?.id) as string[];
|
||||||
const importedFolderGroupBySourceImport = groupBy(importedFolders, (i) => `${i?.envId}-${i?.path}`);
|
const importedFolderGroupBySourceImport = groupBy(importedFolders, (i) => `${i?.envId}-${i?.path}`);
|
||||||
const importedSecrets = await secretDAL.find(
|
|
||||||
{
|
|
||||||
$in: { folderId: importedFolderIds },
|
|
||||||
type: SecretType.Shared
|
|
||||||
},
|
|
||||||
{
|
|
||||||
sort: [["id", "asc"]]
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const importedSecretsGroupByFolderId = groupBy(importedSecrets, (i) => i.folderId);
|
const importedSecrets = await secretDAL.find(
|
||||||
|
{
|
||||||
|
$in: { folderId: importedFolderIds },
|
||||||
|
type: SecretType.Shared
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sort: [["id", "asc"]]
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const importedSecretsGroupByFolderId = groupBy(importedSecrets, (i) => i.folderId);
|
||||||
|
|
||||||
allowedImports.forEach(({ importPath, importEnv }) => {
|
sanitizedImports.forEach(({ importPath, importEnv }) => {
|
||||||
cyclicDetector.add(getImportUniqKey(importEnv.slug, importPath));
|
cyclicDetector.add(getImportUniqKey(importEnv.slug, importPath));
|
||||||
});
|
});
|
||||||
// now we need to check recursively deeper imports made inside other imports
|
// now we need to check recursively deeper imports made inside other imports
|
||||||
// we go level wise meaning we take all imports of a tree level and then go deeper ones level by level
|
// we go level wise meaning we take all imports of a tree level and then go deeper ones level by level
|
||||||
const deeperImports = await secretImportDAL.findByFolderIds(importedFolderIds);
|
const deeperImports = await secretImportDAL.findByFolderIds(importedFolderIds);
|
||||||
let secretsFromDeeperImports: TSecretImportSecretsV2[] = [];
|
const deeperImportsGroupByFolderId = groupBy(deeperImports, (i) => i.folderId);
|
||||||
if (deeperImports.length) {
|
|
||||||
secretsFromDeeperImports = await fnSecretsV2FromImports({
|
const isFirstIteration = !processedImports.length;
|
||||||
allowedImports: deeperImports.filter(({ isReplication }) => !isReplication),
|
sanitizedImports.forEach(({ importPath, importEnv, id, folderId }, i) => {
|
||||||
secretImportDAL,
|
const sourceImportFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0];
|
||||||
folderDAL,
|
const secretsWithDuplicate = (importedSecretsGroupByFolderId?.[importedFolders?.[i]?.id as string] || [])
|
||||||
secretDAL,
|
.filter((item) =>
|
||||||
depth: depth + 1,
|
hasSecretAccess(
|
||||||
cyclicDetector,
|
importEnv.slug,
|
||||||
decryptor,
|
importPath,
|
||||||
expandSecretReferences
|
item.key,
|
||||||
|
item.tags.map((el) => el.slug)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.map((item) => ({
|
||||||
|
...item,
|
||||||
|
secretKey: item.key,
|
||||||
|
secretValue: decryptor(item.encryptedValue),
|
||||||
|
secretComment: decryptor(item.encryptedComment),
|
||||||
|
environment: importEnv.slug,
|
||||||
|
workspace: "", // This field should not be used, it's only here to keep the older Python SDK versions backwards compatible with the new Postgres backend.
|
||||||
|
_id: item.id // The old Python SDK depends on the _id field being returned. We return this to keep the older Python SDK versions backwards compatible with the new Postgres backend.
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (deeperImportsGroupByFolderId?.[sourceImportFolder?.id || ""]) {
|
||||||
|
stack.push({
|
||||||
|
secretImports: deeperImportsGroupByFolderId[sourceImportFolder?.id || ""],
|
||||||
|
depth: depth + 1,
|
||||||
|
parentImportedSecrets: secretsWithDuplicate
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFirstIteration) {
|
||||||
|
processedImports.push({
|
||||||
|
secretPath: importPath,
|
||||||
|
environment: importEnv.slug,
|
||||||
|
environmentInfo: importEnv,
|
||||||
|
folderId: importedFolders?.[i]?.id,
|
||||||
|
id,
|
||||||
|
importFolderId: folderId,
|
||||||
|
secrets: secretsWithDuplicate
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
parentImportedSecrets.push(...secretsWithDuplicate);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const secretsFromdeeperImportGroupedByFolderId = groupBy(secretsFromDeeperImports, (i) => i.importFolderId);
|
/* eslint-enable */
|
||||||
|
|
||||||
const processedImports = allowedImports.map(({ importPath, importEnv, id, folderId }, i) => {
|
|
||||||
const sourceImportFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0];
|
|
||||||
const folderDeeperImportSecrets =
|
|
||||||
secretsFromdeeperImportGroupedByFolderId?.[sourceImportFolder?.id || ""]?.[0]?.secrets || [];
|
|
||||||
const secretsWithDuplicate = (importedSecretsGroupByFolderId?.[importedFolders?.[i]?.id as string] || [])
|
|
||||||
.map((item) => ({
|
|
||||||
...item,
|
|
||||||
secretKey: item.key,
|
|
||||||
secretValue: decryptor(item.encryptedValue),
|
|
||||||
secretComment: decryptor(item.encryptedComment),
|
|
||||||
environment: importEnv.slug,
|
|
||||||
workspace: "", // This field should not be used, it's only here to keep the older Python SDK versions backwards compatible with the new Postgres backend.
|
|
||||||
_id: item.id // The old Python SDK depends on the _id field being returned. We return this to keep the older Python SDK versions backwards compatible with the new Postgres backend.
|
|
||||||
}))
|
|
||||||
.concat(folderDeeperImportSecrets);
|
|
||||||
|
|
||||||
return {
|
|
||||||
secretPath: importPath,
|
|
||||||
environment: importEnv.slug,
|
|
||||||
environmentInfo: importEnv,
|
|
||||||
folderId: importedFolders?.[i]?.id,
|
|
||||||
id,
|
|
||||||
importFolderId: folderId,
|
|
||||||
secrets: unique(secretsWithDuplicate, (el) => el.secretKey)
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
if (expandSecretReferences) {
|
if (expandSecretReferences) {
|
||||||
await Promise.allSettled(
|
await Promise.allSettled(
|
||||||
processedImports.map((processedImport) =>
|
processedImports.map((processedImport) => {
|
||||||
Promise.allSettled(
|
// eslint-disable-next-line
|
||||||
|
processedImport.secrets = unique(processedImport.secrets, (i) => i.key);
|
||||||
|
return Promise.allSettled(
|
||||||
processedImport.secrets.map(async (decryptedSecret, index) => {
|
processedImport.secrets.map(async (decryptedSecret, index) => {
|
||||||
const expandedSecretValue = await expandSecretReferences({
|
const expandedSecretValue = await expandSecretReferences({
|
||||||
value: decryptedSecret.secretValue,
|
value: decryptedSecret.secretValue,
|
||||||
@@ -260,8 +274,8 @@ export const fnSecretsV2FromImports = async ({
|
|||||||
// eslint-disable-next-line no-param-reassign
|
// eslint-disable-next-line no-param-reassign
|
||||||
processedImport.secrets[index].secretValue = expandedSecretValue || "";
|
processedImport.secrets[index].secretValue = expandedSecretValue || "";
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
)
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -84,12 +84,12 @@ export const secretImportServiceFactory = ({
|
|||||||
// check if user has permission to import into destination path
|
// check if user has permission to import into destination path
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
// check if user has permission to import from target path
|
// check if user has permission to import from target path
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
environment: data.environment,
|
environment: data.environment,
|
||||||
secretPath: data.path
|
secretPath: data.path
|
||||||
@@ -198,7 +198,7 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
@@ -292,7 +292,7 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
@@ -364,8 +364,8 @@ export const secretImportServiceFactory = ({
|
|||||||
|
|
||||||
// check if user has permission to import into destination path
|
// check if user has permission to import into destination path
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(actorOrgId);
|
const plan = await licenseService.getPlan(actorOrgId);
|
||||||
@@ -393,7 +393,7 @@ export const secretImportServiceFactory = ({
|
|||||||
|
|
||||||
// check if user has permission to import from target path
|
// check if user has permission to import from target path
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
environment: secretImportDoc.importEnv.slug,
|
environment: secretImportDoc.importEnv.slug,
|
||||||
secretPath: secretImportDoc.importPath
|
secretPath: secretImportDoc.importPath
|
||||||
@@ -441,7 +441,7 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
@@ -476,7 +476,7 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
@@ -526,7 +526,7 @@ export const secretImportServiceFactory = ({
|
|||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.SecretImports, {
|
||||||
environment: folder.environment.envSlug,
|
environment: folder.environment.envSlug,
|
||||||
secretPath: folderWithPath.path
|
secretPath: folderWithPath.path
|
||||||
})
|
})
|
||||||
@@ -573,20 +573,19 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
if (!folder) return [];
|
if (!folder) return [];
|
||||||
// this will already order by position
|
// this will already order by position
|
||||||
// so anything based on this order will also be in right position
|
// so anything based on this order will also be in right position
|
||||||
const secretImports = await secretImportDAL.find({ folderId: folder.id, isReplication: false });
|
const secretImports = await secretImportDAL.find({ folderId: folder.id, isReplication: false });
|
||||||
|
const allowedImports = secretImports.filter((el) =>
|
||||||
const allowedImports = secretImports.filter(({ importEnv, importPath }) =>
|
|
||||||
permission.can(
|
permission.can(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
environment: importEnv.slug,
|
environment: el.importEnv.slug,
|
||||||
secretPath: importPath
|
secretPath: el.importPath
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -611,7 +610,7 @@ export const secretImportServiceFactory = ({
|
|||||||
);
|
);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
|
||||||
);
|
);
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
if (!folder) return [];
|
if (!folder) return [];
|
||||||
@@ -619,16 +618,6 @@ export const secretImportServiceFactory = ({
|
|||||||
// so anything based on this order will also be in right position
|
// so anything based on this order will also be in right position
|
||||||
const secretImports = await secretImportDAL.find({ folderId: folder.id, isReplication: false });
|
const secretImports = await secretImportDAL.find({ folderId: folder.id, isReplication: false });
|
||||||
|
|
||||||
const allowedImports = secretImports.filter(({ importEnv, importPath }) =>
|
|
||||||
permission.can(
|
|
||||||
ProjectPermissionActions.Read,
|
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
|
||||||
environment: importEnv.slug,
|
|
||||||
secretPath: importPath
|
|
||||||
})
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
|
const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
|
||||||
if (shouldUseSecretV2Bridge) {
|
if (shouldUseSecretV2Bridge) {
|
||||||
const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
|
const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
|
||||||
@@ -636,11 +625,21 @@ export const secretImportServiceFactory = ({
|
|||||||
projectId
|
projectId
|
||||||
});
|
});
|
||||||
const importedSecrets = await fnSecretsV2FromImports({
|
const importedSecrets = await fnSecretsV2FromImports({
|
||||||
allowedImports,
|
secretImports,
|
||||||
folderDAL,
|
folderDAL,
|
||||||
secretDAL: secretV2BridgeDAL,
|
secretDAL: secretV2BridgeDAL,
|
||||||
secretImportDAL,
|
secretImportDAL,
|
||||||
decryptor: (value) => (value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : "")
|
decryptor: (value) => (value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : ""),
|
||||||
|
hasSecretAccess: (expandEnvironment, expandSecretPath, expandSecretKey, expandSecretTags) =>
|
||||||
|
permission.can(
|
||||||
|
ProjectPermissionActions.Read,
|
||||||
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: expandEnvironment,
|
||||||
|
secretPath: expandSecretPath,
|
||||||
|
secretName: expandSecretKey,
|
||||||
|
secretTags: expandSecretTags
|
||||||
|
})
|
||||||
|
)
|
||||||
});
|
});
|
||||||
return importedSecrets;
|
return importedSecrets;
|
||||||
}
|
}
|
||||||
@@ -651,7 +650,21 @@ export const secretImportServiceFactory = ({
|
|||||||
name: "bot_not_found_error"
|
name: "bot_not_found_error"
|
||||||
});
|
});
|
||||||
|
|
||||||
const importedSecrets = await fnSecretsFromImports({ allowedImports, folderDAL, secretDAL, secretImportDAL });
|
const allowedImports = secretImports.filter((el) =>
|
||||||
|
permission.can(
|
||||||
|
ProjectPermissionActions.Read,
|
||||||
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: el.importEnv.slug,
|
||||||
|
secretPath: el.importPath
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
const importedSecrets = await fnSecretsFromImports({
|
||||||
|
allowedImports,
|
||||||
|
folderDAL,
|
||||||
|
secretDAL,
|
||||||
|
secretImportDAL
|
||||||
|
});
|
||||||
return importedSecrets.map((el) => ({
|
return importedSecrets.map((el) => ({
|
||||||
...el,
|
...el,
|
||||||
secrets: el.secrets.map((encryptedSecret) =>
|
secrets: el.secrets.map((encryptedSecret) =>
|
||||||
|
|||||||
@@ -4,7 +4,14 @@ import { validate as uuidValidate } from "uuid";
|
|||||||
import { TDbClient } from "@app/db";
|
import { TDbClient } from "@app/db";
|
||||||
import { SecretsV2Schema, SecretType, TableName, TSecretsV2, TSecretsV2Update } from "@app/db/schemas";
|
import { SecretsV2Schema, SecretType, TableName, TSecretsV2, TSecretsV2Update } from "@app/db/schemas";
|
||||||
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
|
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
|
||||||
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
|
import {
|
||||||
|
buildFindFilter,
|
||||||
|
ormify,
|
||||||
|
selectAllTableCols,
|
||||||
|
sqlNestRelationships,
|
||||||
|
TFindFilter,
|
||||||
|
TFindOpt
|
||||||
|
} from "@app/lib/knex";
|
||||||
import { OrderByDirection } from "@app/lib/types";
|
import { OrderByDirection } from "@app/lib/types";
|
||||||
import { SecretsOrderBy } from "@app/services/secret/secret-types";
|
import { SecretsOrderBy } from "@app/services/secret/secret-types";
|
||||||
|
|
||||||
@@ -13,6 +20,97 @@ export type TSecretV2BridgeDALFactory = ReturnType<typeof secretV2BridgeDALFacto
|
|||||||
export const secretV2BridgeDALFactory = (db: TDbClient) => {
|
export const secretV2BridgeDALFactory = (db: TDbClient) => {
|
||||||
const secretOrm = ormify(db, TableName.SecretV2);
|
const secretOrm = ormify(db, TableName.SecretV2);
|
||||||
|
|
||||||
|
const findOne = async (filter: Partial<TSecretsV2>, tx?: Knex) => {
|
||||||
|
try {
|
||||||
|
const docs = await (tx || db)(TableName.SecretV2)
|
||||||
|
.where(filter)
|
||||||
|
.leftJoin(
|
||||||
|
TableName.SecretV2JnTag,
|
||||||
|
`${TableName.SecretV2}.id`,
|
||||||
|
`${TableName.SecretV2JnTag}.${TableName.SecretV2}Id`
|
||||||
|
)
|
||||||
|
.leftJoin(
|
||||||
|
TableName.SecretTag,
|
||||||
|
`${TableName.SecretV2JnTag}.${TableName.SecretTag}Id`,
|
||||||
|
`${TableName.SecretTag}.id`
|
||||||
|
)
|
||||||
|
.select(selectAllTableCols(TableName.SecretV2))
|
||||||
|
.select(db.ref("id").withSchema(TableName.SecretTag).as("tagId"))
|
||||||
|
.select(db.ref("color").withSchema(TableName.SecretTag).as("tagColor"))
|
||||||
|
.select(db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"));
|
||||||
|
|
||||||
|
const data = sqlNestRelationships({
|
||||||
|
data: docs,
|
||||||
|
key: "id",
|
||||||
|
parentMapper: (el) => ({ _id: el.id, ...SecretsV2Schema.parse(el) }),
|
||||||
|
childrenMapper: [
|
||||||
|
{
|
||||||
|
key: "tagId",
|
||||||
|
label: "tags" as const,
|
||||||
|
mapper: ({ tagId: id, tagColor: color, tagSlug: slug }) => ({
|
||||||
|
id,
|
||||||
|
color,
|
||||||
|
slug,
|
||||||
|
name: slug
|
||||||
|
})
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
return data?.[0];
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: `${TableName.SecretV2}: FindOne` });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const find = async (filter: TFindFilter<TSecretsV2>, { offset, limit, sort, tx }: TFindOpt<TSecretsV2> = {}) => {
|
||||||
|
try {
|
||||||
|
const query = (tx || db)(TableName.SecretV2)
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||||
|
.where(buildFindFilter(filter))
|
||||||
|
.leftJoin(
|
||||||
|
TableName.SecretV2JnTag,
|
||||||
|
`${TableName.SecretV2}.id`,
|
||||||
|
`${TableName.SecretV2JnTag}.${TableName.SecretV2}Id`
|
||||||
|
)
|
||||||
|
.leftJoin(
|
||||||
|
TableName.SecretTag,
|
||||||
|
`${TableName.SecretV2JnTag}.${TableName.SecretTag}Id`,
|
||||||
|
`${TableName.SecretTag}.id`
|
||||||
|
)
|
||||||
|
.select(selectAllTableCols(TableName.SecretV2))
|
||||||
|
.select(db.ref("id").withSchema(TableName.SecretTag).as("tagId"))
|
||||||
|
.select(db.ref("color").withSchema(TableName.SecretTag).as("tagColor"))
|
||||||
|
.select(db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"));
|
||||||
|
if (limit) void query.limit(limit);
|
||||||
|
if (offset) void query.offset(offset);
|
||||||
|
if (sort) {
|
||||||
|
void query.orderBy(sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls })));
|
||||||
|
}
|
||||||
|
|
||||||
|
const docs = await query;
|
||||||
|
const data = sqlNestRelationships({
|
||||||
|
data: docs,
|
||||||
|
key: "id",
|
||||||
|
parentMapper: (el) => ({ _id: el.id, ...SecretsV2Schema.parse(el) }),
|
||||||
|
childrenMapper: [
|
||||||
|
{
|
||||||
|
key: "tagId",
|
||||||
|
label: "tags" as const,
|
||||||
|
mapper: ({ tagId: id, tagColor: color, tagSlug: slug }) => ({
|
||||||
|
id,
|
||||||
|
color,
|
||||||
|
slug,
|
||||||
|
name: slug
|
||||||
|
})
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: `${TableName.SecretV2}: Find` });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const update = async (filter: Partial<TSecretsV2>, data: Omit<TSecretsV2Update, "version">, tx?: Knex) => {
|
const update = async (filter: Partial<TSecretsV2>, data: Omit<TSecretsV2Update, "version">, tx?: Knex) => {
|
||||||
try {
|
try {
|
||||||
const sec = await (tx || db)(TableName.SecretV2)
|
const sec = await (tx || db)(TableName.SecretV2)
|
||||||
@@ -484,6 +582,8 @@ export const secretV2BridgeDALFactory = (db: TDbClient) => {
|
|||||||
upsertSecretReferences,
|
upsertSecretReferences,
|
||||||
findReferencedSecretReferences,
|
findReferencedSecretReferences,
|
||||||
findAllProjectSecretValues,
|
findAllProjectSecretValues,
|
||||||
countByFolderIds
|
countByFolderIds,
|
||||||
|
findOne,
|
||||||
|
find
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -30,9 +30,10 @@ export const shouldUseSecretV2Bridge = (version: number) => version === 3;
|
|||||||
* // { environment: 'prod', secretPath: '/anotherFolder' }
|
* // { environment: 'prod', secretPath: '/anotherFolder' }
|
||||||
* // ]
|
* // ]
|
||||||
*/
|
*/
|
||||||
export const getAllNestedSecretReferences = (maybeSecretReference: string) => {
|
export const getAllSecretReferences = (maybeSecretReference: string) => {
|
||||||
const references = Array.from(maybeSecretReference.matchAll(INTERPOLATION_SYNTAX_REG), (m) => m[1]);
|
const references = Array.from(maybeSecretReference.matchAll(INTERPOLATION_SYNTAX_REG), (m) => m[1]);
|
||||||
return references
|
|
||||||
|
const nestedReferences = references
|
||||||
.filter((el) => el.includes("."))
|
.filter((el) => el.includes("."))
|
||||||
.map((el) => {
|
.map((el) => {
|
||||||
const [environment, ...secretPathList] = el.split(".");
|
const [environment, ...secretPathList] = el.split(".");
|
||||||
@@ -42,6 +43,8 @@ export const getAllNestedSecretReferences = (maybeSecretReference: string) => {
|
|||||||
secretKey: secretPathList[secretPathList.length - 1]
|
secretKey: secretPathList[secretPathList.length - 1]
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
const localReferences = references.filter((el) => !el.includes("."));
|
||||||
|
return { nestedReferences, localReferences };
|
||||||
};
|
};
|
||||||
|
|
||||||
// these functions are special functions shared by a couple of resources
|
// these functions are special functions shared by a couple of resources
|
||||||
@@ -325,16 +328,13 @@ type TRecursivelyFetchSecretsFromFoldersArg = {
|
|||||||
projectId: string;
|
projectId: string;
|
||||||
environment: string;
|
environment: string;
|
||||||
currentPath: string;
|
currentPath: string;
|
||||||
hasAccess: (environment: string, secretPath: string) => boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const recursivelyGetSecretPaths = async ({
|
export const recursivelyGetSecretPaths = async ({
|
||||||
folderDAL,
|
folderDAL,
|
||||||
projectEnvDAL,
|
projectEnvDAL,
|
||||||
projectId,
|
projectId,
|
||||||
environment,
|
environment
|
||||||
currentPath,
|
|
||||||
hasAccess
|
|
||||||
}: TRecursivelyFetchSecretsFromFoldersArg) => {
|
}: TRecursivelyFetchSecretsFromFoldersArg) => {
|
||||||
const env = await projectEnvDAL.findOne({
|
const env = await projectEnvDAL.findOne({
|
||||||
projectId,
|
projectId,
|
||||||
@@ -362,12 +362,7 @@ export const recursivelyGetSecretPaths = async ({
|
|||||||
folderId: p.folderId
|
folderId: p.folderId
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Filter out paths that the user does not have permission to access, and paths that are not in the current path
|
return paths;
|
||||||
const allowedPaths = paths.filter(
|
|
||||||
(folder) => hasAccess(environment, folder.path) && folder.path.startsWith(currentPath === "/" ? "" : currentPath)
|
|
||||||
);
|
|
||||||
|
|
||||||
return allowedPaths;
|
|
||||||
};
|
};
|
||||||
// used to convert multi line ones to quotes ones with \n
|
// used to convert multi line ones to quotes ones with \n
|
||||||
const formatMultiValueEnv = (val?: string) => {
|
const formatMultiValueEnv = (val?: string) => {
|
||||||
@@ -381,7 +376,7 @@ type TInterpolateSecretArg = {
|
|||||||
decryptSecretValue: (encryptedValue?: Buffer | null) => string | undefined;
|
decryptSecretValue: (encryptedValue?: Buffer | null) => string | undefined;
|
||||||
secretDAL: Pick<TSecretV2BridgeDALFactory, "findByFolderId">;
|
secretDAL: Pick<TSecretV2BridgeDALFactory, "findByFolderId">;
|
||||||
folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
|
folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
|
||||||
canExpandValue: (environment: string, secretPath: string) => boolean;
|
canExpandValue: (environment: string, secretPath: string, secretName: string, secretTagSlugs: string[]) => boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const MAX_SECRET_REFERENCE_DEPTH = 10;
|
const MAX_SECRET_REFERENCE_DEPTH = 10;
|
||||||
@@ -392,29 +387,29 @@ export const expandSecretReferencesFactory = ({
|
|||||||
folderDAL,
|
folderDAL,
|
||||||
canExpandValue
|
canExpandValue
|
||||||
}: TInterpolateSecretArg) => {
|
}: TInterpolateSecretArg) => {
|
||||||
const secretCache: Record<string, Record<string, string>> = {};
|
const secretCache: Record<string, Record<string, { value: string; tags: string[] }>> = {};
|
||||||
const getCacheUniqueKey = (environment: string, secretPath: string) => `${environment}-${secretPath}`;
|
const getCacheUniqueKey = (environment: string, secretPath: string) => `${environment}-${secretPath}`;
|
||||||
|
|
||||||
const fetchSecret = async (environment: string, secretPath: string, secretKey: string) => {
|
const fetchSecret = async (environment: string, secretPath: string, secretKey: string) => {
|
||||||
const cacheKey = getCacheUniqueKey(environment, secretPath);
|
const cacheKey = getCacheUniqueKey(environment, secretPath);
|
||||||
|
|
||||||
if (secretCache?.[cacheKey]) {
|
if (secretCache?.[cacheKey]) {
|
||||||
return secretCache[cacheKey][secretKey] || "";
|
return secretCache[cacheKey][secretKey] || { value: "", tags: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
|
||||||
if (!folder) return "";
|
if (!folder) return { value: "", tags: [] };
|
||||||
const secrets = await secretDAL.findByFolderId(folder.id);
|
const secrets = await secretDAL.findByFolderId(folder.id);
|
||||||
|
|
||||||
const decryptedSecret = secrets.reduce<Record<string, string>>((prev, secret) => {
|
const decryptedSecret = secrets.reduce<Record<string, { value: string; tags: string[] }>>((prev, secret) => {
|
||||||
// eslint-disable-next-line no-param-reassign
|
// eslint-disable-next-line no-param-reassign
|
||||||
prev[secret.key] = decryptSecret(secret.encryptedValue) || "";
|
prev[secret.key] = { value: decryptSecret(secret.encryptedValue) || "", tags: secret.tags?.map((el) => el.slug) };
|
||||||
return prev;
|
return prev;
|
||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
secretCache[cacheKey] = decryptedSecret;
|
secretCache[cacheKey] = decryptedSecret;
|
||||||
|
|
||||||
return secretCache[cacheKey][secretKey] || "";
|
return secretCache[cacheKey][secretKey] || { value: "", tags: [] };
|
||||||
};
|
};
|
||||||
|
|
||||||
const recursivelyExpandSecret = async (dto: { value?: string; secretPath: string; environment: string }) => {
|
const recursivelyExpandSecret = async (dto: { value?: string; secretPath: string; environment: string }) => {
|
||||||
@@ -440,43 +435,43 @@ export const expandSecretReferencesFactory = ({
|
|||||||
if (entities.length === 1) {
|
if (entities.length === 1) {
|
||||||
const [secretKey] = entities;
|
const [secretKey] = entities;
|
||||||
|
|
||||||
if (!canExpandValue(environment, secretPath))
|
// eslint-disable-next-line no-continue,no-await-in-loop
|
||||||
|
const referredValue = await fetchSecret(environment, secretPath, secretKey);
|
||||||
|
if (!canExpandValue(environment, secretPath, secretKey, referredValue.tags))
|
||||||
throw new ForbiddenRequestError({
|
throw new ForbiddenRequestError({
|
||||||
message: `You are attempting to reference secret named ${secretKey} from environment ${environment} in path ${secretPath} which you do not have access to.`
|
message: `You are attempting to reference secret named ${secretKey} from environment ${environment} in path ${secretPath} which you do not have access to.`
|
||||||
});
|
});
|
||||||
|
|
||||||
// eslint-disable-next-line no-continue,no-await-in-loop
|
|
||||||
const referedValue = await fetchSecret(environment, secretPath, secretKey);
|
|
||||||
const cacheKey = getCacheUniqueKey(environment, secretPath);
|
const cacheKey = getCacheUniqueKey(environment, secretPath);
|
||||||
secretCache[cacheKey][secretKey] = referedValue;
|
secretCache[cacheKey][secretKey] = referredValue;
|
||||||
if (INTERPOLATION_SYNTAX_REG.test(referedValue)) {
|
if (INTERPOLATION_SYNTAX_REG.test(referredValue.value)) {
|
||||||
stack.push({
|
stack.push({
|
||||||
value: referedValue,
|
value: referredValue.value,
|
||||||
secretPath,
|
secretPath,
|
||||||
environment,
|
environment,
|
||||||
depth: depth + 1
|
depth: depth + 1
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (referedValue) {
|
if (referredValue) {
|
||||||
expandedValue = expandedValue.replaceAll(interpolationSyntax, referedValue);
|
expandedValue = expandedValue.replaceAll(interpolationSyntax, referredValue.value);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const secretReferenceEnvironment = entities[0];
|
const secretReferenceEnvironment = entities[0];
|
||||||
const secretReferencePath = path.join("/", ...entities.slice(1, entities.length - 1));
|
const secretReferencePath = path.join("/", ...entities.slice(1, entities.length - 1));
|
||||||
const secretReferenceKey = entities[entities.length - 1];
|
const secretReferenceKey = entities[entities.length - 1];
|
||||||
|
|
||||||
if (!canExpandValue(secretReferenceEnvironment, secretReferencePath))
|
// eslint-disable-next-line no-await-in-loop
|
||||||
|
const referedValue = await fetchSecret(secretReferenceEnvironment, secretReferencePath, secretReferenceKey);
|
||||||
|
if (!canExpandValue(secretReferenceEnvironment, secretReferencePath, secretReferenceKey, referedValue.tags))
|
||||||
throw new ForbiddenRequestError({
|
throw new ForbiddenRequestError({
|
||||||
message: `You are attempting to reference secret named ${secretReferenceKey} from environment ${secretReferenceEnvironment} in path ${secretReferencePath} which you do not have access to.`
|
message: `You are attempting to reference secret named ${secretReferenceKey} from environment ${secretReferenceEnvironment} in path ${secretReferencePath} which you do not have access to.`
|
||||||
});
|
});
|
||||||
|
|
||||||
// eslint-disable-next-line no-await-in-loop
|
|
||||||
const referedValue = await fetchSecret(secretReferenceEnvironment, secretReferencePath, secretReferenceKey);
|
|
||||||
const cacheKey = getCacheUniqueKey(secretReferenceEnvironment, secretReferencePath);
|
const cacheKey = getCacheUniqueKey(secretReferenceEnvironment, secretReferencePath);
|
||||||
secretCache[cacheKey][secretReferenceKey] = referedValue;
|
secretCache[cacheKey][secretReferenceKey] = referedValue;
|
||||||
if (INTERPOLATION_SYNTAX_REG.test(referedValue)) {
|
if (INTERPOLATION_SYNTAX_REG.test(referedValue.value)) {
|
||||||
stack.push({
|
stack.push({
|
||||||
value: referedValue,
|
value: referedValue.value,
|
||||||
secretPath: secretReferencePath,
|
secretPath: secretReferencePath,
|
||||||
environment: secretReferenceEnvironment,
|
environment: secretReferenceEnvironment,
|
||||||
depth: depth + 1
|
depth: depth + 1
|
||||||
@@ -484,7 +479,7 @@ export const expandSecretReferencesFactory = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (referedValue) {
|
if (referedValue) {
|
||||||
expandedValue = expandedValue.replaceAll(interpolationSyntax, referedValue);
|
expandedValue = expandedValue.replaceAll(interpolationSyntax, referedValue.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,12 @@ type TPartialSecret = Pick<TSecretsV2, "id" | "reminderRepeatDays" | "reminderNo
|
|||||||
|
|
||||||
type TPartialInputSecret = Pick<TSecretsV2, "type" | "reminderNote" | "reminderRepeatDays" | "id">;
|
type TPartialInputSecret = Pick<TSecretsV2, "type" | "reminderNote" | "reminderRepeatDays" | "id">;
|
||||||
|
|
||||||
|
export type TSecretReferenceDTO = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
secretKey: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type TGetSecretsDTO = {
|
export type TGetSecretsDTO = {
|
||||||
expandSecretReferences?: boolean;
|
expandSecretReferences?: boolean;
|
||||||
path: string;
|
path: string;
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import { logger } from "@app/lib/logger";
|
|||||||
import {
|
import {
|
||||||
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
|
||||||
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
|
||||||
getAllNestedSecretReferences as getAllNestedSecretReferencesV2Bridge
|
getAllSecretReferences
|
||||||
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
|
||||||
|
|
||||||
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
|
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
|
||||||
@@ -793,7 +793,7 @@ export const createManySecretsRawFnFactory = ({
|
|||||||
: null,
|
: null,
|
||||||
skipMultilineEncoding: secret.skipMultilineEncoding,
|
skipMultilineEncoding: secret.skipMultilineEncoding,
|
||||||
tags: secret.tags,
|
tags: secret.tags,
|
||||||
references: getAllNestedSecretReferencesV2Bridge(secret.secretValue)
|
references: getAllSecretReferences(secret.secretValue).nestedReferences
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -973,7 +973,7 @@ export const updateManySecretsRawFnFactory = ({
|
|||||||
: null,
|
: null,
|
||||||
skipMultilineEncoding: secret.skipMultilineEncoding,
|
skipMultilineEncoding: secret.skipMultilineEncoding,
|
||||||
tags: secret.tags,
|
tags: secret.tags,
|
||||||
references: getAllNestedSecretReferencesV2Bridge(secret.secretValue)
|
references: getAllSecretReferences(secret.secretValue).nestedReferences
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
|
|||||||
import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
|
import { TSecretImportDALFactory } from "../secret-import/secret-import-dal";
|
||||||
import { fnSecretsV2FromImports } from "../secret-import/secret-import-fns";
|
import { fnSecretsV2FromImports } from "../secret-import/secret-import-fns";
|
||||||
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
|
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
|
||||||
import { expandSecretReferencesFactory, getAllNestedSecretReferences } from "../secret-v2-bridge/secret-v2-bridge-fns";
|
import { expandSecretReferencesFactory, getAllSecretReferences } from "../secret-v2-bridge/secret-v2-bridge-fns";
|
||||||
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
|
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
|
||||||
import { TSecretVersionV2TagDALFactory } from "../secret-v2-bridge/secret-version-tag-dal";
|
import { TSecretVersionV2TagDALFactory } from "../secret-v2-bridge/secret-version-tag-dal";
|
||||||
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
|
||||||
@@ -342,7 +342,8 @@ export const secretQueueFactory = ({
|
|||||||
secretDAL: secretV2BridgeDAL,
|
secretDAL: secretV2BridgeDAL,
|
||||||
expandSecretReferences,
|
expandSecretReferences,
|
||||||
secretImportDAL,
|
secretImportDAL,
|
||||||
allowedImports: secretImports
|
secretImports,
|
||||||
|
hasSecretAccess: () => true
|
||||||
});
|
});
|
||||||
|
|
||||||
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
|
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
|
||||||
@@ -1147,7 +1148,7 @@ export const secretQueueFactory = ({
|
|||||||
: "";
|
: "";
|
||||||
const encryptedValue = secretManagerEncryptor({ plainText: Buffer.from(value) }).cipherTextBlob;
|
const encryptedValue = secretManagerEncryptor({ plainText: Buffer.from(value) }).cipherTextBlob;
|
||||||
// create references
|
// create references
|
||||||
const references = getAllNestedSecretReferences(value);
|
const references = getAllSecretReferences(value).nestedReferences;
|
||||||
secretReferences.push({ secretId: el.id, references });
|
secretReferences.push({ secretId: el.id, references });
|
||||||
|
|
||||||
const encryptedComment = comment
|
const encryptedComment = comment
|
||||||
|
|||||||
@@ -2436,17 +2436,26 @@ export const secretServiceFactory = ({
|
|||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: sourceEnvironment, secretPath: sourceSecretPath })
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: sourceEnvironment,
|
||||||
|
secretPath: sourceSecretPath
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: destinationEnvironment, secretPath: destinationSecretPath })
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: destinationEnvironment,
|
||||||
|
secretPath: destinationSecretPath
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment: destinationEnvironment, secretPath: destinationSecretPath })
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
environment: destinationEnvironment,
|
||||||
|
secretPath: destinationSecretPath
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
const { botKey } = await projectBotService.getBotKey(project.id);
|
const { botKey } = await projectBotService.getBotKey(project.id);
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import picomatch from "picomatch";
|
||||||
|
|
||||||
|
import { FormControl } from "../v2/FormControl";
|
||||||
|
import { Input } from "../v2/Input";
|
||||||
|
|
||||||
|
export const GlobPermissionInfo = () => {
|
||||||
|
const [pattern, setPattern] = useState("");
|
||||||
|
const [text, setText] = useState("");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mt-2">A glob pattern uses wildcards to match resources or paths.</div>
|
||||||
|
<div>
|
||||||
|
<FormControl label="Glob pattern" helperText="Examples: /{a,b}, DB_**">
|
||||||
|
<Input value={pattern} onChange={(e) => setPattern(e.target.value)} />
|
||||||
|
</FormControl>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<FormControl
|
||||||
|
label="Test string"
|
||||||
|
helperText="Type a value to test glob match"
|
||||||
|
isError={
|
||||||
|
pattern && text ? !picomatch.isMatch(text, pattern, { strictSlashes: false }) : false
|
||||||
|
}
|
||||||
|
errorText="Invalid"
|
||||||
|
>
|
||||||
|
<Input value={text} onChange={(e) => setText(e.target.value)} />
|
||||||
|
</FormControl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,23 +1,25 @@
|
|||||||
import { FunctionComponent, ReactNode } from "react";
|
import { FunctionComponent, ReactNode } from "react";
|
||||||
import { BoundCanProps, Can } from "@casl/react";
|
import { AbilityTuple, MongoAbility } from "@casl/ability";
|
||||||
|
import { Can } from "@casl/react";
|
||||||
|
|
||||||
import { TProjectPermission, useProjectPermission } from "@app/context/ProjectPermissionContext";
|
import { ProjectPermissionSet, useProjectPermission } from "@app/context/ProjectPermissionContext";
|
||||||
|
|
||||||
import { Tooltip } from "../v2";
|
import { Tooltip } from "../v2/Tooltip";
|
||||||
|
|
||||||
type Props = {
|
type Props<T extends AbilityTuple> = {
|
||||||
label?: ReactNode;
|
label?: ReactNode;
|
||||||
// this prop is used when there exist already a tooltip as helper text for users
|
// this prop is used when there exist already a tooltip as helper text for users
|
||||||
// so when permission is allowed same tooltip will be reused to show helpertext
|
// so when permission is allowed same tooltip will be reused to show helpertext
|
||||||
renderTooltip?: boolean;
|
renderTooltip?: boolean;
|
||||||
allowedLabel?: string;
|
allowedLabel?: string;
|
||||||
// BUG(akhilmhdh): As a workaround for now i put any but this should be TProjectPermission
|
children: ReactNode | ((isAllowed: boolean, ability: T) => ReactNode);
|
||||||
// For some reason when i put TProjectPermission in a wrapper component it just wont work causes a weird ts error
|
passThrough?: boolean;
|
||||||
// tried a lot combinations
|
I: T[0];
|
||||||
// REF: https://github.com/stalniy/casl/blob/ac081a34f56366a7eaaed05d21689d27041ef005/packages/casl-react/src/factory.ts#L15
|
a: T[1];
|
||||||
} & BoundCanProps<any>;
|
ability?: MongoAbility<T>;
|
||||||
|
};
|
||||||
|
|
||||||
export const ProjectPermissionCan: FunctionComponent<Props> = ({
|
export const ProjectPermissionCan: FunctionComponent<Props<ProjectPermissionSet>> = ({
|
||||||
label = "Access restricted",
|
label = "Access restricted",
|
||||||
children,
|
children,
|
||||||
passThrough = true,
|
passThrough = true,
|
||||||
@@ -31,9 +33,7 @@ export const ProjectPermissionCan: FunctionComponent<Props> = ({
|
|||||||
{(isAllowed, ability) => {
|
{(isAllowed, ability) => {
|
||||||
// akhilmhdh: This is set as type due to error in casl react type.
|
// akhilmhdh: This is set as type due to error in casl react type.
|
||||||
const finalChild =
|
const finalChild =
|
||||||
typeof children === "function"
|
typeof children === "function" ? children(isAllowed, ability as any) : children;
|
||||||
? children(isAllowed, ability as TProjectPermission)
|
|
||||||
: children;
|
|
||||||
|
|
||||||
if (!isAllowed && passThrough) {
|
if (!isAllowed && passThrough) {
|
||||||
return <Tooltip content={label}>{finalChild}</Tooltip>;
|
return <Tooltip content={label}>{finalChild}</Tooltip>;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
export { GlobPermissionInfo } from "./GlobPermissionInfo";
|
||||||
export { OrgPermissionCan } from "./OrgPermissionCan";
|
export { OrgPermissionCan } from "./OrgPermissionCan";
|
||||||
export { PermissionDeniedBanner } from "./PermissionDeniedBanner";
|
export { PermissionDeniedBanner } from "./PermissionDeniedBanner";
|
||||||
export { ProjectPermissionCan } from "./ProjectPermissionCan";
|
export { ProjectPermissionCan } from "./ProjectPermissionCan";
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { type VariantProps, cva } from "cva";
|
|||||||
import { twMerge } from "tailwind-merge";
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
const alertVariants = cva(
|
const alertVariants = cva(
|
||||||
"w-full bg-mineshaft-800 rounded-lg border px-4 py-3 text-sm flex items-center gap-x-4",
|
"w-full bg-mineshaft-800 rounded-lg border border-bunker-400 px-4 py-3 text-sm flex items-center gap-x-4",
|
||||||
{
|
{
|
||||||
variants: {
|
variants: {
|
||||||
variant: {
|
variant: {
|
||||||
@@ -66,7 +66,7 @@ const Alert = forwardRef<
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-y-1">
|
<div className="flex flex-col gap-y-1">
|
||||||
{hideTitle ? null : (
|
{hideTitle ? null : (
|
||||||
<h5 className="font-medium leading-none tracking-tight" {...props}>
|
<h5 className="font-medium leading-6 tracking-tight" {...props}>
|
||||||
{defaultTitle}
|
{defaultTitle}
|
||||||
</h5>
|
</h5>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ type Props = {
|
|||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
className?: string;
|
className?: string;
|
||||||
dropdownContainerClassName?: string;
|
dropdownContainerClassName?: string;
|
||||||
|
containerClassName?: string;
|
||||||
isLoading?: boolean;
|
isLoading?: boolean;
|
||||||
position?: "item-aligned" | "popper";
|
position?: "item-aligned" | "popper";
|
||||||
isDisabled?: boolean;
|
isDisabled?: boolean;
|
||||||
@@ -31,12 +32,13 @@ export const Select = forwardRef<HTMLButtonElement, SelectProps>(
|
|||||||
isDisabled,
|
isDisabled,
|
||||||
dropdownContainerClassName,
|
dropdownContainerClassName,
|
||||||
position,
|
position,
|
||||||
|
containerClassName,
|
||||||
...props
|
...props
|
||||||
},
|
},
|
||||||
ref
|
ref
|
||||||
): JSX.Element => {
|
): JSX.Element => {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center space-x-2">
|
<div className={twMerge("flex items-center space-x-2", containerClassName)}>
|
||||||
<SelectPrimitive.Root
|
<SelectPrimitive.Root
|
||||||
{...props}
|
{...props}
|
||||||
onValueChange={(value) => {
|
onValueChange={(value) => {
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ export type { ProjectPermissionSet, TProjectPermission } from "./types";
|
|||||||
export {
|
export {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionCmekActions,
|
ProjectPermissionCmekActions,
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
ProjectPermissionSub
|
ProjectPermissionSub
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|||||||
@@ -7,6 +7,14 @@ export enum ProjectPermissionActions {
|
|||||||
Delete = "delete"
|
Delete = "delete"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum ProjectPermissionDynamicSecretActions {
|
||||||
|
ReadRootCredential = "read-root-credential",
|
||||||
|
CreateRootCredential = "create-root-credential",
|
||||||
|
EditRootCredential = "edit-root-credential",
|
||||||
|
DeleteRootCredential = "delete-root-credential",
|
||||||
|
Lease = "lease"
|
||||||
|
}
|
||||||
|
|
||||||
export enum ProjectPermissionCmekActions {
|
export enum ProjectPermissionCmekActions {
|
||||||
Read = "read",
|
Read = "read",
|
||||||
Create = "create",
|
Create = "create",
|
||||||
@@ -21,7 +29,7 @@ export enum PermissionConditionOperators {
|
|||||||
$ALL = "$all",
|
$ALL = "$all",
|
||||||
$REGEX = "$regex",
|
$REGEX = "$regex",
|
||||||
$EQ = "$eq",
|
$EQ = "$eq",
|
||||||
$NEQ = "$neq",
|
$NEQ = "$ne",
|
||||||
$GLOB = "$glob"
|
$GLOB = "$glob"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +45,7 @@ export type TPermissionConditionOperators = {
|
|||||||
export type TPermissionCondition = Record<
|
export type TPermissionCondition = Record<
|
||||||
string,
|
string,
|
||||||
| string
|
| string
|
||||||
| { $in: string[]; $all: string[]; $regex: string; $eq: string; $neq: string; $glob: string }
|
| { $in: string[]; $all: string[]; $regex: string; $eq: string; $ne: string; $glob: string }
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export enum ProjectPermissionSub {
|
export enum ProjectPermissionSub {
|
||||||
@@ -52,9 +60,11 @@ export enum ProjectPermissionSub {
|
|||||||
Tags = "tags",
|
Tags = "tags",
|
||||||
AuditLogs = "audit-logs",
|
AuditLogs = "audit-logs",
|
||||||
IpAllowList = "ip-allowlist",
|
IpAllowList = "ip-allowlist",
|
||||||
Workspace = "workspace",
|
Project = "workspace",
|
||||||
Secrets = "secrets",
|
Secrets = "secrets",
|
||||||
SecretFolders = "secret-folders",
|
SecretFolders = "secret-folders",
|
||||||
|
SecretImports = "secret-imports",
|
||||||
|
DynamicSecrets = "dynamic-secrets",
|
||||||
SecretRollback = "secret-rollback",
|
SecretRollback = "secret-rollback",
|
||||||
SecretApproval = "secret-approval",
|
SecretApproval = "secret-approval",
|
||||||
SecretRotation = "secret-rotation",
|
SecretRotation = "secret-rotation",
|
||||||
@@ -68,7 +78,24 @@ export enum ProjectPermissionSub {
|
|||||||
Cmek = "cmek"
|
Cmek = "cmek"
|
||||||
}
|
}
|
||||||
|
|
||||||
type SubjectFields = {
|
export type SecretSubjectFields = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
secretName: string;
|
||||||
|
secretTags: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SecretFolderSubjectFields = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DynamicSecretSubjectFields = {
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SecretImportSubjectFields = {
|
||||||
environment: string;
|
environment: string;
|
||||||
secretPath: string;
|
secretPath: string;
|
||||||
};
|
};
|
||||||
@@ -76,13 +103,30 @@ type SubjectFields = {
|
|||||||
export type ProjectPermissionSet =
|
export type ProjectPermissionSet =
|
||||||
| [
|
| [
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub.Secrets | (ForcedSubject<ProjectPermissionSub.Secrets> & SubjectFields)
|
(
|
||||||
|
| ProjectPermissionSub.Secrets
|
||||||
|
| (ForcedSubject<ProjectPermissionSub.Secrets> & SecretSubjectFields)
|
||||||
|
)
|
||||||
]
|
]
|
||||||
| [
|
| [
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
(
|
(
|
||||||
| ProjectPermissionSub.SecretFolders
|
| ProjectPermissionSub.SecretFolders
|
||||||
| (ForcedSubject<ProjectPermissionSub.SecretFolders> & SubjectFields)
|
| (ForcedSubject<ProjectPermissionSub.SecretFolders> & SecretFolderSubjectFields)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
| [
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
|
(
|
||||||
|
| ProjectPermissionSub.DynamicSecrets
|
||||||
|
| (ForcedSubject<ProjectPermissionSub.DynamicSecrets> & DynamicSecretSubjectFields)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
| [
|
||||||
|
ProjectPermissionActions,
|
||||||
|
(
|
||||||
|
| ProjectPermissionSub.SecretImports
|
||||||
|
| (ForcedSubject<ProjectPermissionSub.SecretImports> & SecretImportSubjectFields)
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Role]
|
| [ProjectPermissionActions, ProjectPermissionSub.Role]
|
||||||
@@ -95,19 +139,19 @@ export type ProjectPermissionSet =
|
|||||||
| [ProjectPermissionActions, ProjectPermissionSub.Environments]
|
| [ProjectPermissionActions, ProjectPermissionSub.Environments]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.IpAllowList]
|
| [ProjectPermissionActions, ProjectPermissionSub.IpAllowList]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Settings]
|
| [ProjectPermissionActions, ProjectPermissionSub.Settings]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Identity]
|
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.ServiceTokens]
|
| [ProjectPermissionActions, ProjectPermissionSub.ServiceTokens]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.SecretApproval]
|
| [ProjectPermissionActions, ProjectPermissionSub.SecretApproval]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.SecretRotation]
|
| [ProjectPermissionActions, ProjectPermissionSub.SecretRotation]
|
||||||
|
| [ProjectPermissionActions, ProjectPermissionSub.Identity]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities]
|
| [ProjectPermissionActions, ProjectPermissionSub.CertificateAuthorities]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.Certificates]
|
| [ProjectPermissionActions, ProjectPermissionSub.Certificates]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.CertificateTemplates]
|
| [ProjectPermissionActions, ProjectPermissionSub.CertificateTemplates]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts]
|
| [ProjectPermissionActions, ProjectPermissionSub.PkiAlerts]
|
||||||
| [ProjectPermissionActions, ProjectPermissionSub.PkiCollections]
|
| [ProjectPermissionActions, ProjectPermissionSub.PkiCollections]
|
||||||
| [ProjectPermissionActions.Delete, ProjectPermissionSub.Workspace]
|
| [ProjectPermissionActions.Delete, ProjectPermissionSub.Project]
|
||||||
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Workspace]
|
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Project]
|
||||||
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
|
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
|
||||||
| [ProjectPermissionActions.Create, ProjectPermissionSub.SecretRollback]
|
| [ProjectPermissionActions.Create, ProjectPermissionSub.SecretRollback]
|
||||||
| [ProjectPermissionCmekActions, ProjectPermissionSub.Cmek];
|
| [ProjectPermissionCmekActions, ProjectPermissionSub.Cmek]
|
||||||
|
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Kms];
|
||||||
export type TProjectPermission = MongoAbility<ProjectPermissionSet>;
|
export type TProjectPermission = MongoAbility<ProjectPermissionSet>;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export type { TProjectPermission } from "./ProjectPermissionContext";
|
|||||||
export {
|
export {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionCmekActions,
|
ProjectPermissionCmekActions,
|
||||||
|
ProjectPermissionDynamicSecretActions,
|
||||||
ProjectPermissionProvider,
|
ProjectPermissionProvider,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
useProjectPermission
|
useProjectPermission
|
||||||
|
|||||||
@@ -4,5 +4,17 @@ enum OrgMembershipRole {
|
|||||||
NoAccess = "no-access"
|
NoAccess = "no-access"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum ProjectMemberRole {
|
||||||
|
Admin = "admin",
|
||||||
|
Member = "member",
|
||||||
|
Viewer = "viewer",
|
||||||
|
NoAccess = "no-access"
|
||||||
|
}
|
||||||
|
|
||||||
export const isCustomOrgRole = (slug: string) =>
|
export const isCustomOrgRole = (slug: string) =>
|
||||||
!Object.values(OrgMembershipRole).includes(slug as OrgMembershipRole);
|
!Object.values(OrgMembershipRole).includes(slug as OrgMembershipRole);
|
||||||
|
|
||||||
|
export const formatProjectRoleName = (name: string) => {
|
||||||
|
if (name === ProjectMemberRole.Member) return "developer";
|
||||||
|
return name;
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,31 +1,29 @@
|
|||||||
import { ComponentType } from "react";
|
import { ComponentType } from "react";
|
||||||
import { Abilities, AbilityTuple, Generics, SubjectType } from "@casl/ability";
|
import { AbilityTuple } from "@casl/ability";
|
||||||
import { faLock } from "@fortawesome/free-solid-svg-icons";
|
import { faLock } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { twMerge } from "tailwind-merge";
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
import { TProjectPermission, useProjectPermission } from "@app/context";
|
import { useProjectPermission } from "@app/context";
|
||||||
|
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext";
|
||||||
|
|
||||||
type Props<T extends Abilities> = (T extends AbilityTuple
|
type Props<T extends AbilityTuple> = {
|
||||||
? {
|
className?: string;
|
||||||
action: T[0];
|
containerClassName?: string;
|
||||||
subject: Extract<T[1], SubjectType>;
|
action: T[0];
|
||||||
}
|
subject: T[1];
|
||||||
: {
|
};
|
||||||
action: string;
|
|
||||||
subject: string;
|
|
||||||
}) & { className?: string; containerClassName?: string };
|
|
||||||
|
|
||||||
export const withProjectPermission = <T extends {}, J extends TProjectPermission>(
|
export const withProjectPermission = <T extends {}>(
|
||||||
Component: ComponentType<T>,
|
Component: ComponentType<Omit<Props<ProjectPermissionSet>, "action" | "subject"> & T>,
|
||||||
{ action, subject, className, containerClassName }: Props<Generics<J>["abilities"]>
|
{ action, subject, className, containerClassName }: Props<ProjectPermissionSet>
|
||||||
) => {
|
) => {
|
||||||
const HOC = (hocProps: T) => {
|
const HOC = (hocProps: Omit<Props<ProjectPermissionSet>, "action" | "subject"> & T) => {
|
||||||
const { permission } = useProjectPermission();
|
const { permission } = useProjectPermission();
|
||||||
|
|
||||||
// akhilmhdh: Set as any due to casl/react ts type bug
|
// akhilmhdh: Set as any due to casl/react ts type bug
|
||||||
// REASON: casl due to its type checking can't seem to union even if union intersection is applied
|
// REASON: casl due to its type checking can't seem to union even if union intersection is applied
|
||||||
if (permission.cannot(action as any, subject)) {
|
if (permission.cannot(action as any, subject as any)) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={twMerge(
|
className={twMerge(
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
} from "@app/hooks/api/dashboard/types";
|
} from "@app/hooks/api/dashboard/types";
|
||||||
import { OrderByDirection } from "@app/hooks/api/generic/types";
|
import { OrderByDirection } from "@app/hooks/api/generic/types";
|
||||||
import { mergePersonalSecrets } from "@app/hooks/api/secrets/queries";
|
import { mergePersonalSecrets } from "@app/hooks/api/secrets/queries";
|
||||||
|
import { unique } from "@app/lib/fn/array";
|
||||||
|
|
||||||
export const dashboardKeys = {
|
export const dashboardKeys = {
|
||||||
all: () => ["dashboard"] as const,
|
all: () => ["dashboard"] as const,
|
||||||
@@ -154,10 +155,20 @@ export const useGetProjectSecretsOverview = (
|
|||||||
},
|
},
|
||||||
select: useCallback((data: Awaited<ReturnType<typeof fetchProjectSecretsOverview>>) => {
|
select: useCallback((data: Awaited<ReturnType<typeof fetchProjectSecretsOverview>>) => {
|
||||||
const { secrets, ...select } = data;
|
const { secrets, ...select } = data;
|
||||||
|
const uniqueSecrets = secrets ? unique(secrets, (i) => i.secretKey) : [];
|
||||||
|
|
||||||
|
const uniqueFolders = select.folders ? unique(select.folders, (i) => i.name) : [];
|
||||||
|
|
||||||
|
const uniqueDynamicSecrets = select.dynamicSecrets
|
||||||
|
? unique(select.dynamicSecrets, (i) => i.name)
|
||||||
|
: [];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...select,
|
...select,
|
||||||
secrets: secrets ? mergePersonalSecrets(secrets) : undefined
|
secrets: secrets ? mergePersonalSecrets(secrets) : undefined,
|
||||||
|
totalUniqueSecretsInPage: uniqueSecrets.length,
|
||||||
|
totalUniqueDynamicSecretsInPage: uniqueDynamicSecrets.length,
|
||||||
|
totalUniqueFoldersInPage: uniqueFolders.length
|
||||||
};
|
};
|
||||||
}, []),
|
}, []),
|
||||||
keepPreviousData: true
|
keepPreviousData: true
|
||||||
|
|||||||
@@ -12,6 +12,9 @@ export type DashboardProjectSecretsOverviewResponse = {
|
|||||||
totalFolderCount?: number;
|
totalFolderCount?: number;
|
||||||
totalDynamicSecretCount?: number;
|
totalDynamicSecretCount?: number;
|
||||||
totalCount: number;
|
totalCount: number;
|
||||||
|
totalUniqueSecretsInPage: number;
|
||||||
|
totalUniqueDynamicSecretsInPage: number;
|
||||||
|
totalUniqueFoldersInPage: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type DashboardProjectSecretsDetailsResponse = {
|
export type DashboardProjectSecretsDetailsResponse = {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { TOrgRole } from "../roles/types";
|
import { TOrgRole } from "../roles/types";
|
||||||
import { Workspace } from "../workspace/types";
|
import { ProjectUserMembershipTemporaryMode, Workspace } from "../workspace/types";
|
||||||
import { IdentityAuthMethod } from "./enums";
|
import { IdentityAuthMethod } from "./enums";
|
||||||
|
|
||||||
export type IdentityTrustedIp = {
|
export type IdentityTrustedIp = {
|
||||||
@@ -66,7 +66,7 @@ export type IdentityMembership = {
|
|||||||
| {
|
| {
|
||||||
isTemporary: true;
|
isTemporary: true;
|
||||||
temporaryRange: string;
|
temporaryRange: string;
|
||||||
temporaryMode: string;
|
temporaryMode: ProjectUserMembershipTemporaryMode;
|
||||||
temporaryAccessEndTime: string;
|
temporaryAccessEndTime: string;
|
||||||
temporaryAccessStartTime: string;
|
temporaryAccessStartTime: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,16 +15,11 @@ export const useCreateIdentityProjectAdditionalPrivilege = () => {
|
|||||||
|
|
||||||
return useMutation<TIdentityProjectPrivilege, {}, TCreateIdentityProjectPrivilegeDTO>({
|
return useMutation<TIdentityProjectPrivilege, {}, TCreateIdentityProjectPrivilegeDTO>({
|
||||||
mutationFn: async (dto) => {
|
mutationFn: async (dto) => {
|
||||||
const { data } = await apiRequest.post(
|
const { data } = await apiRequest.post("/api/v2/identity-project-additional-privilege", dto);
|
||||||
"/api/v1/additional-privilege/identity/permanent",
|
|
||||||
dto
|
|
||||||
);
|
|
||||||
return data.privilege;
|
return data.privilege;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug, identityId }) => {
|
onSuccess: (_, { projectId, identityId }) => {
|
||||||
queryClient.invalidateQueries(
|
queryClient.invalidateQueries(identitiyProjectPrivilegeKeys.list({ projectId, identityId }));
|
||||||
identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -33,19 +28,22 @@ export const useUpdateIdentityProjectAdditionalPrivilege = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation<TIdentityProjectPrivilege, {}, TUpdateIdentityProjectPrivlegeDTO>({
|
return useMutation<TIdentityProjectPrivilege, {}, TUpdateIdentityProjectPrivlegeDTO>({
|
||||||
mutationFn: async ({ privilegeSlug, projectSlug, identityId, privilegeDetails }) => {
|
mutationFn: async ({ projectId, privilegeId, identityId, permissions, slug, type }) => {
|
||||||
const { data: res } = await apiRequest.patch("/api/v1/additional-privilege/identity", {
|
const { data: res } = await apiRequest.patch(
|
||||||
privilegeSlug,
|
`/api/v2/identity-project-additional-privilege/${privilegeId}`,
|
||||||
projectSlug,
|
{
|
||||||
identityId,
|
privilegeId,
|
||||||
privilegeDetails
|
projectId,
|
||||||
});
|
identityId,
|
||||||
|
permissions,
|
||||||
|
slug,
|
||||||
|
type
|
||||||
|
}
|
||||||
|
);
|
||||||
return res.privilege;
|
return res.privilege;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug, identityId }) => {
|
onSuccess: (_, { projectId, identityId }) => {
|
||||||
queryClient.invalidateQueries(
|
queryClient.invalidateQueries(identitiyProjectPrivilegeKeys.list({ projectId, identityId }));
|
||||||
identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -54,20 +52,21 @@ export const useDeleteIdentityProjectAdditionalPrivilege = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation<TIdentityProjectPrivilege, {}, TDeleteIdentityProjectPrivilegeDTO>({
|
return useMutation<TIdentityProjectPrivilege, {}, TDeleteIdentityProjectPrivilegeDTO>({
|
||||||
mutationFn: async ({ identityId, projectSlug, privilegeSlug }) => {
|
mutationFn: async ({ identityId, projectId, privilegeId }) => {
|
||||||
const { data } = await apiRequest.delete("/api/v1/additional-privilege/identity", {
|
const { data } = await apiRequest.delete(
|
||||||
data: {
|
`/api/v2/identity-project-additional-privilege/${privilegeId}`,
|
||||||
identityId,
|
{
|
||||||
projectSlug,
|
data: {
|
||||||
privilegeSlug
|
identityId,
|
||||||
|
privilegeId,
|
||||||
|
projectId
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
);
|
||||||
return data.privilege;
|
return data.privilege;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug, identityId }) => {
|
onSuccess: (_, { projectId, identityId }) => {
|
||||||
queryClient.invalidateQueries(
|
queryClient.invalidateQueries(identitiyProjectPrivilegeKeys.list({ projectId, identityId }));
|
||||||
identitiyProjectPrivilegeKeys.list({ projectSlug, identityId })
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,36 +9,36 @@ import {
|
|||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const identitiyProjectPrivilegeKeys = {
|
export const identitiyProjectPrivilegeKeys = {
|
||||||
details: ({ identityId, privilegeSlug, projectSlug }: TGetIdentityProjectPrivilegeDetails) =>
|
details: ({ identityId, privilegeId, projectId }: TGetIdentityProjectPrivilegeDetails) =>
|
||||||
[
|
[
|
||||||
"identity-user-privilege",
|
"identity-user-privilege",
|
||||||
{
|
{
|
||||||
identityId,
|
identityId,
|
||||||
projectSlug,
|
projectId,
|
||||||
privilegeSlug
|
privilegeId
|
||||||
}
|
}
|
||||||
] as const,
|
] as const,
|
||||||
list: ({ projectSlug, identityId }: TListIdentityProjectPrivileges) =>
|
list: ({ projectId, identityId }: TListIdentityProjectPrivileges) =>
|
||||||
["identity-user-privileges", { identityId, projectSlug }] as const
|
["identity-user-privileges", { identityId, projectId }] as const
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetIdentityProjectPrivilegeDetails = ({
|
export const useGetIdentityProjectPrivilegeDetails = ({
|
||||||
projectSlug,
|
projectId,
|
||||||
identityId,
|
identityId,
|
||||||
privilegeSlug
|
privilegeId
|
||||||
}: TGetIdentityProjectPrivilegeDetails) => {
|
}: TGetIdentityProjectPrivilegeDetails) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
enabled: Boolean(projectSlug && identityId && privilegeSlug),
|
enabled: Boolean(projectId && identityId && privilegeId),
|
||||||
queryKey: identitiyProjectPrivilegeKeys.details({ projectSlug, privilegeSlug, identityId }),
|
queryKey: identitiyProjectPrivilegeKeys.details({ projectId, privilegeId, identityId }),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const {
|
const {
|
||||||
data: { privilege }
|
data: { privilege }
|
||||||
} = await apiRequest.get<{
|
} = await apiRequest.get<{
|
||||||
privilege: TIdentityProjectPrivilege;
|
privilege: TIdentityProjectPrivilege;
|
||||||
}>(`/api/v1/additional-privilege/identity/${privilegeSlug}`, {
|
}>(`/api/v2/identity-project-additional-privilege/${privilegeId}`, {
|
||||||
params: {
|
params: {
|
||||||
identityId,
|
identityId,
|
||||||
projectSlug
|
projectId
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return privilege;
|
return privilege;
|
||||||
@@ -47,19 +47,19 @@ export const useGetIdentityProjectPrivilegeDetails = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const useListIdentityProjectPrivileges = ({
|
export const useListIdentityProjectPrivileges = ({
|
||||||
projectSlug,
|
projectId,
|
||||||
identityId
|
identityId
|
||||||
}: TListIdentityProjectPrivileges) => {
|
}: TListIdentityProjectPrivileges) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
enabled: Boolean(projectSlug && identityId),
|
enabled: Boolean(projectId && identityId),
|
||||||
queryKey: identitiyProjectPrivilegeKeys.list({ projectSlug, identityId }),
|
queryKey: identitiyProjectPrivilegeKeys.list({ projectId, identityId }),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const {
|
const {
|
||||||
data: { privileges }
|
data: { privileges }
|
||||||
} = await apiRequest.get<{
|
} = await apiRequest.get<{
|
||||||
privileges: Array<TIdentityProjectPrivilege>;
|
privileges: Array<TIdentityProjectPrivilege>;
|
||||||
}>("/api/v1/additional-privilege/identity", {
|
}>("/api/v2/identity-project-additional-privilege", {
|
||||||
params: { identityId, projectSlug }
|
params: { identityId, projectId }
|
||||||
});
|
});
|
||||||
return privileges;
|
return privileges;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,48 +28,42 @@ export type TIdentityProjectPrivilege = {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
export type TProjectSpecificPrivilegePermission = {
|
|
||||||
conditions: {
|
|
||||||
environment: string;
|
|
||||||
secretPath?: { $glob: string };
|
|
||||||
};
|
|
||||||
actions: string[];
|
|
||||||
subject: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TCreateIdentityProjectPrivilegeDTO = {
|
export type TCreateIdentityProjectPrivilegeDTO = {
|
||||||
identityId: string;
|
identityId: string;
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
isTemporary?: boolean;
|
type:
|
||||||
temporaryMode?: IdentityProjectAdditionalPrivilegeTemporaryMode;
|
| {
|
||||||
temporaryRange?: string;
|
isTemporary: true;
|
||||||
temporaryAccessStartTime?: string;
|
temporaryMode?: IdentityProjectAdditionalPrivilegeTemporaryMode;
|
||||||
privilegePermission: TProjectSpecificPrivilegePermission;
|
temporaryRange?: string;
|
||||||
|
temporaryAccessStartTime?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
isTemporary: false;
|
||||||
|
};
|
||||||
|
permissions: TProjectPermission[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TUpdateIdentityProjectPrivlegeDTO = {
|
export type TUpdateIdentityProjectPrivlegeDTO = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
identityId: string;
|
identityId: string;
|
||||||
privilegeSlug: string;
|
privilegeId: string;
|
||||||
privilegeDetails: Partial<
|
} & Partial<Omit<TCreateIdentityProjectPrivilegeDTO, "projectMembershipId" | "projectId">>;
|
||||||
Omit<TCreateIdentityProjectPrivilegeDTO, "projectMembershipId" | "projectId">
|
|
||||||
>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TDeleteIdentityProjectPrivilegeDTO = {
|
export type TDeleteIdentityProjectPrivilegeDTO = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
identityId: string;
|
identityId: string;
|
||||||
privilegeSlug: string;
|
privilegeId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TListIdentityUserPrivileges = {
|
export type TListIdentityUserPrivileges = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
identityId: string;
|
identityId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TGetIdentityProejctPrivilegeDetails = {
|
export type TGetIdentityProejctPrivilegeDetails = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
identityId: string;
|
identityId: string;
|
||||||
privilegeSlug: string;
|
privilegeId: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { packRules } from "@casl/ability/extra";
|
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
@@ -16,10 +15,7 @@ export const useCreateProjectUserAdditionalPrivilege = () => {
|
|||||||
|
|
||||||
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TCreateProjectUserPrivilegeDTO>({
|
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TCreateProjectUserPrivilegeDTO>({
|
||||||
mutationFn: async (dto) => {
|
mutationFn: async (dto) => {
|
||||||
const { data } = await apiRequest.post("/api/v1/additional-privilege/users/permanent", {
|
const { data } = await apiRequest.post("/api/v1/user-project-additional-privilege", dto);
|
||||||
...dto,
|
|
||||||
permissions: packRules(dto.permissions)
|
|
||||||
});
|
|
||||||
return data.privilege;
|
return data.privilege;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectMembershipId }) => {
|
onSuccess: (_, { projectMembershipId }) => {
|
||||||
@@ -34,8 +30,8 @@ export const useUpdateProjectUserAdditionalPrivilege = () => {
|
|||||||
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TUpdateProjectUserPrivlegeDTO>({
|
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TUpdateProjectUserPrivlegeDTO>({
|
||||||
mutationFn: async (dto) => {
|
mutationFn: async (dto) => {
|
||||||
const { data } = await apiRequest.patch(
|
const { data } = await apiRequest.patch(
|
||||||
`/api/v1/additional-privilege/users/${dto.privilegeId}`,
|
`/api/v1/user-project-additional-privilege/${dto.privilegeId}`,
|
||||||
{ ...dto, permissions: dto.permissions ? packRules(dto.permissions) : undefined }
|
dto
|
||||||
);
|
);
|
||||||
return data.privilege;
|
return data.privilege;
|
||||||
},
|
},
|
||||||
@@ -51,7 +47,7 @@ export const useDeleteProjectUserAdditionalPrivilege = () => {
|
|||||||
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TDeleteProjectUserPrivilegeDTO>({
|
return useMutation<{ privilege: TProjectUserPrivilege }, {}, TDeleteProjectUserPrivilegeDTO>({
|
||||||
mutationFn: async (dto) => {
|
mutationFn: async (dto) => {
|
||||||
const { data } = await apiRequest.delete(
|
const { data } = await apiRequest.delete(
|
||||||
`/api/v1/additional-privilege/users/${dto.privilegeId}`
|
`/api/v1/user-project-additional-privilege/${dto.privilegeId}`
|
||||||
);
|
);
|
||||||
return data.privilege;
|
return data.privilege;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { PackRule, unpackRules } from "@casl/ability/extra";
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
@@ -16,12 +15,9 @@ const fetchProjectUserPrivilegeDetails = async (privilegeId: string) => {
|
|||||||
const {
|
const {
|
||||||
data: { privilege }
|
data: { privilege }
|
||||||
} = await apiRequest.get<{
|
} = await apiRequest.get<{
|
||||||
privilege: Omit<TProjectUserPrivilege, "permissions"> & { permissions: unknown };
|
privilege: Omit<TProjectUserPrivilege, "permissions"> & { permissions: TProjectPermission[] };
|
||||||
}>(`/api/v1/additional-privilege/users/${privilegeId}`);
|
}>(`/api/v1/user-project-additional-privilege/${privilegeId}`);
|
||||||
return {
|
return privilege;
|
||||||
...privilege,
|
|
||||||
permissions: unpackRules(privilege.permissions as PackRule<TProjectPermission>[])
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetProjectUserPrivilegeDetails = (privilegeId: string) => {
|
export const useGetProjectUserPrivilegeDetails = (privilegeId: string) => {
|
||||||
@@ -41,10 +37,10 @@ export const useListProjectUserPrivileges = (projectMembershipId: string) => {
|
|||||||
data: { privileges }
|
data: { privileges }
|
||||||
} = await apiRequest.get<{
|
} = await apiRequest.get<{
|
||||||
privileges: Array<Omit<TProjectUserPrivilege, "permissions"> & { permissions: unknown }>;
|
privileges: Array<Omit<TProjectUserPrivilege, "permissions"> & { permissions: unknown }>;
|
||||||
}>("/api/v1/additional-privilege/users", { params: { projectMembershipId } });
|
}>("/api/v1/user-project-additional-privilege", { params: { projectMembershipId } });
|
||||||
return privileges.map((el) => ({
|
return privileges.map((el) => ({
|
||||||
...el,
|
...el,
|
||||||
permissions: unpackRules(el.permissions as PackRule<TProjectPermission>[])
|
permissions: el.permissions as TProjectPermission[]
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,29 +12,35 @@ export type TProjectUserPrivilege = {
|
|||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
permissions?: TProjectPermission[];
|
permissions?: TProjectPermission[];
|
||||||
} & (
|
} & (
|
||||||
| {
|
| {
|
||||||
isTemporary: true;
|
isTemporary: true;
|
||||||
temporaryMode: string;
|
temporaryMode: string;
|
||||||
temporaryRange: string;
|
temporaryRange: string;
|
||||||
temporaryAccessStartTime: string;
|
temporaryAccessStartTime: string;
|
||||||
temporaryAccessEndTime?: string;
|
temporaryAccessEndTime?: string;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
isTemporary: false;
|
isTemporary: false;
|
||||||
temporaryMode?: null;
|
temporaryMode?: null;
|
||||||
temporaryRange?: null;
|
temporaryRange?: null;
|
||||||
temporaryAccessStartTime?: null;
|
temporaryAccessStartTime?: null;
|
||||||
temporaryAccessEndTime?: null;
|
temporaryAccessEndTime?: null;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
export type TCreateProjectUserPrivilegeDTO = {
|
export type TCreateProjectUserPrivilegeDTO = {
|
||||||
projectMembershipId: string;
|
projectMembershipId: string;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
isTemporary?: boolean;
|
type:
|
||||||
temporaryMode?: ProjectUserAdditionalPrivilegeTemporaryMode;
|
| {
|
||||||
temporaryRange?: string;
|
isTemporary: true;
|
||||||
temporaryAccessStartTime?: string;
|
temporaryMode?: ProjectUserAdditionalPrivilegeTemporaryMode;
|
||||||
|
temporaryRange?: string;
|
||||||
|
temporaryAccessStartTime?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
isTemporary: false;
|
||||||
|
};
|
||||||
permissions: TProjectPermission[];
|
permissions: TProjectPermission[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -19,14 +19,14 @@ export const useCreateProjectRole = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation<TProjectRole, {}, TCreateProjectRoleDTO>({
|
return useMutation<TProjectRole, {}, TCreateProjectRoleDTO>({
|
||||||
mutationFn: async ({ projectSlug, ...dto }: TCreateProjectRoleDTO) => {
|
mutationFn: async ({ projectId, ...dto }: TCreateProjectRoleDTO) => {
|
||||||
const {
|
const {
|
||||||
data: { role }
|
data: { role }
|
||||||
} = await apiRequest.post(`/api/v1/workspace/${projectSlug}/roles`, dto);
|
} = await apiRequest.post(`/api/v2/workspace/${projectId}/roles`, dto);
|
||||||
return role;
|
return role;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug }) => {
|
onSuccess: (_, { projectId }) => {
|
||||||
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectSlug));
|
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectId));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -35,14 +35,17 @@ export const useUpdateProjectRole = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation<TProjectRole, {}, TUpdateProjectRoleDTO>({
|
return useMutation<TProjectRole, {}, TUpdateProjectRoleDTO>({
|
||||||
mutationFn: async ({ id, projectSlug, ...dto }: TUpdateProjectRoleDTO) => {
|
mutationFn: async ({ id, projectId, ...dto }: TUpdateProjectRoleDTO) => {
|
||||||
const {
|
const {
|
||||||
data: { role }
|
data: { role }
|
||||||
} = await apiRequest.patch(`/api/v1/workspace/${projectSlug}/roles/${id}`, dto);
|
} = await apiRequest.patch(`/api/v2/workspace/${projectId}/roles/${id}`, dto);
|
||||||
return role;
|
return role;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug }) => {
|
onSuccess: (_, { projectId, slug }) => {
|
||||||
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectSlug));
|
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectId));
|
||||||
|
if (slug) {
|
||||||
|
queryClient.invalidateQueries(roleQueryKeys.getProjectRoleBySlug(projectId, slug));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -50,14 +53,14 @@ export const useUpdateProjectRole = () => {
|
|||||||
export const useDeleteProjectRole = () => {
|
export const useDeleteProjectRole = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation<TProjectRole, {}, TDeleteProjectRoleDTO>({
|
return useMutation<TProjectRole, {}, TDeleteProjectRoleDTO>({
|
||||||
mutationFn: async ({ projectSlug, id }: TDeleteProjectRoleDTO) => {
|
mutationFn: async ({ projectId, id }: TDeleteProjectRoleDTO) => {
|
||||||
const {
|
const {
|
||||||
data: { role }
|
data: { role }
|
||||||
} = await apiRequest.delete(`/api/v1/workspace/${projectSlug}/roles/${id}`);
|
} = await apiRequest.delete(`/api/v2/workspace/${projectId}/roles/${id}`);
|
||||||
return role;
|
return role;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { projectSlug }) => {
|
onSuccess: (_, { projectId }) => {
|
||||||
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectSlug));
|
queryClient.invalidateQueries(roleQueryKeys.getProjectRoles(projectId));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import picomatch from "picomatch";
|
|||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
import { OrgPermissionSet } from "@app/context/OrgPermissionContext/types";
|
import { OrgPermissionSet } from "@app/context/OrgPermissionContext/types";
|
||||||
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext/types";
|
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext/types";
|
||||||
|
import { groupBy } from "@app/lib/fn/array";
|
||||||
|
import { omit } from "@app/lib/fn/object";
|
||||||
|
|
||||||
import { OrgUser, TProjectMembership } from "../users/types";
|
import { OrgUser, TProjectMembership } from "../users/types";
|
||||||
import {
|
import {
|
||||||
@@ -36,9 +38,9 @@ const glob: JsInterpreter<FieldCondition<string>> = (node, object, context) => {
|
|||||||
const conditionsMatcher = buildMongoQueryMatcher({ $glob }, { glob });
|
const conditionsMatcher = buildMongoQueryMatcher({ $glob }, { glob });
|
||||||
|
|
||||||
export const roleQueryKeys = {
|
export const roleQueryKeys = {
|
||||||
getProjectRoles: (projectSlug: string) => ["roles", { projectSlug }] as const,
|
getProjectRoles: (projectId: string) => ["roles", { projectId }] as const,
|
||||||
getProjectRoleBySlug: (projectSlug: string, roleSlug: string) =>
|
getProjectRoleBySlug: (projectId: string, roleSlug: string) =>
|
||||||
["roles", { projectSlug, roleSlug }] as const,
|
["roles", { projectId, roleSlug }] as const,
|
||||||
getOrgRoles: (orgId: string) => ["org-roles", { orgId }] as const,
|
getOrgRoles: (orgId: string) => ["org-roles", { orgId }] as const,
|
||||||
getOrgRole: (orgId: string, roleId: string) => [{ orgId, roleId }, "org-role"] as const,
|
getOrgRole: (orgId: string, roleId: string) => [{ orgId, roleId }, "org-role"] as const,
|
||||||
getUserOrgPermissions: ({ orgId }: TGetUserOrgPermissionsDTO) =>
|
getUserOrgPermissions: ({ orgId }: TGetUserOrgPermissionsDTO) =>
|
||||||
@@ -49,28 +51,28 @@ export const roleQueryKeys = {
|
|||||||
|
|
||||||
export const getProjectRoles = async (projectId: string) => {
|
export const getProjectRoles = async (projectId: string) => {
|
||||||
const { data } = await apiRequest.get<{ roles: Array<Omit<TProjectRole, "permissions">> }>(
|
const { data } = await apiRequest.get<{ roles: Array<Omit<TProjectRole, "permissions">> }>(
|
||||||
`/api/v1/workspace/${projectId}/roles`
|
`/api/v2/workspace/${projectId}/roles`
|
||||||
);
|
);
|
||||||
return data.roles;
|
return data.roles;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetProjectRoles = (projectSlug: string) =>
|
export const useGetProjectRoles = (projectId: string) =>
|
||||||
useQuery({
|
useQuery({
|
||||||
queryKey: roleQueryKeys.getProjectRoles(projectSlug),
|
queryKey: roleQueryKeys.getProjectRoles(projectId),
|
||||||
queryFn: () => getProjectRoles(projectSlug),
|
queryFn: () => getProjectRoles(projectId),
|
||||||
enabled: Boolean(projectSlug)
|
enabled: Boolean(projectId)
|
||||||
});
|
});
|
||||||
|
|
||||||
export const useGetProjectRoleBySlug = (projectSlug: string, roleSlug: string) =>
|
export const useGetProjectRoleBySlug = (projectId: string, roleSlug: string) =>
|
||||||
useQuery({
|
useQuery({
|
||||||
queryKey: roleQueryKeys.getProjectRoleBySlug(projectSlug, roleSlug),
|
queryKey: roleQueryKeys.getProjectRoleBySlug(projectId, roleSlug),
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const { data } = await apiRequest.get<{ role: TProjectRole }>(
|
const { data } = await apiRequest.get<{ role: TProjectRole }>(
|
||||||
`/api/v1/workspace/${projectSlug}/roles/slug/${roleSlug}`
|
`/api/v2/workspace/${projectId}/roles/slug/${roleSlug}`
|
||||||
);
|
);
|
||||||
return data.role;
|
return data.role;
|
||||||
},
|
},
|
||||||
enabled: Boolean(projectSlug && roleSlug)
|
enabled: Boolean(projectId && roleSlug)
|
||||||
});
|
});
|
||||||
|
|
||||||
const getOrgRoles = async (orgId: string) => {
|
const getOrgRoles = async (orgId: string) => {
|
||||||
@@ -146,8 +148,32 @@ export const useGetUserProjectPermissions = ({ workspaceId }: TGetUserProjectPer
|
|||||||
enabled: Boolean(workspaceId),
|
enabled: Boolean(workspaceId),
|
||||||
select: (data) => {
|
select: (data) => {
|
||||||
const rule = unpackRules<RawRuleOf<MongoAbility<ProjectPermissionSet>>>(data.permissions);
|
const rule = unpackRules<RawRuleOf<MongoAbility<ProjectPermissionSet>>>(data.permissions);
|
||||||
const ability = createMongoAbility<ProjectPermissionSet>(rule, { conditionsMatcher });
|
const negatedRules = groupBy(
|
||||||
|
rule.filter((i) => i.inverted && i.conditions),
|
||||||
|
(i) => `${i.subject}-${JSON.stringify(i.conditions)}`
|
||||||
|
);
|
||||||
|
const ability = createMongoAbility<ProjectPermissionSet>(rule, {
|
||||||
|
// this allows in frontend to skip some rules using *
|
||||||
|
conditionsMatcher: (rules) => {
|
||||||
|
return (entity) => {
|
||||||
|
// skip validation if its negated rules
|
||||||
|
const isNegatedRule =
|
||||||
|
// eslint-disable-next-line no-underscore-dangle
|
||||||
|
negatedRules?.[`${entity.__caslSubjectType__}-${JSON.stringify(rules)}`];
|
||||||
|
if (isNegatedRule) {
|
||||||
|
const baseMatcher = conditionsMatcher(rules);
|
||||||
|
return baseMatcher(entity);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rulesStrippedOfWildcard = omit(
|
||||||
|
rules,
|
||||||
|
Object.keys(entity).filter((el) => entity[el]?.includes("*"))
|
||||||
|
);
|
||||||
|
const baseMatcher = conditionsMatcher(rulesStrippedOfWildcard);
|
||||||
|
return baseMatcher(entity);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
const membership = {
|
const membership = {
|
||||||
...data.membership,
|
...data.membership,
|
||||||
roles: data.membership.roles.map(({ role }) => role)
|
roles: data.membership.roles.map(({ role }) => role)
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ export type TPermission = {
|
|||||||
|
|
||||||
export type TProjectPermission = {
|
export type TProjectPermission = {
|
||||||
conditions?: Record<string, any>;
|
conditions?: Record<string, any>;
|
||||||
|
inverted?: boolean;
|
||||||
action: string | string[];
|
action: string | string[];
|
||||||
subject: string | string[];
|
subject: string | string[];
|
||||||
};
|
};
|
||||||
@@ -71,7 +72,7 @@ export type TDeleteOrgRoleDTO = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type TCreateProjectRoleDTO = {
|
export type TCreateProjectRoleDTO = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
name: string;
|
name: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -79,11 +80,11 @@ export type TCreateProjectRoleDTO = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type TUpdateProjectRoleDTO = {
|
export type TUpdateProjectRoleDTO = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
id: string;
|
id: string;
|
||||||
} & Partial<Omit<TCreateProjectRoleDTO, "orgId">>;
|
} & Partial<Omit<TCreateProjectRoleDTO, "orgId">>;
|
||||||
|
|
||||||
export type TDeleteProjectRoleDTO = {
|
export type TDeleteProjectRoleDTO = {
|
||||||
projectSlug: string;
|
projectId: string;
|
||||||
id: string;
|
id: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { UserWsKeyPair } from "../keys/types";
|
import { UserWsKeyPair } from "../keys/types";
|
||||||
|
import { ProjectUserMembershipTemporaryMode } from "../workspace/types";
|
||||||
|
|
||||||
export enum AuthMethod {
|
export enum AuthMethod {
|
||||||
EMAIL = "email",
|
EMAIL = "email",
|
||||||
@@ -85,6 +86,7 @@ export type TWorkspaceUser = {
|
|||||||
id: string;
|
id: string;
|
||||||
publicKey: string;
|
publicKey: string;
|
||||||
};
|
};
|
||||||
|
createdAt: string;
|
||||||
projectId: string;
|
projectId: string;
|
||||||
isGroupMember: boolean;
|
isGroupMember: boolean;
|
||||||
project: {
|
project: {
|
||||||
@@ -114,7 +116,7 @@ export type TWorkspaceUser = {
|
|||||||
customRoleSlug: string;
|
customRoleSlug: string;
|
||||||
isTemporary: true;
|
isTemporary: true;
|
||||||
temporaryRange: string;
|
temporaryRange: string;
|
||||||
temporaryMode: string;
|
temporaryMode: ProjectUserMembershipTemporaryMode;
|
||||||
temporaryAccessEndTime: string;
|
temporaryAccessEndTime: string;
|
||||||
temporaryAccessStartTime: string;
|
temporaryAccessStartTime: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,13 @@ export {
|
|||||||
useGetUserWorkspaces,
|
useGetUserWorkspaces,
|
||||||
useGetWorkspaceAuthorizations,
|
useGetWorkspaceAuthorizations,
|
||||||
useGetWorkspaceById,
|
useGetWorkspaceById,
|
||||||
|
useGetWorkspaceIdentityMembershipDetails,
|
||||||
useGetWorkspaceIdentityMemberships,
|
useGetWorkspaceIdentityMemberships,
|
||||||
useGetWorkspaceIndexStatus,
|
useGetWorkspaceIndexStatus,
|
||||||
useGetWorkspaceIntegrations,
|
useGetWorkspaceIntegrations,
|
||||||
useGetWorkspaceSecrets,
|
useGetWorkspaceSecrets,
|
||||||
useGetWorkspaceSlackConfig,
|
useGetWorkspaceSlackConfig,
|
||||||
|
useGetWorkspaceUserDetails,
|
||||||
useGetWorkspaceUsers,
|
useGetWorkspaceUsers,
|
||||||
useListWorkspaceCas,
|
useListWorkspaceCas,
|
||||||
useListWorkspaceCertificates,
|
useListWorkspaceCertificates,
|
||||||
@@ -36,6 +38,5 @@ export {
|
|||||||
useUpdateIdentityWorkspaceRole,
|
useUpdateIdentityWorkspaceRole,
|
||||||
useUpdateUserWorkspaceRole,
|
useUpdateUserWorkspaceRole,
|
||||||
useUpdateWsEnvironment,
|
useUpdateWsEnvironment,
|
||||||
useUpgradeProject
|
useUpgradeProject} from "./queries";
|
||||||
} from "./queries";
|
|
||||||
export { workspaceKeys } from "./query-keys";
|
export { workspaceKeys } from "./query-keys";
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { TCertificate } from "../certificates/types";
|
|||||||
import { TCertificateTemplate } from "../certificateTemplates/types";
|
import { TCertificateTemplate } from "../certificateTemplates/types";
|
||||||
import { TGroupMembership } from "../groups/types";
|
import { TGroupMembership } from "../groups/types";
|
||||||
import { identitiesKeys } from "../identities/queries";
|
import { identitiesKeys } from "../identities/queries";
|
||||||
import { TProjectIdentitiesList } from "../identities/types";
|
import { IdentityMembership, TProjectIdentitiesList } from "../identities/types";
|
||||||
import { IntegrationAuth } from "../integrationAuth/types";
|
import { IntegrationAuth } from "../integrationAuth/types";
|
||||||
import { TIntegration } from "../integrations/types";
|
import { TIntegration } from "../integrations/types";
|
||||||
import { TPkiAlert } from "../pkiAlerts/types";
|
import { TPkiAlert } from "../pkiAlerts/types";
|
||||||
@@ -365,6 +365,21 @@ export const useGetWorkspaceUsers = (workspaceId: string, includeGroupMembers?:
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const useGetWorkspaceUserDetails = (workspaceId: string, membershipId: string) => {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: workspaceKeys.getWorkspaceUserDetails(workspaceId, membershipId),
|
||||||
|
queryFn: async () => {
|
||||||
|
const {
|
||||||
|
data: { membership }
|
||||||
|
} = await apiRequest.get<{ membership: TWorkspaceUser }>(
|
||||||
|
`/api/v1/workspace/${workspaceId}/memberships/${membershipId}`
|
||||||
|
);
|
||||||
|
return membership;
|
||||||
|
},
|
||||||
|
enabled: Boolean(workspaceId) && Boolean(membershipId)
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export const useDeleteUserFromWorkspace = () => {
|
export const useDeleteUserFromWorkspace = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -405,8 +420,11 @@ export const useUpdateUserWorkspaceRole = () => {
|
|||||||
);
|
);
|
||||||
return membership;
|
return membership;
|
||||||
},
|
},
|
||||||
onSuccess: (_, { workspaceId }) => {
|
onSuccess: (_, { workspaceId, membershipId }) => {
|
||||||
queryClient.invalidateQueries(workspaceKeys.getWorkspaceUsers(workspaceId));
|
queryClient.invalidateQueries(workspaceKeys.getWorkspaceUsers(workspaceId));
|
||||||
|
queryClient.invalidateQueries(
|
||||||
|
workspaceKeys.getWorkspaceUserDetails(workspaceId, membershipId)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -459,6 +477,9 @@ export const useUpdateIdentityWorkspaceRole = () => {
|
|||||||
onSuccess: (_, { identityId, workspaceId }) => {
|
onSuccess: (_, { identityId, workspaceId }) => {
|
||||||
queryClient.invalidateQueries(workspaceKeys.getWorkspaceIdentityMemberships(workspaceId));
|
queryClient.invalidateQueries(workspaceKeys.getWorkspaceIdentityMemberships(workspaceId));
|
||||||
queryClient.invalidateQueries(identitiesKeys.getIdentityProjectMemberships(identityId));
|
queryClient.invalidateQueries(identitiesKeys.getIdentityProjectMemberships(identityId));
|
||||||
|
queryClient.invalidateQueries(
|
||||||
|
workspaceKeys.getWorkspaceIdentityMembershipDetails(workspaceId, identityId)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -535,6 +556,21 @@ export const useGetWorkspaceIdentityMemberships = (
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const useGetWorkspaceIdentityMembershipDetails = (projectId: string, identityId: string) => {
|
||||||
|
return useQuery({
|
||||||
|
enabled: Boolean(projectId && identityId),
|
||||||
|
queryKey: workspaceKeys.getWorkspaceIdentityMembershipDetails(projectId, identityId),
|
||||||
|
queryFn: async () => {
|
||||||
|
const {
|
||||||
|
data: { identityMembership }
|
||||||
|
} = await apiRequest.get<{ identityMembership: IdentityMembership }>(
|
||||||
|
`/api/v2/workspace/${projectId}/identity-memberships/${identityId}`
|
||||||
|
);
|
||||||
|
return identityMembership;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
export const useListWorkspaceGroups = (projectId: string) => {
|
export const useListWorkspaceGroups = (projectId: string) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId),
|
queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId),
|
||||||
|
|||||||
@@ -15,8 +15,12 @@ export const workspaceKeys = {
|
|||||||
getWorkspaceAuditLogs: (workspaceId: string) =>
|
getWorkspaceAuditLogs: (workspaceId: string) =>
|
||||||
[{ workspaceId }, "workspace-audit-logs"] as const,
|
[{ workspaceId }, "workspace-audit-logs"] as const,
|
||||||
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }, "workspace-users"] as const,
|
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }, "workspace-users"] as const,
|
||||||
|
getWorkspaceUserDetails: (workspaceId: string, membershipId: string) =>
|
||||||
|
[{ workspaceId, membershipId }, "workspace-user-details"] as const,
|
||||||
getWorkspaceIdentityMemberships: (workspaceId: string) =>
|
getWorkspaceIdentityMemberships: (workspaceId: string) =>
|
||||||
[{ workspaceId }, "workspace-identity-memberships"] as const,
|
[{ workspaceId }, "workspace-identity-memberships"] as const,
|
||||||
|
getWorkspaceIdentityMembershipDetails: (workspaceId: string, identityId: string) =>
|
||||||
|
[{ workspaceId, identityId }, "workspace-identity-membership-details"] as const,
|
||||||
// allows invalidation using above key without knowing params
|
// allows invalidation using above key without knowing params
|
||||||
getWorkspaceIdentityMembershipsWithParams: ({
|
getWorkspaceIdentityMembershipsWithParams: ({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
|
|||||||
@@ -13,3 +13,22 @@ export const groupBy = <T, Key extends string | number | symbol>(
|
|||||||
acc[groupId].push(item);
|
acc[groupId].push(item);
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as Record<Key, T[]>);
|
}, {} as Record<Key, T[]>);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Given a list of items returns a new list with only
|
||||||
|
* unique items. Accepts an optional identity function
|
||||||
|
* to convert each item in the list to a comparable identity
|
||||||
|
* value
|
||||||
|
*/
|
||||||
|
export const unique = <T, K extends string | number | symbol>(
|
||||||
|
array: readonly T[],
|
||||||
|
toKey?: (item: T) => K
|
||||||
|
): T[] => {
|
||||||
|
const valueMap = array.reduce((acc, item) => {
|
||||||
|
const key = toKey ? toKey(item) : (item as unknown as string | number | symbol);
|
||||||
|
if (acc[key]) return acc;
|
||||||
|
acc[key] = item;
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string | number | symbol, T>);
|
||||||
|
return Object.values(valueMap);
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* Omit a list of properties from an object
|
||||||
|
* returning a new object with the properties
|
||||||
|
* that remain
|
||||||
|
*/
|
||||||
|
export const omit = <T, TKeys extends keyof T>(obj: T, keys: TKeys[]): Omit<T, TKeys> => {
|
||||||
|
if (!obj) return {} as Omit<T, TKeys>;
|
||||||
|
if (!keys || keys.length === 0) return obj as Omit<T, TKeys>;
|
||||||
|
return keys.reduce(
|
||||||
|
(acc, key) => {
|
||||||
|
// Gross, I know, it's mutating the object, but we
|
||||||
|
// are allowing it in this very limited scope due
|
||||||
|
// to the performance implications of an omit func.
|
||||||
|
// Not a pattern or practice to use elsewhere.
|
||||||
|
delete acc[key];
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{ ...obj }
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import Head from "next/head";
|
||||||
|
|
||||||
|
import { IdentityDetailsPage } from "@app/views/Project/IdentityDetailsPage";
|
||||||
|
|
||||||
|
export default function ProjectIdentityDetailsPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>{t("common.head-title", { title: t("settings.members.title") })}</title>
|
||||||
|
<link rel="icon" href="/infisical.ico" />
|
||||||
|
</Head>
|
||||||
|
<IdentityDetailsPage />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ProjectIdentityDetailsPage.requireAuth = true;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import Head from "next/head";
|
||||||
|
|
||||||
|
import { MemberDetailsPage } from "@app/views/Project/MemberDetailsPage";
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>{t("common.head-title", { title: t("settings.members.title") })}</title>
|
||||||
|
<link rel="icon" href="/infisical.ico" />
|
||||||
|
</Head>
|
||||||
|
<MemberDetailsPage />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Page.requireAuth = true;
|
||||||
+2
-2
@@ -5,7 +5,7 @@ import { z } from "zod";
|
|||||||
|
|
||||||
import { createNotification } from "@app/components/notifications";
|
import { createNotification } from "@app/components/notifications";
|
||||||
import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2";
|
import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2";
|
||||||
import { useOrganization,useWorkspace } from "@app/context";
|
import { useOrganization, useWorkspace } from "@app/context";
|
||||||
import {
|
import {
|
||||||
useAddIdentityToWorkspace,
|
useAddIdentityToWorkspace,
|
||||||
useGetIdentityProjectMemberships,
|
useGetIdentityProjectMemberships,
|
||||||
@@ -50,7 +50,7 @@ export const IdentityAddToProjectModal = ({ identityId, popUp, handlePopUpToggle
|
|||||||
const projectId = watch("projectId");
|
const projectId = watch("projectId");
|
||||||
const { data: projectMemberships } = useGetIdentityProjectMemberships(identityId);
|
const { data: projectMemberships } = useGetIdentityProjectMemberships(identityId);
|
||||||
const { data: project } = useGetWorkspaceById(projectId);
|
const { data: project } = useGetWorkspaceById(projectId);
|
||||||
const { data: roles } = useGetProjectRoles(project?.slug ?? "");
|
const { data: roles } = useGetProjectRoles(project?.id ?? "");
|
||||||
|
|
||||||
const filteredWorkspaces = useMemo(() => {
|
const filteredWorkspaces = useMemo(() => {
|
||||||
const wsWorkspaceIds = new Map();
|
const wsWorkspaceIds = new Map();
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { useRouter } from "next/router";
|
||||||
|
import { faChevronLeft } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
|
||||||
|
import { createNotification } from "@app/components/notifications";
|
||||||
|
import { ProjectPermissionCan } from "@app/components/permissions";
|
||||||
|
import { Button, DeleteActionModal, EmptyState, Spinner } from "@app/components/v2";
|
||||||
|
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
|
||||||
|
import { withProjectPermission } from "@app/hoc";
|
||||||
|
import { usePopUp } from "@app/hooks";
|
||||||
|
import {
|
||||||
|
useDeleteIdentityFromWorkspace,
|
||||||
|
useGetWorkspaceIdentityMembershipDetails
|
||||||
|
} from "@app/hooks/api";
|
||||||
|
|
||||||
|
import { IdentityProjectAdditionalPrivilegeSection } from "./components/IdentityProjectAdditionalPrivilegeSection";
|
||||||
|
import { IdentityRoleDetailsSection } from "./components/IdentityRoleDetailsSection";
|
||||||
|
|
||||||
|
export const IdentityDetailsPage = withProjectPermission(
|
||||||
|
() => {
|
||||||
|
const router = useRouter();
|
||||||
|
const { currentWorkspace } = useWorkspace();
|
||||||
|
|
||||||
|
const workspaceId = currentWorkspace?.id || "";
|
||||||
|
const identityId = router.query.identityId as string;
|
||||||
|
|
||||||
|
const { data: identityMembershipDetails, isLoading: isMembershipDetailsLoading } =
|
||||||
|
useGetWorkspaceIdentityMembershipDetails(workspaceId, identityId);
|
||||||
|
|
||||||
|
const { mutateAsync: deleteMutateAsync, isLoading: isDeletingIdentity } =
|
||||||
|
useDeleteIdentityFromWorkspace();
|
||||||
|
|
||||||
|
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
|
||||||
|
"deleteIdentity",
|
||||||
|
"upgradePlan"
|
||||||
|
] as const);
|
||||||
|
|
||||||
|
const onRemoveIdentitySubmit = async () => {
|
||||||
|
try {
|
||||||
|
await deleteMutateAsync({
|
||||||
|
identityId,
|
||||||
|
workspaceId
|
||||||
|
});
|
||||||
|
createNotification({
|
||||||
|
text: "Successfully removed identity from project",
|
||||||
|
type: "success"
|
||||||
|
});
|
||||||
|
handlePopUpClose("deleteIdentity");
|
||||||
|
router.push(`/project/${workspaceId}/members?selectedTab=identities`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
const error = err as any;
|
||||||
|
const text = error?.response?.data?.message ?? "Failed to remove identity from project";
|
||||||
|
|
||||||
|
createNotification({
|
||||||
|
text,
|
||||||
|
type: "error"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isMembershipDetailsLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex w-full items-center justify-center p-24">
|
||||||
|
<Spinner />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto flex max-w-7xl flex-col justify-between bg-bunker-800 p-6 text-white">
|
||||||
|
<div className="mb-4">
|
||||||
|
<Button
|
||||||
|
variant="link"
|
||||||
|
type="submit"
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faChevronLeft} />}
|
||||||
|
onClick={() => {
|
||||||
|
router.push(`/project/${workspaceId}/members?selectedTab=identities`);
|
||||||
|
}}
|
||||||
|
className="mb-4"
|
||||||
|
>
|
||||||
|
Project Access Control
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{identityMembershipDetails ? (
|
||||||
|
<>
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
|
||||||
|
<div className="mb-4 flex items-center justify-between ">
|
||||||
|
<h3 className="text-xl font-semibold text-mineshaft-100">
|
||||||
|
Project Identity Access
|
||||||
|
</h3>
|
||||||
|
<div>
|
||||||
|
<ProjectPermissionCan
|
||||||
|
I={ProjectPermissionActions.Delete}
|
||||||
|
a={ProjectPermissionSub.Identity}
|
||||||
|
renderTooltip
|
||||||
|
allowedLabel="Remove from project"
|
||||||
|
>
|
||||||
|
{(isAllowed) => (
|
||||||
|
<Button
|
||||||
|
colorSchema="danger"
|
||||||
|
variant="outline_bg"
|
||||||
|
size="xs"
|
||||||
|
isDisabled={!isAllowed}
|
||||||
|
isLoading={isDeletingIdentity}
|
||||||
|
onClick={() => handlePopUpOpen("deleteIdentity")}
|
||||||
|
>
|
||||||
|
Remove Identity
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</ProjectPermissionCan>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-12">
|
||||||
|
<div>
|
||||||
|
<span className="text-xs font-semibold text-gray-400">Name</span>
|
||||||
|
{identityMembershipDetails && (
|
||||||
|
<p className="text-lg capitalize">
|
||||||
|
{identityMembershipDetails?.identity?.name}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 text-sm text-gray-400">
|
||||||
|
Joined on{" "}
|
||||||
|
{identityMembershipDetails?.createdAt &&
|
||||||
|
format(new Date(identityMembershipDetails?.createdAt || ""), "yyyy-MM-dd")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<IdentityRoleDetailsSection
|
||||||
|
identityMembershipDetails={identityMembershipDetails}
|
||||||
|
isMembershipDetailsLoading={isMembershipDetailsLoading}
|
||||||
|
/>
|
||||||
|
<IdentityProjectAdditionalPrivilegeSection
|
||||||
|
identityMembershipDetails={identityMembershipDetails}
|
||||||
|
/>
|
||||||
|
<DeleteActionModal
|
||||||
|
isOpen={popUp.deleteIdentity.isOpen}
|
||||||
|
title={`Are you sure want to remove ${identityMembershipDetails?.identity?.name} from the project?`}
|
||||||
|
onChange={(isOpen) => handlePopUpToggle("deleteIdentity", isOpen)}
|
||||||
|
deleteKey="remove"
|
||||||
|
onDeleteApproved={() => onRemoveIdentitySubmit()}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<EmptyState title="Error: Unable to find the identity." className="py-12" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
{
|
||||||
|
action: ProjectPermissionActions.Read,
|
||||||
|
subject: ProjectPermissionSub.Identity
|
||||||
|
}
|
||||||
|
);
|
||||||
+394
@@ -0,0 +1,394 @@
|
|||||||
|
import { Controller, FormProvider, useForm } from "react-hook-form";
|
||||||
|
import {
|
||||||
|
faCaretDown,
|
||||||
|
faChevronLeft,
|
||||||
|
faClock,
|
||||||
|
faPlus,
|
||||||
|
faSave
|
||||||
|
} from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { format, formatDistance } from "date-fns";
|
||||||
|
import ms from "ms";
|
||||||
|
import { twMerge } from "tailwind-merge";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { TtlFormLabel } from "@app/components/features";
|
||||||
|
import { createNotification } from "@app/components/notifications";
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
FormControl,
|
||||||
|
FormLabel,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
ModalContent,
|
||||||
|
ModalTrigger,
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
Tag,
|
||||||
|
Tooltip
|
||||||
|
} from "@app/components/v2";
|
||||||
|
import {
|
||||||
|
ProjectPermissionActions,
|
||||||
|
ProjectPermissionSub,
|
||||||
|
useProjectPermission,
|
||||||
|
useWorkspace
|
||||||
|
} from "@app/context";
|
||||||
|
import { usePopUp } from "@app/hooks";
|
||||||
|
import {
|
||||||
|
useCreateIdentityProjectAdditionalPrivilege,
|
||||||
|
useGetIdentityProjectPrivilegeDetails,
|
||||||
|
useUpdateIdentityProjectAdditionalPrivilege
|
||||||
|
} from "@app/hooks/api";
|
||||||
|
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/hooks/api/identityProjectAdditionalPrivilege/types";
|
||||||
|
import { GeneralPermissionPolicies } from "@app/views/Project/RolePage/components/RolePermissionsSection/components/GeneralPermissionPolicies";
|
||||||
|
import { NewPermissionRule } from "@app/views/Project/RolePage/components/RolePermissionsSection/components/NewPermissionRule";
|
||||||
|
import { PermissionEmptyState } from "@app/views/Project/RolePage/components/RolePermissionsSection/PermissionEmptyState";
|
||||||
|
import {
|
||||||
|
formRolePermission2API,
|
||||||
|
PROJECT_PERMISSION_OBJECT,
|
||||||
|
projectRoleFormSchema,
|
||||||
|
rolePermission2Form
|
||||||
|
} from "@app/views/Project/RolePage/components/RolePermissionsSection/ProjectRoleModifySection.utils";
|
||||||
|
import { renderConditionalComponents } from "@app/views/Project/RolePage/components/RolePermissionsSection/RolePermissionsSection";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
privilegeId?: string;
|
||||||
|
identityId: string;
|
||||||
|
onGoBack: () => void;
|
||||||
|
isDisabled?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const formSchema = z.object({
|
||||||
|
slug: z.string().optional(),
|
||||||
|
temporaryAccess: z
|
||||||
|
.discriminatedUnion("isTemporary", [
|
||||||
|
z.object({
|
||||||
|
isTemporary: z.literal(true),
|
||||||
|
temporaryRange: z.string().min(1),
|
||||||
|
temporaryAccessStartTime: z.string().datetime(),
|
||||||
|
temporaryAccessEndTime: z.string().datetime().nullable().optional()
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
isTemporary: z.literal(false)
|
||||||
|
})
|
||||||
|
])
|
||||||
|
.default({ isTemporary: false }),
|
||||||
|
permissions: projectRoleFormSchema.shape.permissions
|
||||||
|
});
|
||||||
|
|
||||||
|
type TFormSchema = z.infer<typeof formSchema>;
|
||||||
|
|
||||||
|
export const IdentityProjectAdditionalPrivilegeModifySection = ({
|
||||||
|
privilegeId = "",
|
||||||
|
onGoBack,
|
||||||
|
identityId,
|
||||||
|
isDisabled
|
||||||
|
}: Props) => {
|
||||||
|
const isCreate = !privilegeId;
|
||||||
|
const { currentWorkspace } = useWorkspace();
|
||||||
|
const { popUp, handlePopUpToggle } = usePopUp(["createPolicy"] as const);
|
||||||
|
const projectId = currentWorkspace?.id || "";
|
||||||
|
const { data: privilegeDetails, isLoading } = useGetIdentityProjectPrivilegeDetails({
|
||||||
|
identityId,
|
||||||
|
projectId,
|
||||||
|
privilegeId
|
||||||
|
});
|
||||||
|
const { permission } = useProjectPermission();
|
||||||
|
const isIdentityEditDisabled = permission.cannot(
|
||||||
|
ProjectPermissionActions.Edit,
|
||||||
|
ProjectPermissionSub.Identity
|
||||||
|
);
|
||||||
|
|
||||||
|
const form = useForm<TFormSchema>({
|
||||||
|
values: privilegeDetails
|
||||||
|
? {
|
||||||
|
...privilegeDetails,
|
||||||
|
permissions: rolePermission2Form(privilegeDetails.permissions),
|
||||||
|
temporaryAccess: privilegeDetails.isTemporary
|
||||||
|
? {
|
||||||
|
isTemporary: true,
|
||||||
|
temporaryRange: privilegeDetails.temporaryRange || "",
|
||||||
|
temporaryAccessEndTime: privilegeDetails.temporaryAccessEndTime || "",
|
||||||
|
temporaryAccessStartTime: privilegeDetails.temporaryAccessStartTime || ""
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
isTemporary: privilegeDetails.isTemporary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
resolver: zodResolver(formSchema)
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
handleSubmit,
|
||||||
|
formState: { isDirty, isSubmitting }
|
||||||
|
} = form;
|
||||||
|
|
||||||
|
const { mutateAsync: updateIdentityProjectAdditionalPrivilege } =
|
||||||
|
useUpdateIdentityProjectAdditionalPrivilege();
|
||||||
|
const { mutateAsync: createIdentityProjectAdditionalPrivilege } =
|
||||||
|
useCreateIdentityProjectAdditionalPrivilege();
|
||||||
|
|
||||||
|
const onSubmit = async (el: TFormSchema) => {
|
||||||
|
const accessType = !el.temporaryAccess.isTemporary
|
||||||
|
? { isTemporary: false as const }
|
||||||
|
: {
|
||||||
|
isTemporary: true as const,
|
||||||
|
temporaryMode: IdentityProjectAdditionalPrivilegeTemporaryMode.Relative,
|
||||||
|
temporaryRange: el.temporaryAccess.temporaryRange,
|
||||||
|
temporaryAccessStartTime: el.temporaryAccess.temporaryAccessStartTime
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isCreate) {
|
||||||
|
await createIdentityProjectAdditionalPrivilege({
|
||||||
|
permissions: formRolePermission2API(el.permissions),
|
||||||
|
identityId,
|
||||||
|
projectId,
|
||||||
|
slug: el.slug || undefined,
|
||||||
|
type: accessType
|
||||||
|
});
|
||||||
|
createNotification({ type: "success", text: "Successfully created privilege" });
|
||||||
|
} else {
|
||||||
|
if (!projectId || !privilegeDetails?.id) return;
|
||||||
|
await updateIdentityProjectAdditionalPrivilege({
|
||||||
|
privilegeId: privilegeDetails.id,
|
||||||
|
permissions: formRolePermission2API(el.permissions),
|
||||||
|
projectId,
|
||||||
|
identityId,
|
||||||
|
slug: el.slug || undefined,
|
||||||
|
type: accessType
|
||||||
|
});
|
||||||
|
createNotification({ type: "success", text: "Successfully updated privilege" });
|
||||||
|
}
|
||||||
|
onGoBack();
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
createNotification({ type: "error", text: "Failed to update privilege" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const privilegeTemporaryAccess = form.watch("temporaryAccess");
|
||||||
|
const isTemporary = privilegeTemporaryAccess?.isTemporary;
|
||||||
|
const isExpired =
|
||||||
|
privilegeTemporaryAccess?.isTemporary &&
|
||||||
|
new Date() > new Date(privilegeTemporaryAccess.temporaryAccessEndTime || "");
|
||||||
|
let text = "Permanent";
|
||||||
|
let toolTipText = "Non-Expiring Access";
|
||||||
|
|
||||||
|
if (isTemporary) {
|
||||||
|
if (isExpired) {
|
||||||
|
text = "Access Expired";
|
||||||
|
toolTipText = "Timed Access Expired";
|
||||||
|
} else {
|
||||||
|
text = formatDistance(
|
||||||
|
new Date(privilegeTemporaryAccess.temporaryAccessEndTime || ""),
|
||||||
|
new Date()
|
||||||
|
);
|
||||||
|
toolTipText = `Until ${format(
|
||||||
|
new Date(privilegeTemporaryAccess.temporaryAccessEndTime || ""),
|
||||||
|
"yyyy-MM-dd hh:mm:ss aaa"
|
||||||
|
)}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
onSubmit={handleSubmit(onSubmit)}
|
||||||
|
className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"
|
||||||
|
>
|
||||||
|
<FormProvider {...form}>
|
||||||
|
<div className="flex items-center justify-between border-b border-mineshaft-400 pb-2">
|
||||||
|
<Button
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faChevronLeft} />}
|
||||||
|
className="text-lg font-semibold text-mineshaft-100"
|
||||||
|
variant="link"
|
||||||
|
onClick={onGoBack}
|
||||||
|
>
|
||||||
|
Back
|
||||||
|
</Button>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
{isDirty && (
|
||||||
|
<Button
|
||||||
|
className="mr-4 text-mineshaft-300"
|
||||||
|
variant="link"
|
||||||
|
isDisabled={isSubmitting}
|
||||||
|
isLoading={isSubmitting}
|
||||||
|
onClick={onGoBack}
|
||||||
|
>
|
||||||
|
Discard
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center">
|
||||||
|
<Button
|
||||||
|
variant="outline_bg"
|
||||||
|
type="submit"
|
||||||
|
className={twMerge("h-10 rounded-r-none", isDirty && "bg-primary text-black")}
|
||||||
|
isDisabled={isSubmitting || !isDirty || isDisabled}
|
||||||
|
isLoading={isSubmitting}
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faSave} />}
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</Button>
|
||||||
|
<Modal
|
||||||
|
isOpen={popUp.createPolicy.isOpen}
|
||||||
|
onOpenChange={(isOpen) => handlePopUpToggle("createPolicy", isOpen)}
|
||||||
|
>
|
||||||
|
<ModalTrigger asChild>
|
||||||
|
<Button
|
||||||
|
className="h-10 rounded-l-none"
|
||||||
|
variant="outline_bg"
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
||||||
|
isDisabled={isDisabled}
|
||||||
|
>
|
||||||
|
New Policy
|
||||||
|
</Button>
|
||||||
|
</ModalTrigger>
|
||||||
|
<ModalContent title="New Policy" subTitle="Policies grant additional permissions.">
|
||||||
|
<NewPermissionRule onClose={() => handlePopUpToggle("createPolicy")} />
|
||||||
|
</ModalContent>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 border-b border-gray-800 p-4 pt-2 first:rounded-t-md last:rounded-b-md">
|
||||||
|
<div className="text-lg">Overview</div>
|
||||||
|
<p className="mb-4 text-sm text-mineshaft-300">
|
||||||
|
Additional privileges take precedence over roles when permissions conflict
|
||||||
|
</p>
|
||||||
|
<div className=" flex items-end space-x-6">
|
||||||
|
<div className="w-full max-w-md">
|
||||||
|
<Controller
|
||||||
|
control={form.control}
|
||||||
|
name="slug"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormControl label="Privilege Name" isOptional className="mb-0">
|
||||||
|
<Input {...field} />
|
||||||
|
</FormControl>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger disabled={isIdentityEditDisabled} asChild>
|
||||||
|
<div className="w-full max-w-md flex-grow">
|
||||||
|
<FormLabel label="Duration" />
|
||||||
|
<Tooltip content={toolTipText}>
|
||||||
|
<Button
|
||||||
|
variant="outline_bg"
|
||||||
|
leftIcon={isTemporary ? <FontAwesomeIcon icon={faClock} /> : undefined}
|
||||||
|
rightIcon={<FontAwesomeIcon icon={faCaretDown} className="ml-2" />}
|
||||||
|
isDisabled={isIdentityEditDisabled}
|
||||||
|
className={twMerge(
|
||||||
|
"w-full border-none bg-mineshaft-600 py-2.5 text-xs capitalize hover:bg-mineshaft-500",
|
||||||
|
isTemporary && "text-primary",
|
||||||
|
isExpired && "text-red-600"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{text}
|
||||||
|
</Button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent
|
||||||
|
arrowClassName="fill-gray-600"
|
||||||
|
side="right"
|
||||||
|
sideOffset={12}
|
||||||
|
hideCloseBtn
|
||||||
|
className="border border-gray-600 pt-4"
|
||||||
|
>
|
||||||
|
<div className="flex flex-col space-y-4">
|
||||||
|
<div className="border-b border-b-gray-700 pb-2 text-sm text-mineshaft-300">
|
||||||
|
Configure Timed Access
|
||||||
|
</div>
|
||||||
|
{isExpired && <Tag colorSchema="red">Expired</Tag>}
|
||||||
|
<Controller
|
||||||
|
control={form.control}
|
||||||
|
defaultValue="1h"
|
||||||
|
name="temporaryAccess.temporaryRange"
|
||||||
|
render={({ field, fieldState: { error } }) => (
|
||||||
|
<FormControl
|
||||||
|
label={<TtlFormLabel label="Validity" />}
|
||||||
|
isError={Boolean(error?.message)}
|
||||||
|
errorText={error?.message}
|
||||||
|
>
|
||||||
|
<Input {...field} />
|
||||||
|
</FormControl>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
onClick={() => {
|
||||||
|
const temporaryRange = form.getValues("temporaryAccess.temporaryRange");
|
||||||
|
if (!temporaryRange) {
|
||||||
|
form.setError(
|
||||||
|
"temporaryAccess.temporaryRange",
|
||||||
|
{ type: "required", message: "Required" },
|
||||||
|
{ shouldFocus: true }
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
form.clearErrors("temporaryAccess.temporaryRange");
|
||||||
|
form.setValue(
|
||||||
|
"temporaryAccess",
|
||||||
|
{
|
||||||
|
isTemporary: true,
|
||||||
|
temporaryAccessStartTime: new Date().toISOString(),
|
||||||
|
temporaryRange,
|
||||||
|
temporaryAccessEndTime: new Date(
|
||||||
|
new Date().getTime() + ms(temporaryRange)
|
||||||
|
).toISOString()
|
||||||
|
},
|
||||||
|
{ shouldDirty: true }
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isTemporary ? "Restart" : "Grant"}
|
||||||
|
</Button>
|
||||||
|
{isTemporary && (
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant="outline_bg"
|
||||||
|
colorSchema="danger"
|
||||||
|
onClick={() => {
|
||||||
|
form.setValue(
|
||||||
|
"temporaryAccess",
|
||||||
|
{
|
||||||
|
isTemporary: false
|
||||||
|
},
|
||||||
|
{ shouldDirty: true }
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Revoke Access
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<div className="mb-2 text-lg">Policies</div>
|
||||||
|
{(isCreate || !isLoading) && <PermissionEmptyState />}
|
||||||
|
{(Object.keys(PROJECT_PERMISSION_OBJECT) as ProjectPermissionSub[]).map((subject) => (
|
||||||
|
<GeneralPermissionPolicies
|
||||||
|
subject={subject}
|
||||||
|
actions={PROJECT_PERMISSION_OBJECT[subject].actions}
|
||||||
|
title={PROJECT_PERMISSION_OBJECT[subject].title}
|
||||||
|
key={`project-permission-${subject}`}
|
||||||
|
isDisabled={isDisabled}
|
||||||
|
>
|
||||||
|
{renderConditionalComponents(subject, isDisabled)}
|
||||||
|
</GeneralPermissionPolicies>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</FormProvider>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user