mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-04 20:26:17 +00:00
Merge pull request #1184 from Infisical/stv3-roles
Add role-based project access controls to ST V3
This commit is contained in:
@@ -7,7 +7,7 @@ import * as reqValidator from "../../validation/bot";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { BadRequestError } from "../../utils/errors";
|
import { BadRequestError } from "../../utils/errors";
|
||||||
@@ -28,7 +28,11 @@ export const getBotByWorkspaceId = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetBotByWorkspaceIdV1, req);
|
} = await validateRequest(reqValidator.GetBotByWorkspaceIdV1, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -70,7 +74,11 @@ export const setBotActiveState = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
const userId = req.user._id;
|
const userId = req.user._id;
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(userId, bot.workspace.toString());
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: bot.workspace
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import * as reqValidator from "../../validation/integrationAuth";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { getIntegrationAuthAccessHelper } from "../../helpers";
|
import { getIntegrationAuthAccessHelper } from "../../helpers";
|
||||||
@@ -40,15 +40,15 @@ export const getIntegrationAuth = async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
const integrationAuth = await IntegrationAuth.findById(integrationAuthId);
|
const integrationAuth = await IntegrationAuth.findById(integrationAuthId);
|
||||||
|
|
||||||
if (!integrationAuth)
|
if (!integrationAuth) return res.status(400).send({
|
||||||
return res.status(400).send({
|
message: "Failed to find integration authorization"
|
||||||
message: "Failed to find integration authorization"
|
});
|
||||||
});
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: integrationAuth.workspace
|
||||||
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
|
||||||
req.user._id,
|
|
||||||
integrationAuth.workspace.toString()
|
|
||||||
);
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -79,7 +79,11 @@ export const oAuthExchange = async (req: Request, res: Response) => {
|
|||||||
} = await validateRequest(reqValidator.OauthExchangeV1, req);
|
} = await validateRequest(reqValidator.OauthExchangeV1, req);
|
||||||
if (!INTEGRATION_SET.has(integration)) throw new Error("Failed to validate integration");
|
if (!INTEGRATION_SET.has(integration)) throw new Error("Failed to validate integration");
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -131,7 +135,11 @@ export const saveIntegrationToken = async (req: Request, res: Response) => {
|
|||||||
body: { workspaceId, integration, url, accessId, namespace, accessToken, refreshToken }
|
body: { workspaceId, integration, url, accessId, namespace, accessToken, refreshToken }
|
||||||
} = await validateRequest(reqValidator.SaveIntegrationAccessTokenV1, req);
|
} = await validateRequest(reqValidator.SaveIntegrationAccessTokenV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -224,11 +232,12 @@ export const getIntegrationAuthApps = async (req: Request, res: Response) => {
|
|||||||
const { integrationAuth, accessToken, accessId } = await getIntegrationAuthAccessHelper({
|
const { integrationAuth, accessToken, accessId } = await getIntegrationAuthAccessHelper({
|
||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: integrationAuth.workspace
|
||||||
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
|
||||||
req.user._id,
|
|
||||||
integrationAuth.workspace.toString()
|
|
||||||
);
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -263,10 +272,11 @@ export const getIntegrationAuthTeams = async (req: Request, res: Response) => {
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -299,10 +309,11 @@ export const getIntegrationAuthVercelBranches = async (req: Request, res: Respon
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -360,10 +371,11 @@ export const getIntegrationAuthChecklyGroups = async (req: Request, res: Respons
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -413,10 +425,11 @@ export const getIntegrationAuthQoveryOrgs = async (req: Request, res: Response)
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -465,10 +478,11 @@ export const getIntegrationAuthQoveryProjects = async (req: Request, res: Respon
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -526,10 +540,11 @@ export const getIntegrationAuthQoveryEnvironments = async (req: Request, res: Re
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -587,10 +602,11 @@ export const getIntegrationAuthQoveryApps = async (req: Request, res: Response)
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -648,10 +664,11 @@ export const getIntegrationAuthQoveryContainers = async (req: Request, res: Resp
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -709,10 +726,11 @@ export const getIntegrationAuthQoveryJobs = async (req: Request, res: Response)
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -771,10 +789,11 @@ export const getIntegrationAuthRailwayEnvironments = async (req: Request, res: R
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -864,10 +883,11 @@ export const getIntegrationAuthRailwayServices = async (req: Request, res: Respo
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -988,10 +1008,11 @@ export const getIntegrationAuthBitBucketWorkspaces = async (req: Request, res: R
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -1044,10 +1065,11 @@ export const getIntegrationAuthNorthflankSecretGroups = async (req: Request, res
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -1132,10 +1154,11 @@ export const getIntegrationAuthTeamCityBuildConfigs = async (req: Request, res:
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -1201,10 +1224,11 @@ export const deleteIntegrationAuth = async (req: Request, res: Response) => {
|
|||||||
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
integrationAuthId: new Types.ObjectId(integrationAuthId)
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace.toString()
|
workspaceId: integrationAuth.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import * as reqValidator from "../../validation/integration";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
|
||||||
@@ -51,11 +51,12 @@ export const createIntegration = async (req: Request, res: Response) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!integrationAuth) throw BadRequestError({ message: "Integration auth not found" });
|
if (!integrationAuth) throw BadRequestError({ message: "Integration auth not found" });
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integrationAuth.workspace._id.toString()
|
workspaceId: integrationAuth.workspace._id
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -164,10 +165,11 @@ export const updateIntegration = async (req: Request, res: Response) => {
|
|||||||
const integration = await Integration.findById(integrationId);
|
const integration = await Integration.findById(integrationId);
|
||||||
if (!integration) throw BadRequestError({ message: "Integration not found" });
|
if (!integration) throw BadRequestError({ message: "Integration not found" });
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integration.workspace.toString()
|
workspaceId: integration.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -234,10 +236,11 @@ export const deleteIntegration = async (req: Request, res: Response) => {
|
|||||||
const integration = await Integration.findById(integrationId);
|
const integration = await Integration.findById(integrationId);
|
||||||
if (!integration) throw BadRequestError({ message: "Integration not found" });
|
if (!integration) throw BadRequestError({ message: "Integration not found" });
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
integration.workspace.toString()
|
workspaceId: integration.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -285,7 +288,11 @@ export const manualSync = async (req: Request, res: Response) => {
|
|||||||
body: { workspaceId, environment }
|
body: { workspaceId, environment }
|
||||||
} = await validateRequest(reqValidator.ManualSyncV1, req);
|
} = await validateRequest(reqValidator.ManualSyncV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import * as reqValidator from "../../validation/key";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
|
||||||
@@ -26,7 +26,11 @@ export const uploadKey = async (req: Request, res: Response) => {
|
|||||||
body: { key }
|
body: { key }
|
||||||
} = await validateRequest(reqValidator.UploadKeyV1, req);
|
} = await validateRequest(reqValidator.UploadKeyV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import * as reqValidator from "../../validation/membership";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { BadRequestError } from "../../utils/errors";
|
import { BadRequestError } from "../../utils/errors";
|
||||||
@@ -63,11 +63,12 @@ export const deleteMembership = async (req: Request, res: Response) => {
|
|||||||
if (!membershipToDelete) {
|
if (!membershipToDelete) {
|
||||||
throw new Error("Failed to delete workspace membership that doesn't exist");
|
throw new Error("Failed to delete workspace membership that doesn't exist");
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
membershipToDelete.workspace.toString()
|
workspaceId: membershipToDelete.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -118,10 +119,11 @@ export const changeMembershipRole = async (req: Request, res: Response) => {
|
|||||||
throw new Error("Failed to find membership to change role");
|
throw new Error("Failed to find membership to change role");
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
membershipToChangeRole.workspace.toString()
|
workspaceId: membershipToChangeRole.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -191,7 +193,12 @@ export const inviteUserToWorkspace = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId },
|
params: { workspaceId },
|
||||||
body: { email }
|
body: { email }
|
||||||
} = await validateRequest(InviteUserToWorkspaceV1, req);
|
} = await validateRequest(InviteUserToWorkspaceV1, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
|
import { Types } from "mongoose";
|
||||||
import { isValidScope } from "../../helpers";
|
import { isValidScope } from "../../helpers";
|
||||||
import { Folder, IServiceTokenData, SecretImport, ServiceTokenData } from "../../models";
|
import { Folder, IServiceTokenData, SecretImport, ServiceTokenData } from "../../models";
|
||||||
import { getAllImportedSecrets } from "../../services/SecretImportService";
|
import { getAllImportedSecrets } from "../../services/SecretImportService";
|
||||||
@@ -15,7 +17,7 @@ import * as reqValidator from "../../validation/secretImports";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
|
|
||||||
@@ -105,7 +107,11 @@ export const createSecretImp = async (req: Request, res: Response) => {
|
|||||||
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
||||||
@@ -313,10 +319,11 @@ export const updateSecretImport = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// non token entry check
|
// non token entry check
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
importSecDoc.workspace.toString()
|
workspaceId: importSecDoc.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
@@ -442,10 +449,11 @@ export const deleteSecretImport = async (req: Request, res: Response) => {
|
|||||||
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
importSecDoc.workspace.toString()
|
workspaceId: importSecDoc.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
@@ -550,7 +558,11 @@ export const getSecretImports = async (req: Request, res: Response) => {
|
|||||||
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
@@ -604,7 +616,11 @@ export const getAllSecretsFromImport = async (req: Request, res: Response) => {
|
|||||||
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
@@ -657,10 +673,11 @@ export const getAllSecretsFromImport = async (req: Request, res: Response) => {
|
|||||||
permissionCheckFn = (env: string, secPath: string) =>
|
permissionCheckFn = (env: string, secPath: string) =>
|
||||||
isValidScope(req.authData.authPayload as IServiceTokenData, env, secPath);
|
isValidScope(req.authData.authPayload as IServiceTokenData, env, secPath);
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
importSecDoc.workspace.toString()
|
workspaceId: importSecDoc.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, {
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
||||||
import * as reqValidator from "../../validation/folders";
|
import * as reqValidator from "../../validation/folders";
|
||||||
@@ -125,7 +125,11 @@ export const createFolder = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// user check
|
// user check
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
||||||
@@ -332,7 +336,11 @@ export const updateFolderById = async (req: Request, res: Response) => {
|
|||||||
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
throw UnauthorizedRequestError({ message: "Folder Permission Denied" });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
||||||
@@ -502,7 +510,11 @@ export const deleteFolder = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// check that user is a member of the workspace
|
// check that user is a member of the workspace
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath: directory })
|
||||||
@@ -649,7 +661,10 @@ export const getFolders = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// check that user is a member of the workspace
|
// check that user is a member of the workspace
|
||||||
await getUserProjectPermissions(req.user._id, workspaceId);
|
await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const folders = await Folder.findOne({ workspace: workspaceId, environment });
|
const folders = await Folder.findOne({ workspace: workspaceId, environment });
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import * as reqValidator from "../../validation/webhooks";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { encryptSymmetric128BitHexKeyUTF8 } from "../../utils/crypto";
|
import { encryptSymmetric128BitHexKeyUTF8 } from "../../utils/crypto";
|
||||||
@@ -26,7 +26,11 @@ export const createWebhook = async (req: Request, res: Response) => {
|
|||||||
body: { webhookUrl, webhookSecretKey, environment, workspaceId, secretPath }
|
body: { webhookUrl, webhookSecretKey, environment, workspaceId, secretPath }
|
||||||
} = await validateRequest(reqValidator.CreateWebhookV1, req);
|
} = await validateRequest(reqValidator.CreateWebhookV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Webhooks
|
ProjectPermissionSub.Webhooks
|
||||||
@@ -98,11 +102,11 @@ export const updateWebhook = async (req: Request, res: Response) => {
|
|||||||
if (!webhook) {
|
if (!webhook) {
|
||||||
throw BadRequestError({ message: "Webhook not found!!" });
|
throw BadRequestError({ message: "Webhook not found!!" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
webhook.workspace.toString()
|
workspaceId: webhook.workspace
|
||||||
);
|
});
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Webhooks
|
ProjectPermissionSub.Webhooks
|
||||||
@@ -146,10 +150,11 @@ export const deleteWebhook = async (req: Request, res: Response) => {
|
|||||||
throw ResourceNotFoundError({ message: "Webhook not found!!" });
|
throw ResourceNotFoundError({ message: "Webhook not found!!" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
webhook.workspace.toString()
|
workspaceId: webhook.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Webhooks
|
ProjectPermissionSub.Webhooks
|
||||||
@@ -193,10 +198,11 @@ export const testWebhook = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "Webhook not found!!" });
|
throw BadRequestError({ message: "Webhook not found!!" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
webhook.workspace.toString()
|
workspaceId: webhook.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Webhooks
|
ProjectPermissionSub.Webhooks
|
||||||
@@ -236,8 +242,12 @@ export const listWebhooks = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
query: { environment, workspaceId, secretPath }
|
query: { environment, workspaceId, secretPath }
|
||||||
} = await validateRequest(reqValidator.ListWebhooksV1, req);
|
} = await validateRequest(reqValidator.ListWebhooksV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Webhooks
|
ProjectPermissionSub.Webhooks
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import * as reqValidator from "../../validation";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,7 +39,11 @@ export const getWorkspacePublicKeys = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspacePublicKeysV1, req);
|
} = await validateRequest(reqValidator.GetWorkspacePublicKeysV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -72,7 +76,11 @@ export const getWorkspaceMemberships = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceMembershipsV1, req);
|
} = await validateRequest(reqValidator.GetWorkspaceMembershipsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -195,7 +203,11 @@ export const deleteWorkspace = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.DeleteWorkspaceV1, req);
|
} = await validateRequest(reqValidator.DeleteWorkspaceV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Workspace
|
ProjectPermissionSub.Workspace
|
||||||
@@ -223,7 +235,11 @@ export const changeWorkspaceName = async (req: Request, res: Response) => {
|
|||||||
body: { name }
|
body: { name }
|
||||||
} = await validateRequest(reqValidator.ChangeWorkspaceNameV1, req);
|
} = await validateRequest(reqValidator.ChangeWorkspaceNameV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Workspace
|
ProjectPermissionSub.Workspace
|
||||||
@@ -257,7 +273,12 @@ export const getWorkspaceIntegrations = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceIntegrationsV1, req);
|
} = await validateRequest(reqValidator.GetWorkspaceIntegrationsV1, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -283,7 +304,11 @@ export const getWorkspaceIntegrationAuthorizations = async (req: Request, res: R
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceIntegrationAuthorizationsV1, req);
|
} = await validateRequest(reqValidator.GetWorkspaceIntegrationAuthorizationsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Integrations
|
ProjectPermissionSub.Integrations
|
||||||
@@ -309,7 +334,11 @@ export const getWorkspaceServiceTokens = async (req: Request, res: Response) =>
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceServiceTokensV1, req);
|
} = await validateRequest(reqValidator.GetWorkspaceServiceTokensV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.ServiceTokens
|
ProjectPermissionSub.ServiceTokens
|
||||||
|
|||||||
@@ -12,14 +12,12 @@ import {
|
|||||||
import { EventType, SecretVersion } from "../../ee/models";
|
import { EventType, SecretVersion } from "../../ee/models";
|
||||||
import { EEAuditLogService, EELicenseService } from "../../ee/services";
|
import { EEAuditLogService, EELicenseService } from "../../ee/services";
|
||||||
import { BadRequestError, WorkspaceNotFoundError } from "../../utils/errors";
|
import { BadRequestError, WorkspaceNotFoundError } from "../../utils/errors";
|
||||||
import _ from "lodash";
|
|
||||||
import { PERMISSION_READ_SECRETS, PERMISSION_WRITE_SECRETS } from "../../variables";
|
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
import * as reqValidator from "../../validation/environments";
|
import * as reqValidator from "../../validation/environments";
|
||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { SecretImport } from "../../models";
|
import { SecretImport } from "../../models";
|
||||||
@@ -114,7 +112,11 @@ export const createWorkspaceEnvironment = async (req: Request, res: Response) =>
|
|||||||
body: { environmentName, environmentSlug }
|
body: { environmentName, environmentSlug }
|
||||||
} = await validateRequest(reqValidator.CreateWorkspaceEnvironmentV2, req);
|
} = await validateRequest(reqValidator.CreateWorkspaceEnvironmentV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Environments
|
ProjectPermissionSub.Environments
|
||||||
@@ -191,7 +193,11 @@ export const reorderWorkspaceEnvironments = async (req: Request, res: Response)
|
|||||||
body: { environmentName, environmentSlug, otherEnvironmentSlug, otherEnvironmentName }
|
body: { environmentName, environmentSlug, otherEnvironmentSlug, otherEnvironmentName }
|
||||||
} = await validateRequest(reqValidator.ReorderWorkspaceEnvironmentsV2, req);
|
} = await validateRequest(reqValidator.ReorderWorkspaceEnvironmentsV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Environments
|
ProjectPermissionSub.Environments
|
||||||
@@ -322,7 +328,11 @@ export const renameWorkspaceEnvironment = async (req: Request, res: Response) =>
|
|||||||
body: { environmentName, environmentSlug, oldEnvironmentSlug }
|
body: { environmentName, environmentSlug, oldEnvironmentSlug }
|
||||||
} = await validateRequest(reqValidator.UpdateWorkspaceEnvironmentV2, req);
|
} = await validateRequest(reqValidator.UpdateWorkspaceEnvironmentV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Environments
|
ProjectPermissionSub.Environments
|
||||||
@@ -511,7 +521,11 @@ export const deleteWorkspaceEnvironment = async (req: Request, res: Response) =>
|
|||||||
body: { environmentSlug }
|
body: { environmentSlug }
|
||||||
} = await validateRequest(reqValidator.DeleteWorkspaceEnvironmentV2, req);
|
} = await validateRequest(reqValidator.DeleteWorkspaceEnvironmentV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Environments
|
ProjectPermissionSub.Environments
|
||||||
@@ -587,98 +601,4 @@ export const deleteWorkspaceEnvironment = async (req: Request, res: Response) =>
|
|||||||
workspace: workspaceId,
|
workspace: workspaceId,
|
||||||
environment: environmentSlug
|
environment: environmentSlug
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO(akhilmhdh) after rbac this can be completely removed
|
|
||||||
export const getAllAccessibleEnvironmentsOfWorkspace = async (req: Request, res: Response) => {
|
|
||||||
/*
|
|
||||||
#swagger.summary = 'Get all accessible environments of a workspace'
|
|
||||||
#swagger.description = 'Fetch all environments that the user has access to in a specified workspace'
|
|
||||||
|
|
||||||
#swagger.security = [{
|
|
||||||
"apiKeyAuth": []
|
|
||||||
}]
|
|
||||||
|
|
||||||
#swagger.parameters['workspaceId'] = {
|
|
||||||
"description": "ID of the workspace",
|
|
||||||
"required": true,
|
|
||||||
"type": "string",
|
|
||||||
"in": "path"
|
|
||||||
}
|
|
||||||
|
|
||||||
#swagger.responses[200] = {
|
|
||||||
content: {
|
|
||||||
"application/json": {
|
|
||||||
"schema": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"accessibleEnvironments": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"name": {
|
|
||||||
"type": "string",
|
|
||||||
"example": "Development"
|
|
||||||
},
|
|
||||||
"slug": {
|
|
||||||
"type": "string",
|
|
||||||
"example": "development"
|
|
||||||
},
|
|
||||||
"isWriteDenied": {
|
|
||||||
"type": "boolean",
|
|
||||||
"example": false
|
|
||||||
},
|
|
||||||
"isReadDenied": {
|
|
||||||
"type": "boolean",
|
|
||||||
"example": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"description": "List of environments the user has access to in the specified workspace"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
const {
|
|
||||||
params: { workspaceId }
|
|
||||||
} = await validateRequest(reqValidator.GetAllAccessibileEnvironmentsOfWorkspaceV2, req);
|
|
||||||
|
|
||||||
const { membership: workspacesUserIsMemberOf } = await getUserProjectPermissions(
|
|
||||||
req.user._id,
|
|
||||||
workspaceId
|
|
||||||
);
|
|
||||||
|
|
||||||
const accessibleEnvironments: any = [];
|
|
||||||
const deniedPermission = workspacesUserIsMemberOf.deniedPermissions;
|
|
||||||
|
|
||||||
const relatedWorkspace = await Workspace.findById(workspaceId);
|
|
||||||
if (!relatedWorkspace) {
|
|
||||||
throw BadRequestError();
|
|
||||||
}
|
|
||||||
relatedWorkspace.environments.forEach((environment) => {
|
|
||||||
const isReadBlocked = _.some(deniedPermission, {
|
|
||||||
environmentSlug: environment.slug,
|
|
||||||
ability: PERMISSION_READ_SECRETS
|
|
||||||
});
|
|
||||||
const isWriteBlocked = _.some(deniedPermission, {
|
|
||||||
environmentSlug: environment.slug,
|
|
||||||
ability: PERMISSION_WRITE_SECRETS
|
|
||||||
});
|
|
||||||
if (isReadBlocked && isWriteBlocked) {
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
accessibleEnvironments.push({
|
|
||||||
name: environment.name,
|
|
||||||
slug: environment.slug,
|
|
||||||
isWriteDenied: isWriteBlocked,
|
|
||||||
isReadDenied: isReadBlocked
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
res.json({ accessibleEnvironments });
|
|
||||||
};
|
|
||||||
@@ -8,7 +8,7 @@ import { EEAuditLogService } from "../../ee/services";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { sendMail } from "../../helpers";
|
import { sendMail } from "../../helpers";
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
@@ -27,7 +27,11 @@ export const addUserToWorkspace = async (req: Request, res: Response) => {
|
|||||||
if (!workspace) throw new Error("Failed to find workspace");
|
if (!workspace) throw new Error("Failed to find workspace");
|
||||||
|
|
||||||
// check permission
|
// check permission
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
|
|
||||||
@@ -159,7 +159,11 @@ export const batchSecrets = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
// not using service token using auth
|
// not using service token using auth
|
||||||
if (!(req.authData.authPayload instanceof ServiceTokenData)) {
|
if (!(req.authData.authPayload instanceof ServiceTokenData)) {
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
if (createSecrets.length)
|
if (createSecrets.length)
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import * as reqValidator from "../../validation/serviceTokenData";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
@@ -75,7 +75,12 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
body: { workspaceId, permissions, tag, encryptedKey, scopes, name, expiresIn, iv }
|
body: { workspaceId, permissions, tag, encryptedKey, scopes, name, expiresIn, iv }
|
||||||
} = await validateRequest(reqValidator.CreateServiceTokenV2, req);
|
} = await validateRequest(reqValidator.CreateServiceTokenV2, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.ServiceTokens
|
ProjectPermissionSub.ServiceTokens
|
||||||
@@ -151,10 +156,11 @@ export const deleteServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
let serviceTokenData = await ServiceTokenData.findById(serviceTokenDataId);
|
let serviceTokenData = await ServiceTokenData.findById(serviceTokenDataId);
|
||||||
if (!serviceTokenData) throw BadRequestError({ message: "Service token not found" });
|
if (!serviceTokenData) throw BadRequestError({ message: "Service token not found" });
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
serviceTokenData.workspace.toString()
|
workspaceId: serviceTokenData.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.ServiceTokens
|
ProjectPermissionSub.ServiceTokens
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { validateRequest } from "../../helpers/validation";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import * as reqValidator from "../../validation/tags";
|
import * as reqValidator from "../../validation/tags";
|
||||||
|
|
||||||
@@ -17,7 +17,11 @@ export const createWorkspaceTag = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.CreateWorkspaceTagsV2, req);
|
} = await validateRequest(reqValidator.CreateWorkspaceTagsV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.Tags
|
ProjectPermissionSub.Tags
|
||||||
@@ -45,10 +49,11 @@ export const deleteWorkspaceTag = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError();
|
throw BadRequestError();
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
tagFromDB.workspace.toString()
|
workspaceId: tagFromDB.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Tags
|
ProjectPermissionSub.Tags
|
||||||
@@ -66,7 +71,12 @@ export const getWorkspaceTags = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceTagsV2, req);
|
} = await validateRequest(reqValidator.GetWorkspaceTagsV2, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Tags
|
ProjectPermissionSub.Tags
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import * as reqValidator from "../../validation";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
|
||||||
@@ -272,7 +272,11 @@ export const getWorkspaceMemberships = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceMembershipsV2, req);
|
} = await validateRequest(reqValidator.GetWorkspaceMembershipsV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -352,7 +356,11 @@ export const updateWorkspaceMembership = async (req: Request, res: Response) =>
|
|||||||
body: { role }
|
body: { role }
|
||||||
} = await validateRequest(reqValidator.UpdateWorkspaceMembershipsV2, req);
|
} = await validateRequest(reqValidator.UpdateWorkspaceMembershipsV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -420,7 +428,11 @@ export const deleteWorkspaceMembership = async (req: Request, res: Response) =>
|
|||||||
params: { workspaceId, membershipId }
|
params: { workspaceId, membershipId }
|
||||||
} = await validateRequest(reqValidator.DeleteWorkspaceMembershipsV2, req);
|
} = await validateRequest(reqValidator.DeleteWorkspaceMembershipsV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.Member
|
ProjectPermissionSub.Member
|
||||||
@@ -452,7 +464,11 @@ export const toggleAutoCapitalization = async (req: Request, res: Response) => {
|
|||||||
body: { autoCapitalization }
|
body: { autoCapitalization }
|
||||||
} = await validateRequest(reqValidator.ToggleAutoCapitalizationV2, req);
|
} = await validateRequest(reqValidator.ToggleAutoCapitalizationV2, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.Settings
|
ProjectPermissionSub.Settings
|
||||||
|
|||||||
@@ -3,11 +3,16 @@ import { Types } from "mongoose";
|
|||||||
import { EventService, SecretService } from "../../services";
|
import { EventService, SecretService } from "../../services";
|
||||||
import { eventPushSecrets } from "../../events";
|
import { eventPushSecrets } from "../../events";
|
||||||
import { BotService } from "../../services";
|
import { BotService } from "../../services";
|
||||||
import { containsGlobPatterns, isValidScopeV3, repackageSecretToRaw } from "../../helpers/secrets";
|
import { containsGlobPatterns, repackageSecretToRaw } from "../../helpers/secrets";
|
||||||
import { encryptSymmetric128BitHexKeyUTF8 } from "../../utils/crypto";
|
import { encryptSymmetric128BitHexKeyUTF8 } from "../../utils/crypto";
|
||||||
import { getAllImportedSecrets } from "../../services/SecretImportService";
|
import { getAllImportedSecrets } from "../../services/SecretImportService";
|
||||||
import { Folder, IMembership, IServiceTokenData, IServiceTokenDataV3 } from "../../models";
|
import {
|
||||||
import { Permission } from "../../models/serviceTokenDataV3";
|
Folder,
|
||||||
|
IServiceTokenData,
|
||||||
|
Membership,
|
||||||
|
ServiceTokenData,
|
||||||
|
User
|
||||||
|
} from "../../models";
|
||||||
import { getFolderByPath } from "../../services/FolderService";
|
import { getFolderByPath } from "../../services/FolderService";
|
||||||
import { BadRequestError } from "../../utils/errors";
|
import { BadRequestError } from "../../utils/errors";
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
@@ -15,13 +20,10 @@ import * as reqValidator from "../../validation/secrets";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../ee/services/ProjectRoleService";
|
} from "../../ee/services/ProjectRoleService";
|
||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
import {
|
import { validateServiceTokenDataClientForWorkspace } from "../../validation";
|
||||||
validateServiceTokenDataClientForWorkspace,
|
|
||||||
validateServiceTokenDataV3ClientForWorkspace
|
|
||||||
} from "../../validation";
|
|
||||||
import { PERMISSION_READ_SECRETS, PERMISSION_WRITE_SECRETS } from "../../variables";
|
import { PERMISSION_READ_SECRETS, PERMISSION_WRITE_SECRETS } from "../../variables";
|
||||||
import { ActorType } from "../../ee/models";
|
import { ActorType } from "../../ee/models";
|
||||||
import { UnauthorizedRequestError } from "../../utils/errors";
|
import { UnauthorizedRequestError } from "../../utils/errors";
|
||||||
@@ -31,7 +33,6 @@ import {
|
|||||||
getSecretPolicyOfBoard
|
getSecretPolicyOfBoard
|
||||||
} from "../../ee/services/SecretApprovalService";
|
} from "../../ee/services/SecretApprovalService";
|
||||||
import { CommitType } from "../../ee/models/secretApprovalRequest";
|
import { CommitType } from "../../ee/models/secretApprovalRequest";
|
||||||
import { IRole } from "../../ee/models/role";
|
|
||||||
|
|
||||||
const checkSecretsPermission = async ({
|
const checkSecretsPermission = async ({
|
||||||
authData,
|
authData,
|
||||||
@@ -47,36 +48,31 @@ const checkSecretsPermission = async ({
|
|||||||
secretAction: ProjectPermissionActions; // CRUD
|
secretAction: ProjectPermissionActions; // CRUD
|
||||||
}): Promise<{
|
}): Promise<{
|
||||||
authVerifier: (env: string, secPath: string) => boolean;
|
authVerifier: (env: string, secPath: string) => boolean;
|
||||||
membership?: Omit<IMembership, "customRole"> & { customRole: IRole };
|
|
||||||
}> => {
|
}> => {
|
||||||
let STV2RequiredPermissions = [];
|
let STV2RequiredPermissions = [];
|
||||||
let STV3RequiredPermissions: Permission[] = [];
|
|
||||||
|
|
||||||
switch (secretAction) {
|
switch (secretAction) {
|
||||||
case ProjectPermissionActions.Create:
|
case ProjectPermissionActions.Create:
|
||||||
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
||||||
STV3RequiredPermissions = [Permission.WRITE];
|
|
||||||
break;
|
break;
|
||||||
case ProjectPermissionActions.Read:
|
case ProjectPermissionActions.Read:
|
||||||
STV2RequiredPermissions = [PERMISSION_READ_SECRETS];
|
STV2RequiredPermissions = [PERMISSION_READ_SECRETS];
|
||||||
STV3RequiredPermissions = [Permission.READ];
|
|
||||||
break;
|
break;
|
||||||
case ProjectPermissionActions.Edit:
|
case ProjectPermissionActions.Edit:
|
||||||
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
||||||
STV3RequiredPermissions = [Permission.WRITE];
|
|
||||||
break;
|
break;
|
||||||
case ProjectPermissionActions.Delete:
|
case ProjectPermissionActions.Delete:
|
||||||
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
STV2RequiredPermissions = [PERMISSION_WRITE_SECRETS];
|
||||||
STV3RequiredPermissions = [Permission.WRITE];
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (authData.actor.type) {
|
switch (authData.actor.type) {
|
||||||
case ActorType.USER: {
|
case ActorType.USER: {
|
||||||
const { permission, membership } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
authData.actor.metadata.userId,
|
authData,
|
||||||
workspaceId
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
secretAction,
|
secretAction,
|
||||||
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
||||||
@@ -89,8 +85,7 @@ const checkSecretsPermission = async ({
|
|||||||
environment: env,
|
environment: env,
|
||||||
secretPath: secPath
|
secretPath: secPath
|
||||||
})
|
})
|
||||||
),
|
)
|
||||||
membership
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case ActorType.SERVICE: {
|
case ActorType.SERVICE: {
|
||||||
@@ -104,22 +99,24 @@ const checkSecretsPermission = async ({
|
|||||||
return { authVerifier: () => true };
|
return { authVerifier: () => true };
|
||||||
}
|
}
|
||||||
case ActorType.SERVICE_V3: {
|
case ActorType.SERVICE_V3: {
|
||||||
await validateServiceTokenDataV3ClientForWorkspace({
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
authData,
|
authData,
|
||||||
serviceTokenData: authData.authPayload as IServiceTokenDataV3,
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
workspaceId: new Types.ObjectId(workspaceId),
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
requiredPermissions: STV3RequiredPermissions
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
|
secretAction,
|
||||||
|
subject(ProjectPermissionSub.Secrets, { environment, secretPath })
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
authVerifier: (env: string, secPath: string) =>
|
authVerifier: (env: string, secPath: string) =>
|
||||||
isValidScopeV3({
|
permission.can(
|
||||||
authPayload: authData.authPayload as IServiceTokenDataV3,
|
secretAction,
|
||||||
environment: env,
|
subject(ProjectPermissionSub.Secrets, {
|
||||||
secretPath: secPath,
|
environment: env,
|
||||||
requiredPermissions: STV3RequiredPermissions
|
secretPath: secPath
|
||||||
})
|
})
|
||||||
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
@@ -199,17 +196,20 @@ export const getSecretsRaw = async (req: Request, res: Response) => {
|
|||||||
query: { include_imports: includeImports }
|
query: { include_imports: includeImports }
|
||||||
} = validatedData;
|
} = validatedData;
|
||||||
|
|
||||||
// if the service token has single scope, it will get all secrets for that scope by default
|
if (req.authData.authPayload instanceof ServiceTokenData) {
|
||||||
const serviceTokenDetails: IServiceTokenData = req?.serviceTokenData;
|
|
||||||
if (
|
// if the service token has single scope, it will get all secrets for that scope by default
|
||||||
serviceTokenDetails &&
|
const serviceTokenDetails: IServiceTokenData = req?.serviceTokenData;
|
||||||
serviceTokenDetails.scopes.length == 1 &&
|
if (
|
||||||
!containsGlobPatterns(serviceTokenDetails.scopes[0].secretPath)
|
serviceTokenDetails &&
|
||||||
) {
|
serviceTokenDetails.scopes.length == 1 &&
|
||||||
const scope = serviceTokenDetails.scopes[0];
|
!containsGlobPatterns(serviceTokenDetails.scopes[0].secretPath)
|
||||||
secretPath = scope.secretPath;
|
) {
|
||||||
environment = scope.environment;
|
const scope = serviceTokenDetails.scopes[0];
|
||||||
workspaceId = serviceTokenDetails.workspace.toString();
|
secretPath = scope.secretPath;
|
||||||
|
environment = scope.environment;
|
||||||
|
workspaceId = serviceTokenDetails.workspace.toString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!environment || !workspaceId)
|
if (!environment || !workspaceId)
|
||||||
@@ -900,7 +900,7 @@ export const createSecret = async (req: Request, res: Response) => {
|
|||||||
params: { secretName }
|
params: { secretName }
|
||||||
} = await validateRequest(reqValidator.CreateSecretV3, req);
|
} = await validateRequest(reqValidator.CreateSecretV3, req);
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -908,35 +908,42 @@ export const createSecret = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Create
|
secretAction: ProjectPermissionActions.Create
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership && type !== "personal") {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership && type !== "personal") {
|
||||||
policy: secretApprovalPolicy,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
commiterMembershipId: membership._id.toString(),
|
if (secretApprovalPolicy) {
|
||||||
authData: req.authData,
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
data: {
|
workspaceId,
|
||||||
[CommitType.CREATE]: [
|
environment,
|
||||||
{
|
secretPath,
|
||||||
secretName,
|
policy: secretApprovalPolicy,
|
||||||
secretValueCiphertext,
|
commiterMembershipId: membership._id.toString(),
|
||||||
secretValueIV,
|
authData: req.authData,
|
||||||
secretValueTag,
|
data: {
|
||||||
secretCommentIV,
|
[CommitType.CREATE]: [
|
||||||
secretCommentTag,
|
{
|
||||||
secretCommentCiphertext,
|
secretName,
|
||||||
skipMultilineEncoding,
|
secretValueCiphertext,
|
||||||
secretKeyTag,
|
secretValueIV,
|
||||||
secretKeyCiphertext,
|
secretValueTag,
|
||||||
secretKeyIV
|
secretCommentIV,
|
||||||
}
|
secretCommentTag,
|
||||||
]
|
secretCommentCiphertext,
|
||||||
}
|
skipMultilineEncoding,
|
||||||
});
|
secretKeyTag,
|
||||||
return res.send({ approval: secretApprovalRequest });
|
secretKeyCiphertext,
|
||||||
|
secretKeyIV
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1009,7 +1016,7 @@ export const updateSecretByName = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "Missing encrypted key" });
|
throw BadRequestError({ message: "Missing encrypted key" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -1017,37 +1024,44 @@ export const updateSecretByName = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Edit
|
secretAction: ProjectPermissionActions.Edit
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership && type !== "personal") {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership && type !== "personal") {
|
||||||
policy: secretApprovalPolicy,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
commiterMembershipId: membership._id.toString(),
|
if (secretApprovalPolicy) {
|
||||||
authData: req.authData,
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
data: {
|
workspaceId,
|
||||||
[CommitType.UPDATE]: [
|
environment,
|
||||||
{
|
secretPath,
|
||||||
secretName,
|
policy: secretApprovalPolicy,
|
||||||
newSecretName,
|
commiterMembershipId: membership._id.toString(),
|
||||||
secretValueCiphertext,
|
authData: req.authData,
|
||||||
secretValueIV,
|
data: {
|
||||||
secretValueTag,
|
[CommitType.UPDATE]: [
|
||||||
tags,
|
{
|
||||||
secretCommentIV,
|
secretName,
|
||||||
secretCommentTag,
|
newSecretName,
|
||||||
secretCommentCiphertext,
|
secretValueCiphertext,
|
||||||
skipMultilineEncoding,
|
secretValueIV,
|
||||||
secretKeyTag,
|
secretValueTag,
|
||||||
secretKeyCiphertext,
|
tags,
|
||||||
secretKeyIV
|
secretCommentIV,
|
||||||
}
|
secretCommentTag,
|
||||||
]
|
secretCommentCiphertext,
|
||||||
}
|
skipMultilineEncoding,
|
||||||
});
|
secretKeyTag,
|
||||||
return res.send({ approval: secretApprovalRequest });
|
secretKeyCiphertext,
|
||||||
|
secretKeyIV
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1097,7 +1111,7 @@ export const deleteSecretByName = async (req: Request, res: Response) => {
|
|||||||
params: { secretName }
|
params: { secretName }
|
||||||
} = await validateRequest(reqValidator.DeleteSecretByNameV3, req);
|
} = await validateRequest(reqValidator.DeleteSecretByNameV3, req);
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -1105,25 +1119,32 @@ export const deleteSecretByName = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Delete
|
secretAction: ProjectPermissionActions.Delete
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership && type !== "personal") {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership && type !== "personal") {
|
||||||
authData: req.authData,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
policy: secretApprovalPolicy,
|
if (secretApprovalPolicy) {
|
||||||
commiterMembershipId: membership._id.toString(),
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
data: {
|
workspaceId,
|
||||||
[CommitType.DELETE]: [
|
environment,
|
||||||
{
|
secretPath,
|
||||||
secretName
|
authData: req.authData,
|
||||||
}
|
policy: secretApprovalPolicy,
|
||||||
]
|
commiterMembershipId: membership._id.toString(),
|
||||||
}
|
data: {
|
||||||
});
|
[CommitType.DELETE]: [
|
||||||
return res.send({ approval: secretApprovalRequest });
|
{
|
||||||
|
secretName
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1155,7 +1176,7 @@ export const createSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
body: { secrets, secretPath, environment, workspaceId }
|
body: { secrets, secretPath, environment, workspaceId }
|
||||||
} = await validateRequest(reqValidator.CreateSecretByNameBatchV3, req);
|
} = await validateRequest(reqValidator.CreateSecretByNameBatchV3, req);
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -1163,21 +1184,28 @@ export const createSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Create
|
secretAction: ProjectPermissionActions.Create
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership) {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership) {
|
||||||
authData: req.authData,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
policy: secretApprovalPolicy,
|
if (secretApprovalPolicy) {
|
||||||
commiterMembershipId: membership._id.toString(),
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
data: {
|
workspaceId,
|
||||||
[CommitType.CREATE]: secrets.filter(({ type }) => type === "shared")
|
environment,
|
||||||
}
|
secretPath,
|
||||||
});
|
authData: req.authData,
|
||||||
return res.send({ approval: secretApprovalRequest });
|
policy: secretApprovalPolicy,
|
||||||
|
commiterMembershipId: membership._id.toString(),
|
||||||
|
data: {
|
||||||
|
[CommitType.CREATE]: secrets.filter(({ type }) => type === "shared")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1207,7 +1235,7 @@ export const updateSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
body: { secrets, secretPath, environment, workspaceId }
|
body: { secrets, secretPath, environment, workspaceId }
|
||||||
} = await validateRequest(reqValidator.UpdateSecretByNameBatchV3, req);
|
} = await validateRequest(reqValidator.UpdateSecretByNameBatchV3, req);
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -1215,21 +1243,28 @@ export const updateSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Edit
|
secretAction: ProjectPermissionActions.Edit
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership) {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership) {
|
||||||
policy: secretApprovalPolicy,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
commiterMembershipId: membership._id.toString(),
|
if (secretApprovalPolicy) {
|
||||||
data: {
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
[CommitType.UPDATE]: secrets.filter(({ type }) => type === "shared")
|
workspaceId,
|
||||||
},
|
environment,
|
||||||
authData: req.authData
|
secretPath,
|
||||||
});
|
policy: secretApprovalPolicy,
|
||||||
return res.send({ approval: secretApprovalRequest });
|
commiterMembershipId: membership._id.toString(),
|
||||||
|
data: {
|
||||||
|
[CommitType.UPDATE]: secrets.filter(({ type }) => type === "shared")
|
||||||
|
},
|
||||||
|
authData: req.authData
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1258,8 +1293,8 @@ export const deleteSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
const {
|
const {
|
||||||
body: { secrets, secretPath, environment, workspaceId }
|
body: { secrets, secretPath, environment, workspaceId }
|
||||||
} = await validateRequest(reqValidator.DeleteSecretByNameBatchV3, req);
|
} = await validateRequest(reqValidator.DeleteSecretByNameBatchV3, req);
|
||||||
|
|
||||||
const { membership } = await checkSecretsPermission({
|
await checkSecretsPermission({
|
||||||
authData: req.authData,
|
authData: req.authData,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
environment,
|
environment,
|
||||||
@@ -1267,21 +1302,28 @@ export const deleteSecretByNameBatch = async (req: Request, res: Response) => {
|
|||||||
secretAction: ProjectPermissionActions.Delete
|
secretAction: ProjectPermissionActions.Delete
|
||||||
});
|
});
|
||||||
|
|
||||||
if (membership) {
|
if (req.authData.authPayload instanceof User) {
|
||||||
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
const membership = await Membership.findOne({
|
||||||
if (secretApprovalPolicy) {
|
user: req.authData.authPayload._id,
|
||||||
const secretApprovalRequest = await generateSecretApprovalRequest({
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
workspaceId,
|
});
|
||||||
environment,
|
|
||||||
secretPath,
|
if (membership) {
|
||||||
policy: secretApprovalPolicy,
|
const secretApprovalPolicy = await getSecretPolicyOfBoard(workspaceId, environment, secretPath);
|
||||||
commiterMembershipId: membership._id.toString(),
|
if (secretApprovalPolicy) {
|
||||||
data: {
|
const secretApprovalRequest = await generateSecretApprovalRequest({
|
||||||
[CommitType.DELETE]: secrets.filter(({ type }) => type === "shared")
|
workspaceId,
|
||||||
},
|
environment,
|
||||||
authData: req.authData
|
secretPath,
|
||||||
});
|
policy: secretApprovalPolicy,
|
||||||
return res.send({ approval: secretApprovalRequest });
|
commiterMembershipId: membership._id.toString(),
|
||||||
|
data: {
|
||||||
|
[CommitType.DELETE]: secrets.filter(({ type }) => type === "shared")
|
||||||
|
},
|
||||||
|
authData: req.authData
|
||||||
|
});
|
||||||
|
return res.send({ approval: secretApprovalRequest });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { validateRequest } from "../../helpers/validation";
|
import { validateRequest } from "../../helpers/validation";
|
||||||
import { Secret, ServiceTokenDataV3 } from "../../models";
|
import { Membership, Secret, ServiceTokenDataV3, User } from "../../models";
|
||||||
import { SecretService } from "../../services";
|
import { SecretService } from "../../services";
|
||||||
import { getUserProjectPermissions } from "../../ee/services/ProjectRoleService";
|
import { getAuthDataProjectPermissions } from "../../ee/services/ProjectRoleService";
|
||||||
import { UnauthorizedRequestError } from "../../utils/errors";
|
import { UnauthorizedRequestError } from "../../utils/errors";
|
||||||
import * as reqValidator from "../../validation/workspace";
|
import * as reqValidator from "../../validation/workspace";
|
||||||
|
|
||||||
@@ -19,9 +19,22 @@ export const getWorkspaceBlindIndexStatus = async (req: Request, res: Response)
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceBlinkIndexStatusV3, req);
|
} = await validateRequest(reqValidator.GetWorkspaceBlinkIndexStatusV3, req);
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
await getAuthDataProjectPermissions({
|
||||||
if (membership.role !== "admin")
|
authData: req.authData,
|
||||||
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (req.authData.authPayload instanceof User) {
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
|
if (membership.role !== "admin")
|
||||||
|
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
||||||
|
}
|
||||||
|
|
||||||
const secretsWithoutBlindIndex = await Secret.countDocuments({
|
const secretsWithoutBlindIndex = await Secret.countDocuments({
|
||||||
workspace: new Types.ObjectId(workspaceId),
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
@@ -41,9 +54,22 @@ export const getWorkspaceSecrets = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetWorkspaceSecretsV3, req);
|
} = await validateRequest(reqValidator.GetWorkspaceSecretsV3, req);
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
await getAuthDataProjectPermissions({
|
||||||
if (membership.role !== "admin")
|
authData: req.authData,
|
||||||
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (req.authData.authPayload instanceof User) {
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
|
if (membership.role !== "admin")
|
||||||
|
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
||||||
|
}
|
||||||
|
|
||||||
const secrets = await Secret.find({
|
const secrets = await Secret.find({
|
||||||
workspace: new Types.ObjectId(workspaceId)
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
@@ -65,9 +91,22 @@ export const nameWorkspaceSecrets = async (req: Request, res: Response) => {
|
|||||||
body: { secretsToUpdate }
|
body: { secretsToUpdate }
|
||||||
} = await validateRequest(reqValidator.NameWorkspaceSecretsV3, req);
|
} = await validateRequest(reqValidator.NameWorkspaceSecretsV3, req);
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
await getAuthDataProjectPermissions({
|
||||||
if (membership.role !== "admin")
|
authData: req.authData,
|
||||||
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (req.authData.authPayload instanceof User) {
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
|
if (membership.role !== "admin")
|
||||||
|
throw UnauthorizedRequestError({ message: "User must be an admin" });
|
||||||
|
}
|
||||||
|
|
||||||
// get secret blind index salt
|
// get secret blind index salt
|
||||||
const salt = await SecretService.getSecretBlindIndexSalt({
|
const salt = await SecretService.getSecretBlindIndexSalt({
|
||||||
@@ -109,7 +148,7 @@ export const getWorkspaceServiceTokenData = async (req: Request, res: Response)
|
|||||||
|
|
||||||
const serviceTokenData = await ServiceTokenDataV3.find({
|
const serviceTokenData = await ServiceTokenDataV3.find({
|
||||||
workspace: new Types.ObjectId(workspaceId)
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
});
|
}).populate("customRole");
|
||||||
|
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
serviceTokenData
|
serviceTokenData
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
import { Membership, User } from "../../../models";
|
||||||
import {
|
import {
|
||||||
CreateRoleSchema,
|
CreateRoleSchema,
|
||||||
DeleteRoleSchema,
|
DeleteRoleSchema,
|
||||||
@@ -11,7 +13,7 @@ import {
|
|||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
adminProjectPermissions,
|
adminProjectPermissions,
|
||||||
getUserProjectPermissions,
|
getAuthDataProjectPermissions,
|
||||||
memberProjectPermissions,
|
memberProjectPermissions,
|
||||||
viewerProjectPermission
|
viewerProjectPermission
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
@@ -39,7 +41,10 @@ export const createRole = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "user doesn't have the permission." });
|
throw BadRequestError({ message: "user doesn't have the permission." });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user.id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
if (permission.cannot(ProjectPermissionActions.Create, ProjectPermissionSub.Role)) {
|
if (permission.cannot(ProjectPermissionActions.Create, ProjectPermissionSub.Role)) {
|
||||||
throw BadRequestError({ message: "User doesn't have the permission." });
|
throw BadRequestError({ message: "User doesn't have the permission." });
|
||||||
}
|
}
|
||||||
@@ -82,7 +87,11 @@ export const updateRole = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "User doesn't have the org permission." });
|
throw BadRequestError({ message: "User doesn't have the org permission." });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user.id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
if (permission.cannot(ProjectPermissionActions.Edit, ProjectPermissionSub.Role)) {
|
if (permission.cannot(ProjectPermissionActions.Edit, ProjectPermissionSub.Role)) {
|
||||||
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
||||||
}
|
}
|
||||||
@@ -134,7 +143,11 @@ export const deleteRole = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "User doesn't have the org permission." });
|
throw BadRequestError({ message: "User doesn't have the org permission." });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user.id, role.workspace.toString());
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: role.workspace
|
||||||
|
});
|
||||||
|
|
||||||
if (permission.cannot(ProjectPermissionActions.Delete, ProjectPermissionSub.Role)) {
|
if (permission.cannot(ProjectPermissionActions.Delete, ProjectPermissionSub.Role)) {
|
||||||
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
||||||
}
|
}
|
||||||
@@ -162,7 +175,11 @@ export const getRoles = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "User doesn't have the org permission." });
|
throw BadRequestError({ message: "User doesn't have the org permission." });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const { permission } = await getUserProjectPermissions(req.user.id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
if (permission.cannot(ProjectPermissionActions.Read, ProjectPermissionSub.Role)) {
|
if (permission.cannot(ProjectPermissionActions.Read, ProjectPermissionSub.Role)) {
|
||||||
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
throw BadRequestError({ message: "User doesn't have the workspace permission." });
|
||||||
}
|
}
|
||||||
@@ -227,7 +244,19 @@ export const getUserWorkspacePermissions = async (req: Request, res: Response) =
|
|||||||
const {
|
const {
|
||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(GetUserProjectPermission, req);
|
} = await validateRequest(GetUserProjectPermission, req);
|
||||||
const { permission, membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
let membership;
|
||||||
|
if (req.authData.authPayload instanceof User) {
|
||||||
|
membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
import { Types } from "mongoose";
|
||||||
import { ForbiddenError, subject } from "@casl/ability";
|
import { ForbiddenError, subject } from "@casl/ability";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { validateRequest } from "../../../helpers/validation";
|
import { validateRequest } from "../../../helpers/validation";
|
||||||
import { SecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
import { SecretApprovalPolicy } from "../../models/secretApprovalPolicy";
|
||||||
@@ -19,7 +20,11 @@ export const createSecretApprovalPolicy = async (req: Request, res: Response) =>
|
|||||||
body: { approvals, secretPath, approvers, environment, workspaceId, name }
|
body: { approvals, secretPath, approvers, environment, workspaceId, name }
|
||||||
} = await validateRequest(reqValidator.CreateSecretApprovalRule, req);
|
} = await validateRequest(reqValidator.CreateSecretApprovalRule, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.SecretApproval
|
ProjectPermissionSub.SecretApproval
|
||||||
@@ -49,10 +54,11 @@ export const updateSecretApprovalPolicy = async (req: Request, res: Response) =>
|
|||||||
const secretApproval = await SecretApprovalPolicy.findById(id);
|
const secretApproval = await SecretApprovalPolicy.findById(id);
|
||||||
if (!secretApproval) throw ERR_SECRET_APPROVAL_NOT_FOUND;
|
if (!secretApproval) throw ERR_SECRET_APPROVAL_NOT_FOUND;
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
secretApproval.workspace.toString()
|
workspaceId: secretApproval.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.SecretApproval
|
ProjectPermissionSub.SecretApproval
|
||||||
@@ -78,10 +84,11 @@ export const deleteSecretApprovalPolicy = async (req: Request, res: Response) =>
|
|||||||
const secretApproval = await SecretApprovalPolicy.findById(id);
|
const secretApproval = await SecretApprovalPolicy.findById(id);
|
||||||
if (!secretApproval) throw ERR_SECRET_APPROVAL_NOT_FOUND;
|
if (!secretApproval) throw ERR_SECRET_APPROVAL_NOT_FOUND;
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
secretApproval.workspace.toString()
|
workspaceId: secretApproval.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.SecretApproval
|
ProjectPermissionSub.SecretApproval
|
||||||
@@ -99,7 +106,11 @@ export const getSecretApprovalPolicy = async (req: Request, res: Response) => {
|
|||||||
query: { workspaceId }
|
query: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.GetSecretApprovalRuleList, req);
|
} = await validateRequest(reqValidator.GetSecretApprovalRuleList, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretApproval
|
ProjectPermissionSub.SecretApproval
|
||||||
@@ -117,7 +128,11 @@ export const getSecretApprovalPolicyOfBoard = async (req: Request, res: Response
|
|||||||
query: { workspaceId, environment, secretPath }
|
query: { workspaceId, environment, secretPath }
|
||||||
} = await validateRequest(reqValidator.GetSecretApprovalPolicyOfABoard, req);
|
} = await validateRequest(reqValidator.GetSecretApprovalPolicyOfABoard, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
subject(ProjectPermissionSub.Secrets, { secretPath, environment })
|
subject(ProjectPermissionSub.Secrets, { secretPath, environment })
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { getUserProjectPermissions } from "../../services/ProjectRoleService";
|
|
||||||
import { validateRequest } from "../../../helpers/validation";
|
import { validateRequest } from "../../../helpers/validation";
|
||||||
import { Folder } from "../../../models";
|
import { Folder, Membership, User } from "../../../models";
|
||||||
import { ApprovalStatus, SecretApprovalRequest } from "../../models/secretApprovalRequest";
|
import { ApprovalStatus, SecretApprovalRequest } from "../../models/secretApprovalRequest";
|
||||||
import * as reqValidator from "../../validation/secretApprovalRequest";
|
import * as reqValidator from "../../validation/secretApprovalRequest";
|
||||||
import { getFolderWithPathFromId } from "../../../services/FolderService";
|
import { getFolderWithPathFromId } from "../../../services/FolderService";
|
||||||
@@ -17,7 +16,15 @@ export const getSecretApprovalRequestCount = async (req: Request, res: Response)
|
|||||||
query: { workspaceId }
|
query: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.getSecretApprovalRequestCount, req);
|
} = await validateRequest(reqValidator.getSecretApprovalRequestCount, req);
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
|
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
const approvalRequestCount = await SecretApprovalRequest.aggregate([
|
const approvalRequestCount = await SecretApprovalRequest.aggregate([
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
@@ -65,7 +72,14 @@ export const getSecretApprovalRequests = async (req: Request, res: Response) =>
|
|||||||
query: { status, committer, workspaceId, environment, limit, offset }
|
query: { status, committer, workspaceId, environment, limit, offset }
|
||||||
} = await validateRequest(reqValidator.getSecretApprovalRequests, req);
|
} = await validateRequest(reqValidator.getSecretApprovalRequests, req);
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(req.user._id, workspaceId);
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
|
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
const query = {
|
const query = {
|
||||||
workspace: new Types.ObjectId(workspaceId),
|
workspace: new Types.ObjectId(workspaceId),
|
||||||
@@ -148,10 +162,15 @@ export const getSecretApprovalRequestDetails = async (req: Request, res: Respons
|
|||||||
if (!secretApprovalRequest)
|
if (!secretApprovalRequest)
|
||||||
throw BadRequestError({ message: "Secret approval request not found" });
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
req.user._id,
|
|
||||||
secretApprovalRequest.workspace.toString()
|
const membership = await Membership.findOne({
|
||||||
);
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: secretApprovalRequest.workspace
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
// allow to fetch only if its admin or is the committer or approver
|
// allow to fetch only if its admin or is the committer or approver
|
||||||
if (
|
if (
|
||||||
membership.role !== "admin" &&
|
membership.role !== "admin" &&
|
||||||
@@ -190,10 +209,15 @@ export const updateSecretApprovalReviewStatus = async (req: Request, res: Respon
|
|||||||
if (!secretApprovalRequest)
|
if (!secretApprovalRequest)
|
||||||
throw BadRequestError({ message: "Secret approval request not found" });
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
req.user._id,
|
|
||||||
secretApprovalRequest.workspace.toString()
|
const membership = await Membership.findOne({
|
||||||
);
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: secretApprovalRequest.workspace
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
if (
|
if (
|
||||||
membership.role !== "admin" &&
|
membership.role !== "admin" &&
|
||||||
secretApprovalRequest.committer !== membership.id &&
|
secretApprovalRequest.committer !== membership.id &&
|
||||||
@@ -227,10 +251,15 @@ export const mergeSecretApprovalRequest = async (req: Request, res: Response) =>
|
|||||||
if (!secretApprovalRequest)
|
if (!secretApprovalRequest)
|
||||||
throw BadRequestError({ message: "Secret approval request not found" });
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
req.user._id,
|
|
||||||
secretApprovalRequest.workspace.toString()
|
const membership = await Membership.findOne({
|
||||||
);
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: secretApprovalRequest.workspace
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
if (
|
if (
|
||||||
membership.role !== "admin" &&
|
membership.role !== "admin" &&
|
||||||
secretApprovalRequest.committer !== membership.id &&
|
secretApprovalRequest.committer !== membership.id &&
|
||||||
@@ -272,10 +301,14 @@ export const updateSecretApprovalRequestStatus = async (req: Request, res: Respo
|
|||||||
if (!secretApprovalRequest)
|
if (!secretApprovalRequest)
|
||||||
throw BadRequestError({ message: "Secret approval request not found" });
|
throw BadRequestError({ message: "Secret approval request not found" });
|
||||||
|
|
||||||
const { membership } = await getUserProjectPermissions(
|
if (!(req.authData.authPayload instanceof User)) return;
|
||||||
req.user._id,
|
|
||||||
secretApprovalRequest.workspace.toString()
|
const membership = await Membership.findOne({
|
||||||
);
|
user: req.authData.authPayload._id,
|
||||||
|
workspace: secretApprovalRequest.workspace
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!membership) throw UnauthorizedRequestError();
|
||||||
|
|
||||||
if (
|
if (
|
||||||
membership.role !== "admin" &&
|
membership.role !== "admin" &&
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { Folder, Secret } from "../../../models";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { BadRequestError } from "../../../utils/errors";
|
import { BadRequestError } from "../../../utils/errors";
|
||||||
import * as reqValidator from "../../../validation";
|
import * as reqValidator from "../../../validation";
|
||||||
@@ -74,7 +74,11 @@ export const getSecretVersions = async (req: Request, res: Response) => {
|
|||||||
throw BadRequestError({ message: "Failed to find secret" });
|
throw BadRequestError({ message: "Failed to find secret" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, secret.workspace.toString());
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: secret.workspace
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
@@ -157,10 +161,12 @@ export const rollbackSecretVersion = async (req: Request, res: Response) => {
|
|||||||
if (!toBeUpdatedSec) {
|
if (!toBeUpdatedSec) {
|
||||||
throw BadRequestError({ message: "Failed to find secret" });
|
throw BadRequestError({ message: "Failed to find secret" });
|
||||||
}
|
}
|
||||||
const { permission } = await getUserProjectPermissions(
|
|
||||||
req.user._id,
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
toBeUpdatedSec.workspace.toString()
|
authData: req.authData,
|
||||||
);
|
workspaceId: toBeUpdatedSec.workspace
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
|
import { Types } from "mongoose";
|
||||||
import { validateRequest } from "../../../helpers/validation";
|
import { validateRequest } from "../../../helpers/validation";
|
||||||
import * as reqValidator from "../../validation/secretRotation";
|
import * as reqValidator from "../../validation/secretRotation";
|
||||||
import * as secretRotationService from "../../secretRotation/service";
|
import * as secretRotationService from "../../secretRotation/service";
|
||||||
import {
|
import {
|
||||||
getUserProjectPermissions,
|
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub
|
ProjectPermissionSub,
|
||||||
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
|
||||||
@@ -23,7 +24,11 @@ export const createSecretRotation = async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
} = await validateRequest(reqValidator.createSecretRotationV1, req);
|
} = await validateRequest(reqValidator.createSecretRotationV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.SecretRotation
|
ProjectPermissionSub.SecretRotation
|
||||||
@@ -49,7 +54,12 @@ export const restartSecretRotations = async (req: Request, res: Response) => {
|
|||||||
} = await validateRequest(reqValidator.restartSecretRotationV1, req);
|
} = await validateRequest(reqValidator.restartSecretRotationV1, req);
|
||||||
|
|
||||||
const doc = await secretRotationService.getSecretRotationById({ id });
|
const doc = await secretRotationService.getSecretRotationById({ id });
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, doc.workspace.toString());
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: doc.workspace
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.SecretRotation
|
ProjectPermissionSub.SecretRotation
|
||||||
@@ -65,7 +75,12 @@ export const deleteSecretRotations = async (req: Request, res: Response) => {
|
|||||||
} = await validateRequest(reqValidator.removeSecretRotationV1, req);
|
} = await validateRequest(reqValidator.removeSecretRotationV1, req);
|
||||||
|
|
||||||
const doc = await secretRotationService.getSecretRotationById({ id });
|
const doc = await secretRotationService.getSecretRotationById({ id });
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, doc.workspace.toString());
|
|
||||||
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: doc.workspace
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.SecretRotation
|
ProjectPermissionSub.SecretRotation
|
||||||
@@ -80,7 +95,11 @@ export const getSecretRotations = async (req: Request, res: Response) => {
|
|||||||
query: { workspaceId }
|
query: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.getSecretRotationV1, req);
|
} = await validateRequest(reqValidator.getSecretRotationV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRotation
|
ProjectPermissionSub.SecretRotation
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
|
import { Types } from "mongoose";
|
||||||
import { validateRequest } from "../../../helpers/validation";
|
import { validateRequest } from "../../../helpers/validation";
|
||||||
import * as reqValidator from "../../validation/secretRotationProvider";
|
import * as reqValidator from "../../validation/secretRotationProvider";
|
||||||
import * as secretRotationProviderService from "../../secretRotation/service";
|
import * as secretRotationProviderService from "../../secretRotation/service";
|
||||||
import {
|
import {
|
||||||
getUserProjectPermissions,
|
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub
|
ProjectPermissionSub,
|
||||||
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
|
||||||
@@ -14,7 +15,11 @@ export const getProviderTemplates = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(reqValidator.getSecretRotationProvidersV1, req);
|
} = await validateRequest(reqValidator.getSecretRotationProvidersV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRotation
|
ProjectPermissionSub.SecretRotation
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { validateRequest } from "../../../helpers/validation";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import * as reqValidator from "../../../validation/secretSnapshot";
|
import * as reqValidator from "../../../validation/secretSnapshot";
|
||||||
import { ISecretVersion, SecretSnapshot, TFolderRootVersionSchema } from "../../models";
|
import { ISecretVersion, SecretSnapshot, TFolderRootVersionSchema } from "../../models";
|
||||||
@@ -33,10 +33,11 @@ export const getSecretSnapshot = async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
if (!secretSnapshot) throw new Error("Failed to find secret snapshot");
|
if (!secretSnapshot) throw new Error("Failed to find secret snapshot");
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
secretSnapshot.workspace.toString()
|
workspaceId: secretSnapshot.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import {
|
|||||||
} from "../../models";
|
} from "../../models";
|
||||||
import { EESecretService } from "../../services";
|
import { EESecretService } from "../../services";
|
||||||
import { getLatestSecretVersionIds } from "../../helpers/secretVersion";
|
import { getLatestSecretVersionIds } from "../../helpers/secretVersion";
|
||||||
// import Folder, { TFolderSchema } from "../../../models/folder";
|
|
||||||
import { getFolderByPath, searchByFolderId } from "../../../services/FolderService";
|
import { getFolderByPath, searchByFolderId } from "../../../services/FolderService";
|
||||||
import { EEAuditLogService, EELicenseService } from "../../services";
|
import { EEAuditLogService, EELicenseService } from "../../services";
|
||||||
import { extractIPDetails, isValidIpOrCidr } from "../../../utils/ip";
|
import { extractIPDetails, isValidIpOrCidr } from "../../../utils/ip";
|
||||||
@@ -46,7 +45,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { BadRequestError } from "../../../utils/errors";
|
import { BadRequestError } from "../../../utils/errors";
|
||||||
@@ -107,7 +106,11 @@ export const getWorkspaceSecretSnapshots = async (req: Request, res: Response) =
|
|||||||
query: { environment, directory, offset, limit }
|
query: { environment, directory, offset, limit }
|
||||||
} = await validateRequest(GetWorkspaceSecretSnapshotsV1, req);
|
} = await validateRequest(GetWorkspaceSecretSnapshotsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
@@ -148,7 +151,11 @@ export const getWorkspaceSecretSnapshotsCount = async (req: Request, res: Respon
|
|||||||
query: { environment, directory }
|
query: { environment, directory }
|
||||||
} = await validateRequest(GetWorkspaceSecretSnapshotsCountV1, req);
|
} = await validateRequest(GetWorkspaceSecretSnapshotsCountV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
@@ -238,7 +245,11 @@ export const rollbackWorkspaceSecretSnapshot = async (req: Request, res: Respons
|
|||||||
body: { directory, environment, version }
|
body: { directory, environment, version }
|
||||||
} = await validateRequest(RollbackWorkspaceSecretSnapshotV1, req);
|
} = await validateRequest(RollbackWorkspaceSecretSnapshotV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.SecretRollback
|
ProjectPermissionSub.SecretRollback
|
||||||
@@ -572,7 +583,11 @@ export const getWorkspaceAuditLogs = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(GetWorkspaceAuditLogsV1, req);
|
} = await validateRequest(GetWorkspaceAuditLogsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.AuditLogs
|
ProjectPermissionSub.AuditLogs
|
||||||
@@ -632,7 +647,11 @@ export const getWorkspaceAuditLogActorFilterOpts = async (req: Request, res: Res
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(GetWorkspaceAuditLogActorFilterOptsV1, req);
|
} = await validateRequest(GetWorkspaceAuditLogActorFilterOptsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.AuditLogs
|
ProjectPermissionSub.AuditLogs
|
||||||
@@ -700,7 +719,11 @@ export const getWorkspaceTrustedIps = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId }
|
params: { workspaceId }
|
||||||
} = await validateRequest(GetWorkspaceTrustedIpsV1, req);
|
} = await validateRequest(GetWorkspaceTrustedIpsV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Read,
|
ProjectPermissionActions.Read,
|
||||||
ProjectPermissionSub.IpAllowList
|
ProjectPermissionSub.IpAllowList
|
||||||
@@ -726,7 +749,11 @@ export const addWorkspaceTrustedIp = async (req: Request, res: Response) => {
|
|||||||
body: { comment, isActive, ipAddress: ip }
|
body: { comment, isActive, ipAddress: ip }
|
||||||
} = await validateRequest(AddWorkspaceTrustedIpV1, req);
|
} = await validateRequest(AddWorkspaceTrustedIpV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.IpAllowList
|
ProjectPermissionSub.IpAllowList
|
||||||
@@ -792,7 +819,11 @@ export const updateWorkspaceTrustedIp = async (req: Request, res: Response) => {
|
|||||||
body: { ipAddress: ip, comment }
|
body: { ipAddress: ip, comment }
|
||||||
} = await validateRequest(UpdateWorkspaceTrustedIpV1, req);
|
} = await validateRequest(UpdateWorkspaceTrustedIpV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
ProjectPermissionSub.IpAllowList
|
ProjectPermissionSub.IpAllowList
|
||||||
@@ -884,7 +915,11 @@ export const deleteWorkspaceTrustedIp = async (req: Request, res: Response) => {
|
|||||||
params: { workspaceId, trustedIpId }
|
params: { workspaceId, trustedIpId }
|
||||||
} = await validateRequest(DeleteWorkspaceTrustedIpV1, req);
|
} = await validateRequest(DeleteWorkspaceTrustedIpV1, req);
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
ProjectPermissionSub.IpAllowList
|
ProjectPermissionSub.IpAllowList
|
||||||
|
|||||||
@@ -8,13 +8,11 @@ import {
|
|||||||
ServiceTokenDataV3Key,
|
ServiceTokenDataV3Key,
|
||||||
Workspace
|
Workspace
|
||||||
} from "../../../models";
|
} from "../../../models";
|
||||||
import {
|
import { IServiceTokenV3TrustedIp } from "../../../models/serviceTokenDataV3";
|
||||||
IServiceTokenV3Scope,
|
|
||||||
IServiceTokenV3TrustedIp
|
|
||||||
} from "../../../models/serviceTokenDataV3";
|
|
||||||
import {
|
import {
|
||||||
ActorType,
|
ActorType,
|
||||||
EventType
|
EventType,
|
||||||
|
Role
|
||||||
} from "../../models";
|
} from "../../models";
|
||||||
import { validateRequest } from "../../../helpers/validation";
|
import { validateRequest } from "../../../helpers/validation";
|
||||||
import * as reqValidator from "../../../validation/serviceTokenDataV3";
|
import * as reqValidator from "../../../validation/serviceTokenDataV3";
|
||||||
@@ -22,14 +20,14 @@ import { createToken } from "../../../helpers/auth";
|
|||||||
import {
|
import {
|
||||||
ProjectPermissionActions,
|
ProjectPermissionActions,
|
||||||
ProjectPermissionSub,
|
ProjectPermissionSub,
|
||||||
getUserProjectPermissions
|
getAuthDataProjectPermissions
|
||||||
} from "../../services/ProjectRoleService";
|
} from "../../services/ProjectRoleService";
|
||||||
import { ForbiddenError } from "@casl/ability";
|
import { ForbiddenError } from "@casl/ability";
|
||||||
import { BadRequestError, ResourceNotFoundError, UnauthorizedRequestError } from "../../../utils/errors";
|
import { BadRequestError, ResourceNotFoundError, UnauthorizedRequestError } from "../../../utils/errors";
|
||||||
import { extractIPDetails, isValidIpOrCidr } from "../../../utils/ip";
|
import { extractIPDetails, isValidIpOrCidr } from "../../../utils/ip";
|
||||||
import { EEAuditLogService, EELicenseService } from "../../services";
|
import { EEAuditLogService, EELicenseService } from "../../services";
|
||||||
import { getAuthSecret } from "../../../config";
|
import { getAuthSecret } from "../../../config";
|
||||||
import { AuthTokenType } from "../../../variables";
|
import { ADMIN, AuthTokenType, CUSTOM, MEMBER, VIEWER } from "../../../variables";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return project key for service token V3
|
* Return project key for service token V3
|
||||||
@@ -163,7 +161,7 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
name,
|
name,
|
||||||
workspaceId,
|
workspaceId,
|
||||||
publicKey,
|
publicKey,
|
||||||
scopes,
|
role,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn,
|
expiresIn,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
@@ -172,7 +170,11 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
nonce, // for ServiceTokenDataV3Key
|
nonce, // for ServiceTokenDataV3Key
|
||||||
}
|
}
|
||||||
} = await validateRequest(reqValidator.CreateServiceTokenV3, req);
|
} = await validateRequest(reqValidator.CreateServiceTokenV3, req);
|
||||||
const { permission } = await getUserProjectPermissions(req.user._id, workspaceId);
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
|
authData: req.authData,
|
||||||
|
workspaceId: new Types.ObjectId(workspaceId)
|
||||||
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Create,
|
ProjectPermissionActions.Create,
|
||||||
ProjectPermissionSub.ServiceTokens
|
ProjectPermissionSub.ServiceTokens
|
||||||
@@ -181,6 +183,19 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
const workspace = await Workspace.findById(workspaceId);
|
const workspace = await Workspace.findById(workspaceId);
|
||||||
if (!workspace) throw BadRequestError({ message: "Workspace not found" });
|
if (!workspace) throw BadRequestError({ message: "Workspace not found" });
|
||||||
|
|
||||||
|
const isCustomRole = ![ADMIN, MEMBER, VIEWER].includes(role);
|
||||||
|
|
||||||
|
let customRole;
|
||||||
|
if (isCustomRole) {
|
||||||
|
customRole = await Role.findOne({
|
||||||
|
slug: role,
|
||||||
|
isOrgRole: false,
|
||||||
|
workspace: workspace._id
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||||
|
}
|
||||||
|
|
||||||
const plan = await EELicenseService.getPlan(workspace.organization);
|
const plan = await EELicenseService.getPlan(workspace.organization);
|
||||||
|
|
||||||
// validate trusted ips
|
// validate trusted ips
|
||||||
@@ -219,7 +234,8 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
accessTokenUsageCount: 0,
|
accessTokenUsageCount: 0,
|
||||||
tokenVersion: 1,
|
tokenVersion: 1,
|
||||||
trustedIps: reformattedTrustedIps,
|
trustedIps: reformattedTrustedIps,
|
||||||
scopes,
|
role: isCustomRole ? CUSTOM : role,
|
||||||
|
customRole,
|
||||||
isActive,
|
isActive,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
@@ -250,7 +266,7 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name,
|
name,
|
||||||
isActive,
|
isActive,
|
||||||
scopes: scopes as Array<IServiceTokenV3Scope>,
|
role,
|
||||||
trustedIps: reformattedTrustedIps as Array<IServiceTokenV3TrustedIp>,
|
trustedIps: reformattedTrustedIps as Array<IServiceTokenV3TrustedIp>,
|
||||||
expiresAt
|
expiresAt
|
||||||
}
|
}
|
||||||
@@ -278,7 +294,7 @@ export const updateServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
body: {
|
body: {
|
||||||
name,
|
name,
|
||||||
isActive,
|
isActive,
|
||||||
scopes,
|
role,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn,
|
expiresIn,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
@@ -291,10 +307,10 @@ export const updateServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
message: "Service token not found"
|
message: "Service token not found"
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
serviceTokenData.workspace.toString()
|
workspaceId: serviceTokenData.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Edit,
|
ProjectPermissionActions.Edit,
|
||||||
@@ -304,6 +320,20 @@ export const updateServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
const workspace = await Workspace.findById(serviceTokenData.workspace);
|
const workspace = await Workspace.findById(serviceTokenData.workspace);
|
||||||
if (!workspace) throw BadRequestError({ message: "Workspace not found" });
|
if (!workspace) throw BadRequestError({ message: "Workspace not found" });
|
||||||
|
|
||||||
|
let customRole;
|
||||||
|
if (role) {
|
||||||
|
const isCustomRole = ![ADMIN, MEMBER, VIEWER].includes(role);
|
||||||
|
if (isCustomRole) {
|
||||||
|
customRole = await Role.findOne({
|
||||||
|
slug: role,
|
||||||
|
isOrgRole: false,
|
||||||
|
workspace: workspace._id
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!customRole) throw BadRequestError({ message: "Role not found" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const plan = await EELicenseService.getPlan(workspace.organization);
|
const plan = await EELicenseService.getPlan(workspace.organization);
|
||||||
|
|
||||||
// validate trusted ips
|
// validate trusted ips
|
||||||
@@ -335,7 +365,15 @@ export const updateServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
{
|
{
|
||||||
name,
|
name,
|
||||||
isActive,
|
isActive,
|
||||||
scopes,
|
role: customRole ? CUSTOM : role,
|
||||||
|
...(customRole ? {
|
||||||
|
customRole
|
||||||
|
} : {}),
|
||||||
|
...(role && !customRole ? { // non-custom role
|
||||||
|
$unset: {
|
||||||
|
customRole: 1
|
||||||
|
}
|
||||||
|
} : {}),
|
||||||
trustedIps: reformattedTrustedIps,
|
trustedIps: reformattedTrustedIps,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
@@ -357,7 +395,7 @@ export const updateServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: serviceTokenData.name,
|
name: serviceTokenData.name,
|
||||||
isActive,
|
isActive,
|
||||||
scopes: scopes as Array<IServiceTokenV3Scope>,
|
role,
|
||||||
trustedIps: reformattedTrustedIps as Array<IServiceTokenV3TrustedIp>,
|
trustedIps: reformattedTrustedIps as Array<IServiceTokenV3TrustedIp>,
|
||||||
expiresAt
|
expiresAt
|
||||||
}
|
}
|
||||||
@@ -388,10 +426,10 @@ export const deleteServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
message: "Service token not found"
|
message: "Service token not found"
|
||||||
});
|
});
|
||||||
|
|
||||||
const { permission } = await getUserProjectPermissions(
|
const { permission } = await getAuthDataProjectPermissions({
|
||||||
req.user._id,
|
authData: req.authData,
|
||||||
serviceTokenData.workspace.toString()
|
workspaceId: serviceTokenData.workspace
|
||||||
);
|
});
|
||||||
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(
|
ForbiddenError.from(permission).throwUnlessCan(
|
||||||
ProjectPermissionActions.Delete,
|
ProjectPermissionActions.Delete,
|
||||||
@@ -415,7 +453,7 @@ export const deleteServiceTokenData = async (req: Request, res: Response) => {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: serviceTokenData.name,
|
name: serviceTokenData.name,
|
||||||
isActive: serviceTokenData.isActive,
|
isActive: serviceTokenData.isActive,
|
||||||
scopes: serviceTokenData.scopes as Array<IServiceTokenV3Scope>,
|
role: serviceTokenData.role,
|
||||||
trustedIps: serviceTokenData.trustedIps as Array<IServiceTokenV3TrustedIp>,
|
trustedIps: serviceTokenData.trustedIps as Array<IServiceTokenV3TrustedIp>,
|
||||||
expiresAt: serviceTokenData.expiresAt
|
expiresAt: serviceTokenData.expiresAt
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ export enum ActorType {
|
|||||||
USER = "user",
|
USER = "user",
|
||||||
SERVICE = "service",
|
SERVICE = "service",
|
||||||
SERVICE_V3 = "service-v3",
|
SERVICE_V3 = "service-v3",
|
||||||
Machine = "machine"
|
// Machine = "machine"
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum UserAgentType {
|
export enum UserAgentType {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ActorType, EventType } from "./enums";
|
import { ActorType, EventType } from "./enums";
|
||||||
import { IServiceTokenV3Scope, IServiceTokenV3TrustedIp } from "../../../models/serviceTokenDataV3";
|
import { IServiceTokenV3TrustedIp } from "../../../models/serviceTokenDataV3";
|
||||||
|
|
||||||
interface UserActorMetadata {
|
interface UserActorMetadata {
|
||||||
userId: string;
|
userId: string;
|
||||||
@@ -26,11 +26,11 @@ export interface ServiceActorV3 {
|
|||||||
metadata: ServiceActorMetadata;
|
metadata: ServiceActorMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MachineActor {
|
// export interface MachineActor {
|
||||||
type: ActorType.Machine;
|
// type: ActorType.Machine;
|
||||||
}
|
// }
|
||||||
|
|
||||||
export type Actor = UserActor | ServiceActor | ServiceActorV3 | MachineActor;
|
export type Actor = UserActor | ServiceActor | ServiceActorV3;
|
||||||
|
|
||||||
interface GetSecretsEvent {
|
interface GetSecretsEvent {
|
||||||
type: EventType.GET_SECRETS;
|
type: EventType.GET_SECRETS;
|
||||||
@@ -225,7 +225,7 @@ interface CreateServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: string;
|
name: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
scopes: Array<IServiceTokenV3Scope>;
|
role: string;
|
||||||
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
};
|
};
|
||||||
@@ -236,7 +236,7 @@ interface UpdateServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name?: string;
|
name?: string;
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
scopes?: Array<IServiceTokenV3Scope>;
|
role?: string;
|
||||||
trustedIps?: Array<IServiceTokenV3TrustedIp>;
|
trustedIps?: Array<IServiceTokenV3TrustedIp>;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
};
|
};
|
||||||
@@ -247,7 +247,7 @@ interface DeleteServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: string;
|
name: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
scopes: Array<IServiceTokenV3Scope>;
|
role: string;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { Types } from "mongoose";
|
||||||
import {
|
import {
|
||||||
AbilityBuilder,
|
AbilityBuilder,
|
||||||
ForcedSubject,
|
ForcedSubject,
|
||||||
@@ -6,11 +7,14 @@ import {
|
|||||||
buildMongoQueryMatcher,
|
buildMongoQueryMatcher,
|
||||||
createMongoAbility
|
createMongoAbility
|
||||||
} from "@casl/ability";
|
} from "@casl/ability";
|
||||||
import { Membership } from "../../models";
|
import { UnauthorizedRequestError } from "../../utils/errors";
|
||||||
import { IRole } from "../models/role";
|
|
||||||
import { BadRequestError, UnauthorizedRequestError } from "../../utils/errors";
|
|
||||||
import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js";
|
import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js";
|
||||||
import picomatch from "picomatch";
|
import picomatch from "picomatch";
|
||||||
|
import { AuthData } from "../../interfaces/middleware";
|
||||||
|
import { ActorType, IRole } from "../models";
|
||||||
|
import { Membership, ServiceTokenData, ServiceTokenDataV3 } from "../../models";
|
||||||
|
import { ADMIN, CUSTOM, MEMBER, VIEWER } from "../../variables";
|
||||||
|
import { checkIPAgainstBlocklist } from "../../utils/ip";
|
||||||
|
|
||||||
const $glob: FieldInstruction<string> = {
|
const $glob: FieldInstruction<string> = {
|
||||||
type: "field",
|
type: "field",
|
||||||
@@ -239,31 +243,89 @@ const buildViewerPermission = () => {
|
|||||||
|
|
||||||
export const viewerProjectPermission = buildViewerPermission();
|
export const viewerProjectPermission = buildViewerPermission();
|
||||||
|
|
||||||
export const getUserProjectPermissions = async (userId: string, workspaceId: string) => {
|
/**
|
||||||
// TODO(akhilmhdh): speed this up by pulling from cache later
|
* Return permissions for user/service pertaining to workspace with id [workspaceId]
|
||||||
const membership = await Membership.findOne({
|
*
|
||||||
user: userId,
|
* Note: should not rely on this function for ST V2 authorization logic
|
||||||
workspace: workspaceId
|
* b/c ST V2 does not support role-based access control
|
||||||
})
|
*/
|
||||||
.populate<{
|
export const getAuthDataProjectPermissions = async ({
|
||||||
customRole: IRole & { permissions: RawRuleOf<MongoAbility<ProjectPermissionSet>>[] };
|
authData,
|
||||||
}>("customRole")
|
workspaceId
|
||||||
.exec();
|
}: {
|
||||||
|
authData: AuthData;
|
||||||
|
workspaceId: Types.ObjectId;
|
||||||
|
}) => {
|
||||||
|
let role: "admin" | "member" | "viewer" | "custom";
|
||||||
|
let customRole;
|
||||||
|
|
||||||
|
switch (authData.actor.type) {
|
||||||
|
case ActorType.USER: {
|
||||||
|
const membership = await Membership.findOne({
|
||||||
|
user: authData.authPayload._id,
|
||||||
|
workspace: workspaceId
|
||||||
|
})
|
||||||
|
.populate<{
|
||||||
|
customRole: IRole & { permissions: RawRuleOf<MongoAbility<ProjectPermissionSet>>[] };
|
||||||
|
}>("customRole")
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (!membership || (membership.role === "custom" && !membership.customRole)) {
|
||||||
|
throw UnauthorizedRequestError();
|
||||||
|
}
|
||||||
|
|
||||||
|
role = membership.role;
|
||||||
|
customRole = membership.customRole;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ActorType.SERVICE: {
|
||||||
|
const serviceTokenData = await ServiceTokenData.findById(authData.authPayload._id);
|
||||||
|
if (!serviceTokenData || !serviceTokenData.workspace.equals(workspaceId)) throw UnauthorizedRequestError();
|
||||||
|
role = "viewer";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ActorType.SERVICE_V3: {
|
||||||
|
const serviceTokenData = await ServiceTokenDataV3
|
||||||
|
.findById(authData.authPayload._id)
|
||||||
|
.populate<{
|
||||||
|
customRole: IRole & { permissions: RawRuleOf<MongoAbility<ProjectPermissionSet>>[] };
|
||||||
|
}>("customRole")
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (!serviceTokenData || (serviceTokenData.role === "custom" && !serviceTokenData.customRole)) {
|
||||||
|
throw UnauthorizedRequestError();
|
||||||
|
}
|
||||||
|
|
||||||
if (!membership || (membership.role === "custom" && !membership.customRole)) {
|
checkIPAgainstBlocklist({
|
||||||
throw UnauthorizedRequestError({ message: "User doesn't belong to organization" });
|
ipAddress: authData.ipAddress,
|
||||||
|
trustedIps: serviceTokenData.trustedIps
|
||||||
|
});
|
||||||
|
|
||||||
|
role = serviceTokenData.role;
|
||||||
|
customRole = serviceTokenData.customRole;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw UnauthorizedRequestError();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (membership.role === "admin") return { permission: adminProjectPermissions, membership };
|
switch (role) {
|
||||||
if (membership.role === "member") return { permission: memberProjectPermissions, membership };
|
case ADMIN:
|
||||||
if (membership.role === "viewer") return { permission: viewerProjectPermission, membership };
|
return { permission: adminProjectPermissions };
|
||||||
|
case MEMBER:
|
||||||
if (membership.role === "custom") {
|
return { permission: memberProjectPermissions };
|
||||||
const permission = createMongoAbility<ProjectPermissionSet>(membership.customRole.permissions, {
|
case VIEWER:
|
||||||
conditionsMatcher
|
return { permission: viewerProjectPermission };
|
||||||
});
|
case CUSTOM: {
|
||||||
return { permission, membership };
|
if (!customRole) throw UnauthorizedRequestError();
|
||||||
|
return {
|
||||||
|
permission: createMongoAbility<ProjectPermissionSet>(
|
||||||
|
customRole.permissions,
|
||||||
|
{ conditionsMatcher }
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw UnauthorizedRequestError();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
throw BadRequestError({ message: "User role not found" });
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -13,13 +13,11 @@ import {
|
|||||||
Folder,
|
Folder,
|
||||||
ISecret,
|
ISecret,
|
||||||
IServiceTokenData,
|
IServiceTokenData,
|
||||||
IServiceTokenDataV3,
|
|
||||||
Secret,
|
Secret,
|
||||||
SecretBlindIndexData,
|
SecretBlindIndexData,
|
||||||
ServiceTokenData,
|
ServiceTokenData,
|
||||||
TFolderRootSchema
|
TFolderRootSchema
|
||||||
} from "../models";
|
} from "../models";
|
||||||
import { Permission } from "../models/serviceTokenDataV3";
|
|
||||||
import { EventType, SecretVersion } from "../ee/models";
|
import { EventType, SecretVersion } from "../ee/models";
|
||||||
import {
|
import {
|
||||||
BadRequestError,
|
BadRequestError,
|
||||||
@@ -51,42 +49,6 @@ import picomatch from "picomatch";
|
|||||||
import path from "path";
|
import path from "path";
|
||||||
import { getAnImportedSecret } from "../services/SecretImportService";
|
import { getAnImportedSecret } from "../services/SecretImportService";
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate scope for service token v3
|
|
||||||
* @param authPayload
|
|
||||||
* @param environment
|
|
||||||
* @param secretPath
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
export const isValidScopeV3 = ({
|
|
||||||
authPayload,
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
requiredPermissions
|
|
||||||
}: {
|
|
||||||
authPayload: IServiceTokenDataV3;
|
|
||||||
environment: string;
|
|
||||||
secretPath: string;
|
|
||||||
requiredPermissions: Permission[];
|
|
||||||
}) => {
|
|
||||||
const { scopes } = authPayload;
|
|
||||||
|
|
||||||
const validScope = scopes.find(
|
|
||||||
(scope) =>
|
|
||||||
picomatch.isMatch(secretPath, scope.secretPath, { strictSlashes: false }) &&
|
|
||||||
scope.environment === environment
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
|
||||||
validScope &&
|
|
||||||
!requiredPermissions.every((permission) => validScope.permissions.includes(permission))
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Boolean(validScope);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate scope for service token v2
|
* Validate scope for service token v2
|
||||||
* @param authPayload
|
* @param authPayload
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
import { Document, Schema, Types, model } from "mongoose";
|
import { Document, Schema, Types, model } from "mongoose";
|
||||||
import { IPType } from "../ee/models";
|
import { IPType } from "../ee/models";
|
||||||
|
import { ADMIN, CUSTOM, MEMBER, VIEWER } from "../variables";
|
||||||
export enum Permission {
|
|
||||||
READ = "read",
|
|
||||||
WRITE = "write"
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IServiceTokenV3Scope {
|
|
||||||
environment: string;
|
|
||||||
secretPath: string;
|
|
||||||
permissions: Permission[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IServiceTokenV3TrustedIp {
|
export interface IServiceTokenV3TrustedIp {
|
||||||
ipAddress: string;
|
ipAddress: string;
|
||||||
@@ -33,7 +23,8 @@ export interface IServiceTokenDataV3 extends Document {
|
|||||||
isRefreshTokenRotationEnabled: boolean;
|
isRefreshTokenRotationEnabled: boolean;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
accessTokenTTL: number;
|
accessTokenTTL: number;
|
||||||
scopes: Array<IServiceTokenV3Scope>;
|
role: "admin" | "member" | "viewer" | "custom";
|
||||||
|
customRole: Types.ObjectId;
|
||||||
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
trustedIps: Array<IServiceTokenV3TrustedIp>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,28 +91,15 @@ const serviceTokenDataV3Schema = new Schema(
|
|||||||
default: 7200,
|
default: 7200,
|
||||||
required: true
|
required: true
|
||||||
},
|
},
|
||||||
scopes: { // TODO: consider switching this out for roles instead
|
role: {
|
||||||
type: [
|
type: String,
|
||||||
{
|
enum: [ADMIN, MEMBER, VIEWER, CUSTOM],
|
||||||
environment: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
},
|
|
||||||
secretPath: {
|
|
||||||
type: String,
|
|
||||||
default: "/",
|
|
||||||
required: true
|
|
||||||
},
|
|
||||||
permissions: {
|
|
||||||
type: [String],
|
|
||||||
enum: [Permission.READ, Permission.WRITE],
|
|
||||||
default: [Permission.READ],
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
required: true
|
required: true
|
||||||
},
|
},
|
||||||
|
customRole: {
|
||||||
|
type: Schema.Types.ObjectId,
|
||||||
|
ref: "Role"
|
||||||
|
},
|
||||||
trustedIps: {
|
trustedIps: {
|
||||||
type: [
|
type: [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -36,12 +36,4 @@ router.delete(
|
|||||||
environmentController.deleteWorkspaceEnvironment
|
environmentController.deleteWorkspaceEnvironment
|
||||||
);
|
);
|
||||||
|
|
||||||
router.get(
|
|
||||||
"/:workspaceId/environments",
|
|
||||||
requireAuth({
|
|
||||||
acceptedAuthModes: [AuthMode.JWT, AuthMode.API_KEY]
|
|
||||||
}),
|
|
||||||
environmentController.getAllAccessibleEnvironmentsOfWorkspace
|
|
||||||
);
|
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
|
|||||||
@@ -1,64 +1,5 @@
|
|||||||
import { Types } from "mongoose";
|
|
||||||
import { IServiceTokenDataV3 } from "../models";
|
|
||||||
import { Permission } from "../models/serviceTokenDataV3";
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { UnauthorizedRequestError } from "../utils/errors";
|
import { MEMBER } from "../variables";
|
||||||
import { isValidScopeV3 } from "../helpers";
|
|
||||||
import { AuthData } from "../interfaces/middleware";
|
|
||||||
import { checkIPAgainstBlocklist } from "../utils/ip";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate that service token (client) can access workspace
|
|
||||||
* with id [workspaceId] and its environment [environment] with required permissions
|
|
||||||
* [requiredPermissions]
|
|
||||||
* @param {Object} obj
|
|
||||||
* @param {ServiceTokenData} obj.serviceTokenData - service token client
|
|
||||||
* @param {Types.ObjectId} obj.workspaceId - id of workspace to validate against
|
|
||||||
* @param {String} environment - (optional) environment in workspace to validate against
|
|
||||||
* @param {String[]} acceptedPermissions - accepted permissions as part of the endpoint
|
|
||||||
*/
|
|
||||||
export const validateServiceTokenDataV3ClientForWorkspace = async ({
|
|
||||||
authData,
|
|
||||||
serviceTokenData,
|
|
||||||
workspaceId,
|
|
||||||
environment,
|
|
||||||
secretPath = "/",
|
|
||||||
requiredPermissions
|
|
||||||
}: {
|
|
||||||
authData: AuthData;
|
|
||||||
serviceTokenData: IServiceTokenDataV3;
|
|
||||||
workspaceId: Types.ObjectId;
|
|
||||||
environment?: string;
|
|
||||||
secretPath?: string;
|
|
||||||
requiredPermissions: Permission[];
|
|
||||||
}) => {
|
|
||||||
|
|
||||||
// validate ST V3 IP address
|
|
||||||
checkIPAgainstBlocklist({
|
|
||||||
ipAddress: authData.ipAddress,
|
|
||||||
trustedIps: serviceTokenData.trustedIps
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!serviceTokenData.workspace.equals(workspaceId)) {
|
|
||||||
// case: invalid workspaceId passed
|
|
||||||
throw UnauthorizedRequestError({
|
|
||||||
message: "Failed service token authorization for the given workspace"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (environment) {
|
|
||||||
const isValid = isValidScopeV3({
|
|
||||||
authPayload: serviceTokenData,
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
requiredPermissions
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!isValid) throw UnauthorizedRequestError({
|
|
||||||
message: "Failed service token authorization for the given workspace"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const RefreshTokenV3 = z.object({
|
export const RefreshTokenV3 = z.object({
|
||||||
body: z.object({
|
body: z.object({
|
||||||
@@ -71,20 +12,14 @@ export const CreateServiceTokenV3 = z.object({
|
|||||||
name: z.string().trim(),
|
name: z.string().trim(),
|
||||||
workspaceId: z.string().trim(),
|
workspaceId: z.string().trim(),
|
||||||
publicKey: z.string().trim(),
|
publicKey: z.string().trim(),
|
||||||
scopes: z
|
role: z.string().trim().min(1).default(MEMBER),
|
||||||
.object({
|
trustedIps: z // TODO: provide default
|
||||||
permissions: z.enum(["read", "write"]).array(),
|
|
||||||
environment: z.string().trim(),
|
|
||||||
secretPath: z.string().trim()
|
|
||||||
})
|
|
||||||
.array()
|
|
||||||
.min(1),
|
|
||||||
trustedIps: z
|
|
||||||
.object({
|
.object({
|
||||||
ipAddress: z.string().trim(),
|
ipAddress: z.string().trim(),
|
||||||
})
|
})
|
||||||
.array()
|
.array()
|
||||||
.min(1),
|
.min(1)
|
||||||
|
.default([{ ipAddress: "0.0.0.0/0" }]),
|
||||||
expiresIn: z.number().optional(),
|
expiresIn: z.number().optional(),
|
||||||
accessTokenTTL: z.number().int().min(1),
|
accessTokenTTL: z.number().int().min(1),
|
||||||
encryptedKey: z.string().trim(),
|
encryptedKey: z.string().trim(),
|
||||||
@@ -100,15 +35,7 @@ export const UpdateServiceTokenV3 = z.object({
|
|||||||
body: z.object({
|
body: z.object({
|
||||||
name: z.string().trim().optional(),
|
name: z.string().trim().optional(),
|
||||||
isActive: z.boolean().optional(),
|
isActive: z.boolean().optional(),
|
||||||
scopes: z
|
role: z.string().trim().min(1).optional(),
|
||||||
.object({
|
|
||||||
permissions: z.enum(["read", "write"]).array(),
|
|
||||||
environment: z.string().trim(),
|
|
||||||
secretPath: z.string().trim()
|
|
||||||
})
|
|
||||||
.array()
|
|
||||||
.min(1)
|
|
||||||
.optional(),
|
|
||||||
trustedIps: z
|
trustedIps: z
|
||||||
.object({
|
.object({
|
||||||
ipAddress: z.string().trim()
|
ipAddress: z.string().trim()
|
||||||
|
|||||||
@@ -4,17 +4,6 @@ import {
|
|||||||
UserAgentType
|
UserAgentType
|
||||||
} from "./enums";
|
} from "./enums";
|
||||||
|
|
||||||
enum Permission {
|
|
||||||
READ = "read",
|
|
||||||
READ_WRITE = "readWrite"
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Scope {
|
|
||||||
environment: string;
|
|
||||||
secretPath: string;
|
|
||||||
permission: Permission;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UserActorMetadata {
|
interface UserActorMetadata {
|
||||||
userId: string;
|
userId: string;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -211,7 +200,7 @@ interface CreateServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: string;
|
name: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
scopes: Array<Scope>;
|
role: string;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -221,7 +210,7 @@ interface UpdateServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name?: string;
|
name?: string;
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
scopes?: Array<Scope>;
|
role?: string;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,7 +220,7 @@ interface DeleteServiceTokenV3Event {
|
|||||||
metadata: {
|
metadata: {
|
||||||
name: string;
|
name: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
scopes: Array<Scope>;
|
role?: string;
|
||||||
expiresAt?: Date;
|
expiresAt?: Date;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,8 +85,8 @@ export const useUpdateServiceTokenV3 = () => {
|
|||||||
mutationFn: async ({
|
mutationFn: async ({
|
||||||
serviceTokenDataId,
|
serviceTokenDataId,
|
||||||
name,
|
name,
|
||||||
|
role,
|
||||||
isActive,
|
isActive,
|
||||||
scopes,
|
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn,
|
expiresIn,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
@@ -94,8 +94,8 @@ export const useUpdateServiceTokenV3 = () => {
|
|||||||
}) => {
|
}) => {
|
||||||
const { data: { serviceTokenData } } = await apiRequest.patch(`/api/v3/service-token/${serviceTokenDataId}`, {
|
const { data: { serviceTokenData } } = await apiRequest.patch(`/api/v3/service-token/${serviceTokenDataId}`, {
|
||||||
name,
|
name,
|
||||||
|
role,
|
||||||
isActive,
|
isActive,
|
||||||
scopes,
|
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn,
|
expiresIn,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { Permission } from "./enums";
|
|
||||||
|
|
||||||
export type ServiceTokenScope = {
|
export type ServiceTokenScope = {
|
||||||
environment: string;
|
environment: string;
|
||||||
secretPath: string;
|
secretPath: string;
|
||||||
@@ -38,12 +36,6 @@ export type DeleteServiceTokenRes = { serviceTokenData: ServiceToken };
|
|||||||
|
|
||||||
// --- v3
|
// --- v3
|
||||||
|
|
||||||
export type ServiceTokenV3Scope = {
|
|
||||||
permissions: Permission[];
|
|
||||||
environment: string;
|
|
||||||
secretPath: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ServiceTokenV3TrustedIp = {
|
export type ServiceTokenV3TrustedIp = {
|
||||||
_id: string;
|
_id: string;
|
||||||
ipAddress: string;
|
ipAddress: string;
|
||||||
@@ -54,13 +46,17 @@ export type ServiceTokenV3TrustedIp = {
|
|||||||
export type ServiceTokenDataV3 = {
|
export type ServiceTokenDataV3 = {
|
||||||
_id: string;
|
_id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
role: string;
|
||||||
|
customRole?: {
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
};
|
||||||
workspace: string;
|
workspace: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
refreshTokenLastUsed?: string;
|
refreshTokenLastUsed?: string;
|
||||||
accessTokenLastUsed?: string;
|
accessTokenLastUsed?: string;
|
||||||
refreshTokenUsageCount: number;
|
refreshTokenUsageCount: number;
|
||||||
accessTokenUsageCount: number;
|
accessTokenUsageCount: number;
|
||||||
scopes: ServiceTokenV3Scope[];
|
|
||||||
trustedIps: ServiceTokenV3TrustedIp[];
|
trustedIps: ServiceTokenV3TrustedIp[];
|
||||||
expiresAt?: string;
|
expiresAt?: string;
|
||||||
accessTokenTTL: number;
|
accessTokenTTL: number;
|
||||||
@@ -71,9 +67,9 @@ export type ServiceTokenDataV3 = {
|
|||||||
|
|
||||||
export type CreateServiceTokenDataV3DTO = {
|
export type CreateServiceTokenDataV3DTO = {
|
||||||
name: string;
|
name: string;
|
||||||
|
role?: string;
|
||||||
workspaceId: string;
|
workspaceId: string;
|
||||||
publicKey: string;
|
publicKey: string;
|
||||||
scopes: ServiceTokenV3Scope[];
|
|
||||||
trustedIps: {
|
trustedIps: {
|
||||||
ipAddress: string;
|
ipAddress: string;
|
||||||
}[];
|
}[];
|
||||||
@@ -93,7 +89,7 @@ export type UpdateServiceTokenDataV3DTO = {
|
|||||||
serviceTokenDataId: string;
|
serviceTokenDataId: string;
|
||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
name?: string;
|
name?: string;
|
||||||
scopes?: ServiceTokenV3Scope[];
|
role?: string;
|
||||||
trustedIps?: {
|
trustedIps?: {
|
||||||
ipAddress: string;
|
ipAddress: string;
|
||||||
}[];
|
}[];
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ export {
|
|||||||
useDeleteWsEnvironment,
|
useDeleteWsEnvironment,
|
||||||
useGetUserWorkspaceMemberships,
|
useGetUserWorkspaceMemberships,
|
||||||
useGetUserWorkspaces,
|
useGetUserWorkspaces,
|
||||||
useGetUserWsEnvironments,
|
|
||||||
useGetWorkspaceAuthorizations,
|
useGetWorkspaceAuthorizations,
|
||||||
useGetWorkspaceById,
|
useGetWorkspaceById,
|
||||||
useGetWorkspaceIndexStatus,
|
useGetWorkspaceIndexStatus,
|
||||||
|
|||||||
@@ -12,14 +12,12 @@ import {
|
|||||||
CreateWorkspaceDTO,
|
CreateWorkspaceDTO,
|
||||||
DeleteEnvironmentDTO,
|
DeleteEnvironmentDTO,
|
||||||
DeleteWorkspaceDTO,
|
DeleteWorkspaceDTO,
|
||||||
GetWsEnvironmentDTO,
|
|
||||||
NameWorkspaceSecretsDTO,
|
NameWorkspaceSecretsDTO,
|
||||||
RenameWorkspaceDTO,
|
RenameWorkspaceDTO,
|
||||||
ReorderEnvironmentsDTO,
|
ReorderEnvironmentsDTO,
|
||||||
ToggleAutoCapitalizationDTO,
|
ToggleAutoCapitalizationDTO,
|
||||||
UpdateEnvironmentDTO,
|
UpdateEnvironmentDTO,
|
||||||
Workspace,
|
Workspace
|
||||||
WorkspaceEnv
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const workspaceKeys = {
|
export const workspaceKeys = {
|
||||||
@@ -31,7 +29,6 @@ export const workspaceKeys = {
|
|||||||
getWorkspaceAuthorization: (workspaceId: string) => [{ workspaceId }, "workspace-authorizations"],
|
getWorkspaceAuthorization: (workspaceId: string) => [{ workspaceId }, "workspace-authorizations"],
|
||||||
getWorkspaceIntegrations: (workspaceId: string) => [{ workspaceId }, "workspace-integrations"],
|
getWorkspaceIntegrations: (workspaceId: string) => [{ workspaceId }, "workspace-integrations"],
|
||||||
getAllUserWorkspace: ["workspaces"] as const,
|
getAllUserWorkspace: ["workspaces"] as const,
|
||||||
getUserWsEnvironments: (workspaceId: string) => ["workspace-env", { workspaceId }] as const,
|
|
||||||
getWorkspaceAuditLogs: (workspaceId: string) => [{ workspaceId }] as const,
|
getWorkspaceAuditLogs: (workspaceId: string) => [{ workspaceId }] as const,
|
||||||
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }] as const,
|
getWorkspaceUsers: (workspaceId: string) => [{ workspaceId }] as const,
|
||||||
getWorkspaceServiceTokenDataV3: (workspaceId: string) =>
|
getWorkspaceServiceTokenDataV3: (workspaceId: string) =>
|
||||||
@@ -103,21 +100,6 @@ const fetchUserWorkspaceMemberships = async (orgId: string) => {
|
|||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchUserWsEnvironments = async (workspaceId: string) => {
|
|
||||||
const { data } = await apiRequest.get<{ accessibleEnvironments: WorkspaceEnv[] }>(
|
|
||||||
`/api/v2/workspace/${workspaceId}/environments`
|
|
||||||
);
|
|
||||||
return data.accessibleEnvironments;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const useGetUserWsEnvironments = ({ workspaceId, onSuccess }: GetWsEnvironmentDTO) =>
|
|
||||||
useQuery({
|
|
||||||
enabled: Boolean(workspaceId),
|
|
||||||
onSuccess,
|
|
||||||
queryKey: workspaceKeys.getUserWsEnvironments(workspaceId),
|
|
||||||
queryFn: () => fetchUserWsEnvironments(workspaceId)
|
|
||||||
});
|
|
||||||
|
|
||||||
// to get all userids in an org with the workspace they are part of
|
// to get all userids in an org with the workspace they are part of
|
||||||
export const useGetUserWorkspaceMemberships = (orgId: string) =>
|
export const useGetUserWorkspaceMemberships = (orgId: string) =>
|
||||||
useQuery({
|
useQuery({
|
||||||
|
|||||||
@@ -30,11 +30,6 @@ export type CreateWorkspaceDTO = {
|
|||||||
organizationId: string;
|
organizationId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type GetWsEnvironmentDTO = {
|
|
||||||
workspaceId: string;
|
|
||||||
onSuccess?: (data: WorkspaceEnv[]) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type RenameWorkspaceDTO = { workspaceID: string; newWorkspaceName: string };
|
export type RenameWorkspaceDTO = { workspaceID: string; newWorkspaceName: string };
|
||||||
export type ToggleAutoCapitalizationDTO = { workspaceID: string; state: boolean };
|
export type ToggleAutoCapitalizationDTO = { workspaceID: string; state: boolean };
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
|
|
||||||
import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
|
import { Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
|
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
|
||||||
import { withProjectPermission } from "@app/hoc";
|
import { withProjectPermission } from "@app/hoc";
|
||||||
|
|
||||||
import { MemberListTab } from "./components/MemberListTab";
|
import { MemberListTab } from "./components/MemberListTab";
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ export const MemberListTab = () => {
|
|||||||
orgId,
|
orgId,
|
||||||
workspaceId
|
workspaceId
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: wsKey } = useGetUserWsKey(workspaceId);
|
const { data: wsKey } = useGetUserWsKey(workspaceId);
|
||||||
const { data: members, isLoading: isMembersLoading } = useGetWorkspaceUsers(workspaceId);
|
const { data: members, isLoading: isMembersLoading } = useGetWorkspaceUsers(workspaceId);
|
||||||
const { data: orgUsers } = useGetOrgUsers(orgId);
|
const { data: orgUsers } = useGetOrgUsers(orgId);
|
||||||
|
|||||||
+2
-2
@@ -2,7 +2,7 @@ import { motion } from "framer-motion";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
ServiceTokenSection,
|
ServiceTokenSection,
|
||||||
// ServiceTokenV3Section
|
ServiceTokenV3Section
|
||||||
} from "./components";
|
} from "./components";
|
||||||
|
|
||||||
export const ServiceTokenTab = () => {
|
export const ServiceTokenTab = () => {
|
||||||
@@ -14,7 +14,7 @@ export const ServiceTokenTab = () => {
|
|||||||
animate={{ opacity: 1, translateX: 0 }}
|
animate={{ opacity: 1, translateX: 0 }}
|
||||||
exit={{ opacity: 0, translateX: 30 }}
|
exit={{ opacity: 0, translateX: 30 }}
|
||||||
>
|
>
|
||||||
{/* <ServiceTokenV3Section /> */}
|
<ServiceTokenV3Section />
|
||||||
<ServiceTokenSection />
|
<ServiceTokenSection />
|
||||||
</motion.div>
|
</motion.div>
|
||||||
);
|
);
|
||||||
|
|||||||
+56
-174
@@ -29,22 +29,17 @@ import {
|
|||||||
Tabs,
|
Tabs,
|
||||||
UpgradePlanModal} from "@app/components/v2";
|
UpgradePlanModal} from "@app/components/v2";
|
||||||
import {
|
import {
|
||||||
|
useOrganization,
|
||||||
useSubscription,
|
useSubscription,
|
||||||
useWorkspace
|
useWorkspace
|
||||||
} from "@app/context";
|
} from "@app/context";
|
||||||
import { useToggle } from "@app/hooks";
|
import { useToggle } from "@app/hooks";
|
||||||
import {
|
import {
|
||||||
useCreateServiceTokenV3,
|
useCreateServiceTokenV3,
|
||||||
|
useGetRoles,
|
||||||
useGetUserWsKey,
|
useGetUserWsKey,
|
||||||
useUpdateServiceTokenV3
|
useUpdateServiceTokenV3} from "@app/hooks/api";
|
||||||
} from "@app/hooks/api";
|
import { ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types";
|
||||||
import {
|
|
||||||
Permission
|
|
||||||
} from "@app/hooks/api/serviceTokens/enums";
|
|
||||||
import {
|
|
||||||
ServiceTokenV3Scope,
|
|
||||||
ServiceTokenV3TrustedIp
|
|
||||||
} from "@app/hooks/api/serviceTokens/types";
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||||
|
|
||||||
enum TabSections {
|
enum TabSections {
|
||||||
@@ -61,13 +56,6 @@ const expirations = [
|
|||||||
{ label: "12 months", value: "31104000" }
|
{ label: "12 months", value: "31104000" }
|
||||||
];
|
];
|
||||||
|
|
||||||
const permissionsMap: {
|
|
||||||
[key: string]: Permission[]
|
|
||||||
} = {
|
|
||||||
"read": [Permission.READ],
|
|
||||||
"readWrite": [Permission.READ, Permission.WRITE],
|
|
||||||
}
|
|
||||||
|
|
||||||
const schema = yup.object({
|
const schema = yup.object({
|
||||||
name: yup.string().required("ST V3 name is required"),
|
name: yup.string().required("ST V3 name is required"),
|
||||||
expiresIn: yup.string(),
|
expiresIn: yup.string(),
|
||||||
@@ -82,24 +70,7 @@ const schema = yup.object({
|
|||||||
return !Number.isNaN(num) && num > 0 && String(num) === value;
|
return !Number.isNaN(num) && num > 0 && String(num) === value;
|
||||||
})
|
})
|
||||||
.required("Access Token TTL is required"),
|
.required("Access Token TTL is required"),
|
||||||
scopes: yup
|
role: yup.string().required("ST V3 role is required"),
|
||||||
.array(
|
|
||||||
yup.object({
|
|
||||||
permission: yup.string().oneOf(Object.keys(permissionsMap), "Invalid permission").required().label("Permission"),
|
|
||||||
environment: yup.string().max(50).required().label("Environment"),
|
|
||||||
secretPath: yup
|
|
||||||
.string()
|
|
||||||
.required()
|
|
||||||
.default("/")
|
|
||||||
.label("Secret Path")
|
|
||||||
.transform((val) =>
|
|
||||||
typeof val === "string" && val.at(-1) === "/" && val.length > 1 ? val.slice(0, -1) : val
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required()
|
|
||||||
.label("Scope"),
|
|
||||||
trustedIps: yup
|
trustedIps: yup
|
||||||
.array(
|
.array(
|
||||||
yup.object({
|
yup.object({
|
||||||
@@ -129,9 +100,18 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
const [isServiceTokenJSONCopied, setIsServiceTokenJSONCopied] = useToggle(false);
|
const [isServiceTokenJSONCopied, setIsServiceTokenJSONCopied] = useToggle(false);
|
||||||
|
|
||||||
const { subscription } = useSubscription();
|
const { subscription } = useSubscription();
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
const { currentWorkspace } = useWorkspace();
|
const { currentWorkspace } = useWorkspace();
|
||||||
|
|
||||||
const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
|
const orgId = currentOrg?._id || "";
|
||||||
|
const workspaceId = currentWorkspace?._id || "";
|
||||||
|
|
||||||
|
const { data: roles } = useGetRoles({
|
||||||
|
orgId,
|
||||||
|
workspaceId
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: latestFileKey } = useGetUserWsKey(workspaceId);
|
||||||
const { mutateAsync: createMutateAsync } = useCreateServiceTokenV3();
|
const { mutateAsync: createMutateAsync } = useCreateServiceTokenV3();
|
||||||
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
||||||
const { createNotification } = useNotificationContext();
|
const { createNotification } = useNotificationContext();
|
||||||
@@ -145,11 +125,6 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
defaultValues: {
|
defaultValues: {
|
||||||
name: "",
|
name: "",
|
||||||
accessTokenTTL: "7200",
|
accessTokenTTL: "7200",
|
||||||
scopes: [{
|
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug,
|
|
||||||
secretPath: "/",
|
|
||||||
}],
|
|
||||||
trustedIps: [{
|
trustedIps: [{
|
||||||
ipAddress: "0.0.0.0/0"
|
ipAddress: "0.0.0.0/0"
|
||||||
}]
|
}]
|
||||||
@@ -175,31 +150,22 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
||||||
serviceTokenDataId: string;
|
serviceTokenDataId: string;
|
||||||
name: string;
|
name: string;
|
||||||
scopes: ServiceTokenV3Scope[];
|
role: string;
|
||||||
|
customRole: {
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
};
|
||||||
trustedIps: ServiceTokenV3TrustedIp[];
|
trustedIps: ServiceTokenV3TrustedIp[];
|
||||||
accessTokenTTL: number;
|
accessTokenTTL: number;
|
||||||
isRefreshTokenRotationEnabled: boolean;
|
isRefreshTokenRotationEnabled: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (!roles?.length) return;
|
||||||
|
|
||||||
if (serviceTokenData) {
|
if (serviceTokenData) {
|
||||||
reset({
|
reset({
|
||||||
name: serviceTokenData.name,
|
name: serviceTokenData.name,
|
||||||
scopes: serviceTokenData.scopes.map(({
|
role: serviceTokenData?.customRole?.slug ?? serviceTokenData.role,
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
permissions
|
|
||||||
}: ServiceTokenV3Scope) => {
|
|
||||||
let permission = "read";
|
|
||||||
if (permissions.includes(Permission.WRITE)) {
|
|
||||||
permission = "readWrite";
|
|
||||||
}
|
|
||||||
|
|
||||||
return ({
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
permission
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
trustedIps: serviceTokenData.trustedIps.map(({
|
trustedIps: serviceTokenData.trustedIps.map(({
|
||||||
ipAddress,
|
ipAddress,
|
||||||
prefix
|
prefix
|
||||||
@@ -215,26 +181,21 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
reset({
|
reset({
|
||||||
name: "",
|
name: "",
|
||||||
accessTokenTTL: "7200",
|
accessTokenTTL: "7200",
|
||||||
scopes: [{
|
role: roles[0].slug,
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug,
|
|
||||||
secretPath: "/",
|
|
||||||
}],
|
|
||||||
trustedIps: [{
|
trustedIps: [{
|
||||||
ipAddress: "0.0.0.0/0"
|
ipAddress: "0.0.0.0/0"
|
||||||
}]
|
}]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [popUp?.serviceTokenV3?.data]);
|
}, [popUp?.serviceTokenV3?.data, roles]);
|
||||||
|
|
||||||
const { fields: tokenScopes, append, remove } = useFieldArray({ control, name: "scopes" });
|
|
||||||
const { fields: tokenTrustedIps, append: appendTrustedIp, remove: removeTrustedIp } = useFieldArray({ control, name: "trustedIps" });
|
const { fields: tokenTrustedIps, append: appendTrustedIp, remove: removeTrustedIp } = useFieldArray({ control, name: "trustedIps" });
|
||||||
|
|
||||||
const onFormSubmit = async ({
|
const onFormSubmit = async ({
|
||||||
name,
|
name,
|
||||||
expiresIn,
|
expiresIn,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
scopes,
|
role,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
isRefreshTokenRotationEnabled
|
isRefreshTokenRotationEnabled
|
||||||
}: FormData) => {
|
}: FormData) => {
|
||||||
@@ -242,25 +203,16 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
||||||
serviceTokenDataId: string;
|
serviceTokenDataId: string;
|
||||||
name: string;
|
name: string;
|
||||||
scopes: any;
|
role: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// convert read/readWrite permission => ["read", "write"] format
|
|
||||||
const reformattedScopes = scopes.map((scope) => {
|
|
||||||
return ({
|
|
||||||
environment: scope.environment,
|
|
||||||
secretPath: scope.secretPath,
|
|
||||||
permissions: permissionsMap[scope.permission]
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
if (serviceTokenData) {
|
if (serviceTokenData) {
|
||||||
// update
|
// update
|
||||||
|
|
||||||
await updateMutateAsync({
|
await updateMutateAsync({
|
||||||
serviceTokenDataId: serviceTokenData.serviceTokenDataId,
|
serviceTokenDataId: serviceTokenData.serviceTokenDataId,
|
||||||
name,
|
name,
|
||||||
scopes: reformattedScopes,
|
role,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
||||||
accessTokenTTL: Number(accessTokenTTL),
|
accessTokenTTL: Number(accessTokenTTL),
|
||||||
@@ -270,7 +222,7 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
handlePopUpToggle("serviceTokenV3", false);
|
handlePopUpToggle("serviceTokenV3", false);
|
||||||
} else {
|
} else {
|
||||||
// create
|
// create
|
||||||
if (!currentWorkspace?._id) return;
|
if (!workspaceId) return;
|
||||||
if (!latestFileKey) return;
|
if (!latestFileKey) return;
|
||||||
|
|
||||||
const pair = nacl.box.keyPair();
|
const pair = nacl.box.keyPair();
|
||||||
@@ -294,9 +246,9 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
|
|
||||||
const { refreshToken } = await createMutateAsync({
|
const { refreshToken } = await createMutateAsync({
|
||||||
name,
|
name,
|
||||||
workspaceId: currentWorkspace._id,
|
role,
|
||||||
|
workspaceId,
|
||||||
publicKey,
|
publicKey,
|
||||||
scopes: reformattedScopes,
|
|
||||||
trustedIps,
|
trustedIps,
|
||||||
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
||||||
accessTokenTTL: Number(accessTokenTTL),
|
accessTokenTTL: Number(accessTokenTTL),
|
||||||
@@ -385,102 +337,32 @@ export const AddServiceTokenV3Modal = ({
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
{tokenScopes.map(({ id }, index) => (
|
<Controller
|
||||||
<div className="flex items-end space-x-2 mb-3" key={id}>
|
control={control}
|
||||||
<Controller
|
name="role"
|
||||||
control={control}
|
defaultValue=""
|
||||||
name={`scopes.${index}.permission`}
|
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
<FormControl
|
||||||
<FormControl
|
label={`${popUp?.serviceTokenV3?.data ? "Update" : ""} Role`}
|
||||||
className="mb-0"
|
errorText={error?.message}
|
||||||
label={index === 0 ? "Permission" : undefined}
|
isError={Boolean(error)}
|
||||||
errorText={error?.message}
|
className="mt-4"
|
||||||
isError={Boolean(error)}
|
>
|
||||||
>
|
<Select
|
||||||
<Select
|
defaultValue={field.value}
|
||||||
defaultValue={field.value}
|
{...field}
|
||||||
{...field}
|
onValueChange={(e) => onChange(e)}
|
||||||
onValueChange={(e) => onChange(e)}
|
className="w-full"
|
||||||
className="w-36"
|
>
|
||||||
>
|
{(roles || []).map(({ name, slug }) => (
|
||||||
<SelectItem value="read" key="st-v3-read">
|
<SelectItem value={slug} key={`st-role-${slug}`}>
|
||||||
Read
|
|
||||||
</SelectItem>
|
|
||||||
<SelectItem value="readWrite" key="st-v3-write">
|
|
||||||
Read & Write
|
|
||||||
</SelectItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.environment`}
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0"
|
|
||||||
label={index === 0 ? "Environment" : undefined}
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-36"
|
|
||||||
>
|
|
||||||
{currentWorkspace?.environments.map(({ name, slug }) => (
|
|
||||||
<SelectItem value={slug} key={slug}>
|
|
||||||
{name}
|
{name}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.secretPath`}
|
|
||||||
defaultValue="/"
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0 flex-grow"
|
|
||||||
label={index === 0 ? "Secrets Path" : undefined}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input {...field} placeholder="can be /, /nested/**, /**/deep" />
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => remove(index)}
|
|
||||||
size="lg"
|
|
||||||
colorSchema="danger"
|
|
||||||
variant="plain"
|
|
||||||
ariaLabel="update"
|
|
||||||
className="p-3"
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faXmark} />
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="my-4 ml-1">
|
|
||||||
<Button
|
|
||||||
variant="outline_bg"
|
|
||||||
onClick={() =>
|
|
||||||
append({
|
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug || "",
|
|
||||||
secretPath: "/"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
Add Scope
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<Controller
|
<Controller
|
||||||
control={control}
|
control={control}
|
||||||
name="expiresIn"
|
name="expiresIn"
|
||||||
|
|||||||
+13
-27
@@ -22,8 +22,7 @@ import {
|
|||||||
useGetWorkspaceServiceTokenDataV3,
|
useGetWorkspaceServiceTokenDataV3,
|
||||||
useUpdateServiceTokenV3
|
useUpdateServiceTokenV3
|
||||||
} from "@app/hooks/api";
|
} from "@app/hooks/api";
|
||||||
import { Permission } from "@app/hooks/api/serviceTokens/enums"
|
import { ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types"
|
||||||
import { ServiceTokenV3Scope, ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types"
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
import { UsePopUpState } from "@app/hooks/usePopUp";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -32,7 +31,11 @@ type Props = {
|
|||||||
data?: {
|
data?: {
|
||||||
serviceTokenDataId?: string;
|
serviceTokenDataId?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
scopes?: ServiceTokenV3Scope[];
|
role?: string;
|
||||||
|
customRole?: {
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
};
|
||||||
trustedIps?: ServiceTokenV3TrustedIp[];
|
trustedIps?: ServiceTokenV3TrustedIp[];
|
||||||
accessTokenTTL?: number;
|
accessTokenTTL?: number;
|
||||||
isRefreshTokenRotationEnabled?: boolean;
|
isRefreshTokenRotationEnabled?: boolean;
|
||||||
@@ -47,7 +50,7 @@ export const ServiceTokenV3Table = ({
|
|||||||
const { currentWorkspace } = useWorkspace();
|
const { currentWorkspace } = useWorkspace();
|
||||||
const { data, isLoading } = useGetWorkspaceServiceTokenDataV3(currentWorkspace?._id || "");
|
const { data, isLoading } = useGetWorkspaceServiceTokenDataV3(currentWorkspace?._id || "");
|
||||||
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
||||||
|
|
||||||
const handleToggleServiceTokenDataStatus = async ({
|
const handleToggleServiceTokenDataStatus = async ({
|
||||||
serviceTokenDataId,
|
serviceTokenDataId,
|
||||||
isActive
|
isActive
|
||||||
@@ -81,7 +84,7 @@ export const ServiceTokenV3Table = ({
|
|||||||
<Tr>
|
<Tr>
|
||||||
<Th>Name</Th>
|
<Th>Name</Th>
|
||||||
<Th>Status</Th>
|
<Th>Status</Th>
|
||||||
<Th>Scopes</Th>
|
<Th>Role</Th>
|
||||||
<Th>Trusted IPs</Th>
|
<Th>Trusted IPs</Th>
|
||||||
<Th>Access Token TTL</Th>
|
<Th>Access Token TTL</Th>
|
||||||
<Th>Created At</Th>
|
<Th>Created At</Th>
|
||||||
@@ -98,7 +101,8 @@ export const ServiceTokenV3Table = ({
|
|||||||
_id,
|
_id,
|
||||||
name,
|
name,
|
||||||
isActive,
|
isActive,
|
||||||
scopes,
|
role,
|
||||||
|
customRole,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
createdAt,
|
createdAt,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
@@ -128,26 +132,7 @@ export const ServiceTokenV3Table = ({
|
|||||||
)}
|
)}
|
||||||
</ProjectPermissionCan>
|
</ProjectPermissionCan>
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>{customRole?.slug ?? role}</Td>
|
||||||
{scopes.map((scope) => {
|
|
||||||
let permissionText = "read"
|
|
||||||
if (
|
|
||||||
scope.permissions.includes(Permission.WRITE) &&
|
|
||||||
scope.permissions.includes(Permission.READ)
|
|
||||||
) {
|
|
||||||
permissionText = "readWrite";
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<p key={`service-token-${_id}-scope-${scope.environment}-${scope.secretPath}`}>
|
|
||||||
<span className="font-bold">
|
|
||||||
{permissionText}
|
|
||||||
</span>
|
|
||||||
{` @${scope.environment} - ${scope.secretPath}`}
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Td>
|
|
||||||
<Td>
|
<Td>
|
||||||
{trustedIps.map(({
|
{trustedIps.map(({
|
||||||
_id: trustedIpId,
|
_id: trustedIpId,
|
||||||
@@ -175,7 +160,8 @@ export const ServiceTokenV3Table = ({
|
|||||||
handlePopUpOpen("serviceTokenV3", {
|
handlePopUpOpen("serviceTokenV3", {
|
||||||
serviceTokenDataId: _id,
|
serviceTokenDataId: _id,
|
||||||
name,
|
name,
|
||||||
scopes,
|
role,
|
||||||
|
customRole,
|
||||||
trustedIps,
|
trustedIps,
|
||||||
accessTokenTTL,
|
accessTokenTTL,
|
||||||
isRefreshTokenRotationEnabled
|
isRefreshTokenRotationEnabled
|
||||||
|
|||||||
-375
@@ -1,375 +0,0 @@
|
|||||||
import crypto from "crypto";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Controller, useFieldArray, useForm } from "react-hook-form";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { faCheck, faCopy, faPlus, faTrashCan } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
import { yupResolver } from "@hookform/resolvers/yup";
|
|
||||||
import * as yup from "yup";
|
|
||||||
|
|
||||||
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
|
|
||||||
import {
|
|
||||||
decryptAssymmetric,
|
|
||||||
encryptSymmetric
|
|
||||||
} from "@app/components/utilities/cryptography/crypto";
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
Checkbox,
|
|
||||||
FormControl,
|
|
||||||
IconButton,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
ModalClose,
|
|
||||||
ModalContent,
|
|
||||||
Select,
|
|
||||||
SelectItem
|
|
||||||
} from "@app/components/v2";
|
|
||||||
import { useWorkspace } from "@app/context";
|
|
||||||
import { useToggle } from "@app/hooks";
|
|
||||||
import { useCreateServiceToken, useGetUserWsKey } from "@app/hooks/api";
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
|
||||||
|
|
||||||
const apiTokenExpiry = [
|
|
||||||
{ label: "1 Day", value: 86400 },
|
|
||||||
{ label: "7 Days", value: 604800 },
|
|
||||||
{ label: "1 Month", value: 2592000 },
|
|
||||||
{ label: "6 months", value: 15552000 },
|
|
||||||
{ label: "12 months", value: 31104000 },
|
|
||||||
{ label: "Never", value: null }
|
|
||||||
];
|
|
||||||
|
|
||||||
const schema = yup.object({
|
|
||||||
name: yup.string().max(100).required().label("Service Token Name"),
|
|
||||||
scopes: yup
|
|
||||||
.array(
|
|
||||||
yup.object({
|
|
||||||
environment: yup.string().max(50).required().label("Environment"),
|
|
||||||
secretPath: yup
|
|
||||||
.string()
|
|
||||||
.required()
|
|
||||||
.default("/")
|
|
||||||
.label("Secret Path")
|
|
||||||
.transform((val) =>
|
|
||||||
typeof val === "string" && val.at(-1) === "/" && val.length > 1 ? val.slice(0, -1) : val
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required()
|
|
||||||
.label("Scope"),
|
|
||||||
expiresIn: yup.string().optional().label("Service Token Expiration"),
|
|
||||||
permissions: yup
|
|
||||||
.object()
|
|
||||||
.shape({
|
|
||||||
read: yup.boolean().required(),
|
|
||||||
write: yup.boolean().required()
|
|
||||||
})
|
|
||||||
.defined()
|
|
||||||
.required()
|
|
||||||
});
|
|
||||||
|
|
||||||
export type FormData = yup.InferType<typeof schema>;
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
popUp: UsePopUpState<["createAPIToken"]>;
|
|
||||||
handlePopUpToggle: (popUpName: keyof UsePopUpState<["createAPIToken"]>, state?: boolean) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const { createNotification } = useNotificationContext();
|
|
||||||
const { currentWorkspace } = useWorkspace();
|
|
||||||
const {
|
|
||||||
control,
|
|
||||||
reset,
|
|
||||||
handleSubmit,
|
|
||||||
formState: { isSubmitting }
|
|
||||||
} = useForm<FormData>({
|
|
||||||
resolver: yupResolver(schema),
|
|
||||||
defaultValues: {
|
|
||||||
scopes: [{
|
|
||||||
secretPath: "/",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const { fields: tokenScopes, append, remove } = useFieldArray({ control, name: "scopes" });
|
|
||||||
|
|
||||||
const [newToken, setToken] = useState("");
|
|
||||||
const [isTokenCopied, setIsTokenCopied] = useToggle(false);
|
|
||||||
|
|
||||||
const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
|
|
||||||
const createServiceToken = useCreateServiceToken();
|
|
||||||
const hasServiceToken = Boolean(newToken);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let timer: NodeJS.Timeout;
|
|
||||||
if (isTokenCopied) {
|
|
||||||
timer = setTimeout(() => setIsTokenCopied.off(), 2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [isTokenCopied]);
|
|
||||||
|
|
||||||
const copyTokenToClipboard = () => {
|
|
||||||
navigator.clipboard.writeText(newToken);
|
|
||||||
setIsTokenCopied.on();
|
|
||||||
};
|
|
||||||
|
|
||||||
const onFormSubmit = async ({ name, scopes, expiresIn, permissions }: FormData) => {
|
|
||||||
try {
|
|
||||||
if (!currentWorkspace?._id) return;
|
|
||||||
if (!latestFileKey) return;
|
|
||||||
|
|
||||||
const key = decryptAssymmetric({
|
|
||||||
ciphertext: latestFileKey.encryptedKey,
|
|
||||||
nonce: latestFileKey.nonce,
|
|
||||||
publicKey: latestFileKey.sender.publicKey,
|
|
||||||
privateKey: localStorage.getItem("PRIVATE_KEY") as string
|
|
||||||
});
|
|
||||||
|
|
||||||
const randomBytes = crypto.randomBytes(16).toString("hex");
|
|
||||||
|
|
||||||
const { ciphertext, iv, tag } = encryptSymmetric({
|
|
||||||
plaintext: key,
|
|
||||||
key: randomBytes
|
|
||||||
});
|
|
||||||
|
|
||||||
const { serviceToken } = await createServiceToken.mutateAsync({
|
|
||||||
encryptedKey: ciphertext,
|
|
||||||
iv,
|
|
||||||
tag,
|
|
||||||
scopes,
|
|
||||||
expiresIn: Number(expiresIn),
|
|
||||||
name,
|
|
||||||
workspaceId: currentWorkspace._id,
|
|
||||||
randomBytes,
|
|
||||||
permissions: Object.entries(permissions)
|
|
||||||
.filter(([, permissionsValue]) => permissionsValue)
|
|
||||||
.map(([permissionsKey]) => permissionsKey)
|
|
||||||
});
|
|
||||||
|
|
||||||
setToken(serviceToken);
|
|
||||||
createNotification({
|
|
||||||
text: "Successfully created a service token",
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
createNotification({
|
|
||||||
text: "Failed to create a service token",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={popUp?.createAPIToken?.isOpen}
|
|
||||||
onOpenChange={(open) => {
|
|
||||||
handlePopUpToggle("createAPIToken", open);
|
|
||||||
reset();
|
|
||||||
setToken("");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ModalContent
|
|
||||||
title={
|
|
||||||
t("section.token.add-dialog.title", {
|
|
||||||
target: currentWorkspace?.name
|
|
||||||
}) as string
|
|
||||||
}
|
|
||||||
subTitle={t("section.token.add-dialog.description") as string}
|
|
||||||
>
|
|
||||||
{!hasServiceToken ? (
|
|
||||||
<form onSubmit={handleSubmit(onFormSubmit)}>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name="name"
|
|
||||||
defaultValue=""
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
label={t("section.token.add-dialog.name")}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input {...field} placeholder="Type your token name" />
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
{tokenScopes.map(({ id }, index) => (
|
|
||||||
<div className="mb-3 flex items-end space-x-2" key={id}>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.environment`}
|
|
||||||
defaultValue={currentWorkspace?.environments?.[0]?.slug}
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0"
|
|
||||||
label={index === 0 ? "Environment" : undefined}
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{currentWorkspace?.environments.map(({ name, slug }) => (
|
|
||||||
<SelectItem value={slug} key={slug}>
|
|
||||||
{name}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.secretPath`}
|
|
||||||
defaultValue="/"
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0 flex-grow"
|
|
||||||
label={index === 0 ? "Secrets Path" : undefined}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input {...field} placeholder="can be /, /nested/**, /**/deep" />
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
className="p-3"
|
|
||||||
ariaLabel="remove"
|
|
||||||
colorSchema="danger"
|
|
||||||
onClick={() => remove(index)}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faTrashCan} size="sm" />
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="my-4 ml-1">
|
|
||||||
<Button
|
|
||||||
variant="outline_bg"
|
|
||||||
onClick={() =>
|
|
||||||
append({
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug || "",
|
|
||||||
secretPath: ""
|
|
||||||
})
|
|
||||||
}
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
Add Scope
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name="expiresIn"
|
|
||||||
defaultValue={String(apiTokenExpiry?.[0]?.value)}
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl label="Expiration" errorText={error?.message} isError={Boolean(error)}>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{apiTokenExpiry.map(({ label, value }) => (
|
|
||||||
<SelectItem value={String(value || "")} key={label}>
|
|
||||||
{label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name="permissions"
|
|
||||||
defaultValue={{
|
|
||||||
read: true,
|
|
||||||
write: false
|
|
||||||
}}
|
|
||||||
render={({ field: { onChange, value }, fieldState: { error } }) => {
|
|
||||||
const options = [
|
|
||||||
{
|
|
||||||
label: "Read (default)",
|
|
||||||
value: "read"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Write (optional)",
|
|
||||||
value: "write"
|
|
||||||
}
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<FormControl
|
|
||||||
label="Permissions"
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
>
|
|
||||||
<>
|
|
||||||
{options.map(({ label, value: optionValue }) => {
|
|
||||||
return (
|
|
||||||
<Checkbox
|
|
||||||
id={value[optionValue]}
|
|
||||||
key={optionValue}
|
|
||||||
className="data-[state=checked]:bg-primary"
|
|
||||||
isChecked={value[optionValue]}
|
|
||||||
isDisabled={optionValue === "read"}
|
|
||||||
onCheckedChange={(state) => {
|
|
||||||
onChange({
|
|
||||||
...value,
|
|
||||||
[optionValue]: state
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</Checkbox>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</>
|
|
||||||
</FormControl>
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="mt-8 flex items-center">
|
|
||||||
<Button
|
|
||||||
className="mr-4"
|
|
||||||
type="submit"
|
|
||||||
isDisabled={isSubmitting}
|
|
||||||
isLoading={isSubmitting}
|
|
||||||
>
|
|
||||||
Create
|
|
||||||
</Button>
|
|
||||||
<ModalClose asChild>
|
|
||||||
<Button variant="plain" colorSchema="secondary">
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</ModalClose>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<div className="mt-2 mb-3 mr-2 flex items-center justify-end rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
|
|
||||||
<p className="mr-4 break-all">{newToken}</p>
|
|
||||||
<IconButton
|
|
||||||
ariaLabel="copy icon"
|
|
||||||
colorSchema="secondary"
|
|
||||||
className="group relative"
|
|
||||||
onClick={copyTokenToClipboard}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={isTokenCopied ? faCheck : faCopy} />
|
|
||||||
<span className="absolute -left-8 -top-20 hidden w-28 translate-y-full rounded-md bg-bunker-800 py-2 pl-3 text-center text-sm text-gray-400 group-hover:flex group-hover:animate-fadeIn">
|
|
||||||
{t("common.click-to-copy")}
|
|
||||||
</span>
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ModalContent>
|
|
||||||
</Modal>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
-90
@@ -1,90 +0,0 @@
|
|||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { faPlus } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
|
|
||||||
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
|
|
||||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
|
||||||
import { Button, DeleteActionModal } from "@app/components/v2";
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
|
|
||||||
import { withProjectPermission } from "@app/hoc";
|
|
||||||
import { usePopUp } from "@app/hooks";
|
|
||||||
import { useDeleteServiceToken } from "@app/hooks/api";
|
|
||||||
|
|
||||||
import { AddServiceTokenModal } from "./AddServiceTokenModal";
|
|
||||||
import { ServiceTokenTable } from "./ServiceTokenTable";
|
|
||||||
|
|
||||||
type DeleteModalData = { name: string; id: string };
|
|
||||||
|
|
||||||
export const ServiceTokenSection = withProjectPermission(
|
|
||||||
() => {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const { createNotification } = useNotificationContext();
|
|
||||||
const deleteServiceToken = useDeleteServiceToken();
|
|
||||||
|
|
||||||
const { popUp, handlePopUpToggle, handlePopUpClose, handlePopUpOpen } = usePopUp([
|
|
||||||
"createAPIToken",
|
|
||||||
"deleteAPITokenConfirmation"
|
|
||||||
] as const);
|
|
||||||
|
|
||||||
const onDeleteApproved = async () => {
|
|
||||||
try {
|
|
||||||
deleteServiceToken.mutateAsync(
|
|
||||||
(popUp?.deleteAPITokenConfirmation?.data as DeleteModalData)?.id
|
|
||||||
);
|
|
||||||
createNotification({
|
|
||||||
text: "Successfully deleted service token",
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
|
|
||||||
handlePopUpClose("deleteAPITokenConfirmation");
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
createNotification({
|
|
||||||
text: "Failed to delete service token",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
|
|
||||||
<div className="mb-2 flex justify-between">
|
|
||||||
<p className="text-xl font-semibold text-mineshaft-100">
|
|
||||||
Service Tokens
|
|
||||||
</p>
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Create}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<Button
|
|
||||||
colorSchema="secondary"
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
onClick={() => {
|
|
||||||
handlePopUpOpen("createAPIToken");
|
|
||||||
}}
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
Create token
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
</div>
|
|
||||||
<p className="mb-8 text-gray-400">{t("section.token.service-tokens-description")}</p>
|
|
||||||
<ServiceTokenTable handlePopUpOpen={handlePopUpOpen} />
|
|
||||||
<AddServiceTokenModal popUp={popUp} handlePopUpToggle={handlePopUpToggle} />
|
|
||||||
<DeleteActionModal
|
|
||||||
isOpen={popUp.deleteAPITokenConfirmation.isOpen}
|
|
||||||
title={`Delete ${
|
|
||||||
(popUp?.deleteAPITokenConfirmation?.data as DeleteModalData)?.name || " "
|
|
||||||
} service token?`}
|
|
||||||
onChange={(isOpen) => handlePopUpToggle("deleteAPITokenConfirmation", isOpen)}
|
|
||||||
deleteKey={(popUp?.deleteAPITokenConfirmation?.data as DeleteModalData)?.name}
|
|
||||||
onClose={() => handlePopUpClose("deleteAPITokenConfirmation")}
|
|
||||||
onDeleteApproved={onDeleteApproved}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
{ action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.ServiceTokens }
|
|
||||||
);
|
|
||||||
-108
@@ -1,108 +0,0 @@
|
|||||||
import { faFolder, faKey, faTrashCan } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
|
|
||||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
|
||||||
import {
|
|
||||||
EmptyState,
|
|
||||||
IconButton,
|
|
||||||
Table,
|
|
||||||
TableContainer,
|
|
||||||
TableSkeleton,
|
|
||||||
TBody,
|
|
||||||
Td,
|
|
||||||
Th,
|
|
||||||
THead,
|
|
||||||
Tr
|
|
||||||
} from "@app/components/v2";
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
|
|
||||||
import { useGetUserWsServiceTokens } from "@app/hooks/api";
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
handlePopUpOpen: (
|
|
||||||
popUpName: keyof UsePopUpState<["deleteAPITokenConfirmation"]>,
|
|
||||||
{
|
|
||||||
name,
|
|
||||||
id
|
|
||||||
}: {
|
|
||||||
name: string;
|
|
||||||
id: string;
|
|
||||||
}
|
|
||||||
) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ServiceTokenTable = ({ handlePopUpOpen }: Props) => {
|
|
||||||
const { currentWorkspace } = useWorkspace();
|
|
||||||
const { data, isLoading } = useGetUserWsServiceTokens({
|
|
||||||
workspaceID: currentWorkspace?._id || ""
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<TableContainer>
|
|
||||||
<Table>
|
|
||||||
<THead>
|
|
||||||
<Tr>
|
|
||||||
<Th>Token Name</Th>
|
|
||||||
<Th>Environment - Secret Path</Th>
|
|
||||||
<Th>Valid Until</Th>
|
|
||||||
<Th aria-label="button" />
|
|
||||||
</Tr>
|
|
||||||
</THead>
|
|
||||||
<TBody>
|
|
||||||
{isLoading && <TableSkeleton columns={4} innerKey="project-service-tokens" />}
|
|
||||||
{!isLoading &&
|
|
||||||
data &&
|
|
||||||
data.map((row) => (
|
|
||||||
<Tr key={row._id}>
|
|
||||||
<Td>{row.name}</Td>
|
|
||||||
<Td>
|
|
||||||
<div className="mb-2 flex flex-col flex-wrap space-y-1">
|
|
||||||
{row?.scopes.map(({ secretPath, environment }) => (
|
|
||||||
<div
|
|
||||||
key={`${row._id}-${environment}-${secretPath}`}
|
|
||||||
className="inline-flex items-center space-x-1 rounded-md border border-mineshaft-600 p-1 px-2"
|
|
||||||
>
|
|
||||||
<div className="mr-2 border-r border-mineshaft-600 pr-2">{environment}</div>
|
|
||||||
<FontAwesomeIcon icon={faFolder} size="sm" />
|
|
||||||
<span className="pl-2">{secretPath}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</Td>
|
|
||||||
<Td>{row.expiresAt && new Date(row.expiresAt).toUTCString()}</Td>
|
|
||||||
<Td>
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Delete}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<IconButton
|
|
||||||
onClick={() =>
|
|
||||||
handlePopUpOpen("deleteAPITokenConfirmation", {
|
|
||||||
name: row.name,
|
|
||||||
id: row._id
|
|
||||||
})
|
|
||||||
}
|
|
||||||
colorSchema="danger"
|
|
||||||
ariaLabel="delete"
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faTrashCan} />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
</Td>
|
|
||||||
</Tr>
|
|
||||||
))}
|
|
||||||
{!isLoading && data && data?.length === 0 && (
|
|
||||||
<Tr>
|
|
||||||
<Td colSpan={4} className="bg-mineshaft-800 text-center text-bunker-400">
|
|
||||||
<EmptyState title="No service tokens found" icon={faKey} />
|
|
||||||
</Td>
|
|
||||||
</Tr>
|
|
||||||
)}
|
|
||||||
</TBody>
|
|
||||||
</Table>
|
|
||||||
</TableContainer>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
export {ServiceTokenSection} from "./ServiceTokenSection"
|
|
||||||
-657
@@ -1,657 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Controller, useFieldArray, useForm } from "react-hook-form";
|
|
||||||
import { faCheck, faCopy,faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
import { yupResolver } from "@hookform/resolvers/yup";
|
|
||||||
import { motion } from "framer-motion";
|
|
||||||
import nacl from "tweetnacl";
|
|
||||||
import { encodeBase64 } from "tweetnacl-util";
|
|
||||||
import * as yup from "yup";
|
|
||||||
|
|
||||||
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
|
|
||||||
import {
|
|
||||||
decryptAssymmetric,
|
|
||||||
encryptAssymmetric
|
|
||||||
} from "@app/components/utilities/cryptography/crypto";
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
FormControl,
|
|
||||||
IconButton,
|
|
||||||
Input,
|
|
||||||
Modal,
|
|
||||||
ModalContent,
|
|
||||||
Select,
|
|
||||||
SelectItem,
|
|
||||||
Switch,
|
|
||||||
Tab,
|
|
||||||
TabList,
|
|
||||||
TabPanel,
|
|
||||||
Tabs,
|
|
||||||
UpgradePlanModal} from "@app/components/v2";
|
|
||||||
import {
|
|
||||||
useSubscription,
|
|
||||||
useWorkspace
|
|
||||||
} from "@app/context";
|
|
||||||
import { useToggle } from "@app/hooks";
|
|
||||||
import {
|
|
||||||
useCreateServiceTokenV3,
|
|
||||||
useGetUserWsKey,
|
|
||||||
useUpdateServiceTokenV3
|
|
||||||
} from "@app/hooks/api";
|
|
||||||
import {
|
|
||||||
Permission
|
|
||||||
} from "@app/hooks/api/serviceTokens/enums";
|
|
||||||
import {
|
|
||||||
ServiceTokenV3Scope,
|
|
||||||
ServiceTokenV3TrustedIp
|
|
||||||
} from "@app/hooks/api/serviceTokens/types";
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
|
||||||
|
|
||||||
enum TabSections {
|
|
||||||
General = "general",
|
|
||||||
Advanced = "advanced"
|
|
||||||
}
|
|
||||||
|
|
||||||
const expirations = [
|
|
||||||
{ label: "Never", value: "" },
|
|
||||||
{ label: "1 day", value: "86400" },
|
|
||||||
{ label: "7 days", value: "604800" },
|
|
||||||
{ label: "1 month", value: "2592000" },
|
|
||||||
{ label: "6 months", value: "15552000" },
|
|
||||||
{ label: "12 months", value: "31104000" }
|
|
||||||
];
|
|
||||||
|
|
||||||
const permissionsMap: {
|
|
||||||
[key: string]: Permission[]
|
|
||||||
} = {
|
|
||||||
"read": [Permission.READ],
|
|
||||||
"readWrite": [Permission.READ, Permission.WRITE],
|
|
||||||
}
|
|
||||||
|
|
||||||
const schema = yup.object({
|
|
||||||
name: yup.string().required("ST V3 name is required"),
|
|
||||||
expiresIn: yup.string(),
|
|
||||||
accessTokenTTL: yup
|
|
||||||
.string()
|
|
||||||
.test("is-positive-integer", "Access Token TTL must be a positive integer", (value) => {
|
|
||||||
if (typeof value === "undefined") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const num = parseInt(value, 10);
|
|
||||||
return !Number.isNaN(num) && num > 0 && String(num) === value;
|
|
||||||
})
|
|
||||||
.required("Access Token TTL is required"),
|
|
||||||
scopes: yup
|
|
||||||
.array(
|
|
||||||
yup.object({
|
|
||||||
permission: yup.string().oneOf(Object.keys(permissionsMap), "Invalid permission").required().label("Permission"),
|
|
||||||
environment: yup.string().max(50).required().label("Environment"),
|
|
||||||
secretPath: yup
|
|
||||||
.string()
|
|
||||||
.required()
|
|
||||||
.default("/")
|
|
||||||
.label("Secret Path")
|
|
||||||
.transform((val) =>
|
|
||||||
typeof val === "string" && val.at(-1) === "/" && val.length > 1 ? val.slice(0, -1) : val
|
|
||||||
)
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required()
|
|
||||||
.label("Scope"),
|
|
||||||
trustedIps: yup
|
|
||||||
.array(
|
|
||||||
yup.object({
|
|
||||||
ipAddress: yup.string().max(50).required().label("IP Address")
|
|
||||||
})
|
|
||||||
)
|
|
||||||
.min(1)
|
|
||||||
.required()
|
|
||||||
.label("Trusted IP"),
|
|
||||||
isRefreshTokenRotationEnabled: yup.boolean().default(false)
|
|
||||||
}).required();
|
|
||||||
|
|
||||||
export type FormData = yup.InferType<typeof schema>;
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
popUp: UsePopUpState<["serviceTokenV3", "upgradePlan"]>;
|
|
||||||
handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void;
|
|
||||||
handlePopUpToggle: (popUpName: keyof UsePopUpState<["serviceTokenV3", "upgradePlan"]>, state?: boolean) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const AddServiceTokenV3Modal = ({
|
|
||||||
popUp,
|
|
||||||
handlePopUpOpen,
|
|
||||||
handlePopUpToggle
|
|
||||||
}: Props) => {
|
|
||||||
const [newServiceTokenJSON, setNewServiceTokenJSON] = useState("");
|
|
||||||
const [isServiceTokenJSONCopied, setIsServiceTokenJSONCopied] = useToggle(false);
|
|
||||||
|
|
||||||
const { subscription } = useSubscription();
|
|
||||||
const { currentWorkspace } = useWorkspace();
|
|
||||||
|
|
||||||
const { data: latestFileKey } = useGetUserWsKey(currentWorkspace?._id ?? "");
|
|
||||||
const { mutateAsync: createMutateAsync } = useCreateServiceTokenV3();
|
|
||||||
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
|
||||||
const { createNotification } = useNotificationContext();
|
|
||||||
const {
|
|
||||||
control,
|
|
||||||
handleSubmit,
|
|
||||||
reset,
|
|
||||||
formState: { isSubmitting }
|
|
||||||
} = useForm<FormData>({
|
|
||||||
resolver: yupResolver(schema),
|
|
||||||
defaultValues: {
|
|
||||||
name: "",
|
|
||||||
accessTokenTTL: "7200",
|
|
||||||
scopes: [{
|
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug,
|
|
||||||
secretPath: "/",
|
|
||||||
}],
|
|
||||||
trustedIps: [{
|
|
||||||
ipAddress: "0.0.0.0/0"
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let timer: NodeJS.Timeout;
|
|
||||||
|
|
||||||
if (isServiceTokenJSONCopied) {
|
|
||||||
timer = setTimeout(() => setIsServiceTokenJSONCopied.off(), 2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [setIsServiceTokenJSONCopied]);
|
|
||||||
|
|
||||||
const copyTokenToClipboard = () => {
|
|
||||||
navigator.clipboard.writeText(newServiceTokenJSON);
|
|
||||||
setIsServiceTokenJSONCopied.on();
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
|
||||||
serviceTokenDataId: string;
|
|
||||||
name: string;
|
|
||||||
scopes: ServiceTokenV3Scope[];
|
|
||||||
trustedIps: ServiceTokenV3TrustedIp[];
|
|
||||||
accessTokenTTL: number;
|
|
||||||
isRefreshTokenRotationEnabled: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (serviceTokenData) {
|
|
||||||
reset({
|
|
||||||
name: serviceTokenData.name,
|
|
||||||
scopes: serviceTokenData.scopes.map(({
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
permissions
|
|
||||||
}: ServiceTokenV3Scope) => {
|
|
||||||
let permission = "read";
|
|
||||||
if (permissions.includes(Permission.WRITE)) {
|
|
||||||
permission = "readWrite";
|
|
||||||
}
|
|
||||||
|
|
||||||
return ({
|
|
||||||
environment,
|
|
||||||
secretPath,
|
|
||||||
permission
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
trustedIps: serviceTokenData.trustedIps.map(({
|
|
||||||
ipAddress,
|
|
||||||
prefix
|
|
||||||
}: ServiceTokenV3TrustedIp) => {
|
|
||||||
return ({
|
|
||||||
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
accessTokenTTL: String(serviceTokenData.accessTokenTTL),
|
|
||||||
isRefreshTokenRotationEnabled: serviceTokenData.isRefreshTokenRotationEnabled
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
reset({
|
|
||||||
name: "",
|
|
||||||
accessTokenTTL: "7200",
|
|
||||||
scopes: [{
|
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug,
|
|
||||||
secretPath: "/",
|
|
||||||
}],
|
|
||||||
trustedIps: [{
|
|
||||||
ipAddress: "0.0.0.0/0"
|
|
||||||
}]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [popUp?.serviceTokenV3?.data]);
|
|
||||||
|
|
||||||
const { fields: tokenScopes, append, remove } = useFieldArray({ control, name: "scopes" });
|
|
||||||
const { fields: tokenTrustedIps, append: appendTrustedIp, remove: removeTrustedIp } = useFieldArray({ control, name: "trustedIps" });
|
|
||||||
|
|
||||||
const onFormSubmit = async ({
|
|
||||||
name,
|
|
||||||
expiresIn,
|
|
||||||
accessTokenTTL,
|
|
||||||
scopes,
|
|
||||||
trustedIps,
|
|
||||||
isRefreshTokenRotationEnabled
|
|
||||||
}: FormData) => {
|
|
||||||
try {
|
|
||||||
const serviceTokenData = popUp?.serviceTokenV3?.data as {
|
|
||||||
serviceTokenDataId: string;
|
|
||||||
name: string;
|
|
||||||
scopes: any;
|
|
||||||
};
|
|
||||||
|
|
||||||
// convert read/readWrite permission => ["read", "write"] format
|
|
||||||
const reformattedScopes = scopes.map((scope) => {
|
|
||||||
return ({
|
|
||||||
environment: scope.environment,
|
|
||||||
secretPath: scope.secretPath,
|
|
||||||
permissions: permissionsMap[scope.permission]
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
if (serviceTokenData) {
|
|
||||||
// update
|
|
||||||
|
|
||||||
await updateMutateAsync({
|
|
||||||
serviceTokenDataId: serviceTokenData.serviceTokenDataId,
|
|
||||||
name,
|
|
||||||
scopes: reformattedScopes,
|
|
||||||
trustedIps,
|
|
||||||
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
|
||||||
accessTokenTTL: Number(accessTokenTTL),
|
|
||||||
isRefreshTokenRotationEnabled
|
|
||||||
});
|
|
||||||
|
|
||||||
handlePopUpToggle("serviceTokenV3", false);
|
|
||||||
} else {
|
|
||||||
// create
|
|
||||||
if (!currentWorkspace?._id) return;
|
|
||||||
if (!latestFileKey) return;
|
|
||||||
|
|
||||||
const pair = nacl.box.keyPair();
|
|
||||||
const secretKeyUint8Array = pair.secretKey;
|
|
||||||
const publicKeyUint8Array = pair.publicKey;
|
|
||||||
const privateKey = encodeBase64(secretKeyUint8Array);
|
|
||||||
const publicKey = encodeBase64(publicKeyUint8Array);
|
|
||||||
|
|
||||||
const key = decryptAssymmetric({
|
|
||||||
ciphertext: latestFileKey.encryptedKey,
|
|
||||||
nonce: latestFileKey.nonce,
|
|
||||||
publicKey: latestFileKey.sender.publicKey,
|
|
||||||
privateKey: localStorage.getItem("PRIVATE_KEY") as string
|
|
||||||
});
|
|
||||||
|
|
||||||
const { ciphertext, nonce } = encryptAssymmetric({
|
|
||||||
plaintext: key,
|
|
||||||
publicKey,
|
|
||||||
privateKey: localStorage.getItem("PRIVATE_KEY") as string
|
|
||||||
});
|
|
||||||
|
|
||||||
const { refreshToken } = await createMutateAsync({
|
|
||||||
name,
|
|
||||||
workspaceId: currentWorkspace._id,
|
|
||||||
publicKey,
|
|
||||||
scopes: reformattedScopes,
|
|
||||||
trustedIps,
|
|
||||||
expiresIn: expiresIn === "" ? undefined : Number(expiresIn),
|
|
||||||
accessTokenTTL: Number(accessTokenTTL),
|
|
||||||
encryptedKey: ciphertext,
|
|
||||||
nonce,
|
|
||||||
isRefreshTokenRotationEnabled
|
|
||||||
});
|
|
||||||
|
|
||||||
const downloadData = {
|
|
||||||
public_key: publicKey,
|
|
||||||
private_key: privateKey,
|
|
||||||
refresh_token: refreshToken
|
|
||||||
};
|
|
||||||
|
|
||||||
const serviceTokenJSON = JSON.stringify(downloadData, null, 2);
|
|
||||||
setNewServiceTokenJSON(serviceTokenJSON);
|
|
||||||
|
|
||||||
const blob = new Blob([serviceTokenJSON], { type: "application/json" });
|
|
||||||
const href = URL.createObjectURL(blob);
|
|
||||||
const link = document.createElement("a");
|
|
||||||
link.href = href;
|
|
||||||
link.download = `infisical_${name}.json`;
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
document.body.removeChild(link);
|
|
||||||
}
|
|
||||||
|
|
||||||
createNotification({
|
|
||||||
text: `Successfully ${popUp?.serviceTokenV3?.data ? "updated" : "created"} ST V3`,
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
|
|
||||||
reset();
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
createNotification({
|
|
||||||
text: `Failed to ${popUp?.serviceTokenV3?.data ? "updated" : "created"} ST V3`,
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasServiceTokenJSON = Boolean(newServiceTokenJSON);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={popUp?.serviceTokenV3?.isOpen}
|
|
||||||
onOpenChange={(isOpen) => {
|
|
||||||
handlePopUpToggle("serviceTokenV3", isOpen);
|
|
||||||
reset();
|
|
||||||
setNewServiceTokenJSON("");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ModalContent title={`${popUp?.serviceTokenV3?.data ? "Update" : "Create"} Service Token V3`}>
|
|
||||||
{!hasServiceTokenJSON ? (
|
|
||||||
<form onSubmit={handleSubmit(onFormSubmit)}>
|
|
||||||
<Tabs defaultValue={TabSections.General}>
|
|
||||||
<TabList>
|
|
||||||
<div className="flex flex-row border-b border-mineshaft-600 w-full">
|
|
||||||
<Tab value={TabSections.General}>General</Tab>
|
|
||||||
<Tab value={TabSections.Advanced}>Advanced</Tab>
|
|
||||||
</div>
|
|
||||||
</TabList>
|
|
||||||
<TabPanel value={TabSections.General}>
|
|
||||||
<motion.div
|
|
||||||
key="panel-1"
|
|
||||||
transition={{ duration: 0.15 }}
|
|
||||||
initial={{ opacity: 0, translateX: 30 }}
|
|
||||||
animate={{ opacity: 1, translateX: 0 }}
|
|
||||||
exit={{ opacity: 0, translateX: 30 }}
|
|
||||||
>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
defaultValue=""
|
|
||||||
name="name"
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
label="Name"
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
{...field}
|
|
||||||
placeholder="My ST V3"
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
{tokenScopes.map(({ id }, index) => (
|
|
||||||
<div className="flex items-end space-x-2 mb-3" key={id}>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.permission`}
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0"
|
|
||||||
label={index === 0 ? "Permission" : undefined}
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-36"
|
|
||||||
>
|
|
||||||
<SelectItem value="read" key="st-v3-read">
|
|
||||||
Read
|
|
||||||
</SelectItem>
|
|
||||||
<SelectItem value="readWrite" key="st-v3-write">
|
|
||||||
Read & Write
|
|
||||||
</SelectItem>
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.environment`}
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0"
|
|
||||||
label={index === 0 ? "Environment" : undefined}
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-36"
|
|
||||||
>
|
|
||||||
{currentWorkspace?.environments.map(({ name, slug }) => (
|
|
||||||
<SelectItem value={slug} key={slug}>
|
|
||||||
{name}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`scopes.${index}.secretPath`}
|
|
||||||
defaultValue="/"
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0 flex-grow"
|
|
||||||
label={index === 0 ? "Secrets Path" : undefined}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input {...field} placeholder="can be /, /nested/**, /**/deep" />
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => remove(index)}
|
|
||||||
size="lg"
|
|
||||||
colorSchema="danger"
|
|
||||||
variant="plain"
|
|
||||||
ariaLabel="update"
|
|
||||||
className="p-3"
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faXmark} />
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="my-4 ml-1">
|
|
||||||
<Button
|
|
||||||
variant="outline_bg"
|
|
||||||
onClick={() =>
|
|
||||||
append({
|
|
||||||
permission: "read",
|
|
||||||
environment: currentWorkspace?.environments?.[0]?.slug || "",
|
|
||||||
secretPath: "/"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
Add Scope
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name="expiresIn"
|
|
||||||
defaultValue=""
|
|
||||||
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
label={`${popUp?.serviceTokenV3?.data ? "Update" : ""} Refresh Token Expires In`}
|
|
||||||
errorText={error?.message}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
className="mt-4"
|
|
||||||
>
|
|
||||||
<Select
|
|
||||||
defaultValue={field.value}
|
|
||||||
{...field}
|
|
||||||
onValueChange={(e) => onChange(e)}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{expirations.map(({ label, value }) => (
|
|
||||||
<SelectItem value={String(value || "")} key={`api-key-expiration-${label}`}>
|
|
||||||
{label}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</Select>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</motion.div>
|
|
||||||
</TabPanel>
|
|
||||||
<TabPanel value={TabSections.Advanced}>
|
|
||||||
<div>
|
|
||||||
{tokenTrustedIps.map(({ id }, index) => (
|
|
||||||
<div className="flex items-end space-x-2 mb-3" key={id}>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name={`trustedIps.${index}.ipAddress`}
|
|
||||||
defaultValue="0.0.0.0/0"
|
|
||||||
render={({ field, fieldState: { error } }) => {
|
|
||||||
return (
|
|
||||||
<FormControl
|
|
||||||
className="mb-0 flex-grow"
|
|
||||||
label={index === 0 ? "Trusted IP" : undefined}
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
value={field.value}
|
|
||||||
onChange={(e) => {
|
|
||||||
if (subscription?.ipAllowlisting) {
|
|
||||||
field.onChange(e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
handlePopUpOpen("upgradePlan");
|
|
||||||
}}
|
|
||||||
placeholder="123.456.789.0"
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => {
|
|
||||||
if (subscription?.ipAllowlisting) {
|
|
||||||
removeTrustedIp(index);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
handlePopUpOpen("upgradePlan");
|
|
||||||
}}
|
|
||||||
size="lg"
|
|
||||||
colorSchema="danger"
|
|
||||||
variant="plain"
|
|
||||||
ariaLabel="update"
|
|
||||||
className="p-3"
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faXmark} />
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<div className="my-4 ml-1">
|
|
||||||
<Button
|
|
||||||
variant="outline_bg"
|
|
||||||
onClick={() => {
|
|
||||||
if (subscription?.ipAllowlisting) {
|
|
||||||
appendTrustedIp({
|
|
||||||
ipAddress: "0.0.0.0/0"
|
|
||||||
})
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
handlePopUpOpen("upgradePlan");
|
|
||||||
}}
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
Add IP Address
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
defaultValue="7200"
|
|
||||||
name="accessTokenTTL"
|
|
||||||
render={({ field, fieldState: { error } }) => (
|
|
||||||
<FormControl
|
|
||||||
label="Access Token TTL (seconds)"
|
|
||||||
isError={Boolean(error)}
|
|
||||||
errorText={error?.message}
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
{...field}
|
|
||||||
placeholder="7200"
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div className="mt-8">
|
|
||||||
<Controller
|
|
||||||
control={control}
|
|
||||||
name="isRefreshTokenRotationEnabled"
|
|
||||||
render={({ field: { onChange, value } }) => (
|
|
||||||
<Switch
|
|
||||||
id="label-refresh-token-rotation"
|
|
||||||
onCheckedChange={(isChecked) => onChange(isChecked)}
|
|
||||||
isChecked={value}
|
|
||||||
>
|
|
||||||
Refresh Token Rotation
|
|
||||||
</Switch>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<p className="mt-4 text-sm font-normal text-mineshaft-400">When enabled, as a result of exchanging a refresh token, a new refresh token will be issued and the existing token will be invalidated.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</TabPanel>
|
|
||||||
</Tabs>
|
|
||||||
<div className="flex items-center">
|
|
||||||
<Button
|
|
||||||
className="mr-4"
|
|
||||||
size="sm"
|
|
||||||
type="submit"
|
|
||||||
isLoading={isSubmitting}
|
|
||||||
isDisabled={isSubmitting}
|
|
||||||
>
|
|
||||||
{popUp?.serviceTokenV3?.data ? "Update" : "Create"}
|
|
||||||
</Button>
|
|
||||||
<Button colorSchema="secondary" variant="plain">
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<div className="mt-2 mb-3 mr-2 flex items-center justify-end rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
|
|
||||||
<p className="mr-4 break-all">{newServiceTokenJSON}</p>
|
|
||||||
<IconButton
|
|
||||||
ariaLabel="copy icon"
|
|
||||||
colorSchema="secondary"
|
|
||||||
className="group relative"
|
|
||||||
onClick={copyTokenToClipboard}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={isServiceTokenJSONCopied ? faCheck : faCopy} />
|
|
||||||
<span className="absolute -left-8 -top-20 hidden w-28 translate-y-full rounded-md bg-bunker-800 py-2 pl-3 text-center text-sm text-gray-400 group-hover:flex group-hover:animate-fadeIn">
|
|
||||||
Click to copy
|
|
||||||
</span>
|
|
||||||
</IconButton>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<UpgradePlanModal
|
|
||||||
isOpen={popUp?.upgradePlan?.isOpen}
|
|
||||||
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
|
|
||||||
text="You can use IP allowlisting if you switch to Infisical's Pro plan."
|
|
||||||
/>
|
|
||||||
</ModalContent>
|
|
||||||
</Modal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
-98
@@ -1,98 +0,0 @@
|
|||||||
import { faPlus } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
|
|
||||||
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
|
|
||||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
|
||||||
import {
|
|
||||||
Button,
|
|
||||||
DeleteActionModal
|
|
||||||
} from "@app/components/v2";
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";
|
|
||||||
import { withProjectPermission } from "@app/hoc";
|
|
||||||
import {
|
|
||||||
useDeleteServiceTokenV3
|
|
||||||
} from "@app/hooks/api";
|
|
||||||
import { usePopUp } from "@app/hooks/usePopUp";
|
|
||||||
|
|
||||||
import { AddServiceTokenV3Modal } from "./AddServiceTokenV3Modal";
|
|
||||||
import { ServiceTokenV3Table } from "./ServiceTokenV3Table";
|
|
||||||
|
|
||||||
export const ServiceTokenV3Section = withProjectPermission(
|
|
||||||
() => {
|
|
||||||
const { createNotification } = useNotificationContext();
|
|
||||||
const { mutateAsync: deleteMutateAsync } = useDeleteServiceTokenV3();
|
|
||||||
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
|
|
||||||
"serviceTokenV3",
|
|
||||||
"deleteServiceTokenV3",
|
|
||||||
"upgradePlan"
|
|
||||||
] as const);
|
|
||||||
|
|
||||||
const onDeleteServiceTokenDataSubmit = async (serviceTokenDataId: string) => {
|
|
||||||
try {
|
|
||||||
await deleteMutateAsync({
|
|
||||||
serviceTokenDataId
|
|
||||||
});
|
|
||||||
createNotification({
|
|
||||||
text: "Successfully deleted service token v3",
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
|
|
||||||
handlePopUpClose("deleteServiceTokenV3");
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
createNotification({
|
|
||||||
text: "Failed to delete service token v3",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
|
|
||||||
<div className="flex justify-between mb-8">
|
|
||||||
<p className="text-xl font-semibold text-mineshaft-100">
|
|
||||||
Service Tokens V3 (Beta)
|
|
||||||
</p>
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Create}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<Button
|
|
||||||
colorSchema="secondary"
|
|
||||||
type="submit"
|
|
||||||
leftIcon={<FontAwesomeIcon icon={faPlus} />}
|
|
||||||
onClick={() => handlePopUpOpen("serviceTokenV3")}
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
Create token
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
</div>
|
|
||||||
<ServiceTokenV3Table
|
|
||||||
handlePopUpOpen={handlePopUpOpen}
|
|
||||||
/>
|
|
||||||
<AddServiceTokenV3Modal
|
|
||||||
popUp={popUp}
|
|
||||||
handlePopUpOpen={handlePopUpOpen}
|
|
||||||
handlePopUpToggle={handlePopUpToggle}
|
|
||||||
/>
|
|
||||||
<DeleteActionModal
|
|
||||||
isOpen={popUp.deleteServiceTokenV3.isOpen}
|
|
||||||
title={`Are you sure want to delete ${
|
|
||||||
(popUp?.deleteServiceTokenV3?.data as { name: string })?.name || ""
|
|
||||||
}?`}
|
|
||||||
onChange={(isOpen) => handlePopUpToggle("deleteServiceTokenV3", isOpen)}
|
|
||||||
deleteKey="confirm"
|
|
||||||
onDeleteApproved={() =>
|
|
||||||
onDeleteServiceTokenDataSubmit(
|
|
||||||
(popUp?.deleteServiceTokenV3?.data as { serviceTokenDataId: string })?.serviceTokenDataId
|
|
||||||
)
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
{ action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.ServiceTokens }
|
|
||||||
);
|
|
||||||
-232
@@ -1,232 +0,0 @@
|
|||||||
import { faKey, faPencil,faXmark } from "@fortawesome/free-solid-svg-icons";
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
||||||
import { format } from "date-fns";
|
|
||||||
|
|
||||||
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
|
|
||||||
import { ProjectPermissionCan } from "@app/components/permissions";
|
|
||||||
import {
|
|
||||||
EmptyState,
|
|
||||||
IconButton,
|
|
||||||
Switch,
|
|
||||||
Table,
|
|
||||||
TableContainer,
|
|
||||||
TableSkeleton,
|
|
||||||
TBody,
|
|
||||||
Td,
|
|
||||||
Th,
|
|
||||||
THead,
|
|
||||||
Tr
|
|
||||||
} from "@app/components/v2";
|
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub , useWorkspace } from "@app/context";
|
|
||||||
import {
|
|
||||||
useGetWorkspaceServiceTokenDataV3,
|
|
||||||
useUpdateServiceTokenV3
|
|
||||||
} from "@app/hooks/api";
|
|
||||||
import { Permission } from "@app/hooks/api/serviceTokens/enums"
|
|
||||||
import { ServiceTokenV3Scope, ServiceTokenV3TrustedIp } from "@app/hooks/api/serviceTokens/types"
|
|
||||||
import { UsePopUpState } from "@app/hooks/usePopUp";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
handlePopUpOpen: (
|
|
||||||
popUpName: keyof UsePopUpState<["deleteServiceTokenV3", "serviceTokenV3"]>,
|
|
||||||
data?: {
|
|
||||||
serviceTokenDataId?: string;
|
|
||||||
name?: string;
|
|
||||||
scopes?: ServiceTokenV3Scope[];
|
|
||||||
trustedIps?: ServiceTokenV3TrustedIp[];
|
|
||||||
accessTokenTTL?: number;
|
|
||||||
isRefreshTokenRotationEnabled?: boolean;
|
|
||||||
}
|
|
||||||
) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ServiceTokenV3Table = ({
|
|
||||||
handlePopUpOpen
|
|
||||||
}: Props) => {
|
|
||||||
const { createNotification } = useNotificationContext();
|
|
||||||
const { currentWorkspace } = useWorkspace();
|
|
||||||
const { data, isLoading } = useGetWorkspaceServiceTokenDataV3(currentWorkspace?._id || "");
|
|
||||||
const { mutateAsync: updateMutateAsync } = useUpdateServiceTokenV3();
|
|
||||||
|
|
||||||
const handleToggleServiceTokenDataStatus = async ({
|
|
||||||
serviceTokenDataId,
|
|
||||||
isActive
|
|
||||||
}: {
|
|
||||||
serviceTokenDataId: string;
|
|
||||||
isActive: boolean;
|
|
||||||
}) => {
|
|
||||||
try {
|
|
||||||
await updateMutateAsync({
|
|
||||||
serviceTokenDataId,
|
|
||||||
isActive
|
|
||||||
});
|
|
||||||
|
|
||||||
createNotification({
|
|
||||||
text: `Successfully ${isActive ? "enabled" : "disabled"} service token v3`,
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.log(err);
|
|
||||||
createNotification({
|
|
||||||
text: `Failed to ${isActive ? "enable" : "disable"} service token v3`,
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<TableContainer>
|
|
||||||
<Table>
|
|
||||||
<THead>
|
|
||||||
<Tr>
|
|
||||||
<Th>Name</Th>
|
|
||||||
<Th>Status</Th>
|
|
||||||
<Th>Scopes</Th>
|
|
||||||
<Th>Trusted IPs</Th>
|
|
||||||
<Th>Access Token TTL</Th>
|
|
||||||
<Th>Created At</Th>
|
|
||||||
<Th>Valid Until</Th>
|
|
||||||
<Th className="w-5" />
|
|
||||||
</Tr>
|
|
||||||
</THead>
|
|
||||||
<TBody>
|
|
||||||
{isLoading && <TableSkeleton columns={7} innerKey="service-tokens" />}
|
|
||||||
{!isLoading &&
|
|
||||||
data &&
|
|
||||||
data.length > 0 &&
|
|
||||||
data.map(({
|
|
||||||
_id,
|
|
||||||
name,
|
|
||||||
isActive,
|
|
||||||
scopes,
|
|
||||||
trustedIps,
|
|
||||||
createdAt,
|
|
||||||
expiresAt,
|
|
||||||
accessTokenTTL,
|
|
||||||
isRefreshTokenRotationEnabled
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<Tr className="h-10" key={`st-v3-${_id}`}>
|
|
||||||
<Td>{name}</Td>
|
|
||||||
<Td>
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Edit}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<Switch
|
|
||||||
id={`enable-service-token-${_id}`}
|
|
||||||
onCheckedChange={(value) => handleToggleServiceTokenDataStatus({
|
|
||||||
serviceTokenDataId: _id,
|
|
||||||
isActive: value
|
|
||||||
})}
|
|
||||||
isChecked={isActive}
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
<p className="w-12 mr-4">{isActive ? "Active" : "Inactive"}</p>
|
|
||||||
</Switch>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
</Td>
|
|
||||||
<Td>
|
|
||||||
{scopes.map((scope) => {
|
|
||||||
let permissionText = "read"
|
|
||||||
if (
|
|
||||||
scope.permissions.includes(Permission.WRITE) &&
|
|
||||||
scope.permissions.includes(Permission.READ)
|
|
||||||
) {
|
|
||||||
permissionText = "readWrite";
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<p key={`service-token-${_id}-scope-${scope.environment}-${scope.secretPath}`}>
|
|
||||||
<span className="font-bold">
|
|
||||||
{permissionText}
|
|
||||||
</span>
|
|
||||||
{` @${scope.environment} - ${scope.secretPath}`}
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Td>
|
|
||||||
<Td>
|
|
||||||
{trustedIps.map(({
|
|
||||||
_id: trustedIpId,
|
|
||||||
ipAddress,
|
|
||||||
prefix
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<p key={`service-token-${_id}-}-trusted-ip-${trustedIpId}`}>
|
|
||||||
{`${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`}
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Td>
|
|
||||||
<Td>{accessTokenTTL}</Td>
|
|
||||||
<Td>{format(new Date(createdAt), "yyyy-MM-dd")}</Td>
|
|
||||||
<Td>{expiresAt ? format(new Date(expiresAt), "yyyy-MM-dd") : "-"}</Td>
|
|
||||||
<Td className="flex justify-end">
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Edit}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<IconButton
|
|
||||||
onClick={async () => {
|
|
||||||
handlePopUpOpen("serviceTokenV3", {
|
|
||||||
serviceTokenDataId: _id,
|
|
||||||
name,
|
|
||||||
scopes,
|
|
||||||
trustedIps,
|
|
||||||
accessTokenTTL,
|
|
||||||
isRefreshTokenRotationEnabled
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
size="lg"
|
|
||||||
colorSchema="primary"
|
|
||||||
variant="plain"
|
|
||||||
ariaLabel="update"
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faPencil} />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
<ProjectPermissionCan
|
|
||||||
I={ProjectPermissionActions.Delete}
|
|
||||||
a={ProjectPermissionSub.ServiceTokens}
|
|
||||||
>
|
|
||||||
{(isAllowed) => (
|
|
||||||
<IconButton
|
|
||||||
onClick={() => {
|
|
||||||
handlePopUpOpen("deleteServiceTokenV3", {
|
|
||||||
serviceTokenDataId: _id,
|
|
||||||
name
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
size="lg"
|
|
||||||
colorSchema="danger"
|
|
||||||
variant="plain"
|
|
||||||
ariaLabel="update"
|
|
||||||
className="ml-4"
|
|
||||||
isDisabled={!isAllowed}
|
|
||||||
>
|
|
||||||
<FontAwesomeIcon icon={faXmark} />
|
|
||||||
</IconButton>
|
|
||||||
)}
|
|
||||||
</ProjectPermissionCan>
|
|
||||||
</Td>
|
|
||||||
</Tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{!isLoading && data && data?.length === 0 && (
|
|
||||||
<Tr>
|
|
||||||
<Td colSpan={7}>
|
|
||||||
<EmptyState title="No service token v3 on file" icon={faKey} />
|
|
||||||
</Td>
|
|
||||||
</Tr>
|
|
||||||
)}
|
|
||||||
</TBody>
|
|
||||||
</Table>
|
|
||||||
</TableContainer>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
-1
@@ -1 +0,0 @@
|
|||||||
export { ServiceTokenV3Section } from "./ServiceTokenV3Section";
|
|
||||||
Reference in New Issue
Block a user