Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: updated the rollback to be aligned with our environment and path.

=d60f7d563c2b
diff --git a/backend/src/ee/routes/v1/snapshot-router.ts b/backend/src/ee/routes/v1/snapshot-router.ts
index c14d97192d..8c73adf5f6 100644
--- a/backend/src/ee/routes/v1/snapshot-router.ts
+++ b/backend/src/ee/routes/v1/snapshot-router.ts
@@ -84,19 +84,10 @@ export const registerSnapshotRouter = async (server: FastifyZodProvider) => {
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
+ handler: async () => {
throw new Error(
"This endpoint is deprecated. Please use the new PIT recovery system. More information is available at: https://infisical.com/docs/documentation/platform/pit-recovery."
);
-
- const secretSnapshot = await server.services.snapshot.rollbackSnapshot({
- actor: req.permission.type,
- actorId: req.permission.id,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- id: req.params.secretSnapshotId
- });
- return { secretSnapshot };
}
});
};
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index c4047c2fc4..b3bc08bfb9 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -475,6 +475,11 @@ export type SecretImportSubjectFields = {
secretPath: string;
};
+export type CommitsSubjectFields = {
+ environment: string;
+ secretPath: string;
+};
+
export type SecretRotationsSubjectFields = {
environment?: string;
secretPath?: string;
@@ -673,7 +678,10 @@ export type ProjectPermissionSet =
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
| [ProjectPermissionActions.Create, ProjectPermissionSub.SecretRollback]
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Kms]
- | [ProjectPermissionCommitsActions, ProjectPermissionSub.Commits]
+ | [
+ ProjectPermissionCommitsActions,
+ ProjectPermissionSub.Commits | (ForcedSubject<ProjectPermissionSub.Commits> & CommitsSubjectFields)
+ ]
| [ProjectPermissionSecretScanningDataSourceActions, ProjectPermissionSub.SecretScanningDataSources]
| [ProjectPermissionSecretScanningFindingActions, ProjectPermissionSub.SecretScanningFindings]
| [ProjectPermissionSecretScanningConfigActions, ProjectPermissionSub.SecretScanningConfigs]
@@ -913,6 +921,23 @@ const SecretImportConditionSchema = z
})
.partial();
+const CommitsConditionSchema = z
+ .object({
+ environment: 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()
+ ]),
+ secretPath: SECRET_PATH_PERMISSION_OPERATOR_SCHEMA
+ })
+ .partial();
+
const SecretConditionV2Schema = z
.object({
environment: z.union([
@@ -1730,9 +1755,13 @@ const GeneralPermissionSchema = [
}),
z.object({
subject: z.literal(ProjectPermissionSub.Commits).describe("The entity this permission pertains to."),
+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionCommitsActions).describe(
"Describe what action an entity can take."
- )
+ ),
+ conditions: CommitsConditionSchema.describe(
+ "When specified, only matching conditions will be allowed to access given resource."
+ ).optional()
}),
z.object({
subject: z
diff --git a/backend/src/ee/services/pit/pit-service.ts b/backend/src/ee/services/pit/pit-service.ts
index 02beef3357..0ca81def9e 100644
--- a/backend/src/ee/services/pit/pit-service.ts
+++ b/backend/src/ee/services/pit/pit-service.ts
@@ -1,5 +1,5 @@
/* eslint-disable no-await-in-loop */
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, subject } from "@casl/ability";
import { ActionProjectType } from "@app/db/schemas";
import { Event, EventType } from "@app/ee/services/audit-log/audit-log-types";
@@ -348,6 +348,11 @@ export const pitServiceFactory = ({
message?: string;
environment: string;
}) => {
+ const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(projectId, [folderId]);
+ if (!folderWithPath) {
+ throw new NotFoundError({ message: `Folder with ID ${folderId} not found` });
+ }
+
const { permission: userPermission } = await permissionService.getProjectPermission({
actor,
actorId,
@@ -359,7 +364,10 @@ export const pitServiceFactory = ({
ForbiddenError.from(userPermission).throwUnlessCan(
ProjectPermissionCommitsActions.PerformRollback,
- ProjectPermissionSub.Commits
+ subject(ProjectPermissionSub.Commits, {
+ environment,
+ secretPath: folderWithPath.path
+ })
);
const latestCommit = await folderCommitService.getLatestCommit({
diff --git a/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts b/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts
index d60f0f0a0c..ccd9b8177f 100644
--- a/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts
+++ b/backend/src/ee/services/secret-snapshot/secret-snapshot-service.ts
@@ -1,14 +1,12 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-argument */
// akhilmhdh: I did this, quite strange bug with eslint. Everything do have a type stil has this error
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, subject } from "@casl/ability";
-import { ActionProjectType, TableName, TSecretTagJunctionInsert, TSecretV2TagJunctionInsert } from "@app/db/schemas";
+import { ActionProjectType } from "@app/db/schemas";
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
import { InternalServerError, NotFoundError } from "@app/lib/errors";
-import { groupBy } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
-import { ActorType } from "@app/services/auth/auth-type";
-import { CommitType, TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";
+import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
@@ -30,16 +28,11 @@ import {
} from "../permission/permission-fns";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
import {
- ProjectPermissionActions,
+ ProjectPermissionCommitsActions,
ProjectPermissionSecretActions,
ProjectPermissionSub
} from "../permission/project-permission";
-import {
- TGetSnapshotDataDTO,
- TProjectSnapshotCountDTO,
- TProjectSnapshotListDTO,
- TRollbackSnapshotDTO
-} from "./secret-snapshot-types";
+import { TGetSnapshotDataDTO, TProjectSnapshotCountDTO, TProjectSnapshotListDTO } from "./secret-snapshot-types";
import { TSnapshotDALFactory } from "./snapshot-dal";
import { TSnapshotFolderDALFactory } from "./snapshot-folder-dal";
import { TSnapshotSecretDALFactory } from "./snapshot-secret-dal";
@@ -76,18 +69,12 @@ export const secretSnapshotServiceFactory = ({
snapshotSecretDAL,
snapshotFolderDAL,
folderDAL,
- secretDAL,
permissionService,
licenseService,
- secretTagDAL,
- secretVersionTagDAL,
secretVersionV2BridgeDAL,
- secretV2BridgeDAL,
snapshotSecretV2BridgeDAL,
- secretVersionV2TagBridgeDAL,
kmsService,
- projectBotService,
- folderCommitService
+ projectBotService
}: TSecretSnapshotServiceFactoryDep) => {
const projectSecretSnapshotCount = async ({
environment,
@@ -106,7 +93,13 @@ export const secretSnapshotServiceFactory = ({
actorOrgId,
actionProjectType: ActionProjectType.SecretManager
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ secretPath: path,
+ environment
+ })
+ );
// We need to check if the user has access to the secrets in the folder. If we don't do this, a user could theoretically access snapshot secret values even if they don't have read access to the secrets in the folder.
throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
@@ -143,7 +136,13 @@ export const secretSnapshotServiceFactory = ({
actorOrgId,
actionProjectType: ActionProjectType.SecretManager
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ secretPath: path,
+ environment
+ })
+ );
// We need to check if the user has access to the secrets in the folder. If we don't do this, a user could theoretically access snapshot secret values even if they don't have read access to the secrets in the folder.
throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
@@ -173,8 +172,6 @@ export const secretSnapshotServiceFactory = ({
actionProjectType: ActionProjectType.SecretManager
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
-
const shouldUseBridge = snapshot.projectVersion === 3;
let snapshotDetails;
if (shouldUseBridge) {
@@ -190,6 +187,14 @@ export const secretSnapshotServiceFactory = ({
envId: encryptedSnapshotDetails.environment.id
});
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ secretPath: fullFolderPath,
+ environment: encryptedSnapshotDetails.environment.slug
+ })
+ );
+
snapshotDetails = {
...encryptedSnapshotDetails,
secretVersions: encryptedSnapshotDetails.secretVersions.map((el) => {
@@ -233,6 +238,14 @@ export const secretSnapshotServiceFactory = ({
envId: encryptedSnapshotDetails.environment.id
});
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ secretPath: fullFolderPath,
+ environment: encryptedSnapshotDetails.environment.slug
+ })
+ );
+
const { botKey } = await projectBotService.getBotKey(snapshot.projectId);
if (!botKey)
throw new NotFoundError({ message: `Project bot key not found for project with ID '${snapshot.projectId}'` });
@@ -378,440 +391,10 @@ export const secretSnapshotServiceFactory = ({
}
};
- const rollbackSnapshot = async ({
- id: snapshotId,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId
- }: TRollbackSnapshotDTO) => {
- const snapshot = await snapshotDAL.findById(snapshotId);
- if (!snapshot) throw new NotFoundError({ message: `Snapshot with ID '${snapshotId}' not found` });
- const shouldUseBridge = snapshot.projectVersion === 3;
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- projectId: snapshot.projectId,
- actorAuthMethod,
- actorOrgId,
- actionProjectType: ActionProjectType.SecretManager
- });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionActions.Create,
- ProjectPermissionSub.SecretRollback
- );
-
- if (shouldUseBridge) {
- const rollback = await snapshotDAL.transaction(async (tx) => {
- const rollbackSnaps = await snapshotDAL.findRecursivelySnapshotsV2Bridge(snapshot.id, tx);
- const secretRotationIds = rollbackSnaps
- .flatMap((snap) => snap.secretVersions)
- .filter((el) => el.isRotatedSecret)
- .map((el) => el.secretId);
-
- const deletedSecretsChanges = new Map(); // secretId -> version info
- const deletedFoldersChanges = new Map(); // folderId -> version info
- const addedSecretsChanges = new Map(); // secretId -> version info
- const addedFoldersChanges = new Map(); // folderId -> version info
- const commitChanges: {
- type: string;
- secretVersionId?: string;
- folderVersionId?: string;
- isUpdate?: boolean;
- folderId?: string;
- }[] = [];
-
- // this will remove all secrets in current folder except rotated secrets which we ignore
- const deletedTopLevelSecs = await secretV2BridgeDAL.delete(
- {
- $complex: {
- operator: "and",
- value: [
- {
- operator: "eq",
- field: "folderId",
- value: snapshot.folderId
- },
- {
- operator: "notIn",
- field: "id",
- value: secretRotationIds
- }
- ]
- }
- },
- tx
- );
-
- await Promise.all(
- deletedTopLevelSecs.map(async (sec) => {
- const version = await secretVersionV2BridgeDAL.findOne({ secretId: sec.id, version: sec.version }, tx);
- deletedSecretsChanges.set(sec.id, {
- id: sec.id,
- version: sec.version,
- // Store the version ID if available from the snapshot
- versionId: version?.id
- });
- })
- );
-
- const deletedTopLevelSecsGroupById = groupBy(deletedTopLevelSecs, (item) => item.id);
-
- const deletedFoldersData = await folderDAL.delete({ parentId: snapshot.folderId, isReserved: false }, tx);
-
- await Promise.all(
- deletedFoldersData.map(async (folder) => {
- const version = await folderVersionDAL.findOne({ folderId: folder.id, version: folder.version }, tx);
- deletedFoldersChanges.set(folder.id, {
- id: folder.id,
- version: folder.version,
- // Store the version ID if available
- versionId: version?.id
- });
- })
- );
-
- // this will remove all secrets and folders on child
- // due to sql foreign key and link list connection removing the folders removes everything below too
- const deletedFolders = await folderDAL.delete({ parentId: snapshot.folderId, isReserved: false }, tx);
- const deletedTopLevelFolders = groupBy(
- deletedFolders.filter(({ parentId }) => parentId === snapshot.folderId),
- (item) => item.id
- );
- const folders = await folderDAL.insertMany(
- rollbackSnaps.flatMap(({ folderVersion, folderId }) =>
- folderVersion.map(({ name, id, latestFolderVersion }) => ({
- envId: snapshot.envId,
- id,
- // this means don't bump up the version if not root folder
- // because below ones can be same version as nothing changed
- version: deletedTopLevelFolders[folderId] ? latestFolderVersion + 1 : latestFolderVersion,
- name,
- parentId: folderId
- }))
- ),
- tx
- );
- const secrets = await secretV2BridgeDAL.insertMany(
- rollbackSnaps.flatMap(({ secretVersions, folderId }) =>
- secretVersions
- .filter((v) => !v.isRotatedSecret)
- .map(
- ({
- latestSecretVersion,
- version,
- updatedAt,
- createdAt,
- secretId,
- envId,
- id,
- tags,
- // exclude the bottom fields from the secret - they are for versioning only.
- userActorId,
- identityActorId,
- actorType,
- isRotatedSecret,
- ...el
- }) => ({
- ...el,
- id: secretId,
- version: deletedTopLevelSecsGroupById[secretId] ? latestSecretVersion + 1 : latestSecretVersion,
- folderId
- })
- )
- ),
- tx
- );
- const secretTagsToBeInsert: TSecretV2TagJunctionInsert[] = [];
- const secretVerTagToBeInsert: Record<string, string[]> = {};
- rollbackSnaps.forEach(({ secretVersions }) => {
- secretVersions.forEach((secVer) => {
- secVer.tags.forEach((tag) => {
- secretTagsToBeInsert.push({ secrets_v2Id: secVer.secretId, secret_tagsId: tag.id });
- if (!secretVerTagToBeInsert?.[secVer.secretId]) secretVerTagToBeInsert[secVer.secretId] = [];
- secretVerTagToBeInsert[secVer.secretId].push(tag.id);
- });
- });
- });
- await secretTagDAL.saveTagsToSecretV2(secretTagsToBeInsert, tx);
- const folderVersions = await folderVersionDAL.insertMany(
- folders.map(({ version, name, id, envId, description }) => ({
- name,
- version,
- folderId: id,
- envId,
- description
- })),
- tx
- );
-
- // Track added folders
- folderVersions.forEach((fv) => {
- addedFoldersChanges.set(fv.folderId, fv);
- });
-
- const userActorId = actor === ActorType.USER ? actorId : undefined;
- const identityActorId = actor !== ActorType.USER ? actorId : undefined;
- const actorType = actor || ActorType.PLATFORM;
-
- const secretVersions = await secretVersionV2BridgeDAL.insertMany(
- secrets.map(({ id, updatedAt, createdAt, ...el }) => ({
- ...el,
- secretId: id,
- userActorId,
- identityActorId,
- actorType
- })),
- tx
- );
-
- secretVersions.forEach((sv) => {
- addedSecretsChanges.set(sv.secretId, sv);
- });
-
- await secretVersionV2TagBridgeDAL.insertMany(
- secretVersions.flatMap(({ secretId, id }) =>
- secretVerTagToBeInsert?.[secretId]?.length
- ? secretVerTagToBeInsert[secretId].map((tagId) => ({
- [`${TableName.SecretTag}Id` as const]: tagId,
- [`${TableName.SecretVersionV2}Id` as const]: id
- }))
- : []
- ),
- tx
- );
-
- // Compute commit changes
- // Handle secrets
- deletedSecretsChanges.forEach((deletedInfo, secretId) => {
- const addedSecret = addedSecretsChanges.get(secretId);
- if (addedSecret) {
- // Secret was deleted and re-added - this is an update only if versions are different
- if (deletedInfo.versionId !== addedSecret.id) {
- commitChanges.push({
- type: CommitType.ADD, // In the commit system, updates are tracked as "add" with isUpdate=true
- secretVersionId: addedSecret.id,
- isUpdate: true
- });
- }
- // Remove from addedSecrets since we've handled it
- addedSecretsChanges.delete(secretId);
- } else if (deletedInfo.versionId) {
- // Secret was only deleted
- commitChanges.push({
- type: CommitType.DELETE,
- secretVersionId: deletedInfo.versionId
- });
- }
- });
- // Add remaining new secrets (not updates)
- addedSecretsChanges.forEach((addedSecret) => {
- commitChanges.push({
- type: CommitType.ADD,
- secretVersionId: addedSecret.id
- });
- });
-
- // Handle folders
- deletedFoldersChanges.forEach((deletedInfo, folderId) => {
- const addedFolder = addedFoldersChanges.get(folderId);
- if (addedFolder) {
- // Folder was deleted and re-added - this is an update only if versions are different
- if (deletedInfo.versionId !== addedFolder.id) {
- commitChanges.push({
- type: CommitType.ADD,
- folderVersionId: addedFolder.id,
- isUpdate: true
- });
- }
- // Remove from addedFolders since we've handled it
- addedFoldersChanges.delete(folderId);
- } else if (deletedInfo.versionId) {
- // Folder was only deleted
- commitChanges.push({
- type: CommitType.DELETE,
- folderVersionId: deletedInfo.versionId,
- folderId: deletedInfo.id
- });
- }
- });
-
- // Add remaining new folders (not updates)
- addedFoldersChanges.forEach((addedFolder) => {
- commitChanges.push({
- type: CommitType.ADD,
- folderVersionId: addedFolder.id
- });
- });
-
- const newSnapshot = await snapshotDAL.create(
- {
- folderId: snapshot.folderId,
- envId: snapshot.envId,
- parentFolderId: snapshot.parentFolderId
- },
- tx
- );
- const snapshotSecrets = await snapshotSecretV2BridgeDAL.insertMany(
- secretVersions
- .filter(({ secretId }) => Boolean(deletedTopLevelSecsGroupById?.[secretId]))
- .map(({ id }) => ({
- secretVersionId: id,
- envId: newSnapshot.envId,
- snapshotId: newSnapshot.id
- })),
- tx
- );
- const snapshotFolders = await snapshotFolderDAL.insertMany(
- folderVersions
- .filter(({ folderId }) => Boolean(deletedTopLevelFolders?.[folderId]))
- .map(({ id }) => ({
- folderVersionId: id,
- envId: newSnapshot.envId,
- snapshotId: newSnapshot.id
- })),
- tx
- );
- if (commitChanges.length > 0) {
- await folderCommitService.createCommit(
- {
- actor: {
- type: actorType,
- metadata: {
- id: userActorId || identityActorId
- }
- },
- message: "Rollback to snapshot",
- folderId: snapshot.folderId,
- changes: commitChanges
- },
- tx
- );
- }
-
- return { ...newSnapshot, snapshotSecrets, snapshotFolders };
- });
-
- return rollback;
- }
-
- const rollback = await snapshotDAL.transaction(async (tx) => {
- const rollbackSnaps = await snapshotDAL.findRecursivelySnapshots(snapshot.id, tx);
- // this will remove all secrets in current folder
- const deletedTopLevelSecs = await secretDAL.delete({ folderId: snapshot.folderId }, tx);
- const deletedTopLevelSecsGroupById = groupBy(deletedTopLevelSecs, (item) => item.id);
- // this will remove all secrets and folders on child
- // due to sql foreign key and link list connection removing the folders removes everything below too
- const deletedFolders = await folderDAL.delete({ parentId: snapshot.folderId, isReserved: false }, tx);
- const deletedTopLevelFolders = groupBy(
- deletedFolders.filter(({ parentId }) => parentId === snapshot.folderId),
- (item) => item.id
- );
- const folders = await folderDAL.insertMany(
- rollbackSnaps.flatMap(({ folderVersion, folderId }) =>
- folderVersion.map(({ name, id, latestFolderVersion }) => ({
- envId: snapshot.envId,
- id,
- // this means don't bump up the version if not root folder
- // because below ones can be same version as nothing changed
- version: deletedTopLevelFolders[folderId] ? latestFolderVersion + 1 : latestFolderVersion,
- name,
- parentId: folderId
- }))
- ),
- tx
- );
- const secrets = await secretDAL.insertMany(
- rollbackSnaps.flatMap(({ secretVersions, folderId }) =>
- secretVersions.map(
- ({ latestSecretVersion, version, updatedAt, createdAt, secretId, envId, id, tags, ...el }) => ({
- ...el,
- id: secretId,
- version: deletedTopLevelSecsGroupById[secretId] ? latestSecretVersion + 1 : latestSecretVersion,
- folderId
- })
- )
- ),
- tx
- );
- const secretTagsToBeInsert: TSecretTagJunctionInsert[] = [];
- const secretVerTagToBeInsert: Record<string, string[]> = {};
- rollbackSnaps.forEach(({ secretVersions }) => {
- secretVersions.forEach((secVer) => {
- secVer.tags.forEach((tag) => {
- secretTagsToBeInsert.push({ secretsId: secVer.secretId, secret_tagsId: tag.id });
- if (!secretVerTagToBeInsert?.[secVer.secretId]) secretVerTagToBeInsert[secVer.secretId] = [];
- secretVerTagToBeInsert[secVer.secretId].push(tag.id);
- });
- });
- });
- await secretTagDAL.saveTagsToSecret(secretTagsToBeInsert, tx);
- const folderVersions = await folderVersionDAL.insertMany(
- folders.map(({ version, name, id, envId, description }) => ({
- name,
- version,
- folderId: id,
- envId,
- description
- })),
- tx
- );
- const secretVersions = await secretVersionDAL.insertMany(
- secrets.map(({ id, updatedAt, createdAt, ...el }) => ({ ...el, secretId: id })),
- tx
- );
- await secretVersionTagDAL.insertMany(
- secretVersions.flatMap(({ secretId, id }) =>
- secretVerTagToBeInsert?.[secretId]?.length
- ? secretVerTagToBeInsert[secretId].map((tagId) => ({
- [`${TableName.SecretTag}Id` as const]: tagId,
- [`${TableName.SecretVersion}Id` as const]: id
- }))
- : []
- ),
- tx
- );
- const newSnapshot = await snapshotDAL.create(
- {
- folderId: snapshot.folderId,
- envId: snapshot.envId,
- parentFolderId: snapshot.parentFolderId
- },
- tx
- );
- const snapshotSecrets = await snapshotSecretDAL.insertMany(
- secretVersions
- .filter(({ secretId }) => Boolean(deletedTopLevelSecsGroupById?.[secretId]))
- .map(({ id }) => ({
- secretVersionId: id,
- envId: newSnapshot.envId,
- snapshotId: newSnapshot.id
- })),
- tx
- );
- const snapshotFolders = await snapshotFolderDAL.insertMany(
- folderVersions
- .filter(({ folderId }) => Boolean(deletedTopLevelFolders?.[folderId]))
- .map(({ id }) => ({
- folderVersionId: id,
- envId: newSnapshot.envId,
- snapshotId: newSnapshot.id
- })),
- tx
- );
-
- return { ...newSnapshot, snapshotSecrets, snapshotFolders };
- });
-
- return rollback;
- };
-
return {
performSnapshot,
projectSecretSnapshotCount,
listSnapshots,
- getSnapshotData,
- rollbackSnapshot
+ getSnapshotData
};
};
diff --git a/backend/src/services/folder-commit/folder-commit-service.ts b/backend/src/services/folder-commit/folder-commit-service.ts
index 5cd791188b..3c20c02d32 100644
--- a/backend/src/services/folder-commit/folder-commit-service.ts
+++ b/backend/src/services/folder-commit/folder-commit-service.ts
@@ -1,5 +1,5 @@
/* eslint-disable no-await-in-loop */
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, subject } from "@casl/ability";
import { Knex } from "knex";
import {
@@ -212,13 +212,17 @@ export const folderCommitServiceFactory = ({
actorId,
projectId,
actorAuthMethod,
- actorOrgId
+ actorOrgId,
+ environment,
+ secretPath
}: {
actor: ActorType;
actorId: string;
projectId: string;
actorAuthMethod: ActorAuthMethod;
actorOrgId: string;
+ environment: string;
+ secretPath: string;
}) => {
if (!permissionService) {
throw new Error("Permission service not initialized");
@@ -232,7 +236,10 @@ export const folderCommitServiceFactory = ({
actionProjectType: ActionProjectType.SecretManager
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCommitsActions.Read, ProjectPermissionSub.Commits);
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, { environment, secretPath })
+ );
};
/**
@@ -1447,14 +1454,27 @@ export const folderCommitServiceFactory = ({
projectId: string;
tx?: Knex;
}) => {
+ const commit = await folderCommitDAL.findById(commitId, tx, projectId);
+ if (!commit) {
+ throw new NotFoundError({ message: `Commit with ID ${commitId} not found` });
+ }
+
+ const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(projectId, [commit.folderId], tx);
+ if (!folderWithPath) {
+ throw new NotFoundError({ message: `Folder for commit ${commitId} not found` });
+ }
+
await checkProjectCommitReadPermission({
actor,
actorId,
actorAuthMethod,
actorOrgId,
- projectId
+ projectId,
+ environment: folderWithPath.environmentSlug,
+ secretPath: folderWithPath.path
});
- return folderCommitDAL.findById(commitId, tx, projectId);
+
+ return commit;
};
/**
@@ -1494,7 +1514,9 @@ export const folderCommitServiceFactory = ({
actorId,
actorAuthMethod,
actorOrgId,
- projectId
+ projectId,
+ environment,
+ secretPath: path
});
const folder = await folderDAL.findBySecretPath(projectId, environment, path);
if (!folder) {
@@ -1533,7 +1555,9 @@ export const folderCommitServiceFactory = ({
actorId,
actorAuthMethod,
actorOrgId,
- projectId
+ projectId,
+ environment,
+ secretPath: path
});
const folder = await folderDAL.findBySecretPath(projectId, environment, path);
@@ -1564,15 +1588,27 @@ export const folderCommitServiceFactory = ({
projectId: string;
commitId: string;
}) => {
+ const commit = await folderCommitDAL.findById(commitId, undefined, projectId);
+ if (!commit) {
+ throw new NotFoundError({ message: `Commit with ID ${commitId} not found` });
+ }
+
+ const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(projectId, [commit.folderId]);
+ if (!folderWithPath) {
+ throw new NotFoundError({ message: `Folder for commit ${commitId} not found` });
+ }
+
await checkProjectCommitReadPermission({
actor,
actorId,
actorAuthMethod,
actorOrgId,
- projectId
+ projectId,
+ environment: folderWithPath.environmentSlug,
+ secretPath: folderWithPath.path
});
+
const changes = await folderCommitChangesDAL.findByCommitId(commitId, projectId);
- const commit = await folderCommitDAL.findById(commitId, undefined, projectId);
const latestCommit = await folderCommitDAL.findLatestCommit(commit.folderId, projectId);
return { ...commit, changes, isLatest: commit.id === latestCommit?.id };
};
@@ -2046,13 +2082,21 @@ export const folderCommitServiceFactory = ({
actorOrgId: string;
projectId: string;
}) => {
+ const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(projectId, [folderId]);
+ if (!folderWithPath) {
+ throw new NotFoundError({ message: `Folder with ID ${folderId} not found` });
+ }
+
await checkProjectCommitReadPermission({
actor,
actorId,
actorAuthMethod,
actorOrgId,
- projectId
+ projectId,
+ environment: folderWithPath.environmentSlug,
+ secretPath: folderWithPath.path
});
+
return folderCommitDAL.findLatestCommit(folderId, projectId);
};
@@ -2079,6 +2123,18 @@ export const folderCommitServiceFactory = ({
if (!permissionService) {
throw new Error("Permission service not initialized");
}
+
+ // Get the commit to revert first to get folder info for permission check
+ const commitToRevert = await folderCommitDAL.findById(commitId, undefined, projectId);
+ if (!commitToRevert) {
+ throw new NotFoundError({ message: `Commit with ID ${commitId} not found` });
+ }
+
+ const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(projectId, [commitToRevert.folderId]);
+ if (!folderWithPath) {
+ throw new NotFoundError({ message: `Folder for commit ${commitId} not found` });
+ }
+
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
@@ -2090,23 +2146,23 @@ export const folderCommitServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCommitsActions.PerformRollback,
- ProjectPermissionSub.Commits
+ subject(ProjectPermissionSub.Commits, {
+ environment: folderWithPath.environmentSlug,
+ secretPath: folderWithPath.path
+ })
);
- // Check permissions first
+
+ // Check read permissions
await checkProjectCommitReadPermission({
actor,
actorId,
projectId,
actorAuthMethod,
- actorOrgId
+ actorOrgId,
+ environment: folderWithPath.environmentSlug,
+ secretPath: folderWithPath.path
});
- // Get the commit to revert
- const commitToRevert = await folderCommitDAL.findById(commitId, undefined, projectId);
- if (!commitToRevert) {
- throw new NotFoundError({ message: `Commit with ID ${commitId} not found` });
- }
-
const previousCommit = await folderCommitDAL.findCommitBefore(commitToRevert.folderId, commitToRevert.commitId);
if (!previousCommit) {
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index 8aa6e3f0c6..2ead3aa4d6 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -17,7 +17,6 @@ import {
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
- ProjectPermissionActions,
ProjectPermissionCommitsActions,
ProjectPermissionSecretActions,
ProjectPermissionSet,
@@ -2771,9 +2770,13 @@ export const secretV2BridgeServiceFactory = ({
actionProjectType: ActionProjectType.SecretManager
});
- const canRead =
- permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback) ||
- permission.can(ProjectPermissionCommitsActions.Read, ProjectPermissionSub.Commits);
+ const canRead = permission.can(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ environment: folder.environment.envSlug,
+ secretPath: folderWithPath.path
+ })
+ );
if (!canRead) throw new ForbiddenRequestError({ message: "You do not have permission to read secret versions" });
@@ -3828,9 +3831,13 @@ export const secretV2BridgeServiceFactory = ({
actionProjectType: ActionProjectType.SecretManager
});
- const canRead =
- permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback) ||
- permission.can(ProjectPermissionCommitsActions.Read, ProjectPermissionSub.Commits);
+ const canRead = permission.can(
+ ProjectPermissionCommitsActions.Read,
+ subject(ProjectPermissionSub.Commits, {
+ environment: environment.slug,
+ secretPath
+ })
+ );
if (!canRead) throw new ForbiddenRequestError({ message: "You do not have permission to read secret versions" });
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index a8c4580ad7..423abc6c4a 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -20,11 +20,7 @@ import {
throwIfMissingSecretReadValueOrDescribePermission
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import {
- ProjectPermissionActions,
- ProjectPermissionSecretActions,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
+import { ProjectPermissionSecretActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { TSecretApprovalPolicyServiceFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-service";
import { TSecretApprovalRequestDALFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-dal";
import { TSecretApprovalRequestSecretDALFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-secret-dal";
@@ -2636,96 +2632,18 @@ export const secretServiceFactory = ({
secretId,
secretVersions: filterSecretVersions
}: TGetSecretVersionsDTO) => {
- const secretVersionV2 = await secretV2BridgeService
- .getSecretVersions({
- actorId,
- actor,
- actorOrgId,
- actorAuthMethod,
- limit,
- offset,
- secretId,
- secretVersions: filterSecretVersions
- })
- .catch((err) => {
- if ((err as Error).message === "BadRequest: Failed to find secret") {
- return null;
- }
-
- logger.error(err);
- });
-
- if (secretVersionV2) return secretVersionV2;
-
- const secret = await secretDAL.findById(secretId);
- if (!secret) throw new NotFoundError({ message: `Secret with ID '${secretId}' not found` });
- const folder = await folderDAL.findById(secret.folderId);
- if (!folder) throw new NotFoundError({ message: `Folder with ID '${secret.folderId}' not found` });
-
- const [folderWithPath] = await folderDAL.findSecretPathByFolderIds(folder.projectId, [folder.id]);
-
- if (!folderWithPath) {
- throw new NotFoundError({ message: `Folder with ID '${folder.id}' not found` });
- }
-
- const { botKey } = await projectBotService.getBotKey(folder.projectId);
- if (!botKey)
- throw new NotFoundError({ message: `Project bot for project with ID '${folder.projectId}' not found` });
-
- const { permission } = await permissionService.getProjectPermission({
- actor,
+ const secretVersionV2 = await secretV2BridgeService.getSecretVersions({
actorId,
- projectId: folder.projectId,
- actorAuthMethod,
+ actor,
actorOrgId,
- actionProjectType: ActionProjectType.SecretManager
- });
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback);
- const secretVersions = await secretVersionDAL.findBySecretId(secretId, {
- offset,
+ actorAuthMethod,
limit,
- sort: [["createdAt", "desc"]]
+ offset,
+ secretId,
+ secretVersions: filterSecretVersions
});
- return secretVersions.map((el) => {
- const secretKey = crypto.encryption().symmetric().decrypt({
- ciphertext: secret.secretKeyCiphertext,
- iv: secret.secretKeyIV,
- tag: secret.secretKeyTag,
- key: botKey,
- keySize: SymmetricKeySize.Bits128
- });
-
- const secretValueHidden = !hasSecretReadValueOrDescribePermission(
- permission,
- ProjectPermissionSecretActions.ReadValue,
- {
- environment: folder.environment.envSlug,
- secretPath: folderWithPath.path,
- secretName: secretKey,
- ...(el.tags?.length && {
- secretTags: el.tags.map((tag) => tag.slug)
- })
- }
- );
-
- return {
- ...decryptSecretRaw(
- {
- secretValueHidden,
- ...el,
- workspace: folder.projectId,
- environment: folder.environment.envSlug,
- secretPath: folderWithPath.path
- },
- botKey
- ),
- redactedByActor: null,
- isRedacted: false,
- redactedAt: null,
- redactedByUserId: null
- };
- });
+ return secretVersionV2;
};
const getSecretVersionsV2ByIds = async ({
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 9ee43cc460..95af340b9b 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -360,7 +360,8 @@ export type ConditionalProjectPermissionSubject =
| ProjectPermissionSub.PamResources
| ProjectPermissionSub.McpEndpoints
| ProjectPermissionSub.Member
- | ProjectPermissionSub.Groups;
+ | ProjectPermissionSub.Groups
+ | ProjectPermissionSub.Commits;
export const formatedConditionsOperatorNames: { [K in PermissionConditionOperators]: string } = {
[PermissionConditionOperators.$EQ]: "equal to",
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/GeneralPermissionConditions.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/GeneralPermissionConditions.tsx
index 2e88c39157..2a80525ef5 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/GeneralPermissionConditions.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/GeneralPermissionConditions.tsx
@@ -5,7 +5,10 @@ import { ConditionsFields } from "./ConditionsFields";
type Props = {
position?: number;
isDisabled?: boolean;
- type: ProjectPermissionSub.SecretFolders | ProjectPermissionSub.SecretImports;
+ type:
+ | ProjectPermissionSub.SecretFolders
+ | ProjectPermissionSub.SecretImports
+ | ProjectPermissionSub.Commits;
};
type SelectOption = { value: string; label: string; description?: string };
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 3679b929f7..59bb19c228 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -699,7 +699,12 @@ export const projectRoleFormSchema = z.object({
.array()
.default([]),
- [ProjectPermissionSub.Commits]: CommitPolicyActionSchema.array().default([]),
+ [ProjectPermissionSub.Commits]: CommitPolicyActionSchema.extend({
+ inverted: z.boolean().optional(),
+ conditions: ConditionSchema
+ })
+ .array()
+ .default([]),
[ProjectPermissionSub.Member]: MemberPolicyActionSchema.array().default([]),
[ProjectPermissionSub.Groups]: GroupPolicyActionSchemaWithConditions.array().default([]),
[ProjectPermissionSub.Role]: GeneralPolicyActionSchema.array().default([]),
@@ -909,7 +914,8 @@ type TConditionalFields =
| ProjectPermissionSub.PamDomains
| ProjectPermissionSub.McpEndpoints
| ProjectPermissionSub.Member
- | ProjectPermissionSub.Groups;
+ | ProjectPermissionSub.Groups
+ | ProjectPermissionSub.Commits;
export const isConditionalSubjects = (
subject: ProjectPermissionSub
@@ -936,7 +942,8 @@ export const isConditionalSubjects = (
subject === ProjectPermissionSub.PamDomains ||
subject === ProjectPermissionSub.McpEndpoints ||
subject === ProjectPermissionSub.Member ||
- subject === ProjectPermissionSub.Groups;
+ subject === ProjectPermissionSub.Groups ||
+ subject === ProjectPermissionSub.Commits;
const CONDITION_DISPLAY_ORDER = [
"userEmail",
@@ -1725,10 +1732,13 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
const canRead = action.includes(ProjectPermissionCommitsActions.Read);
const canPerformRollback = action.includes(ProjectPermissionCommitsActions.PerformRollback);
- if (!formVal[subject]) formVal[subject] = [{}];
- if (canRead) formVal[subject]![0][ProjectPermissionCommitsActions.Read] = true;
- if (canPerformRollback)
- formVal[subject]![0][ProjectPermissionCommitsActions.PerformRollback] = true;
+ if (!formVal[subject]) formVal[subject] = [];
+ formVal[subject]!.push({
+ [ProjectPermissionCommitsActions.Read]: canRead,
+ [ProjectPermissionCommitsActions.PerformRollback]: canPerformRollback,
+ conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],
+ inverted
+ });
return;
}