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 Dang6e50adb9ff97
diff --cc backend/src/helpers/bot.tsindex 0000000000,3285ccd6f1..abaf73af4dmode 000000,100644..100644--- a/backend/src/helpers/bot.ts+++ b/backend/src/helpers/bot.ts@@@ -1,0 -1,230 +1,230 @@@+ import * as Sentry from '@sentry/node';+ import {+ Bot,+ BotKey,+ Secret,+ ISecret,+ IUser+ } from '../models';+ import {+ generateKeyPair,+ encryptSymmetric,+ decryptSymmetric,+ decryptAsymmetric+ } from '../utils/crypto';+ import { decryptSecrets } from '../helpers/secret';+ import { ENCRYPTION_KEY } from '../config';+ import { SECRET_SHARED } from '../variables';++ /**+ * Create an inactive bot with name [name] for workspace with id [workspaceId]+ * @param {Object} obj+ * @param {String} obj.name - name of bot+ * @param {String} obj.workspaceId - id of workspace that bot belongs to+ */+ const createBot = async ({+ name,+ workspaceId,+ }: {+ name: string;+ workspaceId: string;+ }) => {+ let bot;+ try {+ const { publicKey, privateKey } = generateKeyPair();+ const { ciphertext, iv, tag } = encryptSymmetric({+ plaintext: privateKey,+ key: ENCRYPTION_KEY+ });++ bot = await new Bot({+ name,+ workspace: workspaceId,+ isActive: false,+ publicKey,+ encryptedPrivateKey: ciphertext,+ iv,+ tag+ }).save();+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to create bot');+ }++ return bot;+ }++ /**+ * Return decrypted secrets for workspace with id [workspaceId]+ * and [environment] using bot+ * @param {Object} obj+ * @param {String} obj.workspaceId - id of workspace+ * @param {String} obj.environment - environment+ */+ const getSecretsHelper = async ({+ workspaceId,+ environment+ }: {+ workspaceId: string;+ environment: string;+ }) => {- let content = {} as any;++ const content = {} as any;+ try {+ const key = await getKey({ workspaceId });+ const secrets = await Secret.find({+ workspaceId,+ environment,+ type: SECRET_SHARED+ });++ secrets.forEach((secret: ISecret) => {+ const secretKey = decryptSymmetric({+ ciphertext: secret.secretKeyCiphertext,+ iv: secret.secretKeyIV,+ tag: secret.secretKeyTag,+ key+ });++ const secretValue = decryptSymmetric({+ ciphertext: secret.secretValueCiphertext,+ iv: secret.secretValueIV,+ tag: secret.secretValueTag,+ key+ });++ content[secretKey] = secretValue;+ });+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to get secrets');+ }++ return content;+ }++ /**+ * Return bot's copy of the workspace key for workspace+ * with id [workspaceId]+ * @param {Object} obj+ * @param {String} obj.workspaceId - id of workspace+ * @returns {String} key - decrypted workspace key+ */+ const getKey = async ({ workspaceId }: { workspaceId: string }) => {+ let key;+ try {+ const botKey = await BotKey.findOne({+ workspace: workspaceId+ }).populate<{ sender: IUser }>('sender', 'publicKey');++ if (!botKey) throw new Error('Failed to find bot key');++ const bot = await Bot.findOne({+ workspace: workspaceId+ }).select('+encryptedPrivateKey +iv +tag');++ if (!bot) throw new Error('Failed to find bot');+ if (!bot.isActive) throw new Error('Bot is not active');++ const privateKeyBot = decryptSymmetric({+ ciphertext: bot.encryptedPrivateKey,+ iv: bot.iv,+ tag: bot.tag,+ key: ENCRYPTION_KEY+ });++ key = decryptAsymmetric({+ ciphertext: botKey.encryptedKey,+ nonce: botKey.nonce,+ publicKey: botKey.sender.publicKey as string,+ privateKey: privateKeyBot+ });+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to get workspace key');+ }++ return key;+ }++ /**+ * Return symmetrically encrypted [plaintext] using the+ * key for workspace with id [workspaceId]+ * @param {Object} obj1+ * @param {String} obj1.workspaceId - id of workspace+ * @param {String} obj1.plaintext - plaintext to encrypt+ */+ const encryptSymmetricHelper = async ({+ workspaceId,+ plaintext+ }: {+ workspaceId: string;+ plaintext: string;+ }) => {++ try {+ const key = await getKey({ workspaceId });+ const { ciphertext, iv, tag } = encryptSymmetric({+ plaintext,+ key+ });++ return ({+ ciphertext,+ iv,+ tag+ });+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to perform symmetric encryption with bot');+ }+ }+ /**+ * Return symmetrically decrypted [ciphertext] using the+ * key for workspace with id [workspaceId]+ * @param {Object} obj+ * @param {String} obj.workspaceId - id of workspace+ * @param {String} obj.ciphertext - ciphertext to decrypt+ * @param {String} obj.iv - iv+ * @param {String} obj.tag - tag+ */+ const decryptSymmetricHelper = async ({+ workspaceId,+ ciphertext,+ iv,+ tag+ }: {+ workspaceId: string;+ ciphertext: string;+ iv: string;+ tag: string;+ }) => {+ let plaintext;+ try {+ const key = await getKey({ workspaceId });+ const plaintext = decryptSymmetric({+ ciphertext,+ iv,+ tag,+ key+ });++ return plaintext;+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to perform symmetric decryption with bot');+ }++ return plaintext;+ }++ export {+ createBot,+ getSecretsHelper,+ encryptSymmetricHelper,+ decryptSymmetricHelper+ }diff --cc backend/src/index.tsindex fd4f867af4,6abc654206..7e1d1411f6--- a/backend/src/index.ts+++ b/backend/src/index.ts@@@ -23,23 -23,23 +23,24 @@@ Sentry.init(});import {- signup as signupRouter,- auth as authRouter,- organization as organizationRouter,- workspace as workspaceRouter,- membershipOrg as membershipOrgRouter,- membership as membershipRouter,- key as keyRouter,- inviteOrg as inviteOrgRouter,- user as userRouter,- userAction as userActionRouter,- secret as secretRouter,- serviceToken as serviceTokenRouter,- password as passwordRouter,- stripe as stripeRouter,- integration as integrationRouter,- integrationAuth as integrationAuthRouter,- log as logRouter+ signup as signupRouter,+ auth as authRouter,+ bot as botRouter,+ organization as organizationRouter,+ workspace as workspaceRouter,+ membershipOrg as membershipOrgRouter,+ membership as membershipRouter,+ key as keyRouter,+ inviteOrg as inviteOrgRouter,+ user as userRouter,+ userAction as userActionRouter,+ secret as secretRouter,+ serviceToken as serviceTokenRouter,+ password as passwordRouter,+ stripe as stripeRouter,+ integration as integrationRouter,- integrationAuth as integrationAuthRouter++ integrationAuth as integrationAuthRouter,++ log as logRouter} from './routes';const connectWithRetry = () => {diff --cc backend/src/integrations/exchange.tsindex 0000000000,26e6521a12..265036ee0dmode 000000,100644..100644--- a/backend/src/integrations/exchange.ts+++ b/backend/src/integrations/exchange.ts@@@ -1,0 -1,241 +1,241 @@@+ import axios from 'axios';+ import * as Sentry from '@sentry/node';+ import {+ INTEGRATION_HEROKU,+ INTEGRATION_VERCEL,+ INTEGRATION_NETLIFY,+ INTEGRATION_HEROKU_TOKEN_URL,+ INTEGRATION_VERCEL_TOKEN_URL,+ INTEGRATION_NETLIFY_TOKEN_URL,+ ACTION_PUSH_TO_HEROKU+ } from '../variables';+ import {+ SITE_URL,+ CLIENT_SECRET_HEROKU,+ CLIENT_ID_VERCEL,+ CLIENT_ID_NETLIFY,+ CLIENT_SECRET_VERCEL,+ CLIENT_SECRET_NETLIFY+ } from '../config';++ interface ExchangeCodeHerokuResponse {+ token_type: string;+ access_token: string;+ expires_in: number;+ refresh_token: string;+ user_id: string;+ session_nonce?: string;+ }++ interface ExchangeCodeVercelResponse {+ token_type: string;+ access_token: string;+ installation_id: string;+ user_id: string;+ team_id?: string;+ }++ interface ExchangeCodeNetlifyResponse {+ access_token: string;+ token_type: string;+ refresh_token: string;+ scope: string;+ created_at: number;+ }++ /**+ * Return [accessToken], [accessExpiresAt], and [refreshToken] for OAuth2+ * code-token exchange for integration named [integration]+ * @param {Object} obj1+ * @param {String} obj1.integration - name of integration+ * @param {String} obj1.code - code for code-token exchange+ * @returns {Object} obj+ * @returns {String} obj.accessToken - access token for integration+ * @returns {String} obj.refreshToken - refresh token for integration+ * @returns {Date} obj.accessExpiresAt - date of expiration for access token+ * @returns {String} obj.action - integration action for bot sequence+ */+ const exchangeCode = async ({+ integration,+ code+ }: {+ integration: string;+ code: string;+ }) => {+ let obj = {} as any;++ try {+ switch (integration) {+ case INTEGRATION_HEROKU:+ obj = await exchangeCodeHeroku({+ code+ });+ break;+ case INTEGRATION_VERCEL:+ obj = await exchangeCodeVercel({+ code+ });+ break;+ case INTEGRATION_NETLIFY:+ obj = await exchangeCodeNetlify({+ code+ });+ break;+ }+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed OAuth2 code-token exchange');+ }++ return obj;+ }++ /**+ * Return [accessToken], [accessExpiresAt], and [refreshToken] for Heroku+ * OAuth2 code-token exchange+ * @param {Object} obj1+ * @param {Object} obj1.code - code for code-token exchange+ * @returns {Object} obj2+ * @returns {String} obj2.accessToken - access token for Heroku API+ * @returns {String} obj2.refreshToken - refresh token for Heroku API+ * @returns {Date} obj2.accessExpiresAt - date of expiration for access token+ */+ const exchangeCodeHeroku = async ({+ code+ }: {+ code: string;+ }) => {+ let res: ExchangeCodeHerokuResponse;- let accessExpiresAt = new Date();++ const accessExpiresAt = new Date();+ try {+ res = (await axios.post(+ INTEGRATION_HEROKU_TOKEN_URL,+ new URLSearchParams({+ grant_type: 'authorization_code',+ code: code,+ client_secret: CLIENT_SECRET_HEROKU+ } as any)+ )).data;++ accessExpiresAt.setSeconds(+ accessExpiresAt.getSeconds() + res.expires_in+ );+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed OAuth2 code-token exchange with Heroku');+ }++ return ({+ accessToken: res.access_token,+ refreshToken: res.refresh_token,+ accessExpiresAt+ });+ }++ /**+ * Return [accessToken], [accessExpiresAt], and [refreshToken] for Vercel+ * code-token exchange+ * @param {Object} obj1+ * @param {Object} obj1.code - code for code-token exchange+ * @returns {Object} obj2+ * @returns {String} obj2.accessToken - access token for Heroku API+ * @returns {String} obj2.refreshToken - refresh token for Heroku API+ * @returns {Date} obj2.accessExpiresAt - date of expiration for access token+ */+ const exchangeCodeVercel = async ({+ code+ }: {+ code: string;+ }) => {+ let res: ExchangeCodeVercelResponse;+ try {+ res = (await axios.post(+ INTEGRATION_VERCEL_TOKEN_URL,+ new URLSearchParams({+ code: code,+ client_id: CLIENT_ID_VERCEL,+ client_secret: CLIENT_SECRET_VERCEL,+ redirect_uri: `${SITE_URL}/vercel`+ } as any)+ )).data;+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed OAuth2 code-token exchange with Vercel');+ }++ return ({+ accessToken: res.access_token,+ refreshToken: null,+ accessExpiresAt: null,+ teamId: res.team_id+ });+ }++ /**+ * Return [accessToken], [accessExpiresAt], and [refreshToken] for Vercel+ * code-token exchange+ * @param {Object} obj1+ * @param {Object} obj1.code - code for code-token exchange+ * @returns {Object} obj2+ * @returns {String} obj2.accessToken - access token for Heroku API+ * @returns {String} obj2.refreshToken - refresh token for Heroku API+ * @returns {Date} obj2.accessExpiresAt - date of expiration for access token+ */+ const exchangeCodeNetlify = async ({+ code+ }: {+ code: string;+ }) => {+ let res: ExchangeCodeNetlifyResponse;+ let accountId;+ try {+ res = (await axios.post(+ INTEGRATION_NETLIFY_TOKEN_URL,+ new URLSearchParams({+ grant_type: 'authorization_code',+ code: code,+ client_id: CLIENT_ID_NETLIFY,+ client_secret: CLIENT_SECRET_NETLIFY,+ redirect_uri: `${SITE_URL}/netlify`+ } as any)+ )).data;++ const res2 = await axios.get(+ 'https://api.netlify.com/api/v1/sites',+ {+ headers: {+ Authorization: `Bearer ${res.access_token}`+ }+ }+ );++ const res3 = (await axios.get(+ 'https://api.netlify.com/api/v1/accounts',+ {+ headers: {+ Authorization: `Bearer ${res.access_token}`+ }+ }+ )).data;++ accountId = res3[0].id;++ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed OAuth2 code-token exchange with Netlify');+ }++ return ({+ accessToken: res.access_token,+ refreshToken: res.refresh_token,+ accountId+ });+ }++ export {+ exchangeCode+ }diff --cc backend/src/integrations/revoke.tsindex 0000000000,833e6c88a3..43a1582b72mode 000000,100644..100644--- a/backend/src/integrations/revoke.ts+++ b/backend/src/integrations/revoke.ts@@@ -1,0 -1,50 +1,50 @@@+ import axios from 'axios';+ import * as Sentry from '@sentry/node';+ import {+ IIntegrationAuth,+ IntegrationAuth,+ Integration+ } from '../models';+ import {+ INTEGRATION_HEROKU,+ INTEGRATION_VERCEL,+ INTEGRATION_NETLIFY+ } from '../variables';++ const revokeAccess = async ({+ integrationAuth,+ accessToken+ }: {+ integrationAuth: IIntegrationAuth,- accessToken: String++ accessToken: string+ }) => {+ try {+ // add any integration-specific revocation logic+ switch (integrationAuth.integration) {+ case INTEGRATION_HEROKU:+ break;+ case INTEGRATION_VERCEL:+ break;+ case INTEGRATION_NETLIFY:+ break;+ }++ const deletedIntegrationAuth = await IntegrationAuth.findOneAndDelete({+ _id: integrationAuth._id+ });++ if (deletedIntegrationAuth) {+ await Integration.deleteMany({+ integrationAuth: deletedIntegrationAuth._id+ });+ }+ } catch (err) {+ Sentry.setUser(null);+ Sentry.captureException(err);+ throw new Error('Failed to delete integration authorization');+ }+ }++ export {+ revokeAccess+ }diff --cc backend/src/models/log.tsindex e3716ab847,0000000000..81dd9fb52cmode 100644,000000..100644--- a/backend/src/models/log.ts+++ b/backend/src/models/log.ts@@@ -1,56 -1,0 +1,53 @@@+import { Schema, model, Types } from 'mongoose';++export interface ILog {+ _id: Types.ObjectId;+ user?: Types.ObjectId;+ workspace: Types.ObjectId;+ event: string;- source: string;++ payload: {++ numberofSecrets?: number;++ environment?: string;++ },++ channel: string;+ ipAddress?: string;+}+- // TODO: need a way to store payload info for each- // log-- // which secret is being ref etc.-- // user logged in-+const logSchema = new Schema<ILog>(+ {+ user: {+ type: Schema.Types.ObjectId,+ ref: 'User'+ },+ workspace: {+ type: Schema.Types.ObjectId,+ ref: 'Workspace'+ },+ event: { // push, pull+ type: String,+ required: true+ },- payload: { // should this just be a payload attr?++ payload: {+ numberOfSecrets: {+ type: Number+ },+ environment: {+ type: String+ }+ },+ channel: {+ type: String,+ enum: ['web', 'cli', 'auto'],+ required: true+ },+ ipAddress: { // store in bytes?+ type: String+ }+ }, {+ timestamps: true+ }+);++const Log = model<ILog>('Log', logSchema);++export default Log;diff --cc backend/src/models/user.tsindex aa1c5d2394,aa1c5d2394..3b0aa1862d--- a/backend/src/models/user.ts+++ b/backend/src/models/user.ts@@@ -11,7 -11,7 +11,7 @@@ export interface IUsertag?: string;salt?: string;verifier?: string;-- refreshVersion?: Number;++ refreshVersion?: number;}const userSchema = new Schema<IUser>(diff --cc frontend/components/basic/dialog/ActivateBotDialog.jsindex 0000000000,600b61c20f..79d8cd6934mode 000000,100644..100644--- a/frontend/components/basic/dialog/ActivateBotDialog.js+++ b/frontend/components/basic/dialog/ActivateBotDialog.js@@@ -1,0 -1,91 +1,92 @@@+ import { Fragment } from "react";+ import { Dialog, Transition } from "@headlessui/react";-import getLatestFileKey from "../../../pages/api/workspace/getLatestFileKey";+++ import setBotActiveStatus from "../../../pages/api/bot/setBotActiveStatus";++import getLatestFileKey from "../../../pages/api/workspace/getLatestFileKey";+ import {+ decryptAssymmetric,+ encryptAssymmetric+ } from "../../utilities/cryptography/crypto";+ import Button from "../buttons/Button";++ const ActivateBotDialog = ({+ isOpen,+ closeModal,+ selectedIntegrationOption,+ handleBotActivate,+ handleIntegrationOption+ }) => {++ const submit = async () => {+ try {+ // 1. activate bot+ await handleBotActivate();++ // 2. start integration+ await handleIntegrationOption({+ integrationOption: selectedIntegrationOption+ });+ } catch (err) {+ console.log(err);+ }++ closeModal();+ }++ return (+ <div>+ <Transition appear show={isOpen} as={Fragment}>+ <Dialog as="div" className="relative z-10" onClose={closeModal}>+ <Transition.Child+ as={Fragment}+ enter="ease-out duration-300"+ enterFrom="opacity-0"+ enterTo="opacity-100"+ leave="ease-in duration-200"+ leaveFrom="opacity-100"+ leaveTo="opacity-0"+ >+ <div className="fixed inset-0 bg-black bg-opacity-70" />+ </Transition.Child>+ <div className="fixed inset-0 overflow-y-auto">+ <div className="flex min-h-full items-center justify-center p-4 text-center">+ <Transition.Child+ as={Fragment}+ enter="ease-out duration-300"+ enterFrom="opacity-0 scale-95"+ enterTo="opacity-100 scale-100"+ leave="ease-in duration-200"+ leaveFrom="opacity-100 scale-100"+ leaveTo="opacity-0 scale-95"+ >+ <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-md bg-bunker-800 border border-gray-700 p-6 text-left align-middle shadow-xl transition-all">+ <Dialog.Title+ as="h3"+ className="text-lg font-medium leading-6 text-gray-400"+ >+ Grant Infisical access to your secrets+ </Dialog.Title>+ <div className="mt-2 mb-2">+ <p className="text-sm text-gray-500">+ Most cloud integrations require Infisical to be able to decrypt your secrets so they can be forwarded over.+ </p>+ </div>+ <div className="mt-6 max-w-max">+ <Button+ onButtonPressed={submit}+ color="mineshaft"+ text="Grant access"+ size="md"+ />+ </div>+ </Dialog.Panel>+ </Transition.Child>+ </div>+ </div>+ </Dialog>+ </Transition>+ </div>+ );+ }++ export default ActivateBotDialog;diff --cc frontend/components/basic/dialog/IntegrationAccessTokenDialog.jsindex 0000000000,dca8d672bc..375dc88042mode 000000,100644..100644--- a/frontend/components/basic/dialog/IntegrationAccessTokenDialog.js+++ b/frontend/components/basic/dialog/IntegrationAccessTokenDialog.js@@@ -1,0 -1,100 +1,101 @@@+ import { Fragment } from "react";+ import { Dialog, Transition } from "@headlessui/react";-import getLatestFileKey from "../../../pages/api/workspace/getLatestFileKey";+++ import setBotActiveStatus from "../../../pages/api/bot/setBotActiveStatus";++import getLatestFileKey from "../../../pages/api/workspace/getLatestFileKey";+ import {+ decryptAssymmetric,+ encryptAssymmetric+ } from "../../utilities/cryptography/crypto";+ import Button from "../buttons/Button";+ import InputField from "../InputField";++ const IntegrationAccessTokenDialog = ({+ isOpen,+ closeModal,+ selectedIntegrationOption,+ handleBotActivate,+ handleIntegrationOption+ }) => {++ const submit = async () => {+ try {+ // 1. activate bot+ await handleBotActivate();++ // 2. start integration+ await handleIntegrationOption({+ integrationOption: selectedIntegrationOption+ });+ } catch (err) {+ console.log(err);+ }++ closeModal();+ }++ return (+ <div>+ <Transition appear show={isOpen} as={Fragment}>+ <Dialog as="div" className="relative z-10" onClose={closeModal}>+ <Transition.Child+ as={Fragment}+ enter="ease-out duration-300"+ enterFrom="opacity-0"+ enterTo="opacity-100"+ leave="ease-in duration-200"+ leaveFrom="opacity-100"+ leaveTo="opacity-0"+ >+ <div className="fixed inset-0 bg-black bg-opacity-70" />+ </Transition.Child>+ <div className="fixed inset-0 overflow-y-auto">+ <div className="flex min-h-full items-center justify-center p-4 text-center">+ <Transition.Child+ as={Fragment}+ enter="ease-out duration-300"+ enterFrom="opacity-0 scale-95"+ enterTo="opacity-100 scale-100"+ leave="ease-in duration-200"+ leaveFrom="opacity-100 scale-100"+ leaveTo="opacity-0 scale-95"+ >+ <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-md bg-bunker-800 border border-gray-700 p-6 text-left align-middle shadow-xl transition-all">+ <Dialog.Title+ as="h3"+ className="text-lg font-medium leading-6 text-gray-400"+ >+ Grant Infisical access to your secrets+ </Dialog.Title>+ <div className="mt-2 mb-2">+ <p className="text-sm text-gray-500">+ Most cloud integrations require Infisical to be able to decrypt your secrets so they can be forwarded over.+ </p>+ </div>+ <div className="mt-6 max-w-max">+ {/* <Button+ onButtonPressed={submit}+ color="mineshaft"+ text="Grant access"+ size="md"+ /> */}+ <InputField+ label="Access token"+ onChangeHandler={() => {}}+ type="varName"+ value={"Hello"}+ placeholder=""+ isRequired+ />+ </div>+ </Dialog.Panel>+ </Transition.Child>+ </div>+ </div>+ </Dialog>+ </Transition>+ </div>+ );+ }++ export default IntegrationAccessTokenDialog;