Skip to content

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

requested changes

Daniel Hougaard0283aca80177
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 28b85eaf10..5533ca4296 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -27,7 +27,8 @@ export const PgSqlLock = {
GatewayPamSessionKey: (gatewayId: string) => pgAdvisoryLockHashText(`gateway-pam-session-key:${gatewayId}`),
IdentityLogin: (identityId: string, nonce: string) => pgAdvisoryLockHashText(`identity-login:${identityId}:${nonce}`),
PamResourceSshCaInit: (resourceId: string) => pgAdvisoryLockHashText(`pam-resource-ssh-ca-init:${resourceId}`),
- CreateIdentity: (orgId: string) => pgAdvisoryLockHashText(`create-identity:${orgId}`)
+ CreateIdentity: (orgId: string) => pgAdvisoryLockHashText(`create-identity:${orgId}`),
+ AccessSharedSecret: (sharedSecretId: string) => pgAdvisoryLockHashText(`access-shared-secret:${sharedSecretId}`)
} as const;
// all the key prefixes used must be set here to avoid conflict
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9b9117b0e9..88e3a60970 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1621,6 +1621,7 @@ export const registerRoutes = async (
kmsService,
smtpService,
userDAL,
+ identityDAL,
licenseService
});
diff --git a/backend/src/server/routes/v1/secret-sharing-router.ts b/backend/src/server/routes/v1/secret-sharing-router.ts
index 6bbcabf19c..aec42951be 100644
--- a/backend/src/server/routes/v1/secret-sharing-router.ts
+++ b/backend/src/server/routes/v1/secret-sharing-router.ts
@@ -96,6 +96,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
response: {
200: SanitizedSecretSharingSchema.extend({
isPasswordProtected: z.boolean().describe("Whether the shared secret is protected by a password.")
+ }).omit({
+ authorizedEmails: true
})
}
},
@@ -234,7 +236,7 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
.object({
name: z.string().max(50).optional().describe(SECRET_SHARING.CREATE.name),
password: z.string().optional().describe(SECRET_SHARING.CREATE.password),
- secretValue: z.string().describe(SECRET_SHARING.CREATE.secretValue),
+ secretValue: z.string().max(10_000).describe(SECRET_SHARING.CREATE.secretValue),
expiresIn: z.string().default("30d").describe(SECRET_SHARING.CREATE.expiresIn),
maxViews: z.number().min(1).optional().describe(SECRET_SHARING.CREATE.maxViews),
accessType: z
diff --git a/backend/src/services/secret-sharing/secret-sharing-service.ts b/backend/src/services/secret-sharing/secret-sharing-service.ts
index 448228b6a2..c6abd1f8ff 100644
--- a/backend/src/services/secret-sharing/secret-sharing-service.ts
+++ b/backend/src/services/secret-sharing/secret-sharing-service.ts
@@ -4,6 +4,7 @@ import { OrganizationActionScope, TOrganizations, TSecretSharing } from "@app/db
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { OrgPermissionSecretShareAction, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
@@ -12,6 +13,7 @@ import { ms } from "@app/lib/ms";
import { OrgServiceActor, SecretSharingAccessType } from "@app/lib/types";
import { ActorType } from "../auth/auth-type";
+import { TIdentityDALFactory } from "../identity/identity-dal";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TOrgDALFactory } from "../org/org-dal";
import { TSecretShareBrandConfig } from "../org/org-types";
@@ -41,6 +43,7 @@ type TSecretSharingServiceFactoryDep = {
kmsService: TKmsServiceFactory;
smtpService: TSmtpService;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ identityDAL: Pick<TIdentityDALFactory, "findById">;
};
export type TSecretSharingServiceFactory = ReturnType<typeof secretSharingServiceFactory>;
@@ -55,7 +58,7 @@ const mapIdentifierToId = (sharedSecret: TSecretSharing): Omit<TSecretSharing, "
if (!identifier) {
throw new BadRequestError({
- message: `Shared secret created at ${sharedSecret.createdAt.toISOString()} has no identifier`
+ message: `Shared secret with ID ${sharedSecret.id} has no identifier`
});
}
@@ -70,6 +73,7 @@ export const secretSharingServiceFactory = ({
secretSharingDAL,
orgAssetDAL,
orgDAL,
+ identityDAL,
kmsService,
smtpService,
userDAL,
@@ -202,23 +206,37 @@ export const secretSharingServiceFactory = ({
// Loop through recipients and send out emails with unique access links
if (authorizedEmails) {
- const user = await userDAL.findById(actorId);
+ let displayUsername: string | undefined;
- if (!user) {
- throw new NotFoundError({ message: `User with ID '${actorId}' not found` });
+ if (actor === ActorType.USER) {
+ const user = await userDAL.findById(actorId);
+
+ if (!user) {
+ throw new NotFoundError({ message: `User with ID '${actorId}' not found` });
+ }
+
+ displayUsername = user.username;
+ } else if (actor === ActorType.IDENTITY) {
+ const identity = await identityDAL.findById(actorId);
+
+ if (!identity) {
+ throw new NotFoundError({ message: `Identity with ID '${actorId}' not found` });
+ }
+
+ displayUsername = `${identity.name} (Machine Identity)`;
}
for await (const email of authorizedEmails) {
try {
// Only show the username to emails which are part of the organization
- const respondentUsername = orgEmails.includes(email) ? user.username : undefined;
+ const senderUsername = orgEmails.includes(email) ? displayUsername : undefined;
await smtpService.sendMail({
recipients: [email],
subjectLine: "A secret has been shared with you",
substitutions: {
name,
- respondentUsername,
+ senderUsername,
secretRequestUrl: `${appCfg.SITE_URL}/shared/secret/${mappedSharedSecret.id}`
},
template: SmtpTemplates.SecretRequestCompleted
@@ -596,91 +614,97 @@ export const secretSharingServiceFactory = ({
/** Gets password-less secret. validates all secret's requested (must be fresh). */
const accessSharedSecret = async ({ sharedSecretId, orgId, actorId, password }: TGetActiveSharedSecretByIdDTO) => {
- const sharedSecret = await secretSharingDAL.findOne({
- type: SecretSharingType.Share,
- identifier: Buffer.from(sharedSecretId, "base64url").toString("hex")
- });
+ const result = await secretSharingDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.AccessSharedSecret(sharedSecretId)]);
- if (!sharedSecret) {
- throw new NotFoundError({
- message: `Shared secret with ID '${sharedSecretId}' not found`
+ const sharedSecret = await secretSharingDAL.findOne({
+ type: SecretSharingType.Share,
+ identifier: Buffer.from(sharedSecretId, "base64url").toString("hex")
});
- }
- const { accessType, expiresAt, expiresAfterViews } = sharedSecret;
+ if (!sharedSecret) {
+ throw new NotFoundError({
+ message: `Shared secret with ID '${sharedSecretId}' not found`
+ });
+ }
- if (accessType === SecretSharingAccessType.Organization && orgId === undefined) {
- throw new UnauthorizedError();
- }
+ const { accessType, expiresAt, expiresAfterViews } = sharedSecret;
- if (accessType === SecretSharingAccessType.Organization && orgId !== sharedSecret.orgId) {
- throw new ForbiddenRequestError();
- }
+ if (accessType === SecretSharingAccessType.Organization && orgId === undefined) {
+ throw new UnauthorizedError();
+ }
- // If the secret was shared with specific emails, verify that the current user's session email is authorized
- if (sharedSecret.authorizedEmails && (sharedSecret.authorizedEmails as string[]).length > 0) {
- if (!actorId) throw new UnauthorizedError();
+ if (accessType === SecretSharingAccessType.Organization && orgId !== sharedSecret.orgId) {
+ throw new ForbiddenRequestError();
+ }
- const user = await userDAL.findById(actorId);
- if (!user || !user.email) throw new UnauthorizedError();
+ // If the secret was shared with specific emails, verify that the current user's session email is authorized
+ if (sharedSecret.authorizedEmails && (sharedSecret.authorizedEmails as string[]).length > 0) {
+ if (!actorId) throw new UnauthorizedError();
- if (!(sharedSecret.authorizedEmails as string[]).includes(user.email))
- throw new ForbiddenRequestError({ message: "You are not authorized to view this secret" });
- }
+ const user = await userDAL.findById(actorId);
+ if (!user || !user.email) throw new UnauthorizedError();
- // all secrets pass through here, meaning we check if its expired first and then check if it needs verification
- // or can be safely sent to the client.
- if (expiresAt !== null && expiresAt < new Date()) {
- // check lifetime expiry
- await secretSharingDAL.softDeleteById(sharedSecret.id);
- throw new NotFoundError({ message: "The shared secret has expired" });
- }
+ if (!(sharedSecret.authorizedEmails as string[]).includes(user.email))
+ throw new ForbiddenRequestError({ message: "You are not authorized to view this secret" });
+ }
- if (expiresAfterViews !== null && expiresAfterViews === 0) {
- // check view count expiry
- await secretSharingDAL.softDeleteById(sharedSecret.id);
- throw new NotFoundError({ message: "The shared secret has reached its view limit" });
- }
+ // all secrets pass through here, meaning we check if its expired first and then check if it needs verification
+ // or can be safely sent to the client.
+ if (expiresAt !== null && expiresAt < new Date()) {
+ // check lifetime expiry
+ await secretSharingDAL.softDeleteById(sharedSecret.id);
+ throw new NotFoundError({ message: "The shared secret has expired" });
+ }
+
+ if (expiresAfterViews !== null && expiresAfterViews === 0) {
+ // check view count expiry
+ await secretSharingDAL.softDeleteById(sharedSecret.id);
+ throw new NotFoundError({ message: "The shared secret has reached its view limit" });
+ }
- // Password checks
- const isPasswordProtected = Boolean(sharedSecret.password);
- const hasProvidedPassword = Boolean(password);
- if (isPasswordProtected) {
- if (hasProvidedPassword) {
- const isMatch = await crypto.hashing().compareHash(password as string, sharedSecret.password as string);
- if (!isMatch) {
- throw new UnauthorizedError({ message: "Invalid credentials" });
+ // Password checks
+ const isPasswordProtected = Boolean(sharedSecret.password);
+ const hasProvidedPassword = Boolean(password);
+ if (isPasswordProtected) {
+ if (hasProvidedPassword) {
+ const isMatch = await crypto.hashing().compareHash(password as string, sharedSecret.password as string);
+ if (!isMatch) {
+ throw new UnauthorizedError({ message: "Invalid credentials" });
+ }
+ } else {
+ throw new UnauthorizedError({ message: "Password is required to access this secret" });
}
- } else {
- throw new UnauthorizedError({ message: "Password is required to access this secret" });
}
- }
- const decryptWithRoot = kmsService.decryptWithRootKey();
+ const decryptWithRoot = kmsService.decryptWithRootKey();
- if (!sharedSecret.encryptedSecret) {
- throw new BadRequestError({ message: "Secret has no value specified" });
- }
- const decryptedSecretValue = decryptWithRoot(sharedSecret.encryptedSecret);
+ if (!sharedSecret.encryptedSecret) {
+ throw new BadRequestError({ message: "Secret has no value specified" });
+ }
+ const decryptedSecretValue = decryptWithRoot(sharedSecret.encryptedSecret);
- let organization: TOrganizations | undefined;
+ let organization: TOrganizations | undefined;
- if (
- sharedSecret.orgId &&
- sharedSecret.orgId === orgId &&
- sharedSecret.accessType === SecretSharingAccessType.Organization
- ) {
- organization = await orgDAL.findOrgById(sharedSecret.orgId);
- }
+ if (
+ sharedSecret.orgId &&
+ sharedSecret.orgId === orgId &&
+ sharedSecret.accessType === SecretSharingAccessType.Organization
+ ) {
+ organization = await orgDAL.findOrgById(sharedSecret.orgId);
+ }
- // decrement when we are sure the user will view secret.
- await $decrementSecretViewCount(sharedSecret);
+ // decrement when we are sure the user will view secret.
+ await $decrementSecretViewCount(sharedSecret);
- return {
- ...mapIdentifierToId(sharedSecret),
- secretValue: decryptedSecretValue.toString(),
- orgName: organization?.name
- };
+ return {
+ ...mapIdentifierToId(sharedSecret),
+ secretValue: decryptedSecretValue.toString(),
+ orgName: organization?.name
+ };
+ });
+
+ return result;
};
const deleteSharedSecretById = async (deleteSharedSecretInput: TDeleteSharedSecretDTO) => {
diff --git a/backend/src/services/smtp/emails/SecretRequestCompletedTemplate.tsx b/backend/src/services/smtp/emails/SecretRequestCompletedTemplate.tsx
index 37e758661c..cdb14232df 100644
--- a/backend/src/services/smtp/emails/SecretRequestCompletedTemplate.tsx
+++ b/backend/src/services/smtp/emails/SecretRequestCompletedTemplate.tsx
@@ -6,14 +6,14 @@ import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
interface SecretRequestCompletedTemplateProps extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
name?: string;
- respondentUsername: string;
+ senderUsername?: string;
secretRequestUrl: string;
}
export const SecretRequestCompletedTemplate = ({
name,
siteUrl,
- respondentUsername,
+ senderUsername,
secretRequestUrl
}: SecretRequestCompletedTemplateProps) => {
return (
@@ -23,7 +23,7 @@ export const SecretRequestCompletedTemplate = ({
</Heading>
<Section className="px-[24px] mb-[28px] mt-[36px] pt-[12px] text-center pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">
<Text className="text-[14px]">
- {respondentUsername ? <strong>{respondentUsername}</strong> : "Someone"} shared a secret{" "}
+ {senderUsername ? <strong>{senderUsername}</strong> : "Someone"} shared a secret{" "}
{name && (
<>
<strong>{name}</strong>{" "}
@@ -42,7 +42,7 @@ export const SecretRequestCompletedTemplate = ({
export default SecretRequestCompletedTemplate;
SecretRequestCompletedTemplate.PreviewProps = {
- respondentUsername: "Gracie",
+ senderUsername: "Gracie",
siteUrl: "https://infisical.com",
secretRequestUrl: "https://infisical.com",
name: "API_TOKEN"
diff --git a/frontend/src/hooks/api/secretSharing/types.ts b/frontend/src/hooks/api/secretSharing/types.ts
index 54b1175bab..5d98e785e3 100644
--- a/frontend/src/hooks/api/secretSharing/types.ts
+++ b/frontend/src/hooks/api/secretSharing/types.ts
@@ -69,7 +69,6 @@ export type TSanitizedSharedSecret = {
accessType: SecretSharingAccessType;
expiresAt: string;
expiresAfterViews: number | null;
- authorizedEmails: string[] | null;
};
export type TSharedSecretPublicDetails = TSanitizedSharedSecret & {