refactor(ui): migrated secret endpoints of e2ee to raw

This commit is contained in:
=
2024-07-15 23:15:37 +05:30
parent 547be80dcf
commit 4caa77e28a
30 changed files with 429 additions and 955 deletions

View File

@@ -1,30 +1,4 @@
import crypto from "crypto"; import { SecretDataProps } from "public/data/frequentInterfaces";
import { SecretDataProps, Tag } from "public/data/frequentInterfaces";
import { fetchUserWsKey } from "@app/hooks/api/keys/queries";
import { SecretType } from "@app/hooks/api/types";
import { decryptAssymmetric, encryptSymmetric } from "../cryptography/crypto";
interface EncryptedSecretProps {
id: string;
createdAt: string;
environment: string;
secretName: string;
secretCommentCiphertext: string;
secretCommentIV: string;
secretCommentTag: string;
secretKeyCiphertext: string;
secretKeyIV: string;
secretKeyTag: string;
secretValueCiphertext: string;
secretValueIV: string;
secretValueTag: string;
type: SecretType;
tags: Tag[];
}
/** /**
* Encypt secrets before pushing the to the DB * Encypt secrets before pushing the to the DB
* @param {object} obj * @param {object} obj
@@ -34,7 +8,6 @@ interface EncryptedSecretProps {
*/ */
const encryptSecrets = async ({ const encryptSecrets = async ({
secretsToEncrypt, secretsToEncrypt,
workspaceId,
env env
}: { }: {
secretsToEncrypt: SecretDataProps[]; secretsToEncrypt: SecretDataProps[];
@@ -43,74 +16,14 @@ const encryptSecrets = async ({
}) => { }) => {
let secrets; let secrets;
try { try {
// const sharedKey = await getLatestFileKey({ workspaceId });
const wsKey = await fetchUserWsKey(workspaceId);
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string;
let randomBytes: string;
if (wsKey) {
// case: a (shared) key exists for the workspace
randomBytes = decryptAssymmetric({
ciphertext: wsKey.encryptedKey,
nonce: wsKey.nonce,
publicKey: wsKey.sender.publicKey,
privateKey: PRIVATE_KEY
});
} else {
// case: a (shared) key does not exist for the workspace
randomBytes = crypto.randomBytes(16).toString("hex");
}
secrets = secretsToEncrypt.map((secret) => { secrets = secretsToEncrypt.map((secret) => {
// encrypt key const result = {
const {
ciphertext: secretKeyCiphertext,
iv: secretKeyIV,
tag: secretKeyTag
} = encryptSymmetric({
plaintext: secret.key,
key: randomBytes
});
// encrypt value
const {
ciphertext: secretValueCiphertext,
iv: secretValueIV,
tag: secretValueTag
} = encryptSymmetric({
plaintext: secret.value ?? "",
key: randomBytes
});
// encrypt comment
const {
ciphertext: secretCommentCiphertext,
iv: secretCommentIV,
tag: secretCommentTag
} = encryptSymmetric({
plaintext: secret.comment ?? "",
key: randomBytes
});
const result: EncryptedSecretProps = {
id: secret.id, id: secret.id,
createdAt: "", createdAt: "",
environment: env, environment: env,
secretName: secret.key, secretKey: secret.key,
secretKeyCiphertext, secretValue: secret.value,
secretKeyIV, secretComment: secret.comment,
secretKeyTag,
secretValueCiphertext,
secretValueIV,
secretValueTag,
secretCommentCiphertext,
secretCommentIV,
secretCommentTag,
type:
secret.valueOverride === undefined || secret?.value !== secret?.valueOverride
? SecretType.Shared
: SecretType.Personal,
tags: secret.tags tags: secret.tags
}; };

View File

@@ -5,7 +5,7 @@ import * as Popover from "@radix-ui/react-popover";
import { useWorkspace } from "@app/context"; import { useWorkspace } from "@app/context";
import { useDebounce, useToggle } from "@app/hooks"; import { useDebounce, useToggle } from "@app/hooks";
import { useGetProjectFolders, useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api"; import { useGetProjectFolders, useGetProjectSecrets } from "@app/hooks/api";
import { SecretInput } from "../SecretInput"; import { SecretInput } from "../SecretInput";
@@ -76,7 +76,6 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
) => { ) => {
const { currentWorkspace } = useWorkspace(); const { currentWorkspace } = useWorkspace();
const workspaceId = currentWorkspace?.id || ""; const workspaceId = currentWorkspace?.id || "";
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const debouncedValue = useDebounce(value, 500); const debouncedValue = useDebounce(value, 500);
@@ -121,7 +120,6 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
const isPopupOpen = Boolean(suggestionSource.isOpen) && isFocused; const isPopupOpen = Boolean(suggestionSource.isOpen) && isFocused;
const { data: secrets } = useGetProjectSecrets({ const { data: secrets } = useGetProjectSecrets({
decryptFileKey: decryptFileKey!,
environment: suggestionSource.environment || "", environment: suggestionSource.environment || "",
secretPath: suggestionSource.secretPath || "", secretPath: suggestionSource.secretPath || "",
workspaceId, workspaceId,
@@ -193,8 +191,9 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
); );
// mid will be computed value inside the interpolation // mid will be computed value inside the interpolation
const mid = suggestionSource.isDeep const mid = suggestionSource.isDeep
? `${suggestionSource.value.slice(0, -suggestionSource.predicate.length || undefined)}${selectedSuggestion.slug ? `${suggestionSource.value.slice(0, -suggestionSource.predicate.length || undefined)}${
}` selectedSuggestion.slug
}`
: selectedSuggestion.slug; : selectedSuggestion.slug;
// whether we should append . or closing bracket on selecting suggestion // whether we should append . or closing bracket on selecting suggestion
const closingSymbol = getClosingSymbol( const closingSymbol = getClosingSymbol(
@@ -328,8 +327,9 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
key={`secret-reference-secret-${i + 1}`} key={`secret-reference-secret-${i + 1}`}
> >
<div <div
className={`${highlightedIndex === i ? "bg-gray-600" : "" className={`${
} text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`} highlightedIndex === i ? "bg-gray-600" : ""
} text-md relative mb-0.5 flex w-full cursor-pointer select-none items-center justify-between rounded-md px-2 py-2 outline-none transition-all hover:bg-mineshaft-500 data-[highlighted]:bg-mineshaft-500`}
> >
<div className="flex w-full gap-2"> <div className="flex w-full gap-2">
<div className="flex items-center text-yellow-700"> <div className="flex items-center text-yellow-700">

View File

@@ -1,81 +1,40 @@
import encryptSecrets from "@app/components/utilities/secrets/encryptSecrets"; import { apiRequest } from "@app/config/request";
import { createSecret } from "@app/hooks/api/secrets/mutations";
import { createWorkspace } from "@app/hooks/api/workspace/queries"; import { createWorkspace } from "@app/hooks/api/workspace/queries";
const secretsToBeAdded = [ const secretsToBeAdded = [
{ {
pos: 0, secretKey: "DATABASE_URL",
key: "DATABASE_URL",
// eslint-disable-next-line no-template-curly-in-string // eslint-disable-next-line no-template-curly-in-string
value: "mongodb+srv://${DB_USERNAME}:${DB_PASSWORD}@mongodb.net", secretValue: "mongodb+srv://${DB_USERNAME}:${DB_PASSWORD}@mongodb.net",
valueOverride: undefined, secretComment: "Secret referencing example"
comment: "Secret referencing example",
id: "",
tags: []
}, },
{ {
pos: 1, secretKey: "DB_USERNAME",
key: "DB_USERNAME", secretValue: "OVERRIDE_THIS",
value: "OVERRIDE_THIS", secretComment: "Override secrets with personal value"
valueOverride: undefined,
comment: "Override secrets with personal value",
id: "",
tags: []
}, },
{ {
pos: 2, secretKey: "DB_PASSWORD",
key: "DB_PASSWORD", secretValue: "OVERRIDE_THIS",
value: "OVERRIDE_THIS", secretComment: "Another secret override"
valueOverride: undefined,
comment: "Another secret override",
id: "",
tags: []
}, },
{ {
pos: 3, secretKey: "DB_PASSWORD",
key: "DB_USERNAME", secretValue: "example_password"
value: "user1234",
valueOverride: "user1234",
comment: "",
id: "",
tags: []
}, },
{ {
pos: 4, secretKey: "TWILIO_AUTH_TOKEN",
key: "DB_PASSWORD", secretValue: "example_twillio_token"
value: "example_password",
valueOverride: "example_password",
comment: "",
id: "",
tags: []
}, },
{ {
pos: 5, secretKey: "WEBSITE_URL",
key: "TWILIO_AUTH_TOKEN", secretValue: "http://localhost:3000"
value: "example_twillio_token",
valueOverride: undefined,
comment: "",
id: "",
tags: []
},
{
pos: 6,
key: "WEBSITE_URL",
value: "http://localhost:3000",
valueOverride: undefined,
comment: "",
id: "",
tags: []
} }
]; ];
/** /**
* Create and initialize a new project in organization with id [organizationId] * Create and initialize a new project in organization with id [organizationId]
* Note: current user should be a member of the organization * Note: current user should be a member of the organization
* @param {Object} obj
* @param {String} obj.organizationId - id of organization
* @param {String} obj.projectName - name of new project
* @returns {Project} project - new project
*/ */
const initProjectHelper = async ({ projectName }: { projectName: string }) => { const initProjectHelper = async ({ projectName }: { projectName: string }) => {
// create new project // create new project
@@ -85,37 +44,14 @@ const initProjectHelper = async ({ projectName }: { projectName: string }) => {
projectName projectName
}); });
// encrypt and upload secrets to new project
const secrets = await encryptSecrets({
secretsToEncrypt: secretsToBeAdded,
workspaceId: project.id,
env: "dev"
});
try { try {
await Promise.allSettled( const { data } = await apiRequest.post("/api/v3/secrets/batch/raw", {
(secrets || []).map((secret) => workspaceId: project.id,
createSecret({ environment: "dev",
workspaceId: project.id, secretPath: "/",
environment: secret.environment, secrets: secretsToBeAdded
type: secret.type, });
secretKey: secret.secretName, return data;
secretKeyCiphertext: secret.secretKeyCiphertext,
secretKeyIV: secret.secretKeyIV,
secretKeyTag: secret.secretKeyTag,
secretValueCiphertext: secret.secretValueCiphertext,
secretValueIV: secret.secretValueIV,
secretValueTag: secret.secretValueTag,
secretCommentCiphertext: secret.secretCommentCiphertext,
secretCommentIV: secret.secretCommentIV,
secretCommentTag: secret.secretCommentTag,
secretPath: "/",
metadata: {
source: "signup"
}
})
)
);
} catch (err) { } catch (err) {
console.error("Failed to upload secrets", err); console.error("Failed to upload secrets", err);
} }

View File

@@ -1,175 +0,0 @@
import path from "path";
import { decryptSymmetric } from "@app/components/utilities/cryptography/crypto";
import { fetchProjectEncryptedSecrets } from "@app/hooks/api/secrets/queries";
const INTERPOLATION_SYNTAX_REG = /\${([^}]+)}/g;
export const interpolateSecrets = ({
projectId,
secretEncKey
}: {
projectId: string;
secretEncKey: string;
}) => {
const fetchSecretsCrossEnv = () => {
const fetchCache: Record<string, Record<string, string>> = {};
return async (secRefEnv: string, secRefPath: string[], secRefKey: string) => {
const secRefPathUrl = path.join("/", ...secRefPath);
const uniqKey = `${secRefEnv}-${secRefPathUrl}`;
if (fetchCache?.[uniqKey]) {
return fetchCache[uniqKey][secRefKey];
}
// get secrets by projectId, env, path
const encryptedSecrets = await fetchProjectEncryptedSecrets({
workspaceId: projectId,
environment: secRefEnv,
secretPath: secRefPathUrl
});
const decryptedSec = encryptedSecrets.reduce<Record<string, string>>((prev, secret) => {
const secretKey = decryptSymmetric({
ciphertext: secret.secretKeyCiphertext,
iv: secret.secretKeyIV,
tag: secret.secretKeyTag,
key: secretEncKey
});
const secretValue = decryptSymmetric({
ciphertext: secret.secretValueCiphertext,
iv: secret.secretValueIV,
tag: secret.secretValueTag,
key: secretEncKey
});
// eslint-disable-next-line
prev[secretKey] = secretValue;
return prev;
}, {});
fetchCache[uniqKey] = decryptedSec;
return fetchCache[uniqKey][secRefKey];
};
};
const recursivelyExpandSecret = async (
expandedSec: Record<string, string>,
interpolatedSec: Record<string, string>,
fetchCrossEnv: (env: string, secPath: string[], secKey: string) => Promise<string>,
recursionChainBreaker: Record<string, boolean>,
key: string
) => {
if (expandedSec?.[key] !== undefined) {
return expandedSec[key];
}
if (recursionChainBreaker?.[key]) {
return "";
}
// eslint-disable-next-line
recursionChainBreaker[key] = true;
let interpolatedValue = interpolatedSec[key];
if (!interpolatedValue) {
// eslint-disable-next-line no-console
console.error(`Couldn't find referenced value - ${key}`);
return "";
}
const refs = interpolatedValue.match(INTERPOLATION_SYNTAX_REG);
if (refs) {
await Promise.all(
refs.map(async (interpolationSyntax) => {
const interpolationKey = interpolationSyntax.slice(2, interpolationSyntax.length - 1);
const entities = interpolationKey.trim().split(".");
if (entities.length === 1) {
const val = await recursivelyExpandSecret(
expandedSec,
interpolatedSec,
fetchCrossEnv,
recursionChainBreaker,
interpolationKey
);
if (val) {
interpolatedValue = interpolatedValue.replaceAll(interpolationSyntax, val);
}
return;
}
if (entities.length > 1) {
const secRefEnv = entities[0];
const secRefPath = entities.slice(1, entities.length - 1);
const secRefKey = entities[entities.length - 1];
const val = await fetchCrossEnv(secRefEnv, secRefPath, secRefKey);
if (val) {
interpolatedValue = interpolatedValue.replaceAll(interpolationSyntax, val);
}
}
})
);
}
// eslint-disable-next-line
expandedSec[key] = interpolatedValue;
return interpolatedValue;
};
// used to convert multi line ones to quotes ones with \n
const formatMultiValueEnv = (val?: string) => {
if (!val) return "";
if (!val.match("\n")) return val;
return `"${val.replace(/\n/g, "\\n")}"`;
};
const expandSecrets = async (
secrets: Record<string, { value: string; comment?: string; skipMultilineEncoding?: boolean }>
) => {
const expandedSec: Record<string, string> = {};
const interpolatedSec: Record<string, string> = {};
const crossSecEnvFetch = fetchSecretsCrossEnv();
Object.keys(secrets).forEach((key) => {
if (secrets[key].value.match(INTERPOLATION_SYNTAX_REG)) {
interpolatedSec[key] = secrets[key].value;
} else {
expandedSec[key] = secrets[key].value;
}
});
await Promise.all(
Object.keys(secrets).map(async (key) => {
if (expandedSec?.[key]) {
// should not do multi line encoding if user has set it to skip
// eslint-disable-next-line
secrets[key].value = secrets[key].skipMultilineEncoding
? expandedSec[key]
: formatMultiValueEnv(expandedSec[key]);
return;
}
// this is to avoid recursion loop. So the graph should be direct graph rather than cyclic
// so for any recursion building if there is an entity two times same key meaning it will be looped
const recursionChainBreaker: Record<string, boolean> = {};
const expandedVal = await recursivelyExpandSecret(
expandedSec,
interpolatedSec,
crossSecEnvFetch,
recursionChainBreaker,
key
);
// eslint-disable-next-line
secrets[key].value = secrets[key].skipMultilineEncoding
? expandedVal
: formatMultiValueEnv(expandedVal);
})
);
return secrets;
};
return expandSecrets;
};

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-param-reassign */
import { import {
useInfiniteQuery, useInfiniteQuery,
UseInfiniteQueryOptions, UseInfiniteQueryOptions,
@@ -12,8 +13,7 @@ import {
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { UserWsKeyPair } from "../keys/types"; import { UserWsKeyPair } from "../keys/types";
import { decryptSecrets } from "../secrets/queries"; import { EncryptedSecret, SecretType,SecretV3RawSanitized } from "../secrets/types";
import { DecryptedSecret } from "../secrets/types";
import { import {
CommitType, CommitType,
TGetSecretApprovalRequestCount, TGetSecretApprovalRequestCount,
@@ -45,6 +45,78 @@ export const secretApprovalRequestKeys = {
] ]
}; };
export const decryptSecrets = (
encryptedSecrets: EncryptedSecret[],
decryptFileKey: UserWsKeyPair
) => {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string;
const key = decryptAssymmetric({
ciphertext: decryptFileKey.encryptedKey,
nonce: decryptFileKey.nonce,
publicKey: decryptFileKey.sender.publicKey,
privateKey: PRIVATE_KEY
});
const personalSecrets: Record<string, { id: string; value: string }> = {};
const secrets: SecretV3RawSanitized[] = [];
encryptedSecrets.forEach((encSecret) => {
const secretKey = decryptSymmetric({
ciphertext: encSecret.secretKeyCiphertext,
iv: encSecret.secretKeyIV,
tag: encSecret.secretKeyTag,
key
});
const secretValue = decryptSymmetric({
ciphertext: encSecret.secretValueCiphertext,
iv: encSecret.secretValueIV,
tag: encSecret.secretValueTag,
key
});
const secretComment = decryptSymmetric({
ciphertext: encSecret.secretCommentCiphertext,
iv: encSecret.secretCommentIV,
tag: encSecret.secretCommentTag,
key
});
const decryptedSecret: SecretV3RawSanitized = {
id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
tags: encSecret.tags,
comment: secretComment,
reminderRepeatDays: encSecret.secretReminderRepeatDays,
reminderNote: encSecret.secretReminderNote,
createdAt: encSecret.createdAt,
updatedAt: encSecret.updatedAt,
version: encSecret.version,
skipMultilineEncoding: encSecret.skipMultilineEncoding
};
if (encSecret.type === SecretType.Personal) {
personalSecrets[decryptedSecret.key] = {
id: encSecret.id,
value: secretValue
};
} else {
secrets.push(decryptedSecret);
}
});
secrets.forEach((sec) => {
if (personalSecrets?.[sec.key]) {
sec.idOverride = personalSecrets[sec.key].id;
sec.valueOverride = personalSecrets[sec.key].value;
sec.overrideAction = "modified";
}
});
return secrets;
};
export const decryptSecretApprovalSecret = ( export const decryptSecretApprovalSecret = (
encSecret: TSecretApprovalSecChangeData, encSecret: TSecretApprovalSecChangeData,
decryptFileKey: UserWsKeyPair decryptFileKey: UserWsKeyPair
@@ -173,7 +245,7 @@ export const useGetSecretApprovalRequestDetails = ({
UseQueryOptions< UseQueryOptions<
TSecretApprovalRequest, TSecretApprovalRequest,
unknown, unknown,
TSecretApprovalRequest<DecryptedSecret>, TSecretApprovalRequest<SecretV3RawSanitized>,
ReturnType<typeof secretApprovalRequestKeys.detail> ReturnType<typeof secretApprovalRequestKeys.detail>
>, >,
"queryKey" | "queryFn" "queryKey" | "queryFn"

View File

@@ -1,10 +1,6 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useQueries, useQuery, UseQueryOptions } from "@tanstack/react-query"; import { useQueries, useQuery, UseQueryOptions } from "@tanstack/react-query";
import {
decryptAssymmetric,
decryptSymmetric
} from "@app/components/utilities/cryptography/crypto";
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { import {
@@ -75,7 +71,7 @@ const fetchImportedSecrets = async (
directory?: string directory?: string
) => { ) => {
const { data } = await apiRequest.get<{ secrets: TImportedSecrets[] }>( const { data } = await apiRequest.get<{ secrets: TImportedSecrets[] }>(
"/api/v1/secret-imports/secrets", "/api/v1/secret-imports/secrets/raw",
{ {
params: { params: {
workspaceId, workspaceId,
@@ -107,7 +103,6 @@ const fetchImportedFolders = async ({
export const useGetImportedSecretsSingleEnv = ({ export const useGetImportedSecretsSingleEnv = ({
environment, environment,
decryptFileKey,
path, path,
projectId, projectId,
options = {} options = {}
@@ -123,78 +118,40 @@ export const useGetImportedSecretsSingleEnv = ({
>; >;
}) => }) =>
useQuery({ useQuery({
enabled: enabled: Boolean(projectId) && Boolean(environment) && (options?.enabled ?? true),
Boolean(projectId) &&
Boolean(environment) &&
Boolean(decryptFileKey) &&
(options?.enabled ?? true),
queryKey: secretImportKeys.getSecretImportSecrets({ queryKey: secretImportKeys.getSecretImportSecrets({
environment, environment,
path, path,
projectId projectId
}), }),
queryFn: () => fetchImportedSecrets(projectId, environment, path), queryFn: () => fetchImportedSecrets(projectId, environment, path),
select: useCallback( select: (data: TImportedSecrets[]) => {
(data: TImportedSecrets[]) => { return data.map((el) => ({
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; environment: el.environment,
const latestKey = decryptFileKey; secretPath: el.secretPath,
const key = decryptAssymmetric({ environmentInfo: el.environmentInfo,
ciphertext: latestKey.encryptedKey, folderId: el.folderId,
nonce: latestKey.nonce, secrets: el.secrets.map((encSecret) => {
publicKey: latestKey.sender.publicKey, return {
privateKey: PRIVATE_KEY id: encSecret.id,
}); env: encSecret.environment,
key: encSecret.secretKey,
return data.map((el) => ({ value: encSecret.secretValue,
environment: el.environment, tags: encSecret.tags,
secretPath: el.secretPath, comment: encSecret.secretComment,
environmentInfo: el.environmentInfo, createdAt: encSecret.createdAt,
folderId: el.folderId, updatedAt: encSecret.updatedAt,
secrets: el.secrets.map((encSecret) => { version: encSecret.version
const secretKey = decryptSymmetric({ };
ciphertext: encSecret.secretKeyCiphertext, })
iv: encSecret.secretKeyIV, }));
tag: encSecret.secretKeyTag, }
key
});
const secretValue = decryptSymmetric({
ciphertext: encSecret.secretValueCiphertext,
iv: encSecret.secretValueIV,
tag: encSecret.secretValueTag,
key
});
const secretComment = decryptSymmetric({
ciphertext: encSecret.secretCommentCiphertext,
iv: encSecret.secretCommentIV,
tag: encSecret.secretCommentTag,
key
});
return {
id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
tags: encSecret.tags,
comment: secretComment,
createdAt: encSecret.createdAt,
updatedAt: encSecret.updatedAt,
version: encSecret.version
};
})
}));
},
[decryptFileKey]
)
}); });
export const useGetImportedSecretsAllEnvs = ({ export const useGetImportedSecretsAllEnvs = ({
projectId, projectId,
environments, environments,
path = "/", path = "/"
decryptFileKey
}: TGetSecretImportsAllEnvs) => { }: TGetSecretImportsAllEnvs) => {
const secretImports = useQueries({ const secretImports = useQueries({
queries: environments.map((env) => ({ queries: environments.map((env) => ({
@@ -206,60 +163,27 @@ export const useGetImportedSecretsAllEnvs = ({
queryFn: () => fetchImportedSecrets(projectId, env, path).catch(() => []), queryFn: () => fetchImportedSecrets(projectId, env, path).catch(() => []),
enabled: Boolean(projectId) && Boolean(env), enabled: Boolean(projectId) && Boolean(env),
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
select: useCallback( select: (data: TImportedSecrets[]) => {
(data: TImportedSecrets[]) => { return data.map((el) => ({
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; environment: el.environment,
const latestKey = decryptFileKey; secretPath: el.secretPath,
const key = decryptAssymmetric({ environmentInfo: el.environmentInfo,
ciphertext: latestKey.encryptedKey, folderId: el.folderId,
nonce: latestKey.nonce, secrets: el.secrets.map((encSecret) => {
publicKey: latestKey.sender.publicKey, return {
privateKey: PRIVATE_KEY id: encSecret.id,
}); env: encSecret.environment,
key: encSecret.secretKey,
return data.map((el) => ({ value: encSecret.secretValue,
environment: el.environment, tags: encSecret.tags,
secretPath: el.secretPath, comment: encSecret.secretComment,
environmentInfo: el.environmentInfo, createdAt: encSecret.createdAt,
folderId: el.folderId, updatedAt: encSecret.updatedAt,
secrets: el.secrets.map((encSecret) => { version: encSecret.version
const secretKey = decryptSymmetric({ };
ciphertext: encSecret.secretKeyCiphertext, })
iv: encSecret.secretKeyIV, }));
tag: encSecret.secretKeyTag, }
key
});
const secretValue = decryptSymmetric({
ciphertext: encSecret.secretValueCiphertext,
iv: encSecret.secretValueIV,
tag: encSecret.secretValueTag,
key
});
const secretComment = decryptSymmetric({
ciphertext: encSecret.secretCommentCiphertext,
iv: encSecret.secretCommentIV,
tag: encSecret.secretCommentTag,
key
});
return {
id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
tags: encSecret.tags,
comment: secretComment,
createdAt: encSecret.createdAt,
updatedAt: encSecret.updatedAt,
version: encSecret.version
};
})
}));
},
[decryptFileKey]
)
})) }))
}); });

View File

@@ -1,5 +1,4 @@
import { UserWsKeyPair } from "../keys/types"; import { SecretV3Raw } from "../secrets/types";
import { EncryptedSecret } from "../secrets/types";
import { WorkspaceEnv } from "../workspace/types"; import { WorkspaceEnv } from "../workspace/types";
export type TSecretImport = { export type TSecretImport = {
@@ -28,7 +27,7 @@ export type TImportedSecrets = {
environmentInfo: WorkspaceEnv; environmentInfo: WorkspaceEnv;
secretPath: string; secretPath: string;
folderId: string; folderId: string;
secrets: EncryptedSecret[]; secrets: SecretV3Raw[];
}; };
export type TGetSecretImports = { export type TGetSecretImports = {
@@ -39,7 +38,6 @@ export type TGetSecretImports = {
export type TGetSecretImportsAllEnvs = { export type TGetSecretImportsAllEnvs = {
projectId: string; projectId: string;
decryptFileKey: UserWsKeyPair;
path?: string; path?: string;
environments: string[]; environments: string[];
}; };
@@ -48,7 +46,6 @@ export type TGetImportedSecrets = {
projectId: string; projectId: string;
environment: string; environment: string;
path?: string; path?: string;
decryptFileKey: UserWsKeyPair;
}; };
export type TuseGetImportedFoldersByEnv = { export type TuseGetImportedFoldersByEnv = {

View File

@@ -7,7 +7,7 @@ import {
} from "@app/components/utilities/cryptography/crypto"; } from "@app/components/utilities/cryptography/crypto";
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { DecryptedSecret, SecretType } from "../secrets/types"; import { SecretType,SecretV3RawSanitized } from "../secrets/types";
import { import {
TGetSecretSnapshotsDTO, TGetSecretSnapshotsDTO,
TSecretRollbackDTO, TSecretRollbackDTO,
@@ -80,7 +80,7 @@ export const useGetSnapshotSecrets = ({ decryptFileKey, snapshotId }: TSnapshotD
privateKey: PRIVATE_KEY privateKey: PRIVATE_KEY
}); });
const sharedSecrets: DecryptedSecret[] = []; const sharedSecrets: SecretV3RawSanitized[] = [];
const personalSecrets: Record<string, { id: string; value: string }> = {}; const personalSecrets: Record<string, { id: string; value: string }> = {};
data.secretVersions.forEach((encSecret) => { data.secretVersions.forEach((encSecret) => {
const secretKey = decryptSymmetric({ const secretKey = decryptSymmetric({

View File

@@ -1,18 +1,11 @@
import crypto from "crypto";
import { MutationOptions, useMutation, useQueryClient } from "@tanstack/react-query"; import { MutationOptions, useMutation, useQueryClient } from "@tanstack/react-query";
import {
decryptAssymmetric,
encryptSymmetric
} from "@app/components/utilities/cryptography/crypto";
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { secretApprovalRequestKeys } from "../secretApprovalRequest/queries"; import { secretApprovalRequestKeys } from "../secretApprovalRequest/queries";
import { secretSnapshotKeys } from "../secretSnapshots/queries"; import { secretSnapshotKeys } from "../secretSnapshots/queries";
import { secretKeys } from "./queries"; import { secretKeys } from "./queries";
import { import {
CreateSecretDTO,
TCreateSecretBatchDTO, TCreateSecretBatchDTO,
TCreateSecretsV3DTO, TCreateSecretsV3DTO,
TDeleteSecretBatchDTO, TDeleteSecretBatchDTO,
@@ -22,50 +15,6 @@ import {
TUpdateSecretsV3DTO TUpdateSecretsV3DTO
} from "./types"; } from "./types";
const encryptSecret = (randomBytes: string, key: string, value?: string, comment?: string) => {
// encrypt key
const {
ciphertext: secretKeyCiphertext,
iv: secretKeyIV,
tag: secretKeyTag
} = encryptSymmetric({
plaintext: key,
key: randomBytes
});
// encrypt value
const {
ciphertext: secretValueCiphertext,
iv: secretValueIV,
tag: secretValueTag
} = encryptSymmetric({
plaintext: value ?? "",
key: randomBytes
});
// encrypt comment
const {
ciphertext: secretCommentCiphertext,
iv: secretCommentIV,
tag: secretCommentTag
} = encryptSymmetric({
plaintext: comment ?? "",
key: randomBytes
});
return {
secretKeyCiphertext,
secretKeyIV,
secretKeyTag,
secretValueCiphertext,
secretValueIV,
secretValueTag,
secretCommentCiphertext,
secretCommentIV,
secretCommentTag
};
};
export const useCreateSecretV3 = ({ export const useCreateSecretV3 = ({
options options
}: { }: {
@@ -78,32 +27,20 @@ export const useCreateSecretV3 = ({
type, type,
environment, environment,
workspaceId, workspaceId,
secretName, secretKey,
secretValue, secretValue,
latestFileKey,
secretComment, secretComment,
skipMultilineEncoding skipMultilineEncoding
}) => { }) => {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; const { data } = await apiRequest.post(`/api/v3/secrets/raw/${secretKey}`, {
const randomBytes = latestFileKey
? decryptAssymmetric({
ciphertext: latestFileKey.encryptedKey,
nonce: latestFileKey.nonce,
publicKey: latestFileKey.sender.publicKey,
privateKey: PRIVATE_KEY
})
: crypto.randomBytes(16).toString("hex");
const reqBody = {
workspaceId,
environment,
type,
secretPath, secretPath,
...encryptSecret(randomBytes, secretName, secretValue, secretComment), type,
environment,
workspaceId,
secretValue,
secretComment,
skipMultilineEncoding skipMultilineEncoding
}; });
const { data } = await apiRequest.post(`/api/v3/secrets/${secretName}`, reqBody);
return data; return data;
}, },
onSuccess: (_, { workspaceId, environment, secretPath }) => { onSuccess: (_, { workspaceId, environment, secretPath }) => {
@@ -132,44 +69,30 @@ export const useUpdateSecretV3 = ({
mutationFn: async ({ mutationFn: async ({
secretPath = "/", secretPath = "/",
type, type,
secretId,
environment, environment,
workspaceId, workspaceId,
secretName, secretKey,
secretValue, secretValue,
latestFileKey, tagIds,
tags,
secretComment, secretComment,
secretReminderRepeatDays, secretReminderRepeatDays,
secretReminderNote, secretReminderNote,
newSecretName, newSecretName,
skipMultilineEncoding skipMultilineEncoding
}) => { }) => {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; const { data } = await apiRequest.patch(`/api/v3/secrets/raw/${secretKey}`, {
const randomBytes = latestFileKey
? decryptAssymmetric({
ciphertext: latestFileKey.encryptedKey,
nonce: latestFileKey.nonce,
publicKey: latestFileKey.sender.publicKey,
privateKey: PRIVATE_KEY
})
: crypto.randomBytes(16).toString("hex");
const reqBody = {
workspaceId, workspaceId,
environment, environment,
type, type,
secretReminderNote, secretReminderNote,
secretReminderRepeatDays, secretReminderRepeatDays,
secretPath, secretPath,
secretId,
...encryptSecret(randomBytes, newSecretName ?? secretName, secretValue, secretComment),
tags,
skipMultilineEncoding, skipMultilineEncoding,
secretName: newSecretName newSecretName,
}; secretComment,
const { data } = await apiRequest.patch(`/api/v3/secrets/${secretName}`, reqBody); tagIds,
secretValue
});
return data; return data;
}, },
onSuccess: (_, { workspaceId, environment, secretPath }) => { onSuccess: (_, { workspaceId, environment, secretPath }) => {
@@ -201,19 +124,17 @@ export const useDeleteSecretV3 = ({
type, type,
environment, environment,
workspaceId, workspaceId,
secretName, secretKey,
secretId secretId
}) => { }) => {
const reqBody = { const { data } = await apiRequest.delete(`/api/v3/secrets/raw/${secretKey}`, {
workspaceId, data: {
environment, workspaceId,
type, environment,
secretPath, type,
secretId secretPath,
}; secretId
}
const { data } = await apiRequest.delete(`/api/v3/secrets/${secretName}`, {
data: reqBody
}); });
return data; return data;
}, },
@@ -241,33 +162,13 @@ export const useCreateSecretBatch = ({
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation<{}, {}, TCreateSecretBatchDTO>({ return useMutation<{}, {}, TCreateSecretBatchDTO>({
mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets, latestFileKey }) => { mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; const { data } = await apiRequest.post("/api/v3/secrets/batch/raw", {
const randomBytes = latestFileKey
? decryptAssymmetric({
ciphertext: latestFileKey.encryptedKey,
nonce: latestFileKey.nonce,
publicKey: latestFileKey.sender.publicKey,
privateKey: PRIVATE_KEY
})
: crypto.randomBytes(16).toString("hex");
const reqBody = {
workspaceId, workspaceId,
environment, environment,
secretPath, secretPath,
secrets: secrets.map( secrets
({ secretName, secretValue, secretComment, metadata, type, skipMultilineEncoding }) => ({ });
secretName,
...encryptSecret(randomBytes, secretName, secretValue, secretComment),
type,
metadata,
skipMultilineEncoding
})
)
};
const { data } = await apiRequest.post("/api/v3/secrets/batch", reqBody);
return data; return data;
}, },
onSuccess: (_, { workspaceId, environment, secretPath }) => { onSuccess: (_, { workspaceId, environment, secretPath }) => {
@@ -294,33 +195,13 @@ export const useUpdateSecretBatch = ({
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation<{}, {}, TUpdateSecretBatchDTO>({ return useMutation<{}, {}, TUpdateSecretBatchDTO>({
mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets, latestFileKey }) => { mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; const { data } = await apiRequest.patch("/api/v3/secrets/batch/raw", {
const randomBytes = latestFileKey
? decryptAssymmetric({
ciphertext: latestFileKey.encryptedKey,
nonce: latestFileKey.nonce,
publicKey: latestFileKey.sender.publicKey,
privateKey: PRIVATE_KEY
})
: crypto.randomBytes(16).toString("hex");
const reqBody = {
workspaceId, workspaceId,
environment, environment,
secretPath, secretPath,
secrets: secrets.map( secrets
({ secretName, secretValue, secretComment, type, tags, skipMultilineEncoding }) => ({ });
secretName,
...encryptSecret(randomBytes, secretName, secretValue, secretComment),
type,
tags,
skipMultilineEncoding
})
)
};
const { data } = await apiRequest.patch("/api/v3/secrets/batch", reqBody);
return data; return data;
}, },
onSuccess: (_, { workspaceId, environment, secretPath }) => { onSuccess: (_, { workspaceId, environment, secretPath }) => {
@@ -348,15 +229,13 @@ export const useDeleteSecretBatch = ({
return useMutation<{}, {}, TDeleteSecretBatchDTO>({ return useMutation<{}, {}, TDeleteSecretBatchDTO>({
mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => { mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
const reqBody = { const { data } = await apiRequest.delete("/api/v3/secrets/batch/raw", {
workspaceId, data: {
environment, workspaceId,
secretPath, environment,
secrets secretPath,
}; secrets
}
const { data } = await apiRequest.delete("/api/v3/secrets/batch", {
data: reqBody
}); });
return data; return data;
}, },
@@ -443,7 +322,7 @@ export const useMoveSecrets = ({
}); });
}; };
export const createSecret = async (dto: CreateSecretDTO) => { export const createSecret = async (dto: TCreateSecretsV3DTO) => {
const { data } = await apiRequest.post(`/api/v3/secrets/${dto.secretKey}`, dto); const { data } = await apiRequest.post(`/api/v3/secrets/${dto.secretKey}`, dto);
return data; return data;
}; };

View File

@@ -8,13 +8,13 @@ import {
} from "@app/components/utilities/cryptography/crypto"; } from "@app/components/utilities/cryptography/crypto";
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { UserWsKeyPair } from "../keys/types";
import { import {
DecryptedSecret,
EncryptedSecret,
EncryptedSecretVersion, EncryptedSecretVersion,
GetSecretVersionsDTO, GetSecretVersionsDTO,
SecretType, SecretType,
SecretV3Raw,
SecretV3RawResponse,
SecretV3RawSanitized,
TGetProjectSecretsAllEnvDTO, TGetProjectSecretsAllEnvDTO,
TGetProjectSecretsDTO, TGetProjectSecretsDTO,
TGetProjectSecretsKey TGetProjectSecretsKey
@@ -27,61 +27,49 @@ export const secretKeys = {
getSecretVersion: (secretId: string) => [{ secretId }, "secret-versions"] as const getSecretVersion: (secretId: string) => [{ secretId }, "secret-versions"] as const
}; };
export const decryptSecrets = ( export const fetchProjectSecrets = async ({
encryptedSecrets: EncryptedSecret[], workspaceId,
decryptFileKey: UserWsKeyPair environment,
) => { secretPath,
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; includeImports,
const key = decryptAssymmetric({ expandSecretReferences
ciphertext: decryptFileKey.encryptedKey, }: TGetProjectSecretsKey) => {
nonce: decryptFileKey.nonce, const { data } = await apiRequest.get<SecretV3RawResponse>("/api/v3/secrets/raw", {
publicKey: decryptFileKey.sender.publicKey, params: {
privateKey: PRIVATE_KEY environment,
workspaceId,
secretPath,
expandSecretReferences,
include_imports: includeImports
}
}); });
return data;
};
export const mergePersonalSecrets = (rawSecrets: SecretV3Raw[]) => {
const personalSecrets: Record<string, { id: string; value: string }> = {}; const personalSecrets: Record<string, { id: string; value: string }> = {};
const secrets: DecryptedSecret[] = []; const secrets: SecretV3RawSanitized[] = [];
encryptedSecrets.forEach((encSecret) => { rawSecrets.forEach((el) => {
const secretKey = decryptSymmetric({ const decryptedSecret: SecretV3RawSanitized = {
ciphertext: encSecret.secretKeyCiphertext, id: el.id,
iv: encSecret.secretKeyIV, env: el.environment,
tag: encSecret.secretKeyTag, key: el.secretKey,
key value: el.secretValue,
}); tags: el.tags || [],
comment: el.secretComment || "",
const secretValue = decryptSymmetric({ reminderRepeatDays: el.secretReminderRepeatDays,
ciphertext: encSecret.secretValueCiphertext, reminderNote: el.secretReminderNote,
iv: encSecret.secretValueIV, createdAt: el.createdAt,
tag: encSecret.secretValueTag, updatedAt: el.updatedAt,
key version: el.version,
}); skipMultilineEncoding: el.skipMultilineEncoding
const secretComment = decryptSymmetric({
ciphertext: encSecret.secretCommentCiphertext,
iv: encSecret.secretCommentIV,
tag: encSecret.secretCommentTag,
key
});
const decryptedSecret: DecryptedSecret = {
id: encSecret.id,
env: encSecret.environment,
key: secretKey,
value: secretValue,
tags: encSecret.tags,
comment: secretComment,
reminderRepeatDays: encSecret.secretReminderRepeatDays,
reminderNote: encSecret.secretReminderNote,
createdAt: encSecret.createdAt,
updatedAt: encSecret.updatedAt,
version: encSecret.version,
skipMultilineEncoding: encSecret.skipMultilineEncoding
}; };
if (encSecret.type === SecretType.Personal) { if (el.type === SecretType.Personal) {
personalSecrets[decryptedSecret.key] = { personalSecrets[decryptedSecret.key] = {
id: encSecret.id, id: el.id,
value: secretValue value: el.secretValue
}; };
} else { } else {
secrets.push(decryptedSecret); secrets.push(decryptedSecret);
@@ -99,33 +87,17 @@ export const decryptSecrets = (
return secrets; return secrets;
}; };
export const fetchProjectEncryptedSecrets = async ({
workspaceId,
environment,
secretPath
}: TGetProjectSecretsKey) => {
const { data } = await apiRequest.get<{ secrets: EncryptedSecret[] }>("/api/v3/secrets", {
params: {
environment,
workspaceId,
secretPath
}
});
return data.secrets;
};
export const useGetProjectSecrets = ({ export const useGetProjectSecrets = ({
workspaceId, workspaceId,
environment, environment,
decryptFileKey,
secretPath, secretPath,
options options
}: TGetProjectSecretsDTO & { }: TGetProjectSecretsDTO & {
options?: Omit< options?: Omit<
UseQueryOptions< UseQueryOptions<
EncryptedSecret[], SecretV3RawResponse,
unknown, unknown,
DecryptedSecret[], SecretV3RawSanitized[],
ReturnType<typeof secretKeys.getProjectSecret> ReturnType<typeof secretKeys.getProjectSecret>
>, >,
"queryKey" | "queryFn" "queryKey" | "queryFn"
@@ -134,25 +106,24 @@ export const useGetProjectSecrets = ({
useQuery({ useQuery({
...options, ...options,
// wait for all values to be available // wait for all values to be available
enabled: Boolean(decryptFileKey && workspaceId && environment) && (options?.enabled ?? true), enabled: Boolean(workspaceId && environment) && (options?.enabled ?? true),
queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath }), queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath }),
queryFn: async () => fetchProjectEncryptedSecrets({ workspaceId, environment, secretPath }), queryFn: async () => fetchProjectSecrets({ workspaceId, environment, secretPath }),
select: (secrets: EncryptedSecret[]) => decryptSecrets(secrets, decryptFileKey) select: ({ secrets }) => mergePersonalSecrets(secrets)
}); });
export const useGetProjectSecretsAllEnv = ({ export const useGetProjectSecretsAllEnv = ({
workspaceId, workspaceId,
envs, envs,
decryptFileKey,
secretPath secretPath
}: TGetProjectSecretsAllEnvDTO) => { }: TGetProjectSecretsAllEnvDTO) => {
const secrets = useQueries({ const secrets = useQueries({
queries: envs.map((environment) => ({ queries: envs.map((environment) => ({
queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath }), queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath }),
enabled: Boolean(decryptFileKey && workspaceId && environment), enabled: Boolean(workspaceId && environment),
queryFn: async () => fetchProjectEncryptedSecrets({ workspaceId, environment, secretPath }), queryFn: async () => fetchProjectSecrets({ workspaceId, environment, secretPath }),
select: (secs: EncryptedSecret[]) => select: (el: SecretV3RawResponse) =>
decryptSecrets(secs, decryptFileKey).reduce<Record<string, DecryptedSecret>>( mergePersonalSecrets(el.secrets).reduce<Record<string, SecretV3RawSanitized>>(
(prev, curr) => ({ ...prev, [curr.key]: curr }), (prev, curr) => ({ ...prev, [curr.key]: curr }),
{} {}
) )

View File

@@ -30,15 +30,16 @@ export type EncryptedSecret = {
tags: WsTag[]; tags: WsTag[];
}; };
export type DecryptedSecret = { // both personal and shared secret stitiched together for dashboard
export type SecretV3RawSanitized = {
id: string; id: string;
version: number; version: number;
key: string; key: string;
value: string; value: string;
comment: string; comment?: string;
reminderRepeatDays?: number | null; reminderRepeatDays?: number | null;
reminderNote?: string | null; reminderNote?: string | null;
tags: WsTag[]; tags?: WsTag[];
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
env: string; env: string;
@@ -49,6 +50,35 @@ export type DecryptedSecret = {
skipMultilineEncoding?: boolean; skipMultilineEncoding?: boolean;
}; };
export type SecretV3Raw = {
id: string;
_id: string;
workspace: string;
environment: string;
version: number;
type: string;
secretKey: string;
secretValue: string;
secretComment?: string;
secretReminderNote?: string;
secretReminderRepeatDays?: number;
skipMultilineEncoding?: boolean;
metadata?: Record<string, string>;
tags?: WsTag[];
createdAt: string;
updatedAt: string;
};
export type SecretV3RawResponse = {
secrets: SecretV3Raw[];
imports: {
secretPath: string;
environment: string;
folderId: string;
secrets: SecretV3Raw[];
}[];
};
export type EncryptedSecretVersion = { export type EncryptedSecretVersion = {
id: string; id: string;
secretId: string; secretId: string;
@@ -75,16 +105,15 @@ export type TGetProjectSecretsKey = {
workspaceId: string; workspaceId: string;
environment: string; environment: string;
secretPath?: string; secretPath?: string;
includeImports?: boolean;
expandSecretReferences?: boolean;
}; };
export type TGetProjectSecretsDTO = { export type TGetProjectSecretsDTO = TGetProjectSecretsKey;
decryptFileKey: UserWsKeyPair;
} & TGetProjectSecretsKey;
export type TGetProjectSecretsAllEnvDTO = { export type TGetProjectSecretsAllEnvDTO = {
workspaceId: string; workspaceId: string;
envs: string[]; envs: string[];
decryptFileKey: UserWsKeyPair;
folderId?: string; folderId?: string;
secretPath?: string; secretPath?: string;
isPaused?: boolean; isPaused?: boolean;
@@ -98,8 +127,7 @@ export type GetSecretVersionsDTO = {
}; };
export type TCreateSecretsV3DTO = { export type TCreateSecretsV3DTO = {
latestFileKey: UserWsKeyPair; secretKey: string;
secretName: string;
secretValue: string; secretValue: string;
secretComment: string; secretComment: string;
skipMultilineEncoding?: boolean; skipMultilineEncoding?: boolean;
@@ -110,20 +138,18 @@ export type TCreateSecretsV3DTO = {
}; };
export type TUpdateSecretsV3DTO = { export type TUpdateSecretsV3DTO = {
latestFileKey: UserWsKeyPair;
workspaceId: string; workspaceId: string;
environment: string; environment: string;
type: SecretType;
secretPath: string; secretPath: string;
type: SecretType;
skipMultilineEncoding?: boolean; skipMultilineEncoding?: boolean;
newSecretName?: string; newSecretName?: string;
secretName: string; secretKey: string;
secretId?: string;
secretValue: string; secretValue: string;
secretComment?: string; secretComment?: string;
secretReminderRepeatDays?: number | null; secretReminderRepeatDays?: number | null;
secretReminderNote?: string | null; secretReminderNote?: string | null;
tags?: string[]; tagIds?: string[];
}; };
export type TDeleteSecretsV3DTO = { export type TDeleteSecretsV3DTO = {
@@ -131,7 +157,7 @@ export type TDeleteSecretsV3DTO = {
environment: string; environment: string;
type: SecretType; type: SecretType;
secretPath: string; secretPath: string;
secretName: string; secretKey: string;
secretId?: string; secretId?: string;
}; };
@@ -139,13 +165,13 @@ export type TCreateSecretBatchDTO = {
workspaceId: string; workspaceId: string;
environment: string; environment: string;
secretPath: string; secretPath: string;
latestFileKey: UserWsKeyPair;
secrets: Array<{ secrets: Array<{
secretName: string; secretKey: string;
secretValue: string; secretValue: string;
secretComment: string; secretComment: string;
skipMultilineEncoding?: boolean; skipMultilineEncoding?: boolean;
type: SecretType; type: SecretType;
tagIds?: string[];
metadata?: { metadata?: {
source?: string; source?: string;
}; };
@@ -156,14 +182,16 @@ export type TUpdateSecretBatchDTO = {
workspaceId: string; workspaceId: string;
environment: string; environment: string;
secretPath: string; secretPath: string;
latestFileKey: UserWsKeyPair;
secrets: Array<{ secrets: Array<{
type: SecretType; type: SecretType;
secretName: string; secretKey: string;
skipMultilineEncoding?: boolean;
secretValue: string; secretValue: string;
secretComment: string; secretComment?: string;
tags?: string[]; skipMultilineEncoding?: boolean;
tagIds?: string[];
metadata?: {
source?: string;
};
}>; }>;
}; };
@@ -172,7 +200,7 @@ export type TDeleteSecretBatchDTO = {
environment: string; environment: string;
secretPath: string; secretPath: string;
secrets: Array<{ secrets: Array<{
secretName: string; secretKey: string;
type: SecretType; type: SecretType;
}>; }>;
}; };
@@ -187,23 +215,3 @@ export type TMoveSecretsDTO = {
secretIds: string[]; secretIds: string[];
shouldOverwrite: boolean; shouldOverwrite: boolean;
}; };
export type CreateSecretDTO = {
workspaceId: string;
environment: string;
type: SecretType;
secretKey: string;
secretKeyCiphertext: string;
secretKeyIV: string;
secretKeyTag: string;
secretValueCiphertext: string;
secretValueIV: string;
secretValueTag: string;
secretCommentCiphertext: string;
secretCommentIV: string;
secretCommentTag: string;
secretPath: string;
metadata?: {
source?: string;
};
};

View File

@@ -13,11 +13,16 @@ import {
Tooltip, Tooltip,
Tr Tr
} from "@app/components/v2"; } from "@app/components/v2";
import { CommitType, DecryptedSecret, TSecretApprovalSecChange, WsTag } from "@app/hooks/api/types"; import {
CommitType,
SecretV3RawSanitized,
TSecretApprovalSecChange,
WsTag
} from "@app/hooks/api/types";
export type Props = { export type Props = {
op: CommitType; op: CommitType;
secretVersion?: DecryptedSecret; secretVersion?: SecretV3RawSanitized;
newVersion?: Omit<TSecretApprovalSecChange, "tags"> & { tags?: WsTag[] }; newVersion?: Omit<TSecretApprovalSecChange, "tags"> & { tags?: WsTag[] };
presentSecretVersionNumber: number; presentSecretVersionNumber: number;
hasMerged?: Boolean; hasMerged?: Boolean;

View File

@@ -100,7 +100,6 @@ export const SecretMainPage = () => {
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
decryptFileKey: decryptFileKey!,
options: { options: {
enabled: canReadSecret enabled: canReadSecret
} }
@@ -131,7 +130,6 @@ export const SecretMainPage = () => {
const { data: importedSecrets } = useGetImportedSecretsSingleEnv({ const { data: importedSecrets } = useGetImportedSecretsSingleEnv({
projectId: workspaceId, projectId: workspaceId,
environment, environment,
decryptFileKey: decryptFileKey!,
path: secretPath, path: secretPath,
options: { options: {
enabled: canReadSecret enabled: canReadSecret
@@ -255,7 +253,6 @@ export const SecretMainPage = () => {
<> <>
<ActionBar <ActionBar
secrets={secrets} secrets={secrets}
importedSecrets={importedSecrets}
environment={environment} environment={environment}
workspaceId={workspaceId} workspaceId={workspaceId}
projectSlug={projectSlug} projectSlug={projectSlug}
@@ -343,7 +340,6 @@ export const SecretMainPage = () => {
<CreateSecretForm <CreateSecretForm
environment={environment} environment={environment}
workspaceId={workspaceId} workspaceId={workspaceId}
decryptFileKey={decryptFileKey!}
secretPath={secretPath} secretPath={secretPath}
autoCapitalize={currentWorkspace?.autoCapitalization} autoCapitalize={currentWorkspace?.autoCapitalization}
isProtectedBranch={isProtectedBranch} isProtectedBranch={isProtectedBranch}
@@ -352,7 +348,6 @@ export const SecretMainPage = () => {
secrets={secrets} secrets={secrets}
environment={environment} environment={environment}
workspaceId={workspaceId} workspaceId={workspaceId}
decryptFileKey={decryptFileKey!}
secretPath={secretPath} secretPath={secretPath}
isSmaller={isNotEmtpy} isSmaller={isNotEmtpy}
environments={currentWorkspace?.environments} environments={currentWorkspace?.environments}

View File

@@ -25,7 +25,6 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications"; import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions"; import { ProjectPermissionCan } from "@app/components/permissions";
import { decryptAssymmetric } from "@app/components/utilities/cryptography/crypto";
import { import {
Button, Button,
DeleteActionModal, DeleteActionModal,
@@ -46,15 +45,10 @@ import {
UpgradePlanModal UpgradePlanModal
} from "@app/components/v2"; } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub, useSubscription } from "@app/context"; import { ProjectPermissionActions, ProjectPermissionSub, useSubscription } from "@app/context";
import { interpolateSecrets } from "@app/helpers/secret";
import { usePopUp } from "@app/hooks"; import { usePopUp } from "@app/hooks";
import { import { useCreateFolder, useDeleteSecretBatch, useMoveSecrets } from "@app/hooks/api";
useCreateFolder, import { fetchProjectSecrets } from "@app/hooks/api/secrets/queries";
useDeleteSecretBatch, import { SecretType, SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
useGetUserWsKey,
useMoveSecrets
} from "@app/hooks/api";
import { DecryptedSecret, SecretType, TImportedSecrets, WsTag } from "@app/hooks/api/types";
import { debounce } from "@app/lib/fn/debounce"; import { debounce } from "@app/lib/fn/debounce";
import { import {
@@ -70,9 +64,8 @@ import { FolderForm } from "./FolderForm";
import { MoveSecretsModal } from "./MoveSecretsModal"; import { MoveSecretsModal } from "./MoveSecretsModal";
type Props = { type Props = {
secrets?: DecryptedSecret[]; secrets?: SecretV3RawSanitized[];
// swtich the secrets type as it gets decrypted after api call // swtich the secrets type as it gets decrypted after api call
importedSecrets?: Array<Omit<TImportedSecrets, "secrets"> & { secrets: DecryptedSecret[] }>;
environment: string; environment: string;
// @depreciated will be moving all these details to zustand // @depreciated will be moving all these details to zustand
workspaceId: string; workspaceId: string;
@@ -92,7 +85,6 @@ type Props = {
export const ActionBar = ({ export const ActionBar = ({
secrets = [], secrets = [],
importedSecrets = [],
environment, environment,
workspaceId, workspaceId,
projectSlug, projectSlug,
@@ -124,7 +116,6 @@ export const ActionBar = ({
const { mutateAsync: createFolder } = useCreateFolder(); const { mutateAsync: createFolder } = useCreateFolder();
const { mutateAsync: deleteBatchSecretV3 } = useDeleteSecretBatch(); const { mutateAsync: deleteBatchSecretV3 } = useDeleteSecretBatch();
const { mutateAsync: moveSecrets } = useMoveSecrets(); const { mutateAsync: moveSecrets } = useMoveSecrets();
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const selectedSecrets = useSelectedSecrets(); const selectedSecrets = useSelectedSecrets();
const { reset: resetSelectedSecret } = useSelectedSecretActions(); const { reset: resetSelectedSecret } = useSelectedSecretActions();
@@ -155,58 +146,46 @@ export const ActionBar = ({
}; };
const handleSecretDownload = async () => { const handleSecretDownload = async () => {
const secPriority: Record<string, boolean> = {}; const { secrets: localSecrets, imports: localImportedSecrets } = await fetchProjectSecrets({
const downloadedSecrets: Array<{ key: string; value: string; comment?: string }> = []; workspaceId,
expandSecretReferences: true,
const PRIVATE_KEY = localStorage.getItem("PRIVATE_KEY") as string; includeImports: true,
const workspaceKey = decryptAssymmetric({ environment,
ciphertext: decryptFileKey!.encryptedKey, secretPath
nonce: decryptFileKey!.nonce,
publicKey: decryptFileKey!.sender.publicKey,
privateKey: PRIVATE_KEY
}); });
const secretsPicked = new Set<string>();
const expandSecrets = interpolateSecrets({ const secretsToDownload: { key: string; value?: string; comment?: string }[] = [];
projectId: workspaceId, localSecrets.forEach((el) => {
secretEncKey: workspaceKey secretsPicked.add(el.secretKey);
}); secretsToDownload.push({
key: el.secretKey,
const secretRecord: Record< value: el.secretValue,
string, comment: el.secretComment
{ value: string; comment?: string; skipMultilineEncoding?: boolean }
> = {};
// load up secrets in dashboard
secrets?.forEach(({ key, value, valueOverride, comment }) => {
secPriority[key] = true;
downloadedSecrets.push({ key, value: valueOverride || value, comment });
});
// now load imported secrets with secPriority
for (let i = importedSecrets.length - 1; i >= 0; i -= 1) {
importedSecrets[i].secrets.forEach(({ key, value, valueOverride, comment }) => {
if (secPriority?.[key]) return;
downloadedSecrets.unshift({ key, value: valueOverride || value, comment });
secPriority[key] = true;
}); });
});
for (let i = localImportedSecrets.length - 1; i >= 0; i -= 1) {
for (let j = localImportedSecrets[i].secrets.length - 1; j >= 0; j -= 1) {
const secret = localImportedSecrets[i].secrets[j];
if (!secretsPicked.has(secret.secretKey)) {
secretsToDownload.push({
key: secret.secretKey,
value: secret.secretValue,
comment: secret.secretComment
});
}
secretsPicked.add(secret.secretKey);
}
} }
downloadedSecrets.forEach((secret) => { const file = secretsToDownload
secretRecord[secret.key] = {
value: secret.value,
comment: secret.comment
};
});
await expandSecrets(secretRecord);
const file = downloadedSecrets
.sort((a, b) => a.key.toLowerCase().localeCompare(b.key.toLowerCase())) .sort((a, b) => a.key.toLowerCase().localeCompare(b.key.toLowerCase()))
.reduce( .reduce(
(prev, { key, comment }, index) => (prev, { key, comment, value }, index) =>
prev + prev +
(comment (comment
? `${index === 0 ? "#" : "\n#"} ${comment}\n${key}=${secretRecord[key].value}\n` ? `${index === 0 ? "#" : "\n#"} ${comment}\n${key}=${value}\n`
: `${key}=${secretRecord[key].value}\n`), : `${key}=${value}\n`),
"" ""
); );
@@ -221,7 +200,7 @@ export const ActionBar = ({
secretPath, secretPath,
workspaceId, workspaceId,
environment, environment,
secrets: bulkDeletedSecrets.map(({ key }) => ({ secretName: key, type: SecretType.Shared })) secrets: bulkDeletedSecrets.map(({ key }) => ({ secretKey: key, type: SecretType.Shared }))
}); });
resetSelectedSecret(); resetSelectedSecret();
handlePopUpClose("bulkDeleteSecrets"); handlePopUpClose("bulkDeleteSecrets");

View File

@@ -6,7 +6,7 @@ import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2"; import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput"; import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import { useCreateSecretV3 } from "@app/hooks/api"; import { useCreateSecretV3 } from "@app/hooks/api";
import { SecretType, UserWsKeyPair } from "@app/hooks/api/types"; import { SecretType } from "@app/hooks/api/types";
import { PopUpNames, usePopUpAction, usePopUpState } from "../../SecretMainPage.store"; import { PopUpNames, usePopUpAction, usePopUpState } from "../../SecretMainPage.store";
@@ -20,7 +20,6 @@ type TFormSchema = z.infer<typeof typeSchema>;
type Props = { type Props = {
environment: string; environment: string;
workspaceId: string; workspaceId: string;
decryptFileKey: UserWsKeyPair;
secretPath?: string; secretPath?: string;
// modal props // modal props
autoCapitalize?: boolean; autoCapitalize?: boolean;
@@ -30,7 +29,6 @@ type Props = {
export const CreateSecretForm = ({ export const CreateSecretForm = ({
environment, environment,
workspaceId, workspaceId,
decryptFileKey,
secretPath = "/", secretPath = "/",
autoCapitalize = true, autoCapitalize = true,
isProtectedBranch = false isProtectedBranch = false
@@ -53,11 +51,10 @@ export const CreateSecretForm = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretValue: value || "", secretValue: value || "",
secretComment: "", secretComment: "",
type: SecretType.Shared, type: SecretType.Shared
latestFileKey: decryptFileKey
}); });
closePopUp(PopUpNames.CreateSecretForm); closePopUp(PopUpNames.CreateSecretForm);
reset(); reset();

View File

@@ -32,7 +32,6 @@ import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { useDebounce } from "@app/hooks"; import { useDebounce } from "@app/hooks";
import { useGetProjectSecrets } from "@app/hooks/api"; import { useGetProjectSecrets } from "@app/hooks/api";
import { UserWsKeyPair } from "@app/hooks/api/types";
const formSchema = z.object({ const formSchema = z.object({
environment: z.string().trim(), environment: z.string().trim(),
@@ -54,7 +53,6 @@ type Props = {
onParsedEnv: (env: Record<string, { value: string; comments: string[] }>) => void; onParsedEnv: (env: Record<string, { value: string; comments: string[] }>) => void;
environments?: { name: string; slug: string }[]; environments?: { name: string; slug: string }[];
workspaceId: string; workspaceId: string;
decryptFileKey: UserWsKeyPair;
environment: string; environment: string;
secretPath: string; secretPath: string;
}; };
@@ -62,7 +60,6 @@ type Props = {
export const CopySecretsFromBoard = ({ export const CopySecretsFromBoard = ({
environments = [], environments = [],
workspaceId, workspaceId,
decryptFileKey,
environment, environment,
secretPath, secretPath,
isOpen, isOpen,
@@ -93,7 +90,6 @@ export const CopySecretsFromBoard = ({
workspaceId, workspaceId,
environment: selectedEnvSlug, environment: selectedEnvSlug,
secretPath: debouncedEnvCopySecretPath, secretPath: debouncedEnvCopySecretPath,
decryptFileKey,
options: { options: {
enabled: enabled:
Boolean(workspaceId) && Boolean(workspaceId) &&

View File

@@ -16,7 +16,7 @@ import { usePopUp, useToggle } from "@app/hooks";
import { useCreateSecretBatch, useUpdateSecretBatch } from "@app/hooks/api"; import { useCreateSecretBatch, useUpdateSecretBatch } from "@app/hooks/api";
import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries"; import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries";
import { secretKeys } from "@app/hooks/api/secrets/queries"; import { secretKeys } from "@app/hooks/api/secrets/queries";
import { DecryptedSecret, SecretType, UserWsKeyPair } from "@app/hooks/api/types"; import { SecretType,SecretV3RawSanitized } from "@app/hooks/api/types";
import { PopUpNames, usePopUpAction } from "../../SecretMainPage.store"; import { PopUpNames, usePopUpAction } from "../../SecretMainPage.store";
import { CopySecretsFromBoard } from "./CopySecretsFromBoard"; import { CopySecretsFromBoard } from "./CopySecretsFromBoard";
@@ -40,10 +40,9 @@ type Props = {
isSmaller: boolean; isSmaller: boolean;
environments?: { name: string; slug: string }[]; environments?: { name: string; slug: string }[];
workspaceId: string; workspaceId: string;
decryptFileKey: UserWsKeyPair;
environment: string; environment: string;
secretPath: string; secretPath: string;
secrets?: DecryptedSecret[]; secrets?: SecretV3RawSanitized[];
isProtectedBranch?: boolean; isProtectedBranch?: boolean;
}; };
@@ -51,7 +50,6 @@ export const SecretDropzone = ({
isSmaller, isSmaller,
environments = [], environments = [],
workspaceId, workspaceId,
decryptFileKey,
environment, environment,
secretPath, secretPath,
secrets = [], secrets = [],
@@ -165,29 +163,27 @@ export const SecretDropzone = ({
try { try {
if (Object.keys(create || {}).length) { if (Object.keys(create || {}).length) {
await createSecretBatch({ await createSecretBatch({
latestFileKey: decryptFileKey!,
secretPath, secretPath,
workspaceId, workspaceId,
environment, environment,
secrets: Object.entries(create).map(([secretName, secData]) => ({ secrets: Object.entries(create).map(([secretKey, secData]) => ({
type: SecretType.Shared, type: SecretType.Shared,
secretComment: secData.comments.join("\n"), secretComment: secData.comments.join("\n"),
secretValue: secData.value, secretValue: secData.value,
secretName secretKey
})) }))
}); });
} }
if (Object.keys(update || {}).length) { if (Object.keys(update || {}).length) {
await updateSecretBatch({ await updateSecretBatch({
latestFileKey: decryptFileKey!,
secretPath, secretPath,
workspaceId, workspaceId,
environment, environment,
secrets: Object.entries(update).map(([secretName, secData]) => ({ secrets: Object.entries(update).map(([secretKey, secData]) => ({
type: SecretType.Shared, type: SecretType.Shared,
secretComment: secData.comments.join("\n"), secretComment: secData.comments.join("\n"),
secretValue: secData.value, secretValue: secData.value,
secretName secretKey
})) }))
}); });
} }
@@ -281,7 +277,6 @@ export const SecretDropzone = ({
environment={environment} environment={environment}
environments={environments} environments={environments}
workspaceId={workspaceId} workspaceId={workspaceId}
decryptFileKey={decryptFileKey}
secretPath={secretPath} secretPath={secretPath}
isSmaller={isSmaller} isSmaller={isSmaller}
/> />

View File

@@ -18,7 +18,7 @@ import { usePopUp } from "@app/hooks";
import { useDeleteSecretImport, useUpdateSecretImport } from "@app/hooks/api"; import { useDeleteSecretImport, useUpdateSecretImport } from "@app/hooks/api";
import { ReservedFolders } from "@app/hooks/api/secretFolders/types"; import { ReservedFolders } from "@app/hooks/api/secretFolders/types";
import { TSecretImport } from "@app/hooks/api/secretImports/types"; import { TSecretImport } from "@app/hooks/api/secretImports/types";
import { DecryptedSecret, WorkspaceEnv } from "@app/hooks/api/types"; import { SecretV3RawSanitized, WorkspaceEnv } from "@app/hooks/api/types";
import { formatReservedPaths } from "@app/lib/fn/string"; import { formatReservedPaths } from "@app/lib/fn/string";
import { SecretImportItem } from "./SecretImportItem"; import { SecretImportItem } from "./SecretImportItem";
@@ -29,14 +29,14 @@ type TImportedSecrets = Array<{
environmentInfo: WorkspaceEnv; environmentInfo: WorkspaceEnv;
secretPath: string; secretPath: string;
folderId: string; folderId: string;
secrets: DecryptedSecret[]; secrets: SecretV3RawSanitized[];
}>; }>;
export const computeImportedSecretRows = ( export const computeImportedSecretRows = (
importedSecEnv: string, importedSecEnv: string,
importedSecPath: string, importedSecPath: string,
importSecrets: TImportedSecrets = [], importSecrets: TImportedSecrets = [],
secrets: DecryptedSecret[] = [] secrets: SecretV3RawSanitized[] = []
) => { ) => {
const importedSecIndex = importSecrets.findIndex( const importedSecIndex = importSecrets.findIndex(
({ secretPath, environmentInfo }) => ({ secretPath, environmentInfo }) =>
@@ -90,7 +90,7 @@ type Props = {
secretPath?: string; secretPath?: string;
secretImports?: TSecretImport[]; secretImports?: TSecretImport[];
isFetching?: boolean; isFetching?: boolean;
secrets?: DecryptedSecret[]; secrets?: SecretV3RawSanitized[];
importedSecrets?: TImportedSecrets; importedSecrets?: TImportedSecrets;
searchTerm: string; searchTerm: string;
}; };

View File

@@ -37,7 +37,7 @@ import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context"; import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context";
import { useToggle } from "@app/hooks"; import { useToggle } from "@app/hooks";
import { useGetSecretVersion } from "@app/hooks/api"; import { useGetSecretVersion } from "@app/hooks/api";
import { DecryptedSecret, UserWsKeyPair, WsTag } from "@app/hooks/api/types"; import { SecretV3RawSanitized, UserWsKeyPair, WsTag } from "@app/hooks/api/types";
import { CreateReminderForm } from "./CreateReminderForm"; import { CreateReminderForm } from "./CreateReminderForm";
import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils"; import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils";
@@ -48,12 +48,12 @@ type Props = {
secretPath: string; secretPath: string;
onToggle: (isOpen: boolean) => void; onToggle: (isOpen: boolean) => void;
onClose: () => void; onClose: () => void;
secret: DecryptedSecret; secret: SecretV3RawSanitized;
decryptFileKey: UserWsKeyPair; decryptFileKey: UserWsKeyPair;
onDeleteSecret: () => void; onDeleteSecret: () => void;
onSaveSecret: ( onSaveSecret: (
orgSec: DecryptedSecret, orgSec: SecretV3RawSanitized,
modSec: Omit<DecryptedSecret, "tags"> & { tags: { id: string }[] }, modSec: Omit<SecretV3RawSanitized, "tags"> & { tags?: { id: string }[] },
cb?: () => void cb?: () => void
) => Promise<void>; ) => Promise<void>;
tags: WsTag[]; tags: WsTag[];
@@ -101,7 +101,7 @@ export const SecretDetailSidebar = ({
control, control,
name: "tags" name: "tags"
}); });
const selectedTags = watch("tags", []); const selectedTags = watch("tags", []) || [];
const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>( const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>(
(prev, curr) => ({ ...prev, [curr.id]: true }), (prev, curr) => ({ ...prev, [curr.id]: true }),
{} {}

View File

@@ -28,7 +28,7 @@ import {
useWorkspace useWorkspace
} from "@app/context"; } from "@app/context";
import { useToggle } from "@app/hooks"; import { useToggle } from "@app/hooks";
import { DecryptedSecret } from "@app/hooks/api/secrets/types"; import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
import { WsTag } from "@app/hooks/api/types"; import { WsTag } from "@app/hooks/api/types";
import { subject } from "@casl/ability"; import { subject } from "@casl/ability";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
@@ -46,14 +46,14 @@ import {
} from "./SecretListView.utils"; } from "./SecretListView.utils";
type Props = { type Props = {
secret: DecryptedSecret; secret: SecretV3RawSanitized;
onSaveSecret: ( onSaveSecret: (
orgSec: DecryptedSecret, orgSec: SecretV3RawSanitized,
modSec: Omit<DecryptedSecret, "tags"> & { tags: { id: string }[] }, modSec: Omit<SecretV3RawSanitized, "tags"> & { tags?: { id: string }[] },
cb?: () => void cb?: () => void
) => Promise<void>; ) => Promise<void>;
onDeleteSecret: (sec: DecryptedSecret) => void; onDeleteSecret: (sec: SecretV3RawSanitized) => void;
onDetailViewSecret: (sec: DecryptedSecret) => void; onDetailViewSecret: (sec: SecretV3RawSanitized) => void;
isVisible?: boolean; isVisible?: boolean;
isSelected?: boolean; isSelected?: boolean;
onToggleSecretSelect: (id: string) => void; onToggleSecretSelect: (id: string) => void;
@@ -113,7 +113,7 @@ export const SecretItem = memo(
const overrideAction = watch("overrideAction"); const overrideAction = watch("overrideAction");
const hasComment = Boolean(watch("comment")); const hasComment = Boolean(watch("comment"));
const selectedTags = watch("tags", []); const selectedTags = watch("tags", []) || [];
const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>( const selectedTagsGroupById = selectedTags.reduce<Record<string, boolean>>(
(prev, curr) => ({ ...prev, [curr.id]: true }), (prev, curr) => ({ ...prev, [curr.id]: true }),
{} {}

View File

@@ -10,7 +10,7 @@ import { usePopUp } from "@app/hooks";
import { useCreateSecretV3, useDeleteSecretV3, useUpdateSecretV3 } from "@app/hooks/api"; import { useCreateSecretV3, useDeleteSecretV3, useUpdateSecretV3 } from "@app/hooks/api";
import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries"; import { secretApprovalRequestKeys } from "@app/hooks/api/secretApprovalRequest/queries";
import { secretKeys } from "@app/hooks/api/secrets/queries"; import { secretKeys } from "@app/hooks/api/secrets/queries";
import { DecryptedSecret, SecretType } from "@app/hooks/api/secrets/types"; import { SecretType,SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
import { secretSnapshotKeys } from "@app/hooks/api/secretSnapshots/queries"; import { secretSnapshotKeys } from "@app/hooks/api/secretSnapshots/queries";
import { UserWsKeyPair, WsTag } from "@app/hooks/api/types"; import { UserWsKeyPair, WsTag } from "@app/hooks/api/types";
import { AddShareSecretModal } from "@app/views/ShareSecretPage/components/AddShareSecretModal"; import { AddShareSecretModal } from "@app/views/ShareSecretPage/components/AddShareSecretModal";
@@ -22,7 +22,7 @@ import { SecretItem } from "./SecretItem";
import { FontAwesomeSpriteSymbols } from "./SecretListView.utils"; import { FontAwesomeSpriteSymbols } from "./SecretListView.utils";
type Props = { type Props = {
secrets?: DecryptedSecret[]; secrets?: SecretV3RawSanitized[];
environment: string; environment: string;
workspaceId: string; workspaceId: string;
decryptFileKey: UserWsKeyPair; decryptFileKey: UserWsKeyPair;
@@ -34,8 +34,8 @@ type Props = {
isProtectedBranch?: boolean; isProtectedBranch?: boolean;
}; };
const reorderSecretGroupByUnderscore = (secrets: DecryptedSecret[], sortDir: SortDir) => { const reorderSecretGroupByUnderscore = (secrets: SecretV3RawSanitized[], sortDir: SortDir) => {
const groupedSecrets: Record<string, DecryptedSecret[]> = {}; const groupedSecrets: Record<string, SecretV3RawSanitized[]> = {};
secrets.forEach((secret) => { secrets.forEach((secret) => {
const lastSeperatorIndex = secret.key.lastIndexOf("_"); const lastSeperatorIndex = secret.key.lastIndexOf("_");
const namespace = const namespace =
@@ -53,7 +53,11 @@ const reorderSecretGroupByUnderscore = (secrets: DecryptedSecret[], sortDir: Sor
.map((namespace) => ({ namespace, secrets: groupedSecrets[namespace] })); .map((namespace) => ({ namespace, secrets: groupedSecrets[namespace] }));
}; };
const reorderSecret = (secrets: DecryptedSecret[], sortDir: SortDir, filter?: GroupBy | null) => { const reorderSecret = (
secrets: SecretV3RawSanitized[],
sortDir: SortDir,
filter?: GroupBy | null
) => {
if (filter === GroupBy.PREFIX) { if (filter === GroupBy.PREFIX) {
return reorderSecretGroupByUnderscore(secrets, sortDir); return reorderSecretGroupByUnderscore(secrets, sortDir);
} }
@@ -70,12 +74,12 @@ const reorderSecret = (secrets: DecryptedSecret[], sortDir: SortDir, filter?: Gr
]; ];
}; };
export const filterSecrets = (secrets: DecryptedSecret[], filter: Filter) => export const filterSecrets = (secrets: SecretV3RawSanitized[], filter: Filter) =>
secrets.filter(({ key, value, tags }) => { secrets.filter(({ key, value, tags }) => {
const isTagFilterActive = Boolean(Object.keys(filter.tags).length); const isTagFilterActive = Boolean(Object.keys(filter.tags).length);
const searchTerm = filter.searchFilter.toLowerCase(); const searchTerm = filter.searchFilter.toLowerCase();
return ( return (
(!isTagFilterActive || tags.some(({ id }) => filter.tags?.[id])) && (!isTagFilterActive || tags?.some(({ id }) => filter.tags?.[id])) &&
(key.toLowerCase().includes(searchTerm) || value.toLowerCase().includes(searchTerm)) (key.toLowerCase().includes(searchTerm) || value.toLowerCase().includes(searchTerm))
); );
}); });
@@ -148,7 +152,7 @@ export const SecretListView = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
type, type,
secretId secretId
}); });
@@ -160,12 +164,10 @@ export const SecretListView = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretId,
secretValue: value || "", secretValue: value || "",
type, type,
latestFileKey: decryptFileKey, tagIds: tags,
tags,
secretComment: comment, secretComment: comment,
secretReminderRepeatDays: reminderRepeatDays, secretReminderRepeatDays: reminderRepeatDays,
secretReminderNote: reminderNote, secretReminderNote: reminderNote,
@@ -180,12 +182,11 @@ export const SecretListView = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretValue: value || "", secretValue: value || "",
secretComment: "", secretComment: "",
skipMultilineEncoding, skipMultilineEncoding,
type, type
latestFileKey: decryptFileKey
}, },
{} {}
); );
@@ -193,8 +194,8 @@ export const SecretListView = ({
const handleSaveSecret = useCallback( const handleSaveSecret = useCallback(
async ( async (
orgSecret: DecryptedSecret, orgSecret: SecretV3RawSanitized,
modSecret: Omit<DecryptedSecret, "tags"> & { tags: { id: string }[] }, modSecret: Omit<SecretV3RawSanitized, "tags"> & { tags?: { id: string }[] },
cb?: () => void cb?: () => void
) => { ) => {
const { key: oldKey } = orgSecret; const { key: oldKey } = orgSecret;
@@ -288,7 +289,7 @@ export const SecretListView = ({
); );
const handleSecretDelete = useCallback(async () => { const handleSecretDelete = useCallback(async () => {
const { key, id: secretId } = popUp.deleteSecret?.data as DecryptedSecret; const { key, id: secretId } = popUp.deleteSecret?.data as SecretV3RawSanitized;
try { try {
await handleSecretOperation("delete", SecretType.Shared, key, { secretId }); await handleSecretOperation("delete", SecretType.Shared, key, { secretId });
// wrap this in another function and then reuse // wrap this in another function and then reuse
@@ -317,16 +318,16 @@ export const SecretListView = ({
text: "Failed to delete secret" text: "Failed to delete secret"
}); });
} }
}, [(popUp.deleteSecret?.data as DecryptedSecret)?.key, environment, secretPath]); }, [(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key, environment, secretPath]);
// for optimization on minimise re-rendering of secret items // for optimization on minimise re-rendering of secret items
const onCreateTag = useCallback(() => handlePopUpOpen("createTag"), []); const onCreateTag = useCallback(() => handlePopUpOpen("createTag"), []);
const onDeleteSecret = useCallback( const onDeleteSecret = useCallback(
(sec: DecryptedSecret) => handlePopUpOpen("deleteSecret", sec), (sec: SecretV3RawSanitized) => handlePopUpOpen("deleteSecret", sec),
[] []
); );
const onDetailViewSecret = useCallback( const onDetailViewSecret = useCallback(
(sec: DecryptedSecret) => handlePopUpOpen("secretDetail", sec), (sec: SecretV3RawSanitized) => handlePopUpOpen("secretDetail", sec),
[] []
); );
@@ -380,7 +381,7 @@ export const SecretListView = ({
)} )}
<DeleteActionModal <DeleteActionModal
isOpen={popUp.deleteSecret.isOpen} isOpen={popUp.deleteSecret.isOpen}
deleteKey={(popUp.deleteSecret?.data as DecryptedSecret)?.key} deleteKey={(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key}
title="Do you want to delete this secret?" title="Do you want to delete this secret?"
onChange={(isOpen) => handlePopUpToggle("deleteSecret", isOpen)} onChange={(isOpen) => handlePopUpToggle("deleteSecret", isOpen)}
onDeleteApproved={handleSecretDelete} onDeleteApproved={handleSecretDelete}
@@ -392,7 +393,7 @@ export const SecretListView = ({
isOpen={popUp.secretDetail.isOpen} isOpen={popUp.secretDetail.isOpen}
onToggle={(isOpen) => handlePopUpToggle("secretDetail", isOpen)} onToggle={(isOpen) => handlePopUpToggle("secretDetail", isOpen)}
decryptFileKey={decryptFileKey} decryptFileKey={decryptFileKey}
secret={popUp.secretDetail.data as DecryptedSecret} secret={popUp.secretDetail.data as SecretV3RawSanitized}
onDeleteSecret={() => handlePopUpOpen("deleteSecret", popUp.secretDetail.data)} onDeleteSecret={() => handlePopUpOpen("deleteSecret", popUp.secretDetail.data)}
onClose={() => handlePopUpClose("secretDetail")} onClose={() => handlePopUpClose("secretDetail")}
onSaveSecret={handleSaveSecret} onSaveSecret={handleSaveSecret}

View File

@@ -52,6 +52,7 @@ export const formSchema = z.object({
}) })
.array() .array()
.default([]) .default([])
.optional()
}); });
export type TFormSchema = z.infer<typeof formSchema>; export type TFormSchema = z.infer<typeof formSchema>;

View File

@@ -21,7 +21,7 @@ import {
Tr Tr
} from "@app/components/v2"; } from "@app/components/v2";
import { useToggle } from "@app/hooks"; import { useToggle } from "@app/hooks";
import { DecryptedSecret } from "@app/hooks/api/types"; import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
export enum TDiffModes { export enum TDiffModes {
NoChange = "no change", NoChange = "no change",
@@ -32,8 +32,8 @@ export enum TDiffModes {
type Props = { type Props = {
mode: TDiffModes; mode: TDiffModes;
preSecret?: DecryptedSecret; preSecret?: SecretV3RawSanitized;
postSecret: DecryptedSecret; postSecret: SecretV3RawSanitized;
}; };
export type TDiffView<T> = { export type TDiffView<T> = {
mode: TDiffModes; mode: TDiffModes;
@@ -120,9 +120,7 @@ export const SecretItem = ({ mode, preSecret, postSecret }: Props) => {
<Td className="border-r border-mineshaft-600">Value</Td> <Td className="border-r border-mineshaft-600">Value</Td>
{isModified && ( {isModified && (
<Td className="border-r border-mineshaft-600"> <Td className="border-r border-mineshaft-600">
<SecretInput <SecretInput value={preSecret?.value} />
value={preSecret?.value}
/>
</Td> </Td>
)} )}
<Td> <Td>

View File

@@ -14,7 +14,7 @@ import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, ContentLoader, Input, Tag, Tooltip } from "@app/components/v2"; import { Button, ContentLoader, Input, Tag, Tooltip } from "@app/components/v2";
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
import { useGetSnapshotSecrets, usePerformSecretRollback } from "@app/hooks/api"; import { useGetSnapshotSecrets, usePerformSecretRollback } from "@app/hooks/api";
import { DecryptedSecret, TSecretFolder, UserWsKeyPair } from "@app/hooks/api/types"; import { SecretV3RawSanitized, TSecretFolder, UserWsKeyPair } from "@app/hooks/api/types";
import { renderIcon, SecretItem, TDiffModes, TDiffView } from "./SecretItem"; import { renderIcon, SecretItem, TDiffModes, TDiffView } from "./SecretItem";
@@ -24,7 +24,7 @@ type Props = {
workspaceId: string; workspaceId: string;
secretPath?: string; secretPath?: string;
decryptFileKey: UserWsKeyPair; decryptFileKey: UserWsKeyPair;
secrets?: DecryptedSecret[]; secrets?: SecretV3RawSanitized[];
folders?: TSecretFolder[]; folders?: TSecretFolder[];
snapshotCount?: number; snapshotCount?: number;
onGoBack: () => void; onGoBack: () => void;
@@ -33,7 +33,7 @@ type Props = {
const LOADER_TEXT = ["Fetching your snapshot", "Creating the difference view"]; const LOADER_TEXT = ["Fetching your snapshot", "Creating the difference view"];
const deepCompareSecrets = (lhs: DecryptedSecret, rhs: DecryptedSecret) => const deepCompareSecrets = (lhs: SecretV3RawSanitized, rhs: SecretV3RawSanitized) =>
lhs.key === rhs.key && lhs.key === rhs.key &&
lhs.value === rhs.value && lhs.value === rhs.value &&
lhs.comment === rhs.comment && lhs.comment === rhs.comment &&
@@ -52,7 +52,6 @@ export const SnapshotView = ({
snapshotCount, snapshotCount,
onClickListSnapshot onClickListSnapshot
}: Props) => { }: Props) => {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const { mutateAsync: performRollback, isLoading: isRollingBack } = usePerformSecretRollback(); const { mutateAsync: performRollback, isLoading: isRollingBack } = usePerformSecretRollback();
@@ -92,11 +91,11 @@ export const SnapshotView = ({
}, [folders, rollingFolder]); }, [folders, rollingFolder]);
const secretDiffView = useMemo(() => { const secretDiffView = useMemo(() => {
const secretGroupById = secrets.reduce<Record<string, DecryptedSecret>>( const secretGroupById = secrets.reduce<Record<string, SecretV3RawSanitized>>(
(prev, curr) => ({ ...prev, [curr.id]: curr }), (prev, curr) => ({ ...prev, [curr.id]: curr }),
{} {}
); );
const diffView: Array<TDiffView<DecryptedSecret>> = []; const diffView: Array<TDiffView<SecretV3RawSanitized>> = [];
rollingSecrets.forEach((rollSecret) => { rollingSecrets.forEach((rollSecret) => {
const { id } = rollSecret; const { id } = rollSecret;
const doesExist = Boolean(secretGroupById?.[id]); const doesExist = Boolean(secretGroupById?.[id]);

View File

@@ -178,8 +178,7 @@ export const SecretOverviewPage = () => {
} = useGetProjectSecretsAllEnv({ } = useGetProjectSecretsAllEnv({
workspaceId, workspaceId,
envs: userAvailableEnvs.map(({ slug }) => slug), envs: userAvailableEnvs.map(({ slug }) => slug),
secretPath, secretPath
decryptFileKey: latestFileKey!
}); });
const { folders, folderNames, isFolderPresentInEnv, getFolderByNameAndEnv } = useGetFoldersByEnv({ const { folders, folderNames, isFolderPresentInEnv, getFolderByNameAndEnv } = useGetFoldersByEnv({
@@ -190,7 +189,6 @@ export const SecretOverviewPage = () => {
const { isImportedSecretPresentInEnv, getImportedSecretByKey } = useGetImportedSecretsAllEnvs({ const { isImportedSecretPresentInEnv, getImportedSecretByKey } = useGetImportedSecretsAllEnvs({
projectId: workspaceId, projectId: workspaceId,
decryptFileKey: latestFileKey!,
path: secretPath, path: secretPath,
environments: userAvailableEnvs.map(({ slug }) => slug) environments: userAvailableEnvs.map(({ slug }) => slug)
}); });
@@ -317,11 +315,10 @@ export const SecretOverviewPage = () => {
environment: env, environment: env,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretValue: value, secretValue: value,
secretComment: "", secretComment: "",
type: SecretType.Shared, type: SecretType.Shared
latestFileKey: latestFileKey!
}); });
createNotification({ createNotification({
type: "success", type: "success",
@@ -348,19 +345,16 @@ export const SecretOverviewPage = () => {
env: string, env: string,
key: string, key: string,
value: string, value: string,
type = SecretType.Shared, type = SecretType.Shared
secretId?: string
) => { ) => {
try { try {
await updateSecretV3({ await updateSecretV3({
environment: env, environment: env,
workspaceId, workspaceId,
secretPath, secretPath,
secretId, secretKey: key,
secretName: key,
secretValue: value, secretValue: value,
type, type
latestFileKey: latestFileKey!
}); });
createNotification({ createNotification({
type: "success", type: "success",
@@ -381,7 +375,7 @@ export const SecretOverviewPage = () => {
environment: env, environment: env,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretId, secretId,
type: SecretType.Shared type: SecretType.Shared
}); });
@@ -861,7 +855,6 @@ export const SecretOverviewPage = () => {
getSecretByKey={getSecretByKey} getSecretByKey={getSecretByKey}
onTogglePopUp={(isOpen) => handlePopUpToggle("addSecretsInAllEnvs", isOpen)} onTogglePopUp={(isOpen) => handlePopUpToggle("addSecretsInAllEnvs", isOpen)}
onClose={() => handlePopUpClose("addSecretsInAllEnvs")} onClose={() => handlePopUpClose("addSecretsInAllEnvs")}
decryptFileKey={latestFileKey!}
/> />
<Modal <Modal
isOpen={popUp.addFolder.isOpen} isOpen={popUp.addFolder.isOpen}

View File

@@ -18,7 +18,7 @@ import {
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput"; import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import { useWorkspace } from "@app/context"; import { useWorkspace } from "@app/context";
import { useCreateFolder, useCreateSecretV3, useUpdateSecretV3 } from "@app/hooks/api"; import { useCreateFolder, useCreateSecretV3, useUpdateSecretV3 } from "@app/hooks/api";
import { DecryptedSecret, SecretType, UserWsKeyPair } from "@app/hooks/api/types"; import { SecretType,SecretV3RawSanitized } from "@app/hooks/api/types";
const typeSchema = z const typeSchema = z
.object({ .object({
@@ -34,8 +34,7 @@ type TFormSchema = z.infer<typeof typeSchema>;
type Props = { type Props = {
secretPath?: string; secretPath?: string;
decryptFileKey: UserWsKeyPair; getSecretByKey: (slug: string, key: string) => SecretV3RawSanitized | undefined;
getSecretByKey: (slug: string, key: string) => DecryptedSecret | undefined;
// modal props // modal props
isOpen?: boolean; isOpen?: boolean;
onClose: () => void; onClose: () => void;
@@ -44,7 +43,6 @@ type Props = {
export const CreateSecretForm = ({ export const CreateSecretForm = ({
secretPath = "/", secretPath = "/",
decryptFileKey,
isOpen, isOpen,
getSecretByKey, getSecretByKey,
onClose, onClose,
@@ -101,10 +99,9 @@ export const CreateSecretForm = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretValue: value || "", secretValue: value || "",
type: SecretType.Shared, type: SecretType.Shared
latestFileKey: decryptFileKey
}); });
} }
@@ -112,11 +109,10 @@ export const CreateSecretForm = ({
environment, environment,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: key, secretKey: key,
secretValue: value || "", secretValue: value || "",
secretComment: "", secretComment: "",
type: SecretType.Shared, type: SecretType.Shared
latestFileKey: decryptFileKey
}); });
}); });

View File

@@ -13,7 +13,7 @@ import { twMerge } from "tailwind-merge";
import { Button, Checkbox, TableContainer, Td, Tooltip, Tr } from "@app/components/v2"; import { Button, Checkbox, TableContainer, Td, Tooltip, Tr } from "@app/components/v2";
import { useToggle } from "@app/hooks"; import { useToggle } from "@app/hooks";
import { DecryptedSecret, SecretType } from "@app/hooks/api/secrets/types"; import { SecretType,SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
import { WorkspaceEnv } from "@app/hooks/api/types"; import { WorkspaceEnv } from "@app/hooks/api/types";
import { SecretEditRow } from "./SecretEditRow"; import { SecretEditRow } from "./SecretEditRow";
@@ -26,7 +26,7 @@ type Props = {
expandableColWidth: number; expandableColWidth: number;
isSelected: boolean; isSelected: boolean;
onToggleSecretSelect: (key: string) => void; onToggleSecretSelect: (key: string) => void;
getSecretByKey: (slug: string, key: string) => DecryptedSecret | undefined; getSecretByKey: (slug: string, key: string) => SecretV3RawSanitized | undefined;
onSecretCreate: (env: string, key: string, value: string) => Promise<void>; onSecretCreate: (env: string, key: string, value: string) => Promise<void>;
onSecretUpdate: ( onSecretUpdate: (
env: string, env: string,
@@ -40,7 +40,7 @@ type Props = {
getImportedSecretByKey: ( getImportedSecretByKey: (
env: string, env: string,
secretName: string secretName: string
) => { secret?: DecryptedSecret; environmentInfo?: WorkspaceEnv } | undefined; ) => { secret?: SecretV3RawSanitized; environmentInfo?: WorkspaceEnv } | undefined;
}; };
export const SecretOverviewTableRow = ({ export const SecretOverviewTableRow = ({

View File

@@ -17,15 +17,15 @@ import {
useWorkspace useWorkspace
} from "@app/context"; } from "@app/context";
import { useToggle } from "@app/hooks"; import { useToggle } from "@app/hooks";
import { useGetUserWsKey, useUpdateSecretV3 } from "@app/hooks/api"; import { useUpdateSecretV3 } from "@app/hooks/api";
import { DecryptedSecret, SecretType } from "@app/hooks/api/types"; import { SecretType,SecretV3RawSanitized } from "@app/hooks/api/types";
import { SecretActionType } from "@app/views/SecretMainPage/components/SecretListView/SecretListView.utils"; import { SecretActionType } from "@app/views/SecretMainPage/components/SecretListView/SecretListView.utils";
type Props = { type Props = {
secretKey: string; secretKey: string;
secretPath: string; secretPath: string;
environments: { name: string; slug: string }[]; environments: { name: string; slug: string }[];
getSecretByKey: (slug: string, key: string) => DecryptedSecret | undefined; getSecretByKey: (slug: string, key: string) => SecretV3RawSanitized | undefined;
}; };
export const formSchema = z.object({ export const formSchema = z.object({
@@ -64,8 +64,6 @@ function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }
); );
const workspaceId = currentWorkspace?.id || ""; const workspaceId = currentWorkspace?.id || "";
const { data: decryptFileKey } = useGetUserWsKey(workspaceId);
const [isSecNameCopied, setIsSecNameCopied] = useToggle(false); const [isSecNameCopied, setIsSecNameCopied] = useToggle(false);
const { mutateAsync: updateSecretV3 } = useUpdateSecretV3(); const { mutateAsync: updateSecretV3 } = useUpdateSecretV3();
@@ -109,12 +107,10 @@ function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }
environment: secret?.env, environment: secret?.env,
workspaceId, workspaceId,
secretPath, secretPath,
secretName: secret.key, secretKey: secret.key,
secretId: secret.id,
secretValue: secret.value || "", secretValue: secret.value || "",
type: SecretType.Shared, type: SecretType.Shared,
latestFileKey: decryptFileKey!, tagIds: secret.tags?.map((tag) => tag.id),
tags: secret.tags.map((tag) => tag.id),
secretComment: secret.comment, secretComment: secret.comment,
secretReminderRepeatDays: secret.reminderRepeatDays, secretReminderRepeatDays: secret.reminderRepeatDays,
secretReminderNote: secret.reminderNote, secretReminderNote: secret.reminderNote,

View File

@@ -14,8 +14,8 @@ import {
import { usePopUp } from "@app/hooks"; import { usePopUp } from "@app/hooks";
import { useDeleteFolder, useDeleteSecretBatch } from "@app/hooks/api"; import { useDeleteFolder, useDeleteSecretBatch } from "@app/hooks/api";
import { import {
DecryptedSecret,
SecretType, SecretType,
SecretV3RawSanitized,
TDeleteSecretBatchDTO, TDeleteSecretBatchDTO,
TSecretFolder TSecretFolder
} from "@app/hooks/api/types"; } from "@app/hooks/api/types";
@@ -27,7 +27,7 @@ export enum EntryType {
type Props = { type Props = {
secretPath: string; secretPath: string;
getSecretByKey: (slug: string, key: string) => DecryptedSecret | undefined; getSecretByKey: (slug: string, key: string) => SecretV3RawSanitized | undefined;
getFolderByNameAndEnv: (name: string, env: string) => TSecretFolder | undefined; getFolderByNameAndEnv: (name: string, env: string) => TSecretFolder | undefined;
resetSelectedEntries: () => void; resetSelectedEntries: () => void;
selectedEntries: { selectedEntries: {
@@ -115,7 +115,7 @@ export const SelectionPanel = ({
return [ return [
...accum, ...accum,
{ {
secretName: entry.key, secretKey: entry.key,
type: SecretType.Shared type: SecretType.Shared
} }
]; ];

View File

@@ -5,7 +5,7 @@ import { z } from "zod";
import { Button, FormControl, Input, Select, SelectItem, Spinner } from "@app/components/v2"; import { Button, FormControl, Input, Select, SelectItem, Spinner } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput"; import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { useWorkspace } from "@app/context"; import { useWorkspace } from "@app/context";
import { useGetProjectSecrets, useGetUserWsKey } from "@app/hooks/api"; import { useGetProjectSecrets } from "@app/hooks/api";
const formSchema = z.object({ const formSchema = z.object({
environment: z.string().trim(), environment: z.string().trim(),
@@ -38,12 +38,10 @@ export const RotationOutputForm = ({ onSubmit, onCancel, outputSchema = {} }: Pr
const secretPath = watch("secretPath"); const secretPath = watch("secretPath");
const selectedSecrets = watch("secrets"); const selectedSecrets = watch("secrets");
const { data: userWsKey } = useGetUserWsKey(workspaceId);
const { data: secrets, isLoading: isSecretsLoading } = useGetProjectSecrets({ const { data: secrets, isLoading: isSecretsLoading } = useGetProjectSecrets({
workspaceId, workspaceId,
environment, environment,
secretPath, secretPath
decryptFileKey: userWsKey!
}); });
return ( return (