Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Fix merge conflicts
Tuan Dang200d9de7406a
diff --cc backend/src/config/index.tsindex b61db88114,f7555248ad..d73b17a724--- a/backend/src/config/index.ts+++ b/backend/src/config/index.ts@@@ -5,18 -5,8 +5,15 @@@ export const client = new InfisicalClie});export const getPort = async () => (await client.getSecret('PORT')).secretValue || 4000;- export const getInviteOnlySignup = async () => (await client.getSecret('INVITE_ONLY_SIGNUP')).secretValue == undefined ? false : (await client.getSecret('INVITE_ONLY_SIGNUP')).secretValue;-+export const getEncryptionKey = async () => {+ const secretValue = (await client.getSecret('ENCRYPTION_KEY')).secretValue;+ return secretValue === '' ? undefined : secretValue;+}-+export const getRootEncryptionKey = async () => {+ const secretValue = (await client.getSecret('ROOT_ENCRYPTION_KEY')).secretValue;+ return secretValue === '' ? undefined : secretValue;+}-+ export const getInviteOnlySignup = async () => (await client.getSecret('INVITE_ONLY_SIGNUP')).secretValue === 'true'-export const getEncryptionKey = async () => (await client.getSecret('ENCRYPTION_KEY')).secretValue;export const getSaltRounds = async () => parseInt((await client.getSecret('SALT_ROUNDS')).secretValue) || 10;export const getJwtAuthLifetime = async () => (await client.getSecret('JWT_AUTH_LIFETIME')).secretValue || '10d';export const getJwtAuthSecret = async () => (await client.getSecret('JWT_AUTH_SECRET')).secretValue;@@@ -55,6 -45,12 +52,18 @@@ export const getSmtpUsername = async (export const getSmtpPassword = async () => (await client.getSecret('SMTP_PASSWORD')).secretValue;export const getSmtpFromAddress = async () => (await client.getSecret('SMTP_FROM_ADDRESS')).secretValue;export const getSmtpFromName = async () => (await client.getSecret('SMTP_FROM_NAME')).secretValue || 'Infisical';+-export const getLicenseKey = async () => (await client.getSecret('LICENSE_KEY')).secretValue;-export const getLicenseServerKey = async () => (await client.getSecret('LICENSE_SERVER_KEY')).secretValue;++export const getLicenseKey = async () => {++ const secretValue = (await client.getSecret('LICENSE_KEY')).secretValue;++ return secretValue === '' ? undefined : secretValue;++}++export const getLicenseServerKey = async () => {++ const secretValue = (await client.getSecret('LICENSE_SERVER_KEY')).secretValue;++ return secretValue === '' ? undefined : secretValue;++}+ export const getLicenseServerUrl = async () => (await client.getSecret('LICENSE_SERVER_URL')).secretValue || 'https://portal.infisical.com';++ // TODO: deprecate from hereexport const getStripeProductStarter = async () => (await client.getSecret('STRIPE_PRODUCT_STARTER')).secretValue;export const getStripeProductPro = async () => (await client.getSecret('STRIPE_PRODUCT_PRO')).secretValue;export const getStripeProductTeam = async () => (await client.getSecret('STRIPE_PRODUCT_TEAM')).secretValue;diff --cc backend/src/controllers/v2/secretsController.tsindex a3773f8157,5c5140587a..ef170ca0f0--- a/backend/src/controllers/v2/secretsController.ts+++ b/backend/src/controllers/v2/secretsController.ts@@@ -8,15 -7,12 +7,14 @@@ importACTION_ADD_SECRETS,ACTION_READ_SECRETS,ACTION_UPDATE_SECRETS,- ACTION_DELETE_SECRETS+ ACTION_DELETE_SECRETS,+ ALGORITHM_AES_256_GCM,+ ENCODING_SCHEME_UTF8} from '../../variables';- import { UnauthorizedRequestError, ValidationError } from '../../utils/errors';+ import { UnauthorizedRequestError, WorkspaceNotFoundError } from '../../utils/errors';import { EventService } from '../../services';import { eventPushSecrets } from '../../events';- import { EESecretService, EELogService } from '../../ee/services';+ import { EESecretService, EELogService, EELicenseService } from '../../ee/services';import { TelemetryService, SecretService } from '../../services';import { getChannelFromUserAgent } from '../../utils/posthog';import { PERMISSION_WRITE_SECRETS } from '../../variables';diff --cc backend/src/helpers/organization.tsindex b9fe4eb9cf,54f050a368..74c5df71d8--- a/backend/src/helpers/organization.ts+++ b/backend/src/helpers/organization.ts@@@ -10,7 -23,105 +10,17 @@@ importgetStripeProductTeam,getStripeProductStarter,} from "../config";-import {- UnauthorizedRequestError,- OrganizationNotFoundError,-} from "../utils/errors";-import { validateUserClientForOrganization } from "../helpers/user";-import { validateServiceAccountClientForOrganization } from "../helpers/serviceAccount";+ import {+ EELicenseService+ } from '../ee/services';+ import {+ getLicenseServerUrl+ } from '../config';+ import {+ licenseServerKeyRequest,+ licenseKeyRequest+ } from '../config/request';-/**- * Validate accepted clients for organization with id [organizationId]- * @param {Object} obj- * @param {Object} obj.authData - authenticated client details- * @param {Types.ObjectId} obj.organizationId - id of organization to validate against- */-const validateClientForOrganization = async ({- authData,- organizationId,- acceptedRoles,- acceptedStatuses,-}: {- authData: {- authMode: string;- authPayload: IUser | IServiceAccount | IServiceTokenData;- };- organizationId: Types.ObjectId;- acceptedRoles: Array<"owner" | "admin" | "member">;- acceptedStatuses: Array<"invited" | "accepted">;-}) => {- const organization = await Organization.findById(organizationId);-- if (!organization) {- throw OrganizationNotFoundError({- message: "Failed to find organization",- });- }-- if (- authData.authMode === AUTH_MODE_JWT &&- authData.authPayload instanceof User- ) {- const membershipOrg = await validateUserClientForOrganization({- user: authData.authPayload,- organization,- acceptedRoles,- acceptedStatuses,- });-- return { organization, membershipOrg };- }-- if (- authData.authMode === AUTH_MODE_SERVICE_ACCOUNT &&- authData.authPayload instanceof ServiceAccount- ) {- await validateServiceAccountClientForOrganization({- serviceAccount: authData.authPayload,- organization,- });-- return { organization };- }-- if (- authData.authMode === AUTH_MODE_SERVICE_TOKEN &&- authData.authPayload instanceof ServiceTokenData- ) {- throw UnauthorizedRequestError({- message: "Failed service token authorization for organization",- });- }-- if (- authData.authMode === AUTH_MODE_API_KEY &&- authData.authPayload instanceof User- ) {- const membershipOrg = await validateUserClientForOrganization({- user: authData.authPayload,- organization,- acceptedRoles,- acceptedStatuses,- });-- return { organization, membershipOrg };- }-- throw UnauthorizedRequestError({- message: "Failed client authorization for organization",- });-};-/*** Create an organization with name [name]* @param {Object} objdiff --cc backend/src/index.tsindex 9f1bd918e1,5906cd5a15..178baaacb1--- a/backend/src/index.ts+++ b/backend/src/index.ts@@@ -4,8 -3,17 +3,9 @@@ dotenv.config()import express from 'express';import helmet from 'helmet';import cors from 'cors';-import * as Sentry from '@sentry/node';import { DatabaseService } from './services';+ import { EELicenseService } from './ee/services';import { setUpHealthEndpoint } from './services/health';-import { initSmtp } from './services/smtp';-import { TelemetryService } from './services';-import { setTransporter } from './helpers/nodemailer';-import { createTestUserForDevelopment } from './utils/addDevelopmentUser';-// eslint-disable-next-line @typescript-eslint/no-var-requires-const { patchRouterParam } = require('./utils/patchAsyncRoutes');-import cookieParser from 'cookie-parser';import swaggerUi = require('swagger-ui-express');// eslint-disable-next-line @typescript-eslint/no-var-requires@@@ -62,19 -72,30 +64,17 @@@ import { getLogger } from './utils/loggimport { RouteNotFoundError } from './utils/errors';import { requestErrorHandler } from './middleware/requestErrorHandler';import {-- getMongoURL,getNodeEnv,getPort,-- getSentryDSN,- getSiteURL,- getSmtpHost+ getSiteURL} from './config';+import { setup } from './utils/setup';- import { patchRouterParam } from './utils/patchAsyncRoutes';const main = async () => {- TelemetryService.logTelemetryMessage();- setTransporter(await initSmtp());+ await setup();+ await EELicenseService.initGlobalFeatureSet();+- await DatabaseService.initDatabase(await getMongoURL());- if ((await getNodeEnv()) !== 'test') {- Sentry.init({- dsn: await getSentryDSN(),- tracesSampleRate: 1.0,- debug: await getNodeEnv() === 'production' ? false : true,- environment: await getNodeEnv()- });- }-- patchRouterParam();const app = express();app.enable('trust proxy');app.use(express.json());diff --cc backend/src/middleware/requireWorkspaceAuth.tsindex 557987490a,7e97b2e32f..da517b998b--- a/backend/src/middleware/requireWorkspaceAuth.ts+++ b/backend/src/middleware/requireWorkspaceAuth.ts@@@ -1,8 -1,6 +1,6 @@@import { Request, Response, NextFunction } from 'express';import { Types } from 'mongoose';- import { validateMembership } from '../helpers/membership';-import { validateClientForWorkspace } from '../helpers/workspace';+import { validateClientForWorkspace } from '../validation';- import { UnauthorizedRequestError } from '../utils/errors';type req = 'params' | 'body' | 'query';diff --cc backend/src/utils/setup/index.tsindex 6c7bfb422d,0000000000..c59a974d03mode 100644,000000..100644--- a/backend/src/utils/setup/index.ts+++ b/backend/src/utils/setup/index.ts@@@ -1,73 -1,0 +1,78 @@@+import * as Sentry from '@sentry/node';+import { DatabaseService, TelemetryService } from '../../services';+import { setTransporter } from '../../helpers/nodemailer';++import { EELicenseService } from '../../ee/services';+import { initSmtp } from '../../services/smtp';+import { createTestUserForDevelopment } from '../addDevelopmentUser'+// eslint-disable-next-line @typescript-eslint/no-var-requires+const { patchRouterParam } = require('../patchAsyncRoutes');+import {+ validateEncryptionKeysConfig+} from './validateConfig';+import {+ backfillSecretVersions,+ backfillBots,+ backfillSecretBlindIndexData,+ backfillEncryptionMetadata+} from './backfillData';+import {+ reencryptBotPrivateKeys,+ reencryptSecretBlindIndexDataSalts+} from './reencryptData';+import {+ getNodeEnv,+ getMongoURL,+ getSentryDSN+} from '../../config';++/**+ * Prepare Infisical upon startup. This includes tasks like:+ * - Log initial telemetry message+ * - Initializing SMTP configuration++ * - Initializing the instance global feature set (if applicable)+ * - Initializing the database connection+ * - Initializing Sentry+ * - Backfilling data+ * - Re-encrypting data+ */+export const setup = async () => {+ patchRouterParam();+ await validateEncryptionKeysConfig();+ await TelemetryService.logTelemetryMessage();++ // initializing SMTP configuration+ setTransporter(await initSmtp());+++ // initializing global feature set++ await EELicenseService.initGlobalFeatureSet();+++ // initializing the database connection+ await DatabaseService.initDatabase(await getMongoURL());++ /**+ * NOTE: the order in this setup function is critical.+ * It is important to backfill data before performing any re-encryption functionality.+ */++ // backfilling data to catch up with new collections and updated fields+ await backfillSecretVersions();+ await backfillBots();+ await backfillSecretBlindIndexData();+ await backfillEncryptionMetadata();++ // re-encrypt any data previously encrypted under server hex 128-bit ENCRYPTION_KEY+ // to base64 256-bit ROOT_ENCRYPTION_KEY+ await reencryptBotPrivateKeys();+ await reencryptSecretBlindIndexDataSalts();++ // initializing Sentry+ Sentry.init({+ dsn: await getSentryDSN(),+ tracesSampleRate: 1.0,+ debug: (await getNodeEnv()) === 'production' ? false : true,+ environment: (await getNodeEnv())+ });++ await createTestUserForDevelopment();+}+diff --cc backend/src/utils/setup/reencryptData.tsindex 1bf499cc9e,0000000000..0741b44f40mode 100644,000000..100644--- a/backend/src/utils/setup/reencryptData.ts+++ b/backend/src/utils/setup/reencryptData.ts@@@ -1,126 -1,0 +1,124 @@@+import {+ Bot,+ IBot,+ ISecretBlindIndexData,+ SecretBlindIndexData+} from '../../models';+import { decryptSymmetric128BitHexKeyUTF8 } from '../../utils/crypto';+import {+ client,+ getEncryptionKey,+ getRootEncryptionKey+} from '../../config';+import {+ ALGORITHM_AES_256_GCM,+ ENCODING_SCHEME_UTF8,+ ENCODING_SCHEME_BASE64+} from '../../variables';++/**+ * Re-encrypt bot private keys from hex 128-bit ENCRYPTION_KEY+ * to base64 256-bit ROOT_ENCRYPTION_KEY+ */+export const reencryptBotPrivateKeys = async () => {+ const encryptionKey = await getEncryptionKey();+ const rootEncryptionKey = await getRootEncryptionKey();++ if (encryptionKey && rootEncryptionKey) {+ // 1: re-encrypt bot private keys under ROOT_ENCRYPTION_KEY+ const bots = await Bot.find({+ algorithm: ALGORITHM_AES_256_GCM,+ keyEncoding: ENCODING_SCHEME_UTF8+ }).select('+encryptedPrivateKey iv tag algorithm keyEncoding');++ if (bots.length === 0) return;++ const operationsBot = await Promise.all(+ bots.map(async (bot: IBot) => {++ const privateKey = decryptSymmetric128BitHexKeyUTF8({+ ciphertext: bot.encryptedPrivateKey,+ iv: bot.iv,+ tag: bot.tag,+ key: encryptionKey+ });++ const {+ ciphertext: encryptedPrivateKey,+ iv,+ tag+ } = client.encryptSymmetric(privateKey, rootEncryptionKey);++ return ({+ updateOne: {+ filter: {+ _id: bot._id+ },+ update: {+ encryptedPrivateKey,+ iv,+ tag,+ algorithm: ALGORITHM_AES_256_GCM,+ keyEncoding: ENCODING_SCHEME_BASE64+ }+ }+ })+ })+ );++ await Bot.bulkWrite(operationsBot);+ }+}++/**+ * Re-encrypt secret blind index data salts from hex 128-bit ENCRYPTION_KEY+ * to base64 256-bit ROOT_ENCRYPTION_KEY+ */+export const reencryptSecretBlindIndexDataSalts = async () => {+ const encryptionKey = await getEncryptionKey();+ const rootEncryptionKey = await getRootEncryptionKey();+- // 2. re-encrypt secret blind index salts under ROOT_ENCRYPTION_KEY-+ if (encryptionKey && rootEncryptionKey) {+ const secretBlindIndexData = await SecretBlindIndexData.find({+ algorithm: ALGORITHM_AES_256_GCM,+ keyEncoding: ENCODING_SCHEME_UTF8+ }).select('+encryptedSaltCiphertext +saltIV +saltTag +algorithm +keyEncoding');++ if (secretBlindIndexData.length == 0) return;++ const operationsSecretBlindIndexData = await Promise.all(+ secretBlindIndexData.map(async (secretBlindIndexDatum: ISecretBlindIndexData) => {++ const salt = decryptSymmetric128BitHexKeyUTF8({+ ciphertext: secretBlindIndexDatum.encryptedSaltCiphertext,+ iv: secretBlindIndexDatum.saltIV,+ tag: secretBlindIndexDatum.saltTag,+ key: encryptionKey+ });++ const {+ ciphertext: encryptedSaltCiphertext,+ iv: saltIV,+ tag: saltTag+ } = client.encryptSymmetric(salt, rootEncryptionKey);++ return ({+ updateOne: {+ filter: {+ _id: secretBlindIndexDatum._id+ },+ update: {+ encryptedSaltCiphertext,+ saltIV,+ saltTag,+ algorithm: ALGORITHM_AES_256_GCM,+ keyEncoding: ENCODING_SCHEME_BASE64+ }+ }+ })+ })+ );++ await SecretBlindIndexData.bulkWrite(operationsSecretBlindIndexData);+ }+}diff --cc backend/src/utils/setup/validateConfig.tsindex b71e6e4d98,0000000000..5e7aa1e5b2mode 100644,000000..100644--- a/backend/src/utils/setup/validateConfig.ts+++ b/backend/src/utils/setup/validateConfig.ts@@@ -1,69 -1,0 +1,61 @@@+import {+ getEncryptionKey,+ getRootEncryptionKey+} from '../../config';+import {+ InternalServerError+} from '../../utils/errors';++/**+ * Validate ENCRYPTION_KEY and ROOT_ENCRYPTION_KEY. Specifically:+ * - ENCRYPTION_KEY is a hex, 128-bit string+ * - ROOT_ENCRYPTION_KEY is a base64, 128-bit string+ * - Either ENCRYPTION_KEY or ROOT_ENCRYPTION_KEY are present+ *+ * - Encrypted data is consistent with the passed in encryption keys+ *+ * NOTE 1: ENCRYPTION_KEY is being transitioned to ROOT_ENCRYPTION_KEY+ * NOTE 2: In the future, we will have a superior validation function+ * built into the SDK.+ */+export const validateEncryptionKeysConfig = async () => {+ const encryptionKey = await getEncryptionKey();+ const rootEncryptionKey = await getRootEncryptionKey();+- // TODO: handle case where either of keys can be empty strings- // and it would actually count as being defined for encryption- // within the application-- // console.log('validateEncryptionKeysConfig');- // console.log('encryptionKey: ', encryptionKey);- // console.log('rootEncryptionKey: ', rootEncryptionKey);-+ if (+ (encryptionKey === undefined || encryptionKey === "") &&+ (rootEncryptionKey === undefined || rootEncryptionKey === "")+ ) throw InternalServerError({+ message: "Failed to find required root encryption key environment variable. Please make sure that you're passing in a ROOT_ENCRYPTION_KEY environment variable."+ });++ if (encryptionKey && encryptionKey !== '') {+ // validate [encryptionKey]++ const keyBuffer = Buffer.from(encryptionKey, 'hex');+ const decoded = keyBuffer.toString('hex');++ if (decoded !== encryptionKey) throw InternalServerError({+ message: 'Failed to validate that the encryption key is correctly encoded in hex.'+ });++ if (keyBuffer.length !== 16) throw InternalServerError({+ message: 'Failed to validate that the encryption key is a 128-bit hex string.'+ });+ }++ if (rootEncryptionKey && rootEncryptionKey !== '') {+ // validate [rootEncryptionKey]++ const keyBuffer = Buffer.from(rootEncryptionKey, 'base64')+ const decoded = keyBuffer.toString('base64');++ if (decoded !== rootEncryptionKey) throw InternalServerError({+ message: 'Failed to validate that the root encryption key is correctly encoded in base64'+ });++ if (keyBuffer.length !== 32) throw InternalServerError({+ message: 'Failed to validate that the encryption key is a 256-bit base64 string'+ });+ }+}diff --cc backend/src/validation/workspace.tsindex 60d13b1297,0000000000..1cbdca4204mode 100644,000000..100644--- a/backend/src/validation/workspace.ts+++ b/backend/src/validation/workspace.ts@@@ -1,124 -1,0 +1,124 @@@+import { Types } from 'mongoose';+import {+ IUser,+ IServiceAccount,+ IServiceTokenData,+ Workspace,+ User,+ ServiceAccount,+ ServiceTokenData,+ SecretBlindIndexData+} from '../models';+import { validateServiceAccountClientForWorkspace } from './serviceAccount';+import { validateUserClientForWorkspace } from './user';+import { validateServiceTokenDataClientForWorkspace } from './serviceTokenData';+import {+ UnauthorizedRequestError,+ WorkspaceNotFoundError+} from '../utils/errors';+import {+ AUTH_MODE_JWT,+ AUTH_MODE_SERVICE_ACCOUNT,+ AUTH_MODE_SERVICE_TOKEN,+ AUTH_MODE_API_KEY+} from '../variables';++/**+ * Validate authenticated clients for workspace with id [workspaceId] based+ * on any known permissions.+ * @param {Object} obj+ * @param {Object} obj.authData - authenticated client details+ * @param {Types.ObjectId} obj.workspaceId - id of workspace to validate against+ * @param {String} obj.environment - (optional) environment in workspace to validate against+ * @param {Array<'admin' | 'member'>} obj.acceptedRoles - accepted workspace roles+ * @param {String[]} obj.requiredPermissions - required permissions as part of the endpoint+ */+export const validateClientForWorkspace = async ({+ authData,+ workspaceId,+ environment,+ acceptedRoles,+ requiredPermissions,+ requireBlindIndicesEnabled+}: {+ authData: {+ authMode: string;+ authPayload: IUser | IServiceAccount | IServiceTokenData;+ };+ workspaceId: Types.ObjectId;+ environment?: string;+ acceptedRoles: Array<'admin' | 'member'>;+ requiredPermissions?: string[];+ requireBlindIndicesEnabled: boolean;+}) => {++ const workspace = await Workspace.findById(workspaceId);++ if (!workspace) throw WorkspaceNotFoundError({+ message: 'Failed to find workspace'+ });++ if (requireBlindIndicesEnabled) {+ // case: blind indices are not enabled for secrets in this workspace+ // (i.e. workspace was created before blind indices were introduced+ // and no admin has enabled it)++ const secretBlindIndexData = await SecretBlindIndexData.exists({+ workspace: new Types.ObjectId(workspaceId)+ });++ if (!secretBlindIndexData) throw UnauthorizedRequestError({+ message: 'Failed workspace authorization due to blind indices not being enabled'+ });+ }++ if (authData.authMode === AUTH_MODE_JWT && authData.authPayload instanceof User) {+ const membership = await validateUserClientForWorkspace({+ user: authData.authPayload,+ workspaceId,+ environment,+ acceptedRoles,+ requiredPermissions+ });+- return ({ membership });++ return ({ membership, workspace });+ }++ if (authData.authMode === AUTH_MODE_SERVICE_ACCOUNT && authData.authPayload instanceof ServiceAccount) {+ await validateServiceAccountClientForWorkspace({+ serviceAccount: authData.authPayload,+ workspaceId,+ environment,+ requiredPermissions+ });++ return {};+ }++ if (authData.authMode === AUTH_MODE_SERVICE_TOKEN && authData.authPayload instanceof ServiceTokenData) {+ await validateServiceTokenDataClientForWorkspace({+ serviceTokenData: authData.authPayload,+ workspaceId,+ environment,+ requiredPermissions+ });++ return {};+ }++ if (authData.authMode === AUTH_MODE_API_KEY && authData.authPayload instanceof User) {+ const membership = await validateUserClientForWorkspace({+ user: authData.authPayload,+ workspaceId,+ environment,+ acceptedRoles,+ requiredPermissions+ });+- return ({ membership });++ return ({ membership, workspace });+ }++ throw UnauthorizedRequestError({+ message: 'Failed client authorization for workspace'+ });+}