Skip to content

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

Merge branch 'main' of github.com:reginaldbondoc/infisical

Reginald Bondocbd207dc65f2a
diff --cc backend/package-lock.json
index 82301465c9,b5da475f0d..852f1c0f3b
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@@ -51,18 -48,11 +51,15 @@@
"@types/swagger-ui-express": "^4.1.3",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
+ "cross-env": "^7.0.3",
"eslint": "^8.26.0",
- "eslint-config-prettier": "^8.5.0",
- "eslint-plugin-prettier": "^4.2.1",
"install": "^0.13.0",
"jest": "^29.3.1",
+ "jest-junit": "^15.0.0",
"nodemon": "^2.0.19",
"npm": "^8.19.3",
- "prettier": "^2.7.1",
+ "supertest": "^6.3.3",
+ "ts-jest": "^29.0.3",
"ts-node": "^10.9.1"
}
},
diff --cc backend/package.json
index 215012a79a,bad2908d9a..e45ed85dc5
--- a/backend/package.json
+++ b/backend/package.json
@@@ -31,17 -31,13 +31,17 @@@
"version": "1.0.0",
"main": "src/index.js",
"scripts": {
+ "prepare": "cd .. && npm install",
"start": "npm run build && node build/index.js",
"dev": "nodemon",
- "build": "rimraf ./build && tsc && cp -R ./src/templates ./src/json ./build",
+ "build": "rimraf ./build && tsc && cp -R ./src/templates ./build",
"lint": "eslint . --ext .ts",
"lint-and-fix": "eslint . --ext .ts --fix",
- "prettier-format": "prettier --config .prettierrc 'src/**/*.ts' --write",
- "lint-staged": "lint-staged"
+ "lint-staged": "lint-staged",
+ "pretest": "docker compose -f test-resources/docker-compose.test.yml up -d",
+ "test": "cross-env NODE_ENV=test jest --testTimeout=10000 --detectOpenHandles",
+ "test:ci": "npm test -- --watchAll=false --ci --reporters=default --reporters=jest-junit --coverage --testLocationInResults",
+ "posttest": "docker compose -f test-resources/docker-compose.test.yml down"
},
"repository": {
"type": "git",
@@@ -69,37 -62,11 +69,34 @@@
"@types/swagger-ui-express": "^4.1.3",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
+ "cross-env": "^7.0.3",
"eslint": "^8.26.0",
- "eslint-config-prettier": "^8.5.0",
- "eslint-plugin-prettier": "^4.2.1",
"install": "^0.13.0",
"jest": "^29.3.1",
+ "jest-junit": "^15.0.0",
"nodemon": "^2.0.19",
"npm": "^8.19.3",
- "prettier": "^2.7.1",
+ "supertest": "^6.3.3",
+ "ts-jest": "^29.0.3",
"ts-node": "^10.9.1"
+ },
+ "jest": {
+ "preset": "ts-jest",
+ "testEnvironment": "node",
+ "coveragePathIgnorePatterns": [
+ "/node_modules/"
+ ],
+ "setupFiles": [
+ "<rootDir>/test-resources/env-vars.js"
+ ]
+ },
+ "jest-junit": {
+ "outputDirectory": "reports",
+ "outputName": "jest-junit.xml",
+ "ancestorSeparator": " › ",
+ "uniqueOutputName": "false",
+ "suiteNameTemplate": "{filepath}",
+ "classNameTemplate": "{classname}",
+ "titleTemplate": "{title}"
}
}
diff --cc backend/src/app.ts
index 1d00c03d98,0000000000..fa11b5f1c0
mode 100644,000000..100644
--- a/backend/src/app.ts
+++ b/backend/src/app.ts
@@@ -1,72 -1,0 +1,74 @@@
+/* eslint-disable no-console */
+
+import express from 'express';
+import helmet from 'helmet';
+import cors from 'cors';
+import cookieParser from 'cookie-parser';
+import dotenv from 'dotenv';
+
+dotenv.config();
+import { PORT, NODE_ENV, SITE_URL } from './config';
+import { apiLimiter } from './helpers/rateLimiter';
+
+import {
+ 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
+} from './routes';
+
+export const app = express();
+
+app.enable('trust proxy');
+app.use(express.json());
+app.use(cookieParser());
+app.use(
+ cors({
+ credentials: true,
+ origin: SITE_URL
+ })
+);
+
+if (NODE_ENV === 'production') {
+ // enable app-wide rate-limiting + helmet security
+ // in production
+ app.disable('x-powered-by');
+ app.use(apiLimiter);
+ app.use(helmet());
+}
+
+// routers
+app.use('/api/v1/signup', signupRouter);
+app.use('/api/v1/auth', authRouter);
++app.use('/api/v1/bot', botRouter);
+app.use('/api/v1/user', userRouter);
+app.use('/api/v1/user-action', userActionRouter);
+app.use('/api/v1/organization', organizationRouter);
+app.use('/api/v1/workspace', workspaceRouter);
+app.use('/api/v1/membership-org', membershipOrgRouter);
+app.use('/api/v1/membership', membershipRouter);
+app.use('/api/v1/key', keyRouter);
+app.use('/api/v1/invite-org', inviteOrgRouter);
+app.use('/api/v1/secret', secretRouter);
+app.use('/api/v1/service-token', serviceTokenRouter);
+app.use('/api/v1/password', passwordRouter);
+app.use('/api/v1/stripe', stripeRouter);
+app.use('/api/v1/integration', integrationRouter);
+app.use('/api/v1/integration-auth', integrationAuthRouter);
+
+export const server = app.listen(PORT, () => {
+ console.log(`Listening on PORT ${[PORT]}`);
+});
diff --cc backend/src/helpers/bot.ts
index 0000000000,3285ccd6f1..abaf73af4d
mode 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/helpers/integration.ts
index e69de29bb2,9aaff9741a..800c90bf49
--- a/backend/src/helpers/integration.ts
+++ b/backend/src/helpers/integration.ts
@@@ -1,0 -1,350 +1,350 @@@
+ import * as Sentry from '@sentry/node';
+ import {
+ Bot,
+ Integration,
+ IIntegration,
+ IntegrationAuth,
+ IIntegrationAuth
+ } from '../models';
+ import { exchangeCode, exchangeRefresh, syncSecrets } from '../integrations';
+ import { BotService, IntegrationService } from '../services';
+ import {
+ ENV_DEV,
+ EVENT_PUSH_SECRETS,
+ INTEGRATION_VERCEL,
+ INTEGRATION_NETLIFY
+ } from '../variables';
+
+ interface Update {
+ workspace: string;
+ integration: string;
+ teamId?: string;
+ accountId?: string;
+ }
+
+ /**
+ * Perform OAuth2 code-token exchange for workspace with id [workspaceId] and integration
+ * named [integration]
+ * - Store integration access and refresh tokens returned from the OAuth2 code-token exchange
+ * - Add placeholder inactive integration
+ * - Create bot sequence for integration
+ * @param {Object} obj
+ * @param {String} obj.workspaceId - id of workspace
+ * @param {String} obj.integration - name of integration
+ * @param {String} obj.code - code
+ */
+ const handleOAuthExchangeHelper = async ({
+ workspaceId,
+ integration,
+ code
+ }: {
+ workspaceId: string;
+ integration: string;
+ code: string;
+ }) => {
+ let action;
+ let integrationAuth;
+ try {
+ const bot = await Bot.findOne({
+ workspace: workspaceId,
+ isActive: true
+ });
+
+ if (!bot) throw new Error('Bot must be enabled for OAuth2 code-token exchange');
+
+ // exchange code for access and refresh tokens
- let res = await exchangeCode({
++ const res = await exchangeCode({
+ integration,
+ code
+ });
+
- let update: Update = {
++ const update: Update = {
+ workspace: workspaceId,
+ integration
+ }
+
+ switch (integration) {
+ case INTEGRATION_VERCEL:
+ update.teamId = res.teamId;
+ break;
+ case INTEGRATION_NETLIFY:
+ update.accountId = res.accountId;
+ break;
+ }
+
+ integrationAuth = await IntegrationAuth.findOneAndUpdate({
+ workspace: workspaceId,
+ integration
+ }, update, {
+ new: true,
+ upsert: true
+ });
+
+ if (res.refreshToken) {
+ // case: refresh token returned from exchange
+ // set integration auth refresh token
+ await setIntegrationAuthRefreshHelper({
+ integrationAuthId: integrationAuth._id.toString(),
+ refreshToken: res.refreshToken
+ });
+ }
+
+ if (res.accessToken) {
+ // case: access token returned from exchange
+ // set integration auth access token
+ await setIntegrationAuthAccessHelper({
+ integrationAuthId: integrationAuth._id.toString(),
+ accessToken: res.accessToken,
+ accessExpiresAt: res.accessExpiresAt
+ });
+ }
+
+ // initialize new integration after exchange
+ await new Integration({
+ workspace: workspaceId,
+ environment: ENV_DEV,
+ isActive: false,
+ app: null,
+ integration,
+ integrationAuth: integrationAuth._id
+ }).save();
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to handle OAuth2 code-token exchange')
+ }
+ }
+ /**
+ * Sync/push environment variables in workspace with id [workspaceId] to
+ * all active integrations for that workspace
+ * @param {Object} obj
+ * @param {Object} obj.workspaceId - id of workspace
+ */
+ const syncIntegrationsHelper = async ({
+ workspaceId
+ }: {
+ workspaceId: string;
+ }) => {
+ let integrations;
+ try {
+
+ integrations = await Integration.find({
+ workspace: workspaceId,
+ isActive: true,
+ app: { $ne: null }
+ });
+
+ // for each workspace integration, sync/push secrets
+ // to that integration
+ for await (const integration of integrations) {
+ // get workspace, environment (shared) secrets
+ const secrets = await BotService.getSecrets({
+ workspaceId: integration.workspace.toString(),
+ environment: integration.environment
+ });
+
+ const integrationAuth = await IntegrationAuth.findById(integration.integrationAuth);
+ if (!integrationAuth) throw new Error('Failed to find integration auth');
+
+ // get integration auth access token
+ const accessToken = await getIntegrationAuthAccessHelper({
+ integrationAuthId: integration.integrationAuth.toString()
+ });
+
+ // sync secrets to integration
+ await syncSecrets({
+ integration,
+ integrationAuth,
+ secrets,
+ accessToken
+ });
+ }
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to sync secrets to integrations');
+ }
+ }
+
+ /**
+ * Return decrypted refresh token using the bot's copy
+ * of the workspace key for workspace belonging to integration auth
+ * with id [integrationAuthId]
+ * @param {Object} obj
+ * @param {String} obj.integrationAuthId - id of integration auth
+ * @param {String} refreshToken - decrypted refresh token
+ */
+ const getIntegrationAuthRefreshHelper = async ({ integrationAuthId }: { integrationAuthId: string }) => {
+ let refreshToken;
+ try {
+ const integrationAuth = await IntegrationAuth
+ .findById(integrationAuthId)
+ .select('+refreshCiphertext +refreshIV +refreshTag');
+
+ if (!integrationAuth) throw new Error('Failed to find integration auth');
+
+ refreshToken = await BotService.decryptSymmetric({
+ workspaceId: integrationAuth.workspace.toString(),
+ ciphertext: integrationAuth.refreshCiphertext as string,
+ iv: integrationAuth.refreshIV as string,
+ tag: integrationAuth.refreshTag as string
+ });
+
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to get integration refresh token');
+ }
+
+ return refreshToken;
+ }
+
+ /**
+ * Return decrypted access token using the bot's copy
+ * of the workspace key for workspace belonging to integration auth
+ * with id [integrationAuthId]
+ * @param {Object} obj
+ * @param {String} obj.integrationAuthId - id of integration auth
+ * @returns {String} accessToken - decrypted access token
+ */
+ const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrationAuthId: string }) => {
+ let accessToken;
+ try {
+ const integrationAuth = await IntegrationAuth
+ .findById(integrationAuthId)
+ .select('workspace integration +accessCiphertext +accessIV +accessTag +accessExpiresAt + refreshCiphertext');
+
+ if (!integrationAuth) throw new Error('Failed to find integration auth');
+
+ accessToken = await BotService.decryptSymmetric({
+ workspaceId: integrationAuth.workspace.toString(),
+ ciphertext: integrationAuth.accessCiphertext as string,
+ iv: integrationAuth.accessIV as string,
+ tag: integrationAuth.accessTag as string
+ });
+
+ if (integrationAuth?.accessExpiresAt && integrationAuth?.refreshCiphertext) {
+ // there is a access token expiration date
+ // and refresh token to exchange with the OAuth2 server
+
+ if (integrationAuth.accessExpiresAt < new Date()) {
+ // access token is expired
+ const refreshToken = await getIntegrationAuthRefreshHelper({ integrationAuthId });
+ accessToken = await exchangeRefresh({
+ integration: integrationAuth.integration,
+ refreshToken
+ });
+ }
+ }
+
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to get integration access token');
+ }
+
+ return accessToken;
+ }
+
+ /**
+ * Encrypt refresh token [refreshToken] using the bot's copy
+ * of the workspace key for workspace belonging to integration auth
+ * with id [integrationAuthId] and store it
+ * @param {Object} obj
+ * @param {String} obj.integrationAuthId - id of integration auth
+ * @param {String} obj.refreshToken - refresh token
+ */
+ const setIntegrationAuthRefreshHelper = async ({
+ integrationAuthId,
+ refreshToken
+ }: {
+ integrationAuthId: string;
+ refreshToken: string;
+ }) => {
+
+ let integrationAuth;
+ try {
+ integrationAuth = await IntegrationAuth
+ .findById(integrationAuthId);
+
+ if (!integrationAuth) throw new Error('Failed to find integration auth');
+
+ const obj = await BotService.encryptSymmetric({
+ workspaceId: integrationAuth.workspace.toString(),
+ plaintext: refreshToken
+ });
+
+ integrationAuth = await IntegrationAuth.findOneAndUpdate({
+ _id: integrationAuthId
+ }, {
+ refreshCiphertext: obj.ciphertext,
+ refreshIV: obj.iv,
+ refreshTag: obj.tag
+ }, {
+ new: true
+ });
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to set integration auth refresh token');
+ }
+
+ return integrationAuth;
+ }
+
+ /**
+ * Encrypt access token [accessToken] using the bot's copy
+ * of the workspace key for workspace belonging to integration auth
+ * with id [integrationAuthId] and store it along with [accessExpiresAt]
+ * @param {Object} obj
+ * @param {String} obj.integrationAuthId - id of integration auth
+ * @param {String} obj.accessToken - access token
+ * @param {Date} obj.accessExpiresAt - expiration date of access token
+ */
+ const setIntegrationAuthAccessHelper = async ({
+ integrationAuthId,
+ accessToken,
+ accessExpiresAt
+ }: {
+ integrationAuthId: string;
+ accessToken: string;
+ accessExpiresAt: Date;
+ }) => {
+ let integrationAuth;
+ try {
+ integrationAuth = await IntegrationAuth.findById(integrationAuthId);
+
+ if (!integrationAuth) throw new Error('Failed to find integration auth');
+
+ const obj = await BotService.encryptSymmetric({
+ workspaceId: integrationAuth.workspace.toString(),
+ plaintext: accessToken
+ });
+
+ integrationAuth = await IntegrationAuth.findOneAndUpdate({
+ _id: integrationAuthId
+ }, {
+ accessCiphertext: obj.ciphertext,
+ accessIV: obj.iv,
+ accessTag: obj.tag,
+ accessExpiresAt
+ }, {
+ new: true
+ });
+ } catch (err) {
+ Sentry.setUser(null);
+ Sentry.captureException(err);
+ throw new Error('Failed to save integration auth access token');
+ }
+
+ return integrationAuth;
+ }
+
+ export {
+ handleOAuthExchangeHelper,
+ syncIntegrationsHelper,
+ getIntegrationAuthRefreshHelper,
+ getIntegrationAuthAccessHelper,
+ setIntegrationAuthRefreshHelper,
+ setIntegrationAuthAccessHelper
+ }
diff --cc backend/src/integrations/exchange.ts
index 0000000000,26e6521a12..265036ee0d
mode 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.ts
index 0000000000,833e6c88a3..43a1582b72
mode 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 frontend/components/basic/dialog/ActivateBotDialog.js
index 0000000000,600b61c20f..79d8cd6934
mode 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.js
index 0000000000,dca8d672bc..375dc88042
mode 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;