Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Merge branch 'main' into feat/addGroupsToSshHosts
carlosmonastyrskib9070a8fa354
diff --cc backend/src/ee/services/ssh-host-group/ssh-host-group-dal.tsindex 0000000000,08242d4cb6..2f57cce3a2mode 000000,100644..100644--- a/backend/src/ee/services/ssh-host-group/ssh-host-group-dal.ts+++ b/backend/src/ee/services/ssh-host-group/ssh-host-group-dal.ts@@@ -1,0 -1,225 +1,231 @@@+ import { Knex } from "knex";++ import { TDbClient } from "@app/db";+ import { TableName } from "@app/db/schemas";+ import { BadRequestError, DatabaseError } from "@app/lib/errors";+ import { groupBy, unique } from "@app/lib/fn";+ import { ormify } from "@app/lib/knex";++ import { EHostGroupMembershipFilter } from "./ssh-host-group-types";++ export type TSshHostGroupDALFactory = ReturnType<typeof sshHostGroupDALFactory>;++ export const sshHostGroupDALFactory = (db: TDbClient) => {+ const sshHostGroupOrm = ormify(db, TableName.SshHostGroup);++ const findSshHostGroupsWithLoginMappings = async (projectId: string, tx?: Knex) => {+ try {+ // First, get all the SSH host groups with their login mappings+ const rows = await (tx || db.replicaNode())(TableName.SshHostGroup)+ .leftJoin(+ TableName.SshHostLoginUser,+ `${TableName.SshHostGroup}.id`,+ `${TableName.SshHostLoginUser}.sshHostGroupId`+ )+ .leftJoin(+ TableName.SshHostLoginUserMapping,+ `${TableName.SshHostLoginUser}.id`,+ `${TableName.SshHostLoginUserMapping}.sshHostLoginUserId`+ )+ .leftJoin(TableName.Users, `${TableName.SshHostLoginUserMapping}.userId`, `${TableName.Users}.id`)++ .leftJoin(TableName.Groups, `${TableName.SshHostLoginUserMapping}.groupId`, `${TableName.Groups}.id`)+ .where(`${TableName.SshHostGroup}.projectId`, projectId)+ .select(+ db.ref("id").withSchema(TableName.SshHostGroup).as("sshHostGroupId"),+ db.ref("projectId").withSchema(TableName.SshHostGroup),+ db.ref("name").withSchema(TableName.SshHostGroup),+ db.ref("loginUser").withSchema(TableName.SshHostLoginUser),+ db.ref("username").withSchema(TableName.Users),- db.ref("userId").withSchema(TableName.SshHostLoginUserMapping)++ db.ref("userId").withSchema(TableName.SshHostLoginUserMapping),++ db.ref("slug").withSchema(TableName.Groups).as("groupSlug")+ )+ .orderBy(`${TableName.SshHostGroup}.updatedAt`, "desc");++ const hostsGrouped = groupBy(rows, (r) => r.sshHostGroupId);++ const hostGroupIds = Object.keys(hostsGrouped);++ type HostCountRow = {+ sshHostGroupId: string;+ host_count: string;+ };++ const hostCountsQuery = (await (tx ||+ db+ .replicaNode()(TableName.SshHostGroupMembership)+ .select(`${TableName.SshHostGroupMembership}.sshHostGroupId`, db.raw(`count(*) as host_count`))+ .whereIn(`${TableName.SshHostGroupMembership}.sshHostGroupId`, hostGroupIds)+ .groupBy(`${TableName.SshHostGroupMembership}.sshHostGroupId`))) as HostCountRow[];++ const hostCountsMap = hostCountsQuery.reduce<Record<string, number>>((acc, { sshHostGroupId, host_count }) => {+ acc[sshHostGroupId] = Number(host_count);+ return acc;+ }, {});++ return Object.values(hostsGrouped).map((hostRows) => {+ const { sshHostGroupId, name } = hostRows[0];+ const loginMappingGrouped = groupBy(+ hostRows.filter((r) => r.loginUser),+ (r) => r.loginUser+ );+ const loginMappings = Object.entries(loginMappingGrouped).map(([loginUser, entries]) => ({+ loginUser,+ allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)++ usernames: unique(entries.map((e) => e.username)).filter(Boolean),++ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)+ }+ }));+ return {+ id: sshHostGroupId,+ projectId,+ name,+ loginMappings,+ hostCount: hostCountsMap[sshHostGroupId] ?? 0+ };+ });+ } catch (error) {+ throw new DatabaseError({ error, name: `${TableName.SshHostGroup}: FindSshHostGroupsWithLoginMappings` });+ }+ };++ const findSshHostGroupByIdWithLoginMappings = async (sshHostGroupId: string, tx?: Knex) => {+ try {+ const rows = await (tx || db.replicaNode())(TableName.SshHostGroup)+ .leftJoin(+ TableName.SshHostLoginUser,+ `${TableName.SshHostGroup}.id`,+ `${TableName.SshHostLoginUser}.sshHostGroupId`+ )+ .leftJoin(+ TableName.SshHostLoginUserMapping,+ `${TableName.SshHostLoginUser}.id`,+ `${TableName.SshHostLoginUserMapping}.sshHostLoginUserId`+ )+ .leftJoin(TableName.Users, `${TableName.SshHostLoginUserMapping}.userId`, `${TableName.Users}.id`)++ .leftJoin(TableName.Groups, `${TableName.SshHostLoginUserMapping}.groupId`, `${TableName.Groups}.id`)+ .where(`${TableName.SshHostGroup}.id`, sshHostGroupId)+ .select(+ db.ref("id").withSchema(TableName.SshHostGroup).as("sshHostGroupId"),+ db.ref("projectId").withSchema(TableName.SshHostGroup),+ db.ref("name").withSchema(TableName.SshHostGroup),+ db.ref("loginUser").withSchema(TableName.SshHostLoginUser),+ db.ref("username").withSchema(TableName.Users),- db.ref("userId").withSchema(TableName.SshHostLoginUserMapping)++ db.ref("userId").withSchema(TableName.SshHostLoginUserMapping),++ db.ref("slug").withSchema(TableName.Groups).as("groupSlug")+ );++ if (rows.length === 0) return null;++ const { sshHostGroupId: id, projectId, name } = rows[0];++ const loginMappingGrouped = groupBy(+ rows.filter((r) => r.loginUser),+ (r) => r.loginUser+ );++ const loginMappings = Object.entries(loginMappingGrouped).map(([loginUser, entries]) => ({+ loginUser,+ allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)++ usernames: unique(entries.map((e) => e.username)).filter(Boolean),++ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)+ }+ }));++ return {+ id,+ projectId,+ name,+ loginMappings+ };+ } catch (error) {+ throw new DatabaseError({ error, name: `${TableName.SshHostGroup}: FindSshHostGroupByIdWithLoginMappings` });+ }+ };++ const findAllSshHostsInGroup = async ({+ sshHostGroupId,+ offset = 0,+ limit,+ filter+ }: {+ sshHostGroupId: string;+ offset?: number;+ limit?: number;+ filter?: EHostGroupMembershipFilter;+ }) => {+ try {+ const sshHostGroup = await db+ .replicaNode()(TableName.SshHostGroup)+ .where(`${TableName.SshHostGroup}.id`, sshHostGroupId)+ .select("projectId")+ .first();++ if (!sshHostGroup) {+ throw new BadRequestError({+ message: `SSH host group with ID ${sshHostGroupId} not found`+ });+ }++ const query = db+ .replicaNode()(TableName.SshHost)+ .where(`${TableName.SshHost}.projectId`, sshHostGroup.projectId)+ .leftJoin(TableName.SshHostGroupMembership, (bd) => {+ bd.on(`${TableName.SshHostGroupMembership}.sshHostId`, "=", `${TableName.SshHost}.id`).andOn(+ `${TableName.SshHostGroupMembership}.sshHostGroupId`,+ "=",+ db.raw("?", [sshHostGroupId])+ );+ })+ .select(+ db.ref("id").withSchema(TableName.SshHost),+ db.ref("hostname").withSchema(TableName.SshHost),+ db.ref("alias").withSchema(TableName.SshHost),+ db.ref("sshHostGroupId").withSchema(TableName.SshHostGroupMembership),+ db.ref("createdAt").withSchema(TableName.SshHostGroupMembership).as("joinedGroupAt"),+ db.raw(`count(*) OVER() as total_count`)+ )+ .offset(offset)+ .orderBy(`${TableName.SshHost}.hostname`, "asc");++ if (limit) {+ void query.limit(limit);+ }++ if (filter) {+ switch (filter) {+ case EHostGroupMembershipFilter.GROUP_MEMBERS:+ void query.andWhere(`${TableName.SshHostGroupMembership}.createdAt`, "is not", null);+ break;+ case EHostGroupMembershipFilter.NON_GROUP_MEMBERS:+ void query.andWhere(`${TableName.SshHostGroupMembership}.createdAt`, "is", null);+ break;+ default:+ break;+ }+ }++ const hosts = await query;++ return {+ hosts: hosts.map(({ id, hostname, alias, sshHostGroupId: memberGroupId, joinedGroupAt }) => ({+ id,+ hostname,+ alias,+ isPartOfGroup: !!memberGroupId,+ joinedGroupAt+ })),+ // @ts-expect-error col select is raw and not strongly typed+ totalCount: Number(hosts?.[0]?.total_count ?? 0)+ };+ } catch (error) {+ throw new DatabaseError({ error, name: `${TableName.SshHostGroupMembership}: FindAllSshHostsInGroup` });+ }+ };++ return {+ findSshHostGroupsWithLoginMappings,+ findSshHostGroupByIdWithLoginMappings,+ findAllSshHostsInGroup,+ ...sshHostGroupOrm+ };+ };diff --cc backend/src/ee/services/ssh-host-group/ssh-host-group-service.tsindex 0000000000,751116895b..1eacc76025mode 000000,100644..100644--- a/backend/src/ee/services/ssh-host-group/ssh-host-group-service.ts+++ b/backend/src/ee/services/ssh-host-group/ssh-host-group-service.ts@@@ -1,0 -1,397 +1,405 @@@+ import { ForbiddenError } from "@casl/ability";++ import { ActionProjectType } from "@app/db/schemas";+ import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";+ import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+ import { TSshHostDALFactory } from "@app/ee/services/ssh-host/ssh-host-dal";+ import { TSshHostLoginUserMappingDALFactory } from "@app/ee/services/ssh-host/ssh-host-login-user-mapping-dal";+ import { TSshHostLoginUserDALFactory } from "@app/ee/services/ssh-host/ssh-login-user-dal";+ import { TSshHostGroupDALFactory } from "@app/ee/services/ssh-host-group/ssh-host-group-dal";+ import { TSshHostGroupMembershipDALFactory } from "@app/ee/services/ssh-host-group/ssh-host-group-membership-dal";+ import { BadRequestError, NotFoundError } from "@app/lib/errors";+ import { TProjectDALFactory } from "@app/services/project/project-dal";+ import { TUserDALFactory } from "@app/services/user/user-dal";+++import { TGroupDALFactory } from "../group/group-dal";+ import { TLicenseServiceFactory } from "../license/license-service";+ import { createSshLoginMappings } from "../ssh-host/ssh-host-fns";+ import {+ TAddHostToSshHostGroupDTO,+ TCreateSshHostGroupDTO,+ TDeleteSshHostGroupDTO,+ TGetSshHostGroupDTO,+ TListSshHostGroupHostsDTO,+ TRemoveHostFromSshHostGroupDTO,+ TUpdateSshHostGroupDTO+ } from "./ssh-host-group-types";++ type TSshHostGroupServiceFactoryDep = {+ projectDAL: Pick<TProjectDALFactory, "findById" | "find">;+ sshHostDAL: Pick<TSshHostDALFactory, "findSshHostByIdWithLoginMappings">;+ sshHostGroupDAL: Pick<+ TSshHostGroupDALFactory,+ | "create"+ | "updateById"+ | "findById"+ | "deleteById"+ | "transaction"+ | "findSshHostGroupByIdWithLoginMappings"+ | "findAllSshHostsInGroup"+ | "findOne"+ | "find"+ >;+ sshHostGroupMembershipDAL: Pick<TSshHostGroupMembershipDALFactory, "create" | "deleteById" | "findOne">;+ sshHostLoginUserDAL: Pick<TSshHostLoginUserDALFactory, "create" | "transaction" | "delete">;+ sshHostLoginUserMappingDAL: Pick<TSshHostLoginUserMappingDALFactory, "insertMany">;+ userDAL: Pick<TUserDALFactory, "find">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getUserProjectPermission">;++ permissionService: Pick<++ TPermissionServiceFactory,++ "getProjectPermission" | "getUserProjectPermission" | "checkGroupProjectPermission"++ >;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;++ groupDAL: Pick<TGroupDALFactory, "findGroupsByProjectId">;+ };++ export type TSshHostGroupServiceFactory = ReturnType<typeof sshHostGroupServiceFactory>;++ export const sshHostGroupServiceFactory = ({+ projectDAL,+ sshHostDAL,+ sshHostGroupDAL,+ sshHostGroupMembershipDAL,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,+ userDAL,+ permissionService,- licenseService++ licenseService,++ groupDAL+ }: TSshHostGroupServiceFactoryDep) => {+ const createSshHostGroup = async ({+ projectId,+ name,+ loginMappings,+ actorId,+ actorAuthMethod,+ actor,+ actorOrgId+ }: TCreateSshHostGroupDTO) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.SshHostGroups);++ const plan = await licenseService.getPlan(actorOrgId);+ if (!plan.sshHostGroups)+ throw new BadRequestError({+ message: "Failed to create SSH host group due to plan restriction. Upgrade plan to create group."+ });++ const newSshHostGroup = await sshHostGroupDAL.transaction(async (tx) => {+ // (dangtony98): room to optimize check to ensure that+ // the SSH host group name is unique across the whole org+ const project = await projectDAL.findById(projectId, tx);+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });+ const projects = await projectDAL.find(+ {+ orgId: project.orgId+ },+ { tx }+ );++ const existingSshHostGroup = await sshHostGroupDAL.find(+ {+ name,+ $in: {+ projectId: projects.map((p) => p.id)+ }+ },+ { tx }+ );++ if (existingSshHostGroup.length) {+ throw new BadRequestError({+ message: `SSH host group with name '${name}' already exists in the organization`+ });+ }++ const sshHostGroup = await sshHostGroupDAL.create(+ {+ projectId,+ name+ },+ tx+ );++ await createSshLoginMappings({+ sshHostGroupId: sshHostGroup.id,+ loginMappings,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,++ groupDAL,+ userDAL,+ permissionService,+ projectId,+ actorAuthMethod,+ actorOrgId,+ tx+ });++ const newSshHostGroupWithLoginMappings = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(+ sshHostGroup.id,+ tx+ );+ if (!newSshHostGroupWithLoginMappings) {+ throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroup.id}' not found` });+ }++ return newSshHostGroupWithLoginMappings;+ });++ return newSshHostGroup;+ };++ const updateSshHostGroup = async ({+ sshHostGroupId,+ name,+ loginMappings,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TUpdateSshHostGroupDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findById(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.SshHostGroups);++ const plan = await licenseService.getPlan(actorOrgId);+ if (!plan.sshHostGroups)+ throw new BadRequestError({+ message: "Failed to update SSH host group due to plan restriction. Upgrade plan to update group."+ });++ const updatedSshHostGroup = await sshHostGroupDAL.transaction(async (tx) => {+ await sshHostGroupDAL.updateById(+ sshHostGroupId,+ {+ name+ },+ tx+ );+ if (loginMappings) {+ await sshHostLoginUserDAL.delete({ sshHostGroupId: sshHostGroup.id }, tx);+ if (loginMappings.length) {+ await createSshLoginMappings({+ sshHostGroupId: sshHostGroup.id,+ loginMappings,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,++ groupDAL,+ userDAL,+ permissionService,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ tx+ });+ }+ }++ const updatedSshHostGroupWithLoginMappings = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(+ sshHostGroup.id,+ tx+ );+ if (!updatedSshHostGroupWithLoginMappings) {+ throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroup.id}' not found` });+ }++ return updatedSshHostGroupWithLoginMappings;+ });++ return updatedSshHostGroup;+ };++ const getSshHostGroup = async ({+ sshHostGroupId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TGetSshHostGroupDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SshHostGroups);++ return sshHostGroup;+ };++ const deleteSshHostGroup = async ({+ sshHostGroupId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TDeleteSshHostGroupDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.SshHostGroups);++ await sshHostGroupDAL.deleteById(sshHostGroupId);++ return sshHostGroup;+ };++ const listSshHostGroupHosts = async ({+ sshHostGroupId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ filter+ }: TListSshHostGroupHostsDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SshHostGroups);++ const { hosts, totalCount } = await sshHostGroupDAL.findAllSshHostsInGroup({ sshHostGroupId, filter });+ return { sshHostGroup, hosts, totalCount };+ };++ const addHostToSshHostGroup = async ({+ sshHostGroupId,+ hostId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TAddHostToSshHostGroupDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const sshHost = await sshHostDAL.findSshHostByIdWithLoginMappings(hostId);+ if (!sshHost) {+ throw new NotFoundError({+ message: `SSH host with ID ${hostId} not found`+ });+ }++ if (sshHostGroup.projectId !== sshHost.projectId) {+ throw new BadRequestError({+ message: `SSH host with ID ${hostId} not found in project ${sshHostGroup.projectId}`+ });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.SshHostGroups);++ await sshHostGroupMembershipDAL.create({ sshHostGroupId, sshHostId: hostId });++ return { sshHostGroup, sshHost };+ };++ const removeHostFromSshHostGroup = async ({+ sshHostGroupId,+ hostId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }: TRemoveHostFromSshHostGroupDTO) => {+ const sshHostGroup = await sshHostGroupDAL.findSshHostGroupByIdWithLoginMappings(sshHostGroupId);+ if (!sshHostGroup) throw new NotFoundError({ message: `SSH host group with ID '${sshHostGroupId}' not found` });++ const sshHost = await sshHostDAL.findSshHostByIdWithLoginMappings(hostId);+ if (!sshHost) {+ throw new NotFoundError({+ message: `SSH host with ID ${hostId} not found`+ });+ }++ if (sshHostGroup.projectId !== sshHost.projectId) {+ throw new BadRequestError({+ message: `SSH host with ID ${hostId} not found in project ${sshHostGroup.projectId}`+ });+ }++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: sshHostGroup.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });++ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.SshHostGroups);++ const sshHostGroupMembership = await sshHostGroupMembershipDAL.findOne({+ sshHostGroupId,+ sshHostId: hostId+ });++ if (!sshHostGroupMembership) {+ throw new NotFoundError({+ message: `SSH host with ID ${hostId} not found in SSH host group with ID ${sshHostGroupId}`+ });+ }++ await sshHostGroupMembershipDAL.deleteById(sshHostGroupMembership.id);++ return { sshHostGroup, sshHost };+ };++ return {+ createSshHostGroup,+ getSshHostGroup,+ deleteSshHostGroup,+ updateSshHostGroup,+ listSshHostGroupHosts,+ addHostToSshHostGroup,+ removeHostFromSshHostGroup+ };+ };diff --cc backend/src/ee/services/ssh-host-group/ssh-host-group-types.tsindex 0000000000,3485b5d26e..52f805f024mode 000000,100644..100644--- a/backend/src/ee/services/ssh-host-group/ssh-host-group-types.ts+++ b/backend/src/ee/services/ssh-host-group/ssh-host-group-types.ts@@@ -1,0 -1,46 +1,41 @@@+ import { TLoginMapping } from "@app/ee/services/ssh-host/ssh-host-types";+ import { TProjectPermission } from "@app/lib/types";++ export type TCreateSshHostGroupDTO = {+ name: string;+ loginMappings: TLoginMapping[];+ } & TProjectPermission;++ export type TUpdateSshHostGroupDTO = {+ sshHostGroupId: string;+ name?: string;- loginMappings?: {- loginUser: string;- allowedPrincipals: {- usernames: string[];- };- }[];++ loginMappings?: TLoginMapping[];+ } & Omit<TProjectPermission, "projectId">;++ export type TGetSshHostGroupDTO = {+ sshHostGroupId: string;+ } & Omit<TProjectPermission, "projectId">;++ export type TDeleteSshHostGroupDTO = {+ sshHostGroupId: string;+ } & Omit<TProjectPermission, "projectId">;++ export type TListSshHostGroupHostsDTO = {+ sshHostGroupId: string;+ filter?: EHostGroupMembershipFilter;+ } & Omit<TProjectPermission, "projectId">;++ export type TAddHostToSshHostGroupDTO = {+ sshHostGroupId: string;+ hostId: string;+ } & Omit<TProjectPermission, "projectId">;++ export type TRemoveHostFromSshHostGroupDTO = {+ sshHostGroupId: string;+ hostId: string;+ } & Omit<TProjectPermission, "projectId">;++ export enum EHostGroupMembershipFilter {+ GROUP_MEMBERS = "group-members",+ NON_GROUP_MEMBERS = "non-group-members"+ }diff --cc backend/src/ee/services/ssh-host/ssh-host-dal.tsindex 347dac697c,e66f7da7a6..3b8564ce27--- a/backend/src/ee/services/ssh-host/ssh-host-dal.ts+++ b/backend/src/ee/services/ssh-host/ssh-host-dal.ts@@@ -46,15 -41,52 +51,61 @@@ export const sshHostDALFactory = (db: Tdb.ref("userCertTtl").withSchema(TableName.SshHost),db.ref("hostCertTtl").withSchema(TableName.SshHost),db.ref("loginUser").withSchema(TableName.SshHostLoginUser),- db.ref("username").withSchema(TableName.Users),- db.ref("userId").withSchema(TableName.SshHostLoginUserMapping),db.ref("userSshCaId").withSchema(TableName.SshHost),db.ref("hostSshCaId").withSchema(TableName.SshHost)+ );++ // get hosts where user has login mappings via host groups+ const groupHostRows = await knex(TableName.SshHostGroupMembership)+ .join(+ TableName.SshHostLoginUser,+ `${TableName.SshHostGroupMembership}.sshHostGroupId`,+ `${TableName.SshHostLoginUser}.sshHostGroupId`)- .orderBy(`${TableName.SshHost}.updatedAt`, "desc");+ .leftJoin(+ TableName.SshHostLoginUserMapping,+ `${TableName.SshHostLoginUser}.id`,+ `${TableName.SshHostLoginUserMapping}.sshHostLoginUserId`+ )+ .join(TableName.SshHost, `${TableName.SshHostGroupMembership}.sshHostId`, `${TableName.SshHost}.id`)++ .leftJoin(++ TableName.UserGroupMembership,++ `${TableName.UserGroupMembership}.groupId`,++ `${TableName.SshHostLoginUserMapping}.groupId`++ )+ .whereIn(`${TableName.SshHost}.projectId`, projectIds)- .andWhere(`${TableName.SshHostLoginUserMapping}.userId`, userId)++ .andWhere((bd) => {++ void bd++ .where(`${TableName.SshHostLoginUserMapping}.userId`, userId)++ .orWhere(`${TableName.UserGroupMembership}.userId`, userId);++ })+ .select(+ db.ref("id").withSchema(TableName.SshHost).as("sshHostId"),+ db.ref("projectId").withSchema(TableName.SshHost),+ db.ref("hostname").withSchema(TableName.SshHost),+ db.ref("alias").withSchema(TableName.SshHost),+ db.ref("userCertTtl").withSchema(TableName.SshHost),+ db.ref("hostCertTtl").withSchema(TableName.SshHost),+ db.ref("loginUser").withSchema(TableName.SshHostLoginUser),+ db.ref("userSshCaId").withSchema(TableName.SshHost),+ db.ref("hostSshCaId").withSchema(TableName.SshHost)+ );- const grouped = groupBy(rows, (r) => r.sshHostId);- return Object.values(grouped).map((hostRows) => {+ const directHostRowsWithSource = directHostRows.map((row) => ({+ ...row,+ source: LoginMappingSource.HOST+ }));++ const groupHostRowsWithSource = groupHostRows.map((row) => ({+ ...row,+ source: LoginMappingSource.HOST_GROUP+ }));++ const mergedRows = [...directHostRowsWithSource, ...groupHostRowsWithSource];++ const hostsGrouped = groupBy(mergedRows, (r) => r.sshHostId);++ return Object.values(hostsGrouped).map((hostRows) => {const { sshHostId, hostname, alias, userCertTtl, hostCertTtl, userSshCaId, hostSshCaId, projectId } =hostRows[0];@@@ -112,6 -149,29 +170,31 @@@).orderBy(`${TableName.SshHost}.updatedAt`, "desc");+ // process login mappings inherited from groups that hosts are part of+ const hostIds = unique(rows.map((r) => r.sshHostId)).filter(Boolean);+ const groupRows = await (tx || db.replicaNode())(TableName.SshHostGroupMembership)+ .join(+ TableName.SshHostLoginUser,+ `${TableName.SshHostGroupMembership}.sshHostGroupId`,+ `${TableName.SshHostLoginUser}.sshHostGroupId`+ )+ .leftJoin(+ TableName.SshHostLoginUserMapping,+ `${TableName.SshHostLoginUser}.id`,+ `${TableName.SshHostLoginUserMapping}.sshHostLoginUserId`+ )+ .leftJoin(TableName.Users, `${TableName.SshHostLoginUserMapping}.userId`, `${TableName.Users}.id`)++ .leftJoin(TableName.Groups, `${TableName.SshHostLoginUserMapping}.groupId`, `${TableName.Groups}.id`)+ .select(+ db.ref("sshHostId").withSchema(TableName.SshHostGroupMembership),+ db.ref("loginUser").withSchema(TableName.SshHostLoginUser),- db.ref("username").withSchema(TableName.Users)++ db.ref("username").withSchema(TableName.Users),++ db.ref("slug").withSchema(TableName.Groups).as("groupSlug")+ )+ .whereIn(`${TableName.SshHostGroupMembership}.sshHostId`, hostIds);++ const groupedGroupMappings = groupBy(groupRows, (r) => r.sshHostId);+const hostsGrouped = groupBy(rows, (r) => r.sshHostId);return Object.values(hostsGrouped).map((hostRows) => {const { sshHostId, hostname, alias, userCertTtl, hostCertTtl, userSshCaId, hostSshCaId } = hostRows[0];@@@ -121,12 -182,24 +205,26 @@@(r) => r.loginUser);- const loginMappings = Object.entries(loginMappingGrouped).map(([loginUser, entries]) => ({+ const directMappings = Object.entries(loginMappingGrouped).map(([loginUser, entries]) => ({loginUser,allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)+ usernames: unique(entries.map((e) => e.username)).filter(Boolean),+ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)- }+ },+ source: LoginMappingSource.HOST+ }));++ // group-inherited login mappings+ const inheritedGroupRows = groupedGroupMappings[sshHostId] || [];+ const inheritedGrouped = groupBy(inheritedGroupRows, (r) => r.loginUser);++ const groupMappings = Object.entries(inheritedGrouped).map(([loginUser, entries]) => ({+ loginUser,+ allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)++ usernames: unique(entries.map((e) => e.username)).filter(Boolean),++ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)+ },+ source: LoginMappingSource.HOST_GROUP}));return {@@@ -182,12 -254,44 +281,48 @@@(r) => r.loginUser);- const loginMappings = Object.entries(loginMappingGrouped).map(([loginUser, entries]) => ({+ const directMappings = Object.entries(directGrouped).map(([loginUser, entries]) => ({+ loginUser,+ allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)++ usernames: unique(entries.map((e) => e.username)).filter(Boolean),++ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)+ },+ source: LoginMappingSource.HOST+ }));++ // group login mappings+ const groupRows = await (tx || db.replicaNode())(TableName.SshHostGroupMembership)+ .join(+ TableName.SshHostLoginUser,+ `${TableName.SshHostGroupMembership}.sshHostGroupId`,+ `${TableName.SshHostLoginUser}.sshHostGroupId`+ )+ .leftJoin(+ TableName.SshHostLoginUserMapping,+ `${TableName.SshHostLoginUser}.id`,+ `${TableName.SshHostLoginUserMapping}.sshHostLoginUserId`+ )+ .leftJoin(TableName.Users, `${TableName.SshHostLoginUserMapping}.userId`, `${TableName.Users}.id`)++ .leftJoin(TableName.Groups, `${TableName.SshHostLoginUserMapping}.groupId`, `${TableName.Groups}.id`)+ .where(`${TableName.SshHostGroupMembership}.sshHostId`, sshHostId)+ .select(+ db.ref("loginUser").withSchema(TableName.SshHostLoginUser),- db.ref("username").withSchema(TableName.Users)++ db.ref("username").withSchema(TableName.Users),++ db.ref("slug").withSchema(TableName.Groups).as("groupSlug")+ );++ const groupGrouped = groupBy(+ groupRows.filter((r) => r.loginUser),+ (r) => r.loginUser+ );++ const groupMappings = Object.entries(groupGrouped).map(([loginUser, entries]) => ({loginUser,allowedPrincipals: {- usernames: unique(entries.map((e) => e.username)).filter(Boolean)+ usernames: unique(entries.map((e) => e.username)).filter(Boolean),+ groups: unique(entries.map((e) => e.groupSlug)).filter(Boolean)- }+ },+ source: LoginMappingSource.HOST_GROUP}));return {diff --cc backend/src/ee/services/ssh-host/ssh-host-fns.tsindex 0000000000,9b9ce26422..dec15e093fmode 000000,100644..100644--- a/backend/src/ee/services/ssh-host/ssh-host-fns.ts+++ b/backend/src/ee/services/ssh-host/ssh-host-fns.ts@@@ -1,0 -1,85 +1,122 @@@+ import { Knex } from "knex";++ import { ActionProjectType } from "@app/db/schemas";+ import { BadRequestError } from "@app/lib/errors";+++import { ProjectPermissionSshHostActions, ProjectPermissionSub } from "../permission/project-permission";+ import { TCreateSshLoginMappingsDTO } from "./ssh-host-types";++ /**+ * Create SSH login mappings for a given SSH host+ * or SSH host group.+ */+ export const createSshLoginMappings = async ({+ sshHostId,+ sshHostGroupId,+ loginMappings,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,++ groupDAL,+ userDAL,+ permissionService,+ projectId,+ actorAuthMethod,+ actorOrgId,+ tx: outerTx+ }: TCreateSshLoginMappingsDTO) => {+ const processCreation = async (tx: Knex) => {+ // (dangtony98): room to optimize+ for await (const { loginUser, allowedPrincipals } of loginMappings) {+ const sshHostLoginUser = await sshHostLoginUserDAL.create(+ // (dangtony98): should either pass in sshHostId or sshHostGroupId but not both+ {+ sshHostId,+ sshHostGroupId,+ loginUser+ },+ tx+ );+- if (allowedPrincipals.usernames.length > 0) {++ if (allowedPrincipals.usernames && allowedPrincipals.usernames.length > 0) {+ const users = await userDAL.find(+ {+ $in: {+ username: allowedPrincipals.usernames+ }+ },+ { tx }+ );++ const foundUsernames = new Set(users.map((u) => u.username));++ for (const uname of allowedPrincipals.usernames) {+ if (!foundUsernames.has(uname)) {+ throw new BadRequestError({+ message: `Invalid username: ${uname}`+ });+ }+ }++ for await (const user of users) {+ // check that each user has access to the SSH project+ await permissionService.getUserProjectPermission({+ userId: user.id,+ projectId,+ authMethod: actorAuthMethod,+ userOrgId: actorOrgId,+ actionProjectType: ActionProjectType.SSH+ });+ }++ await sshHostLoginUserMappingDAL.insertMany(+ users.map((user) => ({+ sshHostLoginUserId: sshHostLoginUser.id,+ userId: user.id+ })),+ tx+ );+ }++++ if (allowedPrincipals.groups && allowedPrincipals.groups.length > 0) {++ const projectGroups = await groupDAL.findGroupsByProjectId(projectId);++ const groups = projectGroups.filter((g) => allowedPrincipals.groups?.includes(g.slug));++++ if (groups.length !== allowedPrincipals.groups?.length) {++ throw new BadRequestError({++ message: `Invalid group slugs: ${allowedPrincipals.groups++ .filter((g) => !projectGroups.some((pg) => pg.slug === g))++ .join(", ")}`++ });++ }++++ for await (const group of groups) {++ // check that each group has access to the SSH project and have read access to hosts++ const hasPermission = await permissionService.checkGroupProjectPermission({++ groupId: group.id,++ projectId,++ checkPermissions: [ProjectPermissionSshHostActions.Read, ProjectPermissionSub.SshHosts]++ });++ if (!hasPermission) {++ throw new BadRequestError({++ message: `Group ${group.slug} does not have access to the SSH project`++ });++ }++ }++++ await sshHostLoginUserMappingDAL.insertMany(++ groups.map((group) => ({++ sshHostLoginUserId: sshHostLoginUser.id,++ groupId: group.id++ })),++ tx++ );++ }+ }+ };++ if (outerTx) {+ return processCreation(outerTx);+ }++ return sshHostLoginUserDAL.transaction(processCreation);+ };diff --cc backend/src/ee/services/ssh-host/ssh-host-service.tsindex 348865b3a6,87f4862bb6..79c74cd57c--- a/backend/src/ee/services/ssh-host/ssh-host-service.ts+++ b/backend/src/ee/services/ssh-host/ssh-host-service.ts@@@ -211,91 -203,18 +212,19 @@@ export const sshHostServiceFactory = (tx);- // (dangtony98): room to optimize- for await (const { loginUser, allowedPrincipals } of loginMappings) {- const sshHostLoginUser = await sshHostLoginUserDAL.create(- {- sshHostId: host.id,- loginUser- },- tx- );-- if (allowedPrincipals.usernames && allowedPrincipals.usernames.length > 0) {- const users = await userDAL.find(- {- $in: {- username: allowedPrincipals.usernames- }- },- { tx }- );-- const foundUsernames = new Set(users.map((u) => u.username));-- for (const uname of allowedPrincipals.usernames) {- if (!foundUsernames.has(uname)) {- throw new BadRequestError({- message: `Invalid username: ${uname}`- });- }- }-- for await (const user of users) {- // check that each user has access to the SSH project- await permissionService.getUserProjectPermission({- userId: user.id,- projectId,- authMethod: actorAuthMethod,- userOrgId: actorOrgId,- actionProjectType: ActionProjectType.SSH- });- }-- await sshHostLoginUserMappingDAL.insertMany(- users.map((user) => ({- sshHostLoginUserId: sshHostLoginUser.id,- userId: user.id- })),- tx- );- }-- if (allowedPrincipals.groups && allowedPrincipals.groups.length > 0) {- const projectGroups = await groupDAL.findGroupsByProjectId(projectId);- const groups = projectGroups.filter((g) => allowedPrincipals.groups?.includes(g.slug));-- if (groups.length !== allowedPrincipals.groups?.length) {- throw new BadRequestError({- message: `Invalid group slugs: ${allowedPrincipals.groups- .filter((g) => !projectGroups.some((pg) => pg.slug === g))- .join(", ")}`- });- }-- for await (const group of groups) {- // check that each group has access to the SSH project and have read access to hosts- const hasPermission = await permissionService.checkGroupProjectPermission({- groupId: group.id,- projectId,- checkPermissions: [ProjectPermissionSshHostActions.Read, ProjectPermissionSub.SshHosts]- });- if (!hasPermission) {- throw new BadRequestError({- message: `Group ${group.slug} does not have access to the SSH project`- });- }- }-- await sshHostLoginUserMappingDAL.insertMany(- groups.map((group) => ({- sshHostLoginUserId: sshHostLoginUser.id,- groupId: group.id- })),- tx- );- }- }+ await createSshLoginMappings({+ sshHostId: host.id,+ loginMappings,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,++ groupDAL,+ userDAL,+ permissionService,+ projectId,+ actorAuthMethod,+ actorOrgId,+ tx+ });const newSshHostWithLoginMappings = await sshHostDAL.findSshHostByIdWithLoginMappings(host.id, tx);if (!newSshHostWithLoginMappings) {@@@ -354,90 -273,18 +283,19 @@@if (loginMappings) {await sshHostLoginUserDAL.delete({ sshHostId: host.id }, tx);if (loginMappings.length) {- for await (const { loginUser, allowedPrincipals } of loginMappings) {- const sshHostLoginUser = await sshHostLoginUserDAL.create(- {- sshHostId: host.id,- loginUser- },- tx- );-- if (allowedPrincipals.usernames && allowedPrincipals.usernames.length > 0) {- const users = await userDAL.find(- {- $in: {- username: allowedPrincipals.usernames- }- },- { tx }- );-- const foundUsernames = new Set(users.map((u) => u.username));-- for (const uname of allowedPrincipals.usernames) {- if (!foundUsernames.has(uname)) {- throw new BadRequestError({- message: `Invalid username: ${uname}`- });- }- }-- for await (const user of users) {- await permissionService.getUserProjectPermission({- userId: user.id,- projectId: host.projectId,- authMethod: actorAuthMethod,- userOrgId: actorOrgId,- actionProjectType: ActionProjectType.SSH- });- }-- await sshHostLoginUserMappingDAL.insertMany(- users.map((user) => ({- sshHostLoginUserId: sshHostLoginUser.id,- userId: user.id- })),- tx- );- }-- if (allowedPrincipals.groups && allowedPrincipals.groups.length > 0) {- const groups = await groupDAL.findGroupsByProjectId(host.projectId);-- const foundGroupSlugs = new Set(groups.map((g) => g.slug));-- for (const slug of allowedPrincipals.groups) {- if (!foundGroupSlugs.has(slug)) {- throw new BadRequestError({- message: `Invalid group slug: ${slug}`- });- }- }-- for await (const group of groups) {- // check that each group has access to the SSH project and have read access to hosts- const hasPermission = await permissionService.checkGroupProjectPermission({- groupId: group.id,- projectId: host.projectId,- checkPermissions: [ProjectPermissionSshHostActions.Read, ProjectPermissionSub.SshHosts]- });- if (!hasPermission) {- throw new BadRequestError({- message: `Group ${group.slug} does not have access to the SSH project`- });- }- }-- await sshHostLoginUserMappingDAL.insertMany(- groups.map((group) => ({- sshHostLoginUserId: sshHostLoginUser.id,- groupId: group.id- })),- tx- );- }- }+ await createSshLoginMappings({+ sshHostId: host.id,+ loginMappings,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,++ groupDAL,+ userDAL,+ permissionService,+ projectId: host.projectId,+ actorAuthMethod,+ actorOrgId,+ tx+ });}}@@@ -546,8 -390,7 +404,8 @@@const mapping = host.loginMappings.find((m) =>m.loginUser === loginUser &&- (m.allowedPrincipals.usernames.some((allowed) => internalPrincipals.includes(allowed)) ||- m.allowedPrincipals.groups.some((allowed) => userGroupSlugs.includes(allowed)))- m.allowedPrincipals.usernames.some((allowed) => internalPrincipals.includes(allowed))++ (m.allowedPrincipals.usernames?.some((allowed) => internalPrincipals.includes(allowed)) ||++ m.allowedPrincipals.groups?.some((allowed) => userGroupSlugs.includes(allowed))));if (!mapping) {diff --cc backend/src/ee/services/ssh-host/ssh-host-types.tsindex 4586d66af0,9846920b78..c0a780fbb8--- a/backend/src/ee/services/ssh-host/ssh-host-types.ts+++ b/backend/src/ee/services/ssh-host/ssh-host-types.ts@@@ -1,7 -1,26 +1,29 @@@+ import { Knex } from "knex";++ import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";+ import { TSshHostLoginUserMappingDALFactory } from "@app/ee/services/ssh-host/ssh-host-login-user-mapping-dal";+ import { TSshHostLoginUserDALFactory } from "@app/ee/services/ssh-host/ssh-login-user-dal";import { TProjectPermission } from "@app/lib/types";+ import { ActorAuthMethod } from "@app/services/auth/auth-type";+ import { TUserDALFactory } from "@app/services/user/user-dal";+++import { TGroupDALFactory } from "../group/group-dal";+export type TListSshHostsDTO = Omit<TProjectPermission, "projectId">;+ export type TLoginMapping = {+ loginUser: string;+ allowedPrincipals: {- usernames: string[];++ usernames?: string[];++ groups?: string[];+ };+ };++ export enum LoginMappingSource {+ HOST = "host",+ HOST_GROUP = "hostGroup"+ }+export type TCreateSshHostDTO = {hostname: string;alias?: string;@@@ -50,3 -57,19 +60,20 @@@ export type TIssueSshHostHostCertDTO =sshHostId: string;publicKey: string;} & Omit<TProjectPermission, "projectId">;++ type BaseCreateSshLoginMappingsDTO = {+ loginMappings: TLoginMapping[];+ sshHostLoginUserDAL: Pick<TSshHostLoginUserDALFactory, "create" | "transaction">;+ sshHostLoginUserMappingDAL: Pick<TSshHostLoginUserMappingDALFactory, "insertMany">;+ userDAL: Pick<TUserDALFactory, "find">;- permissionService: Pick<TPermissionServiceFactory, "getUserProjectPermission">;++ permissionService: Pick<TPermissionServiceFactory, "getUserProjectPermission" | "checkGroupProjectPermission">;++ groupDAL: Pick<TGroupDALFactory, "findGroupsByProjectId">;+ projectId: string;+ actorAuthMethod: ActorAuthMethod;+ actorOrgId: string;+ tx?: Knex;+ };++ export type TCreateSshLoginMappingsDTO =+ | (BaseCreateSshLoginMappingsDTO & { sshHostId: string; sshHostGroupId?: undefined })+ | (BaseCreateSshLoginMappingsDTO & { sshHostGroupId: string; sshHostId?: undefined });diff --cc backend/src/server/routes/index.tsindex 0cabc02918,d15058bcb7..cbe008c9a1--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -851,6 -870,18 +872,19 @@@ export const registerRoutes = asynckmsService});+ const sshHostGroupService = sshHostGroupServiceFactory({+ projectDAL,+ sshHostDAL,+ sshHostGroupDAL,+ sshHostGroupMembershipDAL,+ sshHostLoginUserDAL,+ sshHostLoginUserMappingDAL,+ userDAL,+ permissionService,- licenseService++ licenseService,++ groupDAL+ });+const certificateAuthorityService = certificateAuthorityServiceFactory({certificateAuthorityDAL,certificateAuthorityCertDAL,diff --cc frontend/src/hooks/api/sshHost/types.tsindex 2170bf4159,e92ddeaa8b..ff33664b13--- a/frontend/src/hooks/api/sshHost/types.ts+++ b/frontend/src/hooks/api/sshHost/types.ts@@@ -1,3 -1,16 +1,17 @@@+ export enum LoginMappingSource {+ HOST = "host",+ HOST_GROUP = "hostGroup"+ }++ export type TLoginMapping = {+ loginUser: string;+ allowedPrincipals: {- usernames: string[];++ usernames?: string[];++ groups?: string[];+ };+ source: LoginMappingSource;+ };+export type TSshHost = {id: string;projectId: string;diff --cc frontend/src/pages/organization/SettingsPage/route.tsxindex 803191e1f6,3f7beb4e87..e7fdb706a5--- a/frontend/src/pages/organization/SettingsPage/route.tsx+++ b/frontend/src/pages/organization/SettingsPage/route.tsx@@@ -1,33 -1,33 +1,37 @@@--import { faHome } from "@fortawesome/free-solid-svg-icons";--import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";--import { createFileRoute, linkOptions, stripSearchParams } from "@tanstack/react-router";--import { zodValidator } from "@tanstack/zod-adapter";--import { z } from "zod";++import { faHome } from '@fortawesome/free-solid-svg-icons'++import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'++import {++ createFileRoute,++ linkOptions,++ stripSearchParams,++} from '@tanstack/react-router'++import { zodValidator } from '@tanstack/zod-adapter'++import { z } from 'zod'--import { SettingsPage } from "./SettingsPage";++import { SettingsPage } from './SettingsPage'const SettingsPageQueryParams = z.object({-- selectedTab: z.string().catch("")--});++ selectedTab: z.string().catch(''),++})export const Route = createFileRoute(- "/_authenticate/_inject-org-details/_org-layout/organization/settings"- "/_authenticate/_inject-org-details/_org-layout/organization/settings/"++ '/_authenticate/_inject-org-details/_org-layout/organization/settings/',)({component: SettingsPage,validateSearch: zodValidator(SettingsPageQueryParams),search: {-- middlewares: [stripSearchParams({ selectedTab: "" })]++ middlewares: [stripSearchParams({ selectedTab: '' })],},context: () => ({breadcrumbs: [{-- label: "Home",++ label: 'Home',icon: () => <FontAwesomeIcon icon={faHome} />,-- link: linkOptions({ to: "/" })++ link: linkOptions({ to: '/' }),},{-- label: "Settings"-- }-- ]-- })--});++ label: 'Settings',++ },++ ],++ }),++})diff --cc frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsxindex 0000000000,de5d82311a..6cd99c796emode 000000,100644..100644--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx@@@ -1,0 -1,396 +1,468 @@@+ import { useEffect, useState } from "react";+ import { Controller, useFieldArray, useForm } from "react-hook-form";+ import { faChevronDown, faChevronRight, faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";+ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+ import { zodResolver } from "@hookform/resolvers/zod";+ import { z } from "zod";++ import { createNotification } from "@app/components/notifications";+ import {+ Button,+ FormControl,+ FormLabel,+ IconButton,+ Input,+ Modal,+ ModalContent,+ Select,+ SelectItem+ } from "@app/components/v2";+ import { useWorkspace } from "@app/context";+ import {+ useCreateSshHostGroup,+ useGetSshHostGroupById,+ useGetWorkspaceUsers,++ useListWorkspaceGroups,+ useListWorkspaceSshHostGroups,+ useUpdateSshHostGroup+ } from "@app/hooks/api";+ import { UsePopUpState } from "@app/hooks/usePopUp";++ type Props = {+ popUp: UsePopUpState<["sshHostGroup"]>;+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["sshHostGroup"]>, state?: boolean) => void;+ };++ const schema = z+ .object({+ name: z.string().trim().min(1).max(64),+ loginMappings: z+ .object({+ loginUser: z.string().trim().min(1),- allowedPrincipals: z.array(z.string().trim()).default([])++ allowedPrincipals: z++ .array(++ z.object({++ type: z.enum(["user", "group"]),++ value: z.string().trim().min(1)++ })++ )++ .default([])+ })+ .array()+ .default([])+ })+ .required();++ export type FormData = z.infer<typeof schema>;++ export const SshHostGroupModal = ({ popUp, handlePopUpToggle }: Props) => {+ const { currentWorkspace } = useWorkspace();+ const projectId = currentWorkspace?.id || "";+ const { data: sshHostGroups } = useListWorkspaceSshHostGroups(currentWorkspace.id);+ const { data: members = [] } = useGetWorkspaceUsers(projectId);++ const { data: groups = [] } = useListWorkspaceGroups(projectId);+ const [expandedMappings, setExpandedMappings] = useState<Record<number, boolean>>({});++ const { data: sshHostGroup } = useGetSshHostGroupById(+ (popUp?.sshHostGroup?.data as { sshHostGroupId: string })?.sshHostGroupId || ""+ );++ const { mutateAsync: createMutateAsync } = useCreateSshHostGroup();+ const { mutateAsync: updateMutateAsync } = useUpdateSshHostGroup();++ const {+ control,+ handleSubmit,+ reset,+ getValues,+ setValue,+ formState: { isSubmitting }+ } = useForm<FormData>({+ resolver: zodResolver(schema),+ defaultValues: {+ name: "",+ loginMappings: []+ }+ });++ const loginMappingsFormFields = useFieldArray({+ control,+ name: "loginMappings"+ });++ useEffect(() => {+ if (sshHostGroup) {+ reset({+ name: sshHostGroup.name,+ loginMappings: sshHostGroup.loginMappings.map(({ loginUser, allowedPrincipals }) => ({+ loginUser,- allowedPrincipals: allowedPrincipals.usernames++ allowedPrincipals: [++ ...(allowedPrincipals.usernames || []).map((username) => ({++ type: "user" as const,++ value: username++ })),++ ...(allowedPrincipals.groups || []).map((group) => ({++ type: "group" as const,++ value: group++ }))++ ]+ }))+ });++ setExpandedMappings(+ Object.fromEntries(sshHostGroup.loginMappings.map((_, index) => [index, false]))+ );+ } else {+ reset({+ name: "",+ loginMappings: []+ });+ }+ }, [sshHostGroup]);++ const onFormSubmit = async ({ name, loginMappings }: FormData) => {+ try {+ if (!projectId) return;++ // check if there is already a different host group with the same name+ const existingNames =+ sshHostGroups?.filter((h) => h.id !== sshHostGroup?.id).map((h) => h.name) || [];++ if (existingNames.includes(name.trim())) {+ createNotification({+ text: "A host group with this name already exists.",+ type: "error"+ });+ return;+ }+++ const transformedLoginMappings = loginMappings.map(({ loginUser, allowedPrincipals }) => {++ const usernames = allowedPrincipals++ .filter((p) => p.type === "user" && p.value)++ .map((p) => p.value);++++ const groupNames = allowedPrincipals++ .filter((p) => p.type === "group" && p.value)++ .map((p) => p.value);++++ return {++ loginUser,++ allowedPrincipals: {++ usernames,++ groups: groupNames++ }++ };++ });+++ if (sshHostGroup) {+ await updateMutateAsync({+ sshHostGroupId: sshHostGroup.id,+ name,- loginMappings: loginMappings.map(({ loginUser, allowedPrincipals }) => ({- loginUser,- allowedPrincipals: {- usernames: allowedPrincipals- }- }))++ loginMappings: transformedLoginMappings+ });+ } else {+ await createMutateAsync({+ projectId,+ name,- loginMappings: loginMappings.map(({ loginUser, allowedPrincipals }) => ({- loginUser,- allowedPrincipals: {- usernames: allowedPrincipals- }- }))++ loginMappings: transformedLoginMappings+ });+ }++ reset();+ handlePopUpToggle("sshHostGroup", false);++ createNotification({+ text: `Successfully ${sshHostGroup ? "updated" : "created"} SSH host group`,+ type: "success"+ });+ } catch (err) {+ console.error(err);+ createNotification({+ text: `Failed to ${sshHostGroup ? "update" : "create"} SSH host group`,+ type: "error"+ });+ }+ };++ const toggleMapping = (index: number) => {+ setExpandedMappings((prev) => ({+ ...prev,+ [index]: !prev[index]+ }));+ };+++ const isPrincipalDuplicate = (++ mappingIndex: number,++ principalType: string,++ principalValue: string++ ) => {++ const principals = getValues(`loginMappings.${mappingIndex}.allowedPrincipals`) || [];++ return principals.some((p) => p.type === principalType && p.value === principalValue);++ };+++ return (+ <Modal+ isOpen={popUp?.sshHostGroup?.isOpen}+ onOpenChange={(isOpen) => {+ reset();+ handlePopUpToggle("sshHostGroup", isOpen);+ }}+ >+ <ModalContent title={`${sshHostGroup ? "View" : "Add"} SSH host group`}>+ <form onSubmit={handleSubmit(onFormSubmit)}>+ {sshHostGroup && (+ <FormControl label="SSH Host Group ID">+ <Input value={sshHostGroup.id} isDisabled className="bg-white/[0.07]" />+ </FormControl>+ )}+ <Controller+ control={control}+ defaultValue=""+ name="name"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Name"+ isError={Boolean(error)}+ errorText={error?.message}+ isRequired+ >+ <Input {...field} placeholder="production" />+ </FormControl>+ )}+ />+ <div className="mb-4 flex items-center justify-between">+ <FormLabel label="Login Mappings" />+ <Button+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ size="xs"+ variant="outline_bg"+ onClick={() => {+ const newIndex = loginMappingsFormFields.fields.length;- loginMappingsFormFields.append({ loginUser: "", allowedPrincipals: [""] });++ loginMappingsFormFields.append({++ loginUser: "",++ allowedPrincipals: [{ type: "user", value: "" }]++ });+ setExpandedMappings((prev) => ({+ ...prev,+ [newIndex]: true+ }));+ }}+ >+ Add Login Mapping+ </Button>+ </div>+ <div className="mb-4 flex flex-col space-y-4">+ {loginMappingsFormFields.fields.map(({ id: metadataFieldId }, i) => (+ <div+ key={metadataFieldId}+ className="flex flex-col space-y-2 rounded-md border border-mineshaft-600 p-4"+ >+ <div className="mb-2 flex items-center justify-between">+ <button+ type="button"+ className="flex cursor-pointer items-center py-1 text-sm text-mineshaft-200"+ onClick={() => toggleMapping(i)}+ >+ <FontAwesomeIcon+ icon={expandedMappings[i] ? faChevronDown : faChevronRight}+ className="mr-4"+ size="sm"+ />+ <Controller+ control={control}+ name={`loginMappings.${i}.loginUser`}+ render={({ field }) => (+ <span className="text-sm font-medium leading-tight">+ {field.value || "New Login Mapping"}+ </span>+ )}+ />+ </button>+ <IconButton+ ariaLabel="delete login mapping"+ variant="plain"+ onClick={() => loginMappingsFormFields.remove(i)}+ >+ <FontAwesomeIcon icon={faTrash} />+ </IconButton>+ </div>++ {expandedMappings[i] && (+ <>+ <div>+ <span className="text-xs text-mineshaft-400">Login User</span>+ <Controller+ control={control}+ name={`loginMappings.${i}.loginUser`}+ render={({ field, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error?.message)}+ errorText={error?.message}+ className="mb-0"+ >+ <Input+ {...field}+ placeholder="ec2-user"+ onChange={(e) => {+ const newValue = e.target.value;+ const loginMappings = getValues("loginMappings");+ const isDuplicate = loginMappings.some(+ (mapping, index) => index !== i && mapping.loginUser === newValue+ );++ if (isDuplicate) {+ createNotification({+ text: "This login user already exists",+ type: "error"+ });+ return;+ }++ field.onChange(e);+ }}+ />+ </FormControl>+ )}+ />+ </div>+ <div className="flex flex-col space-y-2">+ <div className="mb-2 mt-4 flex items-center justify-between">+ <FormLabel+ label="Allowed Principals"+ className="text-xs text-mineshaft-400"+ />+ <Button+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ size="xs"+ variant="outline_bg"+ onClick={() => {+ const current = getValues(`loginMappings.${i}.allowedPrincipals`) ?? [];- setValue(`loginMappings.${i}.allowedPrincipals`, [...current, ""]);++ setValue(`loginMappings.${i}.allowedPrincipals`, [++ ...current,++ { type: "user", value: "" }++ ]);+ }}+ >+ Add Principal+ </Button>+ </div>+ <Controller+ control={control}+ name={`loginMappings.${i}.allowedPrincipals`}+ render={({ field: { value = [], onChange }, fieldState: { error } }) => (+ <div className="flex flex-col space-y-2">- {(value.length === 0 ? [""] : value).map(- (principal: string, principalIndex: number) => (++ {(value.length === 0 ? [{ type: "user", value: "" }] : value).map(++ (principal, principalIndex) => (+ <div- key={`${metadataFieldId}-principal-${principal}`}++ key={`principal-${i + 1}-${principalIndex + 1}-${principal.type}`}+ className="flex items-center space-x-2"+ >++ <div className="mr-2">++ <Select++ className="w-24"++ value={principal.type}++ onValueChange={(newType) => {++ const newPrincipals = [...value];++ newPrincipals[principalIndex] = {++ type: newType as "user" | "group",++ value: ""++ };++ onChange(newPrincipals);++ }}++ >++ <SelectItem value="user">User</SelectItem>++ <SelectItem value="group">Group</SelectItem>++ </Select>++ </div>+ <div className="flex-1">+ <Select- value={principal}++ value={principal.value}+ onValueChange={(newValue) => {- if (value.includes(newValue)) {++ if (isPrincipalDuplicate(i, principal.type, newValue)) {+ createNotification({- text: "This principal is already added",++ text: `This ${principal.type} is already added`,+ type: "error"+ });+ return;+ }+ const newPrincipals = [...value];- newPrincipals[principalIndex] = newValue;++ newPrincipals[principalIndex] = {++ type: principal.type as "user" | "group",++ value: newValue++ };+ onChange(newPrincipals);+ }}- placeholder="Select a member"++ placeholder={`Select a ${principal.type}`}+ className="w-full"+ >- {members.map((member) => (- <SelectItem- key={member.user.id}- value={member.user.username}- >- {member.user.username}- </SelectItem>- ))}++ {principal.type === "user"++ ? members.map((member) => (++ <SelectItem++ key={member.user.id}++ value={member.user.username}++ >++ {member.user.username}++ </SelectItem>++ ))++ : groups.map((group) => (++ <SelectItem++ key={group.group.slug}++ value={group.group.slug}++ >++ {group.group.slug}++ </SelectItem>++ ))}+ </Select>+ </div>- <IconButton- size="sm"- ariaLabel="delete principal"- variant="plain"- className="h-9"- onClick={() => {- const newPrincipals = value.filter(- (_, idx) => idx !== principalIndex- );- onChange(newPrincipals);- }}- >- <FontAwesomeIcon icon={faTrash} />- </IconButton>++ <div className="flex w-10 justify-center">++ <IconButton++ size="sm"++ ariaLabel="delete principal"++ variant="plain"++ className="h-9"++ onClick={() => {++ const newPrincipals = value.filter(++ (_, idx) => idx !== principalIndex++ );++ onChange(newPrincipals.length ? newPrincipals : []);++ }}++ >++ <FontAwesomeIcon icon={faTrash} />++ </IconButton>++ </div>+ </div>+ )+ )}+ {error && <span className="text-sm text-red-500">{error.message}</span>}+ </div>+ )}+ />+ </div>+ </>+ )}+ </div>+ ))}+ </div>+ <div className="flex items-center">+ <Button+ className="mr-4"+ size="sm"+ type="submit"+ isLoading={isSubmitting}+ isDisabled={isSubmitting}+ >+ {popUp?.sshHostGroup?.data ? "Update" : "Add"}+ </Button>+ <Button+ colorSchema="secondary"+ variant="plain"+ onClick={() => handlePopUpToggle("sshHostGroup", false)}+ >+ Cancel+ </Button>+ </div>+ </form>+ </ModalContent>+ </Modal>+ );+ };diff --cc frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsxindex 0000000000,194d9e90e0..59fcdfdb54mode 000000,100644..100644--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx@@@ -1,0 -1,184 +1,223 @@@-import { faEllipsis, faPencil, faServer, faTrash } from "@fortawesome/free-solid-svg-icons";++import {++ faEllipsis,++ faPencil,++ faServer,++ faTrash,++ faUser,++ faUsers++} from "@fortawesome/free-solid-svg-icons";+ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+ import { useNavigate } from "@tanstack/react-router";+ import { twMerge } from "tailwind-merge";++ import { ProjectPermissionCan } from "@app/components/permissions";+ import {++ Badge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ EmptyState,+ Table,+ TableContainer,+ TableSkeleton,+ TBody,+ Td,+ Th,+ THead,+ Tooltip,+ Tr+ } from "@app/components/v2";+ import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";+ import { useListWorkspaceSshHostGroups } from "@app/hooks/api";+ import { ProjectType } from "@app/hooks/api/workspace/types";+ import { UsePopUpState } from "@app/hooks/usePopUp";++ type Props = {+ handlePopUpOpen: (+ popUpName: keyof UsePopUpState<["deleteSshHostGroup", "sshHostGroup"]>,+ data?: object+ ) => void;+ };++ export const SshHostGroupsTable = ({ handlePopUpOpen }: Props) => {+ const navigate = useNavigate();+ const { currentWorkspace } = useWorkspace();+ const { data, isPending } = useListWorkspaceSshHostGroups(currentWorkspace?.id || "");+ return (+ <div>+ <TableContainer>+ <Table className="w-full table-fixed">+ <THead>+ <Tr>+ <Th>Name</Th>+ <Th># Hosts in Group</Th>+ <Th>Login User - Authorized Principals Mapping</Th>+ <Th />+ </Tr>+ </THead>+ <TBody>+ {isPending && <TableSkeleton columns={3} innerKey="org-ssh-cas" />}+ {!isPending &&+ data &&+ data.length > 0 &&+ data.map((group) => {+ return (+ <Tr+ className="h-10 cursor-pointer transition-colors duration-100 hover:bg-mineshaft-700"+ key={`ssh-host-group-${group.id}`}+ onClick={() =>+ navigate({+ to: `/${ProjectType.SSH}/$projectId/ssh-host-groups/$sshHostGroupId` as const,+ params: {+ projectId: currentWorkspace.id,+ sshHostGroupId: group.id+ }+ })+ }+ >+ <Td>{group.name}</Td>+ <Td>{group.hostCount}</Td>+ <Td>+ {group.loginMappings.length === 0 ? (+ <span className="italic text-mineshaft-400">None</span>+ ) : (+ group.loginMappings.map(({ loginUser, allowedPrincipals }) => (+ <div key={`${group.id}-${loginUser}`} className="mb-2">+ <div className="text-mineshaft-200">{loginUser}</div>- {allowedPrincipals.usernames.map((username) => (- <div key={`${group.id}-${loginUser}-${username}`} className="ml-4">- └─ {username}++ {allowedPrincipals.usernames?.map((username) => (++ <div++ key={`${loginUser}-${username}`}++ className="flex items-center gap-2"++ >++ <div className="flex items-center">++ <span className="text-gray-400">└─</span>++ </div>++ <div className="flex items-center gap-1.5">++ <FontAwesomeIcon++ icon={faUser}++ className="text-xs text-yellow/80"++ />++ <span>{username}</span>++ <Badge variant="primary">user</Badge>++ </div>++ </div>++ ))}++ {allowedPrincipals.groups?.map((allowedGroup) => (++ <div++ key={`${loginUser}-${allowedGroup}`}++ className="flex items-center gap-2"++ >++ <div className="flex items-center">++ <span className="text-gray-400">└─</span>++ </div>++ <div className="flex items-center gap-1.5">++ <FontAwesomeIcon++ icon={faUsers}++ className="text-xs text-green/80"++ />++ <span>{allowedGroup}</span>++ <Badge variant="success">group</Badge>++ </div>+ </div>+ ))}+ </div>+ ))+ )}+ </Td>+ <Td className="text-right align-middle">+ <DropdownMenu>+ <DropdownMenuTrigger asChild className="rounded-lg">+ <div className="hover:text-primary-400 data-[state=open]:text-primary-400">+ <Tooltip content="More options">+ <FontAwesomeIcon size="lg" icon={faEllipsis} />+ </Tooltip>+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="p-1">+ <ProjectPermissionCan+ I={ProjectPermissionActions.Edit}+ a={ProjectPermissionSub.SshHostGroups}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ className={twMerge(+ !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"+ )}+ onClick={(e) => {+ e.stopPropagation();+ handlePopUpOpen("sshHostGroup", {+ sshHostGroupId: group.id+ });+ }}+ disabled={!isAllowed}+ icon={<FontAwesomeIcon icon={faPencil} />}+ >+ Edit Host Group+ </DropdownMenuItem>+ )}+ </ProjectPermissionCan>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Edit}+ a={ProjectPermissionSub.SshHostGroups}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ className={twMerge(+ !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"+ )}+ onClick={(e) => {+ e.stopPropagation();+ navigate({+ to: `/${ProjectType.SSH}/$projectId/ssh-host-groups/$sshHostGroupId` as const,+ params: {+ projectId: currentWorkspace.id,+ sshHostGroupId: group.id+ }+ });+ }}+ disabled={!isAllowed}+ icon={<FontAwesomeIcon icon={faServer} />}+ >+ Manage Hosts+ </DropdownMenuItem>+ )}+ </ProjectPermissionCan>+ <ProjectPermissionCan+ I={ProjectPermissionActions.Delete}+ a={ProjectPermissionSub.SshHostGroups}+ >+ {(isAllowed) => (+ <DropdownMenuItem+ className={twMerge(+ !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"+ )}+ onClick={(e) => {+ e.stopPropagation();+ handlePopUpOpen("deleteSshHostGroup", {+ sshHostGroupId: group.id,+ name: group.name+ });+ }}+ disabled={!isAllowed}+ icon={<FontAwesomeIcon icon={faTrash} />}+ >+ Delete Host Group+ </DropdownMenuItem>+ )}+ </ProjectPermissionCan>+ </DropdownMenuContent>+ </DropdownMenu>+ </Td>+ </Tr>+ );+ })}+ </TBody>+ </Table>+ {!isPending && data?.length === 0 && (+ <EmptyState title="No SSH host groups have been created" icon={faServer} />+ )}+ </TableContainer>+ </div>+ );+ };diff --cc frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsxindex 570633ce13,5ac53a16ea..5619a75c4c--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx@@@ -49,14 -49,8 +50,15 @@@ const schema =loginMappings: z.object({loginUser: z.string().trim().min(1),- allowedPrincipals: z.array(z.string().trim()).default([]),+ allowedPrincipals: z+ .array(+ z.object({+ type: z.enum(["user", "group"]),+ value: z.string().trim().min(1)+ })+ )- .default([])++ .default([]),+ source: z.nativeEnum(LoginMappingSource)}).array().default([])@@@ -108,18 -101,10 +110,19 @@@ export const SshHostModal = ({ popUp, hhostname: sshHost.hostname,alias: sshHost.alias ?? "",userCertTtl: sshHost.userCertTtl,- loginMappings: sshHost.loginMappings.map(({ loginUser, allowedPrincipals }) => ({+ loginMappings: sshHost.loginMappings.map(({ loginUser, allowedPrincipals, source }) => ({loginUser,- allowedPrincipals: allowedPrincipals.usernames,+ allowedPrincipals: [+ ...(allowedPrincipals.usernames || []).map((username) => ({+ type: "user" as const,+ value: username+ })),+ ...(allowedPrincipals.groups || []).map((group) => ({+ type: "group" as const,+ value: group+ }))- ]++ ],+ source}))});@@@ -169,24 -159,6 +177,24 @@@}}- const transformedLoginMappings = loginMappings.map(({ loginUser, allowedPrincipals }) => {++ const transformedLoginMappings = hostLoginMappings.map(({ loginUser, allowedPrincipals }) => {+ const usernames = allowedPrincipals+ .filter((p) => p.type === "user" && p.value)+ .map((p) => p.value);++ const groupNames = allowedPrincipals+ .filter((p) => p.type === "group" && p.value)+ .map((p) => p.value);++ return {+ loginUser,+ allowedPrincipals: {+ usernames,+ groups: groupNames+ }+ };+ });+if (sshHost) {await updateMutateAsync({sshHostId: sshHost.id,@@@ -300,7 -273,11 +308,11 @@@variant="outline_bg"onClick={() => {const newIndex = loginMappingsFormFields.fields.length;- loginMappingsFormFields.append({ loginUser: "", allowedPrincipals: [] });+ loginMappingsFormFields.append({+ loginUser: "",- allowedPrincipals: [""],++ allowedPrincipals: [],+ source: LoginMappingSource.HOST+ });setExpandedMappings((prev) => ({...prev,[newIndex]: true@@@ -390,89 -389,70 +424,105 @@@label="Allowed Principals"className="text-xs text-mineshaft-400"/>- <Button- leftIcon={<FontAwesomeIcon icon={faPlus} />}- size="xs"- variant="outline_bg"- onClick={() => {- const current = getValues(`loginMappings.${i}.allowedPrincipals`) ?? [];- setValue(`loginMappings.${i}.allowedPrincipals`, [- ...current,- { type: "user", value: "" }- ]);- }}- >- Add Principal- </Button>+ {loginMappingsFormFields.fields[i].source === LoginMappingSource.HOST && (+ <Button+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ size="xs"+ variant="outline_bg"+ onClick={() => {+ const current =+ getValues(`loginMappings.${i}.allowedPrincipals`) ?? [];- setValue(`loginMappings.${i}.allowedPrincipals`, [...current, ""]);++ setValue(`loginMappings.${i}.allowedPrincipals`, [++ ...current,++ { type: "user", value: "" }++ ]);+ }}+ >+ Add Principal+ </Button>+ )}</div><Controllercontrol={control}name={`loginMappings.${i}.allowedPrincipals`}render={({ field: { value = [], onChange }, fieldState: { error } }) => (<div className="flex flex-col space-y-2">- {(value.length === 0 ? [""] : value).map(- (principal: string, principalIndex: number) => (- <div- key={`${metadataFieldId}-principal-${principal}`}- className="flex items-center space-x-2"- >- <div className="flex-1">- <Select- value={principal}- onValueChange={(newValue) => {- if (- loginMappingsFormFields.fields[i].source ===- LoginMappingSource.HOST_GROUP- )- return;-- if (value.includes(newValue)) {- createNotification({- text: "This principal is already added",- type: "error"- });- return;- }- const newPrincipals = [...value];- newPrincipals[principalIndex] = newValue;- onChange(newPrincipals);- }}- placeholder="Select a member"- className="w-full"- isDisabled={+ {value.map((principal, principalIndex) => (+ <div+ key={`principal-${i + 1}-${principalIndex + 1}-${principal.type}`}+ className="flex items-center space-x-2"+ >+ <div className="mr-2">+ <Select+ className="w-24"+ value={principal.type}+ onValueChange={(newType) => {+ const newPrincipals = [...value];+ newPrincipals[principalIndex] = {+ type: newType as "user" | "group",+ value: ""+ };+ onChange(newPrincipals);+ }}++ isDisabled={++ loginMappingsFormFields.fields[i].source ===++ LoginMappingSource.HOST_GROUP++ }+ >+ <SelectItem value="user">User</SelectItem>+ <SelectItem value="group">Group</SelectItem>+ </Select>+ </div>+ <div className="flex-1">+ <Select+ value={principal.value}+ onValueChange={(newValue) => {++ if (+ loginMappingsFormFields.fields[i].source ===+ LoginMappingSource.HOST_GROUP++ )++ return;+ if (isPrincipalDuplicate(i, principal.type, newValue)) {+ createNotification({+ text: `This ${principal.type} is already added`,+ type: "error"+ });+ return;}- >- {members.map((member) => (- <SelectItem- key={member.user.id}- value={member.user.username}- >- {member.user.username}- </SelectItem>- ))}- </Select>- </div>+ const newPrincipals = [...value];+ newPrincipals[principalIndex] = {+ type: principal.type,+ value: newValue+ };+ onChange(newPrincipals);+ }}+ placeholder={`Select a ${principal.type}`}+ className="w-full"++ isDisabled={++ loginMappingsFormFields.fields[i].source ===++ LoginMappingSource.HOST_GROUP++ }+ >+ {principal.type === "user"+ ? members.map((member) => (+ <SelectItem+ key={member.user.id}+ value={member.user.username}+ >+ {member.user.username}+ </SelectItem>+ ))+ : groups.map((group) => (+ <SelectItem+ key={group.group.slug}+ value={group.group.slug}+ >+ {group.group.slug}+ </SelectItem>+ ))}+ </Select>+ </div>+ <div className="flex w-10 justify-center"><IconButtonsize="sm"ariaLabel="delete principal"@@@ -482,8 -468,12 +538,12 @@@const newPrincipals = value.filter((_, idx) => idx !== principalIndex);- onChange(newPrincipals);+ onChange([...newPrincipals]);}}+ isDisabled={+ loginMappingsFormFields.fields[i].source ===+ LoginMappingSource.HOST_GROUP+ }><FontAwesomeIcon icon={faTrash} /></IconButton>diff --cc frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsxindex 02b7f3d9cc,491307d216..fd43697ec6--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx@@@ -93,49 -91,73 +94,110 @@@ export const SshHostsTable = ({ handleP{host.loginMappings.length === 0 ? (<span className="italic text-mineshaft-400">None</span>) : (- host.loginMappings.map(({ loginUser, allowedPrincipals }) => (- <div key={`${host.id}-${loginUser}`} className="mb-3">- <div className="mb-1 text-mineshaft-200">{loginUser}</div>- <div className="ml-4 flex flex-col gap-1">- {allowedPrincipals.usernames.map((username) => (- <div- key={`${host.id}-${loginUser}-${username}`}- className="flex items-center gap-2"- >- <div className="flex items-center">- <span className="text-gray-400">└─</span>- </div>- <div className="flex items-center gap-1.5">- <FontAwesomeIcon- icon={faUser}- className="text-xs text-yellow/80"- />- <span>{username}</span>- <Badge variant="primary">user</Badge>- </div>+ (() => {+ const hostMappings = host.loginMappings.filter(+ (m) => m.source !== LoginMappingSource.HOST_GROUP+ );+ const groupMappings = host.loginMappings.filter(+ (m) => m.source === LoginMappingSource.HOST_GROUP+ );++ const hostLoginUserToPrincipals = hostMappings.reduce(+ (acc, { loginUser, allowedPrincipals }) => {- acc[loginUser] = new Set(allowedPrincipals.usernames);++ acc[loginUser] = {++ users: new Set(allowedPrincipals.usernames),++ groups: new Set(allowedPrincipals.groups)++ };+ return acc;+ },- {} as Record<string, Set<string>>++ {} as Record<string, { users: Set<string>; groups: Set<string> }>+ );++ const entriesFromHost = hostMappings.map(+ ({ loginUser, allowedPrincipals }) => ({+ loginUser,+ source: LoginMappingSource.HOST,- usernames: allowedPrincipals.usernames++ users: allowedPrincipals.usernames,++ groups: allowedPrincipals.groups+ })+ );++ const entriesFromGroup = groupMappings+ .map(({ loginUser, allowedPrincipals }) => {- const existing = hostLoginUserToPrincipals[loginUser] || new Set();- const filteredUsernames = allowedPrincipals.usernames.filter(- (u) => !existing.has(u)++ const existing = hostLoginUserToPrincipals[loginUser] || {};++ const filteredUsernames = allowedPrincipals.usernames?.filter(++ (u) => !existing.users?.has(u)+ );- return filteredUsernames.length > 0++ const filteredGroups = allowedPrincipals.groups?.filter(++ (g) => !existing.groups?.has(g)++ );++ return (filteredGroups?.length ?? 0) > 0+ ? {+ loginUser,+ source: LoginMappingSource.HOST_GROUP,- usernames: filteredUsernames++ users: filteredUsernames,++ groups: filteredGroups+ }+ : null;+ })+ .filter(Boolean) as {+ loginUser: string;+ source: LoginMappingSource;- usernames: string[];++ users: string[];++ groups: string[];+ }[];++ return [...entriesFromHost, ...entriesFromGroup]+ .sort((a, b) => a.loginUser.localeCompare(b.loginUser))- .map(({ loginUser, usernames, source }) => (++ .map(({ loginUser, users, groups, source }) => (+ <div key={`${host.id}-${loginUser}-${source}`} className="mb-2">+ <div className="text-mineshaft-200">+ {loginUser}+ {source === LoginMappingSource.HOST_GROUP && (+ <span className="ml-2 text-xs text-mineshaft-400">+ (inherited from host group)+ </span>+ )}</div>- ))}- {allowedPrincipals.groups.map((group) => (- <div- key={`${host.id}-${loginUser}-${group}`}- className="flex items-center gap-2"- >- <div className="flex items-center">- <span className="text-gray-400">└─</span>- {usernames.map((username) => (++ {users?.map((username) => (+ <div+ key={`${host.id}-${loginUser}-${source}-${username}`}- className="ml-4"++ className="flex items-center gap-2"++ >++ <div className="flex items-center">++ <span className="text-gray-400">└─</span>++ </div>++ <div className="flex items-center gap-1.5">++ <FontAwesomeIcon++ icon={faUser}++ className="text-xs text-yellow/80"++ />++ <span>{username}</span>++ <Badge variant="primary">user</Badge>++ </div>+ </div>- <div className="flex items-center gap-1.5">- <FontAwesomeIcon- icon={faUsers}- className="text-xs text-green/80"- />- <span>{group}</span>- <Badge variant="success">group</Badge>++ ))}++ {groups?.map((group) => (++ <div++ key={`${host.id}-${loginUser}-${source}-${group}`}++ className="flex items-center gap-2"+ >- └─ {username}++ <div className="flex items-center">++ <span className="text-gray-400">└─</span>++ </div>++ <div className="flex items-center gap-1.5">++ <FontAwesomeIcon++ icon={faUsers}++ className="text-xs text-green/80"++ />++ <span>{group}</span>++ <Badge variant="success">group</Badge>++ </div></div>- </div>- ))}- </div>- </div>- ))+ ))}+ </div>+ ));+ })())}</Td><Td className="text-right align-middle">