mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-15 02:51:51 +00:00
Restructure MIs to more generic Identity
This commit is contained in:
@@ -0,0 +1,324 @@
|
||||
import { Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import {
|
||||
IIdentity,
|
||||
Identity,
|
||||
IdentityAccessToken,
|
||||
IdentityMembership,
|
||||
IdentityMembershipOrg,
|
||||
IdentityUniversalAuth,
|
||||
IdentityUniversalAuthClientSecret,
|
||||
Organization
|
||||
} from "../../../models";
|
||||
import {
|
||||
EventType,
|
||||
IRole,
|
||||
Role
|
||||
} from "../../models";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import * as reqValidator from "../../../validation/identities";
|
||||
import {
|
||||
getAuthDataOrgPermissions,
|
||||
getOrgRolePermissions,
|
||||
isAtLeastAsPrivilegedOrg
|
||||
} from "../../services/RoleService";
|
||||
import {
|
||||
BadRequestError,
|
||||
ForbiddenRequestError,
|
||||
ResourceNotFoundError,
|
||||
} from "../../../utils/errors";
|
||||
import { ADMIN, CUSTOM, MEMBER, NO_ACCESS } from "../../../variables";
|
||||
import {
|
||||
OrgPermissionActions,
|
||||
OrgPermissionSubjects
|
||||
} from "../../services/RoleService";
|
||||
import { EEAuditLogService } from "../../services";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
|
||||
/**
|
||||
* Create identity
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const createIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
name,
|
||||
organizationId,
|
||||
role
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateIdentityV1, req);
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: new Types.ObjectId(organizationId)
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Create,
|
||||
OrgPermissionSubjects.Identity
|
||||
);
|
||||
|
||||
const rolePermission = await getOrgRolePermissions(role, organizationId);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to create a more privileged identity"
|
||||
});
|
||||
|
||||
const organization = await Organization.findById(organizationId);
|
||||
if (!organization) throw BadRequestError({ message: `Organization with id ${organizationId} not found` });
|
||||
|
||||
const isCustomRole = ![ADMIN, MEMBER, NO_ACCESS].includes(role);
|
||||
|
||||
let customRole;
|
||||
if (isCustomRole) {
|
||||
customRole = await Role.findOne({
|
||||
slug: role,
|
||||
isOrgRole: true,
|
||||
organization: new Types.ObjectId(organizationId)
|
||||
});
|
||||
|
||||
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||
}
|
||||
|
||||
const identity = await new Identity({
|
||||
name
|
||||
}).save();
|
||||
|
||||
await new IdentityMembershipOrg({
|
||||
identity: identity._id,
|
||||
organization: new Types.ObjectId(organizationId),
|
||||
role: isCustomRole ? CUSTOM : role,
|
||||
customRole
|
||||
}).save();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.CREATE_IDENTITY,
|
||||
metadata: {
|
||||
identityId: identity._id.toString(),
|
||||
name
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: new Types.ObjectId(organizationId)
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
identity
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update identity with id [identityId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const updateIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { identityId },
|
||||
body: {
|
||||
name,
|
||||
role
|
||||
}
|
||||
} = await validateRequest(reqValidator.UpdateIdentityV1, req);
|
||||
|
||||
const identityMembershipOrg = await IdentityMembershipOrg
|
||||
.findOne({
|
||||
identity: new Types.ObjectId(identityId)
|
||||
})
|
||||
.populate<{
|
||||
identity: IIdentity,
|
||||
customRole: IRole
|
||||
}>("identity customRole");
|
||||
|
||||
if (!identityMembershipOrg) throw ResourceNotFoundError({
|
||||
message: `Failed to find identity with id ${identityId}`
|
||||
});
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: identityMembershipOrg.organization
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Edit,
|
||||
OrgPermissionSubjects.Identity
|
||||
);
|
||||
|
||||
const identityRolePermission = await getOrgRolePermissions(
|
||||
identityMembershipOrg?.customRole?.slug ?? identityMembershipOrg.role,
|
||||
identityMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, identityRolePermission);
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to update more privileged identity"
|
||||
});
|
||||
|
||||
if (role) {
|
||||
const rolePermission = await getOrgRolePermissions(role, identityMembershipOrg.organization.toString());
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to update identity to a more privileged role"
|
||||
});
|
||||
}
|
||||
|
||||
let customRole;
|
||||
if (role) {
|
||||
const isCustomRole = ![ADMIN, MEMBER, NO_ACCESS].includes(role);
|
||||
if (isCustomRole) {
|
||||
customRole = await Role.findOne({
|
||||
slug: role,
|
||||
isOrgRole: true,
|
||||
organization: identityMembershipOrg.organization
|
||||
});
|
||||
|
||||
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||
}
|
||||
}
|
||||
|
||||
const identity = await Identity.findByIdAndUpdate(
|
||||
identityId,
|
||||
{
|
||||
name,
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!identity) throw BadRequestError({
|
||||
message: `Failed to update identity with id ${identityId}`
|
||||
});
|
||||
|
||||
await IdentityMembershipOrg.findOneAndUpdate(
|
||||
{
|
||||
identity: identity._id
|
||||
},
|
||||
{
|
||||
role: customRole ? CUSTOM : role,
|
||||
...(customRole ? {
|
||||
customRole
|
||||
} : {}),
|
||||
...(role && !customRole ? { // non-custom role
|
||||
$unset: {
|
||||
customRole: 1
|
||||
}
|
||||
} : {})
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.UPDATE_IDENTITY,
|
||||
metadata: {
|
||||
identityId: identity._id.toString(),
|
||||
name: identity.name,
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: identityMembershipOrg.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
identity
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete identity with id [identityId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const deleteIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { identityId }
|
||||
} = await validateRequest(reqValidator.DeleteIdentityV1, req);
|
||||
|
||||
const identityMembershipOrg = await IdentityMembershipOrg
|
||||
.findOne({
|
||||
identity: new Types.ObjectId(identityId)
|
||||
})
|
||||
.populate<{
|
||||
identity: IIdentity,
|
||||
customRole: IRole
|
||||
}>("identity customRole");
|
||||
|
||||
if (!identityMembershipOrg) throw ResourceNotFoundError({
|
||||
message: `Failed to find identity with id ${identityId}`
|
||||
});
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: identityMembershipOrg.organization
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Delete,
|
||||
OrgPermissionSubjects.Identity
|
||||
);
|
||||
|
||||
const identityRolePermission = await getOrgRolePermissions(
|
||||
identityMembershipOrg?.customRole?.slug ?? identityMembershipOrg.role,
|
||||
identityMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, identityRolePermission);
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to delete more privileged identity"
|
||||
});
|
||||
|
||||
const identity = await Identity.findByIdAndDelete(identityMembershipOrg.identity);
|
||||
if (!identity) throw ResourceNotFoundError({
|
||||
message: `Identity with id ${identityId} not found`
|
||||
});
|
||||
|
||||
await IdentityMembershipOrg.findByIdAndDelete(identityMembershipOrg._id);
|
||||
|
||||
await IdentityMembership.deleteMany({
|
||||
identity: identityMembershipOrg.identity
|
||||
});
|
||||
|
||||
await IdentityUniversalAuth.deleteMany({
|
||||
identity: identityMembershipOrg.identity
|
||||
});
|
||||
|
||||
await IdentityUniversalAuthClientSecret.deleteMany({
|
||||
identity: identityMembershipOrg.identity
|
||||
});
|
||||
|
||||
await IdentityAccessToken.deleteMany({
|
||||
identity: identityMembershipOrg.identity
|
||||
});
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.DELETE_IDENTITY,
|
||||
metadata: {
|
||||
identityId: identity._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: identityMembershipOrg.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
identity
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as machineIdentitiesController from "./machineIdentitiesController";
|
||||
import * as identitiesController from "./identitiesController";
|
||||
import * as secretController from "./secretController";
|
||||
import * as secretSnapshotController from "./secretSnapshotController";
|
||||
import * as organizationsController from "./organizationsController";
|
||||
@@ -14,7 +14,7 @@ import * as secretRotationProviderController from "./secretRotationProviderContr
|
||||
import * as secretRotationController from "./secretRotationController";
|
||||
|
||||
export {
|
||||
machineIdentitiesController,
|
||||
identitiesController,
|
||||
secretController,
|
||||
secretSnapshotController,
|
||||
organizationsController,
|
||||
|
||||
@@ -1,934 +0,0 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import bcrypt from "bcrypt";
|
||||
import crypto from "crypto";
|
||||
import { Request, Response } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import {
|
||||
IMachineIdentity,
|
||||
IMachineIdentityClientSecret,
|
||||
IMachineIdentityTrustedIp,
|
||||
IdentityAccessToken,
|
||||
MachineIdentity,
|
||||
MachineIdentityClientSecret,
|
||||
MachineMembership,
|
||||
MachineMembershipOrg,
|
||||
Organization,
|
||||
} from "../../../models";
|
||||
import {
|
||||
ActorType,
|
||||
EventType,
|
||||
IRole,
|
||||
Role
|
||||
} from "../../models";
|
||||
import { validateRequest } from "../../../helpers/validation";
|
||||
import * as reqValidator from "../../../validation/machineIdentity";
|
||||
import { createToken } from "../../../helpers/auth";
|
||||
import {
|
||||
getAuthDataOrgPermissions,
|
||||
getOrgRolePermissions,
|
||||
isAtLeastAsPrivilegedOrg
|
||||
} from "../../services/RoleService";
|
||||
import {
|
||||
BadRequestError,
|
||||
ForbiddenRequestError,
|
||||
ResourceNotFoundError,
|
||||
UnauthorizedRequestError
|
||||
} from "../../../utils/errors";
|
||||
import { extractIPDetails, isValidIpOrCidr } from "../../../utils/ip";
|
||||
import { EEAuditLogService, EELicenseService } from "../../services";
|
||||
import { getAuthSecret, getSaltRounds } from "../../../config";
|
||||
import { ADMIN, AuthTokenType, CUSTOM, MEMBER, NO_ACCESS } from "../../../variables";
|
||||
import {
|
||||
OrgPermissionActions,
|
||||
OrgPermissionSubjects
|
||||
} from "../../services/RoleService";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import { checkIPAgainstBlocklist } from "../../../utils/ip";
|
||||
import { getUserAgentType } from "../../../utils/posthog";
|
||||
|
||||
const packageClientSecretData = (machineIdentityClientSecret: IMachineIdentityClientSecret) => ({
|
||||
_id: machineIdentityClientSecret._id,
|
||||
machineIdentity: machineIdentityClientSecret.machineIdentity,
|
||||
isClientSecretRevoked: machineIdentityClientSecret.isClientSecretRevoked,
|
||||
description: machineIdentityClientSecret.description,
|
||||
clientSecretPrefix: machineIdentityClientSecret.clientSecretPrefix,
|
||||
clientSecretNumUses: machineIdentityClientSecret.clientSecretNumUses,
|
||||
clientSecretNumUsesLimit: machineIdentityClientSecret.clientSecretNumUsesLimit,
|
||||
clientSecretTTL: machineIdentityClientSecret.clientSecretTTL,
|
||||
createdAt: machineIdentityClientSecret.createdAt,
|
||||
updatedAt: machineIdentityClientSecret.updatedAt
|
||||
});
|
||||
|
||||
/**
|
||||
* Return client secrets for machine with id [machineId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const getMIClientSecrets = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: {
|
||||
machineId
|
||||
}
|
||||
} = await validateRequest(reqValidator.GetClientSecretsV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
}).populate<{
|
||||
machineIdentity: IMachineIdentity,
|
||||
customRole: IRole
|
||||
}>("machineIdentity customRole");
|
||||
|
||||
if (!machineMembershipOrg) throw ResourceNotFoundError();
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: machineMembershipOrg.organization
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Read,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const rolePermission = await getOrgRolePermissions(
|
||||
machineMembershipOrg?.customRole?.slug ?? machineMembershipOrg.role,
|
||||
machineMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to get client secrets for more privileged MI"
|
||||
});
|
||||
|
||||
const clientSecretData = await MachineIdentityClientSecret
|
||||
.find({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity,
|
||||
isClientSecretRevoked: false
|
||||
})
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(5);
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.GET_MACHINE_IDENTITY_CLIENT_SECRETS,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineMembershipOrg.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
clientSecretData: clientSecretData.map((clientSecretDatum) => packageClientSecretData(clientSecretDatum))
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new client secret for machine with id [machineId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const createMIClientSecret = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: {
|
||||
machineId
|
||||
},
|
||||
body: {
|
||||
description,
|
||||
ttl,
|
||||
numUsesLimit
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateClientSecretV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
}).populate<{
|
||||
machineIdentity: IMachineIdentity,
|
||||
customRole: IRole
|
||||
}>("machineIdentity customRole");
|
||||
|
||||
if (!machineMembershipOrg) throw ResourceNotFoundError();
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: machineMembershipOrg.organization
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Create,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const rolePermission = await getOrgRolePermissions(
|
||||
machineMembershipOrg?.customRole?.slug ?? machineMembershipOrg.role,
|
||||
machineMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to create client secret for more privileged MI"
|
||||
});
|
||||
|
||||
const clientSecret = crypto.randomBytes(32).toString("hex");
|
||||
const clientSecretHash = await bcrypt.hash(clientSecret, await getSaltRounds());
|
||||
|
||||
const machineIdentityClientSecret = await new MachineIdentityClientSecret({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity,
|
||||
description,
|
||||
clientSecretPrefix: clientSecret.slice(0, 4),
|
||||
clientSecretHash,
|
||||
clientSecretNumUses: 0,
|
||||
clientSecretNumUsesLimit: numUsesLimit,
|
||||
clientSecretTTL: ttl,
|
||||
isClientSecretRevoked: false
|
||||
}).save();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.CREATE_MACHINE_IDENTITY_CLIENT_SECRET,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString(),
|
||||
clientSecretId: machineIdentityClientSecret._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineMembershipOrg.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
clientSecret,
|
||||
clientSecretData: packageClientSecretData(machineIdentityClientSecret)
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete client secret with id [clientSecretId]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const revokeMIClientSecret = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: {
|
||||
machineId,
|
||||
clientSecretId
|
||||
}
|
||||
} = await validateRequest(reqValidator.DeleteClientSecretV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
})
|
||||
.populate<{
|
||||
machineIdentity: IMachineIdentity,
|
||||
customRole: IRole
|
||||
}>("machineIdentity customRole");
|
||||
|
||||
if (!machineMembershipOrg) throw ResourceNotFoundError({
|
||||
message: `Failed to find machine identity with id ${machineId}`
|
||||
});
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: machineMembershipOrg.organization
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Delete,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const rolePermission = await getOrgRolePermissions(
|
||||
machineMembershipOrg?.customRole?.slug ?? machineMembershipOrg.role,
|
||||
machineMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to delete client secrets for more privileged MI"
|
||||
});
|
||||
|
||||
const machineIdentityClientSecret = await MachineIdentityClientSecret.findOneAndUpdate(
|
||||
{
|
||||
_id: clientSecretId,
|
||||
machineIdentity: machineId
|
||||
},
|
||||
{
|
||||
isClientSecretRevoked: true
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!machineIdentityClientSecret) throw ResourceNotFoundError();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.REVOKE_MACHINE_IDENTITY_CLIENT_SECRET,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString(),
|
||||
clientSecretId: clientSecretId
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineMembershipOrg.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
clientSecretData: packageClientSecretData(machineIdentityClientSecret)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Return access token for machine identity with client id [clientId]
|
||||
* and client secret [clientSecret]
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const loginMI = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
clientId,
|
||||
clientSecret
|
||||
}
|
||||
} = await validateRequest(reqValidator.LoginMachineIdentityV1, req);
|
||||
|
||||
const machineIdentity = await MachineIdentity.findOne({
|
||||
clientId
|
||||
});
|
||||
|
||||
if (!machineIdentity) throw UnauthorizedRequestError();
|
||||
|
||||
checkIPAgainstBlocklist({
|
||||
ipAddress: req.realIP,
|
||||
trustedIps: machineIdentity.clientSecretTrustedIps
|
||||
});
|
||||
|
||||
const clientSecretData = await MachineIdentityClientSecret.find({
|
||||
machineIdentity: machineIdentity._id,
|
||||
isClientSecretRevoked: false
|
||||
});
|
||||
|
||||
let validatedClientSecretDatum: IMachineIdentityClientSecret | undefined;
|
||||
|
||||
for (const clientSecretDatum of clientSecretData) {
|
||||
const isSecretValid = await bcrypt.compare(
|
||||
clientSecret,
|
||||
clientSecretDatum.clientSecretHash
|
||||
);
|
||||
|
||||
if (isSecretValid) {
|
||||
validatedClientSecretDatum = clientSecretDatum;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!validatedClientSecretDatum) throw UnauthorizedRequestError();
|
||||
|
||||
const {
|
||||
clientSecretTTL,
|
||||
clientSecretNumUses,
|
||||
clientSecretNumUsesLimit,
|
||||
} = validatedClientSecretDatum;
|
||||
|
||||
if (clientSecretTTL > 0) {
|
||||
const clientSecretCreated = new Date(validatedClientSecretDatum.createdAt)
|
||||
const ttlInMilliseconds = clientSecretTTL * 1000;
|
||||
const currentDate = new Date();
|
||||
const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) {
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
isClientSecretRevoked: true
|
||||
}
|
||||
);
|
||||
|
||||
throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate MI credentials due to expired client secret"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (clientSecretNumUsesLimit > 0 && clientSecretNumUses === clientSecretNumUsesLimit) {
|
||||
// number of times client secret can be used for
|
||||
// a login operation reached
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
isClientSecretRevoked: true
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate MI credentials due to client secret number of uses limit reached"
|
||||
});
|
||||
}
|
||||
|
||||
// increment usage count by 1
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
clientSecretLastUsedAt: new Date(),
|
||||
$inc: { clientSecretNumUses: 1 }
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
const identityAccessToken = await new IdentityAccessToken({
|
||||
machineIdentity: machineIdentity._id,
|
||||
machineIdentityClientSecret: validatedClientSecretDatum._id,
|
||||
accessTokenNumUses: 0,
|
||||
accessTokenNumUsesLimit: machineIdentity.accessTokenNumUsesLimit,
|
||||
accessTokenTTL: machineIdentity.accessTokenTTL,
|
||||
accessTokenMaxTTL: machineIdentity.accessTokenMaxTTL,
|
||||
isAccessTokenRevoked: false
|
||||
}).save();
|
||||
|
||||
// token version
|
||||
const accessToken = createToken({
|
||||
payload: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
clientSecretId: validatedClientSecretDatum._id.toString(),
|
||||
identityAccessTokenId: identityAccessToken._id.toString(),
|
||||
authTokenType: AuthTokenType.MACHINE_ACCESS_TOKEN
|
||||
},
|
||||
expiresIn: machineIdentity.accessTokenTTL,
|
||||
secret: await getAuthSecret()
|
||||
});
|
||||
|
||||
const userAgent = req.headers["user-agent"] ?? "";
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
{
|
||||
actor: {
|
||||
type: ActorType.MACHINE,
|
||||
metadata: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
name: machineIdentity.name
|
||||
}
|
||||
},
|
||||
authPayload: machineIdentity,
|
||||
ipAddress: req.realIP,
|
||||
userAgent,
|
||||
userAgentType: getUserAgentType(userAgent)
|
||||
},
|
||||
{
|
||||
type: EventType.LOGIN_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
machineAccessTokenId: identityAccessToken._id.toString(),
|
||||
clientSecretId: validatedClientSecretDatum._id.toString(),
|
||||
identityAccessTokenId: identityAccessToken._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineIdentity.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
accessToken,
|
||||
expiresIn: machineIdentity.accessTokenTTL,
|
||||
tokenType: "Bearer"
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renews an access token by its TTL
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const renewAccessToken = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
accessToken
|
||||
}
|
||||
} = await validateRequest(reqValidator.RenewAccessTokenV1, req);
|
||||
|
||||
const decodedToken = <jwt.MachineAccessTokenJwtPayload>(
|
||||
jwt.verify(accessToken, await getAuthSecret())
|
||||
);
|
||||
|
||||
if (decodedToken.authTokenType !== AuthTokenType.MACHINE_ACCESS_TOKEN) throw UnauthorizedRequestError();
|
||||
|
||||
const machineIdentityAccessToken = await IdentityAccessToken.findOne({
|
||||
_id: decodedToken.identityAccessTokenId,
|
||||
isAccessTokenRevoked: false
|
||||
});
|
||||
|
||||
if (!machineIdentityAccessToken) throw UnauthorizedRequestError();
|
||||
|
||||
const {
|
||||
accessTokenTTL,
|
||||
accessTokenLastRenewedAt,
|
||||
accessTokenMaxTTL,
|
||||
createdAt: accessTokenCreatedAt
|
||||
} = machineIdentityAccessToken;
|
||||
|
||||
if (accessTokenTTL === accessTokenMaxTTL) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew non-renewable access token"
|
||||
});
|
||||
|
||||
// ttl check
|
||||
if (accessTokenTTL > 0) {
|
||||
const currentDate = new Date();
|
||||
if (accessTokenLastRenewedAt) {
|
||||
// access token has been renewed
|
||||
const accessTokenRenewed = new Date(accessTokenLastRenewedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationDate = new Date(accessTokenRenewed.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationDate) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token due to TTL expiration"
|
||||
});
|
||||
} else {
|
||||
// access token has never been renewed
|
||||
const accessTokenCreated = new Date(accessTokenCreatedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationDate) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token due to TTL expiration"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// max ttl checks
|
||||
if (accessTokenMaxTTL > 0) {
|
||||
const accessTokenCreated = new Date(accessTokenCreatedAt);
|
||||
const ttlInMilliseconds = accessTokenMaxTTL * 1000;
|
||||
const currentDate = new Date();
|
||||
const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationDate) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token due to Max TTL expiration"
|
||||
});
|
||||
|
||||
const extendToDate = new Date(currentDate.getTime() + accessTokenTTL);
|
||||
if (extendToDate > expirationDate) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token past its Max TTL expiration"
|
||||
});
|
||||
}
|
||||
|
||||
await IdentityAccessToken.findByIdAndUpdate(
|
||||
machineIdentityAccessToken._id,
|
||||
{
|
||||
accessTokenLastRenewedAt: new Date()
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
accessToken,
|
||||
expiresIn: machineIdentityAccessToken.accessTokenTTL,
|
||||
tokenType: "Bearer"
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create machine identity
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const createMachineIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
name,
|
||||
organizationId,
|
||||
role,
|
||||
clientSecretTrustedIps,
|
||||
accessTokenTrustedIps,
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateMachineIdentityV1, req);
|
||||
|
||||
if (accessTokenMaxTTL > 0 && accessTokenTTL > accessTokenMaxTTL) {
|
||||
throw BadRequestError({ message: "Access token TTL cannot be greater than max TTL" })
|
||||
}
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: new Types.ObjectId(organizationId)
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Create,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const rolePermission = await getOrgRolePermissions(role, organizationId);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to create a more privileged MI"
|
||||
});
|
||||
|
||||
const organization = await Organization.findById(organizationId);
|
||||
if (!organization) throw BadRequestError({ message: `Organization with id ${organizationId} not found` });
|
||||
|
||||
const isCustomRole = ![ADMIN, MEMBER, NO_ACCESS].includes(role);
|
||||
|
||||
let customRole;
|
||||
if (isCustomRole) {
|
||||
customRole = await Role.findOne({
|
||||
slug: role,
|
||||
isOrgRole: true,
|
||||
organization: new Types.ObjectId(organizationId)
|
||||
});
|
||||
|
||||
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||
}
|
||||
|
||||
const plan = await EELicenseService.getPlan(new Types.ObjectId(organizationId));
|
||||
|
||||
// validate trusted ips
|
||||
const reformattedClientSecretTrustedIps = clientSecretTrustedIps.map((clientSecretTrustedIp) => {
|
||||
if (!plan.ipAllowlisting && clientSecretTrustedIp.ipAddress !== "0.0.0.0/0") return res.status(400).send({
|
||||
message: "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
|
||||
});
|
||||
|
||||
const isValidIPOrCidr = isValidIpOrCidr(clientSecretTrustedIp.ipAddress);
|
||||
|
||||
if (!isValidIPOrCidr) return res.status(400).send({
|
||||
message: "The IP is not a valid IPv4, IPv6, or CIDR block"
|
||||
});
|
||||
|
||||
return extractIPDetails(clientSecretTrustedIp.ipAddress);
|
||||
});
|
||||
|
||||
const reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {
|
||||
if (!plan.ipAllowlisting && accessTokenTrustedIp.ipAddress !== "0.0.0.0/0") return res.status(400).send({
|
||||
message: "Failed to add IP access range to service token due to plan restriction. Upgrade plan to add IP access range."
|
||||
});
|
||||
|
||||
const isValidIPOrCidr = isValidIpOrCidr(accessTokenTrustedIp.ipAddress);
|
||||
|
||||
if (!isValidIPOrCidr) return res.status(400).send({
|
||||
message: "The IP is not a valid IPv4, IPv6, or CIDR block"
|
||||
});
|
||||
|
||||
return extractIPDetails(accessTokenTrustedIp.ipAddress);
|
||||
});
|
||||
|
||||
const machineIdentity = await new MachineIdentity({
|
||||
clientId: crypto.randomUUID(),
|
||||
name,
|
||||
organization: new Types.ObjectId(organizationId),
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUses: 0,
|
||||
accessTokenNumUsesLimit,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
|
||||
}).save();
|
||||
|
||||
await new MachineMembershipOrg({
|
||||
machineIdentity: machineIdentity._id,
|
||||
organization: machineIdentity.organization,
|
||||
role: isCustomRole ? CUSTOM : role,
|
||||
customRole
|
||||
}).save();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.CREATE_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
name,
|
||||
role,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps as Array<IMachineIdentityTrustedIp>
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: new Types.ObjectId(organizationId)
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
machineIdentity
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update machine identity with id [machineId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const updateMachineIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { machineId },
|
||||
body: {
|
||||
name,
|
||||
role,
|
||||
clientSecretTrustedIps,
|
||||
accessTokenTrustedIps,
|
||||
accessTokenTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenMaxTTL
|
||||
}
|
||||
} = await validateRequest(reqValidator.UpdateMachineIdentityV1, req);
|
||||
|
||||
if (accessTokenTTL && accessTokenMaxTTL > 0 && accessTokenTTL > accessTokenMaxTTL) {
|
||||
throw BadRequestError({ message: "Access token TTL cannot be greater than max TTL" })
|
||||
}
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
})
|
||||
.populate<{
|
||||
machineIdentity: IMachineIdentity,
|
||||
customRole: IRole
|
||||
}>("machineIdentity customRole");
|
||||
|
||||
if (!machineMembershipOrg) throw ResourceNotFoundError({
|
||||
message: `Failed to find machine identity with id ${machineId}`
|
||||
});
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: machineMembershipOrg.organization
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Edit,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const machineIdentityRolePermission = await getOrgRolePermissions(
|
||||
machineMembershipOrg?.customRole?.slug ?? machineMembershipOrg.role,
|
||||
machineMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, machineIdentityRolePermission);
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to update more privileged MI"
|
||||
});
|
||||
|
||||
if (role) {
|
||||
const rolePermission = await getOrgRolePermissions(role, machineMembershipOrg.organization.toString());
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
|
||||
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to update MI to a more privileged role"
|
||||
});
|
||||
}
|
||||
|
||||
let customRole;
|
||||
if (role) {
|
||||
const isCustomRole = ![ADMIN, MEMBER, NO_ACCESS].includes(role);
|
||||
if (isCustomRole) {
|
||||
customRole = await Role.findOne({
|
||||
slug: role,
|
||||
isOrgRole: true,
|
||||
organization: machineMembershipOrg.organization
|
||||
});
|
||||
|
||||
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||
}
|
||||
}
|
||||
|
||||
const plan = await EELicenseService.getPlan(machineMembershipOrg.organization);
|
||||
|
||||
// validate client secret trusted ips
|
||||
let reformattedClientSecretTrustedIps;
|
||||
if (clientSecretTrustedIps) {
|
||||
reformattedClientSecretTrustedIps = clientSecretTrustedIps.map((clientSecretTrustedIp) => {
|
||||
if (!plan.ipAllowlisting && clientSecretTrustedIp.ipAddress !== "0.0.0.0/0") return res.status(400).send({
|
||||
message: "Failed to update IP access range to service token due to plan restriction. Upgrade plan to update IP access range."
|
||||
});
|
||||
|
||||
const isValidIPOrCidr = isValidIpOrCidr(clientSecretTrustedIp.ipAddress);
|
||||
|
||||
if (!isValidIPOrCidr) return res.status(400).send({
|
||||
message: "The IP is not a valid IPv4, IPv6, or CIDR block"
|
||||
});
|
||||
|
||||
return extractIPDetails(clientSecretTrustedIp.ipAddress);
|
||||
});
|
||||
}
|
||||
|
||||
// validate access token trusted ips
|
||||
let reformattedAccessTokenTrustedIps;
|
||||
if (accessTokenTrustedIps) {
|
||||
reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {
|
||||
if (!plan.ipAllowlisting && accessTokenTrustedIp.ipAddress !== "0.0.0.0/0") return res.status(400).send({
|
||||
message: "Failed to update IP access range to service token due to plan restriction. Upgrade plan to update IP access range."
|
||||
});
|
||||
|
||||
const isValidIPOrCidr = isValidIpOrCidr(accessTokenTrustedIp.ipAddress);
|
||||
|
||||
if (!isValidIPOrCidr) return res.status(400).send({
|
||||
message: "The IP is not a valid IPv4, IPv6, or CIDR block"
|
||||
});
|
||||
|
||||
return extractIPDetails(accessTokenTrustedIp.ipAddress);
|
||||
});
|
||||
}
|
||||
|
||||
const machineIdentity = await MachineIdentity.findByIdAndUpdate(
|
||||
machineId,
|
||||
{
|
||||
name,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
|
||||
accessTokenTTL,
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenMaxTTL
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!machineIdentity) throw BadRequestError({
|
||||
message: `Failed to update machine identity with id ${machineId}`
|
||||
});
|
||||
|
||||
await MachineMembershipOrg.findOneAndUpdate(
|
||||
{
|
||||
machineIdentity: machineIdentity._id
|
||||
},
|
||||
{
|
||||
role: customRole ? CUSTOM : role,
|
||||
...(customRole ? {
|
||||
customRole
|
||||
} : {}),
|
||||
...(role && !customRole ? { // non-custom role
|
||||
$unset: {
|
||||
customRole: 1
|
||||
}
|
||||
} : {})
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.UPDATE_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
name: machineIdentity.name,
|
||||
role,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps as Array<IMachineIdentityTrustedIp>
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineIdentity.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
machineIdentity
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete machine identity with id [machineId]
|
||||
* @param req
|
||||
* @param res
|
||||
* @returns
|
||||
*/
|
||||
export const deleteMachineIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { machineId }
|
||||
} = await validateRequest(reqValidator.DeleteMachineIdentityV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
})
|
||||
.populate<{
|
||||
machineIdentity: IMachineIdentity,
|
||||
customRole: IRole
|
||||
}>("machineIdentity customRole");
|
||||
|
||||
if (!machineMembershipOrg) throw ResourceNotFoundError({
|
||||
message: `Failed to find machine identity with id ${machineId}`
|
||||
});
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
organizationId: machineMembershipOrg.organization
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Delete,
|
||||
OrgPermissionSubjects.MachineIdentity
|
||||
);
|
||||
|
||||
const machineIdentityRolePermission = await getOrgRolePermissions(
|
||||
machineMembershipOrg?.customRole?.slug ?? machineMembershipOrg.role,
|
||||
machineMembershipOrg.organization.toString()
|
||||
);
|
||||
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, machineIdentityRolePermission);
|
||||
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
|
||||
message: "Failed to delete more privileged MI"
|
||||
});
|
||||
|
||||
const machineIdentity = await MachineIdentity.findByIdAndDelete(machineMembershipOrg.machineIdentity);
|
||||
if (!machineIdentity) throw ResourceNotFoundError({
|
||||
message: `Machine identity with id ${machineId} not found`
|
||||
});
|
||||
|
||||
await MachineMembershipOrg.findByIdAndDelete(machineMembershipOrg._id);
|
||||
|
||||
if (!machineMembershipOrg) throw BadRequestError({
|
||||
message: `Failed to delete machine identity with id ${machineId}`
|
||||
});
|
||||
|
||||
await MachineMembership.deleteMany({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
const machineIdentityClientSecretIds = await MachineIdentityClientSecret.distinct("_id", {
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
await MachineIdentityClientSecret.deleteMany({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
await IdentityAccessToken.deleteMany({
|
||||
machineIdentityClientSecret: {
|
||||
$in: machineIdentityClientSecretIds
|
||||
}
|
||||
});
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.DELETE_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
name: machineIdentity.name,
|
||||
role: machineMembershipOrg.role,
|
||||
clientSecretTrustedIps: machineIdentity.clientSecretTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
accessTokenTrustedIps: machineIdentity.accessTokenTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
}
|
||||
},
|
||||
{
|
||||
organizationId: machineIdentity.organization
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
machineIdentity
|
||||
});
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { Request, Response } from "express";
|
||||
import { PipelineStage, Types } from "mongoose";
|
||||
import {
|
||||
Folder,
|
||||
MachineIdentity,
|
||||
MachineMembership,
|
||||
Identity,
|
||||
IdentityMembership,
|
||||
Membership,
|
||||
Secret,
|
||||
ServiceTokenData,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
FolderVersion,
|
||||
IPType,
|
||||
ISecretVersion,
|
||||
MachineActor,
|
||||
IdentityActor,
|
||||
SecretSnapshot,
|
||||
SecretVersion,
|
||||
ServiceActor,
|
||||
@@ -679,8 +679,8 @@ export const getWorkspaceAuditLogs = async (req: Request, res: Response) => {
|
||||
case ActorType.SERVICE:
|
||||
actorMetadataQuery = "actor.metadata.serviceId";
|
||||
break;
|
||||
case ActorType.MACHINE:
|
||||
actorMetadataQuery = "actor.metadata.machineId";
|
||||
case ActorType.IDENTITY:
|
||||
actorMetadataQuery = "actor.metadata.identityId";
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -772,25 +772,25 @@ export const getWorkspaceAuditLogActorFilterOpts = async (req: Request, res: Res
|
||||
}
|
||||
}));
|
||||
|
||||
const machineIds = await MachineMembership.distinct("machineIdentity", {
|
||||
const identityIds = await IdentityMembership.distinct("identity", {
|
||||
workspace: new Types.ObjectId(workspaceId)
|
||||
});
|
||||
|
||||
const machineActors: MachineActor[] = (
|
||||
await MachineIdentity.find({
|
||||
const identityActors: IdentityActor[] = (
|
||||
await Identity.find({
|
||||
_id: {
|
||||
$in: machineIds
|
||||
$in: identityIds
|
||||
}
|
||||
})
|
||||
).map((machineIdentity) => ({
|
||||
type: ActorType.MACHINE,
|
||||
).map((identity) => ({
|
||||
type: ActorType.IDENTITY,
|
||||
metadata: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
name: machineIdentity.name
|
||||
identityId: identity._id.toString(),
|
||||
name: identity.name
|
||||
}
|
||||
}));
|
||||
|
||||
const actors = [...userActors, ...serviceActors, ...machineActors];
|
||||
const actors = [...userActors, ...serviceActors, ...identityActors];
|
||||
|
||||
return res.status(200).send({
|
||||
actors
|
||||
|
||||
@@ -10,7 +10,7 @@ export interface IAuditLog {
|
||||
event: Event;
|
||||
userAgent: string;
|
||||
userAgentType: UserAgentType;
|
||||
expiresAt: Date;
|
||||
expiresAt?: Date;
|
||||
}
|
||||
|
||||
const auditLogSchema = new Schema<IAuditLog>(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export enum ActorType { // would extend to AWS, Azure, ...
|
||||
USER = "user", // userIdentity
|
||||
SERVICE = "service",
|
||||
MACHINE = "machine" // machineIdentity
|
||||
USER = "user", // userIdentity
|
||||
SERVICE = "service",
|
||||
IDENTITY = "identity"
|
||||
}
|
||||
|
||||
export enum UserAgentType {
|
||||
@@ -31,13 +31,16 @@ export enum EventType {
|
||||
DELETE_TRUSTED_IP = "delete-trusted-ip",
|
||||
CREATE_SERVICE_TOKEN = "create-service-token", // v2
|
||||
DELETE_SERVICE_TOKEN = "delete-service-token", // v2
|
||||
CREATE_MACHINE_IDENTITY = "create-machine-identity",
|
||||
UPDATE_MACHINE_IDENTITY = "update-machine-identity",
|
||||
DELETE_MACHINE_IDENTITY = "delete-machine-identity",
|
||||
LOGIN_MACHINE_IDENTITY = "login-machine-identity",
|
||||
CREATE_MACHINE_IDENTITY_CLIENT_SECRET = "create-machine-identity-secret",
|
||||
REVOKE_MACHINE_IDENTITY_CLIENT_SECRET = "revoke-machine-identity-secret",
|
||||
GET_MACHINE_IDENTITY_CLIENT_SECRETS = "get-machine-identity-secrets",
|
||||
CREATE_IDENTITY = "create-identity",
|
||||
UPDATE_IDENTITY = "update-identity",
|
||||
DELETE_IDENTITY = "delete-identity",
|
||||
LOGIN_IDENTITY_UNIVERSAL_AUTH = "login-identity-universal-auth",
|
||||
ADD_IDENTITY_UNIVERSAL_AUTH = "add-identity-universal-auth",
|
||||
UPDATE_IDENTITY_UNIVERSAL_AUTH = "update-identity-universal-auth",
|
||||
GET_IDENTITY_UNIVERSAL_AUTH = "get-identity-universal-auth",
|
||||
CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "create-identity-universal-auth-client-secret",
|
||||
REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "revoke-identity-universal-auth-client-secret",
|
||||
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS = "get-identity-universal-auth-client-secret",
|
||||
CREATE_ENVIRONMENT = "create-environment",
|
||||
UPDATE_ENVIRONMENT = "update-environment",
|
||||
DELETE_ENVIRONMENT = "delete-environment",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ActorType, EventType } from "./enums";
|
||||
import { IMachineIdentityTrustedIp } from "../../../models/machineIdentity";
|
||||
import { IIdentityTrustedIp } from "../../../models";
|
||||
|
||||
interface UserActorMetadata {
|
||||
userId: string;
|
||||
@@ -11,8 +11,8 @@ interface ServiceActorMetadata {
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface MachineActorMetadata {
|
||||
machineId: string;
|
||||
interface IdentityActorMetadata {
|
||||
identityId: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@@ -26,16 +26,12 @@ export interface ServiceActor {
|
||||
metadata: ServiceActorMetadata;
|
||||
}
|
||||
|
||||
export interface MachineActor {
|
||||
type: ActorType.MACHINE;
|
||||
metadata: MachineActorMetadata;
|
||||
export interface IdentityActor {
|
||||
type: ActorType.IDENTITY;
|
||||
metadata: IdentityActorMetadata;
|
||||
}
|
||||
|
||||
// export interface MachineActor {
|
||||
// type: ActorType.Machine;
|
||||
// }
|
||||
|
||||
export type Actor = UserActor | ServiceActor | MachineActor;
|
||||
export type Actor = UserActor | ServiceActor | IdentityActor;
|
||||
|
||||
interface GetSecretsEvent {
|
||||
type: EventType.GET_SECRETS;
|
||||
@@ -225,66 +221,90 @@ interface DeleteServiceTokenEvent {
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateMachineIdentityEvent {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY;
|
||||
interface CreateIdentityEvent { // note: currently not logging org-role
|
||||
type: EventType.CREATE_IDENTITY;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
name: string;
|
||||
role: string;
|
||||
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateMachineIdentityEvent {
|
||||
type: EventType.UPDATE_MACHINE_IDENTITY;
|
||||
interface UpdateIdentityEvent {
|
||||
type: EventType.UPDATE_IDENTITY;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
name?: string;
|
||||
role?: string;
|
||||
clientSecretTrustedIps?: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps?: Array<IMachineIdentityTrustedIp>;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteMachineIdentityEvent {
|
||||
type: EventType.DELETE_MACHINE_IDENTITY;
|
||||
interface DeleteIdentityEvent {
|
||||
type: EventType.DELETE_IDENTITY;
|
||||
metadata: {
|
||||
name: string;
|
||||
role: string;
|
||||
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
identityId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface LoginMachineIdentityEvent {
|
||||
type: EventType.LOGIN_MACHINE_IDENTITY ;
|
||||
interface LoginIdentityUniversalAuthEvent {
|
||||
type: EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
machineAccessTokenId: string;
|
||||
identityId: string;
|
||||
clientSecretId: string;
|
||||
identityAccessTokenId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateMachineIdentitySecretEvent {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY_CLIENT_SECRET ;
|
||||
interface AddIdentityUniversalAuthEvent {
|
||||
type: EventType.ADD_IDENTITY_UNIVERSAL_AUTH;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
identityId: string;
|
||||
clientSecretTrustedIps: Array<IIdentityTrustedIp>;
|
||||
accessTokenTTL: number;
|
||||
accessTokenMaxTTL: number;
|
||||
accessTokenNumUsesLimit: number;
|
||||
accessTokenTrustedIps: Array<IIdentityTrustedIp>;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateIdentityUniversalAuthEvent {
|
||||
type: EventType.UPDATE_IDENTITY_UNIVERSAL_AUTH;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
clientSecretTrustedIps?: Array<IIdentityTrustedIp>;
|
||||
accessTokenTTL?: number;
|
||||
accessTokenMaxTTL?: number;
|
||||
accessTokenNumUsesLimit?: number;
|
||||
accessTokenTrustedIps?: Array<IIdentityTrustedIp>;
|
||||
};
|
||||
}
|
||||
|
||||
interface GetIdentityUniversalAuthEvent {
|
||||
type: EventType.GET_IDENTITY_UNIVERSAL_AUTH;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateIdentityUniversalAuthClientSecretEvent {
|
||||
type: EventType.CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET ;
|
||||
metadata: {
|
||||
identityId: string;
|
||||
clientSecretId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteMachineIdentitySecretEvent {
|
||||
type: EventType.REVOKE_MACHINE_IDENTITY_CLIENT_SECRET ;
|
||||
interface GetIdentityUniversalAuthClientSecretsEvent {
|
||||
type: EventType.GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
clientSecretId: string;
|
||||
identityId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface GetMachineIdentitySecretsEvent {
|
||||
type: EventType.GET_MACHINE_IDENTITY_CLIENT_SECRETS ;
|
||||
|
||||
interface RevokeIdentityUniversalAuthClientSecretEvent {
|
||||
type: EventType.REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
identityId: string;
|
||||
clientSecretId: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -530,13 +550,16 @@ export type Event =
|
||||
| DeleteTrustedIPEvent
|
||||
| CreateServiceTokenEvent
|
||||
| DeleteServiceTokenEvent
|
||||
| CreateMachineIdentityEvent
|
||||
| UpdateMachineIdentityEvent
|
||||
| DeleteMachineIdentityEvent
|
||||
| CreateMachineIdentitySecretEvent
|
||||
| DeleteMachineIdentitySecretEvent
|
||||
| LoginMachineIdentityEvent
|
||||
| GetMachineIdentitySecretsEvent
|
||||
| CreateIdentityEvent
|
||||
| UpdateIdentityEvent
|
||||
| DeleteIdentityEvent
|
||||
| LoginIdentityUniversalAuthEvent
|
||||
| AddIdentityUniversalAuthEvent
|
||||
| UpdateIdentityUniversalAuthEvent
|
||||
| GetIdentityUniversalAuthEvent
|
||||
| CreateIdentityUniversalAuthClientSecretEvent
|
||||
| GetIdentityUniversalAuthClientSecretsEvent
|
||||
| RevokeIdentityUniversalAuthClientSecretEvent
|
||||
| CreateEnvironmentEvent
|
||||
| UpdateEnvironmentEvent
|
||||
| DeleteEnvironmentEvent
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import express from "express";
|
||||
const router = express.Router();
|
||||
import { requireAuth } from "../../../middleware";
|
||||
import { AuthMode } from "../../../variables";
|
||||
import { identitiesController } from "../../controllers/v1";
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]
|
||||
}),
|
||||
identitiesController.createIdentity
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/:identityId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
identitiesController.updateIdentity
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:identityId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
identitiesController.deleteIdentity
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -1,4 +1,4 @@
|
||||
import machineIdentities from "./machineIdentities";
|
||||
import identities from "./identities";
|
||||
import secret from "./secret";
|
||||
import secretSnapshot from "./secretSnapshot";
|
||||
import organizations from "./organizations";
|
||||
@@ -14,7 +14,7 @@ import secretRotationProvider from "./secretRotationProvider";
|
||||
import secretRotation from "./secretRotation";
|
||||
|
||||
export {
|
||||
machineIdentities,
|
||||
identities,
|
||||
secret,
|
||||
secretSnapshot,
|
||||
organizations,
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import express from "express";
|
||||
const router = express.Router();
|
||||
import { requireAuth } from "../../../middleware";
|
||||
import { AuthMode } from "../../../variables";
|
||||
import { machineIdentitiesController } from "../../controllers/v1";
|
||||
|
||||
router.get(
|
||||
"/:machineId/client-secrets",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
machineIdentitiesController.getMIClientSecrets
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/:machineId/client-secrets",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
machineIdentitiesController.createMIClientSecret
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/:machineId/client-secrets/:clientSecretId/revoke",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
machineIdentitiesController.revokeMIClientSecret
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/login",
|
||||
machineIdentitiesController.loginMI
|
||||
);
|
||||
|
||||
// note: currently this is machine-identity specific
|
||||
router.post(
|
||||
"/access-token/renew",
|
||||
machineIdentitiesController.renewAccessToken
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT, AuthMode.MACHINE_ACCESS_TOKEN]
|
||||
}),
|
||||
machineIdentitiesController.createMachineIdentity
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/:machineId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
machineIdentitiesController.updateMachineIdentity
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/:machineId",
|
||||
requireAuth({
|
||||
acceptedAuthModes: [AuthMode.JWT]
|
||||
}),
|
||||
machineIdentitiesController.deleteMachineIdentity
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -3,7 +3,6 @@ import { AuditLog, Event } from "../models";
|
||||
import { AuthData } from "../../interfaces/middleware";
|
||||
import EELicenseService from "./EELicenseService";
|
||||
import { Workspace } from "../../models";
|
||||
import { OrganizationNotFoundError } from "../../utils/errors";
|
||||
|
||||
interface EventScope {
|
||||
workspaceId?: Types.ObjectId;
|
||||
@@ -14,31 +13,42 @@ type ValidEventScope =
|
||||
| Required<Pick<EventScope, "workspaceId">>
|
||||
| Required<Pick<EventScope, "organizationId">>
|
||||
| Required<EventScope>
|
||||
| Record<string, never>;
|
||||
|
||||
export default class EEAuditLogService {
|
||||
static async createAuditLog(authData: AuthData, event: Event, eventScope: ValidEventScope, shouldSave = true) {
|
||||
static async createAuditLog(authData: AuthData, event: Event, eventScope: ValidEventScope = {}, shouldSave = true) {
|
||||
|
||||
const MS_IN_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
const organizationId = ("organizationId" in eventScope)
|
||||
? eventScope.organizationId
|
||||
: (await Workspace.findById(eventScope.workspaceId).select("organization").lean())?.organization;
|
||||
let organizationId;
|
||||
if ("organizationId" in eventScope) {
|
||||
organizationId = eventScope.organizationId;
|
||||
}
|
||||
|
||||
if (!organizationId) throw OrganizationNotFoundError({
|
||||
message: "createAuditLog: Failed to create audit log due to missing organizationId"
|
||||
});
|
||||
|
||||
const ttl = (await EELicenseService.getPlan(organizationId)).auditLogsRetentionDays * MS_IN_DAY;
|
||||
let workspaceId;
|
||||
if ("workspaceId" in eventScope) {
|
||||
workspaceId = eventScope.workspaceId;
|
||||
|
||||
if (!organizationId) {
|
||||
organizationId = (await Workspace.findById(workspaceId).select("organization").lean())?.organization;
|
||||
}
|
||||
}
|
||||
|
||||
let expiresAt;
|
||||
if (organizationId) {
|
||||
const ttl = (await EELicenseService.getPlan(organizationId)).auditLogsRetentionDays * MS_IN_DAY;
|
||||
expiresAt = new Date(Date.now() + ttl);
|
||||
}
|
||||
|
||||
const auditLog = await new AuditLog({
|
||||
actor: authData.actor,
|
||||
organization: organizationId,
|
||||
workspace: ("workspaceId" in eventScope) ? eventScope.workspaceId : undefined,
|
||||
workspace: workspaceId,
|
||||
ipAddress: authData.ipAddress,
|
||||
event,
|
||||
userAgent: authData.userAgent,
|
||||
userAgentType: authData.userAgentType,
|
||||
expiresAt: new Date(Date.now() + ttl)
|
||||
expiresAt
|
||||
});
|
||||
|
||||
if (shouldSave) {
|
||||
|
||||
@@ -13,13 +13,12 @@ import picomatch from "picomatch";
|
||||
import { AuthData } from "../../interfaces/middleware";
|
||||
import { ActorType, IRole, Role } from "../models";
|
||||
import {
|
||||
IMachineIdentity,
|
||||
MachineMembership,
|
||||
IIdentity,
|
||||
IdentityMembership,
|
||||
Membership,
|
||||
ServiceTokenData
|
||||
} from "../../models";
|
||||
import { ADMIN, CUSTOM, MEMBER, NO_ACCESS, VIEWER } from "../../variables";
|
||||
import { checkIPAgainstBlocklist } from "../../utils/ip";
|
||||
import { BadRequestError } from "../../utils/errors";
|
||||
|
||||
const $glob: FieldInstruction<string> = {
|
||||
@@ -62,7 +61,7 @@ export enum ProjectPermissionSub {
|
||||
SecretRollback = "secret-rollback",
|
||||
SecretApproval = "secret-approval",
|
||||
SecretRotation = "secret-rotation",
|
||||
MachineIdentity = "machine-identity"
|
||||
Identity = "identity"
|
||||
}
|
||||
|
||||
type SubjectFields = {
|
||||
@@ -87,7 +86,7 @@ export type ProjectPermissionSet =
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.ServiceTokens]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.SecretApproval]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.SecretRotation]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.MachineIdentity]
|
||||
| [ProjectPermissionActions, ProjectPermissionSub.Identity]
|
||||
| [ProjectPermissionActions.Delete, ProjectPermissionSub.Workspace]
|
||||
| [ProjectPermissionActions.Edit, ProjectPermissionSub.Workspace]
|
||||
| [ProjectPermissionActions.Read, ProjectPermissionSub.SecretRollback]
|
||||
@@ -134,10 +133,10 @@ const buildAdminPermission = () => {
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Webhooks);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Webhooks);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Identity);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.ServiceTokens);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.ServiceTokens);
|
||||
@@ -204,10 +203,10 @@ const buildMemberPermission = () => {
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Webhooks);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Webhooks);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Identity);
|
||||
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.ServiceTokens);
|
||||
can(ProjectPermissionActions.Create, ProjectPermissionSub.ServiceTokens);
|
||||
@@ -249,7 +248,7 @@ const buildViewerPermission = () => {
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Role);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Integrations);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Webhooks);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.MachineIdentity);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Identity);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.ServiceTokens);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);
|
||||
can(ProjectPermissionActions.Read, ProjectPermissionSub.Environments);
|
||||
@@ -310,28 +309,23 @@ export const getAuthDataProjectPermissions = async ({
|
||||
role = "viewer";
|
||||
break;
|
||||
}
|
||||
case ActorType.MACHINE: {
|
||||
const machineMembership = await MachineMembership.findOne({
|
||||
machineIdentity: authData.authPayload._id,
|
||||
case ActorType.IDENTITY: {
|
||||
const identityMembership = await IdentityMembership.findOne({
|
||||
identity: authData.authPayload._id,
|
||||
workspace: workspaceId
|
||||
})
|
||||
.populate<{
|
||||
customRole: IRole & { permissions: RawRuleOf<MongoAbility<ProjectPermissionSet>>[] };
|
||||
machineIdentity: IMachineIdentity
|
||||
}>("customRole machineIdentity")
|
||||
identity: IIdentity
|
||||
}>("customRole identity")
|
||||
.exec();
|
||||
|
||||
if (!machineMembership || (machineMembership.role === "custom" && !machineMembership.customRole)) {
|
||||
if (!identityMembership || (identityMembership.role === "custom" && !identityMembership.customRole)) {
|
||||
throw UnauthorizedRequestError();
|
||||
}
|
||||
|
||||
checkIPAgainstBlocklist({
|
||||
ipAddress: authData.ipAddress,
|
||||
trustedIps: machineMembership.machineIdentity.accessTokenTrustedIps
|
||||
});
|
||||
|
||||
role = machineMembership.role;
|
||||
customRole = machineMembership.customRole;
|
||||
role = identityMembership.role;
|
||||
customRole = identityMembership.customRole;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Types } from "mongoose";
|
||||
import { AbilityBuilder, MongoAbility, RawRuleOf, createMongoAbility } from "@casl/ability";
|
||||
import {
|
||||
IMachineIdentity,
|
||||
MachineMembershipOrg,
|
||||
IIdentity,
|
||||
IdentityMembershipOrg,
|
||||
MembershipOrg
|
||||
} from "../../models";
|
||||
import { ActorType, IRole, Role } from "../models";
|
||||
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
||||
import { checkIPAgainstBlocklist } from "../../utils/ip";
|
||||
import { ACCEPTED, ADMIN, CUSTOM, MEMBER, NO_ACCESS} from "../../variables";
|
||||
import { conditionsMatcher } from "./ProjectRoleService";
|
||||
import { AuthData } from "../../interfaces/middleware";
|
||||
@@ -28,7 +27,7 @@ export enum OrgPermissionSubjects {
|
||||
Sso = "sso",
|
||||
Billing = "billing",
|
||||
SecretScanning = "secret-scanning",
|
||||
MachineIdentity = "machine-identity"
|
||||
Identity = "identity"
|
||||
}
|
||||
|
||||
export type OrgPermissionSet =
|
||||
@@ -41,7 +40,7 @@ export type OrgPermissionSet =
|
||||
| [OrgPermissionActions, OrgPermissionSubjects.Sso]
|
||||
| [OrgPermissionActions, OrgPermissionSubjects.SecretScanning]
|
||||
| [OrgPermissionActions, OrgPermissionSubjects.Billing]
|
||||
| [OrgPermissionActions, OrgPermissionSubjects.MachineIdentity];
|
||||
| [OrgPermissionActions, OrgPermissionSubjects.Identity];
|
||||
|
||||
const buildAdminPermission = () => {
|
||||
const { can, build } = new AbilityBuilder<MongoAbility<OrgPermissionSet>>(createMongoAbility);
|
||||
@@ -84,10 +83,10 @@ const buildAdminPermission = () => {
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.Billing);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.Billing);
|
||||
|
||||
can(OrgPermissionActions.Read, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Create, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Read, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Create, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.Identity);
|
||||
|
||||
return build({ conditionsMatcher });
|
||||
};
|
||||
@@ -112,10 +111,10 @@ const buildMemberPermission = () => {
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.SecretScanning);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.SecretScanning);
|
||||
|
||||
can(OrgPermissionActions.Read, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Create, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.MachineIdentity);
|
||||
can(OrgPermissionActions.Read, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Create, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Edit, OrgPermissionSubjects.Identity);
|
||||
can(OrgPermissionActions.Delete, OrgPermissionSubjects.Identity);
|
||||
|
||||
return build({ conditionsMatcher });
|
||||
};
|
||||
@@ -203,28 +202,23 @@ export const getUserOrgPermissions = async (userId: string, orgId: string) => {
|
||||
message: "Failed to access organization-level resources with service token"
|
||||
});
|
||||
}
|
||||
case ActorType.MACHINE: {
|
||||
const machineMembershipOrg = await MachineMembershipOrg.findOne({
|
||||
machineIdentity: authData.authPayload._id,
|
||||
case ActorType.IDENTITY: {
|
||||
const identityMembershipOrg = await IdentityMembershipOrg.findOne({
|
||||
identity: authData.authPayload._id,
|
||||
organization: organizationId
|
||||
})
|
||||
.populate<{
|
||||
customRole: IRole & { permissions: RawRuleOf<MongoAbility<OrgPermissionSet>>[] };
|
||||
machineIdentity: IMachineIdentity
|
||||
}>("customRole machineIdentity")
|
||||
identity: IIdentity
|
||||
}>("customRole identity")
|
||||
.exec();
|
||||
|
||||
if (!machineMembershipOrg || (machineMembershipOrg.role === "custom" && !machineMembershipOrg.customRole)) {
|
||||
if (!identityMembershipOrg || (identityMembershipOrg.role === "custom" && !identityMembershipOrg.customRole)) {
|
||||
throw UnauthorizedRequestError();
|
||||
}
|
||||
|
||||
checkIPAgainstBlocklist({
|
||||
ipAddress: authData.ipAddress,
|
||||
trustedIps: machineMembershipOrg.machineIdentity.accessTokenTrustedIps
|
||||
});
|
||||
|
||||
role = machineMembershipOrg.role;
|
||||
customRole = machineMembershipOrg.customRole;
|
||||
role = identityMembershipOrg.role;
|
||||
customRole = identityMembershipOrg.customRole;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
||||
Reference in New Issue
Block a user