Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

misc: polishing

Sheen Capadngan5182bd97a250
diff --git a/backend/src/db/migrations/20260206151238_add-uniqueness-constraints-for-pam.ts b/backend/src/db/migrations/20260206151238_add-uniqueness-constraints-for-pam.ts
new file mode 100644
index 0000000000..b2deb01d44
--- /dev/null
+++ b/backend/src/db/migrations/20260206151238_add-uniqueness-constraints-for-pam.ts
@@ -0,0 +1,69 @@
+import { Knex } from "knex";
+
+import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
+import { TableName } from "@app/db/schemas";
+
+const RESOURCE_CONSTRAINT_NAME = "pam_resources_name_project_id_unique";
+const ACCOUNT_CONSTRAINT_NAME = "pam_accounts_name_resource_id_unique";
+
+export async function up(knex: Knex): Promise<void> {
+ // 1. Add unique constraint for resource names within a project
+ if (await knex.schema.hasTable(TableName.PamResource)) {
+ const hasName = await knex.schema.hasColumn(TableName.PamResource, "name");
+ const hasProjectId = await knex.schema.hasColumn(TableName.PamResource, "projectId");
+
+ if (hasName && hasProjectId) {
+ // Rename any duplicate resources (keep oldest, append random suffix to newer ones)
+ await knex.raw(`
+ UPDATE ${TableName.PamResource} r1
+ SET "name" = r1."name" || '-' || substr(md5(random()::text), 1, 3)
+ WHERE EXISTS (
+ SELECT 1 FROM ${TableName.PamResource} r2
+ WHERE r2."projectId" = r1."projectId"
+ AND r2."name" = r1."name"
+ AND r2."createdAt" < r1."createdAt"
+ )
+ `);
+
+ await dropConstraintIfExists(TableName.PamResource, RESOURCE_CONSTRAINT_NAME, knex);
+ await knex.schema.alterTable(TableName.PamResource, (table) => {
+ table.unique(["name", "projectId"], { indexName: RESOURCE_CONSTRAINT_NAME });
+ });
+ }
+ }
+
+ // 2. Add unique constraint for account names within the same resource
+ if (await knex.schema.hasTable(TableName.PamAccount)) {
+ const hasName = await knex.schema.hasColumn(TableName.PamAccount, "name");
+ const hasResourceId = await knex.schema.hasColumn(TableName.PamAccount, "resourceId");
+
+ if (hasName && hasResourceId) {
+ // Rename any duplicate accounts (keep oldest, append random suffix to newer ones)
+ await knex.raw(`
+ UPDATE ${TableName.PamAccount} a1
+ SET "name" = a1."name" || '-' || substr(md5(random()::text), 1, 3)
+ WHERE EXISTS (
+ SELECT 1 FROM ${TableName.PamAccount} a2
+ WHERE a2."resourceId" = a1."resourceId"
+ AND a2."name" = a1."name"
+ AND a2."createdAt" < a1."createdAt"
+ )
+ `);
+
+ await dropConstraintIfExists(TableName.PamAccount, ACCOUNT_CONSTRAINT_NAME, knex);
+ await knex.schema.alterTable(TableName.PamAccount, (table) => {
+ table.unique(["name", "resourceId"], { indexName: ACCOUNT_CONSTRAINT_NAME });
+ });
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PamResource)) {
+ await dropConstraintIfExists(TableName.PamResource, RESOURCE_CONSTRAINT_NAME, knex);
+ }
+
+ if (await knex.schema.hasTable(TableName.PamAccount)) {
+ await dropConstraintIfExists(TableName.PamAccount, ACCOUNT_CONSTRAINT_NAME, knex);
+ }
+}
diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.ts
index 9590105cfe..70734a17fb 100644
--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts
+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts
@@ -1,8 +1,12 @@
-import { ForbiddenError } from "@casl/ability";
+import { ForbiddenError, subject } from "@casl/ability";
import { ActionProjectType, TPamResources } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionPamAccountActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { createSshKeyPair } from "@app/ee/services/ssh/ssh-certificate-authority-fns";
import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";
import { PgSqlLock } from "@app/keystore/keystore";
@@ -12,7 +16,10 @@ import { OrgServiceActor } from "@app/lib/types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";
+import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";
+import { PamAccountView } from "../pam-account/pam-account-enums";
import { decryptAccountCredentials, encryptAccountCredentials } from "../pam-account/pam-account-fns";
+import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";
import { TPamResourceDALFactory } from "./pam-resource-dal";
import { PamResource } from "./pam-resource-enums";
import { PAM_RESOURCE_FACTORY_MAP } from "./pam-resource-factory";
@@ -29,6 +36,8 @@ import { TSSHResourceMetadata } from "./ssh/ssh-resource-types";
type TPamResourceServiceFactoryDep = {
pamResourceDAL: TPamResourceDALFactory;
+ pamAccountDAL: Pick<TPamAccountDALFactory, "findByProjectIdWithResourceDetails">;
+ pamFolderDAL: Pick<TPamFolderDALFactory, "find">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gatewayV2Service: Pick<
@@ -41,6 +50,8 @@ export type TPamResourceServiceFactory = ReturnType<typeof pamResourceServiceFac
export const pamResourceServiceFactory = ({
pamResourceDAL,
+ pamAccountDAL,
+ pamFolderDAL,
permissionService,
kmsService,
gatewayV2Service
@@ -58,7 +69,56 @@ export const pamResourceServiceFactory = ({
actionProjectType: ActionProjectType.PAM
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
+ const canReadResources = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
+
+ if (!canReadResources) {
+ // Check if user can read at least one account in this resource
+ const { accounts } = await pamAccountDAL.findByProjectIdWithResourceDetails({
+ projectId: resource.projectId,
+ accountView: PamAccountView.Flat,
+ filterResourceIds: [id]
+ });
+
+ // Compute folder paths for account path resolution
+ const uniqueFolderIds = [...new Set(accounts.filter((a) => a.folderId).map((a) => a.folderId!))];
+ const folderPathMap: Record<string, string> = {};
+
+ if (uniqueFolderIds.length > 0) {
+ const allFolders = await pamFolderDAL.find({ projectId: resource.projectId });
+ const folderMap = new Map(allFolders.map((f) => [f.id, f]));
+
+ for (const folderId of uniqueFolderIds) {
+ const pathSegments: string[] = [];
+ let currentId: string | null | undefined = folderId;
+ while (currentId) {
+ const folder = folderMap.get(currentId);
+ if (!folder) break;
+ pathSegments.unshift(folder.name);
+ currentId = folder.parentId;
+ }
+ folderPathMap[folderId] = `/${pathSegments.join("/")}`;
+ }
+ }
+
+ const hasAccountAccess = accounts.some((account) => {
+ const accountPath = account.folderId ? folderPathMap[account.folderId] || "/" : "/";
+ return permission.can(
+ ProjectPermissionPamAccountActions.Read,
+ subject(ProjectPermissionSub.PamAccounts, {
+ resourceName: resource.name,
+ accountName: account.name,
+ accountPath
+ })
+ );
+ });
+
+ if (!hasAccountAccess) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionActions.Read,
+ ProjectPermissionSub.PamResources
+ );
+ }
+ }
if (resource.resourceType !== resourceType) {
throw new BadRequestError({
@@ -275,12 +335,95 @@ export const pamResourceServiceFactory = ({
actionProjectType: ActionProjectType.PAM
});
- ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
+ const canReadResources = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources);
+
+ if (canReadResources) {
+ const { resources, totalCount } = await pamResourceDAL.findByProjectId({ projectId, ...params });
+ return {
+ resources: await Promise.all(resources.map((resource) => decryptResource(resource, projectId, kmsService))),
+ totalCount
+ };
+ }
+
+ // Fallback: include resources where the user can read at least one account.
+ // Fetch all resources (without pagination) so we can filter by account-level access
+ // and then apply pagination on the permitted results.
+ const { resources: allResources } = await pamResourceDAL.findByProjectId({
+ projectId,
+ search: params.search,
+ orderBy: params.orderBy,
+ orderDirection: params.orderDirection,
+ filterResourceTypes: params.filterResourceTypes
+ });
+
+ if (allResources.length === 0) {
+ return { resources: [], totalCount: 0 };
+ }
+
+ // Fetch all accounts for the project (flat view, no pagination) for permission checking
+ const { accounts: allAccounts } = await pamAccountDAL.findByProjectIdWithResourceDetails({
+ projectId,
+ accountView: PamAccountView.Flat
+ });
+
+ if (allAccounts.length === 0) {
+ return { resources: [], totalCount: 0 };
+ }
+
+ // Compute folder paths so we can build the accountPath for each account
+ const uniqueFolderIds = [...new Set(allAccounts.filter((a) => a.folderId).map((a) => a.folderId!))];
+ const folderPathMap: Record<string, string> = {};
+
+ if (uniqueFolderIds.length > 0) {
+ const allFolders = await pamFolderDAL.find({ projectId });
+ const folderMap = new Map(allFolders.map((f) => [f.id, f]));
+
+ for (const folderId of uniqueFolderIds) {
+ const pathSegments: string[] = [];
+ let currentId: string | null | undefined = folderId;
+ while (currentId) {
+ const folder = folderMap.get(currentId);
+ if (!folder) break;
+ pathSegments.unshift(folder.name);
+ currentId = folder.parentId;
+ }
+ folderPathMap[folderId] = `/${pathSegments.join("/")}`;
+ }
+ }
+
+ // Group accounts by resource ID
+ const accountsByResourceId = new Map<string, Array<{ accountName: string; accountPath: string }>>();
+ for (const account of allAccounts) {
+ const accountPath = account.folderId ? folderPathMap[account.folderId] || "/" : "/";
+ const existing = accountsByResourceId.get(account.resourceId) || [];
+ existing.push({ accountName: account.name, accountPath });
+ accountsByResourceId.set(account.resourceId, existing);
+ }
+
+ // Filter to only resources where the user can read at least one account
+ const permittedResources = allResources.filter((resource) => {
+ const accounts = accountsByResourceId.get(resource.id) || [];
+ return accounts.some((account) =>
+ permission.can(
+ ProjectPermissionPamAccountActions.Read,
+ subject(ProjectPermissionSub.PamAccounts, {
+ resourceName: resource.name,
+ accountName: account.accountName,
+ accountPath: account.accountPath
+ })
+ )
+ );
+ });
- const { resources, totalCount } = await pamResourceDAL.findByProjectId({ projectId, ...params });
+ const totalCount = permittedResources.length;
+ const offset = params.offset || 0;
+ const limit = params.limit || 100;
+ const paginatedResources = permittedResources.slice(offset, offset + limit);
return {
- resources: await Promise.all(resources.map((resource) => decryptResource(resource, projectId, kmsService))),
+ resources: await Promise.all(
+ paginatedResources.map((resource) => decryptResource(resource, projectId, kmsService))
+ ),
totalCount
};
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 66b66e10ae..55a6b58260 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2551,6 +2551,8 @@ export const registerRoutes = async (
const pamResourceService = pamResourceServiceFactory({
pamResourceDAL,
+ pamAccountDAL,
+ pamFolderDAL,
permissionService,
kmsService,
gatewayV2Service
diff --git a/frontend/src/pages/pam/PamResourcesPage/PamResourcesPage.tsx b/frontend/src/pages/pam/PamResourcesPage/PamResourcesPage.tsx
index 2f00c90d84..b6fad67205 100644
--- a/frontend/src/pages/pam/PamResourcesPage/PamResourcesPage.tsx
+++ b/frontend/src/pages/pam/PamResourcesPage/PamResourcesPage.tsx
@@ -1,10 +1,7 @@
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
-import { ProjectPermissionCan } from "@app/components/permissions";
import { PageHeader } from "@app/components/v2";
-import { ProjectPermissionSub } from "@app/context";
-import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";
import { ProjectType } from "@app/hooks/api/projects/types";
import { PamResourcesSection } from "./components/PamResourcesSection";
@@ -16,24 +13,18 @@ export const PamResourcesPage = () => {
<Helmet>
<title>{t("common.head-title", { title: "PAM" })}</title>
</Helmet>
- <ProjectPermissionCan
- renderGuardBanner
- I={ProjectPermissionPamAccountActions.Read}
- a={ProjectPermissionSub.PamResources}
- >
- <div className="h-full bg-bunker-800">
- <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
- <div className="mx-auto mb-6 w-full max-w-8xl">
- <PageHeader
- scope={ProjectType.PAM}
- title="Resources"
- description="Manage resources such as servers, databases, and more."
- />
- <PamResourcesSection />
- </div>
+ <div className="h-full bg-bunker-800">
+ <div className="mx-auto flex flex-col justify-between bg-bunker-800 text-white">
+ <div className="mx-auto mb-6 w-full max-w-8xl">
+ <PageHeader
+ scope={ProjectType.PAM}
+ title="Resources"
+ description="Manage resources such as servers, databases, and more."
+ />
+ <PamResourcesSection />
</div>
</div>
- </ProjectPermissionCan>
+ </div>
</>
);
};