mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-06 19:28:16 +00:00
feat(secret-approval): implemented the new policy based approval system bare version
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
import { SecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
import { SecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
||||||
|
import { getSecretPolicyOfBoard } from "../../services/SecretApprovalService";
|
||||||
import { BadRequestError } from "../../utils/errors";
|
import { BadRequestError } from "../../utils/errors";
|
||||||
import * as reqValidator from "../../validation/secretApproval";
|
import * as reqValidator from "../../validation/secretApproval";
|
||||||
|
|
||||||
@@ -107,3 +108,18 @@ export const getSecretApprovalPolicy = async (req: Request, res: Response) => {
|
|||||||
approvals: doc
|
approvals: doc
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getSecretApprovalPolicyOfBoard = async (req: Request, res: Response) => {
|
||||||
|
const {
|
||||||
|
query: { workspaceId, environment, secretPath }
|
||||||
|
} = await validateRequest(reqValidator.GetSecretApprovalPolicyOfABoard, req);
|
||||||
|
|
||||||
|
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
|
ProjectPermissionActions.Read,
|
||||||
|
subject(ProjectPermissionSub.Secrets, { secretPath, environment })
|
||||||
|
);
|
||||||
|
|
||||||
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
|
return res.send({ policy: secretApprovalPolicy });
|
||||||
|
};
|
||||||
|
|||||||
@@ -2,11 +2,12 @@ import { Request, Response } from "express";
|
|||||||
import { getUserProjectPermissions } from "../../ee/services/ProjectRoleService";
|
import { getUserProjectPermissions } from "../../ee/services/ProjectRoleService";
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
import { Folder } from "../../models";
|
import { Folder } from "../../models";
|
||||||
import { SecretApprovalRequest } from "../../models/secretApprovalRequest";
|
import { ApprovalStatus, SecretApprovalRequest } from "../../models/secretApprovalRequest";
|
||||||
import * as reqValidator from "../../validation/secretApprovalRequest";
|
import * as reqValidator from "../../validation/secretApprovalRequest";
|
||||||
import { getFolderWithPathFromId } from "../../services/FolderService";
|
import { getFolderWithPathFromId } from "../../services/FolderService";
|
||||||
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
||||||
import { ISecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
import { ISecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
||||||
|
import { performSecretApprovalRequestMerge } from "../../services/SecretApprovalService";
|
||||||
|
|
||||||
export const getSecretApprovalRequests = async (req: Request, res: Response) => {
|
export const getSecretApprovalRequests = async (req: Request, res: Response) => {
|
||||||
const {
|
const {
|
||||||
@@ -29,6 +30,7 @@ export const getSecretApprovalRequests = async (req: Request, res: Response) =>
|
|||||||
([key, value]) => value === undefined && delete query[key as keyof typeof query]
|
([key, value]) => value === undefined && delete query[key as keyof typeof query]
|
||||||
);
|
);
|
||||||
const approvalRequests = await SecretApprovalRequest.find(query)
|
const approvalRequests = await SecretApprovalRequest.find(query)
|
||||||
|
.sort({ createdAt: -1 })
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.skip(offset)
|
.skip(offset)
|
||||||
.populate("policy")
|
.populate("policy")
|
||||||
@@ -64,11 +66,12 @@ export const getSecretApprovalRequestDetails = async (req: Request, res: Respons
|
|||||||
const secretApprovalRequest = await SecretApprovalRequest.findById(id)
|
const secretApprovalRequest = await SecretApprovalRequest.findById(id)
|
||||||
.populate("policy")
|
.populate("policy")
|
||||||
.populate({
|
.populate({
|
||||||
path: "commits.secret",
|
path: "commits.secretVersion",
|
||||||
populate: {
|
populate: {
|
||||||
path: "tags"
|
path: "tags"
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
.populate("commits.secret", "version")
|
||||||
.populate("commits.newVersion.tags");
|
.populate("commits.newVersion.tags");
|
||||||
if (!secretApprovalRequest)
|
if (!secretApprovalRequest)
|
||||||
throw BadRequestError({ message: "Secret approval request not found" });
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
@@ -126,3 +129,43 @@ export const updateSecretApprovalRequestStatus = async (req: Request, res: Respo
|
|||||||
|
|
||||||
return res.send({ status });
|
return res.send({ status });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const mergeSecretApprovalRequest = async (req: Request, res: Response) => {
|
||||||
|
const {
|
||||||
|
body: { id }
|
||||||
|
} = await validateRequest(reqValidator.mergeSecretApprovalRequest, req);
|
||||||
|
|
||||||
|
const secretApprovalRequest = await SecretApprovalRequest.findById(id).populate<{
|
||||||
|
policy: ISecretApprovalPolicy;
|
||||||
|
}>("policy");
|
||||||
|
|
||||||
|
if (!secretApprovalRequest)
|
||||||
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
|
|
||||||
|
const { membership } = await getUserProjectPermissions(
|
||||||
|
req.user._id,
|
||||||
|
secretApprovalRequest.workspace.toString()
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
membership.role !== "admin" &&
|
||||||
|
secretApprovalRequest.committer !== membership.id &&
|
||||||
|
!secretApprovalRequest.policy.approvers.find((approverId) => approverId === membership.id)
|
||||||
|
) {
|
||||||
|
throw UnauthorizedRequestError({ message: "User has no access" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const reviewers = secretApprovalRequest.reviewers.reduce<Record<string, ApprovalStatus>>(
|
||||||
|
(prev, curr) => ({ ...prev, [curr.member.toString()]: curr.status }),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
const hasMinApproval =
|
||||||
|
secretApprovalRequest.policy.approvals <=
|
||||||
|
secretApprovalRequest.policy.approvers.filter(
|
||||||
|
(approverId) => reviewers[approverId.toString()] === ApprovalStatus.APPROVED
|
||||||
|
).length;
|
||||||
|
|
||||||
|
if (!hasMinApproval) throw BadRequestError({ message: "Doesn't have minimum approvals needed" });
|
||||||
|
|
||||||
|
const approval = await performSecretApprovalRequestMerge(id, req.authData);
|
||||||
|
return res.send({ approval });
|
||||||
|
};
|
||||||
|
|||||||
@@ -596,7 +596,7 @@ export const createSecret = async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
if (secretApprovalPolicy && membership) {
|
if (secretApprovalPolicy && membership && type !== "personal") {
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -701,7 +701,7 @@ export const updateSecretByName = async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
if (secretApprovalPolicy && membership) {
|
if (secretApprovalPolicy && membership && type !== "personal") {
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -712,6 +712,7 @@ export const updateSecretByName = async (req: Request, res: Response) => {
|
|||||||
[CommitType.UPDATE]: [
|
[CommitType.UPDATE]: [
|
||||||
{
|
{
|
||||||
secretName,
|
secretName,
|
||||||
|
newSecretName,
|
||||||
secretValueCiphertext,
|
secretValueCiphertext,
|
||||||
secretValueIV,
|
secretValueIV,
|
||||||
secretValueTag,
|
secretValueTag,
|
||||||
@@ -784,7 +785,7 @@ export const deleteSecretByName = async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
if (secretApprovalPolicy && membership) {
|
if (secretApprovalPolicy && membership && type !== "personal") {
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -846,7 +847,7 @@ export const createSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
policy: secretApprovalPolicy,
|
policy: secretApprovalPolicy,
|
||||||
commiterMembershipId: membership._id.toString(),
|
commiterMembershipId: membership._id.toString(),
|
||||||
data: {
|
data: {
|
||||||
[CommitType.CREATE]: secrets
|
[CommitType.CREATE]: secrets.filter(({ type }) => type === "shared")
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return res.send({ approval: secretApprovalRequest });
|
return res.send({ approval: secretApprovalRequest });
|
||||||
@@ -887,7 +888,7 @@ export const updateSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
policy: secretApprovalPolicy,
|
policy: secretApprovalPolicy,
|
||||||
commiterMembershipId: membership._id.toString(),
|
commiterMembershipId: membership._id.toString(),
|
||||||
data: {
|
data: {
|
||||||
[CommitType.UPDATE]: secrets
|
[CommitType.UPDATE]: secrets.filter(({ type }) => type === "shared")
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return res.send({ approval: secretApprovalRequest });
|
return res.send({ approval: secretApprovalRequest });
|
||||||
@@ -928,7 +929,7 @@ export const deleteSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
policy: secretApprovalPolicy,
|
policy: secretApprovalPolicy,
|
||||||
commiterMembershipId: membership._id.toString(),
|
commiterMembershipId: membership._id.toString(),
|
||||||
data: {
|
data: {
|
||||||
[CommitType.DELETE]: secrets
|
[CommitType.DELETE]: secrets.filter(({ type }) => type === "shared")
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return res.send({ approval: secretApprovalRequest });
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
|||||||
@@ -32,6 +32,25 @@ export interface ISecretApprovalSecChange {
|
|||||||
tags?: string[];
|
tags?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ISecretCommits<T = Types.ObjectId, J = Types.ObjectId> = Array<
|
||||||
|
| {
|
||||||
|
newVersion: ISecretApprovalSecChange;
|
||||||
|
op: CommitType.CREATE;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
// secret is recorded to get the latest version, we can keep ref to secret for pulling change as it will also get changed
|
||||||
|
// on merge
|
||||||
|
secretVersion: J;
|
||||||
|
secret: T;
|
||||||
|
newVersion: Partial<Omit<ISecretApprovalSecChange, "_id">> & { _id: Types.ObjectId };
|
||||||
|
op: CommitType.UPDATE;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
secret: T;
|
||||||
|
secretVersion: J;
|
||||||
|
op: CommitType.DELETE;
|
||||||
|
}
|
||||||
|
>;
|
||||||
export interface ISecretApprovalRequest {
|
export interface ISecretApprovalRequest {
|
||||||
_id: Types.ObjectId;
|
_id: Types.ObjectId;
|
||||||
committer: Types.ObjectId;
|
committer: Types.ObjectId;
|
||||||
@@ -45,21 +64,8 @@ export interface ISecretApprovalRequest {
|
|||||||
hasMerged: boolean;
|
hasMerged: boolean;
|
||||||
status: "open" | "close";
|
status: "open" | "close";
|
||||||
policy: Types.ObjectId;
|
policy: Types.ObjectId;
|
||||||
commits: Array<
|
commits: ISecretCommits;
|
||||||
| {
|
conflicts: Array<{ secretId: string; op: CommitType }>;
|
||||||
newVersion: ISecretApprovalSecChange;
|
|
||||||
op: CommitType.CREATE;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
secret: Types.ObjectId;
|
|
||||||
newVersion: Partial<ISecretApprovalSecChange>;
|
|
||||||
op: CommitType.UPDATE;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
secret: Types.ObjectId;
|
|
||||||
op: CommitType.DELETE;
|
|
||||||
}
|
|
||||||
>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const secretApprovalSecretChangeSchema = new Schema<ISecretApprovalSecChange>({
|
const secretApprovalSecretChangeSchema = new Schema<ISecretApprovalSecChange>({
|
||||||
@@ -157,9 +163,19 @@ const secretApprovalRequestSchema = new Schema<ISecretApprovalRequest>(
|
|||||||
{
|
{
|
||||||
secret: { type: Types.ObjectId, ref: "Secret" },
|
secret: { type: Types.ObjectId, ref: "Secret" },
|
||||||
newVersion: secretApprovalSecretChangeSchema,
|
newVersion: secretApprovalSecretChangeSchema,
|
||||||
|
secretVersion: { type: Types.ObjectId, ref: "SecretVersion" },
|
||||||
op: { type: String, enum: [CommitType], required: true }
|
op: { type: String, enum: [CommitType], required: true }
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
conflicts: {
|
||||||
|
type: [
|
||||||
|
{
|
||||||
|
secretId: { type: String, required: true },
|
||||||
|
op: { type: String, enum: [CommitType], required: true }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
default: []
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
timestamps: true
|
timestamps: true
|
||||||
|
|||||||
@@ -12,6 +12,14 @@ router.get(
|
|||||||
secretApprovalPolicyController.getSecretApprovalPolicy
|
secretApprovalPolicyController.getSecretApprovalPolicy
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
"/board",
|
||||||
|
requireAuth({
|
||||||
|
acceptedAuthModes: [AuthMode.JWT]
|
||||||
|
}),
|
||||||
|
secretApprovalPolicyController.getSecretApprovalPolicyOfBoard
|
||||||
|
);
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
"/",
|
"/",
|
||||||
requireAuth({
|
requireAuth({
|
||||||
|
|||||||
@@ -20,6 +20,14 @@ router.get(
|
|||||||
secretApprovalRequestController.getSecretApprovalRequestDetails
|
secretApprovalRequestController.getSecretApprovalRequestDetails
|
||||||
);
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/merge",
|
||||||
|
requireAuth({
|
||||||
|
acceptedAuthModes: [AuthMode.JWT]
|
||||||
|
}),
|
||||||
|
secretApprovalRequestController.mergeSecretApprovalRequest
|
||||||
|
);
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
"/:id",
|
"/:id",
|
||||||
requireAuth({
|
requireAuth({
|
||||||
|
|||||||
@@ -11,11 +11,16 @@ import {
|
|||||||
CommitType,
|
CommitType,
|
||||||
ISecretApprovalRequest,
|
ISecretApprovalRequest,
|
||||||
ISecretApprovalSecChange,
|
ISecretApprovalSecChange,
|
||||||
|
ISecretCommits,
|
||||||
SecretApprovalRequest
|
SecretApprovalRequest
|
||||||
} from "../models/secretApprovalRequest";
|
} from "../models/secretApprovalRequest";
|
||||||
import { BadRequestError } from "../utils/errors";
|
import { BadRequestError } from "../utils/errors";
|
||||||
import { getFolderByPath } from "./FolderService";
|
import { getFolderByPath } from "./FolderService";
|
||||||
import { SECRET_SHARED } from "../variables";
|
import { ALGORITHM_AES_256_GCM, ENCODING_SCHEME_UTF8, SECRET_SHARED } from "../variables";
|
||||||
|
import TelemetryService from "./TelemetryService";
|
||||||
|
import { EEAuditLogService, EESecretService } from "../ee/services";
|
||||||
|
import { EventType, SecretVersion } from "../ee/models";
|
||||||
|
import { AuthData } from "../interfaces/middleware";
|
||||||
|
|
||||||
// if glob pattern score is 1, if not exist score is 0 and if its not both then its exact path meaning score 2
|
// if glob pattern score is 1, if not exist score is 0 and if its not both then its exact path meaning score 2
|
||||||
const getPolicyScore = (policy: ISecretApprovalPolicy) =>
|
const getPolicyScore = (policy: ISecretApprovalPolicy) =>
|
||||||
@@ -43,6 +48,35 @@ export const getSecretPolicyOfBoard = async (
|
|||||||
return finalPolicy;
|
return finalPolicy;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getLatestSecretVersion = async (secretIds: Types.ObjectId[]) => {
|
||||||
|
const latestSecretVersions = await SecretVersion.aggregate([
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
secret: {
|
||||||
|
$in: secretIds
|
||||||
|
},
|
||||||
|
type: SECRET_SHARED
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$sort: { version: -1 }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: "$secret",
|
||||||
|
version: { $max: "$version" },
|
||||||
|
versionId: { $max: "$_id" }, // id of latest secret versionId
|
||||||
|
secret: { $first: "$$ROOT" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]).exec();
|
||||||
|
// reduced with secret id and latest version as document
|
||||||
|
return latestSecretVersions.reduce(
|
||||||
|
(prev, curr) => ({ ...prev, [curr._id.toString()]: curr.secret }),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
type TApprovalCreateSecret = Omit<ISecretApprovalSecChange, "_id" | "version"> & {
|
type TApprovalCreateSecret = Omit<ISecretApprovalSecChange, "_id" | "version"> & {
|
||||||
secretName: string;
|
secretName: string;
|
||||||
};
|
};
|
||||||
@@ -50,6 +84,7 @@ type TApprovalUpdateSecret = Partial<Omit<ISecretApprovalSecChange, "_id" | "ver
|
|||||||
secretName: string;
|
secretName: string;
|
||||||
newSecretName?: string;
|
newSecretName?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type TGenerateSecretApprovalRequestArg = {
|
type TGenerateSecretApprovalRequestArg = {
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
environment: string;
|
environment: string;
|
||||||
@@ -151,22 +186,21 @@ export const generateSecretApprovalRequest = async ({
|
|||||||
}, {})
|
}, {})
|
||||||
);
|
);
|
||||||
// check update secret exists
|
// check update secret exists
|
||||||
const secretsToBeUpdated = await Secret.find({
|
const oldSecrets = await Secret.find({
|
||||||
workspace: new Types.ObjectId(workspaceId),
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
folder: folderId,
|
folder: folderId,
|
||||||
environment
|
environment,
|
||||||
|
type: SECRET_SHARED,
|
||||||
|
secretBlindIndex: {
|
||||||
|
$in: updatedSecret.map(({ secretName }) => secretBlindIndexes[secretName])
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.select("+secretBlindIndex")
|
.select("+secretBlindIndex")
|
||||||
.or(
|
|
||||||
updatedSecret.map(({ secretName }) => ({
|
|
||||||
secretBlindIndex: secretBlindIndexes[secretName],
|
|
||||||
type: SECRET_SHARED
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
if (secretsToBeUpdated.length !== updatedSecret.length)
|
if (oldSecrets.length !== updatedSecret.length)
|
||||||
throw BadRequestError({ message: "Secrets already exist" });
|
throw BadRequestError({ message: "Secrets already exist" });
|
||||||
|
|
||||||
// finally check updating blindindex exist
|
// finally check updating blindindex exist
|
||||||
const nameUpdatedSecrets = updatedSecret.filter(({ newSecretName }) => Boolean(newSecretName));
|
const nameUpdatedSecrets = updatedSecret.filter(({ newSecretName }) => Boolean(newSecretName));
|
||||||
const newSecretBlindIndexes = await Promise.all(
|
const newSecretBlindIndexes = await Promise.all(
|
||||||
@@ -188,24 +222,29 @@ export const generateSecretApprovalRequest = async ({
|
|||||||
environment,
|
environment,
|
||||||
secretBlindIndex: { $in: Object.values(newSecretBlindIndexes) }
|
secretBlindIndex: { $in: Object.values(newSecretBlindIndexes) }
|
||||||
});
|
});
|
||||||
if (doesAnySecretExistWithNewIndex)
|
if (doesAnySecretExistWithNewIndex.length)
|
||||||
throw BadRequestError({ message: "Secret with new name already exist" });
|
throw BadRequestError({ message: "Secret with new name already exist" });
|
||||||
|
|
||||||
|
const oldSecretsGroupById = oldSecrets.reduce<Record<string, ISecret>>(
|
||||||
|
(prev, curr) => ({ ...prev, [curr?.secretBlindIndex || ""]: curr }),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
const latestSecretVersions = await getLatestSecretVersion(
|
||||||
|
updatedSecret.map((el) => oldSecretsGroupById[secretBlindIndexes[el.secretName]]._id)
|
||||||
|
);
|
||||||
|
|
||||||
commits.push(
|
commits.push(
|
||||||
...updatedSecret.map((el) => {
|
...updatedSecret.map((el) => {
|
||||||
const oldSecret = secretsToBeUpdated.find(
|
const secretId = oldSecretsGroupById[secretBlindIndexes[el.secretName]]._id;
|
||||||
(sec) => sec?.secretBlindIndex === secretBlindIndexes[el.secretName]
|
|
||||||
);
|
|
||||||
if (!oldSecret) throw BadRequestError({ message: "Secret not found" });
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
op: CommitType.UPDATE as const,
|
op: CommitType.UPDATE as const,
|
||||||
secret: oldSecret._id,
|
secret: secretId,
|
||||||
|
secretVersion: latestSecretVersions[secretId.toString()]._id,
|
||||||
newVersion: {
|
newVersion: {
|
||||||
...el,
|
...el,
|
||||||
secretBlindIndex: newSecretBlindIndexes?.[el.secretName],
|
secretBlindIndex: newSecretBlindIndexes?.[el.secretName],
|
||||||
_id: new Types.ObjectId(),
|
_id: new Types.ObjectId(),
|
||||||
version: oldSecret.version || 1
|
version: oldSecretsGroupById[secretBlindIndexes[el.secretName]].version || 1
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
@@ -233,29 +272,35 @@ export const generateSecretApprovalRequest = async ({
|
|||||||
const secretsToDelete = await Secret.find({
|
const secretsToDelete = await Secret.find({
|
||||||
workspace: new Types.ObjectId(workspaceId),
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
folder: folderId,
|
folder: folderId,
|
||||||
environment
|
environment,
|
||||||
|
type: SECRET_SHARED,
|
||||||
|
secretBlindIndex: {
|
||||||
|
$in: deletedSecrets.map(({ secretName }) => secretBlindIndexes[secretName])
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.or(
|
.select({ secretBlindIndex: 1, _id: 1 })
|
||||||
deletedSecrets.map(({ secretName }) => ({
|
|
||||||
secretBlindIndex: secretBlindIndexes[secretName],
|
|
||||||
type: SECRET_SHARED
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
.select({ secretBlindIndexes: 1 })
|
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
if (secretsToDelete.length !== deletedSecrets.length)
|
if (secretsToDelete.length !== deletedSecrets.length)
|
||||||
throw BadRequestError({ message: "Deleted secrets not found" });
|
throw BadRequestError({ message: "Deleted secrets not found" });
|
||||||
|
|
||||||
|
const oldSecretsGroupById = secretsToDelete.reduce<Record<string, ISecret>>(
|
||||||
|
(prev, curr) => ({ ...prev, [curr?.secretBlindIndex || ""]: curr }),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
const latestSecretVersions = await getLatestSecretVersion(
|
||||||
|
deletedSecrets.map((el) => oldSecretsGroupById[secretBlindIndexes[el.secretName]]._id)
|
||||||
|
);
|
||||||
|
|
||||||
commits.push(
|
commits.push(
|
||||||
...deletedSecrets.map((el) => ({
|
...deletedSecrets.map((el) => {
|
||||||
op: CommitType.DELETE as const,
|
const secretId = oldSecretsGroupById[secretBlindIndexes[el.secretName]]._id;
|
||||||
secret: (
|
return {
|
||||||
secretsToDelete.find(
|
op: CommitType.DELETE as const,
|
||||||
(sec) => sec?.secretBlindIndex === secretBlindIndexes[el.secretName]
|
secret: secretId,
|
||||||
) as ISecret
|
secretVersion: latestSecretVersions[secretId.toString()]
|
||||||
)._id
|
};
|
||||||
}))
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,3 +315,356 @@ export const generateSecretApprovalRequest = async ({
|
|||||||
await secretApprovalRequest.save();
|
await secretApprovalRequest.save();
|
||||||
return secretApprovalRequest;
|
return secretApprovalRequest;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// validation for a merge conditions happen in another function in controller
|
||||||
|
export const performSecretApprovalRequestMerge = async (id: string, authData: AuthData) => {
|
||||||
|
const secretApprovalRequest = await SecretApprovalRequest.findById(id)
|
||||||
|
.populate<{ commits: ISecretCommits<ISecret> }>({
|
||||||
|
path: "commits.secret",
|
||||||
|
select: "+secretBlindIndex",
|
||||||
|
populate: {
|
||||||
|
path: "tags"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.select("+commits.newVersion.secretBlindIndex");
|
||||||
|
if (!secretApprovalRequest) throw BadRequestError({ message: "Approval request not found" });
|
||||||
|
|
||||||
|
const workspaceId = secretApprovalRequest.workspace;
|
||||||
|
const environment = secretApprovalRequest.environment;
|
||||||
|
const folderId = secretApprovalRequest.folderId;
|
||||||
|
const postHogClient = await TelemetryService.getPostHogClient();
|
||||||
|
const conflicts: Array<{ id: string; op: CommitType }> = [];
|
||||||
|
|
||||||
|
const secretCreationCommits = secretApprovalRequest.commits.filter(
|
||||||
|
({ op }) => op === CommitType.CREATE
|
||||||
|
) as Array<{ op: CommitType.CREATE; newVersion: ISecretApprovalSecChange }>;
|
||||||
|
if (secretCreationCommits.length) {
|
||||||
|
// the created secrets already exist thus creation conflict ones
|
||||||
|
const conflictedSecrets = await Secret.find({
|
||||||
|
workspace: workspaceId,
|
||||||
|
environment,
|
||||||
|
folder: folderId,
|
||||||
|
secretBlindIndex: {
|
||||||
|
$in: secretCreationCommits.map(({ newVersion }) => newVersion.secretBlindIndex)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.select("+secretBlindIndex")
|
||||||
|
.lean();
|
||||||
|
const conflictGroupByBlindIndex = conflictedSecrets.reduce<Record<string, boolean>>(
|
||||||
|
(prev, curr) => ({ ...prev, [curr.secretBlindIndex || ""]: true }),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
const nonConflictSecrets = secretCreationCommits.filter(
|
||||||
|
({ newVersion }) => !conflictGroupByBlindIndex[newVersion.secretBlindIndex || ""]
|
||||||
|
);
|
||||||
|
secretCreationCommits
|
||||||
|
.filter(({ newVersion }) => conflictGroupByBlindIndex[newVersion.secretBlindIndex || ""])
|
||||||
|
.forEach((el) => {
|
||||||
|
conflicts.push({ op: CommitType.CREATE, id: el.newVersion._id.toString() });
|
||||||
|
});
|
||||||
|
|
||||||
|
// create secret
|
||||||
|
const newlyCreatedSecrets: ISecret[] = await Secret.insertMany(
|
||||||
|
nonConflictSecrets.map(
|
||||||
|
({
|
||||||
|
newVersion: {
|
||||||
|
secretKeyIV,
|
||||||
|
secretKeyTag,
|
||||||
|
secretValueIV,
|
||||||
|
secretValueTag,
|
||||||
|
secretCommentIV,
|
||||||
|
secretCommentTag,
|
||||||
|
secretKeyCiphertext,
|
||||||
|
secretValueCiphertext,
|
||||||
|
secretCommentCiphertext,
|
||||||
|
skipMultilineEncoding,
|
||||||
|
secretBlindIndex,
|
||||||
|
algorithm,
|
||||||
|
keyEncoding,
|
||||||
|
tags
|
||||||
|
}
|
||||||
|
}) => ({
|
||||||
|
version: 1,
|
||||||
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
|
environment,
|
||||||
|
type: SECRET_SHARED,
|
||||||
|
secretKeyCiphertext,
|
||||||
|
secretKeyIV,
|
||||||
|
secretKeyTag,
|
||||||
|
secretValueCiphertext,
|
||||||
|
secretValueIV,
|
||||||
|
secretValueTag,
|
||||||
|
secretCommentCiphertext,
|
||||||
|
secretCommentIV,
|
||||||
|
secretCommentTag,
|
||||||
|
folder: folderId,
|
||||||
|
algorithm: algorithm || ALGORITHM_AES_256_GCM,
|
||||||
|
keyEncoding: keyEncoding || ENCODING_SCHEME_UTF8,
|
||||||
|
tags,
|
||||||
|
skipMultilineEncoding,
|
||||||
|
secretBlindIndex
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await EESecretService.addSecretVersions({
|
||||||
|
secretVersions: newlyCreatedSecrets.map(
|
||||||
|
(secret) =>
|
||||||
|
new SecretVersion({
|
||||||
|
secret: secret._id,
|
||||||
|
version: secret.version,
|
||||||
|
workspace: secret.workspace,
|
||||||
|
type: secret.type,
|
||||||
|
folder: folderId,
|
||||||
|
tags: secret.tags,
|
||||||
|
skipMultilineEncoding: secret?.skipMultilineEncoding,
|
||||||
|
environment: secret.environment,
|
||||||
|
isDeleted: false,
|
||||||
|
secretBlindIndex: secret.secretBlindIndex,
|
||||||
|
secretKeyCiphertext: secret.secretKeyCiphertext,
|
||||||
|
secretKeyIV: secret.secretKeyIV,
|
||||||
|
secretKeyTag: secret.secretKeyTag,
|
||||||
|
secretValueCiphertext: secret.secretValueCiphertext,
|
||||||
|
secretValueIV: secret.secretValueIV,
|
||||||
|
secretValueTag: secret.secretValueTag,
|
||||||
|
algorithm: ALGORITHM_AES_256_GCM,
|
||||||
|
keyEncoding: ENCODING_SCHEME_UTF8
|
||||||
|
})
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
// question to team where to keep secretKey
|
||||||
|
await EEAuditLogService.createAuditLog(
|
||||||
|
authData,
|
||||||
|
{
|
||||||
|
type: EventType.CREATE_SECRETS,
|
||||||
|
metadata: {
|
||||||
|
environment,
|
||||||
|
secretPath: "/",
|
||||||
|
secrets: newlyCreatedSecrets.map(({ version, _id }) => ({
|
||||||
|
secretId: _id.toString(),
|
||||||
|
secretKey: "",
|
||||||
|
secretVersion: version
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
workspaceId
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const secretUpdationCommits = secretApprovalRequest.commits.filter(
|
||||||
|
({ op }) => op === CommitType.UPDATE
|
||||||
|
) as Array<{
|
||||||
|
op: CommitType.UPDATE;
|
||||||
|
newVersion: Partial<Omit<ISecretApprovalSecChange, "_id">> & { _id: Types.ObjectId };
|
||||||
|
secret: ISecret;
|
||||||
|
}>;
|
||||||
|
if (secretUpdationCommits.length) {
|
||||||
|
const conflictedByNewBlindIndex = await Secret.find({
|
||||||
|
workspace: workspaceId,
|
||||||
|
environment,
|
||||||
|
folder: folderId,
|
||||||
|
secretBlindIndex: {
|
||||||
|
$in: secretUpdationCommits
|
||||||
|
.map(({ newVersion }) => newVersion?.secretBlindIndex)
|
||||||
|
.filter(Boolean)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.select("+secretBlindIndex")
|
||||||
|
.lean();
|
||||||
|
const conflictGroupByBlindIndex = conflictedByNewBlindIndex.reduce<Record<string, boolean>>(
|
||||||
|
(prev, curr) => (curr?.secretBlindIndex ? { ...prev, [curr.secretBlindIndex]: true } : prev),
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
secretUpdationCommits
|
||||||
|
.filter(
|
||||||
|
({ newVersion }) =>
|
||||||
|
newVersion.secretBlindIndex && conflictGroupByBlindIndex[newVersion.secretBlindIndex]
|
||||||
|
)
|
||||||
|
.forEach((el) => {
|
||||||
|
conflicts.push({ op: CommitType.UPDATE, id: el.newVersion._id.toString() });
|
||||||
|
});
|
||||||
|
|
||||||
|
const nonConflictSecrets = secretUpdationCommits.filter(({ newVersion }) =>
|
||||||
|
newVersion?.secretBlindIndex ? !conflictGroupByBlindIndex[newVersion.secretBlindIndex] : true
|
||||||
|
);
|
||||||
|
await Secret.bulkWrite(
|
||||||
|
// id and version are stripped off
|
||||||
|
nonConflictSecrets.map(
|
||||||
|
({
|
||||||
|
newVersion: {
|
||||||
|
secretKeyIV,
|
||||||
|
secretKeyTag,
|
||||||
|
secretValueIV,
|
||||||
|
secretValueTag,
|
||||||
|
secretCommentIV,
|
||||||
|
secretCommentTag,
|
||||||
|
secretKeyCiphertext,
|
||||||
|
secretValueCiphertext,
|
||||||
|
secretCommentCiphertext,
|
||||||
|
skipMultilineEncoding,
|
||||||
|
secretBlindIndex,
|
||||||
|
tags
|
||||||
|
},
|
||||||
|
secret
|
||||||
|
}) => ({
|
||||||
|
updateOne: {
|
||||||
|
filter: {
|
||||||
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
|
environment,
|
||||||
|
folder: folderId,
|
||||||
|
secretBlindIndex: secret.secretBlindIndex,
|
||||||
|
type: SECRET_SHARED
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
$inc: {
|
||||||
|
version: 1
|
||||||
|
},
|
||||||
|
secretKeyIV,
|
||||||
|
secretKeyTag,
|
||||||
|
secretValueIV,
|
||||||
|
secretValueTag,
|
||||||
|
secretCommentIV,
|
||||||
|
secretCommentTag,
|
||||||
|
secretKeyCiphertext,
|
||||||
|
secretValueCiphertext,
|
||||||
|
secretCommentCiphertext,
|
||||||
|
skipMultilineEncoding,
|
||||||
|
secretBlindIndex,
|
||||||
|
tags,
|
||||||
|
algorithm: ALGORITHM_AES_256_GCM,
|
||||||
|
keyEncoding: ENCODING_SCHEME_UTF8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await EESecretService.addSecretVersions({
|
||||||
|
secretVersions: nonConflictSecrets.map(({ newVersion, secret }) => {
|
||||||
|
return new SecretVersion({
|
||||||
|
secret: secret._id,
|
||||||
|
version: secret.version + 1,
|
||||||
|
workspace: workspaceId,
|
||||||
|
type: SECRET_SHARED,
|
||||||
|
folder: folderId,
|
||||||
|
environment,
|
||||||
|
isDeleted: false,
|
||||||
|
secretBlindIndex: newVersion?.secretBlindIndex ?? secret.secretBlindIndex,
|
||||||
|
secretKeyCiphertext: newVersion?.secretKeyCiphertext ?? secret.secretKeyCiphertext,
|
||||||
|
secretKeyIV: newVersion?.secretKeyIV ?? secret.secretKeyCiphertext,
|
||||||
|
secretKeyTag: newVersion?.secretKeyTag ?? secret.secretKeyTag,
|
||||||
|
secretValueCiphertext: newVersion?.secretValueCiphertext ?? secret.secretValueCiphertext,
|
||||||
|
secretValueIV: newVersion?.secretValueIV ?? secret.secretValueIV,
|
||||||
|
secretValueTag: newVersion?.secretValueTag ?? secret.secretValueTag,
|
||||||
|
tags: newVersion?.tags ?? secret.tags,
|
||||||
|
algorithm: ALGORITHM_AES_256_GCM,
|
||||||
|
keyEncoding: ENCODING_SCHEME_UTF8,
|
||||||
|
skipMultilineEncoding: newVersion?.skipMultilineEncoding ?? secret.skipMultilineEncoding
|
||||||
|
});
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
await EEAuditLogService.createAuditLog(
|
||||||
|
authData,
|
||||||
|
{
|
||||||
|
type: EventType.UPDATE_SECRETS,
|
||||||
|
metadata: {
|
||||||
|
environment,
|
||||||
|
secretPath: "/",
|
||||||
|
secrets: nonConflictSecrets.map(({ secret }) => ({
|
||||||
|
secretId: secret._id.toString(),
|
||||||
|
secretKey: "",
|
||||||
|
secretVersion: secret.version + 1
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
workspaceId
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const secretDeletionCommits = secretApprovalRequest.commits.filter(
|
||||||
|
({ op }) => op === CommitType.DELETE
|
||||||
|
) as Array<{
|
||||||
|
op: CommitType.DELETE;
|
||||||
|
secret: ISecret;
|
||||||
|
}>;
|
||||||
|
if (secretDeletionCommits.length) {
|
||||||
|
await Secret.deleteMany({
|
||||||
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
|
folder: folderId,
|
||||||
|
environment
|
||||||
|
})
|
||||||
|
.or(
|
||||||
|
secretDeletionCommits.map(({ secret: { secretBlindIndex } }) => ({
|
||||||
|
secretBlindIndex,
|
||||||
|
type: { $in: ["shared", "personal"] }
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
await EESecretService.markDeletedSecretVersions({
|
||||||
|
secretIds: secretDeletionCommits.map(({ secret }) => secret._id)
|
||||||
|
});
|
||||||
|
|
||||||
|
await EEAuditLogService.createAuditLog(
|
||||||
|
authData,
|
||||||
|
{
|
||||||
|
type: EventType.DELETE_SECRETS,
|
||||||
|
metadata: {
|
||||||
|
environment,
|
||||||
|
secretPath: "/",
|
||||||
|
secrets: secretDeletionCommits.map(({ secret: { _id, version } }) => ({
|
||||||
|
secretId: _id.toString(),
|
||||||
|
secretKey: "",
|
||||||
|
secretVersion: version
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
workspaceId
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedSecretApproval = await SecretApprovalRequest.findByIdAndUpdate(
|
||||||
|
id,
|
||||||
|
{
|
||||||
|
conflicts,
|
||||||
|
hasMerged: true,
|
||||||
|
status: "close"
|
||||||
|
},
|
||||||
|
{ new: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (postHogClient) {
|
||||||
|
if (postHogClient) {
|
||||||
|
postHogClient.capture({
|
||||||
|
event: "secrets merged",
|
||||||
|
distinctId: await TelemetryService.getDistinctId({
|
||||||
|
authData
|
||||||
|
}),
|
||||||
|
properties: {
|
||||||
|
numberOfSecrets: secretApprovalRequest.commits.length,
|
||||||
|
environment,
|
||||||
|
workspaceId,
|
||||||
|
folderId,
|
||||||
|
channel: authData.userAgentType,
|
||||||
|
userAgent: authData.userAgent
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await EESecretService.takeSecretSnapshot({
|
||||||
|
workspaceId,
|
||||||
|
environment,
|
||||||
|
folderId
|
||||||
|
});
|
||||||
|
|
||||||
|
return updatedSecretApproval;
|
||||||
|
};
|
||||||
|
|||||||
@@ -2,7 +2,15 @@ import { z } from "zod";
|
|||||||
|
|
||||||
export const GetSecretApprovalRuleList = z.object({
|
export const GetSecretApprovalRuleList = z.object({
|
||||||
query: z.object({
|
query: z.object({
|
||||||
workspaceId: z.string()
|
workspaceId: z.string().trim()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
export const GetSecretApprovalPolicyOfABoard = z.object({
|
||||||
|
query: z.object({
|
||||||
|
workspaceId: z.string().trim(),
|
||||||
|
environment: z.string().trim(),
|
||||||
|
secretPath: z.string().trim()
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const getSecretApprovalRequests = z.object({
|
|||||||
workspaceId: z.string().trim(),
|
workspaceId: z.string().trim(),
|
||||||
environment: z.string().trim().optional(),
|
environment: z.string().trim().optional(),
|
||||||
committer: z.string().trim().optional(),
|
committer: z.string().trim().optional(),
|
||||||
status: z.string().trim().optional(),
|
status: z.enum(["open", "close"]).optional(),
|
||||||
limit: z.coerce.number().default(20),
|
limit: z.coerce.number().default(20),
|
||||||
offset: z.coerce.number().default(0)
|
offset: z.coerce.number().default(0)
|
||||||
})
|
})
|
||||||
@@ -26,3 +26,9 @@ export const updateSecretApprovalRequestStatus = z.object({
|
|||||||
id: z.string().trim()
|
id: z.string().trim()
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const mergeSecretApprovalRequest = z.object({
|
||||||
|
body: z.object({
|
||||||
|
id: z.string().trim()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import { faAngleRight } from "@fortawesome/free-solid-svg-icons";
|
import { faAngleRight, faShield } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
|
||||||
import { useOrganization, useWorkspace } from "@app/context";
|
import { useOrganization, useWorkspace } from "@app/context";
|
||||||
@@ -16,6 +16,7 @@ type Props = {
|
|||||||
onEnvChange?: (slug: string) => void;
|
onEnvChange?: (slug: string) => void;
|
||||||
secretPath?: string;
|
secretPath?: string;
|
||||||
isFolderMode?: boolean;
|
isFolderMode?: boolean;
|
||||||
|
isProtectedBranch?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: make links clickable and clean up
|
// TODO: make links clickable and clean up
|
||||||
@@ -42,7 +43,8 @@ export default function NavHeader({
|
|||||||
userAvailableEnvs = [],
|
userAvailableEnvs = [],
|
||||||
onEnvChange,
|
onEnvChange,
|
||||||
isFolderMode,
|
isFolderMode,
|
||||||
secretPath = "/"
|
secretPath = "/",
|
||||||
|
isProtectedBranch = false
|
||||||
}: Props): JSX.Element {
|
}: Props): JSX.Element {
|
||||||
const { currentWorkspace } = useWorkspace();
|
const { currentWorkspace } = useWorkspace();
|
||||||
const { currentOrg } = useOrganization();
|
const { currentOrg } = useOrganization();
|
||||||
@@ -151,6 +153,7 @@ export default function NavHeader({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{isProtectedBranch && <FontAwesomeIcon icon={faShield} className="text-primary" />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,4 +3,4 @@ export {
|
|||||||
useDeleteSecretApprovalPolicy,
|
useDeleteSecretApprovalPolicy,
|
||||||
useUpdateSecretApprovalPolicy
|
useUpdateSecretApprovalPolicy
|
||||||
} from "./mutation";
|
} from "./mutation";
|
||||||
export { useGetSecretApprovalPolicies } from "./queries";
|
export { useGetSecretApprovalPolicies, useGetSecretApprovalPolicyOfABoard } from "./queries";
|
||||||
|
|||||||
@@ -2,11 +2,19 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query";
|
|||||||
|
|
||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
|
|
||||||
import { TSecretApprovalPolicy } from "./types";
|
import {
|
||||||
|
TGetSecretApprovalPoliciesDTO,
|
||||||
|
TGetSecretApprovalPolicyOfBoardDTO,
|
||||||
|
TSecretApprovalPolicy
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
export const secretApprovalKeys = {
|
export const secretApprovalKeys = {
|
||||||
getApprovalPolicies: (workspaceId: string) =>
|
getApprovalPolicies: (workspaceId: string) =>
|
||||||
[{ workspaceId }, "secret-approval-policies"] as const
|
[{ workspaceId }, "secret-approval-policies"] as const,
|
||||||
|
getApprovalPolicyOfABoard: (workspaceId: string, environment: string, secretPath: string) => [
|
||||||
|
{ workspaceId, environment, secretPath },
|
||||||
|
"Secret-approval-policy"
|
||||||
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchApprovalPolicies = async (workspaceId: string) => {
|
const fetchApprovalPolicies = async (workspaceId: string) => {
|
||||||
@@ -20,7 +28,7 @@ const fetchApprovalPolicies = async (workspaceId: string) => {
|
|||||||
export const useGetSecretApprovalPolicies = ({
|
export const useGetSecretApprovalPolicies = ({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
options = {}
|
options = {}
|
||||||
}: { workspaceId: string } & {
|
}: TGetSecretApprovalPoliciesDTO & {
|
||||||
options?: UseQueryOptions<
|
options?: UseQueryOptions<
|
||||||
TSecretApprovalPolicy[],
|
TSecretApprovalPolicy[],
|
||||||
unknown,
|
unknown,
|
||||||
@@ -34,3 +42,35 @@ export const useGetSecretApprovalPolicies = ({
|
|||||||
...options,
|
...options,
|
||||||
enabled: Boolean(workspaceId) && (options?.enabled ?? true)
|
enabled: Boolean(workspaceId) && (options?.enabled ?? true)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const fetchApprovalPolicyOfABoard = async (
|
||||||
|
workspaceId: string,
|
||||||
|
environment: string,
|
||||||
|
secretPath: string
|
||||||
|
) => {
|
||||||
|
const { data } = await apiRequest.get<{ policy: TSecretApprovalPolicy }>(
|
||||||
|
"/api/v1/secret-approvals/board",
|
||||||
|
{ params: { workspaceId, environment, secretPath } }
|
||||||
|
);
|
||||||
|
return data.policy;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useGetSecretApprovalPolicyOfABoard = ({
|
||||||
|
workspaceId,
|
||||||
|
secretPath = "/",
|
||||||
|
environment,
|
||||||
|
options = {}
|
||||||
|
}: TGetSecretApprovalPolicyOfBoardDTO & {
|
||||||
|
options?: UseQueryOptions<
|
||||||
|
TSecretApprovalPolicy,
|
||||||
|
unknown,
|
||||||
|
TSecretApprovalPolicy,
|
||||||
|
ReturnType<typeof secretApprovalKeys.getApprovalPolicyOfABoard>
|
||||||
|
>;
|
||||||
|
}) =>
|
||||||
|
useQuery({
|
||||||
|
queryKey: secretApprovalKeys.getApprovalPolicyOfABoard(workspaceId, environment, secretPath),
|
||||||
|
queryFn: () => fetchApprovalPolicyOfABoard(workspaceId, environment, secretPath),
|
||||||
|
...options,
|
||||||
|
enabled: Boolean(workspaceId && secretPath && environment) && (options?.enabled ?? true)
|
||||||
|
});
|
||||||
|
|||||||
@@ -7,6 +7,16 @@ export type TSecretApprovalPolicy = {
|
|||||||
approvals: number;
|
approvals: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TGetSecretApprovalPoliciesDTO = {
|
||||||
|
workspaceId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TGetSecretApprovalPolicyOfBoardDTO = {
|
||||||
|
workspaceId: string;
|
||||||
|
environment: string;
|
||||||
|
secretPath: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type TCreateSecretPolicyDTO = {
|
export type TCreateSecretPolicyDTO = {
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
environment: string;
|
environment: string;
|
||||||
|
|||||||
@@ -1,2 +1,5 @@
|
|||||||
export { useUpdateSecretApprovalRequestStatus } from "./mutation";
|
export {
|
||||||
|
usePerformSecretApprovalRequestMerge,
|
||||||
|
useUpdateSecretApprovalRequestStatus
|
||||||
|
} from "./mutation";
|
||||||
export { useGetSecretApprovalRequestDetails, useGetSecretApprovalRequests } from "./queries";
|
export { useGetSecretApprovalRequestDetails, useGetSecretApprovalRequests } from "./queries";
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|||||||
import { apiRequest } from "@app/config/request";
|
import { apiRequest } from "@app/config/request";
|
||||||
|
|
||||||
import { secretApprovalRequestKeys } from "./queries";
|
import { secretApprovalRequestKeys } from "./queries";
|
||||||
import { TUpdateSecretApprovalRequestStatusDTO } from "./types";
|
import { TPerformSecretApprovalRequestMerge, TUpdateSecretApprovalRequestStatusDTO } from "./types";
|
||||||
|
|
||||||
export const useUpdateSecretApprovalRequestStatus = () => {
|
export const useUpdateSecretApprovalRequestStatus = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -18,3 +18,17 @@ export const useUpdateSecretApprovalRequestStatus = () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const usePerformSecretApprovalRequestMerge = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation<{}, {}, TPerformSecretApprovalRequestMerge>({
|
||||||
|
mutationFn: async ({ id }) => {
|
||||||
|
const { data } = await apiRequest.post("/api/v1/secret-approval-requests/merge", { id });
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
onSuccess: (_, { id }) => {
|
||||||
|
queryClient.invalidateQueries(secretApprovalRequestKeys.detail({ id }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
|
import {
|
||||||
|
useInfiniteQuery,
|
||||||
|
UseInfiniteQueryOptions,
|
||||||
|
useQuery,
|
||||||
|
UseQueryOptions
|
||||||
|
} from "@tanstack/react-query";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
decryptAssymmetric,
|
decryptAssymmetric,
|
||||||
@@ -18,8 +23,18 @@ import {
|
|||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const secretApprovalRequestKeys = {
|
export const secretApprovalRequestKeys = {
|
||||||
list: ({ workspaceId, environment }: TGetSecretApprovalRequestList) =>
|
list: ({
|
||||||
[{ workspaceId, environment }, "secret-approval-requests"] as const,
|
workspaceId,
|
||||||
|
environment,
|
||||||
|
status,
|
||||||
|
committer,
|
||||||
|
offset,
|
||||||
|
limit
|
||||||
|
}: TGetSecretApprovalRequestList) =>
|
||||||
|
[
|
||||||
|
{ workspaceId, environment, status, committer, offset, limit },
|
||||||
|
"secret-approval-requests"
|
||||||
|
] as const,
|
||||||
detail: ({ id }: Omit<TGetSecretApprovalRequestDetails, "decryptKey">) =>
|
detail: ({ id }: Omit<TGetSecretApprovalRequestDetails, "decryptKey">) =>
|
||||||
[{ id }, "secret-approval-request-detail"] as const
|
[{ id }, "secret-approval-request-detail"] as const
|
||||||
};
|
};
|
||||||
@@ -68,14 +83,22 @@ export const decryptSecretApprovalSecret = (
|
|||||||
|
|
||||||
const fetchSecretApprovalRequestList = async ({
|
const fetchSecretApprovalRequestList = async ({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment
|
environment,
|
||||||
|
committer,
|
||||||
|
status = "open",
|
||||||
|
limit = 20,
|
||||||
|
offset
|
||||||
}: TGetSecretApprovalRequestList) => {
|
}: TGetSecretApprovalRequestList) => {
|
||||||
const { data } = await apiRequest.get<{ approvals: TSecretApprovalRequest[] }>(
|
const { data } = await apiRequest.get<{ approvals: TSecretApprovalRequest[] }>(
|
||||||
"/api/v1/secret-approval-requests",
|
"/api/v1/secret-approval-requests",
|
||||||
{
|
{
|
||||||
params: {
|
params: {
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment
|
environment,
|
||||||
|
committer,
|
||||||
|
status,
|
||||||
|
limit,
|
||||||
|
offset
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -86,10 +109,13 @@ const fetchSecretApprovalRequestList = async ({
|
|||||||
export const useGetSecretApprovalRequests = ({
|
export const useGetSecretApprovalRequests = ({
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
options = {}
|
options = {},
|
||||||
|
status,
|
||||||
|
limit = 20,
|
||||||
|
committer
|
||||||
}: TGetSecretApprovalRequestList & {
|
}: TGetSecretApprovalRequestList & {
|
||||||
options?: Omit<
|
options?: Omit<
|
||||||
UseQueryOptions<
|
UseInfiniteQueryOptions<
|
||||||
TSecretApprovalRequest[],
|
TSecretApprovalRequest[],
|
||||||
unknown,
|
unknown,
|
||||||
TSecretApprovalRequest[],
|
TSecretApprovalRequest[],
|
||||||
@@ -98,10 +124,26 @@ export const useGetSecretApprovalRequests = ({
|
|||||||
"queryKey" | "queryFn"
|
"queryKey" | "queryFn"
|
||||||
>;
|
>;
|
||||||
}) =>
|
}) =>
|
||||||
useQuery({
|
useInfiniteQuery({
|
||||||
queryKey: secretApprovalRequestKeys.list({ workspaceId, environment }),
|
queryKey: secretApprovalRequestKeys.list({
|
||||||
queryFn: () => fetchSecretApprovalRequestList({ workspaceId, environment }),
|
workspaceId,
|
||||||
enabled: Boolean(workspaceId) && (options?.enabled ?? true)
|
environment,
|
||||||
|
committer,
|
||||||
|
status
|
||||||
|
}),
|
||||||
|
queryFn: ({ pageParam }) =>
|
||||||
|
fetchSecretApprovalRequestList({
|
||||||
|
workspaceId,
|
||||||
|
environment,
|
||||||
|
status,
|
||||||
|
committer,
|
||||||
|
limit,
|
||||||
|
offset: pageParam
|
||||||
|
}),
|
||||||
|
enabled: Boolean(workspaceId) && (options?.enabled ?? true),
|
||||||
|
getNextPageParam: (lastPage, pages) => {
|
||||||
|
return lastPage?.length !== 0 ? pages.length * limit : undefined;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const fetchSecretApprovalRequestDetails = async ({
|
const fetchSecretApprovalRequestDetails = async ({
|
||||||
@@ -134,9 +176,10 @@ export const useGetSecretApprovalRequestDetails = ({
|
|||||||
queryFn: () => fetchSecretApprovalRequestDetails({ id }),
|
queryFn: () => fetchSecretApprovalRequestDetails({ id }),
|
||||||
select: (data) => ({
|
select: (data) => ({
|
||||||
...data,
|
...data,
|
||||||
commits: data.commits.map(({ secret, op, newVersion }) => ({
|
commits: data.commits.map(({ secretVersion, op, newVersion, secret }) => ({
|
||||||
op,
|
op,
|
||||||
secret: secret ? decryptSecrets([secret], decryptKey)[0] : undefined,
|
secret,
|
||||||
|
secretVersion: secretVersion ? decryptSecrets([secretVersion], decryptKey)[0] : undefined,
|
||||||
newVersion: newVersion ? decryptSecretApprovalSecret(newVersion, decryptKey) : undefined
|
newVersion: newVersion ? decryptSecretApprovalSecret(newVersion, decryptKey) : undefined
|
||||||
}))
|
}))
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -60,7 +60,8 @@ export type TSecretApprovalRequest<
|
|||||||
policy: TSecretApprovalPolicy;
|
policy: TSecretApprovalPolicy;
|
||||||
commits: {
|
commits: {
|
||||||
// if there is no secret means it was creation
|
// if there is no secret means it was creation
|
||||||
secret?: J;
|
secret?: { version: number };
|
||||||
|
secretVersion: J;
|
||||||
// if there is no new version its for Delete
|
// if there is no new version its for Delete
|
||||||
newVersion?: T;
|
newVersion?: T;
|
||||||
op: CommitType;
|
op: CommitType;
|
||||||
@@ -70,6 +71,10 @@ export type TSecretApprovalRequest<
|
|||||||
export type TGetSecretApprovalRequestList = {
|
export type TGetSecretApprovalRequestList = {
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
environment?: string;
|
environment?: string;
|
||||||
|
status?: "open" | "close";
|
||||||
|
committer?: string;
|
||||||
|
limit?: number;
|
||||||
|
offset?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TGetSecretApprovalRequestDetails = {
|
export type TGetSecretApprovalRequestDetails = {
|
||||||
@@ -81,3 +86,7 @@ export type TUpdateSecretApprovalRequestStatusDTO = {
|
|||||||
status: ApprovalStatus;
|
status: ApprovalStatus;
|
||||||
id: string;
|
id: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TPerformSecretApprovalRequestMerge = {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
|||||||
+145
-33
@@ -1,8 +1,21 @@
|
|||||||
import { useState } from "react";
|
import { Fragment, useState } from "react";
|
||||||
import { faCheck, faCodeBranch } from "@fortawesome/free-solid-svg-icons";
|
import {
|
||||||
|
faCheck,
|
||||||
|
faCheckCircle,
|
||||||
|
faChevronDown,
|
||||||
|
faCodeBranch
|
||||||
|
} from "@fortawesome/free-solid-svg-icons";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { AnimatePresence, motion } from "framer-motion";
|
import { AnimatePresence, motion } from "framer-motion";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuTrigger
|
||||||
|
} from "@app/components/v2";
|
||||||
import { useWorkspace } from "@app/context";
|
import { useWorkspace } from "@app/context";
|
||||||
import { useGetSecretApprovalRequests, useGetWorkspaceUsers } from "@app/hooks/api";
|
import { useGetSecretApprovalRequests, useGetWorkspaceUsers } from "@app/hooks/api";
|
||||||
import { TSecretApprovalRequest, TWorkspaceUser } from "@app/hooks/api/types";
|
import { TSecretApprovalRequest, TWorkspaceUser } from "@app/hooks/api/types";
|
||||||
@@ -17,7 +30,22 @@ export const SecretApprovalRequest = () => {
|
|||||||
const workspaceId = currentWorkspace?._id || "";
|
const workspaceId = currentWorkspace?._id || "";
|
||||||
const [selectedApproval, setSelectedApproval] = useState<TSecretApprovalRequest | null>(null);
|
const [selectedApproval, setSelectedApproval] = useState<TSecretApprovalRequest | null>(null);
|
||||||
|
|
||||||
const { data: secretApprovalRequests } = useGetSecretApprovalRequests({ workspaceId });
|
// filters
|
||||||
|
const [statusFilter, setStatusFilter] = useState<"open" | "close">("open");
|
||||||
|
const [envFilter, setEnvFilter] = useState<string>();
|
||||||
|
const [committerFilter, setCommitterFilter] = useState<string>();
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: secretApprovalRequests,
|
||||||
|
isFetchingNextPage: isFetchingNextApprovalRequest,
|
||||||
|
fetchNextPage: fetchNextApprovalRequest,
|
||||||
|
hasNextPage: hasNextApprovalPage
|
||||||
|
} = useGetSecretApprovalRequests({
|
||||||
|
workspaceId,
|
||||||
|
status: statusFilter,
|
||||||
|
environment: envFilter,
|
||||||
|
committer: committerFilter
|
||||||
|
});
|
||||||
const { data: members } = useGetWorkspaceUsers(workspaceId);
|
const { data: members } = useGetWorkspaceUsers(workspaceId);
|
||||||
const membersGroupById = members?.reduce<Record<string, TWorkspaceUser>>(
|
const membersGroupById = members?.reduce<Record<string, TWorkspaceUser>>(
|
||||||
(prev, curr) => ({ ...prev, [curr._id]: curr }),
|
(prev, curr) => ({ ...prev, [curr._id]: curr }),
|
||||||
@@ -51,45 +79,129 @@ export const SecretApprovalRequest = () => {
|
|||||||
initial={{ opacity: 0, translateX: -30 }}
|
initial={{ opacity: 0, translateX: -30 }}
|
||||||
animate={{ opacity: 1, translateX: 0 }}
|
animate={{ opacity: 1, translateX: 0 }}
|
||||||
exit={{ opacity: 0, translateX: -30 }}
|
exit={{ opacity: 0, translateX: -30 }}
|
||||||
className="rounded-md bg-mineshaft-800 text-gray-300"
|
className="rounded-md text-gray-300"
|
||||||
>
|
>
|
||||||
<div className="p-4 px-8 flex items-center space-x-8">
|
<div className="p-4 px-8 flex items-center space-x-8 bg-mineshaft-800">
|
||||||
<div>
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={() => setStatusFilter("open")}
|
||||||
|
onKeyDown={(evt) => {
|
||||||
|
if (evt.key === "Enter") setStatusFilter("open");
|
||||||
|
}}
|
||||||
|
className={statusFilter === "close" ? "text-gray-500" : ""}
|
||||||
|
>
|
||||||
<FontAwesomeIcon icon={faCodeBranch} className="mr-2" />
|
<FontAwesomeIcon icon={faCodeBranch} className="mr-2" />
|
||||||
27 Open
|
27 Open
|
||||||
</div>
|
</div>
|
||||||
<div className="text-gray-500">
|
<div
|
||||||
|
className={statusFilter === "open" ? "text-gray-500" : ""}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={() => setStatusFilter("close")}
|
||||||
|
onKeyDown={(evt) => {
|
||||||
|
if (evt.key === "Enter") setStatusFilter("close");
|
||||||
|
}}
|
||||||
|
>
|
||||||
<FontAwesomeIcon icon={faCheck} className="mr-2" />
|
<FontAwesomeIcon icon={faCheck} className="mr-2" />
|
||||||
27 Closed
|
27 Closed
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex-grow flex justify-end space-x-8">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger>
|
||||||
|
<Button
|
||||||
|
variant="plain"
|
||||||
|
colorSchema="secondary"
|
||||||
|
className={envFilter ? "text-white" : "text-bunker-300"}
|
||||||
|
rightIcon={<FontAwesomeIcon icon={faChevronDown} size="sm" className="ml-2" />}
|
||||||
|
>
|
||||||
|
Environments
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent>
|
||||||
|
<DropdownMenuLabel>Select an environment</DropdownMenuLabel>
|
||||||
|
{currentWorkspace?.environments.map(({ slug, name }) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => setEnvFilter((state) => (state === slug ? undefined : slug))}
|
||||||
|
key={`request-filter-${slug}`}
|
||||||
|
icon={envFilter === slug && <FontAwesomeIcon icon={faCheckCircle} />}
|
||||||
|
iconPos="right"
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger>
|
||||||
|
<Button
|
||||||
|
variant="plain"
|
||||||
|
colorSchema="secondary"
|
||||||
|
className={committerFilter ? "text-white" : "text-bunker-300"}
|
||||||
|
rightIcon={<FontAwesomeIcon icon={faChevronDown} size="sm" className="ml-2" />}
|
||||||
|
>
|
||||||
|
Author
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuLabel>Select an author</DropdownMenuLabel>
|
||||||
|
{members?.map(({ user, _id }) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
setCommitterFilter((state) => (state === _id ? undefined : _id))
|
||||||
|
}
|
||||||
|
key={`request-filter-member-${_id}`}
|
||||||
|
icon={committerFilter === _id && <FontAwesomeIcon icon={faCheckCircle} />}
|
||||||
|
iconPos="right"
|
||||||
|
>
|
||||||
|
{user.email}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col border-t border-mineshaft-600">
|
<div className="flex flex-col border-t border-mineshaft-600 bg-mineshaft-800">
|
||||||
{secretApprovalRequests?.map((secretApproval) => {
|
{secretApprovalRequests?.pages?.map((group, i) => (
|
||||||
const { _id: reqId, commits, committer } = secretApproval;
|
<Fragment key={`secret-approval-request-${i + 1}`}>
|
||||||
return (
|
{group?.map((secretApproval) => {
|
||||||
<div
|
const { _id: reqId, commits, committer } = secretApproval;
|
||||||
key={reqId}
|
return (
|
||||||
className="flex flex-col px-8 py-4 hover:bg-mineshaft-700"
|
<div
|
||||||
role="button"
|
key={reqId}
|
||||||
tabIndex={0}
|
className="flex flex-col px-8 py-4 hover:bg-mineshaft-700"
|
||||||
onClick={() => setSelectedApproval(secretApproval)}
|
role="button"
|
||||||
onKeyDown={(evt) => {
|
tabIndex={0}
|
||||||
if (evt.key === "Enter") setSelectedApproval(secretApproval);
|
onClick={() => setSelectedApproval(secretApproval)}
|
||||||
}}
|
onKeyDown={(evt) => {
|
||||||
>
|
if (evt.key === "Enter") setSelectedApproval(secretApproval);
|
||||||
<div className="mb-1">
|
}}
|
||||||
<FontAwesomeIcon icon={faCodeBranch} className="mr-2" />
|
>
|
||||||
{generateCommitText(commits)}
|
<div className="mb-1">
|
||||||
</div>
|
<FontAwesomeIcon icon={faCodeBranch} className="mr-2" />
|
||||||
<span className="text-xs text-gray-500">
|
{generateCommitText(commits)}
|
||||||
Opened 2 hours ago by {membersGroupById?.[committer]?.user?.firstName}{" "}
|
</div>
|
||||||
{membersGroupById?.[committer]?.user?.lastName} (
|
<span className="text-xs text-gray-500">
|
||||||
{membersGroupById?.[committer]?.user?.email}) - Review required
|
Opened 2 hours ago by {membersGroupById?.[committer]?.user?.firstName}{" "}
|
||||||
</span>
|
{membersGroupById?.[committer]?.user?.lastName} (
|
||||||
</div>
|
{membersGroupById?.[committer]?.user?.email}) - Review required
|
||||||
);
|
</span>
|
||||||
})}
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</Fragment>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<Button
|
||||||
|
className="mt-4 text-sm"
|
||||||
|
isFullWidth
|
||||||
|
variant="star"
|
||||||
|
isLoading={isFetchingNextApprovalRequest}
|
||||||
|
isDisabled={isFetchingNextApprovalRequest || !hasNextApprovalPage}
|
||||||
|
onClick={() => fetchNextApprovalRequest()}
|
||||||
|
>
|
||||||
|
{hasNextApprovalPage ? "Load More" : "End of history"}
|
||||||
|
</Button>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
|
|||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
import { faCheck, faClose } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
|
||||||
|
import { Button } from "@app/components/v2";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
hasMerged?: boolean;
|
||||||
|
status: "close" | "open";
|
||||||
|
isMergable?: boolean;
|
||||||
|
isMerging?: boolean;
|
||||||
|
onMerge: () => void;
|
||||||
|
onClose?: () => void;
|
||||||
|
};
|
||||||
|
export const SecretApprovalRequestAction = ({
|
||||||
|
hasMerged,
|
||||||
|
status,
|
||||||
|
isMergable,
|
||||||
|
onMerge,
|
||||||
|
isMerging,
|
||||||
|
onClose
|
||||||
|
}: Props) => {
|
||||||
|
if (!hasMerged && status === "open") {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faCheck} />}
|
||||||
|
isDisabled={!isMergable}
|
||||||
|
isLoading={isMerging}
|
||||||
|
onClick={onMerge}
|
||||||
|
>
|
||||||
|
Merge
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={onClose}
|
||||||
|
variant="outline_bg"
|
||||||
|
leftIcon={<FontAwesomeIcon icon={faClose} />}
|
||||||
|
>
|
||||||
|
Close request
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasMerged && status === "close") return <span>This approval request has been merged</span>;
|
||||||
|
|
||||||
|
return <span>This approval request has been closed</span>;
|
||||||
|
};
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
type Props = {};
|
|
||||||
+75
-23
@@ -4,7 +4,6 @@ import {
|
|||||||
faCheck,
|
faCheck,
|
||||||
faCheckCircle,
|
faCheckCircle,
|
||||||
faCircle,
|
faCircle,
|
||||||
faClose,
|
|
||||||
faCodeBranch,
|
faCodeBranch,
|
||||||
faXmarkCircle
|
faXmarkCircle
|
||||||
} from "@fortawesome/free-solid-svg-icons";
|
} from "@fortawesome/free-solid-svg-icons";
|
||||||
@@ -25,15 +24,19 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Tr
|
Tr
|
||||||
} from "@app/components/v2";
|
} from "@app/components/v2";
|
||||||
|
import { useUser } from "@app/context";
|
||||||
import {
|
import {
|
||||||
useGetSecretApprovalRequestDetails,
|
useGetSecretApprovalRequestDetails,
|
||||||
useGetUserWsKey,
|
useGetUserWsKey,
|
||||||
|
usePerformSecretApprovalRequestMerge,
|
||||||
useUpdateSecretApprovalRequestStatus
|
useUpdateSecretApprovalRequestStatus
|
||||||
} from "@app/hooks/api";
|
} from "@app/hooks/api";
|
||||||
import { ApprovalStatus, CommitType, TWorkspaceUser } from "@app/hooks/api/types";
|
import { ApprovalStatus, CommitType, TWorkspaceUser } from "@app/hooks/api/types";
|
||||||
|
|
||||||
import { useNotificationContext } from "~/components/context/Notifications/NotificationProvider";
|
import { useNotificationContext } from "~/components/context/Notifications/NotificationProvider";
|
||||||
|
|
||||||
|
import { SecretApprovalRequestAction } from "./SecretApprovalRequestAction";
|
||||||
|
|
||||||
export const generateCommitText = (commits: { op: CommitType }[] = []) => {
|
export const generateCommitText = (commits: { op: CommitType }[] = []) => {
|
||||||
const score: Record<string, number> = {};
|
const score: Record<string, number> = {};
|
||||||
commits.forEach(({ op }) => {
|
commits.forEach(({ op }) => {
|
||||||
@@ -94,6 +97,7 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
members = {}
|
members = {}
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const { createNotification } = useNotificationContext();
|
const { createNotification } = useNotificationContext();
|
||||||
|
const { user } = useUser();
|
||||||
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
|
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
|
||||||
const {
|
const {
|
||||||
data: secretApprovalRequestDetails,
|
data: secretApprovalRequestDetails,
|
||||||
@@ -109,9 +113,17 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
isLoading: isUpdatingRequestStatus,
|
isLoading: isUpdatingRequestStatus,
|
||||||
variables
|
variables
|
||||||
} = useUpdateSecretApprovalRequestStatus();
|
} = useUpdateSecretApprovalRequestStatus();
|
||||||
|
const { mutateAsync: performSecretApprovalMerge, isLoading: isMerging } =
|
||||||
|
usePerformSecretApprovalRequestMerge();
|
||||||
|
|
||||||
const isApproving = variables?.status === ApprovalStatus.APPROVED && isUpdatingRequestStatus;
|
const isApproving = variables?.status === ApprovalStatus.APPROVED && isUpdatingRequestStatus;
|
||||||
const isRejecting = variables?.status === ApprovalStatus.REJECTED && isUpdatingRequestStatus;
|
const isRejecting = variables?.status === ApprovalStatus.REJECTED && isUpdatingRequestStatus;
|
||||||
|
|
||||||
|
// membership of present user
|
||||||
|
const myMembership = Object.values(members).find(
|
||||||
|
({ user: membershipUser }) => membershipUser.email === user.email
|
||||||
|
);
|
||||||
|
const myMembershipId = myMembership?._id || "";
|
||||||
const reviewedMembers = secretApprovalRequestDetails?.reviewers?.reduce<
|
const reviewedMembers = secretApprovalRequestDetails?.reviewers?.reduce<
|
||||||
Record<string, ApprovalStatus>
|
Record<string, ApprovalStatus>
|
||||||
>(
|
>(
|
||||||
@@ -121,6 +133,8 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
}),
|
}),
|
||||||
{}
|
{}
|
||||||
);
|
);
|
||||||
|
const hasApproved = reviewedMembers?.[myMembershipId] === ApprovalStatus.APPROVED;
|
||||||
|
const hasRejected = reviewedMembers?.[myMembershipId] === ApprovalStatus.REJECTED;
|
||||||
|
|
||||||
const handleSecretApprovalStatusUpdate = async (status: ApprovalStatus) => {
|
const handleSecretApprovalStatusUpdate = async (status: ApprovalStatus) => {
|
||||||
try {
|
try {
|
||||||
@@ -128,6 +142,28 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
id: approvalRequestId,
|
id: approvalRequestId,
|
||||||
status
|
status
|
||||||
});
|
});
|
||||||
|
createNotification({
|
||||||
|
type: "success",
|
||||||
|
text: `Successfully ${status} the request`
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
createNotification({
|
||||||
|
type: "error",
|
||||||
|
text: "Failed to update the request status"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSecretApprovalRequestMerge = async () => {
|
||||||
|
try {
|
||||||
|
await performSecretApprovalMerge({
|
||||||
|
id: approvalRequestId
|
||||||
|
});
|
||||||
|
createNotification({
|
||||||
|
type: "success",
|
||||||
|
text: "Successfully merged the request"
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
createNotification({
|
createNotification({
|
||||||
@@ -145,6 +181,13 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
|
|
||||||
if (!isSecretApprovalRequestSuccess) return <div>Failed</div>;
|
if (!isSecretApprovalRequestSuccess) return <div>Failed</div>;
|
||||||
|
|
||||||
|
const isMergable =
|
||||||
|
secretApprovalRequestDetails?.policy?.approvals <=
|
||||||
|
secretApprovalRequestDetails?.policy?.approvers?.filter(
|
||||||
|
(approverId) => reviewedMembers?.[approverId] === ApprovalStatus.APPROVED
|
||||||
|
).length;
|
||||||
|
const hasMerged = secretApprovalRequestDetails?.hasMerged;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex space-x-6">
|
<div className="flex space-x-6">
|
||||||
<div className="flex-grow">
|
<div className="flex-grow">
|
||||||
@@ -171,26 +214,26 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
size="xs"
|
size="xs"
|
||||||
leftIcon={<FontAwesomeIcon icon={faCheck} />}
|
leftIcon={hasApproved && <FontAwesomeIcon icon={faCheck} />}
|
||||||
onClick={() => handleSecretApprovalStatusUpdate(ApprovalStatus.APPROVED)}
|
onClick={() => handleSecretApprovalStatusUpdate(ApprovalStatus.APPROVED)}
|
||||||
isLoading={isApproving}
|
isLoading={isApproving}
|
||||||
isDisabled={isApproving}
|
isDisabled={isApproving || hasApproved}
|
||||||
>
|
>
|
||||||
Approve
|
{hasApproved ? "Approved" : "Approve"}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
size="xs"
|
size="xs"
|
||||||
variant="outline_bg"
|
colorSchema="danger"
|
||||||
leftIcon={<FontAwesomeIcon icon={faClose} />}
|
leftIcon={hasRejected && <FontAwesomeIcon icon={faCheck} />}
|
||||||
onClick={() => handleSecretApprovalStatusUpdate(ApprovalStatus.REJECTED)}
|
onClick={() => handleSecretApprovalStatusUpdate(ApprovalStatus.REJECTED)}
|
||||||
isLoading={isRejecting}
|
isLoading={isRejecting}
|
||||||
isDisabled={isRejecting}
|
isDisabled={isRejecting || hasRejected}
|
||||||
>
|
>
|
||||||
Reject
|
{hasRejected ? "Rejected" : "Reject"}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col space-y-4">
|
<div className="flex flex-col space-y-4">
|
||||||
{secretApprovalRequestDetails.commits.map(({ op, secret, newVersion }, index) => (
|
{secretApprovalRequestDetails.commits.map(({ op, secretVersion, newVersion }, index) => (
|
||||||
<div key={`commit-change-secret-${index + 1}`}>
|
<div key={`commit-change-secret-${index + 1}`}>
|
||||||
<TableContainer>
|
<TableContainer>
|
||||||
<Table>
|
<Table>
|
||||||
@@ -207,16 +250,16 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
<TBody>
|
<TBody>
|
||||||
<Tr>
|
<Tr>
|
||||||
<Td className="text-red-600">OLD</Td>
|
<Td className="text-red-600">OLD</Td>
|
||||||
<Td>{secret?.key}</Td>
|
<Td>{secretVersion?.key}</Td>
|
||||||
<Td>
|
<Td>
|
||||||
<SecretInput isReadOnly value={secret?.value} />
|
<SecretInput isReadOnly value={secretVersion?.value} />
|
||||||
</Td>
|
</Td>
|
||||||
<Td>{secret?.comment}</Td>
|
<Td>{secretVersion?.comment}</Td>
|
||||||
<Td>
|
<Td>
|
||||||
{secret?.tags?.map(({ name, _id: tagId, tagColor }) => (
|
{secretVersion?.tags?.map(({ name, _id: tagId, tagColor }) => (
|
||||||
<Tag
|
<Tag
|
||||||
className="flex items-center space-x-2 w-min"
|
className="flex items-center space-x-2 w-min"
|
||||||
key={`${secret._id}-${tagId}`}
|
key={`${secretVersion._id}-${tagId}`}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
className="w-3 h-3 rounded-full"
|
className="w-3 h-3 rounded-full"
|
||||||
@@ -253,25 +296,31 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
) : (
|
) : (
|
||||||
<TBody>
|
<TBody>
|
||||||
<Tr>
|
<Tr>
|
||||||
<Td>{op === CommitType.CREATE ? newVersion?.secretKey : secret?.key}</Td>
|
<Td>
|
||||||
|
{op === CommitType.CREATE ? newVersion?.secretKey : secretVersion?.key}
|
||||||
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
<SecretInput
|
<SecretInput
|
||||||
isReadOnly
|
isReadOnly
|
||||||
value={
|
value={
|
||||||
op === CommitType.CREATE ? newVersion?.secretValue : secret?.value
|
op === CommitType.CREATE
|
||||||
|
? newVersion?.secretValue
|
||||||
|
: secretVersion?.value
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
{op === CommitType.CREATE ? newVersion?.secretComment : secret?.comment}
|
{op === CommitType.CREATE
|
||||||
|
? newVersion?.secretComment
|
||||||
|
: secretVersion?.comment}
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
{(op === CommitType.CREATE ? newVersion?.tags : secret?.tags)?.map(
|
{(op === CommitType.CREATE ? newVersion?.tags : secretVersion?.tags)?.map(
|
||||||
({ name, _id: tagId, tagColor }) => (
|
({ name, _id: tagId, tagColor }) => (
|
||||||
<Tag
|
<Tag
|
||||||
className="flex items-center space-x-2 w-min"
|
className="flex items-center space-x-2 w-min"
|
||||||
key={`${
|
key={`${
|
||||||
op === CommitType.CREATE ? newVersion?._id : secret?._id
|
op === CommitType.CREATE ? newVersion?._id : secretVersion?._id
|
||||||
}-${tagId}`}
|
}-${tagId}`}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -292,10 +341,13 @@ export const SecretApprovalRequestChanges = ({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center px-4 py-6 rounded-lg space-x-6 bg-mineshaft-800 mt-8">
|
<div className="flex items-center px-4 py-6 rounded-lg space-x-6 bg-mineshaft-800 mt-8">
|
||||||
<Button leftIcon={<FontAwesomeIcon icon={faCheck} />}>Merge</Button>
|
<SecretApprovalRequestAction
|
||||||
<Button variant="outline_bg" leftIcon={<FontAwesomeIcon icon={faClose} />}>
|
hasMerged={hasMerged}
|
||||||
Close request
|
status={secretApprovalRequestDetails.status}
|
||||||
</Button>
|
isMerging={isMerging}
|
||||||
|
isMergable={isMergable}
|
||||||
|
onMerge={handleSecretApprovalRequestMerge}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="w-1/5 pt-4 sticky top-0" style={{ minWidth: "240px" }}>
|
<div className="w-1/5 pt-4 sticky top-0" style={{ minWidth: "240px" }}>
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
useGetImportedSecrets,
|
useGetImportedSecrets,
|
||||||
useGetProjectFolders,
|
useGetProjectFolders,
|
||||||
useGetProjectSecrets,
|
useGetProjectSecrets,
|
||||||
|
useGetSecretApprovalPolicyOfABoard,
|
||||||
useGetSecretImports,
|
useGetSecretImports,
|
||||||
useGetUserWsKey,
|
useGetUserWsKey,
|
||||||
useGetWorkspaceSnapshotList,
|
useGetWorkspaceSnapshotList,
|
||||||
@@ -118,6 +119,13 @@ export const SecretMainPage = () => {
|
|||||||
// fetch tags
|
// fetch tags
|
||||||
const { data: tags } = useGetWsTags(canReadSecret ? workspaceId : "");
|
const { data: tags } = useGetWsTags(canReadSecret ? workspaceId : "");
|
||||||
|
|
||||||
|
const { data: boardPolicy } = useGetSecretApprovalPolicyOfABoard({
|
||||||
|
workspaceId,
|
||||||
|
environment,
|
||||||
|
secretPath
|
||||||
|
});
|
||||||
|
const isProtectedBranch = Boolean(boardPolicy);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: snapshotList,
|
data: snapshotList,
|
||||||
isFetchingNextPage: isFetchingNextSnapshotList,
|
isFetchingNextPage: isFetchingNextSnapshotList,
|
||||||
@@ -207,6 +215,7 @@ export const SecretMainPage = () => {
|
|||||||
secretPath={secretPath}
|
secretPath={secretPath}
|
||||||
isProjectRelated
|
isProjectRelated
|
||||||
onEnvChange={handleEnvChange}
|
onEnvChange={handleEnvChange}
|
||||||
|
isProtectedBranch={isProtectedBranch}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{!isRollbackMode ? (
|
{!isRollbackMode ? (
|
||||||
@@ -281,6 +290,7 @@ export const SecretMainPage = () => {
|
|||||||
workspaceId={workspaceId}
|
workspaceId={workspaceId}
|
||||||
secretPath={secretPath}
|
secretPath={secretPath}
|
||||||
decryptFileKey={decryptFileKey!}
|
decryptFileKey={decryptFileKey!}
|
||||||
|
isProtectedBranch={isProtectedBranch}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{!canReadSecret && folders?.length === 0 && <PermissionDeniedBanner />}
|
{!canReadSecret && folders?.length === 0 && <PermissionDeniedBanner />}
|
||||||
@@ -292,6 +302,7 @@ export const SecretMainPage = () => {
|
|||||||
decryptFileKey={decryptFileKey!}
|
decryptFileKey={decryptFileKey!}
|
||||||
secretPath={secretPath}
|
secretPath={secretPath}
|
||||||
autoCapitalize={currentWorkspace?.autoCapitalization}
|
autoCapitalize={currentWorkspace?.autoCapitalization}
|
||||||
|
isProtectedBranch={isProtectedBranch}
|
||||||
/>
|
/>
|
||||||
<SecretDropzone
|
<SecretDropzone
|
||||||
secrets={secrets}
|
secrets={secrets}
|
||||||
@@ -301,6 +312,7 @@ export const SecretMainPage = () => {
|
|||||||
secretPath={secretPath}
|
secretPath={secretPath}
|
||||||
isSmaller={isNotEmtpy}
|
isSmaller={isNotEmtpy}
|
||||||
environments={currentWorkspace?.environments}
|
environments={currentWorkspace?.environments}
|
||||||
|
isProtectedBranch={isProtectedBranch}
|
||||||
/>
|
/>
|
||||||
<PitDrawer
|
<PitDrawer
|
||||||
secretSnaphots={snapshotList}
|
secretSnaphots={snapshotList}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ type Props = {
|
|||||||
secretPath?: string;
|
secretPath?: string;
|
||||||
// modal props
|
// modal props
|
||||||
autoCapitalize?: boolean;
|
autoCapitalize?: boolean;
|
||||||
|
isProtectedBranch?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CreateSecretForm = ({
|
export const CreateSecretForm = ({
|
||||||
@@ -30,7 +31,8 @@ export const CreateSecretForm = ({
|
|||||||
workspaceId,
|
workspaceId,
|
||||||
decryptFileKey,
|
decryptFileKey,
|
||||||
secretPath = "/",
|
secretPath = "/",
|
||||||
autoCapitalize = true
|
autoCapitalize = true,
|
||||||
|
isProtectedBranch = false
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -62,7 +64,9 @@ export const CreateSecretForm = ({
|
|||||||
reset();
|
reset();
|
||||||
createNotification({
|
createNotification({
|
||||||
type: "success",
|
type: "success",
|
||||||
text: "Successfully created secret"
|
text: isProtectedBranch
|
||||||
|
? "Requested changes have been send for review"
|
||||||
|
: "Successfully created secret"
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ type Props = {
|
|||||||
environment: string;
|
environment: string;
|
||||||
secretPath: string;
|
secretPath: string;
|
||||||
secrets?: DecryptedSecret[];
|
secrets?: DecryptedSecret[];
|
||||||
|
isProtectedBranch?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const SecretDropzone = ({
|
export const SecretDropzone = ({
|
||||||
@@ -52,7 +53,8 @@ export const SecretDropzone = ({
|
|||||||
decryptFileKey,
|
decryptFileKey,
|
||||||
environment,
|
environment,
|
||||||
secretPath,
|
secretPath,
|
||||||
secrets = []
|
secrets = [],
|
||||||
|
isProtectedBranch = false
|
||||||
}: Props): JSX.Element => {
|
}: Props): JSX.Element => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [isDragActive, setDragActive] = useToggle();
|
const [isDragActive, setDragActive] = useToggle();
|
||||||
@@ -195,7 +197,9 @@ export const SecretDropzone = ({
|
|||||||
handlePopUpClose("overlapKeyWarning");
|
handlePopUpClose("overlapKeyWarning");
|
||||||
createNotification({
|
createNotification({
|
||||||
type: "success",
|
type: "success",
|
||||||
text: "Successfully uploaded secrets"
|
text: isProtectedBranch
|
||||||
|
? "Uploaded changes have been send for review"
|
||||||
|
: "Successfully uploaded secrets"
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
|
|||||||
@@ -49,7 +49,8 @@ type Props = {
|
|||||||
onDeleteSecret: () => void;
|
onDeleteSecret: () => void;
|
||||||
onSaveSecret: (
|
onSaveSecret: (
|
||||||
orgSec: DecryptedSecret,
|
orgSec: DecryptedSecret,
|
||||||
modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] }
|
modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] },
|
||||||
|
cb?: () => void
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
tags: WsTag[];
|
tags: WsTag[];
|
||||||
onCreateTag: () => void;
|
onCreateTag: () => void;
|
||||||
@@ -143,7 +144,7 @@ export const SecretDetailSidebar = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleFormSubmit = async (data: TFormSchema) => {
|
const handleFormSubmit = async (data: TFormSchema) => {
|
||||||
await onSaveSecret(secret, { ...secret, ...data });
|
await onSaveSecret(secret, { ...secret, ...data }, () => reset());
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -54,7 +54,8 @@ type Props = {
|
|||||||
secret: DecryptedSecret;
|
secret: DecryptedSecret;
|
||||||
onSaveSecret: (
|
onSaveSecret: (
|
||||||
orgSec: DecryptedSecret,
|
orgSec: DecryptedSecret,
|
||||||
modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] }
|
modSec: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] },
|
||||||
|
cb?: () => void
|
||||||
) => Promise<void>;
|
) => Promise<void>;
|
||||||
onDeleteSecret: (sec: DecryptedSecret) => void;
|
onDeleteSecret: (sec: DecryptedSecret) => void;
|
||||||
onDetailViewSecret: (sec: DecryptedSecret) => void;
|
onDetailViewSecret: (sec: DecryptedSecret) => void;
|
||||||
@@ -148,13 +149,14 @@ export const SecretItem = memo(
|
|||||||
);
|
);
|
||||||
setValue("valueOverride", secret?.valueOverride, { shouldDirty: !isUnsavedOverride });
|
setValue("valueOverride", secret?.valueOverride, { shouldDirty: !isUnsavedOverride });
|
||||||
} else {
|
} else {
|
||||||
|
reset();
|
||||||
setValue("overrideAction", SecretActionType.Modified, { shouldDirty: true });
|
setValue("overrideAction", SecretActionType.Modified, { shouldDirty: true });
|
||||||
setValue("valueOverride", "", { shouldDirty: true });
|
setValue("valueOverride", "", { shouldDirty: true });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleFormSubmit = async (data: TFormSchema) => {
|
const handleFormSubmit = async (data: TFormSchema) => {
|
||||||
await onSaveSecret(secret, { ...secret, ...data });
|
await onSaveSecret(secret, { ...secret, ...data }, () => reset());
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleTagSelect = (tag: WsTag) => {
|
const handleTagSelect = (tag: WsTag) => {
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ type Props = {
|
|||||||
sortDir?: SortDir;
|
sortDir?: SortDir;
|
||||||
tags?: WsTag[];
|
tags?: WsTag[];
|
||||||
isVisible?: boolean;
|
isVisible?: boolean;
|
||||||
|
isProtectedBranch?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const reorderSecretGroupByUnderscore = (secrets: DecryptedSecret[], sortDir: SortDir) => {
|
const reorderSecretGroupByUnderscore = (secrets: DecryptedSecret[], sortDir: SortDir) => {
|
||||||
@@ -84,7 +85,8 @@ export const SecretListView = ({
|
|||||||
filter,
|
filter,
|
||||||
sortDir = SortDir.ASC,
|
sortDir = SortDir.ASC,
|
||||||
tags: wsTags = [],
|
tags: wsTags = [],
|
||||||
isVisible
|
isVisible,
|
||||||
|
isProtectedBranch = false
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const { createNotification } = useNotificationContext();
|
const { createNotification } = useNotificationContext();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -178,8 +180,10 @@ export const SecretListView = ({
|
|||||||
const handleSaveSecret = useCallback(
|
const handleSaveSecret = useCallback(
|
||||||
async (
|
async (
|
||||||
orgSecret: DecryptedSecret,
|
orgSecret: DecryptedSecret,
|
||||||
modSecret: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] }
|
modSecret: Omit<DecryptedSecret, "tags"> & { tags: { _id: string }[] },
|
||||||
|
cb?: () => void
|
||||||
) => {
|
) => {
|
||||||
|
console.log(orgSecret, modSecret);
|
||||||
const { key: oldKey } = orgSecret;
|
const { key: oldKey } = orgSecret;
|
||||||
const { key, value, overrideAction, idOverride, valueOverride, tags, comment } = modSecret;
|
const { key, value, overrideAction, idOverride, valueOverride, tags, comment } = modSecret;
|
||||||
const hasKeyChanged = oldKey !== key;
|
const hasKeyChanged = oldKey !== key;
|
||||||
@@ -193,6 +197,19 @@ export const SecretListView = ({
|
|||||||
) && isSameTags;
|
) && isSameTags;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// personal secret change
|
||||||
|
if (overrideAction === "deleted") {
|
||||||
|
await handleSecretOperation("delete", "personal", oldKey);
|
||||||
|
} else if (overrideAction && idOverride) {
|
||||||
|
await handleSecretOperation("update", "personal", oldKey, {
|
||||||
|
value: valueOverride,
|
||||||
|
newKey: hasKeyChanged ? key : undefined,
|
||||||
|
skipMultilineEncoding: modSecret.skipMultilineEncoding
|
||||||
|
});
|
||||||
|
} else if (overrideAction) {
|
||||||
|
await handleSecretOperation("create", "personal", oldKey, { value: valueOverride });
|
||||||
|
}
|
||||||
|
|
||||||
// shared secret change
|
// shared secret change
|
||||||
if (!isSharedSecUnchanged) {
|
if (!isSharedSecUnchanged) {
|
||||||
await handleSecretOperation("update", "shared", oldKey, {
|
await handleSecretOperation("update", "shared", oldKey, {
|
||||||
@@ -202,19 +219,7 @@ export const SecretListView = ({
|
|||||||
newKey: hasKeyChanged ? key : undefined,
|
newKey: hasKeyChanged ? key : undefined,
|
||||||
skipMultilineEncoding: modSecret.skipMultilineEncoding
|
skipMultilineEncoding: modSecret.skipMultilineEncoding
|
||||||
});
|
});
|
||||||
}
|
if (isProtectedBranch) cb?.();
|
||||||
|
|
||||||
// personal secret change
|
|
||||||
if (overrideAction === "deleted") {
|
|
||||||
await handleSecretOperation("delete", "personal", key);
|
|
||||||
} else if (overrideAction && idOverride) {
|
|
||||||
await handleSecretOperation("update", "personal", oldKey, {
|
|
||||||
value: valueOverride,
|
|
||||||
newKey: hasKeyChanged ? key : undefined,
|
|
||||||
skipMultilineEncoding: modSecret.skipMultilineEncoding
|
|
||||||
});
|
|
||||||
} else if (overrideAction) {
|
|
||||||
await handleSecretOperation("create", "personal", key, { value: valueOverride });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
queryClient.invalidateQueries(
|
queryClient.invalidateQueries(
|
||||||
@@ -229,7 +234,9 @@ export const SecretListView = ({
|
|||||||
handlePopUpClose("secretDetail");
|
handlePopUpClose("secretDetail");
|
||||||
createNotification({
|
createNotification({
|
||||||
type: "success",
|
type: "success",
|
||||||
text: "Successfully saved secrets"
|
text: isProtectedBranch
|
||||||
|
? "Requested changes have been sent for review"
|
||||||
|
: "Successfully saved secrets"
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
@@ -259,7 +266,9 @@ export const SecretListView = ({
|
|||||||
handlePopUpClose("secretDetail");
|
handlePopUpClose("secretDetail");
|
||||||
createNotification({
|
createNotification({
|
||||||
type: "success",
|
type: "success",
|
||||||
text: "Successfully deleted secret"
|
text: isProtectedBranch
|
||||||
|
? "Requested changes have been sent for review"
|
||||||
|
: "Successfully deleted secret"
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
|||||||
Reference in New Issue
Block a user