From 433c16c732bde8e8022d72fdcd9937c2e9816e57 Mon Sep 17 00:00:00 2001 From: x032205 Date: Fri, 7 Nov 2025 05:44:38 -0500 Subject: [PATCH 001/108] pam: accounts table server-side filter, search, pagination --- .../pam-account-routers/pam-account-router.ts | 42 ++- .../services/pam-account/pam-account-dal.ts | 114 ++++++-- .../pam-account/pam-account-service.ts | 115 ++++++-- .../services/pam-account/pam-account-types.ts | 21 ++ .../ee/services/pam-folder/pam-folder-dal.ts | 99 ++++++- frontend/src/hooks/api/pam/enums.ts | 9 + frontend/src/hooks/api/pam/mutations.tsx | 12 +- frontend/src/hooks/api/pam/queries.tsx | 32 ++- frontend/src/hooks/api/pam/types/index.ts | 14 +- .../components/AccountViewToggle.tsx | 18 +- .../components/PamAccountsSection.tsx | 16 +- .../components/PamAccountsTable.tsx | 263 ++++++++---------- .../src/pages/pam/PamAccountsPage/route.tsx | 5 +- 13 files changed, 514 insertions(+), 246 deletions(-) diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts index 286e0896f..626daa898 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts @@ -2,11 +2,14 @@ import { z } from "zod"; import { PamFoldersSchema } from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { PamAccountOrderBy, PamAccountView } from "@app/ee/services/pam-account/pam-account-types"; import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; import { BadRequestError } from "@app/lib/errors"; +import { removeTrailingSlash } from "@app/lib/fn"; import { ms } from "@app/lib/ms"; +import { OrderByDirection } from "@app/lib/types"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; @@ -26,33 +29,58 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => { schema: { description: "List PAM accounts", querystring: z.object({ - projectId: z.string().uuid() + projectId: z.string().uuid(), + accountPath: z.string().trim().default("/").transform(removeTrailingSlash), + accountView: z.nativeEnum(PamAccountView).default(PamAccountView.Flat), + offset: z.coerce.number().min(0).default(0), + limit: z.coerce.number().min(1).max(100).default(100), + orderBy: z.nativeEnum(PamAccountOrderBy).default(PamAccountOrderBy.Name), + orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC), + search: z.string().trim().optional() }), response: { 200: z.object({ accounts: SanitizedAccountSchema.array(), - folders: PamFoldersSchema.array() + folders: PamFoldersSchema.array(), + totalCount: z.number().default(0), + folderId: z.string().optional(), + folderPaths: z.record(z.string(), z.string()) }) } }, onRequest: verifyAuth([AuthMode.JWT]), handler: async (req) => { - const response = await server.services.pamAccount.list(req.query.projectId, req.permission); + const { projectId, accountPath, accountView, limit, offset, search, orderBy, orderDirection } = req.query; + + const { accounts, folders, totalCount, folderId, folderPaths } = await server.services.pamAccount.list({ + actorId: req.permission.id, + actor: req.permission.type, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + projectId, + accountPath, + accountView, + limit, + offset, + search, + orderBy, + orderDirection + }); await server.services.auditLog.createAuditLog({ ...req.auditLogInfo, orgId: req.permission.orgId, - projectId: req.query.projectId, + projectId, event: { type: EventType.PAM_ACCOUNT_LIST, metadata: { - accountCount: response.accounts.length, - folderCount: response.folders.length + accountCount: accounts.length, + folderCount: folders.length } } }); - return response; + return { accounts, folders, totalCount, folderId, folderPaths }; } }); diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts index 6ef7df76e..562567172 100644 --- a/backend/src/ee/services/pam-account/pam-account-dal.ts +++ b/backend/src/ee/services/pam-account/pam-account-dal.ts @@ -1,46 +1,100 @@ import { Knex } from "knex"; import { TDbClient } from "@app/db"; -import { TableName, TPamAccounts } from "@app/db/schemas"; -import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex"; +import { TableName } from "@app/db/schemas"; +import { DatabaseError } from "@app/lib/errors"; +import { ormify, selectAllTableCols } from "@app/lib/knex"; +import { OrderByDirection } from "@app/lib/types"; + +import { PamAccountOrderBy, PamAccountView } from "./pam-account-types"; export type TPamAccountDALFactory = ReturnType; -type PamAccountFindFilter = Parameters>[0]; - export const pamAccountDALFactory = (db: TDbClient) => { const orm = ormify(db, TableName.PamAccount); - const findWithResourceDetails = async (filter: PamAccountFindFilter, tx?: Knex) => { - const query = (tx || db.replicaNode())(TableName.PamAccount) - .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`) - .select(selectAllTableCols(TableName.PamAccount)) - .select( + const findByProjectIdWithResourceDetails = async ( + { + projectId, + folderId, + accountView = PamAccountView.Nested, + search, + limit, + offset = 0, + orderBy = PamAccountOrderBy.Name, + orderDirection = OrderByDirection.ASC + }: { + projectId: string; + folderId?: string | null; + accountView?: PamAccountView; + search?: string; + limit?: number; + offset?: number; + orderBy?: PamAccountOrderBy; + orderDirection?: OrderByDirection; + }, + tx?: Knex + ) => { + try { + const dbInstance = tx || db.replicaNode(); + const query = dbInstance(TableName.PamAccount) + .leftJoin(TableName.PamResource, `${TableName.PamAccount}.resourceId`, `${TableName.PamResource}.id`) + .where(`${TableName.PamAccount}.projectId`, projectId); + + if (accountView === PamAccountView.Nested) { + if (folderId) { + void query.where(`${TableName.PamAccount}.folderId`, folderId); + } else { + void query.whereNull(`${TableName.PamAccount}.folderId`); + } + } + + if (search) { + void query.where((q) => { + void q + .whereILike(`${TableName.PamAccount}.name`, `%${search}%`) + .orWhereILike(`${TableName.PamResource}.name`, `%${search}%`) + .orWhereILike(`${TableName.PamAccount}.description`, `%${search}%`); + }); + } + + const countQuery = query.clone().count("*", { as: "count" }).first(); + + void query.select(selectAllTableCols(TableName.PamAccount)).select( // resource db.ref("name").withSchema(TableName.PamResource).as("resourceName"), db.ref("resourceType").withSchema(TableName.PamResource), db.ref("encryptedRotationAccountCredentials").withSchema(TableName.PamResource) ); - if (filter) { - /* eslint-disable @typescript-eslint/no-misused-promises */ - void query.where(buildFindFilter(prependTableNameToFindFilter(TableName.PamAccount, filter))); + const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC"; + + void query.orderByRaw(`${TableName.PamAccount}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]); + + if (typeof limit === "number") { + void query.limit(limit).offset(offset); + } + + const [results, countResult] = await Promise.all([query, countQuery]); + const totalCount = Number(countResult?.count || 0); + + const accounts = results.map( + // @ts-expect-error resourceName, resourceType, encryptedRotationAccountCredentials are from joined table + ({ resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, ...account }) => ({ + ...account, + resourceId, + resource: { + id: resourceId, + name: resourceName as string, + resourceType, + encryptedRotationAccountCredentials + } + }) + ); + return { accounts, totalCount }; + } catch (error) { + throw new DatabaseError({ error, name: "Find PAM accounts with resource details" }); } - - const accounts = await query; - - return accounts.map( - ({ resourceId, resourceName, resourceType, encryptedRotationAccountCredentials, ...account }) => ({ - ...account, - resourceId, - resource: { - id: resourceId, - name: resourceName, - resourceType, - encryptedRotationAccountCredentials - } - }) - ); }; const findAccountsDueForRotation = async (tx?: Knex) => { @@ -59,5 +113,9 @@ export const pamAccountDALFactory = (db: TDbClient) => { return accounts; }; - return { ...orm, findWithResourceDetails, findAccountsDueForRotation }; + return { + ...orm, + findByProjectIdWithResourceDetails, + findAccountsDueForRotation + }; }; diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts index 2f66d28d7..bfc6c7e7f 100644 --- a/backend/src/ee/services/pam-account/pam-account-service.ts +++ b/backend/src/ee/services/pam-account/pam-account-service.ts @@ -1,6 +1,6 @@ import { ForbiddenError, subject } from "@casl/ability"; -import { ActionProjectType, OrganizationActionScope, TPamAccounts, TPamResources } from "@app/db/schemas"; +import { ActionProjectType, OrganizationActionScope, TPamAccounts, TPamFolders, TPamResources } from "@app/db/schemas"; import { PAM_RESOURCE_FACTORY_MAP } from "@app/ee/services/pam-resource/pam-resource-factory"; import { decryptResource, decryptResourceConnectionDetails } from "@app/ee/services/pam-resource/pam-resource-fns"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; @@ -32,7 +32,13 @@ import { PamSessionStatus } from "../pam-session/pam-session-enums"; import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission"; import { TPamAccountDALFactory } from "./pam-account-dal"; import { decryptAccount, decryptAccountCredentials, encryptAccountCredentials } from "./pam-account-fns"; -import { TAccessAccountDTO, TCreateAccountDTO, TUpdateAccountDTO } from "./pam-account-types"; +import { + PamAccountView, + TAccessAccountDTO, + TCreateAccountDTO, + TListAccountsDTO, + TUpdateAccountDTO +} from "./pam-account-types"; type TPamAccountServiceFactoryDep = { pamResourceDAL: TPamResourceDALFactory; @@ -334,21 +340,86 @@ export const pamAccountServiceFactory = ({ }; }; - const list = async (projectId: string, actor: OrgServiceActor) => { + const list = async ({ + projectId, + accountPath, + accountView, + actor, + actorId, + actorAuthMethod, + actorOrgId, + ...params + }: TListAccountsDTO) => { const { permission } = await permissionService.getProjectPermission({ - actor: actor.type, - actorAuthMethod: actor.authMethod, - actorId: actor.id, - actorOrgId: actor.orgId, + actor, + actorId, projectId, + actorAuthMethod, + actorOrgId, actionProjectType: ActionProjectType.PAM }); - const accountsWithResourceDetails = await pamAccountDAL.findWithResourceDetails({ projectId }); + const limit = params.limit || 20; + const offset = params.offset || 0; const canReadFolders = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.PamFolders); - const folders = canReadFolders ? await pamFolderDAL.find({ projectId }) : []; + const folder = accountPath === "/" ? null : await pamFolderDAL.findByPath(projectId, accountPath); + if (accountPath !== "/" && !folder) { + return { accounts: [], folders: [], totalCount: 0, folderPaths: {} }; + } + const folderId = folder?.id; + + let totalFolderCount = 0; + if (canReadFolders && accountView === PamAccountView.Nested) { + const { totalCount } = await pamFolderDAL.findByProjectId({ + projectId, + parentId: folderId + }); + totalFolderCount = totalCount; + } + const { totalCount: totalAccountCount } = await pamAccountDAL.findByProjectIdWithResourceDetails({ + projectId, + folderId, + accountView + }); + + const totalCount = totalFolderCount + totalAccountCount; + + let folders: TPamFolders[] = []; + if (canReadFolders && accountView === PamAccountView.Nested && offset < totalFolderCount) { + const folderLimit = Math.min(limit, totalFolderCount - offset); + const { folders: foldersResp } = await pamFolderDAL.findByProjectId({ + projectId, + parentId: folderId, + limit: folderLimit, + offset, + search: params.search, + orderBy: params.orderBy, + orderDirection: params.orderDirection + }); + + folders = foldersResp; + } + + let accountsWithResourceDetails: Awaited< + ReturnType + >["accounts"] = []; + const accountsToFetch = limit - folders.length; + if (accountsToFetch > 0) { + const accountOffset = Math.max(0, offset - totalFolderCount); + const { accounts: accountsResp } = await pamAccountDAL.findByProjectIdWithResourceDetails({ + projectId, + folderId, + accountView, + offset: accountOffset, + limit: accountsToFetch, + search: params.search, + orderBy: params.orderBy, + orderDirection: params.orderDirection + }); + accountsWithResourceDetails = accountsResp; + } const decryptedAndPermittedAccounts: Array< TPamAccounts & { @@ -359,12 +430,6 @@ export const pamAccountServiceFactory = ({ > = []; for await (const account of accountsWithResourceDetails) { - const accountPath = await getFullPamFolderPath({ - pamFolderDAL, - folderId: account.folderId, - projectId: account.projectId - }); - // Check permission for each individual account if ( permission.can( @@ -391,9 +456,27 @@ export const pamAccountServiceFactory = ({ } } + const folderPaths: Record = {}; + const accountFolderIds = [ + ...new Set(decryptedAndPermittedAccounts.flatMap((a) => (a.folderId ? [a.folderId] : []))) + ]; + + await Promise.all( + accountFolderIds.map(async (fId) => { + folderPaths[fId] = await getFullPamFolderPath({ + pamFolderDAL, + folderId: fId, + projectId + }); + }) + ); + return { accounts: decryptedAndPermittedAccounts, - folders + folders, + totalCount, + folderId, + folderPaths }; }; diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts index 4bbccc6fa..775ef1f78 100644 --- a/backend/src/ee/services/pam-account/pam-account-types.ts +++ b/backend/src/ee/services/pam-account/pam-account-types.ts @@ -1,3 +1,5 @@ +import { OrderByDirection, TProjectPermission } from "@app/lib/types"; + import { TPamAccount } from "../pam-resource/pam-resource-types"; // DTOs @@ -18,3 +20,22 @@ export type TAccessAccountDTO = { actorUserAgent: string; duration: number; }; + +export type TListAccountsDTO = { + accountPath: string; + accountView: PamAccountView; + search?: string; + orderBy?: PamAccountOrderBy; + orderDirection?: OrderByDirection; + limit?: number; + offset?: number; +} & TProjectPermission; + +export enum PamAccountOrderBy { + Name = "name" +} + +export enum PamAccountView { + Flat = "flat", + Nested = "nested" +} diff --git a/backend/src/ee/services/pam-folder/pam-folder-dal.ts b/backend/src/ee/services/pam-folder/pam-folder-dal.ts index aa334618d..9d0ca6cd2 100644 --- a/backend/src/ee/services/pam-folder/pam-folder-dal.ts +++ b/backend/src/ee/services/pam-folder/pam-folder-dal.ts @@ -1,9 +1,104 @@ +import { Knex } from "knex"; + import { TDbClient } from "@app/db"; import { TableName } from "@app/db/schemas"; -import { ormify } from "@app/lib/knex"; +import { DatabaseError } from "@app/lib/errors"; +import { ormify, selectAllTableCols } from "@app/lib/knex"; +import { OrderByDirection } from "@app/lib/types"; + +import { PamAccountOrderBy } from "../pam-account/pam-account-types"; export type TPamFolderDALFactory = ReturnType; export const pamFolderDALFactory = (db: TDbClient) => { const orm = ormify(db, TableName.PamFolder); - return { ...orm }; + + const findByProjectId = async ( + { + projectId, + parentId, + search, + limit, + offset = 0, + orderBy = PamAccountOrderBy.Name, + orderDirection = OrderByDirection.ASC + }: { + projectId: string; + parentId?: string | null; + search?: string; + limit?: number; + offset?: number; + orderBy?: PamAccountOrderBy; + orderDirection?: OrderByDirection; + }, + tx?: Knex + ) => { + try { + const dbInstance = tx || db.replicaNode(); + const query = dbInstance(TableName.PamFolder).where(`${TableName.PamFolder}.projectId`, projectId); + + if (parentId) { + void query.where(`${TableName.PamFolder}.parentId`, parentId); + } else { + void query.whereNull(`${TableName.PamFolder}.parentId`); + } + + if (search) { + void query.whereILike(`${TableName.PamFolder}.name`, `%${search}%`); + } + + const countQuery = query.clone().count("*", { as: "count" }).first(); + + void query.select(selectAllTableCols(TableName.PamFolder)); + const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC"; + + void query.orderByRaw(`${TableName.PamFolder}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]); + + if (typeof limit === "number") { + void query.limit(limit).offset(offset); + } + + const [folders, countResult] = await Promise.all([query, countQuery]); + const totalCount = Number(countResult?.count || 0); + + return { folders, totalCount }; + } catch (error) { + throw new DatabaseError({ error, name: "Find PAM folders" }); + } + }; + + const findByPath = async (projectId: string, path: string, tx?: Knex) => { + try { + const dbInstance = tx || db.replicaNode(); + const pathSegments = path.split("/").filter(Boolean); + + let parentId: string | null = null; + let currentFolder: Awaited> | undefined; + + for await (const segment of pathSegments) { + const query = dbInstance(TableName.PamFolder) + .where(`${TableName.PamFolder}.projectId`, projectId) + .where(`${TableName.PamFolder}.name`, segment); + + if (parentId) { + void query.where(`${TableName.PamFolder}.parentId`, parentId); + } else { + void query.whereNull(`${TableName.PamFolder}.parentId`); + } + + currentFolder = await query.first(); + + if (!currentFolder) { + return undefined; + } + + parentId = currentFolder.id; + } + + return currentFolder; + } catch (error) { + throw new DatabaseError({ error, name: "Find PAM folder by path" }); + } + }; + + return { ...orm, findByProjectId, findByPath }; }; diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts index 0684f6073..bd5779487 100644 --- a/frontend/src/hooks/api/pam/enums.ts +++ b/frontend/src/hooks/api/pam/enums.ts @@ -12,3 +12,12 @@ export enum PamSessionStatus { Ended = "ended", Terminated = "terminated" } + +export enum PamAccountOrderBy { + Name = "name" +} + +export enum PamAccountView { + Flat = "flat", + Nested = "nested" +} diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx index 99a89b425..e6ee62e02 100644 --- a/frontend/src/hooks/api/pam/mutations.tsx +++ b/frontend/src/hooks/api/pam/mutations.tsx @@ -82,7 +82,7 @@ export const useCreatePamAccount = () => { return data.account; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; @@ -99,7 +99,7 @@ export const useUpdatePamAccount = () => { return data.account; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; @@ -115,7 +115,7 @@ export const useDeletePamAccount = () => { return data.account; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; @@ -130,7 +130,7 @@ export const useCreatePamFolder = () => { return data.folder; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; @@ -147,7 +147,7 @@ export const useUpdatePamFolder = () => { return data.folder; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; @@ -163,7 +163,7 @@ export const useDeletePamFolder = () => { return data.folder; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listAccounts({ projectId }) }); } }); }; diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx index 6339b4761..08861d1e2 100644 --- a/frontend/src/hooks/api/pam/queries.tsx +++ b/frontend/src/hooks/api/pam/queries.tsx @@ -4,7 +4,7 @@ import { apiRequest } from "@app/config/request"; import { TPamResourceOption } from "./types/resource-options"; import { PamResourceType } from "./enums"; -import { TPamAccount, TPamFolder, TPamResource, TPamSession } from "./types"; +import { TListPamAccountsDTO, TPamAccount, TPamFolder, TPamResource, TPamSession } from "./types"; export const pamKeys = { all: ["pam"] as const, @@ -19,7 +19,12 @@ export const pamKeys = { resourceType, resourceId ], - listAccounts: (projectId: string) => [...pamKeys.account(), "list", projectId], + listAccounts: ({ projectId, ...params }: TListPamAccountsDTO) => [ + ...pamKeys.account(), + "list", + projectId, + params + ], getSession: (sessionId: string) => [...pamKeys.session(), "get", sessionId], listSessions: (projectId: string) => [...pamKeys.session(), "list", projectId] }; @@ -98,25 +103,32 @@ export const useGetPamResourceById = ( }; // Accounts +type TListPamAccountsResponse = { + accounts: TPamAccount[]; + folders: TPamFolder[]; + totalCount: number; + folderId?: string; + folderPaths: Record; +}; + export const useListPamAccounts = ( - projectId: string, + params: TListPamAccountsDTO, options?: Omit< UseQueryOptions< - { accounts: TPamAccount[]; folders: TPamFolder[] }, + TListPamAccountsResponse, unknown, - { accounts: TPamAccount[]; folders: TPamFolder[] }, + TListPamAccountsResponse, ReturnType >, "queryKey" | "queryFn" > ) => { return useQuery({ - queryKey: pamKeys.listAccounts(projectId), + queryKey: pamKeys.listAccounts(params), queryFn: async () => { - const { data } = await apiRequest.get<{ accounts: TPamAccount[]; folders: TPamFolder[] }>( - "/api/v1/pam/accounts", - { params: { projectId } } - ); + const { data } = await apiRequest.get("/api/v1/pam/accounts", { + params + }); return data; }, diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts index 1b1890cbd..0b91cb9b0 100644 --- a/frontend/src/hooks/api/pam/types/index.ts +++ b/frontend/src/hooks/api/pam/types/index.ts @@ -1,4 +1,5 @@ -import { PamResourceType, PamSessionStatus } from "../enums"; +import { OrderByDirection } from "../../generic/types"; +import { PamAccountOrderBy, PamAccountView, PamResourceType, PamSessionStatus } from "../enums"; import { TMySQLAccount, TMySQLResource } from "./mysql-resource"; import { TPostgresAccount, TPostgresResource } from "./postgres-resource"; @@ -63,6 +64,17 @@ export type TDeletePamResourceDTO = { }; // Account DTOs +export type TListPamAccountsDTO = { + projectId: string; + accountPath?: string | null; + accountView?: PamAccountView; + offset?: number; + limit?: number; + orderBy?: PamAccountOrderBy; + orderDirection?: OrderByDirection; + search?: string; +}; + export type TCreatePamAccountDTO = Pick< TPamAccount, "name" | "description" | "credentials" | "projectId" | "resourceId" | "folderId" diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AccountViewToggle.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AccountViewToggle.tsx index 92b2f7859..51e568551 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/AccountViewToggle.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/AccountViewToggle.tsx @@ -1,13 +1,9 @@ import { Button } from "@app/components/v2"; - -export enum AccountView { - Flat = "flat", - Nested = "nested" -} +import { PamAccountView } from "@app/hooks/api/pam"; type Props = { - value: AccountView; - onChange: (value: AccountView) => void; + value: PamAccountView; + onChange: (value: PamAccountView) => void; }; export const AccountViewToggle = ({ value, onChange }: Props) => { @@ -16,11 +12,11 @@ export const AccountViewToggle = ({ value, onChange }: Props) => { - {accountView !== AccountView.Flat && ( + {accountView !== PamAccountView.Flat && ( handlePopUpToggle("misc", isOpen)} @@ -414,11 +378,11 @@ export const PamAccountsTable = ({ accounts, folders, projectId }: Props) => { Accounts handleSort(OrderBy.Name)} + onClick={() => handleSort(PamAccountOrderBy.Name)} > - + @@ -426,45 +390,48 @@ export const PamAccountsTable = ({ accounts, folders, projectId }: Props) => { - {accountView !== AccountView.Flat && - foldersToRender.map((folder) => ( - handleFolderClick(folder)} - onUpdate={(e) => handlePopUpOpen("updateFolder", e)} - onDelete={(e) => handlePopUpOpen("deleteFolder", e)} - /> - ))} - {currentPageData.map((account) => ( - { - handlePopUpOpen("accessAccount", e); - }} - onUpdate={(e) => handlePopUpOpen("updateAccount", e)} - onDelete={(e) => handlePopUpOpen("deleteAccount", e)} - /> - ))} + {isLoading && } + {!isLoading && ( + <> + {accountView !== PamAccountView.Flat && + foldersToRender.map((folder) => ( + handleFolderClick(folder)} + onUpdate={(e) => handlePopUpOpen("updateFolder", e)} + onDelete={(e) => handlePopUpOpen("deleteFolder", e)} + /> + ))} + {filteredAccounts.map((account) => ( + { + handlePopUpOpen("accessAccount", e); + }} + onUpdate={(e) => handlePopUpOpen("updateAccount", e)} + onDelete={(e) => handlePopUpOpen("deleteAccount", e)} + /> + ))} + + )} - {Boolean(filteredAccounts.length) && ( + {Boolean(totalCount) && !isLoading && ( setPage(newPage)} + onChangePerPage={handlePerPageChange} /> )} - {isContentEmpty && ( + {!isLoading && isContentEmpty && ( { isOpen={popUp.addFolder.isOpen} onOpenChange={(isOpen) => handlePopUpToggle("addFolder", isOpen)} projectId={projectId} - currentFolderId={effectiveFolderIdForFiltering} + currentFolderId={currentFolderId} /> { isOpen={popUp.addAccount.isOpen} onOpenChange={(isOpen) => handlePopUpToggle("addAccount", isOpen)} projectId={projectId} - currentFolderId={effectiveFolderIdForFiltering} + currentFolderId={currentFolderId} /> ); diff --git a/frontend/src/pages/pam/PamAccountsPage/route.tsx b/frontend/src/pages/pam/PamAccountsPage/route.tsx index 7fbf81b45..65a8c567e 100644 --- a/frontend/src/pages/pam/PamAccountsPage/route.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/route.tsx @@ -2,12 +2,13 @@ import { createFileRoute, linkOptions, stripSearchParams } from "@tanstack/react import { zodValidator } from "@tanstack/zod-adapter"; import { z } from "zod"; -import { AccountView } from "./components/AccountViewToggle"; +import { PamAccountView } from "@app/hooks/api/pam"; + import { PamAccountsPage } from "./PamAccountsPage"; const PamAccountsPageQueryParamsSchema = z.object({ search: z.string().optional(), - accountView: z.nativeEnum(AccountView).optional(), + accountView: z.nativeEnum(PamAccountView).optional(), accountPath: z.string().catch("/") }); From 87f30328134579f663e2618837f9cbd3dfe2f814 Mon Sep 17 00:00:00 2001 From: x032205 Date: Fri, 7 Nov 2025 16:54:24 -0500 Subject: [PATCH 002/108] pam: resources table server-side filter, search, pagination --- .../pam-resource-router.ts | 31 +++- .../services/pam-resource/pam-resource-dal.ts | 57 +++++++- .../pam-resource/pam-resource-enums.ts | 4 + .../pam-resource/pam-resource-service.ts | 17 +-- .../pam-resource/pam-resource-types.ts | 12 +- frontend/src/hooks/api/pam/enums.ts | 7 + frontend/src/hooks/api/pam/mutations.tsx | 6 +- frontend/src/hooks/api/pam/queries.tsx | 38 +++-- frontend/src/hooks/api/pam/types/index.ts | 17 ++- .../components/ResourceSelect.tsx | 32 +++-- .../components/PamResourcesSection.tsx | 10 +- .../components/PamResourcesTable.tsx | 135 +++++++++--------- 12 files changed, 251 insertions(+), 115 deletions(-) diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts index 6563c86c7..255e11aa8 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts @@ -5,10 +5,12 @@ import { MySQLResourceListItemSchema, SanitizedMySQLResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; +import { PamResourceOrderBy } from "@app/ee/services/pam-resource/pam-resource-enums"; import { PostgresResourceListItemSchema, SanitizedPostgresResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { OrderByDirection } from "@app/lib/types"; import { readLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; @@ -52,17 +54,36 @@ export const registerPamResourceRouter = async (server: FastifyZodProvider) => { schema: { description: "List PAM resources", querystring: z.object({ - projectId: z.string().uuid() + projectId: z.string().uuid(), + offset: z.coerce.number().min(0).default(0), + limit: z.coerce.number().min(1).max(100).default(100), + orderBy: z.nativeEnum(PamResourceOrderBy).default(PamResourceOrderBy.Name), + orderDirection: z.nativeEnum(OrderByDirection).default(OrderByDirection.ASC), + search: z.string().trim().optional() }), response: { 200: z.object({ - resources: SanitizedResourceSchema.array() + resources: SanitizedResourceSchema.array(), + totalCount: z.number().default(0) }) } }, onRequest: verifyAuth([AuthMode.JWT]), handler: async (req) => { - const response = await server.services.pamResource.list(req.query.projectId, req.permission); + const { projectId, limit, offset, search, orderBy, orderDirection } = req.query; + + const { resources, totalCount } = await server.services.pamResource.list({ + actorId: req.permission.id, + actor: req.permission.type, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + projectId, + limit, + offset, + search, + orderBy, + orderDirection + }); await server.services.auditLog.createAuditLog({ ...req.auditLogInfo, @@ -71,12 +92,12 @@ export const registerPamResourceRouter = async (server: FastifyZodProvider) => { event: { type: EventType.PAM_RESOURCE_LIST, metadata: { - count: response.resources.length + count: totalCount } } }); - return response; + return { resources, totalCount }; } }); }; diff --git a/backend/src/ee/services/pam-resource/pam-resource-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-dal.ts index 1a408ca27..3b7e17499 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-dal.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-dal.ts @@ -2,7 +2,11 @@ import { Knex } from "knex"; import { TDbClient } from "@app/db"; import { TableName } from "@app/db/schemas"; +import { DatabaseError } from "@app/lib/errors"; import { ormify, selectAllTableCols } from "@app/lib/knex"; +import { OrderByDirection } from "@app/lib/types"; + +import { PamResourceOrderBy } from "./pam-resource-enums"; export type TPamResourceDALFactory = ReturnType; export const pamResourceDALFactory = (db: TDbClient) => { @@ -20,5 +24,56 @@ export const pamResourceDALFactory = (db: TDbClient) => { return doc; }; - return { ...orm, findById }; + const findByProjectId = async ( + { + projectId, + search, + limit, + offset = 0, + orderBy = PamResourceOrderBy.Name, + orderDirection = OrderByDirection.ASC + }: { + projectId: string; + search?: string; + limit?: number; + offset?: number; + orderBy?: PamResourceOrderBy; + orderDirection?: OrderByDirection; + }, + tx?: Knex + ) => { + try { + const dbInstance = tx || db.replicaNode(); + const query = dbInstance(TableName.PamResource).where(`${TableName.PamResource}.projectId`, projectId); + + if (search) { + void query.where((q) => { + void q + .whereILike(`${TableName.PamResource}.name`, `%${search}%`) + .orWhereILike(`${TableName.PamResource}.resourceType`, `%${search}%`); + }); + } + + const countQuery = query.clone().count("*", { as: "count" }).first(); + + void query.select(selectAllTableCols(TableName.PamResource)); + + const direction = orderDirection === OrderByDirection.ASC ? "ASC" : "DESC"; + + void query.orderByRaw(`${TableName.PamResource}.?? COLLATE "en-x-icu" ${direction}`, [orderBy]); + + if (typeof limit === "number") { + void query.limit(limit).offset(offset); + } + + const [resources, countResult] = await Promise.all([query, countQuery]); + const totalCount = Number(countResult?.count || 0); + + return { resources, totalCount }; + } catch (error) { + throw new DatabaseError({ error, name: "Find PAM resources" }); + } + }; + + return { ...orm, findById, findByProjectId }; }; diff --git a/backend/src/ee/services/pam-resource/pam-resource-enums.ts b/backend/src/ee/services/pam-resource/pam-resource-enums.ts index dff1cc650..e377b8172 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-enums.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-enums.ts @@ -2,3 +2,7 @@ export enum PamResource { Postgres = "postgres", MySQL = "mysql" } + +export enum PamResourceOrderBy { + Name = "name" +} 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 d97905dbe..f3ab43944 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-service.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts @@ -20,7 +20,7 @@ import { encryptResourceConnectionDetails, listResourceOptions } from "./pam-resource-fns"; -import { TCreateResourceDTO, TUpdateResourceDTO } from "./pam-resource-types"; +import { TCreateResourceDTO, TListResourcesDTO, TUpdateResourceDTO } from "./pam-resource-types"; type TPamResourceServiceFactoryDep = { pamResourceDAL: TPamResourceDALFactory; @@ -268,22 +268,23 @@ export const pamResourceServiceFactory = ({ } }; - const list = async (projectId: string, actor: OrgServiceActor) => { + const list = async ({ projectId, actor, actorId, actorAuthMethod, actorOrgId, ...params }: TListResourcesDTO) => { const { permission } = await permissionService.getProjectPermission({ - actor: actor.type, - actorAuthMethod: actor.authMethod, - actorId: actor.id, - actorOrgId: actor.orgId, + actor, + actorId, + actorAuthMethod, + actorOrgId, projectId, actionProjectType: ActionProjectType.PAM }); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.PamResources); - const resources = await pamResourceDAL.find({ projectId }); + const { resources, totalCount } = await pamResourceDAL.findByProjectId({ projectId, ...params }); return { - resources: await Promise.all(resources.map((resource) => decryptResource(resource, projectId, kmsService))) + resources: await Promise.all(resources.map((resource) => decryptResource(resource, projectId, kmsService))), + totalCount }; }; diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.ts index 1ca9db3e2..8d1f8052b 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-types.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts @@ -1,3 +1,5 @@ +import { OrderByDirection, TProjectPermission } from "@app/lib/types"; + import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service"; import { TMySQLAccount, @@ -5,7 +7,7 @@ import { TMySQLResource, TMySQLResourceConnectionDetails } from "./mysql/mysql-resource-types"; -import { PamResource } from "./pam-resource-enums"; +import { PamResource, PamResourceOrderBy } from "./pam-resource-enums"; import { TPostgresAccount, TPostgresAccountCredentials, @@ -32,6 +34,14 @@ export type TUpdateResourceDTO = Partial = () => Promise; export type TPamResourceFactoryValidateAccountCredentials = ( diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts index bd5779487..d0d88edb8 100644 --- a/frontend/src/hooks/api/pam/enums.ts +++ b/frontend/src/hooks/api/pam/enums.ts @@ -1,3 +1,4 @@ +// Resources export enum PamResourceType { Postgres = "postgres", MySQL = "mysql", @@ -6,6 +7,11 @@ export enum PamResourceType { Kubernetes = "kubernetes" } +export enum PamResourceOrderBy { + Name = "name" +} + +// Sessions export enum PamSessionStatus { Starting = "starting", Active = "active", @@ -13,6 +19,7 @@ export enum PamSessionStatus { Terminated = "terminated" } +// Accounts export enum PamAccountOrderBy { Name = "name" } diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsx index e6ee62e02..c5d6ff05b 100644 --- a/frontend/src/hooks/api/pam/mutations.tsx +++ b/frontend/src/hooks/api/pam/mutations.tsx @@ -31,7 +31,7 @@ export const useCreatePamResource = () => { return data.resource; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listResources(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listResources({ projectId }) }); } }); }; @@ -48,7 +48,7 @@ export const useUpdatePamResource = () => { return data.resource; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listResources(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listResources({ projectId }) }); } }); }; @@ -64,7 +64,7 @@ export const useDeletePamResource = () => { return data.resource; }, onSuccess: ({ projectId }) => { - queryClient.invalidateQueries({ queryKey: pamKeys.listResources(projectId) }); + queryClient.invalidateQueries({ queryKey: pamKeys.listResources({ projectId }) }); } }); }; diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx index 08861d1e2..7fcfb2569 100644 --- a/frontend/src/hooks/api/pam/queries.tsx +++ b/frontend/src/hooks/api/pam/queries.tsx @@ -4,7 +4,14 @@ import { apiRequest } from "@app/config/request"; import { TPamResourceOption } from "./types/resource-options"; import { PamResourceType } from "./enums"; -import { TListPamAccountsDTO, TPamAccount, TPamFolder, TPamResource, TPamSession } from "./types"; +import { + TListPamAccountsDTO, + TListPamResourcesDTO, + TPamAccount, + TPamFolder, + TPamResource, + TPamSession +} from "./types"; export const pamKeys = { all: ["pam"] as const, @@ -12,7 +19,12 @@ export const pamKeys = { account: () => [...pamKeys.all, "account"] as const, session: () => [...pamKeys.all, "session"] as const, listResourceOptions: () => [...pamKeys.resource(), "options"] as const, - listResources: (projectId: string) => [...pamKeys.resource(), "list", projectId], + listResources: ({ projectId, ...params }: TListPamResourcesDTO) => [ + ...pamKeys.resource(), + "list", + projectId, + params + ], getResource: (resourceType: string, resourceId: string) => [ ...pamKeys.resource(), "get", @@ -54,27 +66,31 @@ export const useListPamResourceOptions = ( }); }; +type TListPamResourcesResponse = { + resources: TPamResource[]; + totalCount: number; +}; + export const useListPamResources = ( - projectId: string, + params: TListPamResourcesDTO, options?: Omit< UseQueryOptions< - TPamResource[], + TListPamResourcesResponse, unknown, - TPamResource[], + TListPamResourcesResponse, ReturnType >, "queryKey" | "queryFn" > ) => { return useQuery({ - queryKey: pamKeys.listResources(projectId), + queryKey: pamKeys.listResources(params), queryFn: async () => { - const { data } = await apiRequest.get<{ resources: TPamResource[] }>( - "/api/v1/pam/resources", - { params: { projectId } } - ); + const { data } = await apiRequest.get("/api/v1/pam/resources", { + params + }); - return data.resources; + return data; }, ...options }); diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts index 0b91cb9b0..b7e2c70b0 100644 --- a/frontend/src/hooks/api/pam/types/index.ts +++ b/frontend/src/hooks/api/pam/types/index.ts @@ -1,5 +1,11 @@ import { OrderByDirection } from "../../generic/types"; -import { PamAccountOrderBy, PamAccountView, PamResourceType, PamSessionStatus } from "../enums"; +import { + PamAccountOrderBy, + PamAccountView, + PamResourceOrderBy, + PamResourceType, + PamSessionStatus +} from "../enums"; import { TMySQLAccount, TMySQLResource } from "./mysql-resource"; import { TPostgresAccount, TPostgresResource } from "./postgres-resource"; @@ -46,6 +52,15 @@ export type TPamSession = { }; // Resource DTOs +export type TListPamResourcesDTO = { + projectId: string; + offset?: number; + limit?: number; + orderBy?: PamResourceOrderBy; + orderDirection?: OrderByDirection; + search?: string; +}; + export type TCreatePamResourceDTO = Pick< TPamResource, "name" | "connectionDetails" | "resourceType" | "gatewayId" | "projectId" diff --git a/frontend/src/pages/pam/PamAccountsPage/components/ResourceSelect.tsx b/frontend/src/pages/pam/PamAccountsPage/components/ResourceSelect.tsx index 6c6bcfba6..879167195 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/ResourceSelect.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/ResourceSelect.tsx @@ -1,11 +1,12 @@ +import { useState } from "react"; import { Controller, FormProvider, useForm } from "react-hook-form"; import { SingleValue } from "react-select"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; -import { Button, FilterableSelect, FormControl, ModalClose, Spinner } from "@app/components/v2"; +import { Button, FilterableSelect, FormControl, ModalClose } from "@app/components/v2"; import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context"; -import { usePopUp } from "@app/hooks"; +import { useDebounce, usePopUp } from "@app/hooks"; import { PamResourceType, useListPamResources } from "@app/hooks/api/pam"; import { PamAddResourceModal } from "../../PamResourcesPage/components/PamAddResourceModal"; @@ -28,7 +29,17 @@ type FormData = z.infer; export const ResourceSelect = ({ onSubmit, projectId }: Props) => { const { permission } = useProjectPermission(); - const { isPending, data: resources } = useListPamResources(projectId); + + const [search, setSearch] = useState(""); + const [debouncedSearch] = useDebounce(search, 350); + + const { isPending, data } = useListPamResources({ + projectId, + limit: 100, + search: debouncedSearch + }); + + const resources = data?.resources || []; const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addResource"] as const); @@ -43,15 +54,6 @@ export const ResourceSelect = ({ onSubmit, projectId }: Props) => { ProjectPermissionSub.PamResources ); - if (isPending) { - return ( -
- -

Loading options...

-
- ); - } - return ( <> @@ -65,6 +67,12 @@ export const ResourceSelect = ({ onSubmit, projectId }: Props) => { { + if (actionMeta.action === "input-change") { + setSearch(val); + } + }} onChange={(newValue) => { if ((newValue as SingleValue<{ id: string }>)?.id === "_create") { handlePopUpOpen("addResource"); diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesSection.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesSection.tsx index 41be0a652..dd29c1b21 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesSection.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesSection.tsx @@ -1,17 +1,9 @@ -import { ContentLoader } from "@app/components/v2"; import { useProject } from "@app/context"; -import { useListPamResources } from "@app/hooks/api/pam"; import { PamResourcesTable } from "./PamResourcesTable"; export const PamResourcesSection = () => { const { currentProject } = useProject(); - const { data: resources = [], isPending } = useListPamResources(currentProject.id, { - refetchInterval: 30000 - }); - - if (isPending) return ; - - return ; + return ; }; diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesTable.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesTable.tsx index 2f46a8aca..cb2e35a04 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesTable.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourcesTable.tsx @@ -27,6 +27,7 @@ import { Pagination, Table, TableContainer, + TableSkeleton, TBody, Th, THead, @@ -39,29 +40,34 @@ import { OrgGatewayPermissionActions, OrgPermissionSubjects } from "@app/context/OrgPermissionContext/types"; -import { usePagination, usePopUp, useResetPageHelper } from "@app/hooks"; +import { + getUserTablePreference, + PreferenceKey, + setUserTablePreference +} from "@app/helpers/userTablePreferences"; +import { usePagination, usePopUp } from "@app/hooks"; import { OrderByDirection } from "@app/hooks/api/generic/types"; -import { PAM_RESOURCE_TYPE_MAP, PamResourceType, TPamResource } from "@app/hooks/api/pam"; +import { + PAM_RESOURCE_TYPE_MAP, + PamResourceOrderBy, + PamResourceType, + useListPamResources +} from "@app/hooks/api/pam"; import { PamAddResourceModal } from "./PamAddResourceModal"; import { PamDeleteResourceModal } from "./PamDeleteResourceModal"; import { PamResourceRow } from "./PamResourceRow"; import { PamUpdateResourceModal } from "./PamUpdateResourceModal"; -enum OrderBy { - Name = "name" -} - type Filters = { resourceType: PamResourceType[]; }; type Props = { projectId: string; - resources: TPamResource[]; }; -export const PamResourcesTable = ({ projectId, resources }: Props) => { +export const PamResourcesTable = ({ projectId }: Props) => { const navigate = useNavigate({ from: ROUTE_PATHS.Pam.ResourcesPage.path }); const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([ @@ -80,6 +86,7 @@ export const PamResourcesTable = ({ projectId, resources }: Props) => { const { search, + debouncedSearch, setSearch, setPage, page, @@ -91,51 +98,48 @@ export const PamResourcesTable = ({ projectId, resources }: Props) => { orderBy, setOrderDirection, setOrderBy - } = usePagination(OrderBy.Name, { initPerPage: 20, initSearch }); + } = usePagination(PamResourceOrderBy.Name, { + initPerPage: getUserTablePreference("pamResourcesTable", PreferenceKey.PerPage, 20), + initSearch + }); + + const handlePerPageChange = (newPerPage: number) => { + setPerPage(newPerPage); + setUserTablePreference("pamResourcesTable", PreferenceKey.PerPage, newPerPage); + }; + + const { data, isLoading } = useListPamResources({ + projectId, + offset, + limit: perPage, + search: debouncedSearch, + orderBy, + orderDirection + }); + + const resources = data?.resources || []; + const totalCount = data?.totalCount || 0; const filteredResources = useMemo( () => - resources - .filter((resource) => { - const { name, resourceType } = resource; + resources.filter((resource) => { + const { name, resourceType } = resource; - if (filters.resourceType.length && !filters.resourceType.includes(resourceType)) { - return false; - } + if (filters.resourceType.length && !filters.resourceType.includes(resourceType)) { + return false; + } - const searchValue = search.trim().toLowerCase(); + const searchValue = search.trim().toLowerCase(); - const { name: resourceTypeName } = PAM_RESOURCE_TYPE_MAP[resourceType]; - - return ( - name.toLowerCase().includes(searchValue) || - resourceTypeName.toLowerCase().includes(searchValue) - ); - }) - .sort((a, b) => { - const [one, two] = orderDirection === OrderByDirection.ASC ? [a, b] : [b, a]; - - switch (orderBy) { - case OrderBy.Name: - default: - return one.name.toLowerCase().localeCompare(two.name.toLowerCase()); - } - }), - [resources, orderDirection, search, orderBy, filters] + return ( + name.toLowerCase().includes(searchValue) || + resourceType.toLowerCase().includes(searchValue) + ); + }), + [resources, search, filters] ); - useResetPageHelper({ - totalCount: filteredResources.length, - offset, - setPage - }); - - const currentPageData = useMemo( - () => filteredResources.slice(offset, perPage * page), - [filteredResources, offset, perPage, page] - ); - - const handleSort = (column: OrderBy) => { + const handleSort = (column: PamResourceOrderBy) => { if (column === orderBy) { toggleOrderDirection(); return; @@ -145,9 +149,10 @@ export const PamResourcesTable = ({ projectId, resources }: Props) => { setOrderDirection(OrderByDirection.ASC); }; - const getClassName = (col: OrderBy) => twMerge("ml-2", orderBy === col ? "" : "opacity-30"); + const getClassName = (col: PamResourceOrderBy) => + twMerge("ml-2", orderBy === col ? "" : "opacity-30"); - const getColSortIcon = (col: OrderBy) => + const getColSortIcon = (col: PamResourceOrderBy) => orderDirection === OrderByDirection.DESC && orderBy === col ? faArrowUp : faArrowDown; const isTableFiltered = Boolean(filters.resourceType.length); @@ -263,11 +268,11 @@ export const PamResourcesTable = ({ projectId, resources }: Props) => { Resource handleSort(OrderBy.Name)} + onClick={() => handleSort(PamResourceOrderBy.Name)} > - + @@ -275,27 +280,29 @@ export const PamResourcesTable = ({ projectId, resources }: Props) => { - {currentPageData.map((resource) => ( - handlePopUpOpen("updateResource", e)} - onDelete={(e) => handlePopUpOpen("deleteResource", e)} - search={search.trim().toLowerCase()} - /> - ))} + {isLoading && } + {!isLoading && + filteredResources.map((resource) => ( + handlePopUpOpen("updateResource", e)} + onDelete={(e) => handlePopUpOpen("deleteResource", e)} + search={search.trim().toLowerCase()} + /> + ))} - {Boolean(filteredResources.length) && ( + {Boolean(totalCount) && !isLoading && ( setPage(newPage)} + onChangePerPage={handlePerPageChange} /> )} - {isContentEmpty && ( + {!isLoading && isContentEmpty && ( Date: Fri, 7 Nov 2025 17:00:32 -0500 Subject: [PATCH 003/108] move enums to their own file + lint --- .../v1/pam-account-routers/pam-account-router.ts | 2 +- backend/src/ee/services/pam-account/pam-account-dal.ts | 2 +- .../src/ee/services/pam-account/pam-account-enums.ts | 8 ++++++++ .../src/ee/services/pam-account/pam-account-service.ts | 9 ++------- .../src/ee/services/pam-account/pam-account-types.ts | 10 +--------- backend/src/ee/services/pam-folder/pam-folder-dal.ts | 2 +- 6 files changed, 14 insertions(+), 19 deletions(-) create mode 100644 backend/src/ee/services/pam-account/pam-account-enums.ts diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts index 626daa898..59756ab3e 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { PamFoldersSchema } from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; -import { PamAccountOrderBy, PamAccountView } from "@app/ee/services/pam-account/pam-account-types"; +import { PamAccountOrderBy, PamAccountView } from "@app/ee/services/pam-account/pam-account-enums"; import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; diff --git a/backend/src/ee/services/pam-account/pam-account-dal.ts b/backend/src/ee/services/pam-account/pam-account-dal.ts index 562567172..5ee805ce1 100644 --- a/backend/src/ee/services/pam-account/pam-account-dal.ts +++ b/backend/src/ee/services/pam-account/pam-account-dal.ts @@ -6,7 +6,7 @@ import { DatabaseError } from "@app/lib/errors"; import { ormify, selectAllTableCols } from "@app/lib/knex"; import { OrderByDirection } from "@app/lib/types"; -import { PamAccountOrderBy, PamAccountView } from "./pam-account-types"; +import { PamAccountOrderBy, PamAccountView } from "./pam-account-enums"; export type TPamAccountDALFactory = ReturnType; diff --git a/backend/src/ee/services/pam-account/pam-account-enums.ts b/backend/src/ee/services/pam-account/pam-account-enums.ts new file mode 100644 index 000000000..92b95df94 --- /dev/null +++ b/backend/src/ee/services/pam-account/pam-account-enums.ts @@ -0,0 +1,8 @@ +export enum PamAccountOrderBy { + Name = "name" +} + +export enum PamAccountView { + Flat = "flat", + Nested = "nested" +} diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts index bfc6c7e7f..8050f702e 100644 --- a/backend/src/ee/services/pam-account/pam-account-service.ts +++ b/backend/src/ee/services/pam-account/pam-account-service.ts @@ -31,14 +31,9 @@ import { TPamSessionDALFactory } from "../pam-session/pam-session-dal"; import { PamSessionStatus } from "../pam-session/pam-session-enums"; import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission"; import { TPamAccountDALFactory } from "./pam-account-dal"; +import { PamAccountView } from "./pam-account-enums"; import { decryptAccount, decryptAccountCredentials, encryptAccountCredentials } from "./pam-account-fns"; -import { - PamAccountView, - TAccessAccountDTO, - TCreateAccountDTO, - TListAccountsDTO, - TUpdateAccountDTO -} from "./pam-account-types"; +import { TAccessAccountDTO, TCreateAccountDTO, TListAccountsDTO, TUpdateAccountDTO } from "./pam-account-types"; type TPamAccountServiceFactoryDep = { pamResourceDAL: TPamResourceDALFactory; diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts index 775ef1f78..781223f33 100644 --- a/backend/src/ee/services/pam-account/pam-account-types.ts +++ b/backend/src/ee/services/pam-account/pam-account-types.ts @@ -1,6 +1,7 @@ import { OrderByDirection, TProjectPermission } from "@app/lib/types"; import { TPamAccount } from "../pam-resource/pam-resource-types"; +import { PamAccountOrderBy, PamAccountView } from "./pam-account-enums"; // DTOs export type TCreateAccountDTO = Pick< @@ -30,12 +31,3 @@ export type TListAccountsDTO = { limit?: number; offset?: number; } & TProjectPermission; - -export enum PamAccountOrderBy { - Name = "name" -} - -export enum PamAccountView { - Flat = "flat", - Nested = "nested" -} diff --git a/backend/src/ee/services/pam-folder/pam-folder-dal.ts b/backend/src/ee/services/pam-folder/pam-folder-dal.ts index 9d0ca6cd2..3566ff5f9 100644 --- a/backend/src/ee/services/pam-folder/pam-folder-dal.ts +++ b/backend/src/ee/services/pam-folder/pam-folder-dal.ts @@ -6,7 +6,7 @@ import { DatabaseError } from "@app/lib/errors"; import { ormify, selectAllTableCols } from "@app/lib/knex"; import { OrderByDirection } from "@app/lib/types"; -import { PamAccountOrderBy } from "../pam-account/pam-account-types"; +import { PamAccountOrderBy } from "../pam-account/pam-account-enums"; export type TPamFolderDALFactory = ReturnType; export const pamFolderDALFactory = (db: TDbClient) => { From c51c47eb0373c14d970db37222a40489aea89eb6 Mon Sep 17 00:00:00 2001 From: x032205 Date: Fri, 7 Nov 2025 17:09:03 -0500 Subject: [PATCH 004/108] review fixes --- .../ee/routes/v1/pam-resource-routers/pam-resource-router.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts index 255e11aa8..f2d0f98ef 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts @@ -92,7 +92,7 @@ export const registerPamResourceRouter = async (server: FastifyZodProvider) => { event: { type: EventType.PAM_RESOURCE_LIST, metadata: { - count: totalCount + count: resources.length } } }); From 8d9775c42a67c563e080402b492d2c570c8ae146 Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Wed, 12 Nov 2025 21:50:21 +0530 Subject: [PATCH 005/108] feat: adds GET endpoint for single auth token by ID --- .../ee/services/audit-log/audit-log-types.ts | 10 +++ backend/src/lib/api-docs/constants.ts | 4 ++ .../routes/v1/identity-token-auth-router.ts | 61 +++++++++++++++++-- .../identity-token-auth-service.ts | 47 ++++++++++++++ .../identity-token-auth-types.ts | 6 ++ frontend/src/hooks/api/identities/types.ts | 4 +- 6 files changed, 123 insertions(+), 9 deletions(-) diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts index bcc2a0770..97dfdb9fa 100644 --- a/backend/src/ee/services/audit-log/audit-log-types.ts +++ b/backend/src/ee/services/audit-log/audit-log-types.ts @@ -173,6 +173,7 @@ export enum EventType { CREATE_TOKEN_IDENTITY_TOKEN_AUTH = "create-token-identity-token-auth", UPDATE_TOKEN_IDENTITY_TOKEN_AUTH = "update-token-identity-token-auth", GET_TOKENS_IDENTITY_TOKEN_AUTH = "get-tokens-identity-token-auth", + GET_TOKEN_IDENTITY_TOKEN_AUTH = "get-token-identity-token-auth", CREATE_SUB_ORGANIZATION = "create-sub-organization", UPDATE_SUB_ORGANIZATION = "update-sub-organization", @@ -1013,6 +1014,14 @@ interface GetTokensIdentityTokenAuthEvent { }; } +interface GetTokenIdentityTokenAuthEvent { + type: EventType.GET_TOKEN_IDENTITY_TOKEN_AUTH; + metadata: { + identityId: string; + tokenId: string; + }; +} + interface AddIdentityTokenAuthEvent { type: EventType.ADD_IDENTITY_TOKEN_AUTH; metadata: { @@ -4128,6 +4137,7 @@ export type Event = | CreateTokenIdentityTokenAuthEvent | UpdateTokenIdentityTokenAuthEvent | GetTokensIdentityTokenAuthEvent + | GetTokenIdentityTokenAuthEvent | AddIdentityTokenAuthEvent | UpdateIdentityTokenAuthEvent | GetIdentityTokenAuthEvent diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts index 927694ef4..09adf2b8b 100644 --- a/backend/src/lib/api-docs/constants.ts +++ b/backend/src/lib/api-docs/constants.ts @@ -577,6 +577,10 @@ export const TOKEN_AUTH = { offset: "The offset to start from. If you enter 10, it will start from the 10th token.", limit: "The number of tokens to return." }, + GET_TOKEN: { + identityId: "The ID of the machine identity to get the token for.", + tokenId: "The ID of the token to get metadata for." + }, CREATE_TOKEN: { identityId: "The ID of the machine identity to create the token for.", name: "The name of the token to create." diff --git a/backend/src/server/routes/v1/identity-token-auth-router.ts b/backend/src/server/routes/v1/identity-token-auth-router.ts index aafffdfdb..9906b6b5d 100644 --- a/backend/src/server/routes/v1/identity-token-auth-router.ts +++ b/backend/src/server/routes/v1/identity-token-auth-router.ts @@ -312,9 +312,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider response: { 200: z.object({ accessToken: z.string(), - expiresIn: z.coerce.number(), - accessTokenMaxTTL: z.coerce.number(), - tokenType: z.literal("Bearer") + tokenData: IdentityAccessTokensSchema }) } }, @@ -344,9 +342,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider return { accessToken, - tokenType: "Bearer" as const, - expiresIn: identityTokenAuth.accessTokenTTL, - accessTokenMaxTTL: identityTokenAuth.accessTokenMaxTTL + tokenData: identityAccessToken }; } }); @@ -406,6 +402,59 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider } }); + server.route({ + method: "GET", + url: "/token-auth/identities/:identityId/tokens/:tokenId", + config: { + rateLimit: readLimit + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + schema: { + hide: false, + tags: [ApiDocsTags.TokenAuth], + description: "Get token for machine identity with Token Auth", + security: [ + { + bearerAuth: [] + } + ], + params: z.object({ + identityId: z.string().describe(TOKEN_AUTH.GET_TOKEN.identityId), + tokenId: z.string().describe(TOKEN_AUTH.GET_TOKEN.tokenId) + }), + response: { + 200: z.object({ + token: IdentityAccessTokensSchema + }) + } + }, + handler: async (req) => { + const { token, identityMembershipOrg } = await server.services.identityTokenAuth.getTokenAuthTokenById({ + identityId: req.params.identityId, + tokenId: req.params.tokenId, + actor: req.permission.type, + actorId: req.permission.id, + actorOrgId: req.permission.orgId, + actorAuthMethod: req.permission.authMethod, + isActorSuperAdmin: isSuperAdmin(req.auth) + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + orgId: identityMembershipOrg.scopeOrgId, + event: { + type: EventType.GET_TOKEN_IDENTITY_TOKEN_AUTH, + metadata: { + identityId: token.identityId, + tokenId: token.id + } + } + }); + + return { token }; + } + }); + server.route({ method: "PATCH", url: "/token-auth/tokens/:tokenId", diff --git a/backend/src/services/identity-token-auth/identity-token-auth-service.ts b/backend/src/services/identity-token-auth/identity-token-auth-service.ts index e6969da61..8c2c90711 100644 --- a/backend/src/services/identity-token-auth/identity-token-auth-service.ts +++ b/backend/src/services/identity-token-auth/identity-token-auth-service.ts @@ -31,6 +31,7 @@ import { TAttachTokenAuthDTO, TCreateTokenAuthTokenDTO, TGetTokenAuthDTO, + TGetTokenAuthTokenByIdDTO, TGetTokenAuthTokensDTO, TRevokeTokenAuthDTO, TRevokeTokenAuthTokenDTO, @@ -499,6 +500,51 @@ export const identityTokenAuthServiceFactory = ({ return { tokens, identityMembershipOrg }; }; + const getTokenAuthTokenById = async ({ + tokenId, + identityId, + isActorSuperAdmin, + actorId, + actor, + actorAuthMethod, + actorOrgId + }: TGetTokenAuthTokenByIdDTO) => { + await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin); + + const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({ + scopeData: { + scope: AccessScope.Organization, + orgId: actorOrgId + }, + identityId + }); + if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` }); + + if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.TOKEN_AUTH)) { + throw new BadRequestError({ + message: "The identity does not have Token Auth" + }); + } + const { permission } = await permissionService.getOrgPermission({ + scope: OrganizationActionScope.Any, + actor, + actorId, + orgId: identityMembershipOrg.scopeOrgId, + actorAuthMethod, + actorOrgId + }); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity); + + const token = await identityAccessTokenDAL.findOne({ + [`${TableName.IdentityAccessToken}.id` as "id"]: tokenId, + [`${TableName.IdentityAccessToken}.authMethod` as "authMethod"]: IdentityAuthMethod.TOKEN_AUTH + }); + + if (!token) throw new NotFoundError({ message: `Token with ID ${tokenId} not found` }); + + return { token, identityMembershipOrg }; + }; + const updateTokenAuthToken = async ({ tokenId, name, @@ -642,6 +688,7 @@ export const identityTokenAuthServiceFactory = ({ revokeIdentityTokenAuth, createTokenAuthToken, getTokenAuthTokens, + getTokenAuthTokenById, updateTokenAuthToken, revokeTokenAuthToken }; diff --git a/backend/src/services/identity-token-auth/identity-token-auth-types.ts b/backend/src/services/identity-token-auth/identity-token-auth-types.ts index 16cd60db7..fdecc6d4c 100644 --- a/backend/src/services/identity-token-auth/identity-token-auth-types.ts +++ b/backend/src/services/identity-token-auth/identity-token-auth-types.ts @@ -40,6 +40,12 @@ export type TGetTokenAuthTokensDTO = { isActorSuperAdmin?: boolean; } & Omit; +export type TGetTokenAuthTokenByIdDTO = { + tokenId: string; + identityId: string; + isActorSuperAdmin?: boolean; +} & Omit; + export type TUpdateTokenAuthTokenDTO = { tokenId: string; name?: string; diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.ts index a0eb828e8..b7be75e1c 100644 --- a/frontend/src/hooks/api/identities/types.ts +++ b/frontend/src/hooks/api/identities/types.ts @@ -765,9 +765,7 @@ export type CreateTokenIdentityTokenAuthDTO = { export type CreateTokenIdentityTokenAuthRes = { accessToken: string; - tokenType: string; - expiresIn: number; - accessTokenMaxTTL: number; + tokenData: IdentityAccessToken; }; export type UpdateTokenIdentityTokenAuthDTO = { From 4091dc53a570faa5f6a5cf8eff53c55bb367fa79 Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Wed, 12 Nov 2025 23:00:58 +0530 Subject: [PATCH 006/108] refactor: simplify token retrieval by using findById method --- .../identity-token-auth/identity-token-auth-service.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/backend/src/services/identity-token-auth/identity-token-auth-service.ts b/backend/src/services/identity-token-auth/identity-token-auth-service.ts index 8c2c90711..1ece312ea 100644 --- a/backend/src/services/identity-token-auth/identity-token-auth-service.ts +++ b/backend/src/services/identity-token-auth/identity-token-auth-service.ts @@ -535,10 +535,7 @@ export const identityTokenAuthServiceFactory = ({ }); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity); - const token = await identityAccessTokenDAL.findOne({ - [`${TableName.IdentityAccessToken}.id` as "id"]: tokenId, - [`${TableName.IdentityAccessToken}.authMethod` as "authMethod"]: IdentityAuthMethod.TOKEN_AUTH - }); + const token = await identityAccessTokenDAL.findById(tokenId); if (!token) throw new NotFoundError({ message: `Token with ID ${tokenId} not found` }); From a76e323b6cf4528aea3b5769624e2ddbe36620ba Mon Sep 17 00:00:00 2001 From: Piyush Gupta Date: Wed, 12 Nov 2025 23:27:19 +0530 Subject: [PATCH 007/108] fix: identityAccessTokenDALFactory.findOne dal function --- .../identity-access-token/identity-access-token-dal.ts | 1 - .../identity-token-auth/identity-token-auth-service.ts | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/src/services/identity-access-token/identity-access-token-dal.ts b/backend/src/services/identity-access-token/identity-access-token-dal.ts index ffdb78645..74b624a7e 100644 --- a/backend/src/services/identity-access-token/identity-access-token-dal.ts +++ b/backend/src/services/identity-access-token/identity-access-token-dal.ts @@ -18,7 +18,6 @@ export const identityAccessTokenDALFactory = (db: TDbClient) => { .where(filter) .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.IdentityAccessToken}.identityId`) .select(selectAllTableCols(TableName.IdentityAccessToken)) - .select(db.ref("name").withSchema(TableName.Identity)) .select(db.ref("orgId").withSchema(TableName.Identity).as("identityScopeOrgId")) .first(); diff --git a/backend/src/services/identity-token-auth/identity-token-auth-service.ts b/backend/src/services/identity-token-auth/identity-token-auth-service.ts index 1ece312ea..97717c4f3 100644 --- a/backend/src/services/identity-token-auth/identity-token-auth-service.ts +++ b/backend/src/services/identity-token-auth/identity-token-auth-service.ts @@ -535,7 +535,11 @@ export const identityTokenAuthServiceFactory = ({ }); ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity); - const token = await identityAccessTokenDAL.findById(tokenId); + const token = await identityAccessTokenDAL.findOne({ + [`${TableName.IdentityAccessToken}.id` as "id"]: tokenId, + [`${TableName.IdentityAccessToken}.authMethod` as "authMethod"]: IdentityAuthMethod.TOKEN_AUTH, + [`${TableName.IdentityAccessToken}.identityId` as "identityId"]: identityId + }); if (!token) throw new NotFoundError({ message: `Token with ID ${tokenId} not found` }); From ace77b516ecc52ce59e115f92fa54c4aebbfde3d Mon Sep 17 00:00:00 2001 From: Sheen Capadngan Date: Thu, 13 Nov 2025 03:39:18 +0800 Subject: [PATCH 008/108] feat: ssh pam draft --- .../ee/routes/v1/pam-account-routers/index.ts | 14 ++ .../pam-account-routers/pam-account-router.ts | 4 +- .../routes/v1/pam-resource-routers/index.ts | 14 ++ .../pam-resource-router.ts | 13 +- .../src/ee/routes/v1/pam-session-router.ts | 11 +- .../pam-account/pam-account-service.ts | 41 ++++-- .../pam-resource/pam-resource-enums.ts | 3 +- .../pam-resource/pam-resource-factory.ts | 4 +- .../pam-resource/pam-resource-service.ts | 13 +- .../pam-resource/pam-resource-types.ts | 18 ++- .../shared/sql/sql-resource-factory.ts | 17 ++- .../pam-resource/ssh/ssh-resource-enums.ts | 5 + .../pam-resource/ssh/ssh-resource-factory.ts | 73 +++++++++ .../pam-resource/ssh/ssh-resource-schemas.ts | 117 +++++++++++++++ .../pam-resource/ssh/ssh-resource-types.ts | 16 ++ frontend/src/hooks/api/pam/types/index.ts | 6 +- .../src/hooks/api/pam/types/ssh-resource.ts | 47 ++++++ .../components/PamAccessAccountModal.tsx | 25 ++-- .../PamAccountForm/PamAccountForm.tsx | 11 +- .../PamAccountForm/SSHAccountForm.tsx | 96 ++++++++++++ .../shared/SshAccountFields.tsx | 138 ++++++++++++++++++ .../shared/ssh-account-schemas.ts | 26 ++++ .../PamResourceForm/PamResourceForm.tsx | 5 + .../PamResourceForm/SSHResourceForm.tsx | 68 +++++++++ .../shared/SshResourceFields.tsx | 42 ++++++ .../shared/ssh-resource-schemas.ts | 31 ++++ .../components/ResourceTypeSelect.tsx | 1 - 27 files changed, 813 insertions(+), 46 deletions(-) create mode 100644 backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts create mode 100644 backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts create mode 100644 backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts create mode 100644 backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts create mode 100644 frontend/src/hooks/api/pam/types/ssh-resource.ts create mode 100644 frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SSHAccountForm.tsx create mode 100644 frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/shared/SshAccountFields.tsx create mode 100644 frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/shared/ssh-account-schemas.ts create mode 100644 frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx create mode 100644 frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/SshResourceFields.tsx create mode 100644 frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/ssh-resource-schemas.ts diff --git a/backend/src/ee/routes/v1/pam-account-routers/index.ts b/backend/src/ee/routes/v1/pam-account-routers/index.ts index 60d621467..d3aadd5a4 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/index.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/index.ts @@ -9,6 +9,11 @@ import { SanitizedPostgresAccountWithResourceSchema, UpdatePostgresAccountSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { + CreateSSHAccountSchema, + SanitizedSSHAccountWithResourceSchema, + UpdateSSHAccountSchema +} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas"; import { registerPamResourceEndpoints } from "./pam-account-endpoints"; @@ -30,5 +35,14 @@ export const PAM_ACCOUNT_REGISTER_ROUTER_MAP: Record { + registerPamResourceEndpoints({ + server, + resourceType: PamResource.SSH, + accountResponseSchema: SanitizedSSHAccountWithResourceSchema, + createAccountSchema: CreateSSHAccountSchema, + updateAccountSchema: UpdateSSHAccountSchema + }); } }; diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts index 286e0896f..c28770be4 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts @@ -5,6 +5,7 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types"; import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { SanitizedSSHAccountWithResourceSchema } from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas"; import { BadRequestError } from "@app/lib/errors"; import { ms } from "@app/lib/ms"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; @@ -12,6 +13,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; const SanitizedAccountSchema = z.union([ + SanitizedSSHAccountWithResourceSchema, // ORDER MATTERS SanitizedPostgresAccountWithResourceSchema, SanitizedMySQLAccountWithResourceSchema ]); @@ -93,7 +95,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => { gatewayClientPrivateKey: z.string(), gatewayServerCertificateChain: z.string(), relayHost: z.string(), - metadata: z.record(z.string(), z.string()).optional() + metadata: z.record(z.string(), z.string().optional()).optional() }) } }, diff --git a/backend/src/ee/routes/v1/pam-resource-routers/index.ts b/backend/src/ee/routes/v1/pam-resource-routers/index.ts index 821532598..5dae317da 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/index.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/index.ts @@ -9,6 +9,11 @@ import { SanitizedPostgresResourceSchema, UpdatePostgresResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { + CreateSSHResourceSchema, + SanitizedSSHResourceSchema, + UpdateSSHResourceSchema +} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas"; import { registerPamResourceEndpoints } from "./pam-resource-endpoints"; @@ -30,5 +35,14 @@ export const PAM_RESOURCE_REGISTER_ROUTER_MAP: Record { + registerPamResourceEndpoints({ + server, + resourceType: PamResource.SSH, + resourceResponseSchema: SanitizedSSHResourceSchema, + createResourceSchema: CreateSSHResourceSchema, + updateResourceSchema: UpdateSSHResourceSchema + }); } }; diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts index 6563c86c7..8cac0525b 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts @@ -9,15 +9,24 @@ import { PostgresResourceListItemSchema, SanitizedPostgresResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { + SanitizedSSHResourceSchema, + SSHResourceListItemSchema +} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas"; import { readLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; -const SanitizedResourceSchema = z.union([SanitizedPostgresResourceSchema, SanitizedMySQLResourceSchema]); +const SanitizedResourceSchema = z.union([ + SanitizedPostgresResourceSchema, + SanitizedMySQLResourceSchema, + SanitizedSSHResourceSchema +]); const ResourceOptionsSchema = z.discriminatedUnion("resource", [ PostgresResourceListItemSchema, - MySQLResourceListItemSchema + MySQLResourceListItemSchema, + SSHResourceListItemSchema ]); export const registerPamResourceRouter = async (server: FastifyZodProvider) => { diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts index 5fe10e434..c31ae0d78 100644 --- a/backend/src/ee/routes/v1/pam-session-router.ts +++ b/backend/src/ee/routes/v1/pam-session-router.ts @@ -4,12 +4,17 @@ import { PamSessionsSchema } from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; import { MySQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PostgresSessionCredentialsSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; +import { SSHSessionCredentialsSchema } from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas"; import { PamSessionCommandLogSchema, SanitizedSessionSchema } from "@app/ee/services/pam-session/pam-session-schemas"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; -const SessionCredentialsSchema = z.union([PostgresSessionCredentialsSchema, MySQLSessionCredentialsSchema]); +const SessionCredentialsSchema = z.union([ + SSHSessionCredentialsSchema, + PostgresSessionCredentialsSchema, + MySQLSessionCredentialsSchema +]); export const registerPamSessionRouter = async (server: FastifyZodProvider) => { // Meant to be hit solely by gateway identities @@ -26,7 +31,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => { }), response: { 200: z.object({ - credentials: SessionCredentialsSchema + credentials: z.any() // UNION DOES NOT WORK WITH ZOD SCHEMA }) } }, @@ -50,7 +55,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => { } }); - return { credentials }; + return { credentials: credentials as z.infer }; } }); diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts index 2f66d28d7..b6f2bbae9 100644 --- a/backend/src/ee/services/pam-account/pam-account-service.ts +++ b/backend/src/ee/services/pam-account/pam-account-service.ts @@ -24,9 +24,11 @@ import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service"; import { TLicenseServiceFactory } from "../license/license-service"; import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal"; import { getFullPamFolderPath } from "../pam-folder/pam-folder-fns"; +import { TMySQLResourceConnectionDetails } from "../pam-resource/mysql/mysql-resource-types"; import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal"; import { PamResource } from "../pam-resource/pam-resource-enums"; import { TPamAccountCredentials } from "../pam-resource/pam-resource-types"; +import { TPostgresResourceConnectionDetails } from "../pam-resource/postgres/postgres-resource-types"; import { TPamSessionDALFactory } from "../pam-session/pam-session-dal"; import { PamSessionStatus } from "../pam-session/pam-session-enums"; import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission"; @@ -251,17 +253,17 @@ export const pamAccountServiceFactory = ({ gatewayV2Service ); - // Logic to prevent overwriting unedited censored values - const finalCredentials = { ...credentials }; - if (credentials.password === "__INFISICAL_UNCHANGED__") { - const decryptedCredentials = await decryptAccountCredentials({ - encryptedCredentials: account.encryptedCredentials, - projectId: account.projectId, - kmsService - }); + const decryptedCredentials = await decryptAccountCredentials({ + encryptedCredentials: account.encryptedCredentials, + projectId: account.projectId, + kmsService + }); - finalCredentials.password = decryptedCredentials.password; - } + // Logic to prevent overwriting unedited censored values + const finalCredentials = await factory.handleOverwritePreventionForCensoredValues( + credentials, + decryptedCredentials + ); const validatedCredentials = await factory.validateAccountCredentials(finalCredentials); const encryptedCredentials = await encryptAccountCredentials({ @@ -486,11 +488,11 @@ export const pamAccountServiceFactory = ({ case PamResource.Postgres: case PamResource.MySQL: { - const connectionCredentials = await decryptResourceConnectionDetails({ + const connectionCredentials = (await decryptResourceConnectionDetails({ encryptedConnectionDetails: resource.encryptedConnectionDetails, kmsService, projectId: account.projectId - }); + })) as TMySQLResourceConnectionDetails | TPostgresResourceConnectionDetails; const credentials = await decryptAccountCredentials({ encryptedCredentials: account.encryptedCredentials, @@ -506,6 +508,21 @@ export const pamAccountServiceFactory = ({ }; } break; + case PamResource.SSH: + { + const credentials = await decryptAccountCredentials({ + encryptedCredentials: account.encryptedCredentials, + kmsService, + projectId: account.projectId + }); + + metadata = { + username: credentials.username, + accountName: account.name, + accountPath + }; + } + break; default: break; } diff --git a/backend/src/ee/services/pam-resource/pam-resource-enums.ts b/backend/src/ee/services/pam-resource/pam-resource-enums.ts index dff1cc650..e913a1a09 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-enums.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-enums.ts @@ -1,4 +1,5 @@ export enum PamResource { Postgres = "postgres", - MySQL = "mysql" + MySQL = "mysql", + SSH = "ssh" } diff --git a/backend/src/ee/services/pam-resource/pam-resource-factory.ts b/backend/src/ee/services/pam-resource/pam-resource-factory.ts index 151fa7ea1..e2d0a50f8 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-factory.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-factory.ts @@ -1,10 +1,12 @@ import { PamResource } from "./pam-resource-enums"; import { TPamAccountCredentials, TPamResourceConnectionDetails, TPamResourceFactory } from "./pam-resource-types"; import { sqlResourceFactory } from "./shared/sql/sql-resource-factory"; +import { sshResourceFactory } from "./ssh/ssh-resource-factory"; type TPamResourceFactoryImplementation = TPamResourceFactory; export const PAM_RESOURCE_FACTORY_MAP: Record = { [PamResource.Postgres]: sqlResourceFactory as TPamResourceFactoryImplementation, - [PamResource.MySQL]: sqlResourceFactory as TPamResourceFactoryImplementation + [PamResource.MySQL]: sqlResourceFactory as TPamResourceFactoryImplementation, + [PamResource.SSH]: sshResourceFactory as TPamResourceFactoryImplementation }; 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 d97905dbe..8d3fd8cbe 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-service.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts @@ -192,19 +192,18 @@ export const pamResourceServiceFactory = ({ gatewayV2Service ); - // Logic to prevent overwriting unedited censored values - const finalCredentials = { ...rotationAccountCredentials }; - if ( - resource.encryptedRotationAccountCredentials && - rotationAccountCredentials.password === "__INFISICAL_UNCHANGED__" - ) { + let finalCredentials = { ...rotationAccountCredentials }; + if (resource.encryptedRotationAccountCredentials) { const decryptedCredentials = await decryptAccountCredentials({ encryptedCredentials: resource.encryptedRotationAccountCredentials, projectId: resource.projectId, kmsService }); - finalCredentials.password = decryptedCredentials.password; + finalCredentials = await factory.handleOverwritePreventionForCensoredValues( + rotationAccountCredentials, + decryptedCredentials + ); } try { diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.ts index 1ca9db3e2..2a36f17bc 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-types.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts @@ -12,15 +12,24 @@ import { TPostgresResource, TPostgresResourceConnectionDetails } from "./postgres/postgres-resource-types"; +import { + TSSHAccount, + TSSHAccountCredentials, + TSSHResource, + TSSHResourceConnectionDetails +} from "./ssh/ssh-resource-types"; // Resource types -export type TPamResource = TPostgresResource | TMySQLResource; -export type TPamResourceConnectionDetails = TPostgresResourceConnectionDetails | TMySQLResourceConnectionDetails; +export type TPamResource = TPostgresResource | TMySQLResource | TSSHResource; +export type TPamResourceConnectionDetails = + | TPostgresResourceConnectionDetails + | TMySQLResourceConnectionDetails + | TSSHResourceConnectionDetails; // Account types -export type TPamAccount = TPostgresAccount | TMySQLAccount; +export type TPamAccount = TPostgresAccount | TMySQLAccount | TSSHAccount; // eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents -export type TPamAccountCredentials = TPostgresAccountCredentials | TMySQLAccountCredentials; +export type TPamAccountCredentials = TPostgresAccountCredentials | TMySQLAccountCredentials | TSSHAccountCredentials; // Resource DTOs export type TCreateResourceDTO = Pick< @@ -51,4 +60,5 @@ export type TPamResourceFactory; validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials; rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials; + handleOverwritePreventionForCensoredValues: (updatedAccountCredentials: C, currentCredentials: C) => Promise; }; diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts index 7dd7948ef..b3128c422 100644 --- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts +++ b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts @@ -337,9 +337,24 @@ export const sqlResourceFactory: TPamResourceFactory { + if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") { + return { + ...updatedAccountCredentials, + password: currentCredentials.password + }; + } + + return updatedAccountCredentials; + }; + return { validateConnection, validateAccountCredentials, - rotateAccountCredentials + rotateAccountCredentials, + handleOverwritePreventionForCensoredValues }; }; diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts new file mode 100644 index 000000000..9b6ed1f15 --- /dev/null +++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-enums.ts @@ -0,0 +1,5 @@ +export enum SSHAuthMethod { + Password = "password", + PublicKey = "public-key", + Certificate = "certificate" +} diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts new file mode 100644 index 000000000..b01c87151 --- /dev/null +++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-factory.ts @@ -0,0 +1,73 @@ +import { + TPamResourceFactory, + TPamResourceFactoryRotateAccountCredentials, + TPamResourceFactoryValidateAccountCredentials +} from "../pam-resource-types"; +import { SSHAuthMethod } from "./ssh-resource-enums"; +import { TSSHAccountCredentials, TSSHResourceConnectionDetails } from "./ssh-resource-types"; + +export const sshResourceFactory: TPamResourceFactory = ( + resourceType, + connectionDetails, + gatewayId, + gatewayV2Service +) => { + const validateConnection = async () => { + return connectionDetails; + }; + + const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials = async ( + credentials + ) => { + return credentials; + }; + + const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials = async ( + rotationAccountCredentials, + currentCredentials + ) => { + return rotationAccountCredentials; + }; + + const handleOverwritePreventionForCensoredValues = async ( + updatedAccountCredentials: TSSHAccountCredentials, + currentCredentials: TSSHAccountCredentials + ) => { + if (updatedAccountCredentials.authMethod !== currentCredentials.authMethod) { + return updatedAccountCredentials; + } + + if ( + updatedAccountCredentials.authMethod === SSHAuthMethod.Password && + currentCredentials.authMethod === SSHAuthMethod.Password + ) { + if (updatedAccountCredentials.password === "__INFISICAL_UNCHANGED__") { + return { + ...updatedAccountCredentials, + password: currentCredentials.password + }; + } + } + + if ( + updatedAccountCredentials.authMethod === SSHAuthMethod.PublicKey && + currentCredentials.authMethod === SSHAuthMethod.PublicKey + ) { + if (updatedAccountCredentials.privateKey === "__INFISICAL_UNCHANGED__") { + return { + ...updatedAccountCredentials, + privateKey: currentCredentials.privateKey + }; + } + } + + return updatedAccountCredentials; + }; + + return { + validateConnection, + validateAccountCredentials, + rotateAccountCredentials, + handleOverwritePreventionForCensoredValues + }; +}; diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts new file mode 100644 index 000000000..779574e01 --- /dev/null +++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-schemas.ts @@ -0,0 +1,117 @@ +import { z } from "zod"; + +import { PamResource } from "../pam-resource-enums"; +import { + BaseCreatePamAccountSchema, + BaseCreatePamResourceSchema, + BasePamAccountSchema, + BasePamAccountSchemaWithResource, + BasePamResourceSchema, + BaseUpdatePamAccountSchema, + BaseUpdatePamResourceSchema +} from "../pam-resource-schemas"; +import { SSHAuthMethod } from "./ssh-resource-enums"; + +export const BaseSSHResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.SSH) }); + +export const SSHResourceListItemSchema = z.object({ + name: z.literal("SSH"), + resource: z.literal(PamResource.SSH) +}); + +export const SSHResourceConnectionDetailsSchema = z.object({ + host: z.string().trim(), + port: z.number() +}); + +export const SSHPasswordCredentialsSchema = z.object({ + authMethod: z.literal(SSHAuthMethod.Password), + username: z.string().trim(), + password: z.string().trim() +}); + +export const SSHPublicKeyCredentialsSchema = z.object({ + authMethod: z.literal(SSHAuthMethod.PublicKey), + username: z.string().trim(), + privateKey: z.string().trim() +}); + +export const SSHCertificateCredentialsSchema = z.object({ + authMethod: z.literal(SSHAuthMethod.Certificate), + username: z.string().trim() +}); + +export const SSHAccountCredentialsSchema = z.discriminatedUnion("authMethod", [ + SSHPasswordCredentialsSchema, + SSHPublicKeyCredentialsSchema, + SSHCertificateCredentialsSchema +]); + +export const SSHResourceSchema = BaseSSHResourceSchema.extend({ + connectionDetails: SSHResourceConnectionDetailsSchema, + rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional() +}); + +export const SanitizedSSHResourceSchema = BaseSSHResourceSchema.extend({ + connectionDetails: SSHResourceConnectionDetailsSchema, + rotationAccountCredentials: z + .discriminatedUnion("authMethod", [ + z.object({ + authMethod: z.literal(SSHAuthMethod.Password), + username: z.string() + }), + z.object({ + authMethod: z.literal(SSHAuthMethod.PublicKey), + username: z.string() + }), + z.object({ + authMethod: z.literal(SSHAuthMethod.Certificate), + username: z.string() + }) + ]) + .nullable() + .optional() +}); + +export const CreateSSHResourceSchema = BaseCreatePamResourceSchema.extend({ + connectionDetails: SSHResourceConnectionDetailsSchema, + rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional() +}); + +export const UpdateSSHResourceSchema = BaseUpdatePamResourceSchema.extend({ + connectionDetails: SSHResourceConnectionDetailsSchema.optional(), + rotationAccountCredentials: SSHAccountCredentialsSchema.nullable().optional() +}); + +// Accounts +export const SSHAccountSchema = BasePamAccountSchema.extend({ + credentials: SSHAccountCredentialsSchema +}); + +export const CreateSSHAccountSchema = BaseCreatePamAccountSchema.extend({ + credentials: SSHAccountCredentialsSchema +}); + +export const UpdateSSHAccountSchema = BaseUpdatePamAccountSchema.extend({ + credentials: SSHAccountCredentialsSchema.optional() +}); + +export const SanitizedSSHAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({ + credentials: z.discriminatedUnion("authMethod", [ + z.object({ + authMethod: z.literal(SSHAuthMethod.Password), + username: z.string() + }), + z.object({ + authMethod: z.literal(SSHAuthMethod.PublicKey), + username: z.string() + }), + z.object({ + authMethod: z.literal(SSHAuthMethod.Certificate), + username: z.string() + }) + ]) +}); + +// Sessions +export const SSHSessionCredentialsSchema = SSHResourceConnectionDetailsSchema.and(SSHAccountCredentialsSchema); diff --git a/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts b/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts new file mode 100644 index 000000000..920dc4274 --- /dev/null +++ b/backend/src/ee/services/pam-resource/ssh/ssh-resource-types.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +import { + SSHAccountCredentialsSchema, + SSHAccountSchema, + SSHResourceConnectionDetailsSchema, + SSHResourceSchema +} from "./ssh-resource-schemas"; + +// Resources +export type TSSHResource = z.infer; +export type TSSHResourceConnectionDetails = z.infer; + +// Accounts +export type TSSHAccount = z.infer; +export type TSSHAccountCredentials = z.infer; diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts index 1b1890cbd..055cb8dea 100644 --- a/frontend/src/hooks/api/pam/types/index.ts +++ b/frontend/src/hooks/api/pam/types/index.ts @@ -1,13 +1,15 @@ import { PamResourceType, PamSessionStatus } from "../enums"; import { TMySQLAccount, TMySQLResource } from "./mysql-resource"; import { TPostgresAccount, TPostgresResource } from "./postgres-resource"; +import { TSSHAccount, TSSHResource } from "./ssh-resource"; export * from "./mysql-resource"; export * from "./postgres-resource"; +export * from "./ssh-resource"; -export type TPamResource = TPostgresResource | TMySQLResource; +export type TPamResource = TPostgresResource | TMySQLResource | TSSHResource; -export type TPamAccount = TPostgresAccount | TMySQLAccount; +export type TPamAccount = TPostgresAccount | TMySQLAccount | TSSHAccount; export type TPamFolder = { id: string; diff --git a/frontend/src/hooks/api/pam/types/ssh-resource.ts b/frontend/src/hooks/api/pam/types/ssh-resource.ts new file mode 100644 index 000000000..0ac3b5a77 --- /dev/null +++ b/frontend/src/hooks/api/pam/types/ssh-resource.ts @@ -0,0 +1,47 @@ +import { PamResourceType } from "../enums"; +import { TBasePamAccount } from "./base-account"; +import { TBasePamResource } from "./base-resource"; + +export enum SSHAuthMethod { + Password = "password", + PublicKey = "public-key", + Certificate = "certificate" +} + +export type TSSHConnectionDetails = { + host: string; + port: number; +}; + +export type TSSHPasswordCredentials = { + authMethod: SSHAuthMethod.Password; + username: string; + password: string; +}; + +export type TSSHPublicKeyCredentials = { + authMethod: SSHAuthMethod.PublicKey; + username: string; + privateKey: string; +}; + +export type TSSHCertificateCredentials = { + authMethod: SSHAuthMethod.Certificate; + username: string; +}; + +export type TSSHCredentials = + | TSSHPasswordCredentials + | TSSHPublicKeyCredentials + | TSSHCertificateCredentials; + +// Resources +export type TSSHResource = TBasePamResource & { resourceType: PamResourceType.SSH } & { + connectionDetails: TSSHConnectionDetails; + rotationAccountCredentials?: TSSHCredentials | null; +}; + +// Accounts +export type TSSHAccount = TBasePamAccount & { + credentials: TSSHCredentials; +}; diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx index a1bf76888..97fcb26f6 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx @@ -58,15 +58,22 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account }: Props) return duration; }, [duration]); - const command = useMemo( - () => - account && - (account.resource.resourceType === PamResourceType.Postgres || - account.resource.resourceType === PamResourceType.MySQL) - ? `infisical pam db access-account ${account.id} --duration ${cliDuration}` - : "", - [account, cliDuration] - ); + const command = useMemo(() => { + if (!account) return ""; + + if ( + account.resource.resourceType === PamResourceType.Postgres || + account.resource.resourceType === PamResourceType.MySQL + ) { + return `infisical pam db access-account ${account.id} --duration ${cliDuration}`; + } + + if (account.resource.resourceType === PamResourceType.SSH) { + return `infisical pam ssh ${account.id} --duration ${cliDuration}`; + } + + return ""; + }, [account, cliDuration]); if (!account) return null; diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx index 346195e11..0288411b1 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx @@ -10,6 +10,7 @@ import { DiscriminativePick } from "@app/types"; import { PamAccountHeader } from "../PamAccountHeader"; import { MySQLAccountForm } from "./MySQLAccountForm"; import { PostgresAccountForm } from "./PostgresAccountForm"; +import { SSHAccountForm } from "./SSHAccountForm"; type FormProps = { onComplete: (account: TPamAccount) => void; @@ -65,6 +66,10 @@ const CreateForm = ({ return ( ); + case PamResourceType.SSH: + return ( + + ); default: throw new Error(`Unhandled resource: ${resourceType}`); } @@ -90,9 +95,11 @@ const UpdateForm = ({ account, onComplete }: UpdateFormProps) => { switch (account.resource.resourceType) { case PamResourceType.Postgres: - return ; + return ; case PamResourceType.MySQL: - return ; + return ; + case PamResourceType.SSH: + return ; default: throw new Error(`Unhandled resource: ${account.resource.resourceType}`); } diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SSHAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SSHAccountForm.tsx new file mode 100644 index 000000000..c6d303c63 --- /dev/null +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/SSHAccountForm.tsx @@ -0,0 +1,96 @@ +import { FormProvider, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { Button, ModalClose } from "@app/components/v2"; +import { PamResourceType, TSSHAccount } from "@app/hooks/api/pam"; +import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants"; +import { SSHAuthMethod } from "@app/hooks/api/pam/types/ssh-resource"; + +import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields"; +import { BaseSshAccountSchema } from "./shared/ssh-account-schemas"; +import { SshAccountFields } from "./shared/SshAccountFields"; + +type Props = { + account?: TSSHAccount; + resourceId?: string; + resourceType?: PamResourceType; + onSubmit: (formData: FormData) => Promise; +}; + +const formSchema = genericAccountFieldsSchema.extend({ + credentials: BaseSshAccountSchema, + // We don't support rotation for now, just feed a false value to + // make the schema happy + rotationEnabled: z.boolean().default(false) +}); + +type FormData = z.infer; + +export const SSHAccountForm = ({ account, onSubmit }: Props) => { + const isUpdate = Boolean(account); + + const form = useForm({ + resolver: zodResolver(formSchema), + defaultValues: account + ? { + ...account, + credentials: + account.credentials.authMethod === SSHAuthMethod.Password + ? { + ...account.credentials, + password: UNCHANGED_PASSWORD_SENTINEL + } + : account.credentials.authMethod === SSHAuthMethod.PublicKey + ? { + ...account.credentials, + privateKey: UNCHANGED_PASSWORD_SENTINEL + } + : account.credentials + } + : { + name: "", + description: "", + credentials: { + authMethod: SSHAuthMethod.Password, + username: "", + password: "" + } + } + }); + + const { + handleSubmit, + formState: { isSubmitting, isDirty } + } = form; + + return ( + +
{ + handleSubmit(onSubmit)(e); + }} + > + + +
+ + + + +
+ +
+ ); +}; diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/shared/SshAccountFields.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/shared/SshAccountFields.tsx new file mode 100644 index 000000000..0ca294fb9 --- /dev/null +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/shared/SshAccountFields.tsx @@ -0,0 +1,138 @@ +import { useEffect, useState } from "react"; +import { Controller, useFormContext, useWatch } from "react-hook-form"; + +import { FormControl, Input, Select, SelectItem, TextArea } from "@app/components/v2"; +import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants"; +import { SSHAuthMethod } from "@app/hooks/api/pam/types/ssh-resource"; + +export const SshAccountFields = ({ isUpdate }: { isUpdate: boolean }) => { + const { control, setValue } = useFormContext(); + const [showPassword, setShowPassword] = useState(false); + + const authMethod = + useWatch({ control, name: "credentials.authMethod" }) || SSHAuthMethod.Password; + const password = useWatch({ control, name: "credentials.password" }); + + useEffect(() => { + if (password === UNCHANGED_PASSWORD_SENTINEL) { + setShowPassword(false); + } + }, [password]); + + return ( +
+ ( + + + + )} + /> + + ( + + + + )} + /> + + {authMethod === SSHAuthMethod.Password && ( + ( + + { + if (isUpdate && field.value === UNCHANGED_PASSWORD_SENTINEL) { + field.onChange(""); + } + setShowPassword(true); + }} + onBlur={() => { + if (isUpdate && field.value === "") { + field.onChange(UNCHANGED_PASSWORD_SENTINEL); + } + setShowPassword(false); + }} + /> + + )} + /> + )} + + {authMethod === SSHAuthMethod.PublicKey && ( + ( + +