Restructure MIs to more generic Identity

This commit is contained in:
Tuan Dang
2023-12-09 22:18:38 +07:00
parent 89d0c0e3c3
commit 50ef23e8a0
102 changed files with 3652 additions and 2981 deletions
+789 -6
View File
@@ -1,21 +1,54 @@
import { Request, Response } from "express";
import { Types } from "mongoose";
import jwt from "jsonwebtoken";
import crypto from "crypto";
import bcrypt from "bcrypt";
import * as bigintConversion from "bigint-conversion";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jsrp = require("jsrp");
import { LoginSRPDetail, TokenVersion, User } from "../../models";
import {
IIdentity,
IIdentityTrustedIp,
IIdentityUniversalAuthClientSecret,
Identity,
IdentityAccessToken,
IdentityAuthMethod,
IdentityMembershipOrg,
IdentityUniversalAuth,
IdentityUniversalAuthClientSecret,
LoginSRPDetail,
TokenVersion,
User
} from "../../models";
import { clearTokens, createToken, issueAuthTokens } from "../../helpers/auth";
import { checkUserDevice } from "../../helpers/user";
import { AuthTokenType } from "../../variables";
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
import {
BadRequestError,
ForbiddenRequestError,
ResourceNotFoundError,
UnauthorizedRequestError
} from "../../utils/errors";
import {
getAuthSecret,
getHttpsEnabled,
getJwtAuthLifetime
getJwtAuthLifetime,
getSaltRounds
} from "../../config";
import { ActorType } from "../../ee/models";
import { ActorType, EventType, IRole } from "../../ee/models";
import { validateRequest } from "../../helpers/validation";
import * as reqValidator from "../../validation/auth";
import { checkIPAgainstBlocklist, extractIPDetails, isValidIpOrCidr } from "../../utils/ip";
import { getUserAgentType } from "../../utils/posthog";
import { EEAuditLogService, EELicenseService } from "../../ee/services";
import {
OrgPermissionActions,
OrgPermissionSubjects,
getAuthDataOrgPermissions,
getOrgRolePermissions,
isAtLeastAsPrivilegedOrg
} from "../../ee/services/RoleService";
import { ForbiddenError } from "@casl/ability";
declare module "jsonwebtoken" {
export interface AuthnJwtPayload extends jwt.JwtPayload {
@@ -25,10 +58,10 @@ declare module "jsonwebtoken" {
userId: string;
refreshVersion?: number;
}
export interface MachineAccessTokenJwtPayload extends jwt.JwtPayload {
export interface IdentityAccessTokenJwtPayload extends jwt.JwtPayload {
_id: string;
clientSecretId: string;
machineAccessTokenId: string;
identityAccessTokenId: string;
authTokenType: string;
}
}
@@ -268,3 +301,753 @@ export const getNewToken = async (req: Request, res: Response) => {
export const handleAuthProviderCallback = (req: Request, res: Response) => {
res.redirect(`/login/provider/success?token=${encodeURIComponent(req.providerAuthToken)}`);
};
// ---- new IDENTITY logic
const packageUniversalAuthClientSecretData = (identityUniversalAuthClientSecret: IIdentityUniversalAuthClientSecret) => ({
_id: identityUniversalAuthClientSecret._id,
identityUniversalAuth: identityUniversalAuthClientSecret.identityUniversalAuth,
isClientSecretRevoked: identityUniversalAuthClientSecret.isClientSecretRevoked,
description: identityUniversalAuthClientSecret.description,
clientSecretPrefix: identityUniversalAuthClientSecret.clientSecretPrefix,
clientSecretNumUses: identityUniversalAuthClientSecret.clientSecretNumUses,
clientSecretNumUsesLimit: identityUniversalAuthClientSecret.clientSecretNumUsesLimit,
clientSecretTTL: identityUniversalAuthClientSecret.clientSecretTTL,
createdAt: identityUniversalAuthClientSecret.createdAt,
updatedAt: identityUniversalAuthClientSecret.updatedAt
});
/**
* 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.IdentityAccessTokenJwtPayload>(
jwt.verify(accessToken, await getAuthSecret())
);
if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) throw UnauthorizedRequestError();
const identityAccessToken = await IdentityAccessToken.findOne({
_id: decodedToken.identityAccessTokenId,
isAccessTokenRevoked: false
});
if (!identityAccessToken) throw UnauthorizedRequestError();
const {
accessTokenTTL,
accessTokenLastRenewedAt,
accessTokenMaxTTL,
createdAt: accessTokenCreatedAt
} = identityAccessToken;
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(
identityAccessToken._id,
{
accessTokenLastRenewedAt: new Date()
}
);
return res.status(200).send({
accessToken,
expiresIn: identityAccessToken.accessTokenTTL,
tokenType: "Bearer"
});
}
/**
* Return access token for identity with client id [clientId]
* and client secret [clientSecret]
* @param req
* @param res
*/
export const loginIdentityUniversalAuth = async (req: Request, res: Response) => {
const {
body: {
clientId,
clientSecret
}
} = await validateRequest(reqValidator.LoginUniversalAuthV1, req);
const identityUniversalAuth = await IdentityUniversalAuth.findOne({
clientId
}).populate<{ identity: IIdentity }>("identity");
if (!identityUniversalAuth) throw UnauthorizedRequestError();
checkIPAgainstBlocklist({
ipAddress: req.realIP,
trustedIps: identityUniversalAuth.clientSecretTrustedIps
});
const clientSecretData = await IdentityUniversalAuthClientSecret.find({
identity: identityUniversalAuth.identity,
isClientSecretRevoked: false
});
let validatedClientSecretDatum: IIdentityUniversalAuthClientSecret | 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 IdentityUniversalAuthClientSecret.findByIdAndUpdate(
validatedClientSecretDatum._id,
{
isClientSecretRevoked: true
}
);
throw UnauthorizedRequestError({
message: "Failed to authenticate identity 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 IdentityUniversalAuthClientSecret.findByIdAndUpdate(
validatedClientSecretDatum._id,
{
isClientSecretRevoked: true
},
{
new: true
}
);
throw UnauthorizedRequestError({
message: "Failed to authenticate identity credentials due to client secret number of uses limit reached"
});
}
// increment usage count by 1
await IdentityUniversalAuthClientSecret
.findByIdAndUpdate(
validatedClientSecretDatum._id,
{
clientSecretLastUsedAt: new Date(),
$inc: { clientSecretNumUses: 1 }
},
{
new: true
}
);
const identityAccessToken = await new IdentityAccessToken({
identity: identityUniversalAuth.identity,
identityUniversalAuthClientSecret: validatedClientSecretDatum._id,
accessTokenNumUses: 0,
accessTokenNumUsesLimit: identityUniversalAuth.accessTokenNumUsesLimit,
accessTokenTTL: identityUniversalAuth.accessTokenTTL,
accessTokenMaxTTL: identityUniversalAuth.accessTokenMaxTTL,
accessTokenTrustedIps: identityUniversalAuth.accessTokenTrustedIps,
isAccessTokenRevoked: false
}).save();
// token version
const accessToken = createToken({
payload: {
identityId: identityUniversalAuth.identity.toString(),
clientSecretId: validatedClientSecretDatum._id.toString(),
identityAccessTokenId: identityAccessToken._id.toString(),
authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN
},
secret: await getAuthSecret()
});
const userAgent = req.headers["user-agent"] ?? "";
await EEAuditLogService.createAuditLog(
{
actor: {
type: ActorType.IDENTITY,
metadata: {
identityId: identityUniversalAuth.identity._id.toString(),
name: identityUniversalAuth.identity.name
}
},
authPayload: identityUniversalAuth.identity,
ipAddress: req.realIP,
userAgent,
userAgentType: getUserAgentType(userAgent)
},
{
type: EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,
metadata: {
identityId: identityUniversalAuth.identity._id.toString(),
clientSecretId: validatedClientSecretDatum._id.toString(),
identityAccessTokenId: identityAccessToken._id.toString()
}
}
);
return res.status(200).send({
accessToken,
expiresIn: identityUniversalAuth.accessTokenTTL,
tokenType: "Bearer"
});
}
export const addIdentityUniversalAuth = async (req: Request, res: Response) => {
const {
params: { identityId },
body: {
clientSecretTrustedIps,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
}
} = await validateRequest(reqValidator.AddUniversalAuthToIdentityV1, 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}`
});
if (identityMembershipOrg.identity?.authMethod) throw BadRequestError({
message: "Failed to add universal auth to already-configured identity"
});
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: identityMembershipOrg.organization
});
ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Create,
OrgPermissionSubjects.Identity
);
const plan = await EELicenseService.getPlan(identityMembershipOrg.organization);
// 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 identityUniversalAuth = await new IdentityUniversalAuth({
identity: identityMembershipOrg.identity._id,
clientId: crypto.randomUUID(),
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
}).save();
await Identity.findByIdAndUpdate(
identityMembershipOrg.identity._id,
{
authMethod: IdentityAuthMethod.UNIVERSAL_AUTH
}
);
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.ADD_IDENTITY_UNIVERSAL_AUTH,
metadata: {
identityId: identityMembershipOrg.identity._id.toString(),
clientSecretTrustedIps: reformattedClientSecretTrustedIps as Array<IIdentityTrustedIp>,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps as Array<IIdentityTrustedIp>
}
}
);
return res.status(200).send({
identityUniversalAuth
});
}
export const updateIdentityUniversalAuth = async (req: Request, res: Response) => {
const {
params: { identityId },
body: {
clientSecretTrustedIps,
accessTokenTTL, // TODO: validate this and max TTL
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
}
} = await validateRequest(reqValidator.UpdateUniversalAuthToIdentityV1, 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}`
});
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.UNIVERSAL_AUTH) throw BadRequestError({
message: "Failed to add universal auth to already-configured identity"
});
const { permission } = await getAuthDataOrgPermissions({
authData: req.authData,
organizationId: identityMembershipOrg.organization
});
ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Edit,
OrgPermissionSubjects.Identity
);
const plan = await EELicenseService.getPlan(identityMembershipOrg.organization);
// validate 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 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);
});
}
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 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 identityUniversalAuth = await IdentityUniversalAuth.findOneAndUpdate(
{
identity: identityMembershipOrg.identity._id,
},
{
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
},
{
new: true
}
);
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.UPDATE_IDENTITY_UNIVERSAL_AUTH,
metadata: {
identityId: identityMembershipOrg.identity._id.toString(),
clientSecretTrustedIps: reformattedClientSecretTrustedIps as Array<IIdentityTrustedIp>,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps as Array<IIdentityTrustedIp>
}
}
);
return res.status(200).send({
identityUniversalAuth
});
}
export const getIdentityUniversalAuth = async (req: Request, res: Response) => {
const {
params: { identityId }
} = await validateRequest(reqValidator.GetUniversalAuthForIdentityV1, 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.Read,
OrgPermissionSubjects.Identity
);
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.UNIVERSAL_AUTH) throw BadRequestError({
message: "The identity does not have universal auth configured"
});
const identityUniversalAuth = await IdentityUniversalAuth.findOne({
identity: identityMembershipOrg.identity._id,
});
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.GET_IDENTITY_UNIVERSAL_AUTH,
metadata: {
identityId: identityMembershipOrg.identity._id.toString(),
}
}
);
return res.status(200).send({
identityUniversalAuth
});
}
export const createUniversalAuthClientSecret = async (req: Request, res: Response) => {
const {
params: { identityId },
body: {
description,
numUsesLimit,
ttl
}
} = await validateRequest(reqValidator.CreateUniversalAuthClientSecretV1, 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.Create,
OrgPermissionSubjects.Identity
);
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.UNIVERSAL_AUTH) throw BadRequestError({
message: "The identity does not have universal auth configured"
});
const rolePermission = await getOrgRolePermissions(
identityMembershipOrg?.customRole?.slug ?? identityMembershipOrg.role,
identityMembershipOrg.organization.toString()
);
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
message: "Failed to create client secret for more privileged identity"
});
const clientSecret = crypto.randomBytes(32).toString("hex");
const clientSecretHash = await bcrypt.hash(clientSecret, await getSaltRounds());
const identityUniversalAuth = await IdentityUniversalAuth.findOne({
identity: identityMembershipOrg.identity._id
});
if (!identityUniversalAuth) throw ResourceNotFoundError();
const identityUniversalAuthClientSecret = await new IdentityUniversalAuthClientSecret({
identity: identityMembershipOrg.identity._id,
identityUniversalAuth: identityUniversalAuth._id,
description,
clientSecretPrefix: clientSecret.slice(0, 4),
clientSecretHash,
clientSecretNumUses: 0,
clientSecretNumUsesLimit: numUsesLimit,
clientSecretTTL: ttl,
isClientSecretRevoked: false
}).save();
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET,
metadata: {
identityId: identityMembershipOrg.identity._id.toString(),
clientSecretId: identityUniversalAuthClientSecret._id.toString()
}
}
);
return res.status(200).send({
clientSecret,
clientSecretData: packageUniversalAuthClientSecretData(identityUniversalAuthClientSecret)
});
}
export const getUniversalAuthClientSecrets = async (req: Request, res: Response) => {
const {
params: { identityId }
} = await validateRequest(reqValidator.GetUniversalAuthClientSecretsV1, req);
const identityMembershipOrg = await IdentityMembershipOrg.findOne({
identity: new Types.ObjectId(identityId)
}).populate<{
identity: IIdentity,
customRole: IRole
}>("identity customRole");
if (!identityMembershipOrg) throw ResourceNotFoundError();
const { permission } = await getAuthDataOrgPermissions({
authData: req.authData,
organizationId: identityMembershipOrg.organization
});
ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Read,
OrgPermissionSubjects.Identity
);
if (identityMembershipOrg.identity?.authMethod !== IdentityAuthMethod.UNIVERSAL_AUTH) throw BadRequestError({
message: "The identity does not have universal auth configured"
});
const rolePermission = await getOrgRolePermissions(
identityMembershipOrg?.customRole?.slug ?? identityMembershipOrg.role,
identityMembershipOrg.organization.toString()
);
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
message: "Failed to get client secrets for more privileged MI"
});
const clientSecretData = await IdentityUniversalAuthClientSecret
.find({
identity: identityMembershipOrg.identity,
isClientSecretRevoked: false
})
.sort({ createdAt: -1 })
.limit(5);
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS,
metadata: {
identityId: identityMembershipOrg.identity._id.toString()
}
}
);
return res.status(200).send({
clientSecretData: clientSecretData.map((clientSecretDatum) => packageUniversalAuthClientSecretData(clientSecretDatum))
});
}
export const revokeUniversalAuthClientSecret = async (req: Request, res: Response) => {
const {
params: { identityId, clientSecretId }
} = await validateRequest(reqValidator.RevokeUniversalAuthClientSecretV1, 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 rolePermission = await getOrgRolePermissions(
identityMembershipOrg?.customRole?.slug ?? identityMembershipOrg.role,
identityMembershipOrg.organization.toString()
);
const hasRequiredPrivileges = isAtLeastAsPrivilegedOrg(permission, rolePermission);
if (!hasRequiredPrivileges) throw ForbiddenRequestError({
message: "Failed to delete client secrets for more privileged identity"
});
const clientSecretData = await IdentityUniversalAuthClientSecret.findOneAndUpdate(
{
_id: new Types.ObjectId(clientSecretId),
identity: identityMembershipOrg.identity._id
},
{
isClientSecretRevoked: true
},
{
new: true
}
);
if (!clientSecretData) throw ResourceNotFoundError();
await EEAuditLogService.createAuditLog(
req.authData,
{
type: EventType.REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET,
metadata: {
identityId: identityMembershipOrg.identity._id.toString(),
clientSecretId: clientSecretId
}
}
);
return res.status(200).send({
clientSecretData: packageUniversalAuthClientSecretData(clientSecretData)
})
}
@@ -1,7 +1,7 @@
import { Request, Response } from "express";
import { Types } from "mongoose";
import {
MachineMembershipOrg,
IdentityMembershipOrg,
Membership,
MembershipOrg,
Workspace
@@ -419,15 +419,15 @@ export const deleteOrganizationById = async (req: Request, res: Response) => {
};
/**
* Return list of service memberships for organization with id [organizationId]
* Return list of identity memberships for organization with id [organizationId]
* @param req
* @param res
* @returns
*/
export const getOrganizationMachineMemberships = async (req: Request, res: Response) => {
export const getOrganizationIdentityMemberships = async (req: Request, res: Response) => {
const {
params: { organizationId }
} = await validateRequest(reqValidator.GetOrgServiceMembersV2, req);
} = await validateRequest(reqValidator.GetOrgIdentityMembershipsV2, req);
const { permission } = await getAuthDataOrgPermissions({
authData: req.authData,
@@ -435,14 +435,14 @@ export const getOrganizationMachineMemberships = async (req: Request, res: Respo
});
ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Read,
OrgPermissionSubjects.MachineIdentity
OrgPermissionSubjects.Identity
);
const machineMemberships = await MachineMembershipOrg.find({
const identityMemberships = await IdentityMembershipOrg.find({
organization: new Types.ObjectId(organizationId)
}).populate("machineIdentity customRole");
}).populate("identity customRole");
return res.status(200).send({
machineMemberships
identityMemberships
});
}
@@ -1,10 +1,10 @@
import { Request, Response } from "express";
import { Types } from "mongoose";
import {
IMachineIdentity,
IIdentity,
IdentityMembership,
IdentityMembershipOrg,
Key,
MachineIdentity,
MachineMembership,
Membership,
ServiceTokenData,
Workspace
@@ -506,18 +506,18 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
};
/**
* Add machine identity with id [machineId] to workspace
* Add identity with id [identityId] to workspace
* with id [workspaceId]
* @param req
* @param res
*/
export const addMachineToWorkspace = async (req: Request, res: Response) => {
export const addIdentityToWorkspace = async (req: Request, res: Response) => {
const {
params: { workspaceId, machineId },
params: { workspaceId, identityId },
body: {
role
}
} = await validateRequest(reqValidator.AddMachineToWorkspaceV2, req);
} = await validateRequest(reqValidator.AddIdentityToWorkspaceV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
@@ -526,35 +526,40 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Create,
ProjectPermissionSub.MachineIdentity
ProjectPermissionSub.Identity
);
let machineMembership = await MachineMembership.findOne({
machineIdentity: new Types.ObjectId(machineId),
let identityMembership = await IdentityMembership.findOne({
identity: new Types.ObjectId(identityId),
workspace: new Types.ObjectId(workspaceId)
});
if (machineMembership) throw BadRequestError({
message: `Machine identity with id ${machineId} already exists in project with id ${workspaceId}`
if (identityMembership) throw BadRequestError({
message: `Identity with id ${identityId} already exists in project with id ${workspaceId}`
});
const machineIdentity = await MachineIdentity.findById(machineId);
if (!machineIdentity) throw ResourceNotFoundError({
message: `Failed to find machine identity with id ${machineId}`
});
const workspace = await Workspace.findById(workspaceId);
if (!workspace) throw ResourceNotFoundError();
const identityMembershipOrg = await IdentityMembershipOrg.findOne({
identity: new Types.ObjectId(identityId),
organization: workspace.organization
});
if (!identityMembershipOrg) throw ResourceNotFoundError({
message: `Failed to find identity with id ${identityId}`
});
if (!machineIdentity.organization.equals(workspace.organization)) throw BadRequestError({
message: "Failed to add machine identity to project in another organization"
if (!identityMembershipOrg.organization.equals(workspace.organization)) throw BadRequestError({
message: "Failed to add identity to project in another organization"
});
const rolePermission = await getWorkspaceRolePermissions(role, workspaceId);
const isAsPrivilegedAsIntendedRole = isAtLeastAsPrivilegedWorkspace(permission, rolePermission);
if (!isAsPrivilegedAsIntendedRole) throw ForbiddenRequestError({
message: "Failed to add MI to project with more privileged role"
message: "Failed to add identity to project with more privileged role"
});
let customRole;
@@ -571,31 +576,31 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
}
}
machineMembership = await new MachineMembership({
machineIdentity: machineIdentity._id,
identityMembership = await new IdentityMembership({
identity: identityMembershipOrg.identity,
workspace: new Types.ObjectId(workspaceId),
role: customRole ? CUSTOM : role,
customRole
}).save();
return res.status(200).send({
machineMembership
identityMembership
});
}
/**
* Update role of machine identity with id [machineId] in workspace
* Update role of identity with id [identityId] in workspace
* with id [workspaceId] to [role]
* @param req
* @param res
*/
export const updateMachineWorkspaceRole = async (req: Request, res: Response) => {
export const updateIdentityWorkspaceRole = async (req: Request, res: Response) => {
const {
params: { workspaceId, machineId },
params: { workspaceId, identityId },
body: {
role
}
} = await validateRequest(reqValidator.UpdateMachineWorkspaceRoleV2, req);
} = await validateRequest(reqValidator.UpdateIdentityWorkspaceRoleV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
@@ -604,37 +609,37 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Edit,
ProjectPermissionSub.MachineIdentity
ProjectPermissionSub.Identity
);
let machineMembership = await MachineMembership
let identityMembership = await IdentityMembership
.findOne({
machineIdentity: new Types.ObjectId(machineId),
identity: new Types.ObjectId(identityId),
workspace: new Types.ObjectId(workspaceId)
})
.populate<{
machineIdentity: IMachineIdentity,
identity: IIdentity,
customRole: IRole
}>("machineIdentity customRole");
}>("identity customRole");
if (!machineMembership) throw BadRequestError({
message: `Machine identity with id ${machineId} does not exist in project with id ${workspaceId}`
if (!identityMembership) throw BadRequestError({
message: `Identity with id ${identityId} does not exist in project with id ${workspaceId}`
});
const machineIdentityRolePermission = await getWorkspaceRolePermissions(
machineMembership?.customRole?.slug ?? machineMembership.role,
machineMembership.workspace.toString()
const identityRolePermission = await getWorkspaceRolePermissions(
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership.workspace.toString()
);
const isAsPrivilegedAsMachine = isAtLeastAsPrivilegedWorkspace(permission, machineIdentityRolePermission);
if (!isAsPrivilegedAsMachine) throw ForbiddenRequestError({
message: "Failed to update role of more privileged MI"
const isAsPrivilegedAsIdentity = isAtLeastAsPrivilegedWorkspace(permission, identityRolePermission);
if (!isAsPrivilegedAsIdentity) throw ForbiddenRequestError({
message: "Failed to update role of more privileged identity"
});
const rolePermission = await getWorkspaceRolePermissions(role, workspaceId);
const isAsPrivilegedAsIntendedRole = isAtLeastAsPrivilegedWorkspace(permission, rolePermission);
if (!isAsPrivilegedAsIntendedRole) throw ForbiddenRequestError({
message: "Failed to update MI to a more privileged role"
message: "Failed to update identity to a more privileged role"
});
let customRole;
@@ -651,9 +656,9 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
}
}
machineMembership = await MachineMembership.findOneAndUpdate(
identityMembership = await IdentityMembership.findOneAndUpdate(
{
machineIdentity: machineMembership.machineIdentity,
identity: identityMembership.identity._id,
workspace: new Types.ObjectId(workspaceId),
},
{
@@ -666,20 +671,20 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
);
return res.status(200).send({
machineMembership
identityMembership
});
}
/**
* Delete machine identity with id [machineId] to workspace
* Delete identity with id [identityId] to workspace
* with id [workspaceId]
* @param req
* @param res
*/
export const deleteMachineFromWorkspace = async (req: Request, res: Response) => {
export const deleteIdentityFromWorkspace = async (req: Request, res: Response) => {
const {
params: { workspaceId, machineId }
} = await validateRequest(reqValidator.DeleteMachineFromWorkspaceV2, req);
params: { workspaceId, identityId }
} = await validateRequest(reqValidator.DeleteIdentityFromWorkspaceV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
@@ -688,49 +693,49 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Delete,
ProjectPermissionSub.MachineIdentity
ProjectPermissionSub.Identity
);
const machineMembership = await MachineMembership
const identityMembership = await IdentityMembership
.findOne({
machineIdentity: new Types.ObjectId(machineId),
identity: new Types.ObjectId(identityId),
workspace: new Types.ObjectId(workspaceId)
})
.populate<{
machineIdentity: IMachineIdentity,
identity: IIdentity,
customRole: IRole
}>("machineIdentity customRole");
}>("identity customRole");
if (!machineMembership) throw ResourceNotFoundError({
message: `Machine with id ${machineId} does not exist in project with id ${workspaceId}`
if (!identityMembership) throw ResourceNotFoundError({
message: `Identity with id ${identityId} does not exist in project with id ${workspaceId}`
});
const machineIdentityRolePermission = await getWorkspaceRolePermissions(
machineMembership?.customRole?.slug ?? machineMembership.role,
machineMembership.workspace.toString()
const identityRolePermission = await getWorkspaceRolePermissions(
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership.workspace.toString()
);
const isAsPrivilegedAsMachine = isAtLeastAsPrivilegedWorkspace(permission, machineIdentityRolePermission);
if (!isAsPrivilegedAsMachine) throw ForbiddenRequestError({
message: "Failed to remove more privileged MI from project"
const isAsPrivilegedAsIdentity = isAtLeastAsPrivilegedWorkspace(permission, identityRolePermission);
if (!isAsPrivilegedAsIdentity) throw ForbiddenRequestError({
message: "Failed to remove more privileged identity from project"
});
await MachineMembership.findByIdAndDelete(machineMembership._id);
await IdentityMembership.findByIdAndDelete(identityMembership._id);
return res.status(200).send({
machineMembership
identityMembership
});
}
/**
* Return list of machine identity memberships for workspace with id [workspaceId]
* Return list of identity memberships for workspace with id [workspaceId]
* @param req
* @param res
* @returns
*/
export const getWorkspaceMachineMemberships = async (req: Request, res: Response) => {
export const getWorkspaceIdentityMemberships = async (req: Request, res: Response) => {
const {
params: { workspaceId }
} = await validateRequest(reqValidator.GetWorkspaceMachineMembersV2, req);
} = await validateRequest(reqValidator.GetWorkspaceIdentityMembersV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
@@ -739,14 +744,14 @@ export const addMachineToWorkspace = async (req: Request, res: Response) => {
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Read,
ProjectPermissionSub.MachineIdentity
ProjectPermissionSub.Identity
);
const machineMemberships = await MachineMembership.find({
const identityMemberships = await IdentityMembership.find({
workspace: new Types.ObjectId(workspaceId)
}).populate("machineIdentity customRole");
}).populate("identity customRole");
return res.status(200).send({
machineMemberships
identityMemberships
});
}
@@ -94,7 +94,7 @@ const checkSecretsPermission = async ({
});
return { authVerifier: () => true };
}
case ActorType.MACHINE: {
case ActorType.IDENTITY: {
const { permission } = await getAuthDataProjectPermissions({
authData,
workspaceId: new Types.ObjectId(workspaceId)
@@ -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
});
}
+2 -2
View File
@@ -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
+1 -1
View File
@@ -10,7 +10,7 @@ export interface IAuditLog {
event: Event;
userAgent: string;
userAgentType: UserAgentType;
expiresAt: Date;
expiresAt?: Date;
}
const auditLogSchema = new Schema<IAuditLog>(
+13 -10
View File
@@ -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",
+71 -48
View File
@@ -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
+31
View File
@@ -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;
+2 -2
View File
@@ -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;
+22 -12
View File
@@ -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) {
+21 -27
View File
@@ -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;
}
+20 -26
View File
@@ -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:
+6 -6
View File
@@ -4,13 +4,13 @@ import {
BotKey,
BotOrg,
Folder,
Identity,
IdentityMembership,
IdentityMembershipOrg,
IncidentContactOrg,
Integration,
IntegrationAuth,
Key,
MachineIdentity,
MachineMembership,
MachineMembershipOrg,
Membership,
MembershipOrg,
Organization,
@@ -125,11 +125,11 @@ export const deleteOrganization = async ({
organization: organization._id
});
await MachineIdentity.deleteMany({
await Identity.deleteMany({
organization: organization._id
});
await MachineMembershipOrg.deleteMany({
await IdentityMembershipOrg.deleteMany({
organization: organization._id
});
@@ -277,7 +277,7 @@ export const deleteOrganization = async ({
}
});
await MachineMembership.deleteMany({
await IdentityMembership.deleteMany({
workspace: {
$in: workspaceIds
}
+2 -2
View File
@@ -3,10 +3,10 @@ import {
Bot,
BotKey,
Folder,
IdentityMembership,
Integration,
IntegrationAuth,
Key,
MachineMembership,
Membership,
Secret,
SecretBlindIndexData,
@@ -178,7 +178,7 @@ export const deleteWorkspace = async ({
workspace: workspace._id
});
await MachineMembership.deleteMany({
await IdentityMembership.deleteMany({
workspace: workspace._id
});
+3 -3
View File
@@ -25,7 +25,7 @@ import {
secretSnapshot as eeSecretSnapshotRouter,
users as eeUsersRouter,
workspace as eeWorkspaceRouter,
machineIdentities as v1MachineIdentitiesRouter,
identities as v1IdentitiesRouter,
roles as v1RoleRouter,
secretApprovalPolicy as v1SecretApprovalPolicyRouter,
secretApprovalRequest as v1SecretApprovalRequestRouter,
@@ -198,7 +198,7 @@ const main = async () => {
}
// (EE) routes
app.use("/api/v1/machine-identities", v1MachineIdentitiesRouter);
app.use("/api/v1/identities", v1IdentitiesRouter);
app.use("/api/v1/secret", eeSecretRouter);
app.use("/api/v1/secret-snapshot", eeSecretSnapshotRouter);
app.use("/api/v1/users", eeUsersRouter);
@@ -212,7 +212,7 @@ const main = async () => {
// v1 routes
app.use("/api/v1/signup", v1SignupRouter);
app.use("/api/v1/auth", v1AuthRouter);
app.use("/api/v1/auth", v1AuthRouter); // note: updated for identities
app.use("/api/v1/admin", v1AdminRouter);
app.use("/api/v1/bot", v1BotRouter);
app.use("/api/v1/user", v1UserRouter);
+6 -6
View File
@@ -1,6 +1,6 @@
import { Types } from "mongoose";
import { IMachineIdentity, IServiceTokenData, IUser } from "../../models";
import { MachineActor, ServiceActor, UserActor, UserAgentType } from "../../ee/models";
import { IIdentity, IServiceTokenData, IUser } from "../../models";
import { IdentityActor, ServiceActor, UserActor, UserAgentType } from "../../ee/models";
interface BaseAuthData {
ipAddress: string;
@@ -14,9 +14,9 @@ export interface UserAuthData extends BaseAuthData {
authPayload: IUser;
}
export interface MachineIdentityAuthData extends BaseAuthData {
actor: MachineActor;
authPayload: IMachineIdentity;
export interface IdentityAuthData extends BaseAuthData {
actor: IdentityActor;
authPayload: IIdentity;
}
export interface ServiceTokenAuthData extends BaseAuthData {
@@ -24,4 +24,4 @@ export interface ServiceTokenAuthData extends BaseAuthData {
authPayload: IServiceTokenData;
}
export type AuthData = UserAuthData | MachineIdentityAuthData | ServiceTokenAuthData;
export type AuthData = UserAuthData | IdentityAuthData | ServiceTokenAuthData;
+1 -1
View File
@@ -50,7 +50,7 @@ const requireAuth = ({
case AuthMode.SERVICE_TOKEN:
req.serviceTokenData = authData.authPayload;
break;
case AuthMode.MACHINE_ACCESS_TOKEN:
case AuthMode.IDENTITY_ACCESS_TOKEN:
req.serviceTokenData = authData.authPayload;
break;
case AuthMode.API_KEY:
+38
View File
@@ -0,0 +1,38 @@
import { Document, Schema, Types, model } from "mongoose";
import { IPType } from "../ee/models";
export interface IIdentityTrustedIp {
ipAddress: string;
type: IPType;
prefix: number;
}
export enum IdentityAuthMethod {
UNIVERSAL_AUTH = "universal-auth"
}
export interface IIdentity extends Document {
_id: Types.ObjectId;
name: string;
authMethod?: IdentityAuthMethod;
}
const identitySchema = new Schema(
{
name: {
type: String,
required: true
},
authMethod: {
type: String,
enum: IdentityAuthMethod,
required: false,
},
},
{
timestamps: true
}
);
export const Identity = model<IIdentity>("Identity", identitySchema);
+38 -7
View File
@@ -1,15 +1,18 @@
import { Document, Schema, Types, model } from "mongoose";
import { IIdentityTrustedIp } from "./identity";
import { IPType } from "../ee/models/trustedIp";
export interface IIdentityAccessToken extends Document {
_id: Types.ObjectId;
machineIdentity?: Types.ObjectId;
machineIdentityClientSecret?: Types.ObjectId;
identity: Types.ObjectId;
identityUniversalAuthClientSecret?: Types.ObjectId;
accessTokenLastUsedAt?: Date;
accessTokenLastRenewedAt?: Date;
accessTokenNumUses: number;
accessTokenNumUsesLimit: number;
accessTokenTTL: number;
accessTokenMaxTTL: number;
accessTokenTrustedIps: Array<IIdentityTrustedIp>;
isAccessTokenRevoked: boolean;
updatedAt: Date;
createdAt: Date;
@@ -17,14 +20,14 @@ export interface IIdentityAccessToken extends Document {
const identityAccessTokenSchema = new Schema(
{
machineIdentity: {
identity: {
type: Schema.Types.ObjectId,
ref: "MachineIdentity",
ref: "Identity",
required: false
},
machineIdentityClientSecret: {
identityUniversalAuthClientSecret: {
type: Schema.Types.ObjectId,
ref: "MachineIdentityClientSecret",
ref: "IdentityUniversalAuthClientSecret",
required: false
},
accessTokenLastUsedAt: {
@@ -59,6 +62,34 @@ const identityAccessTokenSchema = new Schema(
default: 7200,
required: true
},
accessTokenTrustedIps: {
type: [
{
ipAddress: {
type: String,
required: true
},
type: {
type: String,
enum: [
IPType.IPV4,
IPType.IPV6
],
required: true
},
prefix: {
type: Number,
required: false
}
}
],
default: [{
ipAddress: "0.0.0.0",
type: IPType.IPV4.toString(),
prefix: 0
}],
required: true
},
isAccessTokenRevoked: {
type: Boolean,
default: false,
@@ -70,4 +101,4 @@ const identityAccessTokenSchema = new Schema(
}
);
export const IdentityAccessToken = model<IIdentityAccessToken>("IdentityAccessToken", identityAccessTokenSchema);
export const IdentityAccessToken = model<IIdentityAccessToken>("IdentityAccessToken", identityAccessTokenSchema);
@@ -1,19 +1,19 @@
import { Schema, Types, model } from "mongoose";
import { ADMIN, CUSTOM, MEMBER, NO_ACCESS, VIEWER } from "../variables";
export interface IMachineMembership {
export interface IIdentityMembership {
_id: Types.ObjectId;
machineIdentity: Types.ObjectId;
identity: Types.ObjectId;
workspace: Types.ObjectId;
role: "admin" | "member" | "viewer" | "no-access" | "custom";
customRole: Types.ObjectId;
}
const machineMembershipSchema = new Schema<IMachineMembership>(
const identityMembershipSchema = new Schema<IIdentityMembership>(
{
machineIdentity: {
identity: {
type: Schema.Types.ObjectId,
ref: "MachineIdentity"
ref: "Identity"
},
workspace: {
type: Schema.Types.ObjectId,
@@ -36,4 +36,4 @@ const machineMembershipSchema = new Schema<IMachineMembership>(
}
);
export const MachineMembership = model<IMachineMembership>("MachineMembership", machineMembershipSchema);
export const IdentityMembership = model<IIdentityMembership>("IdentityMembership", identityMembershipSchema);
@@ -1,19 +1,19 @@
import { Schema, Types, model } from "mongoose";
import { ADMIN, CUSTOM, MEMBER, NO_ACCESS} from "../variables";
export interface IMachineMembershipOrg {
export interface IIdentityMembershipOrg {
_id: Types.ObjectId;
machineIdentity: Types.ObjectId;
identity: Types.ObjectId;
organization: Types.ObjectId;
role: "admin" | "member" | "no-access" | "custom";
customRole: Types.ObjectId;
}
const machineMembershipOrgSchema = new Schema<IMachineMembershipOrg>(
const identityMembershipOrgSchema = new Schema<IIdentityMembershipOrg>(
{
machineIdentity: {
identity: {
type: Schema.Types.ObjectId,
ref: "MachineIdentity"
ref: "Identity"
},
organization: {
type: Schema.Types.ObjectId,
@@ -34,4 +34,4 @@ const machineMembershipOrgSchema = new Schema<IMachineMembershipOrg>(
}
);
export const MachineMembershipOrg = model<IMachineMembershipOrg>("MachineMembershipOrg", machineMembershipOrgSchema);
export const IdentityMembershipOrg = model<IIdentityMembershipOrg>("IdentityMembershipOrg", identityMembershipOrgSchema);
@@ -1,57 +1,29 @@
import { Document, Schema, Types, model } from "mongoose";
import { IPType } from "../ee/models";
import { IIdentityTrustedIp } from "./identity";
export interface IMachineIdentityTrustedIp {
ipAddress: string;
type: IPType;
prefix: number;
}
export interface IMachineIdentity extends Document {
export interface IIdentityUniversalAuth extends Document {
_id: Types.ObjectId;
identity: Types.ObjectId;
clientId: string;
name: string;
organization: Types.ObjectId;
clientSecretTrustedIps: Array<IIdentityTrustedIp>;
accessTokenTTL: number;
accessTokenMaxTTL: number;
accessTokenNumUsesLimit: number;
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
accessTokenTrustedIps: Array<IIdentityTrustedIp>;
}
const machineIdentitySchema = new Schema(
const identityUniversalAuthSchema = new Schema(
{
identity: {
type: Schema.Types.ObjectId,
ref: "Identity",
required: true
},
clientId: {
type: String,
required: true
},
name: {
type: String,
required: true
},
organization: {
type: Schema.Types.ObjectId,
ref: "Organization",
required: true
},
accessTokenTTL: { // seconds
// incremental lifetime
type: Number,
default: 7200,
required: true
},
accessTokenMaxTTL: { // seconds
// max lifetime
type: Number,
default: 7200,
required: true
},
accessTokenNumUsesLimit: {
// number of times access token can be used for
type: Number,
default: 0, // default: used as many times as needed
required: true
},
clientSecretTrustedIps: {
type: [
{
@@ -80,6 +52,24 @@ const machineIdentitySchema = new Schema(
}],
required: true
},
accessTokenTTL: { // seconds
// incremental lifetime
type: Number,
default: 7200,
required: true
},
accessTokenMaxTTL: { // seconds
// max lifetime
type: Number,
default: 7200,
required: true
},
accessTokenNumUsesLimit: {
// number of times access token can be used for
type: Number,
default: 0, // default: used as many times as needed
required: true
},
accessTokenTrustedIps: {
type: [
{
@@ -114,6 +104,4 @@ const machineIdentitySchema = new Schema(
}
);
machineIdentitySchema.index({ clientId: 1 })
export const MachineIdentity = model<IMachineIdentity>("MachineIdentity", machineIdentitySchema);
export const IdentityUniversalAuth = model<IIdentityUniversalAuth>("IdentityUniversalAuth", identityUniversalAuthSchema);
@@ -1,8 +1,9 @@
import { Document, Schema, Types, model } from "mongoose";
export interface IMachineIdentityClientSecret extends Document {
export interface IIdentityUniversalAuthClientSecret extends Document {
_id: Types.ObjectId;
machineIdentity: Types.ObjectId;
identity: Types.ObjectId;
identityUniversalAuth : Types.ObjectId;
description: string;
clientSecretPrefix: string;
clientSecretHash: string;
@@ -15,11 +16,16 @@ export interface IMachineIdentityClientSecret extends Document {
isClientSecretRevoked: boolean;
}
const machineIdentityClientSecretSchema = new Schema(
const identityUniversalAuthClientSecretSchema = new Schema(
{
machineIdentity: {
identity: {
type: Schema.Types.ObjectId,
ref: "MachineIdentity",
ref: "Identity",
required: true
},
identityUniversalAuth: {
type: Schema.Types.ObjectId,
ref: "IdentityUniversalAuth",
required: true
},
description: {
@@ -68,8 +74,8 @@ const machineIdentityClientSecretSchema = new Schema(
}
);
machineIdentityClientSecretSchema.index(
{ machineIdentity: 1, isClientSecretRevoked: 1 }
)
identityUniversalAuthClientSecretSchema.index(
{ identityUniversalAuth: 1, isClientSecretRevoked: 1 }
);
export const MachineIdentityClientSecret = model<IMachineIdentityClientSecret>("MachineIdentityClientSecret", machineIdentityClientSecretSchema);
export const IdentityUniversalAuthClientSecret = model<IIdentityUniversalAuthClientSecret>("IdentityUniversalAuthClientSecret", identityUniversalAuthClientSecretSchema);
+8 -4
View File
@@ -20,11 +20,15 @@ export * from "./user";
export * from "./userAction";
export * from "./workspace";
export * from "./serviceTokenData"; // TODO: deprecate
export * from "./machineIdentity";
export * from "./machineIdentityClientSecret";
// new
export * from "./identity";
export * from "./identityMembership";
export * from "./identityMembershipOrg";
export * from "./identityUniversalAuth";
export * from "./identityUniversalAuthClientSecret";
export * from "./identityAccessToken";
export * from "./machineMembershipOrg";
export * from "./machineMembership";
export * from "./apiKeyData"; // TODO: deprecate
export * from "./apiKeyDataV2";
export * from "./loginSRPDetail";
+60
View File
@@ -48,4 +48,64 @@ router.delete(
authController.revokeAllSessions
);
// --- identity endpoints
router.post(
"/token/renew",
authController.renewAccessToken
);
router.post(
"/universal-auth/login",
authController.loginIdentityUniversalAuth
);
router.post(
"/universal-auth/identities/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.addIdentityUniversalAuth
);
router.patch(
"/universal-auth/identities/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.updateIdentityUniversalAuth
);
router.get(
"/universal-auth/identities/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.getIdentityUniversalAuth
);
router.post(
"/universal-auth/identities/:identityId/client-secrets",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.createUniversalAuthClientSecret
);
router.get(
"/universal-auth/identities/:identityId/client-secrets",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.getUniversalAuthClientSecrets
);
router.delete(
"/universal-auth/identities/:identityId/client-secrets/:clientSecretId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
authController.revokeUniversalAuthClientSecret
);
export default router;
+2 -2
View File
@@ -55,11 +55,11 @@ router.delete(
);
router.get(
"/:organizationId/machine-memberships",
"/:organizationId/identity-memberships",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
organizationsController.getOrganizationMachineMemberships
organizationsController.getOrganizationIdentityMemberships
);
export default router;
+3 -3
View File
@@ -6,7 +6,7 @@ import {
import { AuthMode } from "../../variables";
import { serviceTokenDataController } from "../../controllers/v2";
router.get( // TODO: deprecate (moving to machine identity)
router.get( // TODO: deprecate (moving to identity)
"/",
requireAuth({
acceptedAuthModes: [AuthMode.SERVICE_TOKEN]
@@ -14,7 +14,7 @@ router.get( // TODO: deprecate (moving to machine identity)
serviceTokenDataController.getServiceTokenData
);
router.post( // TODO: deprecate (moving to machine identity)
router.post( // TODO: deprecate (moving to identity)
"/",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
@@ -22,7 +22,7 @@ router.post( // TODO: deprecate (moving to machine identity)
serviceTokenDataController.createServiceTokenData
);
router.delete( // TODO: deprecate (moving to machine identity)
router.delete( // TODO: deprecate (moving to identity)
"/:serviceTokenDataId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
+9 -8
View File
@@ -94,35 +94,36 @@ router.patch(
);
router.post(
"/:workspaceId/machine-memberships/:machineId",
"/:workspaceId/identity-memberships/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY]
}),
workspaceController.addMachineToWorkspace
workspaceController.addIdentityToWorkspace
);
router.patch(
"/:workspaceId/machine-memberships/:machineId",
"/:workspaceId/identity-memberships/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY]
}),
workspaceController.updateMachineWorkspaceRole
workspaceController.updateIdentityWorkspaceRole
);
router.delete(
"/:workspaceId/machine-memberships/:machineId",
"/:workspaceId/identity-memberships/:identityId",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY]
}),
workspaceController.deleteMachineFromWorkspace
workspaceController.deleteIdentityFromWorkspace
);
router.get(
"/:workspaceId/machine-memberships",
"/:workspaceId/identity-memberships",
requireAuth({
acceptedAuthModes: [AuthMode.JWT]
}),
workspaceController.getWorkspaceMachineMemberships
workspaceController.getWorkspaceIdentityMemberships
);
export default router;
+10 -10
View File
@@ -7,7 +7,7 @@ import { AuthMode } from "../../variables";
router.get(
"/raw",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]
}),
secretsController.getSecretsRaw
);
@@ -15,7 +15,7 @@ router.get(
router.get(
"/raw/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "query"
@@ -29,7 +29,7 @@ router.get(
router.post(
"/raw/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -43,7 +43,7 @@ router.post(
router.patch(
"/raw/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -57,7 +57,7 @@ router.patch(
router.delete(
"/raw/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -71,7 +71,7 @@ router.delete(
router.get(
"/",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "query"
@@ -116,7 +116,7 @@ router.delete(
router.post(
"/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -127,7 +127,7 @@ router.post(
router.get(
"/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "query"
@@ -138,7 +138,7 @@ router.get(
router.patch(
"/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -149,7 +149,7 @@ router.patch(
router.delete(
"/:secretName",
requireAuth({
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN, AuthMode.MACHINE_ACCESS_TOKEN]
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY, AuthMode.API_KEY_V2, AuthMode.SERVICE_TOKEN]
}),
requireBlindIndicesEnabled({
locationWorkspaceId: "body"
@@ -1,33 +1,33 @@
import jwt from "jsonwebtoken";
import {
IMachineIdentity,
IdentityAccessToken,
} from "../../../models";
import { IIdentity, IdentityAccessToken } from "../../../models";
import { getAuthSecret } from "../../../config";
import { AuthTokenType } from "../../../variables";
import { UnauthorizedRequestError } from "../../errors";
import { checkIPAgainstBlocklist } from "../../../utils/ip";
interface ValidateMachineIdentityParams {
interface ValidateIdentityParams {
authTokenValue: string;
ipAddress: string;
}
export const validateMachineIdentity = async ({
authTokenValue
}: ValidateMachineIdentityParams) => {
const decodedToken = <jwt.MachineAccessTokenJwtPayload>(
export const validateIdentity = async ({
authTokenValue,
ipAddress
}: ValidateIdentityParams) => {
const decodedToken = <jwt.IdentityAccessTokenJwtPayload>(
jwt.verify(authTokenValue, await getAuthSecret())
);
if (decodedToken.authTokenType !== AuthTokenType.MACHINE_ACCESS_TOKEN) throw UnauthorizedRequestError();
if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) throw UnauthorizedRequestError();
const machineIdentityAccessToken = await IdentityAccessToken
const identityAccessToken = await IdentityAccessToken
.findOne({
_id: decodedToken.identityAccessTokenId,
isAccessTokenRevoked: false
})
.populate<{ machineIdentity: IMachineIdentity }>("machineIdentity");
.populate<{ identity: IIdentity }>("identity");
if (!machineIdentityAccessToken || !machineIdentityAccessToken?.machineIdentity) throw UnauthorizedRequestError();
if (!identityAccessToken || !identityAccessToken?.identity) throw UnauthorizedRequestError();
const {
accessTokenNumUsesLimit,
@@ -36,7 +36,12 @@ export const validateMachineIdentity = async ({
accessTokenLastRenewedAt,
accessTokenMaxTTL,
createdAt: accessTokenCreatedAt
} = machineIdentityAccessToken;
} = identityAccessToken;
checkIPAgainstBlocklist({
ipAddress,
trustedIps: identityAccessToken.accessTokenTrustedIps
});
// ttl check
if (accessTokenTTL > 0) {
@@ -48,7 +53,7 @@ export const validateMachineIdentity = async ({
const expirationDate = new Date(accessTokenRenewed.getTime() + ttlInMilliseconds);
if (currentDate > expirationDate) throw UnauthorizedRequestError({
message: "Failed to authenticate MI access token due to TTL expiration"
message: "Failed to authenticate identity access token due to TTL expiration"
});
} else {
// access token has never been renewed
@@ -57,7 +62,7 @@ export const validateMachineIdentity = async ({
const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
if (currentDate > expirationDate) throw UnauthorizedRequestError({
message: "Failed to authenticate MI access token due to TTL expiration"
message: "Failed to authenticate identity access token due to TTL expiration"
});
}
}
@@ -70,7 +75,7 @@ export const validateMachineIdentity = async ({
const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
if (currentDate > expirationDate) throw UnauthorizedRequestError({
message: "Failed to authenticate MI access token due to Max TTL expiration"
message: "Failed to authenticate identity access token due to Max TTL expiration"
});
}
@@ -85,7 +90,7 @@ export const validateMachineIdentity = async ({
}
await IdentityAccessToken.findByIdAndUpdate(
machineIdentityAccessToken._id,
identityAccessToken._id,
{
accessTokenLastUsedAt: new Date(),
$inc: { accessTokenNumUses: 1 }
@@ -95,5 +100,5 @@ export const validateMachineIdentity = async ({
}
);
return machineIdentityAccessToken.machineIdentity;
return identityAccessToken.identity;
}
@@ -2,4 +2,4 @@ export * from "./apiKey";
export * from "./apiKeyV2";
export * from "./jwt";
export * from "./serviceTokenV2";
export * from "./machineIdentity";
export * from "./identity";
@@ -1,6 +1,6 @@
import { AuthData } from "../../../interfaces/middleware";
import {
MachineIdentity,
Identity,
ServiceTokenData,
User
} from "../../../models";
@@ -19,7 +19,7 @@ import {
return { serviceTokenDataId: authData.authPayload._id };
}
if (authData.authPayload instanceof MachineIdentity) {
if (authData.authPayload instanceof Identity) {
return { serviceTokenDataId: authData.authPayload._id };
}
};
@@ -38,7 +38,7 @@ export const getAuthDataPayloadUserObj = (authData: AuthData) => {
return { user: authData.authPayload.user };
}
if (authData.authPayload instanceof MachineIdentity) {
if (authData.authPayload instanceof Identity) {
return {};
}
}
+12 -11
View File
@@ -7,8 +7,8 @@ import { UnauthorizedRequestError } from "../../errors";
import {
validateAPIKey,
validateAPIKeyV2,
validateIdentity,
validateJWT,
validateMachineIdentity,
validateServiceTokenV2
} from "../authModeValidators";
import { getUserAgentType } from "../../posthog";
@@ -36,7 +36,7 @@ interface GetAuthDataParams {
* - SERVICE_TOKEN
* - API_KEY
* - JWT
* - MACHINE_ACCESS_TOKEN (from machine identity)
* - IDENTITY_ACCESS_TOKEN (from identity)
* - API_KEY_V2
* @param {Object} params
* @param {Object.<string, (string|string[]|undefined)>} params.headers - The HTTP request headers, usually from Express's `req.headers`.
@@ -77,8 +77,8 @@ export const extractAuthMode = async ({
return { authMode: AuthMode.JWT, authTokenValue };
case AuthTokenType.API_KEY:
return { authMode: AuthMode.API_KEY_V2, authTokenValue };
case AuthTokenType.MACHINE_ACCESS_TOKEN:
return { authMode: AuthMode.MACHINE_ACCESS_TOKEN, authTokenValue };
case AuthTokenType.IDENTITY_ACCESS_TOKEN:
return { authMode: AuthMode.IDENTITY_ACCESS_TOKEN, authTokenValue };
default:
throw UnauthorizedRequestError({
message: "Failed to authenticate unknown authentication method"
@@ -115,20 +115,21 @@ export const getAuthData = async ({
userAgentType
}
}
case AuthMode.MACHINE_ACCESS_TOKEN: {
const machineIdentity = await validateMachineIdentity({
authTokenValue
case AuthMode.IDENTITY_ACCESS_TOKEN: {
const identity = await validateIdentity({
authTokenValue,
ipAddress
});
return {
actor: {
type: ActorType.MACHINE,
type: ActorType.IDENTITY,
metadata: {
machineId: machineIdentity._id.toString(),
name: machineIdentity.name
identityId: identity._id.toString(),
name: identity.name
}
},
authPayload: machineIdentity,
authPayload: identity,
ipAddress,
userAgent,
userAgentType
+93
View File
@@ -84,6 +84,99 @@ export const ResetPasswordV1 = z.object({
})
});
export const RenewAccessTokenV1 = z.object({
body: z.object({
accessToken: z.string().trim(),
})
});
export const LoginUniversalAuthV1 = z.object({
body: z.object({
clientId: z.string().trim(),
clientSecret: z.string().trim()
})
});
export const AddUniversalAuthToIdentityV1 = z.object({
params: z.object({
identityId: z.string().trim()
}),
body: z.object({
clientSecretTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.default([{ ipAddress: "0.0.0.0/0" }]),
accessTokenTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.default([{ ipAddress: "0.0.0.0/0" }]),
accessTokenTTL: z.number().int().min(0).default(7200),
accessTokenMaxTTL: z.number().int().min(0).default(0),
accessTokenNumUsesLimit: z.number().int().min(0).default(0)
})
});
export const UpdateUniversalAuthToIdentityV1 = z.object({
params: z.object({
identityId: z.string()
}),
body: z.object({
clientSecretTrustedIps: z
.object({
ipAddress: z.string().trim()
})
.array()
.min(1)
.optional(),
accessTokenTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.optional(),
accessTokenTTL: z.number().int().min(0).optional(),
accessTokenNumUsesLimit: z.number().int().min(0).optional(),
accessTokenMaxTTL: z.number().int().min(0).default(0),
}),
});
export const GetUniversalAuthForIdentityV1 = z.object({
params: z.object({
identityId: z.string().trim()
})
});
export const CreateUniversalAuthClientSecretV1 = z.object({
params: z.object({
identityId: z.string()
}),
body: z.object({
description: z.string().trim().default(""),
numUsesLimit: z.number().min(0).default(0),
ttl: z.number().min(0).default(0),
}),
});
export const GetUniversalAuthClientSecretsV1 = z.object({
params: z.object({
identityId: z.string()
})
});
export const RevokeUniversalAuthClientSecretV1 = z.object({
params: z.object({
identityId: z.string(),
clientSecretId: z.string()
})
});
export const VerifyMfaTokenV2 = z.object({
body: z.object({
mfaToken: z.string().trim()
+26
View File
@@ -0,0 +1,26 @@
import { z } from "zod";
import { NO_ACCESS } from "../variables";
export const CreateIdentityV1 = z.object({
body: z.object({
name: z.string().trim(),
organizationId: z.string().trim(),
role: z.string().trim().min(1).default(NO_ACCESS)
})
});
export const UpdateIdentityV1 = z.object({
params: z.object({
identityId: z.string()
}),
body: z.object({
name: z.string().trim().optional(),
role: z.string().trim().min(1).optional()
}),
});
export const DeleteIdentityV1 = z.object({
params: z.object({
identityId: z.string()
}),
});
+1 -1
View File
@@ -8,5 +8,5 @@ export * from "./membershipOrg";
export * from "./organization";
export * from "./secrets";
export * from "./serviceTokenData";
export * from "./machineIdentity";
export * from "./identities";
export * from "./apiKeyDataV3";
+2 -2
View File
@@ -58,9 +58,9 @@ const validateClientForIntegrationAuth = async ({
throw UnauthorizedRequestError({
message: "Failed service token authorization for integration authorization"
});
case ActorType.MACHINE:
case ActorType.IDENTITY:
throw UnauthorizedRequestError({
message: "Failed machine authorization for integration authorization"
message: "Failed identity authorization for integration authorization"
});
}
};
-97
View File
@@ -1,97 +0,0 @@
import { z } from "zod";
import { NO_ACCESS } from "../variables";
export const GetClientSecretsV1 = z.object({
params: z.object({
machineId: z.string()
})
});
export const CreateClientSecretV1 = z.object({
params: z.object({
machineId: z.string()
}),
body: z.object({
description: z.string().trim().default(""),
numUsesLimit: z.number().min(0).default(0),
ttl: z.number().min(0).default(0),
}),
});
export const DeleteClientSecretV1 = z.object({
params: z.object({
machineId: z.string(),
clientSecretId: z.string()
})
});
export const LoginMachineIdentityV1 = z.object({
body: z.object({
clientId: z.string().trim(),
clientSecret: z.string().trim()
})
});
export const RenewAccessTokenV1 = z.object({
body: z.object({
accessToken: z.string().trim()
})
});
export const CreateMachineIdentityV1 = z.object({
body: z.object({
name: z.string().trim(),
organizationId: z.string().trim(),
role: z.string().trim().min(1).default(NO_ACCESS),
clientSecretTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.default([{ ipAddress: "0.0.0.0/0" }]),
accessTokenTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.default([{ ipAddress: "0.0.0.0/0" }]),
accessTokenTTL: z.number().int().min(0).default(7200),
accessTokenMaxTTL: z.number().int().min(0).default(0),
accessTokenNumUsesLimit: z.number().int().min(0).default(0)
})
});
export const UpdateMachineIdentityV1 = z.object({
params: z.object({
machineId: z.string()
}),
body: z.object({
name: z.string().trim().optional(),
role: z.string().trim().min(1).optional(),
clientSecretTrustedIps: z
.object({
ipAddress: z.string().trim()
})
.array()
.min(1)
.optional(),
accessTokenTrustedIps: z
.object({
ipAddress: z.string().trim(),
})
.array()
.min(1)
.optional(),
accessTokenTTL: z.number().int().min(0).optional(),
accessTokenNumUsesLimit: z.number().int().min(0).optional(),
accessTokenMaxTTL: z.number().int().min(0).default(0),
}),
});
export const DeleteMachineIdentityV1 = z.object({
params: z.object({
machineId: z.string()
}),
});
+6 -2
View File
@@ -46,9 +46,9 @@ export const validateClientForOrganization = async ({
throw UnauthorizedRequestError({
message: "Failed service token authorization for organization"
});
case ActorType.MACHINE:
case ActorType.IDENTITY:
throw UnauthorizedRequestError({
message: "Failed machine authorization for organization"
message: "Failed identity authorization for organization"
});
}
};
@@ -216,4 +216,8 @@ export const DeleteOrgv2 = z.object({
export const GetOrgServiceMembersV2 = z.object({
params: z.object({ organizationId: z.string().trim() })
});
export const GetOrgIdentityMembershipsV2 = z.object({
params: z.object({ organizationId: z.string().trim() })
});
+9 -9
View File
@@ -60,9 +60,9 @@ export const validateClientForWorkspace = async ({
requiredPermissions
});
return { membership, workspace };
case ActorType.MACHINE:
case ActorType.IDENTITY:
throw UnauthorizedRequestError({
message: "Failed machine authorization for organization"
message: "Failed identity authorization for organization"
});
}
};
@@ -280,34 +280,34 @@ export const ToggleAutoCapitalizationV2 = z.object({
})
});
export const AddMachineToWorkspaceV2 = z.object({
export const AddIdentityToWorkspaceV2 = z.object({
params: z.object({
workspaceId: z.string().trim(),
machineId: z.string().trim()
identityId: z.string().trim()
}),
body: z.object({
role: z.string().trim().min(1).default(NO_ACCESS),
})
});
export const UpdateMachineWorkspaceRoleV2 = z.object({
export const UpdateIdentityWorkspaceRoleV2 = z.object({
params: z.object({
workspaceId: z.string().trim(),
machineId: z.string().trim()
identityId: z.string().trim()
}),
body: z.object({
role: z.string().trim().min(1).default(NO_ACCESS),
})
});
export const DeleteMachineFromWorkspaceV2 = z.object({
export const DeleteIdentityFromWorkspaceV2 = z.object({
params: z.object({
workspaceId: z.string().trim(),
machineId: z.string().trim()
identityId: z.string().trim()
})
});
export const GetWorkspaceMachineMembersV2 = z.object({
export const GetWorkspaceIdentityMembersV2 = z.object({
params: z.object({
workspaceId: z.string().trim()
}),
+2 -3
View File
@@ -7,14 +7,13 @@ export enum AuthTokenType {
MFA_TOKEN = "mfaToken", // TODO: remove in favor of claim
PROVIDER_TOKEN = "providerToken", // TODO: remove in favor of claim
API_KEY = "apiKey",
MACHINE_ACCESS_TOKEN = "machineAccessToken",
MACHINE_REFRESH_TOKEN = "machineRefreshToken"
IDENTITY_ACCESS_TOKEN = "identityAccessToken",
}
export enum AuthMode {
JWT = "jwt",
SERVICE_TOKEN = "serviceToken",
MACHINE_ACCESS_TOKEN = "machineAccessToken",
IDENTITY_ACCESS_TOKEN = "identityAccessToken",
API_KEY = "apiKey",
API_KEY_V2 = "apiKeyV2"
}