Merge branch 'main' into identities-docs

This commit is contained in:
Maidul Islam
2023-12-13 16:56:35 -05:00
committed by GitHub
15 changed files with 9553 additions and 614 deletions

View File

@@ -3,28 +3,28 @@ import { Types } from "mongoose";
import jwt from "jsonwebtoken";
import crypto from "crypto";
import bcrypt from "bcrypt";
import {
IIdentity,
IIdentityTrustedIp,
IIdentityUniversalAuthClientSecret,
Identity,
IdentityAccessToken,
IdentityAuthMethod,
IdentityMembershipOrg,
IdentityUniversalAuth,
IdentityUniversalAuthClientSecret,
import {
IIdentity,
IIdentityTrustedIp,
IIdentityUniversalAuthClientSecret,
Identity,
IdentityAccessToken,
IdentityAuthMethod,
IdentityMembershipOrg,
IdentityUniversalAuth,
IdentityUniversalAuthClientSecret,
} from "../../models";
import { createToken } from "../../helpers/auth";
import { AuthTokenType } from "../../variables";
import {
BadRequestError,
ForbiddenRequestError,
ResourceNotFoundError,
UnauthorizedRequestError
import {
BadRequestError,
ForbiddenRequestError,
ResourceNotFoundError,
UnauthorizedRequestError
} from "../../utils/errors";
import {
getAuthSecret,
getSaltRounds
getAuthSecret,
getSaltRounds
} from "../../config";
import { ActorType, EventType, IRole } from "../../ee/models";
import { validateRequest } from "../../helpers/validation";
@@ -32,12 +32,12 @@ 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
import {
OrgPermissionActions,
OrgPermissionSubjects,
getAuthDataOrgPermissions,
getOrgRolePermissions,
isAtLeastAsPrivilegedOrg
} from "../../ee/services/RoleService";
import { ForbiddenError } from "@casl/ability";
@@ -53,7 +53,7 @@ const packageUniversalAuthClientSecretData = (identityUniversalAuthClientSecret:
createdAt: identityUniversalAuthClientSecret.createdAt,
updatedAt: identityUniversalAuthClientSecret.updatedAt
});
/**
* Renews an access token by its TTL
* @param req
@@ -132,9 +132,6 @@ export const renewAccessToken = async (req: Request, res: Response) => {
createdAt: accessTokenCreatedAt
} = identityAccessToken;
if (accessTokenTTL === accessTokenMaxTTL) throw UnauthorizedRequestError({
message: "Failed to renew non-renewable access token"
});
// ttl check
if (accessTokenTTL > 0) {
@@ -187,6 +184,7 @@ export const renewAccessToken = async (req: Request, res: Response) => {
return res.status(200).send({
accessToken,
expiresIn: identityAccessToken.accessTokenTTL,
accessTokenMaxTTL: identityAccessToken.accessTokenMaxTTL,
tokenType: "Bearer"
});
}
@@ -259,7 +257,7 @@ export const loginIdentityUniversalAuth = async (req: Request, res: Response) =>
const identityUniversalAuth = await IdentityUniversalAuth.findOne({
clientId
}).populate<{ identity: IIdentity }>("identity");
if (!identityUniversalAuth) throw UnauthorizedRequestError();
checkIPAgainstBlocklist({
@@ -334,16 +332,16 @@ export const loginIdentityUniversalAuth = async (req: Request, res: Response) =>
// increment usage count by 1
await IdentityUniversalAuthClientSecret
.findByIdAndUpdate(
validatedClientSecretDatum._id,
{
clientSecretLastUsedAt: new Date(),
$inc: { clientSecretNumUses: 1 }
},
{
new: true
}
);
.findByIdAndUpdate(
validatedClientSecretDatum._id,
{
clientSecretLastUsedAt: new Date(),
$inc: { clientSecretNumUses: 1 }
},
{
new: true
}
);
const identityAccessToken = await new IdentityAccessToken({
identity: identityUniversalAuth.identity,
@@ -397,7 +395,8 @@ export const loginIdentityUniversalAuth = async (req: Request, res: Response) =>
return res.status(200).send({
accessToken,
expiresIn: identityUniversalAuth.accessTokenTTL,
tokenType: "Bearer"
accessTokenMaxTTL: identityUniversalAuth.accessTokenMaxTTL,
tokenType: "Bearer",
});
}
@@ -523,7 +522,7 @@ export const attachIdentityUniversalAuth = async (req: Request, res: Response) =
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"
});
@@ -572,7 +571,7 @@ export const attachIdentityUniversalAuth = async (req: Request, res: Response) =
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
const identityUniversalAuth = await new IdentityUniversalAuth({
identity: identityMembershipOrg.identity._id,
clientId: crypto.randomUUID(),
@@ -582,7 +581,7 @@ export const attachIdentityUniversalAuth = async (req: Request, res: Response) =
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
}).save();
await Identity.findByIdAndUpdate(
identityMembershipOrg.identity._id,
{
@@ -725,7 +724,7 @@ export const updateIdentityUniversalAuth = async (req: Request, res: Response) =
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"
});
@@ -776,7 +775,7 @@ export const updateIdentityUniversalAuth = async (req: Request, res: Response) =
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
}
const identityUniversalAuth = await IdentityUniversalAuth.findOneAndUpdate(
{
identity: identityMembershipOrg.identity._id,
@@ -853,7 +852,7 @@ 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)
@@ -880,7 +879,7 @@ export const getIdentityUniversalAuth = async (req: Request, res: Response) => {
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,
});
@@ -1017,11 +1016,11 @@ export const createUniversalAuthClientSecret = async (req: Request, res: Respons
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({
@@ -1096,7 +1095,7 @@ export const getUniversalAuthClientSecretsDetails = async (req: Request, res: Re
const {
params: { identityId }
} = await validateRequest(reqValidator.GetUniversalAuthClientSecretsV1, req);
const identityMembershipOrg = await IdentityMembershipOrg.findOne({
identity: new Types.ObjectId(identityId)
}).populate<{
@@ -1199,7 +1198,7 @@ export const revokeUniversalAuthClientSecret = async (req: Request, res: Respons
const {
params: { identityId, clientSecretId }
} = await validateRequest(reqValidator.RevokeUniversalAuthClientSecretV1, req);
const identityMembershipOrg = await IdentityMembershipOrg
.findOne({
identity: new Types.ObjectId(identityId)
@@ -1247,7 +1246,7 @@ export const revokeUniversalAuthClientSecret = async (req: Request, res: Respons
);
if (!clientSecretData) throw ResourceNotFoundError();
await EEAuditLogService.createAuditLog(
req.authData,
{

View File

@@ -1,10 +1,10 @@
import { Request, Response } from "express";
import { Types } from "mongoose";
import {
import {
IIdentity,
IdentityMembership,
IdentityMembershipOrg,
Key,
Key,
Membership,
ServiceTokenData,
Workspace
@@ -182,11 +182,11 @@ export const getWorkspaceKey = async (req: Request, res: Response) => {
"apiKeyAuth": []
}]
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.responses[200] = {
content: {
@@ -211,7 +211,7 @@ export const getWorkspaceKey = async (req: Request, res: Response) => {
receiver: req.user._id
}).populate("sender", "+publicKey");
if (!key) throw new Error("Failed to find workspace key");
if (!key) throw new Error(`getWorkspaceKey: Failed to find workspace key [workspaceId=${workspaceId}] [receiver=${req.user._id}]`);
await EEAuditLogService.createAuditLog(
req.authData,
@@ -257,26 +257,26 @@ export const getWorkspaceMemberships = async (req: Request, res: Response) => {
"bearerAuth": []
}]
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.responses[200] = {
content: {
"application/json": {
"schema": {
"type": "object",
"properties": {
"memberships": {
"type": "array",
"items": {
$ref: "#/components/schemas/Membership"
},
"description": "Memberships of project"
}
}
"properties": {
"memberships": {
"type": "array",
"items": {
$ref: "#/components/schemas/Membership"
},
"description": "Memberships of project"
}
}
}
}
}
@@ -321,19 +321,19 @@ export const updateWorkspaceMembership = async (req: Request, res: Response) =>
"bearerAuth": []
}]
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['membershipId'] = {
"description": "ID of project membership to update",
"required": true,
"type": "string"
}
#swagger.parameters['membershipId'] = {
"description": "ID of project membership to update",
"required": true,
"type": "string"
}
#swagger.requestBody = {
#swagger.requestBody = {
"required": true,
"content": {
"application/json": {
@@ -354,13 +354,13 @@ export const updateWorkspaceMembership = async (req: Request, res: Response) =>
content: {
"application/json": {
"schema": {
"type": "object",
"properties": {
"membership": {
$ref: "#/components/schemas/Membership",
"description": "Updated membership"
}
}
"type": "object",
"properties": {
"membership": {
$ref: "#/components/schemas/Membership",
"description": "Updated membership"
}
}
}
}
}
@@ -412,29 +412,29 @@ export const deleteWorkspaceMembership = async (req: Request, res: Response) =>
"bearerAuth": []
}]
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['workspaceId'] = {
"description": "ID of project",
"required": true,
"type": "string"
}
#swagger.parameters['membershipId'] = {
"description": "ID of project membership to delete",
"required": true,
"type": "string"
}
#swagger.parameters['membershipId'] = {
"description": "ID of project membership to delete",
"required": true,
"type": "string"
}
#swagger.responses[200] = {
content: {
"application/json": {
"schema": {
"type": "object",
"properties": {
"membership": {
$ref: "#/components/schemas/Membership",
"description": "Deleted membership"
}
}
"type": "object",
"properties": {
"membership": {
$ref: "#/components/schemas/Membership",
"description": "Deleted membership"
}
}
}
}
}
@@ -514,14 +514,14 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
* @param req
* @param res
*/
export const addIdentityToWorkspace = async (req: Request, res: Response) => {
export const addIdentityToWorkspace = async (req: Request, res: Response) => {
const {
params: { workspaceId, identityId },
body: {
role
}
} = await validateRequest(reqValidator.AddIdentityToWorkspaceV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
workspaceId: new Types.ObjectId(workspaceId)
@@ -541,7 +541,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
message: `Identity with id ${identityId} already exists in project with id ${workspaceId}`
});
const workspace = await Workspace.findById(workspaceId);
if (!workspace) throw ResourceNotFoundError();
@@ -553,16 +553,16 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
if (!identityMembershipOrg) throw ResourceNotFoundError({
message: `Failed to find identity with id ${identityId}`
});
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 identity to project with more privileged role"
message: "Failed to add identity to project with more privileged role"
});
let customRole;
@@ -574,18 +574,18 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
isOrgRole: false,
workspace: new Types.ObjectId(workspaceId)
});
if (!customRole) throw BadRequestError({ message: "Role not found" });
}
}
identityMembership = await new IdentityMembership({
identity: identityMembershipOrg.identity,
workspace: new Types.ObjectId(workspaceId),
role: customRole ? CUSTOM : role,
customRole
}).save();
return res.status(200).send({
identityMembership
});
@@ -657,7 +657,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
role
}
} = await validateRequest(reqValidator.UpdateIdentityWorkspaceRoleV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
workspaceId: new Types.ObjectId(workspaceId)
@@ -667,7 +667,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
ProjectPermissionActions.Edit,
ProjectPermissionSub.Identity
);
let identityMembership = await IdentityMembership
.findOne({
identity: new Types.ObjectId(identityId),
@@ -681,21 +681,21 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
if (!identityMembership) throw BadRequestError({
message: `Identity with id ${identityId} does not exist in project with id ${workspaceId}`
});
const identityRolePermission = await getWorkspaceRolePermissions(
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership.workspace.toString()
);
const isAsPrivilegedAsIdentity = isAtLeastAsPrivilegedWorkspace(permission, identityRolePermission);
if (!isAsPrivilegedAsIdentity) throw ForbiddenRequestError({
message: "Failed to update role of more privileged identity"
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 identity to a more privileged role"
message: "Failed to update identity to a more privileged role"
});
let customRole;
@@ -707,11 +707,11 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
isOrgRole: false,
workspace: new Types.ObjectId(workspaceId)
});
if (!customRole) throw BadRequestError({ message: "Role not found" });
}
}
identityMembership = await IdentityMembership.findOneAndUpdate(
{
identity: identityMembership.identity._id,
@@ -777,7 +777,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
const {
params: { workspaceId, identityId }
} = await validateRequest(reqValidator.DeleteIdentityFromWorkspaceV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
workspaceId: new Types.ObjectId(workspaceId)
@@ -787,7 +787,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
ProjectPermissionActions.Delete,
ProjectPermissionSub.Identity
);
const identityMembership = await IdentityMembership
.findOne({
identity: new Types.ObjectId(identityId),
@@ -797,20 +797,20 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
identity: IIdentity,
customRole: IRole
}>("identity customRole");
if (!identityMembership) throw ResourceNotFoundError({
message: `Identity with id ${identityId} does not exist in project with id ${workspaceId}`
});
const identityRolePermission = await getWorkspaceRolePermissions(
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership?.customRole?.slug ?? identityMembership.role,
identityMembership.workspace.toString()
);
const isAsPrivilegedAsIdentity = isAtLeastAsPrivilegedWorkspace(permission, identityRolePermission);
if (!isAsPrivilegedAsIdentity) throw ForbiddenRequestError({
message: "Failed to remove more privileged identity from project"
message: "Failed to remove more privileged identity from project"
});
await IdentityMembership.findByIdAndDelete(identityMembership._id);
return res.status(200).send({
@@ -862,7 +862,7 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
const {
params: { workspaceId }
} = await validateRequest(reqValidator.GetWorkspaceIdentityMembersV2, req);
const { permission } = await getAuthDataProjectPermissions({
authData: req.authData,
workspaceId: new Types.ObjectId(workspaceId)

View File

@@ -116,7 +116,9 @@ export const AddUniversalAuthToIdentityV1 = z.object({
.array()
.min(1)
.default([{ ipAddress: "0.0.0.0/0" }]),
accessTokenTTL: z.number().int().min(0).default(7200),
accessTokenTTL: z.number().int().min(1).refine(value => value !== 0, {
message: "accessTokenTTL must have a non zero number",
}).default(2592000),
accessTokenMaxTTL: z.number().int().refine(value => value !== 0, {
message: "accessTokenMaxTTL must have a non zero number",
}).default(2592000), // 30 days