Compare commits
163 Commits
Author | SHA1 | Date |
---|---|---|
Maidul Islam | 94f893017b | 7 months ago |
Maidul Islam | 1fea2f1121 | 7 months ago |
Maidul Islam | 7fe8999432 | 7 months ago |
Akhil Mohan | 4aacbed28b | 7 months ago |
Maidul Islam | 9fbf01c19e | 7 months ago |
Maidul Islam | 954bc0c5f1 | 7 months ago |
Akhil Mohan | 4ac3669756 | 7 months ago |
Reza Rahemtola | 6b334b3103 | 7 months ago |
Vladyslav Matsiiako | 3aae1b8432 | 7 months ago |
Vladyslav Matsiiako | e462722ec3 | 7 months ago |
Vladyslav Matsiiako | f58c560fc0 | 7 months ago |
Vladyslav Matsiiako | d035fe1008 | 7 months ago |
Vladyslav Matsiiako | 8be0071413 | 7 months ago |
Akhil Mohan | c3ca992777 | 7 months ago |
Akhil Mohan | 29fa85e499 | 7 months ago |
Akhil Mohan | df7d8e7be9 | 7 months ago |
BlackMagiq | 1de5fd28a9 | 7 months ago |
Tuan Dang | b3cdc4fdd2 | 7 months ago |
Tuan Dang | 5ee79be873 | 7 months ago |
BlackMagiq | cae7e1808d | 7 months ago |
BlackMagiq | 131d5d7207 | 7 months ago |
Tuan Dang | 393cfe8953 | 7 months ago |
BlackMagiq | 5098c0731b | 7 months ago |
Tuan Dang | c9ed5f793a | 7 months ago |
Tuan Dang | 50ce977c55 | 7 months ago |
Tuan Dang | c29a11866e | 7 months ago |
BlackMagiq | b3a468408e | 7 months ago |
Tuan Dang | d1a26766ca | 7 months ago |
Maidul Islam | 73c8e8dc0f | 7 months ago |
BlackMagiq | 32882848ba | 7 months ago |
Tuan Dang | 5fb406884d | 7 months ago |
Tuan Dang | 176d92546c | 7 months ago |
Maidul Islam | 1063c12d25 | 7 months ago |
Maidul Islam | 3402acb05c | 7 months ago |
Akhil Mohan | db7a064961 | 7 months ago |
Akhil Mohan | b521d9fa3a | 7 months ago |
Maidul Islam | 73c7b917ab | 7 months ago |
Maidul Islam | a8470d2133 | 7 months ago |
Maidul Islam | ca8fff320d | 7 months ago |
Tuan Dang | f9c28ab045 | 7 months ago |
Tuan Dang | d4a5eb12e8 | 7 months ago |
BlackMagiq | 86d82737f4 | 7 months ago |
Akhil Mohan | abbeb67b95 | 7 months ago |
Tuan Dang | c0c96d6407 | 7 months ago |
Tuan Dang | 58ff6a43bc | 7 months ago |
Vladyslav Matsiiako | 079a09a3d1 | 7 months ago |
Maidul Islam | a07bd5ad40 | 7 months ago |
Maidul Islam | 9cc99e41b8 | 7 months ago |
Tuan Dang | f256493cb3 | 7 months ago |
Tuan Dang | 7bf2e96ad3 | 7 months ago |
Akhil Mohan | 40238788e5 | 7 months ago |
Akhil Mohan | 75eeda4278 | 7 months ago |
Maidul Islam | c1ea441e3a | 7 months ago |
Akhil Mohan | 8b522a3fb5 | 7 months ago |
Akhil Mohan | c36352f05f | 7 months ago |
Akhil Mohan | 2de898fdbd | 7 months ago |
Akhil Mohan | bc68a00265 | 7 months ago |
Maidul Islam | 1382688e58 | 7 months ago |
Akhil Mohan | 9248f36edb | 7 months ago |
Akhil Mohan | c9c40521b2 | 7 months ago |
Akhil Mohan | 97e4338335 | 7 months ago |
Akhil Mohan | 82e924baff | 7 months ago |
BlackMagiq | 2350219cc9 | 7 months ago |
Tuan Dang | 28d7c72390 | 7 months ago |
Akhil Mohan | e7321e8060 | 7 months ago |
Akhil Mohan | 28a2aebe67 | 7 months ago |
Tuan Dang | 20d4f16d33 | 7 months ago |
Tuan Dang | 7d802b41a8 | 7 months ago |
Tuan Dang | 75992e5566 | 7 months ago |
Tuan Dang | 911aa3fd8a | 7 months ago |
Tuan Dang | 7622a3f518 | 7 months ago |
Tuan Dang | 3b0bd362c9 | 7 months ago |
Tuan Dang | ad4513f926 | 7 months ago |
dependabot[bot] | a2c1a17222 | 7 months ago |
Andrew Atimapre | 279958d54c | 7 months ago |
Akhil Mohan | 1be46b5e57 | 7 months ago |
Maidul Islam | 98d9dd256b | 7 months ago |
Maidul Islam | e5eee14409 | 7 months ago |
Andrew Atimapre | f3c76c79ee | 7 months ago |
Maidul Islam | 5bdb6ad6a1 | 7 months ago |
Akhil Mohan | c6846f8bf1 | 7 months ago |
Maidul Islam | 46f03f33b0 | 7 months ago |
Akhil Mohan | 6280d7eb34 | 7 months ago |
Maidul Islam | 29286d2125 | 7 months ago |
Shreyas Singh | c9f01ce086 | 7 months ago |
Maidul Islam | bc43e109eb | 7 months ago |
Maidul Islam | 238c43a360 | 7 months ago |
Maidul Islam | 040a50d599 | 7 months ago |
Tchoupinax | 8a1a3e9ab9 | 7 months ago |
Tchoupinax | 2585d50b29 | 7 months ago |
Maidul Islam | 4792e752c2 | 7 months ago |
Akhil Mohan | 1d161f6c97 | 7 months ago |
Maidul Islam | 0d94b6deed | 7 months ago |
Maidul Islam | 75428bb750 | 7 months ago |
Maidul Islam | d90680cc91 | 7 months ago |
Maidul Islam | 031c05b82d | 7 months ago |
Tuan Dang | d414353258 | 7 months ago |
BlackMagiq | ffc6dcdeb4 | 7 months ago |
Tuan Dang | dfc74262ee | 7 months ago |
Maidul Islam | 59e46ef1d0 | 7 months ago |
BlackMagiq | 36e4cd71d3 | 7 months ago |
Tuan Dang | d60b3d1598 | 7 months ago |
Tuan Dang | e555a8d313 | 7 months ago |
Tuan Dang | 44ec88acd6 | 7 months ago |
Akhil Mohan | 15504346cd | 7 months ago |
Maidul Islam | 508ed7f7d6 | 7 months ago |
Tuan Dang | 52bcee2785 | 7 months ago |
Akhil Mohan | c097e43a4e | 7 months ago |
Tuan Dang | 65afaa8177 | 7 months ago |
Emmanuel Oloyede | 01cbd4236d | 7 months ago |
snyk-bot | 40a9a15709 | 7 months ago |
Emmanuel Oloyede | abfc69fc75 | 7 months ago |
Maidul Islam | c0592ad904 | 7 months ago |
Maidul Islam | 32970e4990 | 7 months ago |
Ronit Panda | 619bbf2027 | 7 months ago |
Ronit Panda | 1476d06b7e | 7 months ago |
Ronit Panda | fb59b02ab4 | 7 months ago |
BlackMagiq | fc3db93f8b | 7 months ago |
Tuan Dang | 120f1cb5dd | 7 months ago |
Tuan Dang | bb9b060fc0 | 7 months ago |
Maidul Islam | 26605638fa | 7 months ago |
BlackMagiq | 76758732af | 7 months ago |
Tuan Dang | 827d5b25c2 | 7 months ago |
Tuan Dang | b32b19bcc1 | 7 months ago |
Emmanuel Oloyede | 69b9881cbc | 7 months ago |
Maidul Islam | 1084323d6d | 7 months ago |
Maidul Islam | c98c45157a | 7 months ago |
Akhil Mohan | 6009dda2d2 | 8 months ago |
nafees nazik | d4e8162c41 | 8 months ago |
nafees nazik | f6ad641858 | 8 months ago |
nafees nazik | 32acc370a4 | 8 months ago |
Maidul Islam | ba9b1b45ae | 8 months ago |
Tuan Dang | e05b26c727 | 8 months ago |
Maidul Islam | e22557b4bb | 8 months ago |
Maidul Islam | cbbb12c74e | 8 months ago |
Tuan Dang | 60beda604f | 8 months ago |
Tuan Dang | ae50987f91 | 8 months ago |
Maidul Islam | 32977e06f8 | 8 months ago |
nafees nazik | 4d78f4a824 | 8 months ago |
nafees nazik | 47bf483c2e | 8 months ago |
nafees nazik | 40e5ecfd7d | 8 months ago |
nafees nazik | 0fb0744f09 | 8 months ago |
Tuan Dang | 058712e8ec | 8 months ago |
nafees nazik | e13b3f72b1 | 8 months ago |
nafees nazik | a6e02238ad | 8 months ago |
nafees nazik | ebe4f70b51 | 8 months ago |
nafees nazik | c3c7316ec0 | 8 months ago |
nafees nazik | 2cd791a433 | 8 months ago |
vmatsiiako | 912818eec8 | 8 months ago |
Lanre Adelowo | e0dfb2548f | 8 months ago |
Lanre Adelowo | 01997a5187 | 8 months ago |
Ronit Panda | 840eef7bce | 8 months ago |
Ronit Panda | 70b9d435d1 | 8 months ago |
nafees nazik | 9546916aad | 8 months ago |
nafees nazik | 59c861c695 | 8 months ago |
nafees nazik | 2eff06cf06 | 8 months ago |
nafees nazik | a024eecf2c | 8 months ago |
nafees nazik | a2ad9e10b4 | 8 months ago |
nafees nazik | 7fa4e09874 | 9 months ago |
nafees nazik | 20c4e956aa | 9 months ago |
nafees nazik | 4a227d05ce | 9 months ago |
nafees nazik | 6f57ef03d1 | 9 months ago |
nafees nazik | 257b4b0490 | 9 months ago |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,43 @@
|
||||
import ora from "ora";
|
||||
import nodemailer from "nodemailer";
|
||||
import { getSmtpHost, getSmtpPort } from "./config";
|
||||
import { logger } from "./utils/logging";
|
||||
import mongoose from "mongoose";
|
||||
import { redisClient } from "./services/RedisService";
|
||||
|
||||
type BootstrapOpt = {
|
||||
transporter: nodemailer.Transporter;
|
||||
};
|
||||
|
||||
export const bootstrap = async ({ transporter }: BootstrapOpt) => {
|
||||
const spinner = ora().start();
|
||||
spinner.info("Checking configurations...");
|
||||
spinner.info("Testing smtp connection");
|
||||
|
||||
await transporter
|
||||
.verify()
|
||||
.then(async () => {
|
||||
spinner.succeed("SMTP successfully connected");
|
||||
})
|
||||
.catch(async (err) => {
|
||||
spinner.fail(`SMTP - Failed to connect to ${await getSmtpHost()}:${await getSmtpPort()}`);
|
||||
logger.error(err);
|
||||
});
|
||||
|
||||
spinner.info("Testing mongodb connection");
|
||||
if (mongoose.connection.readyState !== mongoose.ConnectionStates.connected) {
|
||||
spinner.fail("Mongo DB - Failed to connect");
|
||||
} else {
|
||||
spinner.succeed("Mongodb successfully connected");
|
||||
}
|
||||
|
||||
spinner.info("Testing redis connection");
|
||||
const redisPing = await redisClient?.ping();
|
||||
if (!redisPing) {
|
||||
spinner.fail("Redis - Failed to connect");
|
||||
} else {
|
||||
spinner.succeed("Redis successfully connected");
|
||||
}
|
||||
|
||||
spinner.stop();
|
||||
};
|
@ -0,0 +1,24 @@
|
||||
import { IServerConfig, ServerConfig } from "../models/serverConfig";
|
||||
|
||||
let serverConfig: IServerConfig;
|
||||
|
||||
export const serverConfigInit = async () => {
|
||||
const cfg = await ServerConfig.findOne({});
|
||||
if (!cfg) {
|
||||
const cfg = new ServerConfig();
|
||||
await cfg.save();
|
||||
serverConfig = cfg;
|
||||
} else {
|
||||
serverConfig = cfg;
|
||||
}
|
||||
return serverConfig;
|
||||
};
|
||||
|
||||
export const getServerConfig = () => serverConfig;
|
||||
|
||||
export const updateServerConfig = async (data: Partial<IServerConfig>) => {
|
||||
const cfg = await ServerConfig.findByIdAndUpdate(serverConfig._id, data, { new: true });
|
||||
if (!cfg) throw new Error("Failed to update server config");
|
||||
serverConfig = cfg;
|
||||
return serverConfig;
|
||||
};
|
@ -0,0 +1,100 @@
|
||||
import { Request, Response } from "express";
|
||||
import { getHttpsEnabled } from "../../config";
|
||||
import { getServerConfig, updateServerConfig as setServerConfig } from "../../config/serverConfig";
|
||||
import { initializeDefaultOrg, issueAuthTokens } from "../../helpers";
|
||||
import { validateRequest } from "../../helpers/validation";
|
||||
import { User } from "../../models";
|
||||
import { TelemetryService } from "../../services";
|
||||
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
||||
import * as reqValidator from "../../validation/admin";
|
||||
|
||||
export const getServerConfigInfo = (_req: Request, res: Response) => {
|
||||
const config = getServerConfig();
|
||||
return res.send({ config });
|
||||
};
|
||||
|
||||
export const updateServerConfig = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: { allowSignUp }
|
||||
} = await validateRequest(reqValidator.UpdateServerConfigV1, req);
|
||||
const config = await setServerConfig({ allowSignUp });
|
||||
return res.send({ config });
|
||||
};
|
||||
|
||||
export const adminSignUp = async (req: Request, res: Response) => {
|
||||
const cfg = getServerConfig();
|
||||
if (cfg.initialized) throw UnauthorizedRequestError({ message: "Admin has been created" });
|
||||
const {
|
||||
body: {
|
||||
email,
|
||||
publicKey,
|
||||
salt,
|
||||
lastName,
|
||||
verifier,
|
||||
firstName,
|
||||
protectedKey,
|
||||
protectedKeyIV,
|
||||
protectedKeyTag,
|
||||
encryptedPrivateKey,
|
||||
encryptedPrivateKeyIV,
|
||||
encryptedPrivateKeyTag
|
||||
}
|
||||
} = await validateRequest(reqValidator.SignupV1, req);
|
||||
let user = await User.findOne({ email });
|
||||
if (user) throw BadRequestError({ message: "User already exist" });
|
||||
user = new User({
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
encryptionVersion: 2,
|
||||
protectedKey,
|
||||
protectedKeyIV,
|
||||
protectedKeyTag,
|
||||
publicKey,
|
||||
encryptedPrivateKey,
|
||||
iv: encryptedPrivateKeyIV,
|
||||
tag: encryptedPrivateKeyTag,
|
||||
salt,
|
||||
verifier,
|
||||
superAdmin: true
|
||||
});
|
||||
await user.save();
|
||||
await initializeDefaultOrg({ organizationName: "Admin Org", user });
|
||||
|
||||
await setServerConfig({ initialized: true });
|
||||
|
||||
// issue tokens
|
||||
const tokens = await issueAuthTokens({
|
||||
userId: user._id,
|
||||
ip: req.realIP,
|
||||
userAgent: req.headers["user-agent"] ?? ""
|
||||
});
|
||||
|
||||
const token = tokens.token;
|
||||
|
||||
const postHogClient = await TelemetryService.getPostHogClient();
|
||||
if (postHogClient) {
|
||||
postHogClient.capture({
|
||||
event: "admin initialization",
|
||||
properties: {
|
||||
email: user.email,
|
||||
lastName,
|
||||
firstName
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// store (refresh) token in httpOnly cookie
|
||||
res.cookie("jid", tokens.refreshToken, {
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "strict",
|
||||
secure: await getHttpsEnabled()
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
message: "Successfully set up admin account",
|
||||
user,
|
||||
token
|
||||
});
|
||||
};
|
@ -0,0 +1,103 @@
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import { Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
import { getSiteURL } from "../../config";
|
||||
import { EventType } from "../../ee/models";
|
||||
import { EEAuditLogService } from "../../ee/services";
|
||||
import {
|
||||
ProjectPermissionActions,
|
||||
ProjectPermissionSub,
|
||||
getUserProjectPermissions
|
||||
} from "../../ee/services/ProjectRoleService";
|
||||
import { sendMail } from "../../helpers";
|
||||
import { validateRequest } from "../../helpers/validation";
|
||||
import { IUser, Key, Membership, MembershipOrg, Workspace } from "../../models";
|
||||
import { BadRequestError } from "../../utils/errors";
|
||||
import * as reqValidator from "../../validation/membership";
|
||||
import { ACCEPTED, MEMBER } from "../../variables";
|
||||
|
||||
export const addUserToWorkspace = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { workspaceId },
|
||||
body: { members }
|
||||
} = await validateRequest(reqValidator.AddUserToWorkspaceV2, req);
|
||||
// check workspace
|
||||
const workspace = await Workspace.findById(workspaceId);
|
||||
if (!workspace) throw new Error("Failed to find workspace");
|
||||
|
||||
// check permission
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Create,
|
||||
ProjectPermissionSub.Member
|
||||
);
|
||||
|
||||
// validate members are part of the organization
|
||||
const orgMembers = await MembershipOrg.find({
|
||||
status: ACCEPTED,
|
||||
_id: { $in: members.map(({ orgMembershipId }) => orgMembershipId) },
|
||||
organization: workspace.organization
|
||||
})
|
||||
.populate<{ user: IUser }>("user")
|
||||
.select({ _id: 1, user: 1 })
|
||||
.lean();
|
||||
if (orgMembers.length !== members.length)
|
||||
throw BadRequestError({ message: "Org member not found" });
|
||||
|
||||
const existingMember = await Membership.find({
|
||||
workspace: workspaceId,
|
||||
user: { $in: orgMembers.map(({ user }) => user) }
|
||||
});
|
||||
if (existingMember?.length)
|
||||
throw BadRequestError({ message: "Some users are already part of workspace" });
|
||||
|
||||
await Membership.insertMany(
|
||||
orgMembers.map(({ user }) => ({ user: user._id, workspace: workspaceId, role: MEMBER }))
|
||||
);
|
||||
|
||||
const encKeyGroupedByOrgMemberId = members.reduce<Record<string, (typeof members)[number]>>(
|
||||
(prev, curr) => ({ ...prev, [curr.orgMembershipId]: curr }),
|
||||
{}
|
||||
);
|
||||
await Key.insertMany(
|
||||
orgMembers.map(({ user, _id: id }) => ({
|
||||
encryptedKey: encKeyGroupedByOrgMemberId[id.toString()].workspaceEncryptedKey,
|
||||
nonce: encKeyGroupedByOrgMemberId[id.toString()].workspaceEncryptedNonce,
|
||||
sender: req.user._id,
|
||||
receiver: user._id,
|
||||
workspace: workspaceId
|
||||
}))
|
||||
);
|
||||
|
||||
await sendMail({
|
||||
template: "workspaceInvitation.handlebars",
|
||||
subjectLine: "Infisical workspace invitation",
|
||||
recipients: orgMembers.map(({ user }) => user.email),
|
||||
substitutions: {
|
||||
inviterFirstName: req.user.firstName,
|
||||
inviterEmail: req.user.email,
|
||||
workspaceName: workspace.name,
|
||||
callback_url: (await getSiteURL()) + "/login"
|
||||
}
|
||||
});
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.ADD_BATCH_WORKSPACE_MEMBER,
|
||||
metadata: orgMembers.map(({ user }) => ({
|
||||
userId: user._id.toString(),
|
||||
email: user.email
|
||||
}))
|
||||
},
|
||||
{
|
||||
workspaceId: new Types.ObjectId(workspaceId)
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
success: true,
|
||||
data: orgMembers
|
||||
});
|
||||
};
|
@ -1,306 +0,0 @@
|
||||
import { Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import crypto from "crypto";
|
||||
import bcrypt from "bcrypt";
|
||||
import {
|
||||
ServiceAccount,
|
||||
ServiceAccountKey,
|
||||
ServiceAccountOrganizationPermission,
|
||||
ServiceAccountWorkspacePermission,
|
||||
} from "../../models";
|
||||
import {
|
||||
CreateServiceAccountDto,
|
||||
} from "../../interfaces/serviceAccounts/dto";
|
||||
import { BadRequestError, ServiceAccountNotFoundError } from "../../utils/errors";
|
||||
import { getSaltRounds } from "../../config";
|
||||
|
||||
/**
|
||||
* Return service account tied to the request (service account) client
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const getCurrentServiceAccount = async (req: Request, res: Response) => {
|
||||
const serviceAccount = await ServiceAccount.findById(req.serviceAccount._id);
|
||||
|
||||
if (!serviceAccount) {
|
||||
throw ServiceAccountNotFoundError({ message: "Failed to find service account" });
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccount,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const getServiceAccountById = async (req: Request, res: Response) => {
|
||||
const { serviceAccountId } = req.params;
|
||||
|
||||
const serviceAccount = await ServiceAccount.findById(serviceAccountId);
|
||||
|
||||
if (!serviceAccount) {
|
||||
throw ServiceAccountNotFoundError({ message: "Failed to find service account" });
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccount,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new service account under organization with id [organizationId]
|
||||
* that has access to workspaces [workspaces]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const createServiceAccount = async (req: Request, res: Response) => {
|
||||
const {
|
||||
name,
|
||||
organizationId,
|
||||
publicKey,
|
||||
expiresIn,
|
||||
}: CreateServiceAccountDto = req.body;
|
||||
|
||||
let expiresAt;
|
||||
if (expiresIn) {
|
||||
expiresAt = new Date();
|
||||
expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);
|
||||
}
|
||||
|
||||
const secret = crypto.randomBytes(16).toString("base64");
|
||||
const secretHash = await bcrypt.hash(secret, await getSaltRounds());
|
||||
|
||||
// create service account
|
||||
const serviceAccount = await new ServiceAccount({
|
||||
name,
|
||||
organization: new Types.ObjectId(organizationId),
|
||||
user: req.user,
|
||||
publicKey,
|
||||
lastUsed: new Date(),
|
||||
expiresAt,
|
||||
secretHash,
|
||||
}).save()
|
||||
|
||||
const serviceAccountObj = serviceAccount.toObject();
|
||||
|
||||
delete (serviceAccountObj as any).secretHash;
|
||||
|
||||
// provision default org-level permission for service account
|
||||
await new ServiceAccountOrganizationPermission({
|
||||
serviceAccount: serviceAccount._id,
|
||||
}).save();
|
||||
|
||||
const secretId = Buffer.from(serviceAccount._id.toString(), "hex").toString("base64");
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccountAccessKey: `sa.${secretId}.${secret}`,
|
||||
serviceAccount: serviceAccountObj,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Change name of service account with id [serviceAccountId] to [name]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const changeServiceAccountName = async (req: Request, res: Response) => {
|
||||
const { serviceAccountId } = req.params;
|
||||
const { name } = req.body;
|
||||
|
||||
const serviceAccount = await ServiceAccount.findOneAndUpdate(
|
||||
{
|
||||
_id: new Types.ObjectId(serviceAccountId),
|
||||
},
|
||||
{
|
||||
name,
|
||||
},
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccount,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a service account key to service account with id [serviceAccountId]
|
||||
* for workspace with id [workspaceId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const addServiceAccountKey = async (req: Request, res: Response) => {
|
||||
const {
|
||||
workspaceId,
|
||||
encryptedKey,
|
||||
nonce,
|
||||
} = req.body;
|
||||
|
||||
const serviceAccountKey = await new ServiceAccountKey({
|
||||
encryptedKey,
|
||||
nonce,
|
||||
sender: req.user._id,
|
||||
serviceAccount: req.serviceAccount._d,
|
||||
workspace: new Types.ObjectId(workspaceId),
|
||||
}).save();
|
||||
|
||||
return serviceAccountKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return workspace-level permission for service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const getServiceAccountWorkspacePermissions = async (req: Request, res: Response) => {
|
||||
const serviceAccountWorkspacePermissions = await ServiceAccountWorkspacePermission.find({
|
||||
serviceAccount: req.serviceAccount._id,
|
||||
}).populate("workspace");
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccountWorkspacePermissions,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a workspace permission to service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const addServiceAccountWorkspacePermission = async (req: Request, res: Response) => {
|
||||
const { serviceAccountId } = req.params;
|
||||
const {
|
||||
environment,
|
||||
workspaceId,
|
||||
read = false,
|
||||
write = false,
|
||||
encryptedKey,
|
||||
nonce,
|
||||
} = req.body;
|
||||
|
||||
if (!req.membership.workspace.environments.some((e: { name: string; slug: string }) => e.slug === environment)) {
|
||||
return res.status(400).send({
|
||||
message: "Failed to validate workspace environment",
|
||||
});
|
||||
}
|
||||
|
||||
const existingPermission = await ServiceAccountWorkspacePermission.findOne({
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
workspace: new Types.ObjectId(workspaceId),
|
||||
environment,
|
||||
});
|
||||
|
||||
if (existingPermission) throw BadRequestError({ message: "Failed to add workspace permission to service account due to already-existing " });
|
||||
|
||||
const serviceAccountWorkspacePermission = await new ServiceAccountWorkspacePermission({
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
workspace: new Types.ObjectId(workspaceId),
|
||||
environment,
|
||||
read,
|
||||
write,
|
||||
}).save();
|
||||
|
||||
const existingServiceAccountKey = await ServiceAccountKey.findOne({
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
workspace: new Types.ObjectId(workspaceId),
|
||||
});
|
||||
|
||||
if (!existingServiceAccountKey) {
|
||||
await new ServiceAccountKey({
|
||||
encryptedKey,
|
||||
nonce,
|
||||
sender: req.user._id,
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
workspace: new Types.ObjectId(workspaceId),
|
||||
}).save();
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccountWorkspacePermission,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete workspace permission from service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const deleteServiceAccountWorkspacePermission = async (req: Request, res: Response) => {
|
||||
const { serviceAccountWorkspacePermissionId } = req.params;
|
||||
const serviceAccountWorkspacePermission = await ServiceAccountWorkspacePermission.findByIdAndDelete(serviceAccountWorkspacePermissionId);
|
||||
|
||||
if (serviceAccountWorkspacePermission) {
|
||||
const { serviceAccount, workspace } = serviceAccountWorkspacePermission;
|
||||
const count = await ServiceAccountWorkspacePermission.countDocuments({
|
||||
serviceAccount,
|
||||
workspace,
|
||||
});
|
||||
|
||||
if (count === 0) {
|
||||
await ServiceAccountKey.findOneAndDelete({
|
||||
serviceAccount,
|
||||
workspace,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccountWorkspacePermission,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const deleteServiceAccount = async (req: Request, res: Response) => {
|
||||
const { serviceAccountId } = req.params;
|
||||
|
||||
const serviceAccount = await ServiceAccount.findByIdAndDelete(serviceAccountId);
|
||||
|
||||
if (serviceAccount) {
|
||||
await ServiceAccountKey.deleteMany({
|
||||
serviceAccount: serviceAccount._id,
|
||||
});
|
||||
|
||||
await ServiceAccountOrganizationPermission.deleteMany({
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
});
|
||||
|
||||
await ServiceAccountWorkspacePermission.deleteMany({
|
||||
serviceAccount: new Types.ObjectId(serviceAccountId),
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccount,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return service account keys for service account with id [serviceAccountId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const getServiceAccountKeys = async (req: Request, res: Response) => {
|
||||
const workspaceId = req.query.workspaceId as string;
|
||||
|
||||
const serviceAccountKeys = await ServiceAccountKey.find({
|
||||
serviceAccount: req.serviceAccount._id,
|
||||
...(workspaceId ? { workspace: new Types.ObjectId(workspaceId) } : {}),
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
serviceAccountKeys,
|
||||
});
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
import { Request, Response } from "express";
|
||||
import { APIKeyDataV2 } from "../../models";
|
||||
|
||||
/**
|
||||
* Return API keys belonging to current user.
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const getMyAPIKeys = async (req: Request, res: Response) => {
|
||||
const apiKeyData = await APIKeyDataV2.find({
|
||||
user: req.user._id
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
apiKeyData
|
||||
});
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
import { Request, Response } from "express";
|
||||
import { Action } from "../../models";
|
||||
import { ActionNotFoundError } from "../../../utils/errors";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import * as reqValidator from "../../../validation/action";
|
||||
|
||||
export const getAction = async (req: Request, res: Response) => {
|
||||
let action;
|
||||
try {
|
||||
const {
|
||||
params: { actionId }
|
||||
} = await validateRequest(reqValidator.GetActionV1, req);
|
||||
|
||||
action = await Action.findById(actionId).populate([
|
||||
"payload.secretVersions.oldSecretVersion",
|
||||
"payload.secretVersions.newSecretVersion"
|
||||
]);
|
||||
|
||||
if (!action)
|
||||
throw ActionNotFoundError({
|
||||
message: "Failed to find action"
|
||||
});
|
||||
} catch (err) {
|
||||
throw ActionNotFoundError({
|
||||
message: "Failed to find action"
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
action
|
||||
});
|
||||
};
|
@ -0,0 +1,91 @@
|
||||
import { Request, Response } from "express";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import * as reqValidator from "../../validation/secretRotation";
|
||||
import * as secretRotationService from "../../secretRotation/service";
|
||||
import {
|
||||
getUserProjectPermissions,
|
||||
ProjectPermissionActions,
|
||||
ProjectPermissionSub
|
||||
} from "../../services/ProjectRoleService";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
|
||||
export const createSecretRotation = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
provider,
|
||||
customProvider,
|
||||
interval,
|
||||
outputs,
|
||||
secretPath,
|
||||
environment,
|
||||
workspaceId,
|
||||
inputs
|
||||
}
|
||||
} = await validateRequest(reqValidator.createSecretRotationV1, req);
|
||||
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Create,
|
||||
ProjectPermissionSub.SecretRotation
|
||||
);
|
||||
|
||||
const secretRotation = await secretRotationService.createSecretRotation({
|
||||
workspaceId,
|
||||
inputs,
|
||||
environment,
|
||||
secretPath,
|
||||
outputs,
|
||||
interval,
|
||||
customProvider,
|
||||
provider
|
||||
});
|
||||
|
||||
return res.send({ secretRotation });
|
||||
};
|
||||
|
||||
export const restartSecretRotations = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: { id }
|
||||
} = await validateRequest(reqValidator.restartSecretRotationV1, req);
|
||||
|
||||
const doc = await secretRotationService.getSecretRotationById({ id });
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, doc.workspace.toString());
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Edit,
|
||||
ProjectPermissionSub.SecretRotation
|
||||
);
|
||||
|
||||
const secretRotation = await secretRotationService.restartSecretRotation({ id });
|
||||
return res.send({ secretRotation });
|
||||
};
|
||||
|
||||
export const deleteSecretRotations = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { id }
|
||||
} = await validateRequest(reqValidator.removeSecretRotationV1, req);
|
||||
|
||||
const doc = await secretRotationService.getSecretRotationById({ id });
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, doc.workspace.toString());
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Delete,
|
||||
ProjectPermissionSub.SecretRotation
|
||||
);
|
||||
|
||||
const secretRotations = await secretRotationService.deleteSecretRotation({ id });
|
||||
return res.send({ secretRotations });
|
||||
};
|
||||
|
||||
export const getSecretRotations = async (req: Request, res: Response) => {
|
||||
const {
|
||||
query: { workspaceId }
|
||||
} = await validateRequest(reqValidator.getSecretRotationV1, req);
|
||||
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Read,
|
||||
ProjectPermissionSub.SecretRotation
|
||||
);
|
||||
|
||||
const secretRotations = await secretRotationService.getSecretRotationOfWorkspace(workspaceId);
|
||||
return res.send({ secretRotations });
|
||||
};
|
@ -0,0 +1,28 @@
|
||||
import { Request, Response } from "express";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import * as reqValidator from "../../validation/secretRotationProvider";
|
||||
import * as secretRotationProviderService from "../../secretRotation/service";
|
||||
import {
|
||||
getUserProjectPermissions,
|
||||
ProjectPermissionActions,
|
||||
ProjectPermissionSub
|
||||
} from "../../services/ProjectRoleService";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
|
||||
export const getProviderTemplates = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { workspaceId }
|
||||
} = await validateRequest(reqValidator.getSecretRotationProvidersV1, req);
|
||||
|
||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
ProjectPermissionActions.Read,
|
||||
ProjectPermissionSub.SecretRotation
|
||||
);
|
||||
|
||||
const rotationProviderList = await secretRotationProviderService.getProviderTemplate({
|
||||
workspaceId
|
||||
});
|
||||
|
||||
return res.send(rotationProviderList);
|
||||
};
|
@ -0,0 +1,101 @@
|
||||
import { Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { APIKeyDataV2 } from "../../../models/apiKeyDataV2";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import { BadRequestError } from "../../../utils/errors";
|
||||
import * as reqValidator from "../../../validation";
|
||||
import { createToken } from "../../../helpers";
|
||||
import { AuthTokenType } from "../../../variables";
|
||||
import { getAuthSecret } from "../../../config";
|
||||
|
||||
/**
|
||||
* Create API key data v2
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const createAPIKeyData = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
name
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateAPIKeyV3, req);
|
||||
|
||||
const apiKeyData = await new APIKeyDataV2({
|
||||
name,
|
||||
user: req.user._id,
|
||||
usageCount: 0,
|
||||
}).save();
|
||||
|
||||
const apiKey = createToken({
|
||||
payload: {
|
||||
authTokenType: AuthTokenType.API_KEY,
|
||||
apiKeyDataId: apiKeyData._id.toString(),
|
||||
userId: req.user._id.toString()
|
||||
},
|
||||
secret: await getAuthSecret()
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
apiKeyData,
|
||||
apiKey
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update API key data v2 with id [apiKeyDataId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const updateAPIKeyData = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { apiKeyDataId },
|
||||
body: {
|
||||
name,
|
||||
}
|
||||
} = await validateRequest(reqValidator.UpdateAPIKeyV3, req);
|
||||
|
||||
const apiKeyData = await APIKeyDataV2.findOneAndUpdate(
|
||||
{
|
||||
_id: new Types.ObjectId(apiKeyDataId),
|
||||
user: req.user._id
|
||||
},
|
||||
{
|
||||
name
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!apiKeyData) throw BadRequestError({
|
||||
message: "Failed to update API key"
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
apiKeyData
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete API key data v2 with id [apiKeyDataId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const deleteAPIKeyData = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { apiKeyDataId }
|
||||
} = await validateRequest(reqValidator.DeleteAPIKeyV3, req);
|
||||
|
||||
const apiKeyData = await APIKeyDataV2.findOneAndDelete({
|
||||
_id: new Types.ObjectId(apiKeyDataId),
|
||||
user: req.user._id
|
||||
});
|
||||
|
||||
if (!apiKeyData) throw BadRequestError({
|
||||
message: "Failed to delete API key"
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
apiKeyData
|
||||
});
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
import * as serviceTokenDataController from "./serviceTokenDataController";
|
||||
import * as apiKeyDataController from "./apiKeyDataController";
|
||||
|
||||
export {
|
||||
serviceTokenDataController
|
||||
serviceTokenDataController,
|
||||
apiKeyDataController
|
||||
}
|
@ -1,195 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import { Action } from "../models";
|
||||
import {
|
||||
getLatestNSecretSecretVersionIds,
|
||||
getLatestSecretVersionIds,
|
||||
} from "../helpers/secretVersion";
|
||||
import {
|
||||
ACTION_ADD_SECRETS,
|
||||
ACTION_DELETE_SECRETS,
|
||||
ACTION_LOGIN,
|
||||
ACTION_LOGOUT,
|
||||
ACTION_READ_SECRETS,
|
||||
ACTION_UPDATE_SECRETS,
|
||||
} from "../../variables";
|
||||
|
||||
/**
|
||||
* Create an (audit) action for updating secrets
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.name - name of action
|
||||
* @param {Types.ObjectId} obj.secretIds - ids of relevant secrets
|
||||
* @returns {Action} action - new action
|
||||
*/
|
||||
const createActionUpdateSecret = async ({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
}: {
|
||||
name: string;
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId: Types.ObjectId;
|
||||
secretIds: Types.ObjectId[];
|
||||
}) => {
|
||||
const latestSecretVersions = (await getLatestNSecretSecretVersionIds({
|
||||
secretIds,
|
||||
n: 2,
|
||||
}))
|
||||
.map((s) => ({
|
||||
oldSecretVersion: s.versions[0]._id,
|
||||
newSecretVersion: s.versions[1]._id,
|
||||
}));
|
||||
|
||||
const action = await new Action({
|
||||
name,
|
||||
user: userId,
|
||||
serviceAccount: serviceAccountId,
|
||||
serviceTokenData: serviceTokenDataId,
|
||||
workspace: workspaceId,
|
||||
payload: {
|
||||
secretVersions: latestSecretVersions,
|
||||
},
|
||||
}).save();
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an (audit) action for creating, reading, and deleting
|
||||
* secrets
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.name - name of action
|
||||
* @param {Types.ObjectId} obj.secretIds - ids of relevant secrets
|
||||
* @returns {Action} action - new action
|
||||
*/
|
||||
const createActionSecret = async ({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
}: {
|
||||
name: string;
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId: Types.ObjectId;
|
||||
secretIds: Types.ObjectId[];
|
||||
}) => {
|
||||
// case: action is adding, deleting, or reading secrets
|
||||
// -> add new secret versions
|
||||
const latestSecretVersions = (await getLatestSecretVersionIds({
|
||||
secretIds,
|
||||
}))
|
||||
.map((s) => ({
|
||||
newSecretVersion: s.versionId,
|
||||
}));
|
||||
|
||||
const action = await new Action({
|
||||
name,
|
||||
user: userId,
|
||||
serviceAccount: serviceAccountId,
|
||||
serviceTokenData: serviceTokenDataId,
|
||||
workspace: workspaceId,
|
||||
payload: {
|
||||
secretVersions: latestSecretVersions,
|
||||
},
|
||||
}).save();
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an (audit) action for client with id [userId],
|
||||
* [serviceAccountId], or [serviceTokenDataId]
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.name - name of action
|
||||
* @param {String} obj.userId - id of user associated with action
|
||||
* @returns
|
||||
*/
|
||||
const createActionClient = ({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
}: {
|
||||
name: string;
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
}) => {
|
||||
const action = new Action({
|
||||
name,
|
||||
user: userId,
|
||||
serviceAccount: serviceAccountId,
|
||||
serviceTokenData: serviceTokenDataId,
|
||||
}).save();
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an (audit) action.
|
||||
* @param {Object} obj
|
||||
* @param {Object} obj.name - name of action
|
||||
* @param {Types.ObjectId} obj.userId - id of user associated with action
|
||||
* @param {Types.ObjectId} obj.workspaceId - id of workspace associated with action
|
||||
* @param {Types.ObjectId[]} obj.secretIds - ids of secrets associated with action
|
||||
*/
|
||||
const createActionHelper = async ({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
}: {
|
||||
name: string;
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId?: Types.ObjectId;
|
||||
secretIds?: Types.ObjectId[];
|
||||
}) => {
|
||||
let action;
|
||||
switch (name) {
|
||||
case ACTION_LOGIN:
|
||||
case ACTION_LOGOUT:
|
||||
action = await createActionClient({
|
||||
name,
|
||||
userId,
|
||||
});
|
||||
break;
|
||||
case ACTION_ADD_SECRETS:
|
||||
case ACTION_READ_SECRETS:
|
||||
case ACTION_DELETE_SECRETS:
|
||||
if (!workspaceId || !secretIds) throw new Error("Missing required params workspace id or secret ids to create action secret");
|
||||
action = await createActionSecret({
|
||||
name,
|
||||
userId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
});
|
||||
break;
|
||||
case ACTION_UPDATE_SECRETS:
|
||||
if (!workspaceId || !secretIds) throw new Error("Missing required params workspace id or secret ids to create action secret");
|
||||
action = await createActionUpdateSecret({
|
||||
name,
|
||||
userId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
export {
|
||||
createActionHelper,
|
||||
};
|
@ -1,50 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import {
|
||||
IAction,
|
||||
Log,
|
||||
} from "../models";
|
||||
|
||||
/**
|
||||
* Create an (audit) log
|
||||
* @param {Object} obj
|
||||
* @param {Types.ObjectId} obj.userId - id of user associated with the log
|
||||
* @param {Types.ObjectId} obj.workspaceId - id of workspace associated with the log
|
||||
* @param {IAction[]} obj.actions - actions to include in log
|
||||
* @param {String} obj.channel - channel (web/cli/auto) associated with the log
|
||||
* @param {String} obj.ipAddress - ip address associated with the log
|
||||
* @returns {Log} log - new audit log
|
||||
*/
|
||||
const createLogHelper = async ({
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
actions,
|
||||
channel,
|
||||
ipAddress,
|
||||
}: {
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId?: Types.ObjectId;
|
||||
actions: IAction[];
|
||||
channel: string;
|
||||
ipAddress: string;
|
||||
}) => {
|
||||
const log = await new Log({
|
||||
user: userId,
|
||||
serviceAccount: serviceAccountId,
|
||||
serviceTokenData: serviceTokenDataId,
|
||||
workspace: workspaceId ?? undefined,
|
||||
actionNames: actions.map((a) => a.name),
|
||||
actions,
|
||||
channel,
|
||||
ipAddress,
|
||||
}).save();
|
||||
|
||||
return log;
|
||||
}
|
||||
|
||||
export {
|
||||
createLogHelper,
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
import requireSecretSnapshotAuth from "./requireSecretSnapshotAuth";
|
||||
|
||||
export {
|
||||
requireSecretSnapshotAuth,
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { SecretSnapshotNotFoundError } from "../../utils/errors";
|
||||
import { SecretSnapshot } from "../models";
|
||||
import {
|
||||
validateMembership,
|
||||
} from "../../helpers/membership";
|
||||
|
||||
/**
|
||||
* Validate if user on request has proper membership for secret snapshot
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted workspace roles
|
||||
* @param {String[]} obj.acceptedStatuses - accepted workspace statuses
|
||||
* @param {String[]} obj.location - location of [workspaceId] on request (e.g. params, body) for parsing
|
||||
*/
|
||||
const requireSecretSnapshotAuth = ({
|
||||
acceptedRoles,
|
||||
}: {
|
||||
acceptedRoles: Array<"admin" | "member">;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { secretSnapshotId } = req.params;
|
||||
|
||||
const secretSnapshot = await SecretSnapshot.findById(secretSnapshotId);
|
||||
|
||||
if (!secretSnapshot) {
|
||||
return next(SecretSnapshotNotFoundError({
|
||||
message: "Failed to find secret snapshot",
|
||||
}));
|
||||
}
|
||||
|
||||
await validateMembership({
|
||||
userId: req.user._id,
|
||||
workspaceId: secretSnapshot.workspace,
|
||||
acceptedRoles,
|
||||
});
|
||||
|
||||
req.secretSnapshot = secretSnapshot as any;
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireSecretSnapshotAuth;
|
@ -1,69 +0,0 @@
|
||||
import { Schema, Types, model } from "mongoose";
|
||||
import {
|
||||
ACTION_ADD_SECRETS,
|
||||
ACTION_DELETE_SECRETS,
|
||||
ACTION_LOGIN,
|
||||
ACTION_LOGOUT,
|
||||
ACTION_READ_SECRETS,
|
||||
ACTION_UPDATE_SECRETS,
|
||||
} from "../../variables";
|
||||
|
||||
export interface IAction {
|
||||
name: string;
|
||||
user?: Types.ObjectId,
|
||||
serviceAccount?: Types.ObjectId,
|
||||
serviceTokenData?: Types.ObjectId,
|
||||
workspace?: Types.ObjectId,
|
||||
payload?: {
|
||||
secretVersions?: Types.ObjectId[]
|
||||
}
|
||||
}
|
||||
|
||||
const actionSchema = new Schema<IAction>(
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: [
|
||||
ACTION_LOGIN,
|
||||
ACTION_LOGOUT,
|
||||
ACTION_ADD_SECRETS,
|
||||
ACTION_UPDATE_SECRETS,
|
||||
ACTION_READ_SECRETS,
|
||||
ACTION_DELETE_SECRETS,
|
||||
],
|
||||
},
|
||||
user: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
},
|
||||
serviceAccount: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "ServiceAccount",
|
||||
},
|
||||
serviceTokenData: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "ServiceTokenData",
|
||||
},
|
||||
workspace: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Workspace",
|
||||
},
|
||||
payload: {
|
||||
secretVersions: [{
|
||||
oldSecretVersion: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "SecretVersion",
|
||||
},
|
||||
newSecretVersion: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "SecretVersion",
|
||||
},
|
||||
}],
|
||||
},
|
||||
}, {
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
export const Action = model<IAction>("Action", actionSchema);
|
@ -1,72 +0,0 @@
|
||||
import { Schema, Types, model } from "mongoose";
|
||||
import {
|
||||
ACTION_ADD_SECRETS,
|
||||
ACTION_DELETE_SECRETS,
|
||||
ACTION_LOGIN,
|
||||
ACTION_LOGOUT,
|
||||
ACTION_READ_SECRETS,
|
||||
ACTION_UPDATE_SECRETS,
|
||||
} from "../../variables";
|
||||
|
||||
export interface ILog {
|
||||
_id: Types.ObjectId;
|
||||
user?: Types.ObjectId;
|
||||
serviceAccount?: Types.ObjectId;
|
||||
serviceTokenData?: Types.ObjectId;
|
||||
workspace?: Types.ObjectId;
|
||||
actionNames: string[];
|
||||
actions: Types.ObjectId[];
|
||||
channel: string;
|
||||
ipAddress?: string;
|
||||
}
|
||||
|
||||
const logSchema = new Schema<ILog>(
|
||||
{
|
||||
user: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
},
|
||||
serviceAccount: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "ServiceAccount",
|
||||
},
|
||||
serviceTokenData: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "ServiceTokenData",
|
||||
},
|
||||
workspace: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Workspace",
|
||||
},
|
||||
actionNames: {
|
||||
type: [String],
|
||||
enum: [
|
||||
ACTION_LOGIN,
|
||||
ACTION_LOGOUT,
|
||||
ACTION_ADD_SECRETS,
|
||||
ACTION_UPDATE_SECRETS,
|
||||
ACTION_READ_SECRETS,
|
||||
ACTION_DELETE_SECRETS,
|
||||
],
|
||||
required: true,
|
||||
},
|
||||
actions: [{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Action",
|
||||
required: true,
|
||||
}],
|
||||
channel: {
|
||||
type: String,
|
||||
enum: ["web", "cli", "auto", "k8-operator", "other"],
|
||||
required: true,
|
||||
},
|
||||
ipAddress: {
|
||||
type: String,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
export const Log = model<ILog>("Log", logSchema);
|
@ -1,8 +0,0 @@
|
||||
import express from "express";
|
||||
const router = express.Router();
|
||||
import { actionController } from "../../controllers/v1";
|
||||
|
||||
// TODO: put into action controller
|
||||
router.get("/:actionId", actionController.getAction);
|
||||
|
||||
export default router;
|
@ -0,0 +1,41 @@
|
||||
import express from "express";
|
||||
|
||||
import { AuthMode } from "../../../variables";
|
||||
import { requireAuth } from "../../../middleware";
|
||||
import { secretRotationController } from "../../controllers/v1";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
secretRotationController.createSecretRotation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/restart",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
secretRotationController.restartSecretRotations
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
secretRotationController.getSecretRotations
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:id",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
secretRotationController.deleteSecretRotations
|
||||
);
|
||||
|
||||
export default router;
|
@ -0,0 +1,17 @@
|
||||
import express from "express";
|
||||
|
||||
import { AuthMode } from "../../../variables";
|
||||
import { requireAuth } from "../../../middleware";
|
||||
import { secretRotationProviderController } from "../../controllers/v1";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get(
|
||||
"/:workspaceId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
secretRotationProviderController.getProviderTemplates
|
||||
);
|
||||
|
||||
export default router;
|
@ -0,0 +1,31 @@
|
||||
import express from "express";
|
||||
const router = express.Router();
|
||||
import { requireAuth } from "../../../middleware";
|
||||
import { AuthMode } from "../../../variables";
|
||||
import { apiKeyDataController } from "../../controllers/v3";
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
apiKeyDataController.createAPIKeyData
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/:apiKeyDataId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
apiKeyDataController.updateAPIKeyData
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:apiKeyDataId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
apiKeyDataController.deleteAPIKeyData
|
||||
);
|
||||
|
||||
export default router;
|
@ -1,5 +1,7 @@
|
||||
import serviceTokenData from "./serviceTokenData";
|
||||
import apiKeyData from "./apiKeyData";
|
||||
|
||||
export {
|
||||
serviceTokenData
|
||||
serviceTokenData,
|
||||
apiKeyData
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
import { Schema, model } from "mongoose";
|
||||
import {
|
||||
ALGORITHM_AES_256_GCM,
|
||||
ENCODING_SCHEME_BASE64,
|
||||
ENCODING_SCHEME_UTF8
|
||||
} from "../../variables";
|
||||
import { ISecretRotation } from "./types";
|
||||
|
||||
const secretRotationSchema = new Schema(
|
||||
{
|
||||
workspace: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Workspace"
|
||||
},
|
||||
provider: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
customProvider: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "SecretRotationProvider"
|
||||
},
|
||||
environment: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
secretPath: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
interval: {
|
||||
type: Number,
|
||||
required: true
|
||||
},
|
||||
lastRotatedAt: {
|
||||
type: String
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: ["success", "failed"]
|
||||
},
|
||||
statusMessage: {
|
||||
type: String
|
||||
},
|
||||
// encrypted data on input keys and secrets got
|
||||
encryptedData: {
|
||||
type: String,
|
||||
select: false
|
||||
},
|
||||
encryptedDataIV: {
|
||||
type: String,
|
||||
select: false
|
||||
},
|
||||
encryptedDataTag: {
|
||||
type: String,
|
||||
select: false
|
||||
},
|
||||
algorithm: {
|
||||
// the encryption algorithm used
|
||||
type: String,
|
||||
enum: [ALGORITHM_AES_256_GCM],
|
||||
required: true,
|
||||
select: false,
|
||||
default: ALGORITHM_AES_256_GCM
|
||||
},
|
||||
keyEncoding: {
|
||||
type: String,
|
||||
enum: [ENCODING_SCHEME_UTF8, ENCODING_SCHEME_BASE64],
|
||||
required: true,
|
||||
select: false,
|
||||
default: ENCODING_SCHEME_UTF8
|
||||
},
|
||||
outputs: [
|
||||
{
|
||||
key: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
secret: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Secret"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
timestamps: true
|
||||
}
|
||||
);
|
||||
|
||||
export const SecretRotation = model<ISecretRotation>("SecretRotation", secretRotationSchema);
|
@ -0,0 +1,288 @@
|
||||
import Queue, { Job } from "bull";
|
||||
import { client, getEncryptionKey, getRootEncryptionKey } from "../../../config";
|
||||
import { BotService, EventService, TelemetryService } from "../../../services";
|
||||
import { SecretRotation } from "../models";
|
||||
import { rotationTemplates } from "../templates";
|
||||
import {
|
||||
ISecretRotationData,
|
||||
ISecretRotationEncData,
|
||||
ISecretRotationProviderTemplate,
|
||||
TProviderFunctionTypes
|
||||
} from "../types";
|
||||
import {
|
||||
decryptSymmetric128BitHexKeyUTF8,
|
||||
encryptSymmetric128BitHexKeyUTF8
|
||||
} from "../../../utils/crypto";
|
||||
import { ISecret, Secret } from "../../../models";
|
||||
import { ENCODING_SCHEME_BASE64, ENCODING_SCHEME_UTF8, SECRET_SHARED } from "../../../variables";
|
||||
import { EESecretService } from "../../services";
|
||||
import { SecretVersion } from "../../models";
|
||||
import { eventPushSecrets } from "../../../events";
|
||||
import { logger } from "../../../utils/logging";
|
||||
|
||||
import {
|
||||
secretRotationPreSetFn,
|
||||
secretRotationRemoveFn,
|
||||
secretRotationSetFn,
|
||||
secretRotationTestFn
|
||||
} from "./queue.utils";
|
||||
|
||||
const secretRotationQueue = new Queue("secret-rotation-service", process.env.REDIS_URL as string);
|
||||
|
||||
secretRotationQueue.process(async (job: Job) => {
|
||||
logger.info(`secretRotationQueue.process: [rotationDocument=${job.data.rotationDocId}]`);
|
||||
const rotationStratDocId = job.data.rotationDocId;
|
||||
const secretRotation = await SecretRotation.findById(rotationStratDocId)
|
||||
.select("+encryptedData +encryptedDataTag +encryptedDataIV +keyEncoding")
|
||||
.populate<{
|
||||
outputs: [
|
||||
{
|
||||
key: string;
|
||||
secret: ISecret;
|
||||
}
|
||||
];
|
||||
}>("outputs.secret");
|
||||
|
||||
const infisicalRotationProvider = rotationTemplates.find(
|
||||
({ name }) => name === secretRotation?.provider
|
||||
);
|
||||
|
||||
try {
|
||||
if (!infisicalRotationProvider || !secretRotation)
|
||||
throw new Error("Failed to find rotation strategy");
|
||||
|
||||
if (secretRotation.outputs.some(({ secret }) => !secret))
|
||||
throw new Error("Secrets not found in dashboard");
|
||||
|
||||
const workspaceId = secretRotation.workspace;
|
||||
|
||||
// deep copy
|
||||
const provider = JSON.parse(
|
||||
JSON.stringify(infisicalRotationProvider)
|
||||
) as ISecretRotationProviderTemplate;
|
||||
|
||||
// decrypt user provided inputs for secret rotation
|
||||
const encryptionKey = await getEncryptionKey();
|
||||
const rootEncryptionKey = await getRootEncryptionKey();
|
||||
let decryptedData = "";
|
||||
if (rootEncryptionKey && secretRotation.keyEncoding === ENCODING_SCHEME_BASE64) {
|
||||
// case: encoding scheme is base64
|
||||
decryptedData = client.decryptSymmetric(
|
||||
secretRotation.encryptedData,
|
||||
rootEncryptionKey,
|
||||
secretRotation.encryptedDataIV,
|
||||
secretRotation.encryptedDataTag
|
||||
);
|
||||
} else if (encryptionKey && secretRotation.keyEncoding === ENCODING_SCHEME_UTF8) {
|
||||
// case: encoding scheme is utf8
|
||||
decryptedData = decryptSymmetric128BitHexKeyUTF8({
|
||||
ciphertext: secretRotation.encryptedData,
|
||||
iv: secretRotation.encryptedDataIV,
|
||||
tag: secretRotation.encryptedDataTag,
|
||||
key: encryptionKey
|
||||
});
|
||||
}
|
||||
|
||||
const variables = JSON.parse(decryptedData) as ISecretRotationEncData;
|
||||
|
||||
// rotation set cycle
|
||||
const newCredential: ISecretRotationData = {
|
||||
inputs: variables.inputs,
|
||||
outputs: {},
|
||||
internal: {}
|
||||
};
|
||||
// special glue code for database
|
||||
if (provider.template.functions.set.type === TProviderFunctionTypes.DB) {
|
||||
const lastCred = variables.creds.at(-1);
|
||||
if (lastCred && variables.creds.length === 1) {
|
||||
newCredential.internal.username =
|
||||
lastCred.internal.username === variables.inputs.username1
|
||||
? variables.inputs.username2
|
||||
: variables.inputs.username1;
|
||||
} else {
|
||||
newCredential.internal.username = lastCred
|
||||
? lastCred.internal.username
|
||||
: variables.inputs.username1;
|
||||
}
|
||||
}
|
||||
if (provider.template.functions.set?.pre) {
|
||||
secretRotationPreSetFn(provider.template.functions.set.pre, newCredential);
|
||||
}
|
||||
await secretRotationSetFn(provider.template.functions.set, newCredential);
|
||||
await secretRotationTestFn(provider.template.functions.test, newCredential);
|
||||
|
||||
if (variables.creds.length === 2) {
|
||||
const deleteCycleCred = variables.creds.pop();
|
||||
if (deleteCycleCred && provider.template.functions.remove) {
|
||||
const deleteCycleVar = { inputs: variables.inputs, ...deleteCycleCred };
|
||||
await secretRotationRemoveFn(provider.template.functions.remove, deleteCycleVar);
|
||||
}
|
||||
}
|
||||
variables.creds.unshift({ outputs: newCredential.outputs, internal: newCredential.internal });
|
||||
const { ciphertext, iv, tag } = client.encryptSymmetric(
|
||||
JSON.stringify(variables),
|
||||
rootEncryptionKey
|
||||
);
|
||||
|
||||
// save the rotation state
|
||||
await SecretRotation.findByIdAndUpdate(rotationStratDocId, {
|
||||
encryptedData: ciphertext,
|
||||
encryptedDataIV: iv,
|
||||
encryptedDataTag: tag,
|
||||
status: "success",
|
||||
statusMessage: "Rotated successfully",
|
||||
lastRotatedAt: new Date().toUTCString()
|
||||
});
|
||||
|
||||
const key = await BotService.getWorkspaceKeyWithBot({
|
||||
workspaceId: secretRotation.workspace
|
||||
});
|
||||
|
||||
const encryptedSecrets = secretRotation.outputs.map(({ key: outputKey, secret }) => ({
|
||||
secret,
|
||||
value: encryptSymmetric128BitHexKeyUTF8({
|
||||
plaintext:
|
||||
typeof newCredential.outputs[outputKey] === "object"
|
||||
? JSON.stringify(newCredential.outputs[outputKey])
|
||||
: String(newCredential.outputs[outputKey]),
|
||||
key
|
||||
})
|
||||
}));
|
||||
|
||||
// now save the secret do a bulk update
|
||||
// can't use the updateSecret function due to various parameter required issue
|
||||
// REFACTOR(akhilmhdh): secret module should be lot more flexible. Ability to update bulk or individually by blindIndex, by id etc
|
||||
await Secret.bulkWrite(
|
||||
encryptedSecrets.map(({ secret, value }) => ({
|
||||
updateOne: {
|
||||
filter: {
|
||||
workspace: workspaceId,
|
||||
environment: secretRotation.environment,
|
||||
_id: secret._id,
|
||||
type: SECRET_SHARED
|
||||
},
|
||||
update: {
|
||||
$inc: {
|
||||
version: 1
|
||||
},
|
||||
secretValueCiphertext: value.ciphertext,
|
||||
secretValueIV: value.iv,
|
||||
secretValueTag: value.tag
|
||||
}
|
||||
}
|
||||
}))
|
||||
);
|
||||
|
||||
await EESecretService.addSecretVersions({
|
||||
secretVersions: encryptedSecrets.map(({ secret, value }) => {
|
||||
const {
|
||||
_id,
|
||||
version,
|
||||
workspace,
|
||||
type,
|
||||
folder,
|
||||
secretBlindIndex,
|
||||
secretKeyIV,
|
||||
secretKeyTag,
|
||||
secretKeyCiphertext,
|
||||
skipMultilineEncoding,
|
||||
environment,
|
||||
algorithm,
|
||||
keyEncoding
|
||||
} = secret;
|
||||
|
||||
return new SecretVersion({
|
||||
secret: _id,
|
||||
version: version + 1,
|
||||
workspace: workspace,
|
||||
type,
|
||||
folder,
|
||||
environment,
|
||||
isDeleted: false,
|
||||
secretBlindIndex: secretBlindIndex,
|
||||
secretKeyCiphertext: secretKeyCiphertext,
|
||||
secretKeyIV: secretKeyIV,
|
||||
secretKeyTag: secretKeyTag,
|
||||
secretValueCiphertext: value.ciphertext,
|
||||
secretValueIV: value.iv,
|
||||
secretValueTag: value.tag,
|
||||
algorithm,
|
||||
keyEncoding,
|
||||
skipMultilineEncoding
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
// akhilmhdh: @tony need to do something about this as its depend on authData which is not possibile in here
|
||||
// await EEAuditLogService.createAuditLog(
|
||||
// {actor:ActorType.Machine},
|
||||
// {
|
||||
// type: EventType.UPDATE_SECRETS,
|
||||
// metadata: {
|
||||
// environment,
|
||||
// secretPath,
|
||||
// secrets: secretsToBeUpdated.map(({ _id, version, secretBlindIndex }) => ({
|
||||
// secretId: _id.toString(),
|
||||
// secretKey: secretBlindIndexToKey[secretBlindIndex || ""],
|
||||
// secretVersion: version + 1
|
||||
// }))
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// workspaceId
|
||||
// }
|
||||
// );
|
||||
|
||||
const folderId = encryptedSecrets?.[0]?.secret?.folder;
|
||||
// (EE) take a secret snapshot
|
||||
await EESecretService.takeSecretSnapshot({
|
||||
workspaceId,
|
||||
environment: secretRotation.environment,
|
||||
folderId
|
||||
});
|
||||
|
||||
await EventService.handleEvent({
|
||||
event: eventPushSecrets({
|
||||
workspaceId: secretRotation.workspace,
|
||||
environment: secretRotation.environment,
|
||||
secretPath: secretRotation.secretPath
|
||||
})
|
||||
});
|
||||
|
||||
const postHogClient = await TelemetryService.getPostHogClient();
|
||||
if (postHogClient) {
|
||||
postHogClient.capture({
|
||||
event: "secrets rotated",
|
||||
properties: {
|
||||
numberOfSecrets: encryptedSecrets.length,
|
||||
environment: secretRotation.environment,
|
||||
workspaceId,
|
||||
folderId
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
await SecretRotation.findByIdAndUpdate(rotationStratDocId, {
|
||||
status: "failed",
|
||||
statusMessage: (err as Error).message,
|
||||
lastRotatedAt: new Date().toUTCString()
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
const daysToMillisecond = (days: number) => days * 24 * 60 * 60 * 1000;
|
||||
export const startSecretRotationQueue = async (rotationDocId: string, interval: number) => {
|
||||
// when migration to bull mq just use the option immedite to trigger repeatable immediately
|
||||
secretRotationQueue.add({ rotationDocId }, { jobId: rotationDocId, removeOnComplete: true });
|
||||
return secretRotationQueue.add(
|
||||
{ rotationDocId },
|
||||
{ repeat: { every: daysToMillisecond(interval) }, jobId: rotationDocId }
|
||||
);
|
||||
};
|
||||
|
||||
export const removeSecretRotationQueue = async (rotationDocId: string, interval: number) => {
|
||||
return secretRotationQueue.removeRepeatable({ every: interval * 1000, jobId: rotationDocId });
|
||||
};
|
@ -0,0 +1,179 @@
|
||||
import axios from "axios";
|
||||
import jmespath from "jmespath";
|
||||
import { customAlphabet } from "nanoid";
|
||||
import { Client as PgClient } from "pg";
|
||||
import mysql from "mysql2";
|
||||
import {
|
||||
ISecretRotationData,
|
||||
TAssignOp,
|
||||
TDbProviderClients,
|
||||
TDbProviderFunction,
|
||||
TDirectAssignOp,
|
||||
THttpProviderFunction,
|
||||
TProviderFunction,
|
||||
TProviderFunctionTypes
|
||||
} from "../types";
|
||||
const REGEX = /\${([^}]+)}/g;
|
||||
const SLUG_ALPHABETS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
const nanoId = customAlphabet(SLUG_ALPHABETS, 10);
|
||||
|
||||
export const interpolate = (data: any, getValue: (key: string) => unknown) => {
|
||||
if (!data) return;
|
||||
|
||||
if (typeof data === "number") return data;
|
||||
|
||||
if (typeof data === "string") {
|
||||
return data.replace(REGEX, (_a, b) => getValue(b) as string);
|
||||
}
|
||||
|
||||
if (typeof data === "object" && Array.isArray(data)) {
|
||||
data.forEach((el, index) => {
|
||||
data[index] = interpolate(el, getValue);
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof data === "object") {
|
||||
if ((data as { ref: string })?.ref) return getValue((data as { ref: string }).ref);
|
||||
const temp = data as Record<string, unknown>; // for converting ts object to record type
|
||||
Object.keys(temp).forEach((key) => {
|
||||
temp[key as keyof typeof temp] = interpolate(data[key as keyof typeof temp], getValue);
|
||||
});
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const getInterpolationValue = (variables: ISecretRotationData) => (key: string) => {
|
||||
if (key.includes("|")) {
|
||||
const [keyword, ...arg] = key.split("|").map((el) => el.trim());
|
||||
switch (keyword) {
|
||||
case "random": {
|
||||
return nanoId(parseInt(arg[0], 10));
|
||||
}
|
||||
default: {
|
||||
throw Error(`Interpolation key not found - ${key}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const [type, keyName] = key.split(".").map((el) => el.trim());
|
||||
return variables[type as keyof ISecretRotationData][keyName];
|
||||
};
|
||||
|
||||
export const secretRotationHttpFn = async (
|
||||
func: THttpProviderFunction,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
// string interpolation
|
||||
const headers = interpolate(func.header, getInterpolationValue(variables));
|
||||
const url = interpolate(func.url, getInterpolationValue(variables));
|
||||
const body = interpolate(func.body, getInterpolationValue(variables));
|
||||
// axios will automatically throw error if req status is not between 2xx range
|
||||
return axios({ method: func.method, url, headers, data: body });
|
||||
};
|
||||
|
||||
export const secretRotationDbFn = async (
|
||||
func: TDbProviderFunction,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
const { type, client, pre, ...dbConnection } = func;
|
||||
const { username, password, host, database, port, query, ca } = interpolate(
|
||||
dbConnection,
|
||||
getInterpolationValue(variables)
|
||||
);
|
||||
const ssl = ca ? { rejectUnauthorized: false, ca } : undefined;
|
||||
if (host === "localhost" || host === "127.0.0.1") throw new Error("Invalid db host");
|
||||
if (client === TDbProviderClients.Pg) {
|
||||
const pgClient = new PgClient({ user: username, password, host, database, port, ssl });
|
||||
await pgClient.connect();
|
||||
const res = await pgClient.query(query);
|
||||
await pgClient.end();
|
||||
return res.rows[0];
|
||||
} else if (client === TDbProviderClients.Sql) {
|
||||
const sqlClient = mysql.createPool({
|
||||
user: username,
|
||||
password,
|
||||
host,
|
||||
database,
|
||||
port,
|
||||
connectionLimit: 1,
|
||||
ssl
|
||||
});
|
||||
const res = await new Promise((resolve, reject) => {
|
||||
sqlClient.query(query, (err, data) => {
|
||||
if (err) return reject(err);
|
||||
resolve(data);
|
||||
});
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
sqlClient.end(function (err) {
|
||||
if (err) return reject(err);
|
||||
return resolve({});
|
||||
});
|
||||
});
|
||||
return (res as any)?.[0];
|
||||
}
|
||||
};
|
||||
|
||||
export const secretRotationPreSetFn = (
|
||||
op: Record<string, TDirectAssignOp>,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
const getValFn = getInterpolationValue(variables);
|
||||
Object.entries(op || {}).forEach(([key, assignFn]) => {
|
||||
const [type, keyName] = key.split(".") as [keyof ISecretRotationData, string];
|
||||
variables[type][keyName] = interpolate(assignFn.value, getValFn);
|
||||
});
|
||||
};
|
||||
|
||||
export const secretRotationSetFn = async (
|
||||
func: TProviderFunction,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
const getValFn = getInterpolationValue(variables);
|
||||
// http setter
|
||||
if (func.type === TProviderFunctionTypes.HTTP) {
|
||||
const res = await secretRotationHttpFn(func, variables);
|
||||
Object.entries(func.setter || {}).forEach(([key, assignFn]) => {
|
||||
const [type, keyName] = key.split(".") as [keyof ISecretRotationData, string];
|
||||
if (assignFn.assign === TAssignOp.JmesPath) {
|
||||
variables[type][keyName] = jmespath.search(res.data, assignFn.path);
|
||||
} else if (assignFn.value) {
|
||||
variables[type][keyName] = interpolate(assignFn.value, getValFn);
|
||||
}
|
||||
});
|
||||
// db setter
|
||||
} else if (func.type === TProviderFunctionTypes.DB) {
|
||||
const data = await secretRotationDbFn(func, variables);
|
||||
Object.entries(func.setter || {}).forEach(([key, assignFn]) => {
|
||||
const [type, keyName] = key.split(".") as [keyof ISecretRotationData, string];
|
||||
if (assignFn.assign === TAssignOp.JmesPath) {
|
||||
if (typeof data === "object") {
|
||||
variables[type][keyName] = jmespath.search(data, assignFn.path);
|
||||
}
|
||||
} else if (assignFn.value) {
|
||||
variables[type][keyName] = interpolate(assignFn.value, getValFn);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const secretRotationTestFn = async (
|
||||
func: TProviderFunction,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
if (func.type === TProviderFunctionTypes.HTTP) {
|
||||
await secretRotationHttpFn(func, variables);
|
||||
} else if (func.type === TProviderFunctionTypes.DB) {
|
||||
await secretRotationDbFn(func, variables);
|
||||
}
|
||||
};
|
||||
|
||||
export const secretRotationRemoveFn = async (
|
||||
func: TProviderFunction,
|
||||
variables: ISecretRotationData
|
||||
) => {
|
||||
if (!func) return;
|
||||
if (func.type === TProviderFunctionTypes.HTTP) {
|
||||
// string interpolation
|
||||
return await secretRotationHttpFn(func, variables);
|
||||
}
|
||||
};
|
@ -0,0 +1,130 @@
|
||||
import { ISecretRotationEncData, TCreateSecretRotation, TGetProviderTemplates } from "./types";
|
||||
import { rotationTemplates } from "./templates";
|
||||
import { SecretRotation } from "./models";
|
||||
import { client, getEncryptionKey, getRootEncryptionKey } from "../../config";
|
||||
import { BadRequestError } from "../../utils/errors";
|
||||
import Ajv from "ajv";
|
||||
import { removeSecretRotationQueue, startSecretRotationQueue } from "./queue/queue";
|
||||
import {
|
||||
ALGORITHM_AES_256_GCM,
|
||||
ENCODING_SCHEME_BASE64,
|
||||
ENCODING_SCHEME_UTF8
|
||||
} from "../../variables";
|
||||
import { encryptSymmetric128BitHexKeyUTF8 } from "../../utils/crypto";
|
||||
|
||||
const ajv = new Ajv({ strict: false });
|
||||
|
||||
export const getProviderTemplate = async ({ workspaceId }: TGetProviderTemplates) => {
|
||||
return {
|
||||
custom: [],
|
||||
providers: rotationTemplates
|
||||
};
|
||||
};
|
||||
|
||||
export const createSecretRotation = async ({
|
||||
workspaceId,
|
||||
secretPath,
|
||||
environment,
|
||||
provider,
|
||||
interval,
|
||||
inputs,
|
||||
outputs
|
||||
}: TCreateSecretRotation) => {
|
||||
const rotationTemplate = rotationTemplates.find(({ name }) => name === provider);
|
||||
if (!rotationTemplate) throw BadRequestError({ message: "Provider not found" });
|
||||
|
||||
const formattedInputs: Record<string, unknown> = {};
|
||||
Object.entries(inputs).forEach(([key, value]) => {
|
||||
const type = rotationTemplate.template.inputs.properties[key].type;
|
||||
if (type === "string") {
|
||||
formattedInputs[key] = value;
|
||||
return;
|
||||
}
|
||||
if (type === "integer") {
|
||||
formattedInputs[key] = parseInt(value as string, 10);
|
||||
return;
|
||||
}
|
||||
formattedInputs[key] = JSON.parse(value as string);
|
||||
});
|
||||
// ensure input one follows the correct schema
|
||||
const valid = ajv.validate(rotationTemplate.template.inputs, formattedInputs);
|
||||
if (!valid) {
|
||||
throw BadRequestError({ message: ajv.errors?.[0].message });
|
||||
}
|
||||
|
||||
const encData: Partial<ISecretRotationEncData> = {
|
||||
inputs: formattedInputs,
|
||||
creds: []
|
||||
};
|
||||
|
||||
const secretRotation = new SecretRotation({
|
||||
workspace: workspaceId,
|
||||
provider,
|
||||
environment,
|
||||
secretPath,
|
||||
interval,
|
||||
outputs: Object.entries(outputs).map(([key, secret]) => ({ key, secret }))
|
||||
});
|
||||
|
||||
const encryptionKey = await getEncryptionKey();
|
||||
const rootEncryptionKey = await getRootEncryptionKey();
|
||||
|
||||
if (rootEncryptionKey) {
|
||||
const { ciphertext, iv, tag } = client.encryptSymmetric(
|
||||
JSON.stringify(encData),
|
||||
rootEncryptionKey
|
||||
);
|
||||
secretRotation.encryptedDataIV = iv;
|
||||
secretRotation.encryptedDataTag = tag;
|
||||
secretRotation.encryptedData = ciphertext;
|
||||
secretRotation.algorithm = ALGORITHM_AES_256_GCM;
|
||||
secretRotation.keyEncoding = ENCODING_SCHEME_BASE64;
|
||||
} else if (encryptionKey) {
|
||||
const { ciphertext, iv, tag } = encryptSymmetric128BitHexKeyUTF8({
|
||||
plaintext: JSON.stringify(encData),
|
||||
key: encryptionKey
|
||||
});
|
||||
secretRotation.encryptedDataIV = iv;
|
||||
secretRotation.encryptedDataTag = tag;
|
||||
secretRotation.encryptedData = ciphertext;
|
||||
secretRotation.algorithm = ALGORITHM_AES_256_GCM;
|
||||
secretRotation.keyEncoding = ENCODING_SCHEME_UTF8;
|
||||
}
|
||||
|
||||
await secretRotation.save();
|
||||
await startSecretRotationQueue(secretRotation._id.toString(), interval);
|
||||
|
||||
return secretRotation;
|
||||
};
|
||||
|
||||
export const deleteSecretRotation = async ({ id }: { id: string }) => {
|
||||
const doc = await SecretRotation.findByIdAndRemove(id);
|
||||
if (!doc) throw BadRequestError({ message: "Rotation not found" });
|
||||
|
||||
await removeSecretRotationQueue(doc._id.toString(), doc.interval);
|
||||
return doc;
|
||||
};
|
||||
|
||||
export const restartSecretRotation = async ({ id }: { id: string }) => {
|
||||
const secretRotation = await SecretRotation.findById(id);
|
||||
if (!secretRotation) throw BadRequestError({ message: "Rotation not found" });
|
||||
|
||||
await removeSecretRotationQueue(secretRotation._id.toString(), secretRotation.interval);
|
||||
await startSecretRotationQueue(secretRotation._id.toString(), secretRotation.interval);
|
||||
|
||||
return secretRotation;
|
||||
};
|
||||
|
||||
export const getSecretRotationById = async ({ id }: { id: string }) => {
|
||||
const doc = await SecretRotation.findById(id);
|
||||
if (!doc) throw BadRequestError({ message: "Rotation not found" });
|
||||
return doc;
|
||||
};
|
||||
|
||||
export const getSecretRotationOfWorkspace = async (workspaceId: string) => {
|
||||
const secretRotations = await SecretRotation.find({
|
||||
workspace: workspaceId
|
||||
}).populate("outputs.secret");
|
||||
|
||||
return secretRotations;
|
||||
};
|
@ -0,0 +1,28 @@
|
||||
import { ISecretRotationProviderTemplate } from "../types";
|
||||
import { MYSQL_TEMPLATE } from "./mysql";
|
||||
import { POSTGRES_TEMPLATE } from "./postgres";
|
||||
import { SENDGRID_TEMPLATE } from "./sendgrid";
|
||||
|
||||
export const rotationTemplates: ISecretRotationProviderTemplate[] = [
|
||||
{
|
||||
name: "sendgrid",
|
||||
title: "Twilio Sendgrid",
|
||||
image: "sendgrid.png",
|
||||
description: "Rotate Twilio Sendgrid API keys",
|
||||
template: SENDGRID_TEMPLATE
|
||||
},
|
||||
{
|
||||
name: "postgres",
|
||||
title: "PostgreSQL",
|
||||
image: "postgres.png",
|
||||
description: "Rotate PostgreSQL/CockroachDB user credentials",
|
||||
template: POSTGRES_TEMPLATE
|
||||
},
|
||||
{
|
||||
name: "mysql",
|
||||
title: "MySQL",
|
||||
image: "mysql.png",
|
||||
description: "Rotate MySQL@7/MariaDB user credentials",
|
||||
template: MYSQL_TEMPLATE
|
||||
}
|
||||
];
|
@ -0,0 +1,83 @@
|
||||
import { TAssignOp, TDbProviderClients, TProviderFunctionTypes } from "../types";
|
||||
|
||||
export const MYSQL_TEMPLATE = {
|
||||
inputs: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
admin_username: { type: "string" as const },
|
||||
admin_password: { type: "string" as const },
|
||||
host: { type: "string" as const },
|
||||
database: { type: "string" as const },
|
||||
port: { type: "integer" as const, default: "3306" },
|
||||
username1: {
|
||||
type: "string",
|
||||
default: "infisical-sql-user1",
|
||||
desc: "This user must be created in your database"
|
||||
},
|
||||
username2: {
|
||||
type: "string",
|
||||
default: "infisical-sql-user2",
|
||||
desc: "This user must be created in your database"
|
||||
},
|
||||
ca: { type: "string", desc: "SSL certificate for db auth(string)" }
|
||||
},
|
||||
required: [
|
||||
"admin_username",
|
||||
"admin_password",
|
||||
"host",
|
||||
"database",
|
||||
"username1",
|
||||
"username2",
|
||||
"port"
|
||||
],
|
||||
additionalProperties: false
|
||||
},
|
||||
outputs: {
|
||||
db_username: { type: "string" },
|
||||
db_password: { type: "string" }
|
||||
},
|
||||
internal: {
|
||||
rotated_password: { type: "string" },
|
||||
username: { type: "string" }
|
||||
},
|
||||
functions: {
|
||||
set: {
|
||||
type: TProviderFunctionTypes.DB as const,
|
||||
client: TDbProviderClients.Sql,
|
||||
username: "${inputs.admin_username}",
|
||||
password: "${inputs.admin_password}",
|
||||
host: "${inputs.host}",
|
||||
database: "${inputs.database}",
|
||||
port: "${inputs.port}",
|
||||
ca: "${inputs.ca}",
|
||||
query: "ALTER USER ${internal.username} IDENTIFIED BY '${internal.rotated_password}'",
|
||||
setter: {
|
||||
"outputs.db_username": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${internal.username}"
|
||||
},
|
||||
"outputs.db_password": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${internal.rotated_password}"
|
||||
}
|
||||
},
|
||||
pre: {
|
||||
"internal.rotated_password": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${random | 32}"
|
||||
}
|
||||
}
|
||||
},
|
||||
test: {
|
||||
type: TProviderFunctionTypes.DB as const,
|
||||
client: TDbProviderClients.Sql,
|
||||
username: "${internal.username}",
|
||||
password: "${internal.rotated_password}",
|
||||
host: "${inputs.host}",
|
||||
database: "${inputs.database}",
|
||||
port: "${inputs.port}",
|
||||
ca: "${inputs.ca}",
|
||||
query: "SELECT NOW()"
|
||||
}
|
||||
}
|
||||
};
|
@ -0,0 +1,83 @@
|
||||
import { TAssignOp, TDbProviderClients, TProviderFunctionTypes } from "../types";
|
||||
|
||||
export const POSTGRES_TEMPLATE = {
|
||||
inputs: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
admin_username: { type: "string" as const },
|
||||
admin_password: { type: "string" as const },
|
||||
host: { type: "string" as const },
|
||||
database: { type: "string" as const },
|
||||
port: { type: "integer" as const, default: "5432" },
|
||||
username1: {
|
||||
type: "string",
|
||||
default: "infisical-pg-user1",
|
||||
desc: "This user must be created in your database"
|
||||
},
|
||||
username2: {
|
||||
type: "string",
|
||||
default: "infisical-pg-user2",
|
||||
desc: "This user must be created in your database"
|
||||
},
|
||||
ca: { type: "string", desc: "SSL certificate for db auth(string)" }
|
||||
},
|
||||
required: [
|
||||
"admin_username",
|
||||
"admin_password",
|
||||
"host",
|
||||
"database",
|
||||
"username1",
|
||||
"username2",
|
||||
"port"
|
||||
],
|
||||
additionalProperties: false
|
||||
},
|
||||
outputs: {
|
||||
db_username: { type: "string" },
|
||||
db_password: { type: "string" }
|
||||
},
|
||||
internal: {
|
||||
rotated_password: { type: "string" },
|
||||
username: { type: "string" }
|
||||
},
|
||||
functions: {
|
||||
set: {
|
||||
type: TProviderFunctionTypes.DB as const,
|
||||
client: TDbProviderClients.Pg,
|
||||
username: "${inputs.admin_username}",
|
||||
password: "${inputs.admin_password}",
|
||||
host: "${inputs.host}",
|
||||
database: "${inputs.database}",
|
||||
port: "${inputs.port}",
|
||||
ca: "${inputs.ca}",
|
||||
query: "ALTER USER ${internal.username} WITH PASSWORD '${internal.rotated_password}'",
|
||||
setter: {
|
||||
"outputs.db_username": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${internal.username}"
|
||||
},
|
||||
"outputs.db_password": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${internal.rotated_password}"
|
||||
}
|
||||
},
|
||||
pre: {
|
||||
"internal.rotated_password": {
|
||||
assign: TAssignOp.Direct as const,
|
||||
value: "${random | 32}"
|
||||
}
|
||||
}
|
||||
},
|
||||
test: {
|
||||
type: TProviderFunctionTypes.DB as const,
|
||||
client: TDbProviderClients.Pg,
|
||||
username: "${internal.username}",
|
||||
password: "${internal.rotated_password}",
|
||||
host: "${inputs.host}",
|
||||
database: "${inputs.database}",
|
||||
port: "${inputs.port}",
|
||||
ca: "${inputs.ca}",
|
||||
query: "SELECT NOW()"
|
||||
}
|
||||
}
|
||||
};
|
@ -0,0 +1,63 @@
|
||||
import { TAssignOp, TProviderFunctionTypes } from "../types";
|
||||
|
||||
export const SENDGRID_TEMPLATE = {
|
||||
inputs: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
admin_api_key: { type: "string" as const, desc: "Sendgrid admin api key to create new keys" },
|
||||
api_key_scopes: {
|
||||
type: "array",
|
||||
items: { type: "string" as const },
|
||||
desc: "Scopes for created tokens by rotation(Array)"
|
||||
}
|
||||
},
|
||||
required: ["admin_api_key", "api_key_scopes"],
|
||||
additionalProperties: false
|
||||
},
|
||||
outputs: {
|
||||
api_key: { type: "string" }
|
||||
},
|
||||
internal: {
|
||||
api_key_id: { type: "string" }
|
||||
},
|
||||
functions: {
|
||||
set: {
|
||||
type: TProviderFunctionTypes.HTTP as const,
|
||||
url: "https://api.sendgrid.com/v3/api_keys",
|
||||
method: "POST",
|
||||
header: {
|
||||
Authorization: "Bearer ${inputs.admin_api_key}"
|
||||
},
|
||||
body: {
|
||||
name: "infisical-${random | 16}",
|
||||
scopes: { ref: "inputs.api_key_scopes" }
|
||||
},
|
||||
setter: {
|
||||
"outputs.api_key": {
|
||||
assign: TAssignOp.JmesPath as const,
|
||||
path: "api_key"
|
||||
},
|
||||
"internal.api_key_id": {
|
||||
assign: TAssignOp.JmesPath as const,
|
||||
path: "api_key_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
remove: {
|
||||
type: TProviderFunctionTypes.HTTP as const,
|
||||
url: "https://api.sendgrid.com/v3/api_keys/${internal.api_key_id}",
|
||||
header: {
|
||||
Authorization: "Bearer ${inputs.admin_api_key}"
|
||||
},
|
||||
method: "DELETE"
|
||||
},
|
||||
test: {
|
||||
type: TProviderFunctionTypes.HTTP as const,
|
||||
url: "https://api.sendgrid.com/v3/api_keys/${internal.api_key_id}",
|
||||
header: {
|
||||
Authorization: "Bearer ${inputs.admin_api_key}"
|
||||
},
|
||||
method: "GET"
|
||||
}
|
||||
}
|
||||
};
|
@ -0,0 +1,131 @@
|
||||
import { Document, Types } from "mongoose";
|
||||
|
||||
export interface ISecretRotation extends Document {
|
||||
_id: Types.ObjectId;
|
||||
name: string;
|
||||
interval: number;
|
||||
provider: string;
|
||||
customProvider: Types.ObjectId;
|
||||
workspace: Types.ObjectId;
|
||||
environment: string;
|
||||
secretPath: string;
|
||||
outputs: Array<{
|
||||
key: string;
|
||||
secret: Types.ObjectId;
|
||||
}>;
|
||||
status?: "success" | "failed";
|
||||
lastRotatedAt?: string;
|
||||
statusMessage?: string;
|
||||
encryptedData: string;
|
||||
encryptedDataIV: string;
|
||||
encryptedDataTag: string;
|
||||
algorithm: string;
|
||||
keyEncoding: string;
|
||||
}
|
||||
|
||||
export type ISecretRotationEncData = {
|
||||
inputs: Record<string, unknown>;
|
||||
creds: Array<{
|
||||
outputs: Record<string, unknown>;
|
||||
internal: Record<string, unknown>;
|
||||
}>;
|
||||
};
|
||||
|
||||
export type ISecretRotationData = {
|
||||
inputs: Record<string, unknown>;
|
||||
outputs: Record<string, unknown>;
|
||||
internal: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type ISecretRotationProviderTemplate = {
|
||||
name: string;
|
||||
title: string;
|
||||
image?: string;
|
||||
description?: string;
|
||||
template: TProviderTemplate;
|
||||
};
|
||||
|
||||
export enum TProviderFunctionTypes {
|
||||
HTTP = "http",
|
||||
DB = "database"
|
||||
}
|
||||
|
||||
export enum TDbProviderClients {
|
||||
// postgres, cockroack db, amazon red shift
|
||||
Pg = "pg",
|
||||
// mysql and maria db
|
||||
Sql = "sql"
|
||||
}
|
||||
|
||||
export enum TAssignOp {
|
||||
Direct = "direct",
|
||||
JmesPath = "jmesopath"
|
||||
}
|
||||
|
||||
export type TJmesPathAssignOp = {
|
||||
assign: TAssignOp.JmesPath;
|
||||
path: string;
|
||||
};
|
||||
|
||||
export type TDirectAssignOp = {
|
||||
assign: TAssignOp.Direct;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type TAssignFunction = TJmesPathAssignOp | TDirectAssignOp;
|
||||
|
||||
export type THttpProviderFunction = {
|
||||
type: TProviderFunctionTypes.HTTP;
|
||||
url: string;
|
||||
method: string;
|
||||
header?: Record<string, string>;
|
||||
query?: Record<string, string>;
|
||||
body?: Record<string, unknown>;
|
||||
setter?: Record<string, TAssignFunction>;
|
||||
pre?: Record<string, TDirectAssignOp>;
|
||||
};
|
||||
|
||||
export type TDbProviderFunction = {
|
||||
type: TProviderFunctionTypes.DB;
|
||||
client: TDbProviderClients;
|
||||
username: string;
|
||||
password: string;
|
||||
host: string;
|
||||
database: string;
|
||||
port: string;
|
||||
query: string;
|
||||
setter?: Record<string, TAssignFunction>;
|
||||
pre?: Record<string, TDirectAssignOp>;
|
||||
};
|
||||
|
||||
export type TProviderFunction = THttpProviderFunction | TDbProviderFunction;
|
||||
|
||||
export type TProviderTemplate = {
|
||||
inputs: {
|
||||
type: "object";
|
||||
properties: Record<string, { type: string; [x: string]: unknown; desc?: string }>;
|
||||
required?: string[];
|
||||
};
|
||||
outputs: Record<string, unknown>;
|
||||
functions: {
|
||||
set: TProviderFunction;
|
||||
remove?: TProviderFunction;
|
||||
test: TProviderFunction;
|
||||
};
|
||||
};
|
||||
|
||||
// function type args
|
||||
export type TGetProviderTemplates = {
|
||||
workspaceId: string;
|
||||
};
|
||||
|
||||
export type TCreateSecretRotation = {
|
||||
provider: string;
|
||||
customProvider?: string;
|
||||
workspaceId: string;
|
||||
secretPath: string;
|
||||
environment: string;
|
||||
interval: number;
|
||||
inputs: Record<string, unknown>;
|
||||
outputs: Record<string, string>;
|
||||
};
|
@ -1,91 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import {
|
||||
IAction,
|
||||
} from "../models";
|
||||
import {
|
||||
createLogHelper,
|
||||
} from "../helpers/log";
|
||||
import {
|
||||
createActionHelper,
|
||||
} from "../helpers/action";
|
||||
import EELicenseService from "./EELicenseService";
|
||||
|
||||
/**
|
||||
* Class to handle Enterprise Edition log actions
|
||||
*/
|
||||
class EELogService {
|
||||
/**
|
||||
* Create an (audit) log
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.userId - id of user associated with the log
|
||||
* @param {String} obj.workspaceId - id of workspace associated with the log
|
||||
* @param {Action} obj.actions - actions to include in log
|
||||
* @param {String} obj.channel - channel (web/cli/auto) associated with the log
|
||||
* @param {String} obj.ipAddress - ip address associated with the log
|
||||
* @returns {Log} log - new audit log
|
||||
*/
|
||||
static async createLog({
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
actions,
|
||||
channel,
|
||||
ipAddress,
|
||||
}: {
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId?: Types.ObjectId;
|
||||
actions: IAction[];
|
||||
channel: string;
|
||||
ipAddress: string;
|
||||
}) {
|
||||
if (!EELicenseService.isLicenseValid) return null;
|
||||
return await createLogHelper({
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
actions,
|
||||
channel,
|
||||
ipAddress,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an (audit) action
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.name - name of action
|
||||
* @param {Types.ObjectId} obj.userId - id of user associated with the action
|
||||
* @param {Types.ObjectId} obj.workspaceId - id of workspace associated with the action
|
||||
* @param {ObjectId[]} obj.secretIds - ids of secrets associated with the action
|
||||
* @returns {Action} action - new action
|
||||
*/
|
||||
static async createAction({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
}: {
|
||||
name: string;
|
||||
userId?: Types.ObjectId;
|
||||
serviceAccountId?: Types.ObjectId;
|
||||
serviceTokenDataId?: Types.ObjectId;
|
||||
workspaceId?: Types.ObjectId;
|
||||
secretIds?: Types.ObjectId[];
|
||||
}) {
|
||||
return await createActionHelper({
|
||||
name,
|
||||
userId,
|
||||
serviceAccountId,
|
||||
serviceTokenDataId,
|
||||
workspaceId,
|
||||
secretIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default EELogService;
|
@ -1,13 +1,11 @@
|
||||
import EELicenseService from "./EELicenseService";
|
||||
import EESecretService from "./EESecretService";
|
||||
import EELogService from "./EELogService";
|
||||
import EEAuditLogService from "./EEAuditLogService";
|
||||
import GithubSecretScanningService from "./GithubSecretScanning/GithubSecretScanningService"
|
||||
|
||||
export {
|
||||
EELicenseService,
|
||||
EESecretService,
|
||||
EELogService,
|
||||
EEAuditLogService,
|
||||
GithubSecretScanningService
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const createSecretRotationV1 = z.object({
|
||||
body: z.object({
|
||||
workspaceId: z.string().trim(),
|
||||
secretPath: z.string().trim(),
|
||||
environment: z.string().trim(),
|
||||
interval: z.number().min(1),
|
||||
provider: z.string().trim(),
|
||||
customProvider: z.string().trim().optional(),
|
||||
inputs: z.record(z.unknown()),
|
||||
outputs: z.record(z.string())
|
||||
})
|
||||
});
|
||||
|
||||
export const restartSecretRotationV1 = z.object({
|
||||
body: z.object({
|
||||
id: z.string().trim()
|
||||
})
|
||||
});
|
||||
|
||||
export const getSecretRotationV1 = z.object({
|
||||
query: z.object({
|
||||
workspaceId: z.string().trim()
|
||||
})
|
||||
});
|
||||
|
||||
export const removeSecretRotationV1 = z.object({
|
||||
params: z.object({
|
||||
id: z.string().trim()
|
||||
})
|
||||
});
|
@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const getSecretRotationProvidersV1 = z.object({
|
||||
params: z.object({
|
||||
workspaceId: z.string()
|
||||
})
|
||||
});
|
File diff suppressed because it is too large
Load Diff
@ -1,39 +1,27 @@
|
||||
import { Types } from "mongoose";
|
||||
import {
|
||||
IServiceTokenData,
|
||||
IServiceTokenDataV3,
|
||||
IUser,
|
||||
} from "../../models";
|
||||
import {
|
||||
ServiceActor,
|
||||
ServiceActorV3,
|
||||
UserActor,
|
||||
UserAgentType
|
||||
} from "../../ee/models";
|
||||
import { IServiceTokenData, IServiceTokenDataV3, IUser } from "../../models";
|
||||
import { ServiceActor, ServiceActorV3, UserActor, UserAgentType } from "../../ee/models";
|
||||
|
||||
interface BaseAuthData {
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
userAgentType: UserAgentType;
|
||||
tokenVersionId?: Types.ObjectId;
|
||||
ipAddress: string;
|
||||
userAgent: string;
|
||||
userAgentType: UserAgentType;
|
||||
tokenVersionId?: Types.ObjectId;
|
||||
}
|
||||
|
||||
export interface UserAuthData extends BaseAuthData {
|
||||
actor: UserActor;
|
||||
authPayload: IUser;
|
||||
actor: UserActor;
|
||||
authPayload: IUser;
|
||||
}
|
||||
|
||||
export interface ServiceTokenV3AuthData extends BaseAuthData {
|
||||
actor: ServiceActorV3;
|
||||
authPayload: IServiceTokenDataV3;
|
||||
actor: ServiceActorV3;
|
||||
authPayload: IServiceTokenDataV3;
|
||||
}
|
||||
|
||||
export interface ServiceTokenAuthData extends BaseAuthData {
|
||||
actor: ServiceActor;
|
||||
authPayload: IServiceTokenData;
|
||||
actor: ServiceActor;
|
||||
authPayload: IServiceTokenData;
|
||||
}
|
||||
|
||||
export type AuthData =
|
||||
| UserAuthData
|
||||
| ServiceTokenV3AuthData
|
||||
| ServiceTokenAuthData;
|
||||
export type AuthData = UserAuthData | ServiceTokenV3AuthData | ServiceTokenAuthData;
|
||||
|
@ -1,7 +0,0 @@
|
||||
interface AddServiceAccountPermissionDto {
|
||||
name: string;
|
||||
workspaceId?: string;
|
||||
environment?: string;
|
||||
}
|
||||
|
||||
export default AddServiceAccountPermissionDto;
|
@ -1,8 +0,0 @@
|
||||
interface CreateServiceAccountDto {
|
||||
organizationId: string;
|
||||
name: string;
|
||||
publicKey: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
export default CreateServiceAccountDto;
|
@ -1,7 +0,0 @@
|
||||
import CreateServiceAccountDto from "./CreateServiceAccountDto";
|
||||
import AddServiceAccountPermissionDto from "./AddServiceAccountPermissionDto";
|
||||
|
||||
export {
|
||||
CreateServiceAccountDto,
|
||||
AddServiceAccountPermissionDto,
|
||||
}
|
@ -1,43 +1,27 @@
|
||||
import requireAuth from "./requireAuth";
|
||||
import requireMfaAuth from "./requireMfaAuth";
|
||||
import requireBotAuth from "./requireBotAuth";
|
||||
import requireSignupAuth from "./requireSignupAuth";
|
||||
import requireWorkspaceAuth from "./requireWorkspaceAuth";
|
||||
import requireMembershipAuth from "./requireMembershipAuth";
|
||||
import requireMembershipOrgAuth from "./requireMembershipOrgAuth";
|
||||
import requireOrganizationAuth from "./requireOrganizationAuth";
|
||||
import requireIntegrationAuth from "./requireIntegrationAuth";
|
||||
import requireIntegrationAuthorizationAuth from "./requireIntegrationAuthorizationAuth";
|
||||
import requireServiceTokenAuth from "./requireServiceTokenAuth";
|
||||
import requireServiceTokenDataAuth from "./requireServiceTokenDataAuth";
|
||||
import requireServiceAccountAuth from "./requireServiceAccountAuth";
|
||||
import requireServiceAccountWorkspacePermissionAuth from "./requireServiceAccountWorkspacePermissionAuth";
|
||||
import requireSecretAuth from "./requireSecretAuth";
|
||||
import requireSecretsAuth from "./requireSecretsAuth";
|
||||
import requireBlindIndicesEnabled from "./requireBlindIndicesEnabled";
|
||||
import requireE2EEOff from "./requireE2EEOff";
|
||||
import requireIPAllowlistCheck from "./requireIPAllowlistCheck";
|
||||
import { requireSuperAdminAccess } from "./requireSuperAdminAccess";
|
||||
import validateRequest from "./validateRequest";
|
||||
import { disableSignUpByServerCfg } from "./serverAdmin";
|
||||
|
||||
export {
|
||||
requireAuth,
|
||||
requireMfaAuth,
|
||||
requireBotAuth,
|
||||
requireSignupAuth,
|
||||
requireWorkspaceAuth,
|
||||
requireMembershipAuth,
|
||||
requireMembershipOrgAuth,
|
||||
requireOrganizationAuth,
|
||||
requireIntegrationAuth,
|
||||
requireIntegrationAuthorizationAuth,
|
||||
requireServiceTokenAuth,
|
||||
requireServiceTokenDataAuth,
|
||||
requireServiceAccountAuth,
|
||||
requireServiceAccountWorkspacePermissionAuth,
|
||||
requireSecretAuth,
|
||||
requireSecretsAuth,
|
||||
requireBlindIndicesEnabled,
|
||||
requireE2EEOff,
|
||||
requireIPAllowlistCheck,
|
||||
validateRequest,
|
||||
requireAuth,
|
||||
requireMfaAuth,
|
||||
requireSignupAuth,
|
||||
requireWorkspaceAuth,
|
||||
requireServiceTokenAuth,
|
||||
requireSecretAuth,
|
||||
requireSecretsAuth,
|
||||
requireBlindIndicesEnabled,
|
||||
requireE2EEOff,
|
||||
validateRequest,
|
||||
requireSuperAdminAccess,
|
||||
disableSignUpByServerCfg
|
||||
};
|
||||
|
@ -1,27 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { validateClientForBot } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
const requireBotAuth = ({
|
||||
acceptedRoles,
|
||||
locationBotId = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"admin" | "member">;
|
||||
locationBotId?: req;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { botId } = req[locationBotId];
|
||||
|
||||
req.bot = await validateClientForBot({
|
||||
authData: req.authData,
|
||||
botId: new Types.ObjectId(botId),
|
||||
acceptedRoles,
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireBotAuth;
|
@ -1,55 +0,0 @@
|
||||
import net from "net";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { UnauthorizedRequestError } from "../utils/errors";
|
||||
import { extractIPDetails } from "../utils/ip";
|
||||
import { ActorType, TrustedIP } from "../ee/models";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
/**
|
||||
* Validate if workspace with [workspaceId] has E2EE off/disabled
|
||||
* @param {Object} obj
|
||||
* @param {String} obj.locationWorkspaceId - location of [workspaceId] on request (e.g. params, body) for parsing
|
||||
* @returns
|
||||
*/
|
||||
const requireIPAllowlistCheck = ({
|
||||
locationWorkspaceId
|
||||
}: {
|
||||
locationWorkspaceId: req;
|
||||
}) => {
|
||||
return async (req: Request, _: Response, next: NextFunction) => {
|
||||
const workspaceId = req[locationWorkspaceId]?.workspaceId;
|
||||
|
||||
if (req.authData.actor.type === ActorType.SERVICE) {
|
||||
const trustedIps = await TrustedIP.find({
|
||||
workspace: workspaceId
|
||||
});
|
||||
|
||||
if (trustedIps.length > 0) {
|
||||
// case: check the IP address of the inbound request against trusted IPs
|
||||
|
||||
const blockList = new net.BlockList();
|
||||
|
||||
for (const trustedIp of trustedIps) {
|
||||
if (trustedIp.prefix !== undefined) {
|
||||
blockList.addSubnet(trustedIp.ipAddress, trustedIp.prefix, trustedIp.type);
|
||||
} else {
|
||||
blockList.addAddress(trustedIp.ipAddress, trustedIp.type);
|
||||
}
|
||||
}
|
||||
|
||||
const { type } = extractIPDetails(req.authData.ipAddress);
|
||||
const check = blockList.check(req.authData.ipAddress, type);
|
||||
|
||||
if (!check)
|
||||
throw UnauthorizedRequestError({
|
||||
message: "Failed workspace authorization"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireIPAllowlistCheck;
|
@ -1,37 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { validateClientForIntegration } from "../validation";
|
||||
|
||||
/**
|
||||
* Validate if user on request is a member of workspace with proper roles associated
|
||||
* with the integration on request params.
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted workspace roles
|
||||
*/
|
||||
const requireIntegrationAuth = ({
|
||||
acceptedRoles,
|
||||
}: {
|
||||
acceptedRoles: Array<"admin" | "member">;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { integrationId } = req.params;
|
||||
|
||||
const { integration, accessToken } = await validateClientForIntegration({
|
||||
authData: req.authData,
|
||||
integrationId: new Types.ObjectId(integrationId),
|
||||
acceptedRoles,
|
||||
});
|
||||
|
||||
if (integration) {
|
||||
req.integration = integration;
|
||||
}
|
||||
|
||||
if (accessToken) {
|
||||
req.accessToken = accessToken;
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
};
|
||||
|
||||
export default requireIntegrationAuth;
|
@ -1,49 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { validateClientForIntegrationAuth } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
/**
|
||||
* Validate if user on request is a member of workspace with proper roles associated
|
||||
* with the integration authorization on request params.
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted workspace roles
|
||||
* @param {Boolean} obj.attachAccessToken - whether or not to decrypt and attach integration authorization access token onto request
|
||||
*/
|
||||
const requireIntegrationAuthorizationAuth = ({
|
||||
acceptedRoles,
|
||||
attachAccessToken = true,
|
||||
location = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"admin" | "member">;
|
||||
attachAccessToken?: boolean;
|
||||
location?: req;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { integrationAuthId } = req[location];
|
||||
|
||||
const { integrationAuth, accessToken, accessId } = await validateClientForIntegrationAuth({
|
||||
authData: req.authData,
|
||||
integrationAuthId: new Types.ObjectId(integrationAuthId),
|
||||
acceptedRoles,
|
||||
attachAccessToken,
|
||||
});
|
||||
|
||||
if (integrationAuth) {
|
||||
req.integrationAuth = integrationAuth;
|
||||
}
|
||||
|
||||
if (accessToken) {
|
||||
req.accessToken = accessToken;
|
||||
}
|
||||
|
||||
if (accessId) {
|
||||
req.accessId = accessId;
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
};
|
||||
|
||||
export default requireIntegrationAuthorizationAuth;
|
@ -1,38 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { validateClientForMembership } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
/**
|
||||
* Validate membership with id [membershipId] and that user with id
|
||||
* [req.user._id] can modify that membership.
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted workspace roles
|
||||
* @param {String[]} obj.location - location of [workspaceId] on request (e.g. params, body) for parsing
|
||||
*/
|
||||
const requireMembershipAuth = ({
|
||||
acceptedRoles,
|
||||
locationMembershipId = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"admin" | "member">;
|
||||
locationMembershipId: req
|
||||
}) => {
|
||||
return async (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
const { membershipId } = req[locationMembershipId];
|
||||
|
||||
req.targetMembership = await validateClientForMembership({
|
||||
authData: req.authData,
|
||||
membershipId: new Types.ObjectId(membershipId),
|
||||
acceptedRoles,
|
||||
});
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireMembershipAuth;
|
@ -1,37 +0,0 @@
|
||||
import { Types } from "mongoose";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { validateClientForMembershipOrg } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
/**
|
||||
* Validate (organization) membership id [membershipId] and that user with id
|
||||
* [req.user._id] can modify that membership.
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted organization roles
|
||||
* @param {String[]} obj.location - location of [membershipId] on request (e.g. params, body) for parsing
|
||||
*/
|
||||
const requireMembershipOrgAuth = ({
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
locationMembershipOrgId = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"owner" | "admin" | "member">;
|
||||
acceptedStatuses: Array<"invited" | "accepted">;
|
||||
locationMembershipOrgId?: req;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { membershipId } = req[locationMembershipOrgId];
|
||||
|
||||
req.membershipOrg = await validateClientForMembershipOrg({
|
||||
authData: req.authData,
|
||||
membershipOrgId: new Types.ObjectId(membershipId),
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
});
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireMembershipOrgAuth;
|
@ -1,45 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { validateClientForOrganization } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
/**
|
||||
* Validate if user on request is a member with proper roles for organization
|
||||
* on request params.
|
||||
* @param {Object} obj
|
||||
* @param {String[]} obj.acceptedRoles - accepted organization roles
|
||||
* @param {String[]} obj.accepteStatuses - accepted organization statuses
|
||||
*/
|
||||
const requireOrganizationAuth = ({
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
locationOrganizationId = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"owner" | "admin" | "member">;
|
||||
acceptedStatuses: Array<"invited" | "accepted">;
|
||||
locationOrganizationId?: req;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { organizationId } = req[locationOrganizationId];
|
||||
|
||||
const { organization, membershipOrg } = await validateClientForOrganization({
|
||||
authData: req.authData,
|
||||
organizationId: new Types.ObjectId(organizationId),
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
});
|
||||
|
||||
if (organization) {
|
||||
req.organization = organization;
|
||||
}
|
||||
|
||||
if (membershipOrg) {
|
||||
req.membershipOrg = membershipOrg;
|
||||
}
|
||||
|
||||
return next();
|
||||
};
|
||||
};
|
||||
|
||||
export default requireOrganizationAuth;
|
@ -1,31 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { validateClientForServiceAccount } from "../validation";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
const requireServiceAccountAuth = ({
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
locationServiceAccountId = "params",
|
||||
requiredPermissions = [],
|
||||
}: {
|
||||
acceptedRoles: string[];
|
||||
acceptedStatuses: string[];
|
||||
locationServiceAccountId?: req;
|
||||
requiredPermissions?: string[];
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const serviceAccountId = req[locationServiceAccountId].serviceAccountId;
|
||||
|
||||
req.serviceAccount = await validateClientForServiceAccount({
|
||||
authData: req.authData,
|
||||
serviceAccountId: new Types.ObjectId(serviceAccountId),
|
||||
requiredPermissions,
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireServiceAccountAuth;
|
@ -1,52 +0,0 @@
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { ServiceAccount, ServiceAccountWorkspacePermission } from "../models";
|
||||
import {
|
||||
ServiceAccountNotFoundError,
|
||||
} from "../utils/errors";
|
||||
import {
|
||||
validateMembershipOrg,
|
||||
} from "../helpers/membershipOrg";
|
||||
|
||||
type req = "params" | "body" | "query";
|
||||
|
||||
const requireServiceAccountWorkspacePermissionAuth = ({
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
location = "params",
|
||||
}: {
|
||||
acceptedRoles: Array<"owner" | "admin" | "member">;
|
||||
acceptedStatuses: Array<"invited" | "accepted">;
|
||||
location?: req;
|
||||
}) => {
|
||||
return async (req: Request, res: Response, next: NextFunction) => {
|
||||
const serviceAccountWorkspacePermissionId = req[location].serviceAccountWorkspacePermissionId;
|
||||
const serviceAccountWorkspacePermission = await ServiceAccountWorkspacePermission.findById(serviceAccountWorkspacePermissionId);
|
||||
|
||||
if (!serviceAccountWorkspacePermission) {
|
||||
return next(ServiceAccountNotFoundError({ message: "Failed to locate Service Account workspace permission" }));
|
||||
}
|
||||
|
||||
const serviceAccount = await ServiceAccount.findById(serviceAccountWorkspacePermission.serviceAccount);
|
||||
|
||||
if (!serviceAccount) {
|
||||
return next(ServiceAccountNotFoundError({ message: "Failed to locate Service Account" }));
|
||||
}
|
||||
|
||||
if (serviceAccount.user.toString() !== req.user.id.toString()) {
|
||||
// case: creator of the service account is different from
|
||||
// the user on the request -> apply middleware role/status validation
|
||||
await validateMembershipOrg({
|
||||
userId: req.user._id,
|
||||
organizationId: serviceAccount.organization,
|
||||
acceptedRoles,
|
||||
acceptedStatuses,
|
||||
});
|
||||
}
|
||||
|
||||
req.serviceAccount = serviceAccount;
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
export default requireServiceAccountWorkspacePermissionAuth;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue