mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-09-22 13:39:35 +00:00
Merge branch 'main' into PAM-79
This commit is contained in:
@@ -3,6 +3,11 @@ import {
|
||||
SanitizedAwsIamAccountWithResourceSchema,
|
||||
UpdateAwsIamAccountSchema
|
||||
} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
|
||||
import {
|
||||
CreateKubernetesAccountSchema,
|
||||
SanitizedKubernetesAccountWithResourceSchema,
|
||||
UpdateKubernetesAccountSchema
|
||||
} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
|
||||
import {
|
||||
CreateMySQLAccountSchema,
|
||||
SanitizedMySQLAccountWithResourceSchema,
|
||||
@@ -50,6 +55,15 @@ export const PAM_ACCOUNT_REGISTER_ROUTER_MAP: Record<PamResource, (server: Fasti
|
||||
updateAccountSchema: UpdateSSHAccountSchema
|
||||
});
|
||||
},
|
||||
[PamResource.Kubernetes]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.Kubernetes,
|
||||
accountResponseSchema: SanitizedKubernetesAccountWithResourceSchema,
|
||||
createAccountSchema: CreateKubernetesAccountSchema,
|
||||
updateAccountSchema: UpdateKubernetesAccountSchema
|
||||
});
|
||||
},
|
||||
[PamResource.AwsIam]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
|
||||
@@ -4,6 +4,7 @@ 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-enums";
|
||||
import { SanitizedAwsIamAccountWithResourceSchema } from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
|
||||
import { SanitizedKubernetesAccountWithResourceSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
|
||||
import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import { GatewayAccessResponseSchema } from "@app/ee/services/pam-resource/pam-resource-schemas";
|
||||
@@ -21,10 +22,17 @@ const SanitizedAccountSchema = z.union([
|
||||
SanitizedSSHAccountWithResourceSchema, // ORDER MATTERS
|
||||
SanitizedPostgresAccountWithResourceSchema,
|
||||
SanitizedMySQLAccountWithResourceSchema,
|
||||
SanitizedKubernetesAccountWithResourceSchema,
|
||||
SanitizedAwsIamAccountWithResourceSchema
|
||||
]);
|
||||
|
||||
type TSanitizedAccount = z.infer<typeof SanitizedAccountSchema>;
|
||||
const ListPamAccountsResponseSchema = z.object({
|
||||
accounts: SanitizedAccountSchema.array(),
|
||||
folders: PamFoldersSchema.array(),
|
||||
totalCount: z.number().default(0),
|
||||
folderId: z.string().optional(),
|
||||
folderPaths: z.record(z.string(), z.string())
|
||||
});
|
||||
|
||||
export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -55,13 +63,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
|
||||
.optional()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
accounts: SanitizedAccountSchema.array(),
|
||||
folders: PamFoldersSchema.array(),
|
||||
totalCount: z.number().default(0),
|
||||
folderId: z.string().optional(),
|
||||
folderPaths: z.record(z.string(), z.string())
|
||||
})
|
||||
200: ListPamAccountsResponseSchema
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
@@ -98,7 +100,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { accounts: accounts as TSanitizedAccount[], folders, totalCount, folderId, folderPaths };
|
||||
return { accounts, folders, totalCount, folderId, folderPaths } as z.infer<typeof ListPamAccountsResponseSchema>;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -135,6 +137,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
|
||||
GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Postgres) }),
|
||||
GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.MySQL) }),
|
||||
GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.SSH) }),
|
||||
GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Kubernetes) }),
|
||||
// AWS IAM (no gateway, returns console URL)
|
||||
z.object({
|
||||
sessionId: z.string(),
|
||||
|
||||
@@ -3,6 +3,11 @@ import {
|
||||
SanitizedAwsIamResourceSchema,
|
||||
UpdateAwsIamResourceSchema
|
||||
} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
|
||||
import {
|
||||
CreateKubernetesResourceSchema,
|
||||
SanitizedKubernetesResourceSchema,
|
||||
UpdateKubernetesResourceSchema
|
||||
} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
|
||||
import {
|
||||
CreateMySQLResourceSchema,
|
||||
MySQLResourceSchema,
|
||||
@@ -50,6 +55,15 @@ export const PAM_RESOURCE_REGISTER_ROUTER_MAP: Record<PamResource, (server: Fast
|
||||
updateResourceSchema: UpdateSSHResourceSchema
|
||||
});
|
||||
},
|
||||
[PamResource.Kubernetes]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.Kubernetes,
|
||||
resourceResponseSchema: SanitizedKubernetesResourceSchema,
|
||||
createResourceSchema: CreateKubernetesResourceSchema,
|
||||
updateResourceSchema: UpdateKubernetesResourceSchema
|
||||
});
|
||||
},
|
||||
[PamResource.AwsIam]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
|
||||
@@ -5,6 +5,10 @@ import {
|
||||
AwsIamResourceListItemSchema,
|
||||
SanitizedAwsIamResourceSchema
|
||||
} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
|
||||
import {
|
||||
KubernetesResourceListItemSchema,
|
||||
SanitizedKubernetesResourceSchema
|
||||
} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
|
||||
import {
|
||||
MySQLResourceListItemSchema,
|
||||
SanitizedMySQLResourceSchema
|
||||
@@ -27,6 +31,7 @@ const SanitizedResourceSchema = z.union([
|
||||
SanitizedPostgresResourceSchema,
|
||||
SanitizedMySQLResourceSchema,
|
||||
SanitizedSSHResourceSchema,
|
||||
SanitizedKubernetesResourceSchema,
|
||||
SanitizedAwsIamResourceSchema
|
||||
]);
|
||||
|
||||
@@ -34,6 +39,7 @@ const ResourceOptionsSchema = z.discriminatedUnion("resource", [
|
||||
PostgresResourceListItemSchema,
|
||||
MySQLResourceListItemSchema,
|
||||
SSHResourceListItemSchema,
|
||||
KubernetesResourceListItemSchema,
|
||||
AwsIamResourceListItemSchema
|
||||
]);
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ import { z } from "zod";
|
||||
|
||||
import { PamSessionsSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { KubernetesSessionCredentialsSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
|
||||
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 {
|
||||
HttpEventSchema,
|
||||
PamSessionCommandLogSchema,
|
||||
SanitizedSessionSchema,
|
||||
TerminalEventSchema
|
||||
@@ -17,7 +19,8 @@ import { AuthMode } from "@app/services/auth/auth-type";
|
||||
const SessionCredentialsSchema = z.union([
|
||||
SSHSessionCredentialsSchema,
|
||||
PostgresSessionCredentialsSchema,
|
||||
MySQLSessionCredentialsSchema
|
||||
MySQLSessionCredentialsSchema,
|
||||
KubernetesSessionCredentialsSchema
|
||||
]);
|
||||
|
||||
export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
|
||||
@@ -89,7 +92,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
|
||||
sessionId: z.string().uuid()
|
||||
}),
|
||||
body: z.object({
|
||||
logs: z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema]))
|
||||
logs: z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema, HttpEventSchema]))
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
|
||||
@@ -689,13 +689,30 @@ export const pamAccountServiceFactory = ({
|
||||
throw new BadRequestError({ message: "Gateway ID is required for this resource type" });
|
||||
}
|
||||
|
||||
const { host, port } =
|
||||
resourceType !== PamResource.Kubernetes
|
||||
? connectionDetails
|
||||
: (() => {
|
||||
const url = new URL(connectionDetails.url);
|
||||
let portNumber: number | undefined;
|
||||
if (url.port) {
|
||||
portNumber = Number(url.port);
|
||||
} else {
|
||||
portNumber = url.protocol === "https:" ? 443 : 80;
|
||||
}
|
||||
return {
|
||||
host: url.hostname,
|
||||
port: portNumber
|
||||
};
|
||||
})();
|
||||
|
||||
const gatewayConnectionDetails = await gatewayV2Service.getPAMConnectionDetails({
|
||||
gatewayId,
|
||||
duration,
|
||||
sessionId: session.id,
|
||||
resourceType: resource.resourceType as PamResource,
|
||||
host: (connectionDetails as TSqlResourceConnectionDetails).host,
|
||||
port: (connectionDetails as TSqlResourceConnectionDetails).port,
|
||||
host,
|
||||
port,
|
||||
actorMetadata: {
|
||||
id: actor.id,
|
||||
type: actor.type,
|
||||
@@ -746,6 +763,13 @@ export const pamAccountServiceFactory = ({
|
||||
};
|
||||
}
|
||||
break;
|
||||
case PamResource.Kubernetes:
|
||||
metadata = {
|
||||
resourceName: resource.name,
|
||||
accountName: account.name,
|
||||
accountPath
|
||||
};
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -71,23 +71,29 @@ export const pamFolderDALFactory = (db: TDbClient) => {
|
||||
const findByPath = async (projectId: string, path: string, tx?: Knex) => {
|
||||
try {
|
||||
const dbInstance = tx || db.replicaNode();
|
||||
|
||||
const folders = await dbInstance(TableName.PamFolder)
|
||||
.where(`${TableName.PamFolder}.projectId`, projectId)
|
||||
.select(selectAllTableCols(TableName.PamFolder));
|
||||
|
||||
const pathSegments = path.split("/").filter(Boolean);
|
||||
if (pathSegments.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const foldersByParentId = new Map<string | null, typeof folders>();
|
||||
for (const folder of folders) {
|
||||
const children = foldersByParentId.get(folder.parentId ?? null) ?? [];
|
||||
children.push(folder);
|
||||
foldersByParentId.set(folder.parentId ?? null, children);
|
||||
}
|
||||
|
||||
let parentId: string | null = null;
|
||||
let currentFolder: Awaited<ReturnType<typeof orm.findOne>> | undefined;
|
||||
let currentFolder: (typeof folders)[0] | 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();
|
||||
for (const segment of pathSegments) {
|
||||
const childFolders: typeof folders = foldersByParentId.get(parentId) || [];
|
||||
currentFolder = childFolders.find((folder) => folder.name === segment);
|
||||
|
||||
if (!currentFolder) {
|
||||
return undefined;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export enum KubernetesAuthMethod {
|
||||
ServiceAccountToken = "service-account-token"
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import axios, { AxiosError } from "axios";
|
||||
import https from "https";
|
||||
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { GatewayProxyProtocol } from "@app/lib/gateway/types";
|
||||
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
|
||||
import { logger } from "@app/lib/logger";
|
||||
|
||||
import { verifyHostInputValidity } from "../../dynamic-secret/dynamic-secret-fns";
|
||||
import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
|
||||
import { PamResource } from "../pam-resource-enums";
|
||||
import {
|
||||
TPamResourceFactory,
|
||||
TPamResourceFactoryRotateAccountCredentials,
|
||||
TPamResourceFactoryValidateAccountCredentials
|
||||
} from "../pam-resource-types";
|
||||
import { KubernetesAuthMethod } from "./kubernetes-resource-enums";
|
||||
import { TKubernetesAccountCredentials, TKubernetesResourceConnectionDetails } from "./kubernetes-resource-types";
|
||||
|
||||
const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
|
||||
|
||||
export const executeWithGateway = async <T>(
|
||||
config: {
|
||||
connectionDetails: TKubernetesResourceConnectionDetails;
|
||||
resourceType: PamResource;
|
||||
gatewayId: string;
|
||||
},
|
||||
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
|
||||
operation: (baseUrl: string, httpsAgent: https.Agent) => Promise<T>
|
||||
): Promise<T> => {
|
||||
const { connectionDetails, gatewayId } = config;
|
||||
const url = new URL(connectionDetails.url);
|
||||
const [targetHost] = await verifyHostInputValidity(url.hostname, true);
|
||||
|
||||
let targetPort: number;
|
||||
if (url.port) {
|
||||
targetPort = Number(url.port);
|
||||
} else if (url.protocol === "https:") {
|
||||
targetPort = 443;
|
||||
} else {
|
||||
targetPort = 80;
|
||||
}
|
||||
|
||||
const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
|
||||
gatewayId,
|
||||
targetHost,
|
||||
targetPort
|
||||
});
|
||||
if (!platformConnectionDetails) {
|
||||
throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
|
||||
}
|
||||
const httpsAgent = new https.Agent({
|
||||
ca: connectionDetails.sslCertificate,
|
||||
rejectUnauthorized: connectionDetails.sslRejectUnauthorized,
|
||||
servername: targetHost
|
||||
});
|
||||
return withGatewayV2Proxy(
|
||||
async (proxyPort) => {
|
||||
const protocol = url.protocol === "https:" ? "https" : "http";
|
||||
const baseUrl = `${protocol}://localhost:${proxyPort}`;
|
||||
return operation(baseUrl, httpsAgent);
|
||||
},
|
||||
{
|
||||
protocol: GatewayProxyProtocol.Tcp,
|
||||
relayHost: platformConnectionDetails.relayHost,
|
||||
gateway: platformConnectionDetails.gateway,
|
||||
relay: platformConnectionDetails.relay,
|
||||
httpsAgent
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
export const kubernetesResourceFactory: TPamResourceFactory<
|
||||
TKubernetesResourceConnectionDetails,
|
||||
TKubernetesAccountCredentials
|
||||
> = (resourceType, connectionDetails, gatewayId, gatewayV2Service) => {
|
||||
const validateConnection = async () => {
|
||||
if (!gatewayId) {
|
||||
throw new BadRequestError({ message: "Gateway ID is required" });
|
||||
}
|
||||
try {
|
||||
await executeWithGateway(
|
||||
{ connectionDetails, gatewayId, resourceType },
|
||||
gatewayV2Service,
|
||||
async (baseUrl, httpsAgent) => {
|
||||
// Validate connection by checking API server version
|
||||
try {
|
||||
await axios.get(`${baseUrl}/version`, {
|
||||
...(httpsAgent ? { httpsAgent } : {}),
|
||||
signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
|
||||
timeout: EXTERNAL_REQUEST_TIMEOUT
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AxiosError) {
|
||||
// If we get a 401/403, it means we reached the API server but need auth - that's fine for connection validation
|
||||
if (error.response?.status === 401 || error.response?.status === 403) {
|
||||
logger.info(
|
||||
{ status: error.response.status },
|
||||
"[Kubernetes Resource Factory] Kubernetes connection validation succeeded (auth required)"
|
||||
);
|
||||
return connectionDetails;
|
||||
}
|
||||
throw new BadRequestError({
|
||||
message: `Unable to connect to Kubernetes API server: ${error.response?.statusText || error.message}`
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
logger.info("[Kubernetes Resource Factory] Kubernetes connection validation succeeded");
|
||||
return connectionDetails;
|
||||
}
|
||||
);
|
||||
return connectionDetails;
|
||||
} catch (error) {
|
||||
throw new BadRequestError({
|
||||
message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}`
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const validateAccountCredentials: TPamResourceFactoryValidateAccountCredentials<
|
||||
TKubernetesAccountCredentials
|
||||
> = async (credentials) => {
|
||||
if (!gatewayId) {
|
||||
throw new BadRequestError({ message: "Gateway ID is required" });
|
||||
}
|
||||
try {
|
||||
await executeWithGateway(
|
||||
{ connectionDetails, gatewayId, resourceType },
|
||||
gatewayV2Service,
|
||||
async (baseUrl, httpsAgent) => {
|
||||
const { authMethod } = credentials;
|
||||
if (authMethod === KubernetesAuthMethod.ServiceAccountToken) {
|
||||
// Validate service account token using SelfSubjectReview API (whoami)
|
||||
// This endpoint doesn't require any special permissions from the service account
|
||||
try {
|
||||
await axios.post(
|
||||
`${baseUrl}/apis/authentication.k8s.io/v1/selfsubjectreviews`,
|
||||
{
|
||||
apiVersion: "authentication.k8s.io/v1",
|
||||
kind: "SelfSubjectReview"
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${credentials.serviceAccountToken}`
|
||||
},
|
||||
...(httpsAgent ? { httpsAgent } : {}),
|
||||
signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
|
||||
timeout: EXTERNAL_REQUEST_TIMEOUT
|
||||
}
|
||||
);
|
||||
|
||||
logger.info("[Kubernetes Resource Factory] Kubernetes service account token authentication successful");
|
||||
} catch (error) {
|
||||
if (error instanceof AxiosError) {
|
||||
if (error.response?.status === 401 || error.response?.status === 403) {
|
||||
throw new BadRequestError({
|
||||
message:
|
||||
"Account credentials invalid. Service account token is not valid or does not have required permissions."
|
||||
});
|
||||
}
|
||||
throw new BadRequestError({
|
||||
message: `Unable to validate account credentials: ${error.response?.statusText || error.message}`
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else {
|
||||
throw new BadRequestError({
|
||||
message: `Unsupported Kubernetes auth method: ${authMethod as string}`
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
return credentials;
|
||||
} catch (error) {
|
||||
if (error instanceof BadRequestError) {
|
||||
throw error;
|
||||
}
|
||||
throw new BadRequestError({
|
||||
message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<
|
||||
TKubernetesAccountCredentials
|
||||
> = async () => {
|
||||
throw new BadRequestError({
|
||||
message: `Unable to rotate account credentials for ${resourceType}: not implemented`
|
||||
});
|
||||
};
|
||||
|
||||
const handleOverwritePreventionForCensoredValues = async (
|
||||
updatedAccountCredentials: TKubernetesAccountCredentials,
|
||||
currentCredentials: TKubernetesAccountCredentials
|
||||
) => {
|
||||
if (updatedAccountCredentials.authMethod !== currentCredentials.authMethod) {
|
||||
return updatedAccountCredentials;
|
||||
}
|
||||
|
||||
if (
|
||||
updatedAccountCredentials.authMethod === KubernetesAuthMethod.ServiceAccountToken &&
|
||||
currentCredentials.authMethod === KubernetesAuthMethod.ServiceAccountToken
|
||||
) {
|
||||
if (updatedAccountCredentials.serviceAccountToken === "__INFISICAL_UNCHANGED__") {
|
||||
return {
|
||||
...updatedAccountCredentials,
|
||||
serviceAccountToken: currentCredentials.serviceAccountToken
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return updatedAccountCredentials;
|
||||
};
|
||||
|
||||
return {
|
||||
validateConnection,
|
||||
validateAccountCredentials,
|
||||
rotateAccountCredentials,
|
||||
handleOverwritePreventionForCensoredValues
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import { KubernetesResourceListItemSchema } from "./kubernetes-resource-schemas";
|
||||
|
||||
export const getKubernetesResourceListItem = () => {
|
||||
return {
|
||||
name: KubernetesResourceListItemSchema.shape.name.value,
|
||||
resource: KubernetesResourceListItemSchema.shape.resource.value
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,94 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PamResource } from "../pam-resource-enums";
|
||||
import {
|
||||
BaseCreateGatewayPamResourceSchema,
|
||||
BaseCreatePamAccountSchema,
|
||||
BasePamAccountSchema,
|
||||
BasePamAccountSchemaWithResource,
|
||||
BasePamResourceSchema,
|
||||
BaseUpdateGatewayPamResourceSchema,
|
||||
BaseUpdatePamAccountSchema
|
||||
} from "../pam-resource-schemas";
|
||||
import { KubernetesAuthMethod } from "./kubernetes-resource-enums";
|
||||
|
||||
export const BaseKubernetesResourceSchema = BasePamResourceSchema.extend({
|
||||
resourceType: z.literal(PamResource.Kubernetes)
|
||||
});
|
||||
|
||||
export const KubernetesResourceListItemSchema = z.object({
|
||||
name: z.literal("Kubernetes"),
|
||||
resource: z.literal(PamResource.Kubernetes)
|
||||
});
|
||||
|
||||
export const KubernetesResourceConnectionDetailsSchema = z.object({
|
||||
url: z.string().url().trim().max(500),
|
||||
sslRejectUnauthorized: z.boolean(),
|
||||
sslCertificate: z
|
||||
.string()
|
||||
.trim()
|
||||
.transform((value) => value || undefined)
|
||||
.optional()
|
||||
});
|
||||
|
||||
export const KubernetesServiceAccountTokenCredentialsSchema = z.object({
|
||||
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken),
|
||||
serviceAccountToken: z.string().trim().max(10000)
|
||||
});
|
||||
|
||||
export const KubernetesAccountCredentialsSchema = z.discriminatedUnion("authMethod", [
|
||||
KubernetesServiceAccountTokenCredentialsSchema
|
||||
]);
|
||||
|
||||
export const KubernetesResourceSchema = BaseKubernetesResourceSchema.extend({
|
||||
connectionDetails: KubernetesResourceConnectionDetailsSchema,
|
||||
rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
|
||||
});
|
||||
|
||||
export const SanitizedKubernetesResourceSchema = BaseKubernetesResourceSchema.extend({
|
||||
connectionDetails: KubernetesResourceConnectionDetailsSchema,
|
||||
rotationAccountCredentials: z
|
||||
.discriminatedUnion("authMethod", [
|
||||
z.object({
|
||||
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
|
||||
})
|
||||
])
|
||||
.nullable()
|
||||
.optional()
|
||||
});
|
||||
|
||||
export const CreateKubernetesResourceSchema = BaseCreateGatewayPamResourceSchema.extend({
|
||||
connectionDetails: KubernetesResourceConnectionDetailsSchema,
|
||||
rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
|
||||
});
|
||||
|
||||
export const UpdateKubernetesResourceSchema = BaseUpdateGatewayPamResourceSchema.extend({
|
||||
connectionDetails: KubernetesResourceConnectionDetailsSchema.optional(),
|
||||
rotationAccountCredentials: KubernetesAccountCredentialsSchema.nullable().optional()
|
||||
});
|
||||
|
||||
// Accounts
|
||||
export const KubernetesAccountSchema = BasePamAccountSchema.extend({
|
||||
credentials: KubernetesAccountCredentialsSchema
|
||||
});
|
||||
|
||||
export const CreateKubernetesAccountSchema = BaseCreatePamAccountSchema.extend({
|
||||
credentials: KubernetesAccountCredentialsSchema
|
||||
});
|
||||
|
||||
export const UpdateKubernetesAccountSchema = BaseUpdatePamAccountSchema.extend({
|
||||
credentials: KubernetesAccountCredentialsSchema.optional()
|
||||
});
|
||||
|
||||
export const SanitizedKubernetesAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({
|
||||
credentials: z.discriminatedUnion("authMethod", [
|
||||
z.object({
|
||||
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
|
||||
})
|
||||
])
|
||||
});
|
||||
|
||||
// Sessions
|
||||
export const KubernetesSessionCredentialsSchema = KubernetesResourceConnectionDetailsSchema.and(
|
||||
KubernetesAccountCredentialsSchema
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
KubernetesAccountCredentialsSchema,
|
||||
KubernetesAccountSchema,
|
||||
KubernetesResourceConnectionDetailsSchema,
|
||||
KubernetesResourceSchema
|
||||
} from "./kubernetes-resource-schemas";
|
||||
|
||||
// Resources
|
||||
export type TKubernetesResource = z.infer<typeof KubernetesResourceSchema>;
|
||||
export type TKubernetesResourceConnectionDetails = z.infer<typeof KubernetesResourceConnectionDetailsSchema>;
|
||||
|
||||
// Accounts
|
||||
export type TKubernetesAccount = z.infer<typeof KubernetesAccountSchema>;
|
||||
export type TKubernetesAccountCredentials = z.infer<typeof KubernetesAccountCredentialsSchema>;
|
||||
@@ -2,6 +2,7 @@ export enum PamResource {
|
||||
Postgres = "postgres",
|
||||
MySQL = "mysql",
|
||||
SSH = "ssh",
|
||||
Kubernetes = "kubernetes",
|
||||
AwsIam = "aws-iam"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { awsIamResourceFactory } from "./aws-iam/aws-iam-resource-factory";
|
||||
import { kubernetesResourceFactory } from "./kubernetes/kubernetes-resource-factory";
|
||||
import { PamResource } from "./pam-resource-enums";
|
||||
import { TPamAccountCredentials, TPamResourceConnectionDetails, TPamResourceFactory } from "./pam-resource-types";
|
||||
import { sqlResourceFactory } from "./shared/sql/sql-resource-factory";
|
||||
@@ -10,5 +11,6 @@ export const PAM_RESOURCE_FACTORY_MAP: Record<PamResource, TPamResourceFactoryIm
|
||||
[PamResource.Postgres]: sqlResourceFactory as TPamResourceFactoryImplementation,
|
||||
[PamResource.MySQL]: sqlResourceFactory as TPamResourceFactoryImplementation,
|
||||
[PamResource.SSH]: sshResourceFactory as TPamResourceFactoryImplementation,
|
||||
[PamResource.Kubernetes]: kubernetesResourceFactory as TPamResourceFactoryImplementation,
|
||||
[PamResource.AwsIam]: awsIamResourceFactory as TPamResourceFactoryImplementation
|
||||
};
|
||||
|
||||
@@ -4,14 +4,18 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
|
||||
import { decryptAccountCredentials } from "../pam-account/pam-account-fns";
|
||||
import { getAwsIamResourceListItem } from "./aws-iam/aws-iam-resource-fns";
|
||||
import { getKubernetesResourceListItem } from "./kubernetes/kubernetes-resource-fns";
|
||||
import { getMySQLResourceListItem } from "./mysql/mysql-resource-fns";
|
||||
import { TPamResource, TPamResourceConnectionDetails } from "./pam-resource-types";
|
||||
import { getPostgresResourceListItem } from "./postgres/postgres-resource-fns";
|
||||
|
||||
export const listResourceOptions = () => {
|
||||
return [getPostgresResourceListItem(), getMySQLResourceListItem(), getAwsIamResourceListItem()].sort((a, b) =>
|
||||
a.name.localeCompare(b.name)
|
||||
);
|
||||
return [
|
||||
getPostgresResourceListItem(),
|
||||
getMySQLResourceListItem(),
|
||||
getAwsIamResourceListItem(),
|
||||
getKubernetesResourceListItem()
|
||||
].sort((a, b) => a.name.localeCompare(b.name));
|
||||
};
|
||||
|
||||
// Resource
|
||||
|
||||
@@ -7,6 +7,12 @@ import {
|
||||
TAwsIamResource,
|
||||
TAwsIamResourceConnectionDetails
|
||||
} from "./aws-iam/aws-iam-resource-types";
|
||||
import {
|
||||
TKubernetesAccount,
|
||||
TKubernetesAccountCredentials,
|
||||
TKubernetesResource,
|
||||
TKubernetesResourceConnectionDetails
|
||||
} from "./kubernetes/kubernetes-resource-types";
|
||||
import {
|
||||
TMySQLAccount,
|
||||
TMySQLAccountCredentials,
|
||||
@@ -28,21 +34,23 @@ import {
|
||||
} from "./ssh/ssh-resource-types";
|
||||
|
||||
// Resource types
|
||||
export type TPamResource = TPostgresResource | TMySQLResource | TSSHResource | TAwsIamResource;
|
||||
export type TPamResource = TPostgresResource | TMySQLResource | TSSHResource | TAwsIamResource | TKubernetesResource;
|
||||
export type TPamResourceConnectionDetails =
|
||||
| TPostgresResourceConnectionDetails
|
||||
| TMySQLResourceConnectionDetails
|
||||
| TSSHResourceConnectionDetails
|
||||
| TKubernetesResourceConnectionDetails
|
||||
| TAwsIamResourceConnectionDetails;
|
||||
|
||||
// Account types
|
||||
export type TPamAccount = TPostgresAccount | TMySQLAccount | TSSHAccount | TAwsIamAccount;
|
||||
export type TPamAccount = TPostgresAccount | TMySQLAccount | TSSHAccount | TAwsIamAccount | TKubernetesAccount;
|
||||
|
||||
export type TPamAccountCredentials =
|
||||
| TPostgresAccountCredentials
|
||||
// eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents
|
||||
| TMySQLAccountCredentials
|
||||
| TSSHAccountCredentials
|
||||
| TKubernetesAccountCredentials
|
||||
| TAwsIamAccountCredentials;
|
||||
|
||||
// Resource DTOs
|
||||
|
||||
@@ -11,6 +11,8 @@ export const PamSessionCommandLogSchema = z.object({
|
||||
// SSH Terminal Event schemas
|
||||
export const TerminalEventTypeSchema = z.enum(["input", "output", "resize", "error"]);
|
||||
|
||||
export const HttpEventTypeSchema = z.enum(["request", "response"]);
|
||||
|
||||
export const TerminalEventSchema = z.object({
|
||||
timestamp: z.coerce.date(),
|
||||
eventType: TerminalEventTypeSchema,
|
||||
@@ -18,8 +20,29 @@ export const TerminalEventSchema = z.object({
|
||||
elapsedTime: z.number() // Seconds since session start (for replay)
|
||||
});
|
||||
|
||||
export const HttpBaseEventSchema = z.object({
|
||||
timestamp: z.coerce.date(),
|
||||
requestId: z.string(),
|
||||
eventType: TerminalEventTypeSchema,
|
||||
headers: z.record(z.string(), z.array(z.string())),
|
||||
body: z.string().optional()
|
||||
});
|
||||
|
||||
export const HttpRequestEventSchema = HttpBaseEventSchema.extend({
|
||||
eventType: z.literal(HttpEventTypeSchema.Values.request),
|
||||
method: z.string(),
|
||||
url: z.string()
|
||||
});
|
||||
|
||||
export const HttpResponseEventSchema = HttpBaseEventSchema.extend({
|
||||
eventType: z.literal(HttpEventTypeSchema.Values.response),
|
||||
status: z.string()
|
||||
});
|
||||
|
||||
export const HttpEventSchema = z.discriminatedUnion("eventType", [HttpRequestEventSchema, HttpResponseEventSchema]);
|
||||
|
||||
export const SanitizedSessionSchema = PamSessionsSchema.omit({
|
||||
encryptedLogsBlob: true
|
||||
}).extend({
|
||||
logs: z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema]))
|
||||
logs: z.array(z.union([PamSessionCommandLogSchema, HttpEventSchema, TerminalEventSchema]))
|
||||
});
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PamSessionCommandLogSchema, SanitizedSessionSchema, TerminalEventSchema } from "./pam-session-schemas";
|
||||
import {
|
||||
HttpEventSchema,
|
||||
PamSessionCommandLogSchema,
|
||||
SanitizedSessionSchema,
|
||||
TerminalEventSchema
|
||||
} from "./pam-session-schemas";
|
||||
|
||||
export type TPamSessionCommandLog = z.infer<typeof PamSessionCommandLogSchema>;
|
||||
export type TTerminalEvent = z.infer<typeof TerminalEventSchema>;
|
||||
export type THttpEvent = z.infer<typeof HttpEventSchema>;
|
||||
export type TPamSanitizedSession = z.infer<typeof SanitizedSessionSchema>;
|
||||
|
||||
// DTOs
|
||||
export type TUpdateSessionLogsDTO = {
|
||||
sessionId: string;
|
||||
logs: (TPamSessionCommandLog | TTerminalEvent)[];
|
||||
logs: (TPamSessionCommandLog | TTerminalEvent | THttpEvent)[];
|
||||
};
|
||||
|
||||
@@ -214,7 +214,10 @@ export const secretRotationV2DALFactory = (
|
||||
tx?: Knex
|
||||
) => {
|
||||
try {
|
||||
const extendedQuery = baseSecretRotationV2Query({ filter, db, tx, options })
|
||||
const { limit, offset = 0, sort, ...queryOptions } = options || {};
|
||||
const baseOptions = { ...queryOptions };
|
||||
|
||||
const subquery = baseSecretRotationV2Query({ filter, db, tx, options: baseOptions })
|
||||
.join(
|
||||
TableName.SecretRotationV2SecretMapping,
|
||||
`${TableName.SecretRotationV2SecretMapping}.rotationId`,
|
||||
@@ -233,6 +236,7 @@ export const secretRotationV2DALFactory = (
|
||||
)
|
||||
.leftJoin(TableName.ResourceMetadata, `${TableName.SecretV2}.id`, `${TableName.ResourceMetadata}.secretId`)
|
||||
.select(
|
||||
selectAllTableCols(TableName.SecretRotationV2),
|
||||
db.ref("id").withSchema(TableName.SecretV2).as("secretId"),
|
||||
db.ref("key").withSchema(TableName.SecretV2).as("secretKey"),
|
||||
db.ref("version").withSchema(TableName.SecretV2).as("secretVersion"),
|
||||
@@ -252,18 +256,31 @@ export const secretRotationV2DALFactory = (
|
||||
db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"),
|
||||
db.ref("id").withSchema(TableName.ResourceMetadata).as("metadataId"),
|
||||
db.ref("key").withSchema(TableName.ResourceMetadata).as("metadataKey"),
|
||||
db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue")
|
||||
db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue"),
|
||||
db.raw(`DENSE_RANK() OVER (ORDER BY ${TableName.SecretRotationV2}."createdAt" DESC) as rank`)
|
||||
);
|
||||
|
||||
if (search) {
|
||||
void extendedQuery.where((query) => {
|
||||
void query
|
||||
void subquery.where((qb) => {
|
||||
void qb
|
||||
.whereILike(`${TableName.SecretV2}.key`, `%${search}%`)
|
||||
.orWhereILike(`${TableName.SecretRotationV2}.name`, `%${search}%`);
|
||||
});
|
||||
}
|
||||
|
||||
const secretRotations = await extendedQuery;
|
||||
let secretRotations: Awaited<typeof subquery>;
|
||||
if (limit !== undefined) {
|
||||
const rankOffset = offset + 1;
|
||||
const queryWithLimit = (tx || db)
|
||||
.with("inner", subquery)
|
||||
.select("*")
|
||||
.from("inner")
|
||||
.where("inner.rank", ">=", rankOffset)
|
||||
.andWhere("inner.rank", "<", rankOffset + limit);
|
||||
secretRotations = (await queryWithLimit) as unknown as Awaited<typeof subquery>;
|
||||
} else {
|
||||
secretRotations = await subquery;
|
||||
}
|
||||
|
||||
if (!secretRotations.length) return [];
|
||||
|
||||
|
||||
@@ -624,7 +624,10 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
||||
secretValueHidden: z.boolean(),
|
||||
secretPath: z.string().optional(),
|
||||
secretMetadata: ResourceMetadataSchema.optional(),
|
||||
tags: SanitizedTagSchema.array().optional()
|
||||
tags: SanitizedTagSchema.array().optional(),
|
||||
reminder: RemindersSchema.extend({
|
||||
recipients: z.string().array()
|
||||
}).nullable()
|
||||
})
|
||||
.nullable()
|
||||
.array()
|
||||
@@ -743,6 +746,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
||||
ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>
|
||||
>[number]["secrets"][number] & {
|
||||
isEmpty: boolean;
|
||||
reminder: Awaited<ReturnType<typeof server.services.reminder.getRemindersForDashboard>>[string] | null;
|
||||
}
|
||||
> | null)[];
|
||||
})[]
|
||||
@@ -847,27 +851,38 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
||||
);
|
||||
|
||||
if (remainingLimit > 0 && totalSecretRotationCount > adjustedOffset) {
|
||||
secretRotations = (
|
||||
await server.services.secretRotationV2.getDashboardSecretRotations(
|
||||
{
|
||||
projectId,
|
||||
search,
|
||||
orderBy,
|
||||
orderDirection,
|
||||
environments: [environment],
|
||||
secretPath,
|
||||
limit: remainingLimit,
|
||||
offset: adjustedOffset
|
||||
},
|
||||
req.permission
|
||||
)
|
||||
).map((rotation) => ({
|
||||
const rawSecretRotations = await server.services.secretRotationV2.getDashboardSecretRotations(
|
||||
{
|
||||
projectId,
|
||||
search,
|
||||
orderBy,
|
||||
orderDirection,
|
||||
environments: [environment],
|
||||
secretPath,
|
||||
limit: remainingLimit,
|
||||
offset: adjustedOffset
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
const allRotationSecretIds = rawSecretRotations
|
||||
.flatMap((rotation) => rotation.secrets)
|
||||
.filter((secret) => Boolean(secret))
|
||||
.map((secret) => secret.id);
|
||||
|
||||
const rotationReminders =
|
||||
allRotationSecretIds.length > 0
|
||||
? await server.services.reminder.getRemindersForDashboard(allRotationSecretIds)
|
||||
: {};
|
||||
|
||||
secretRotations = rawSecretRotations.map((rotation) => ({
|
||||
...rotation,
|
||||
secrets: rotation.secrets.map((secret) =>
|
||||
secret
|
||||
? {
|
||||
...secret,
|
||||
isEmpty: !secret.secretValue
|
||||
isEmpty: !secret.secretValue,
|
||||
reminder: rotationReminders[secret.id] ?? null
|
||||
}
|
||||
: secret
|
||||
)
|
||||
@@ -948,7 +963,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
||||
search,
|
||||
tagSlugs: tags,
|
||||
includeTagsInSearch: true,
|
||||
includeMetadataInSearch: true
|
||||
includeMetadataInSearch: true,
|
||||
excludeRotatedSecrets: includeSecretRotations
|
||||
});
|
||||
|
||||
if (remainingLimit > 0 && totalSecretCount > adjustedOffset) {
|
||||
@@ -970,7 +986,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
|
||||
offset: adjustedOffset,
|
||||
tagSlugs: tags,
|
||||
includeTagsInSearch: true,
|
||||
includeMetadataInSearch: true
|
||||
includeMetadataInSearch: true,
|
||||
excludeRotatedSecrets: includeSecretRotations
|
||||
})
|
||||
).secrets;
|
||||
|
||||
|
||||
@@ -416,6 +416,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
|
||||
tagSlugs?: string[];
|
||||
includeTagsInSearch?: boolean;
|
||||
includeMetadataInSearch?: boolean;
|
||||
excludeRotatedSecrets?: boolean;
|
||||
}
|
||||
) => {
|
||||
try {
|
||||
@@ -481,6 +482,10 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
|
||||
);
|
||||
}
|
||||
|
||||
if (filters?.excludeRotatedSecrets) {
|
||||
void query.whereNull(`${TableName.SecretRotationV2SecretMapping}.secretId`);
|
||||
}
|
||||
|
||||
const secrets = await query;
|
||||
|
||||
// @ts-expect-error not inferred by knex
|
||||
@@ -594,6 +599,11 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
|
||||
void bd.whereIn(`${TableName.SecretTag}.slug`, slugs);
|
||||
}
|
||||
})
|
||||
.where((bd) => {
|
||||
if (filters?.excludeRotatedSecrets) {
|
||||
void bd.whereNull(`${TableName.SecretRotationV2SecretMapping}.secretId`);
|
||||
}
|
||||
})
|
||||
.orderBy(
|
||||
filters?.orderBy === SecretsOrderBy.Name ? "key" : "id",
|
||||
filters?.orderDirection ?? OrderByDirection.ASC
|
||||
|
||||
@@ -483,8 +483,8 @@ export const secretV2BridgeServiceFactory = ({
|
||||
});
|
||||
if (!sharedSecretToModify)
|
||||
throw new NotFoundError({ message: `Secret with name ${inputSecret.secretName} not found` });
|
||||
if (sharedSecretToModify.isRotatedSecret && (inputSecret.newSecretName || inputSecret.secretValue))
|
||||
throw new BadRequestError({ message: "Cannot update rotated secret name or value" });
|
||||
if (sharedSecretToModify.isRotatedSecret && inputSecret.newSecretName)
|
||||
throw new BadRequestError({ message: "Cannot update rotated secret name" });
|
||||
secretId = sharedSecretToModify.id;
|
||||
secret = sharedSecretToModify;
|
||||
}
|
||||
@@ -888,6 +888,7 @@ export const secretV2BridgeServiceFactory = ({
|
||||
| "tagSlugs"
|
||||
| "environment"
|
||||
| "search"
|
||||
| "excludeRotatedSecrets"
|
||||
>) => {
|
||||
const { permission } = await permissionService.getProjectPermission({
|
||||
actor,
|
||||
@@ -1934,8 +1935,14 @@ export const secretV2BridgeServiceFactory = ({
|
||||
if (el.isRotatedSecret) {
|
||||
const input = secretsToUpdateGroupByPath[secretPath].find((i) => i.secretKey === el.key);
|
||||
|
||||
if (input && (input.newSecretName || input.secretValue))
|
||||
throw new BadRequestError({ message: `Cannot update rotated secret name or value: ${el.key}` });
|
||||
if (input) {
|
||||
if (input.newSecretName) {
|
||||
delete input.newSecretName;
|
||||
}
|
||||
if (input.secretValue !== undefined) {
|
||||
delete input.secretValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2061,8 +2068,11 @@ export const secretV2BridgeServiceFactory = ({
|
||||
commitChanges,
|
||||
inputSecrets: secretsToUpdate.map((el) => {
|
||||
const originalSecret = secretsToUpdateInDBGroupedByKey[el.secretKey][0];
|
||||
const shouldUpdateValue = !originalSecret.isRotatedSecret && typeof el.secretValue !== "undefined";
|
||||
const shouldUpdateName = !originalSecret.isRotatedSecret && el.newSecretName;
|
||||
|
||||
const encryptedValue =
|
||||
typeof el.secretValue !== "undefined"
|
||||
shouldUpdateValue && el.secretValue !== undefined
|
||||
? {
|
||||
encryptedValue: secretManagerEncryptor({ plainText: Buffer.from(el.secretValue) }).cipherTextBlob,
|
||||
references: secretReferencesGroupByInputSecretKey[el.secretKey]?.nestedReferences
|
||||
@@ -2077,7 +2087,7 @@ export const secretV2BridgeServiceFactory = ({
|
||||
(value) => secretManagerEncryptor({ plainText: Buffer.from(value) }).cipherTextBlob
|
||||
),
|
||||
skipMultilineEncoding: el.skipMultilineEncoding,
|
||||
key: el.newSecretName || el.secretKey,
|
||||
key: shouldUpdateName ? el.newSecretName : el.secretKey,
|
||||
tags: el.tagIds,
|
||||
secretMetadata: el.secretMetadata,
|
||||
...encryptedValue
|
||||
|
||||
@@ -50,6 +50,7 @@ export type TGetSecretsDTO = {
|
||||
limit?: number;
|
||||
search?: string;
|
||||
keys?: string[];
|
||||
excludeRotatedSecrets?: boolean;
|
||||
} & TProjectPermission;
|
||||
|
||||
export type TGetSecretsMissingReadValuePermissionDTO = Omit<
|
||||
@@ -362,6 +363,7 @@ export type TFindSecretsByFolderIdsFilter = {
|
||||
includeTagsInSearch?: boolean;
|
||||
includeMetadataInSearch?: boolean;
|
||||
keys?: string[];
|
||||
excludeRotatedSecrets?: boolean;
|
||||
};
|
||||
|
||||
export type TGetSecretsRawByFolderMappingsDTO = {
|
||||
|
||||
@@ -1154,6 +1154,7 @@ export const secretServiceFactory = ({
|
||||
| "search"
|
||||
| "includeTagsInSearch"
|
||||
| "includeMetadataInSearch"
|
||||
| "excludeRotatedSecrets"
|
||||
>) => {
|
||||
const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
|
||||
|
||||
|
||||
@@ -214,6 +214,7 @@ export type TGetSecretsRawDTO = {
|
||||
keys?: string[];
|
||||
includeTagsInSearch?: boolean;
|
||||
includeMetadataInSearch?: boolean;
|
||||
excludeRotatedSecrets?: boolean;
|
||||
} & TProjectPermission;
|
||||
|
||||
export type TGetSecretAccessListDTO = {
|
||||
|
||||
@@ -795,12 +795,6 @@
|
||||
"documentation/platform/pam/product-reference/session-recording",
|
||||
"documentation/platform/pam/product-reference/credential-rotation"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Resources",
|
||||
"pages": [
|
||||
"documentation/platform/pam/resources/aws-iam"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
224
docs/documentation/platform/pam/resources/kubernetes.mdx
Normal file
224
docs/documentation/platform/pam/resources/kubernetes.mdx
Normal file
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: "Kubernetes"
|
||||
sidebarTitle: "Kubernetes"
|
||||
description: "Learn how to configure Kubernetes cluster access through Infisical PAM for secure, audited, and just-in-time access to your Kubernetes clusters."
|
||||
---
|
||||
|
||||
Infisical PAM supports secure, just-in-time access to Kubernetes clusters through service account token authentication. This allows your team to access Kubernetes clusters without sharing long-lived credentials, while maintaining a complete audit trail of who accessed what and when.
|
||||
|
||||
## How It Works
|
||||
|
||||
Kubernetes access in Infisical PAM uses an Infisical Gateway to securely proxy connections to your Kubernetes API server. When a user requests access, Infisical generates a temporary kubeconfig that routes traffic through the Gateway, enabling secure access without exposing your cluster directly.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User
|
||||
participant CLI as Infisical CLI
|
||||
participant Infisical
|
||||
participant Gateway as Infisical Gateway
|
||||
participant K8s as Kubernetes API Server
|
||||
|
||||
User->>CLI: Request Kubernetes access
|
||||
CLI->>Infisical: Authenticate & request session
|
||||
Infisical-->>CLI: Session credentials & Gateway info
|
||||
CLI->>CLI: Start local proxy
|
||||
CLI->>Gateway: Establish secure tunnel
|
||||
User->>CLI: kubectl commands
|
||||
CLI->>Gateway: Proxy kubectl requests
|
||||
Gateway->>K8s: Forward with SA token
|
||||
K8s-->>Gateway: Response
|
||||
Gateway-->>CLI: Return response
|
||||
CLI-->>User: kubectl output
|
||||
```
|
||||
|
||||
### Key Concepts
|
||||
|
||||
1. **Gateway**: An Infisical Gateway deployed in your network that can reach the Kubernetes API server. The Gateway handles secure communication between users and your cluster.
|
||||
|
||||
2. **Service Account Token**: A Kubernetes service account token that grants access to the cluster. This token is stored securely in Infisical and used by the Gateway to authenticate with the Kubernetes API.
|
||||
|
||||
3. **Local Proxy**: The Infisical CLI starts a local proxy on your machine that intercepts kubectl commands and routes them securely through the Gateway to your cluster.
|
||||
|
||||
4. **Session Tracking**: All access sessions are logged, including when the session was created, who accessed the cluster, session duration, and when it ended.
|
||||
|
||||
### Session Tracking
|
||||
|
||||
Infisical tracks:
|
||||
- When the session was created
|
||||
- Who accessed which cluster
|
||||
- Session duration
|
||||
- All kubectl commands executed during the session
|
||||
- When the session ended
|
||||
|
||||
<Info>
|
||||
**Session Logs**: After ending a session (by stopping the proxy), you can view detailed session logs in the Sessions page, including all commands executed during the session.
|
||||
</Info>
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before configuring Kubernetes access in Infisical PAM, you need:
|
||||
|
||||
1. **Infisical Gateway** - A Gateway deployed in your network with access to the Kubernetes API server
|
||||
2. **Service Account** - A Kubernetes service account with appropriate RBAC permissions
|
||||
3. **Infisical CLI** - The Infisical CLI installed on user machines
|
||||
|
||||
<Warning>
|
||||
**Gateway Required**: Unlike AWS Console access, Kubernetes access requires an Infisical Gateway to be deployed and registered with your Infisical instance. The Gateway must have network connectivity to your Kubernetes API server.
|
||||
</Warning>
|
||||
|
||||
## Create the PAM Resource
|
||||
|
||||
The PAM Resource represents the connection between Infisical and your Kubernetes cluster.
|
||||
|
||||
<Steps>
|
||||
<Step title="Ensure Gateway is Running">
|
||||
Before creating the resource, ensure you have an Infisical Gateway running and registered with your Infisical instance. The Gateway must have network access to your Kubernetes API server.
|
||||
</Step>
|
||||
|
||||
<Step title="Create the Resource in Infisical">
|
||||
1. Navigate to your PAM project and go to the **Resources** tab
|
||||
2. Click **Add Resource** and select **Kubernetes**
|
||||
3. Enter a name for the resource (e.g., `production-k8s`, `staging-cluster`)
|
||||
4. Enter the **Kubernetes API Server URL** - the URL to your Kubernetes API endpoint (e.g.`https://kubernetes.example.com:6443`)
|
||||
5. Select the **Gateway** that has access to this cluster
|
||||
6. Configure SSL verification options if needed
|
||||
|
||||
<Note>
|
||||
**SSL Verification**: You may need to disable SSL verification if your Kubernetes API server uses a self-signed certificate or if the certificate's hostname doesn't match the URL you're using to access it.
|
||||
</Note>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Create a Service Account
|
||||
|
||||
Infisical PAM currently supports service account token authentication for Kubernetes. You'll need to create a service account with appropriate permissions in your cluster.
|
||||
|
||||
<Steps>
|
||||
<Step title="Create the Service Account YAML">
|
||||
Create a file named `sa.yaml` with the following content:
|
||||
|
||||
```yaml sa.yaml
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: infisical-pam-sa
|
||||
namespace: kube-system
|
||||
---
|
||||
# Bind the ServiceAccount to the desired ClusterRole
|
||||
# This example uses cluster-admin - adjust based on your needs
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: ClusterRoleBinding
|
||||
metadata:
|
||||
name: infisical-pam-binding
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: infisical-pam-sa
|
||||
namespace: kube-system
|
||||
roleRef:
|
||||
kind: ClusterRole
|
||||
name: cluster-admin # Change this to a more restrictive role as needed
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
---
|
||||
# Create a static, non-expiring token for the ServiceAccount
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: infisical-pam-sa-token
|
||||
namespace: kube-system
|
||||
annotations:
|
||||
kubernetes.io/service-account.name: infisical-pam-sa
|
||||
type: kubernetes.io/service-account-token
|
||||
```
|
||||
|
||||
<Warning>
|
||||
**Security Best Practice**: The example above uses `cluster-admin` for simplicity. In production environments, you should create custom ClusterRoles or Roles with the minimum permissions required for each use case.
|
||||
</Warning>
|
||||
</Step>
|
||||
|
||||
<Step title="Apply the Service Account">
|
||||
Apply the configuration to your cluster:
|
||||
|
||||
```bash
|
||||
kubectl apply -f sa.yaml
|
||||
```
|
||||
|
||||
This creates:
|
||||
- A ServiceAccount named `infisical-pam-sa` in the `kube-system` namespace
|
||||
- A ClusterRoleBinding that grants the service account its permissions
|
||||
- A Secret containing a static, non-expiring token for the service account
|
||||
</Step>
|
||||
|
||||
<Step title="Retrieve the Service Account Token">
|
||||
Get the service account token that you'll use when creating the PAM account:
|
||||
|
||||
```bash
|
||||
kubectl -n kube-system get secret infisical-pam-sa-token -o jsonpath='{.data.token}' | base64 -d
|
||||
```
|
||||
|
||||
Copy this token - you'll need it in the next step.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Create PAM Accounts
|
||||
|
||||
Once you have configured the PAM resource, you'll need to configure a PAM account for your Kubernetes resource.
|
||||
A PAM Account represents a specific service account that users can request access to. You can create multiple accounts per resource, each with different permission levels.
|
||||
|
||||
<Steps>
|
||||
<Step title="Navigate to Accounts">
|
||||
Go to the **Accounts** tab in your PAM project.
|
||||
</Step>
|
||||
|
||||
<Step title="Add New Account">
|
||||
Click **Add Account** and select the Kubernetes resource you created.
|
||||
</Step>
|
||||
|
||||
<Step title="Fill in Account Details">
|
||||
Fill in the account details and paste the service account token you retrieved earlier.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Access Kubernetes Cluster
|
||||
|
||||
Once your resource and accounts are configured, users can request access through the Infisical CLI:
|
||||
|
||||
<Steps>
|
||||
<Step title="Get the Access Command">
|
||||
1. Navigate to the **Accounts** tab in your PAM project
|
||||
2. Find the Kubernetes account you want to access
|
||||
3. Click the **Access** button
|
||||
4. Copy the provided CLI command
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Access Command">
|
||||
Run the copied command in your terminal.
|
||||
|
||||
The CLI will:
|
||||
1. Authenticate with Infisical
|
||||
2. Establish a secure connection through the Gateway
|
||||
3. Start a local proxy on your machine
|
||||
4. Configure kubectl to use the proxy
|
||||
</Step>
|
||||
|
||||
<Step title="Use kubectl">
|
||||
Once the proxy is running, you can use `kubectl` commands as normal:
|
||||
|
||||
```bash
|
||||
kubectl get pods
|
||||
kubectl get namespaces
|
||||
kubectl describe deployment my-app
|
||||
```
|
||||
|
||||
All commands are routed securely through the Infisical Gateway to your cluster.
|
||||
</Step>
|
||||
|
||||
<Step title="End the Session">
|
||||
When you're done, stop the proxy by pressing `Ctrl+C` in the terminal where it's running. This will:
|
||||
- Close the secure tunnel
|
||||
- End the session
|
||||
- Log the session details to Infisical
|
||||
|
||||
You can view session logs in the **Sessions** page of your PAM project.
|
||||
</Step>
|
||||
</Steps>
|
||||
@@ -7,18 +7,30 @@ import {
|
||||
PamSessionStatus
|
||||
} from "../enums";
|
||||
import { TAwsIamAccount, TAwsIamResource } from "./aws-iam-resource";
|
||||
import { TKubernetesAccount, TKubernetesResource } from "./kubernetes-resource";
|
||||
import { TMySQLAccount, TMySQLResource } from "./mysql-resource";
|
||||
import { TPostgresAccount, TPostgresResource } from "./postgres-resource";
|
||||
import { TSSHAccount, TSSHResource } from "./ssh-resource";
|
||||
|
||||
export * from "./aws-iam-resource";
|
||||
export * from "./kubernetes-resource";
|
||||
export * from "./mysql-resource";
|
||||
export * from "./postgres-resource";
|
||||
export * from "./ssh-resource";
|
||||
|
||||
export type TPamResource = TPostgresResource | TMySQLResource | TSSHResource | TAwsIamResource;
|
||||
export type TPamResource =
|
||||
| TPostgresResource
|
||||
| TMySQLResource
|
||||
| TSSHResource
|
||||
| TAwsIamResource
|
||||
| TKubernetesResource;
|
||||
|
||||
export type TPamAccount = TPostgresAccount | TMySQLAccount | TSSHAccount | TAwsIamAccount;
|
||||
export type TPamAccount =
|
||||
| TPostgresAccount
|
||||
| TMySQLAccount
|
||||
| TSSHAccount
|
||||
| TAwsIamAccount
|
||||
| TKubernetesAccount;
|
||||
|
||||
export type TPamFolder = {
|
||||
id: string;
|
||||
@@ -44,7 +56,28 @@ export type TTerminalEvent = {
|
||||
elapsedTime: number; // Seconds since session start (for replay)
|
||||
};
|
||||
|
||||
export type TPamSessionLog = TPamCommandLog | TTerminalEvent;
|
||||
export type THttpRequestEvent = {
|
||||
timestamp: string;
|
||||
requestId: string;
|
||||
eventType: "request";
|
||||
headers: Record<string, string[]>;
|
||||
method: string;
|
||||
url: string;
|
||||
body?: string;
|
||||
};
|
||||
|
||||
export type THttpResponseEvent = {
|
||||
timestamp: string;
|
||||
requestId: string;
|
||||
eventType: "response";
|
||||
headers: Record<string, string[]>;
|
||||
status: string;
|
||||
body?: string;
|
||||
};
|
||||
|
||||
export type THttpEvent = THttpRequestEvent | THttpResponseEvent;
|
||||
|
||||
export type TPamSessionLog = TPamCommandLog | TTerminalEvent | THttpEvent;
|
||||
|
||||
export type TPamSession = {
|
||||
id: string;
|
||||
|
||||
33
frontend/src/hooks/api/pam/types/kubernetes-resource.ts
Normal file
33
frontend/src/hooks/api/pam/types/kubernetes-resource.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { PamResourceType } from "../enums";
|
||||
import { TBasePamAccount } from "./base-account";
|
||||
import { TBasePamResource } from "./base-resource";
|
||||
|
||||
export enum KubernetesAuthMethod {
|
||||
ServiceAccountToken = "service-account-token"
|
||||
}
|
||||
|
||||
export type TKubernetesConnectionDetails = {
|
||||
url: string;
|
||||
sslRejectUnauthorized: boolean;
|
||||
sslCertificate?: string;
|
||||
};
|
||||
|
||||
export type TKubernetesServiceAccountTokenCredentials = {
|
||||
authMethod: KubernetesAuthMethod.ServiceAccountToken;
|
||||
serviceAccountToken: string;
|
||||
};
|
||||
|
||||
export type TKubernetesCredentials = TKubernetesServiceAccountTokenCredentials;
|
||||
|
||||
// Resources
|
||||
export type TKubernetesResource = TBasePamResource & {
|
||||
resourceType: PamResourceType.Kubernetes;
|
||||
} & {
|
||||
connectionDetails: TKubernetesConnectionDetails;
|
||||
rotationAccountCredentials?: TKubernetesCredentials | null;
|
||||
};
|
||||
|
||||
// Accounts
|
||||
export type TKubernetesAccount = TBasePamAccount & {
|
||||
credentials: TKubernetesCredentials;
|
||||
};
|
||||
@@ -170,7 +170,7 @@ export const Navbar = () => {
|
||||
const [isOrgSelectOpen, setIsOrgSelectOpen] = useState(false);
|
||||
|
||||
const location = useLocation();
|
||||
const isBillingPage = location.pathname === "/organization/billing";
|
||||
const isBillingPage = location.pathname === `/organizations/${currentOrg.id}/billing`;
|
||||
|
||||
const isModalIntrusive = Boolean(!isBillingPage && isCardDeclinedMoreThan30Days);
|
||||
|
||||
|
||||
@@ -85,6 +85,8 @@ export const PamAccessAccountModal = ({
|
||||
return `infisical pam db access-account ${fullAccountPath} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
|
||||
case PamResourceType.SSH:
|
||||
return `infisical pam ssh access-account ${fullAccountPath} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
|
||||
case PamResourceType.Kubernetes:
|
||||
return `infisical pam kubernetes access-account ${fullAccountPath} --project-id ${projectId} --duration ${cliDuration} --domain ${siteURL}`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Controller, FormProvider, useForm, useFormContext } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
|
||||
import { Button, FormControl, ModalClose, TextArea } from "@app/components/v2";
|
||||
import { KubernetesAuthMethod, PamResourceType, TKubernetesAccount } from "@app/hooks/api/pam";
|
||||
import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
|
||||
|
||||
import { GenericAccountFields, genericAccountFieldsSchema } from "./GenericAccountFields";
|
||||
import { rotateAccountFieldsSchema } from "./RotateAccountFields";
|
||||
|
||||
type Props = {
|
||||
account?: TKubernetesAccount;
|
||||
resourceId?: string;
|
||||
resourceType?: PamResourceType;
|
||||
onSubmit: (formData: FormData) => Promise<void>;
|
||||
};
|
||||
|
||||
const KubernetesServiceAccountTokenCredentialsSchema = z.object({
|
||||
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken),
|
||||
serviceAccountToken: z.string().trim().min(1, "Service account token is required")
|
||||
});
|
||||
|
||||
const formSchema = genericAccountFieldsSchema.extend(rotateAccountFieldsSchema.shape).extend({
|
||||
credentials: KubernetesServiceAccountTokenCredentialsSchema
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof formSchema>;
|
||||
|
||||
const KubernetesAccountFields = ({ isUpdate }: { isUpdate: boolean }) => {
|
||||
const { control } = useFormContext<FormData>();
|
||||
|
||||
return (
|
||||
<div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3">
|
||||
<Controller
|
||||
name="credentials.serviceAccountToken"
|
||||
control={control}
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
className="mb-0"
|
||||
errorText={error?.message}
|
||||
isError={Boolean(error?.message)}
|
||||
label="Service Account Token"
|
||||
helperText="The bearer token for the service account"
|
||||
>
|
||||
<TextArea
|
||||
{...field}
|
||||
value={field.value === UNCHANGED_PASSWORD_SENTINEL ? "" : field.value || ""}
|
||||
className="min-h-32 resize-y font-mono text-xs"
|
||||
placeholder={
|
||||
isUpdate && field.value === UNCHANGED_PASSWORD_SENTINEL
|
||||
? "Token unchanged - click to update"
|
||||
: "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const KubernetesAccountForm = ({ account, onSubmit }: Props) => {
|
||||
const isUpdate = Boolean(account);
|
||||
|
||||
const form = useForm<FormData>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: account
|
||||
? {
|
||||
...account,
|
||||
credentials: {
|
||||
...account.credentials,
|
||||
serviceAccountToken: UNCHANGED_PASSWORD_SENTINEL
|
||||
}
|
||||
}
|
||||
: {
|
||||
name: "",
|
||||
description: "",
|
||||
credentials: {
|
||||
authMethod: KubernetesAuthMethod.ServiceAccountToken,
|
||||
serviceAccountToken: ""
|
||||
},
|
||||
rotationEnabled: false
|
||||
}
|
||||
});
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
formState: { isSubmitting, isDirty }
|
||||
} = form;
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
handleSubmit(onSubmit)(e);
|
||||
}}
|
||||
>
|
||||
<GenericAccountFields />
|
||||
<KubernetesAccountFields isUpdate={isUpdate} />
|
||||
<div className="mt-6 flex items-center">
|
||||
<Button
|
||||
className="mr-4"
|
||||
size="sm"
|
||||
type="submit"
|
||||
colorSchema="secondary"
|
||||
isLoading={isSubmitting}
|
||||
isDisabled={isSubmitting || !isDirty}
|
||||
>
|
||||
{isUpdate ? "Update Account" : "Create Account"}
|
||||
</Button>
|
||||
<ModalClose asChild>
|
||||
<Button colorSchema="secondary" variant="plain">
|
||||
Cancel
|
||||
</Button>
|
||||
</ModalClose>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
@@ -9,6 +9,7 @@ import { DiscriminativePick } from "@app/types";
|
||||
|
||||
import { PamAccountHeader } from "../PamAccountHeader";
|
||||
import { AwsIamAccountForm } from "./AwsIamAccountForm";
|
||||
import { KubernetesAccountForm } from "./KubernetesAccountForm";
|
||||
import { MySQLAccountForm } from "./MySQLAccountForm";
|
||||
import { PostgresAccountForm } from "./PostgresAccountForm";
|
||||
import { SshAccountForm } from "./SshAccountForm";
|
||||
@@ -71,6 +72,14 @@ const CreateForm = ({
|
||||
return (
|
||||
<SshAccountForm onSubmit={onSubmit} resourceId={resourceId} resourceType={resourceType} />
|
||||
);
|
||||
case PamResourceType.Kubernetes:
|
||||
return (
|
||||
<KubernetesAccountForm
|
||||
onSubmit={onSubmit}
|
||||
resourceId={resourceId}
|
||||
resourceType={resourceType}
|
||||
/>
|
||||
);
|
||||
case PamResourceType.AwsIam:
|
||||
return (
|
||||
<AwsIamAccountForm
|
||||
@@ -109,6 +118,8 @@ const UpdateForm = ({ account, onComplete }: UpdateFormProps) => {
|
||||
return <MySQLAccountForm account={account as any} onSubmit={onSubmit} />;
|
||||
case PamResourceType.SSH:
|
||||
return <SshAccountForm account={account as any} onSubmit={onSubmit} />;
|
||||
case PamResourceType.Kubernetes:
|
||||
return <KubernetesAccountForm account={account as any} onSubmit={onSubmit} />;
|
||||
case PamResourceType.AwsIam:
|
||||
return <AwsIamAccountForm account={account as any} onSubmit={onSubmit} />;
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
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 { KubernetesAuthMethod, PamResourceType, TKubernetesResource } from "@app/hooks/api/pam";
|
||||
|
||||
import { KubernetesResourceFields } from "./shared/KubernetesResourceFields";
|
||||
import { GenericResourceFields, genericResourceFieldsSchema } from "./GenericResourceFields";
|
||||
|
||||
type Props = {
|
||||
resource?: TKubernetesResource;
|
||||
onSubmit: (formData: FormData) => Promise<void>;
|
||||
};
|
||||
|
||||
const KubernetesConnectionDetailsSchema = z.object({
|
||||
url: z.string().url().trim().max(500),
|
||||
sslRejectUnauthorized: z.boolean(),
|
||||
sslCertificate: z.string().trim().max(10000).optional()
|
||||
});
|
||||
|
||||
const KubernetesServiceAccountTokenCredentialsSchema = z.object({
|
||||
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken),
|
||||
serviceAccountToken: z.string().trim().max(10000)
|
||||
});
|
||||
|
||||
const formSchema = genericResourceFieldsSchema.extend({
|
||||
resourceType: z.literal(PamResourceType.Kubernetes),
|
||||
connectionDetails: KubernetesConnectionDetailsSchema,
|
||||
rotationAccountCredentials: KubernetesServiceAccountTokenCredentialsSchema.nullable().optional()
|
||||
});
|
||||
|
||||
type FormData = z.infer<typeof formSchema>;
|
||||
|
||||
export const KubernetesResourceForm = ({ resource, onSubmit }: Props) => {
|
||||
const isUpdate = Boolean(resource);
|
||||
|
||||
const form = useForm<FormData>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: resource ?? {
|
||||
resourceType: PamResourceType.Kubernetes,
|
||||
connectionDetails: {
|
||||
url: "",
|
||||
sslRejectUnauthorized: true,
|
||||
sslCertificate: undefined
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const {
|
||||
handleSubmit,
|
||||
formState: { isSubmitting, isDirty }
|
||||
} = form;
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<GenericResourceFields />
|
||||
<KubernetesResourceFields />
|
||||
<div className="mt-6 flex items-center">
|
||||
<Button
|
||||
className="mr-4"
|
||||
size="sm"
|
||||
type="submit"
|
||||
colorSchema="secondary"
|
||||
isLoading={isSubmitting}
|
||||
isDisabled={isSubmitting || !isDirty}
|
||||
>
|
||||
{isUpdate ? "Update Details" : "Create Resource"}
|
||||
</Button>
|
||||
<ModalClose asChild>
|
||||
<Button colorSchema="secondary" variant="plain">
|
||||
Cancel
|
||||
</Button>
|
||||
</ModalClose>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
@@ -10,6 +10,7 @@ import { DiscriminativePick } from "@app/types";
|
||||
|
||||
import { PamResourceHeader } from "../PamResourceHeader";
|
||||
import { AwsIamResourceForm } from "./AwsIamResourceForm";
|
||||
import { KubernetesResourceForm } from "./KubernetesResourceForm";
|
||||
import { MySQLResourceForm } from "./MySQLResourceForm";
|
||||
import { PostgresResourceForm } from "./PostgresResourceForm";
|
||||
import { SSHResourceForm } from "./SSHResourceForm";
|
||||
@@ -55,6 +56,8 @@ const CreateForm = ({ resourceType, onComplete, projectId }: CreateFormProps) =>
|
||||
return <MySQLResourceForm onSubmit={onSubmit} />;
|
||||
case PamResourceType.SSH:
|
||||
return <SSHResourceForm onSubmit={onSubmit} />;
|
||||
case PamResourceType.Kubernetes:
|
||||
return <KubernetesResourceForm onSubmit={onSubmit} />;
|
||||
case PamResourceType.AwsIam:
|
||||
return <AwsIamResourceForm onSubmit={onSubmit} />;
|
||||
default:
|
||||
@@ -87,6 +90,8 @@ const UpdateForm = ({ resource, onComplete }: UpdateFormProps) => {
|
||||
return <MySQLResourceForm resource={resource} onSubmit={onSubmit} />;
|
||||
case PamResourceType.SSH:
|
||||
return <SSHResourceForm resource={resource} onSubmit={onSubmit} />;
|
||||
case PamResourceType.Kubernetes:
|
||||
return <KubernetesResourceForm resource={resource} onSubmit={onSubmit} />;
|
||||
case PamResourceType.AwsIam:
|
||||
return <AwsIamResourceForm resource={resource} onSubmit={onSubmit} />;
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import { FormControl, Input, Switch, TextArea, Tooltip } from "@app/components/v2";
|
||||
|
||||
export const KubernetesResourceFields = () => {
|
||||
const { control } = useFormContext();
|
||||
|
||||
return (
|
||||
<div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3">
|
||||
<div className="mt-[0.675rem] flex flex-col gap-4">
|
||||
<Controller
|
||||
name="connectionDetails.url"
|
||||
control={control}
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
errorText={error?.message}
|
||||
isError={Boolean(error?.message)}
|
||||
label="Kubernetes API URL"
|
||||
>
|
||||
<Input placeholder="https://kubernetes.example.com:6443" {...field} />
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="connectionDetails.sslCertificate"
|
||||
control={control}
|
||||
render={({ field, fieldState: { error } }) => (
|
||||
<FormControl
|
||||
errorText={error?.message}
|
||||
isError={Boolean(error?.message)}
|
||||
label="CA Certificate"
|
||||
isOptional
|
||||
>
|
||||
<TextArea
|
||||
className="h-14 resize-none!"
|
||||
{...field}
|
||||
placeholder="-----BEGIN CERTIFICATE-----..."
|
||||
/>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
name="connectionDetails.sslRejectUnauthorized"
|
||||
control={control}
|
||||
render={({ field: { value, onChange }, fieldState: { error } }) => (
|
||||
<FormControl isError={Boolean(error?.message)} errorText={error?.message}>
|
||||
<Switch
|
||||
className="bg-mineshaft-400/50 shadow-inner data-[state=checked]:bg-green/80"
|
||||
id="ssl-reject-unauthorized"
|
||||
thumbClassName="bg-mineshaft-800"
|
||||
isChecked={value}
|
||||
onCheckedChange={onChange}
|
||||
>
|
||||
<p className="w-38">
|
||||
Reject Unauthorized
|
||||
<Tooltip
|
||||
className="max-w-md"
|
||||
content={
|
||||
<p>
|
||||
If enabled, Infisical will only connect to the server if it has a valid,
|
||||
trusted SSL certificate.
|
||||
</p>
|
||||
}
|
||||
>
|
||||
<FontAwesomeIcon icon={faQuestionCircle} size="sm" className="ml-1" />
|
||||
</Tooltip>
|
||||
</p>
|
||||
</Switch>
|
||||
</FormControl>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -2,7 +2,8 @@ import { DocumentationLinkBadge } from "@app/components/v3";
|
||||
import { PAM_RESOURCE_TYPE_MAP, PamResourceType } from "@app/hooks/api/pam";
|
||||
|
||||
const PAM_RESOURCE_DOCS_MAP: Partial<Record<PamResourceType, string>> = {
|
||||
[PamResourceType.AwsIam]: "aws-iam#create-the-pam-resource"
|
||||
[PamResourceType.AwsIam]: "aws-iam#create-the-pam-resource",
|
||||
[PamResourceType.Kubernetes]: "kubernetes"
|
||||
};
|
||||
|
||||
type Props = {
|
||||
|
||||
@@ -38,7 +38,6 @@ export const ResourceTypeSelect = ({ onSelect }: Props) => {
|
||||
{ name: "Redis", resource: PamResourceType.Redis },
|
||||
{ name: "RDP", resource: PamResourceType.RDP },
|
||||
{ name: "SSH", resource: PamResourceType.SSH },
|
||||
{ name: "Kubernetes", resource: PamResourceType.Kubernetes },
|
||||
{ name: "MCP", resource: PamResourceType.MCP },
|
||||
{ name: "Web Application", resource: PamResourceType.WebApp }
|
||||
];
|
||||
@@ -78,7 +77,6 @@ export const ResourceTypeSelect = ({ onSelect }: Props) => {
|
||||
// We temporarily show a special license modal for these because we will have to write some code to complete the integration
|
||||
if (
|
||||
resource === PamResourceType.RDP ||
|
||||
resource === PamResourceType.Kubernetes ||
|
||||
resource === PamResourceType.MCP ||
|
||||
resource === PamResourceType.Redis ||
|
||||
resource === PamResourceType.MongoDB ||
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { faChevronDown, faChevronUp, faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import { Input } from "@app/components/v2";
|
||||
import { HighlightText } from "@app/components/v2/HighlightText";
|
||||
import { THttpEvent } from "@app/hooks/api/pam";
|
||||
|
||||
type Props = {
|
||||
events: THttpEvent[];
|
||||
};
|
||||
|
||||
export const HttpEventView = ({ events }: Props) => {
|
||||
const [search, setSearch] = useState("");
|
||||
const [expandedEvents, setExpandedEvents] = useState<Record<string, boolean>>({});
|
||||
const [expandedSections, setExpandedSections] = useState<
|
||||
Record<string, { headers: boolean; body: boolean }>
|
||||
>({});
|
||||
|
||||
const getContentType = (headers: Record<string, string[]>): string | undefined => {
|
||||
const contentTypeKey = Object.keys(headers).find((key) => key.toLowerCase() === "content-type");
|
||||
return contentTypeKey ? headers[contentTypeKey]?.[0] : undefined;
|
||||
};
|
||||
|
||||
const decodeBase64Body = (body: string): string => {
|
||||
try {
|
||||
return atob(body);
|
||||
} catch {
|
||||
// If base64 decoding fails, return original body
|
||||
return body;
|
||||
}
|
||||
};
|
||||
|
||||
const parseBodyForSearch = (
|
||||
body: string | undefined,
|
||||
headers: Record<string, string[]>
|
||||
): string => {
|
||||
if (!body) return "";
|
||||
|
||||
// Decode base64 first
|
||||
const decodedBody = decodeBase64Body(body);
|
||||
|
||||
const contentType = getContentType(headers);
|
||||
const isJson = contentType?.toLowerCase().includes("application/json");
|
||||
|
||||
if (isJson) {
|
||||
try {
|
||||
const parsed = JSON.parse(decodedBody);
|
||||
return JSON.stringify(parsed);
|
||||
} catch {
|
||||
// If JSON parsing fails, fall back to decoded body
|
||||
return decodedBody;
|
||||
}
|
||||
}
|
||||
|
||||
return decodedBody;
|
||||
};
|
||||
|
||||
const filteredEvents = useMemo(
|
||||
() =>
|
||||
events.filter((event) => {
|
||||
const searchValue = search.trim().toLowerCase();
|
||||
if (!searchValue) return true;
|
||||
|
||||
if (event.eventType === "request") {
|
||||
const bodyForSearch = parseBodyForSearch(event.body, event.headers);
|
||||
return (
|
||||
event.method.toLowerCase().includes(searchValue) ||
|
||||
event.url.toLowerCase().includes(searchValue) ||
|
||||
event.requestId.toLowerCase().includes(searchValue) ||
|
||||
Object.keys(event.headers).some((key) => key.toLowerCase().includes(searchValue)) ||
|
||||
Object.values(event.headers).some((values) =>
|
||||
values.some((value) => value.toLowerCase().includes(searchValue))
|
||||
) ||
|
||||
bodyForSearch.toLowerCase().includes(searchValue)
|
||||
);
|
||||
}
|
||||
return (
|
||||
event.status.toLowerCase().includes(searchValue) ||
|
||||
event.requestId.toLowerCase().includes(searchValue) ||
|
||||
Object.keys(event.headers).some((key) => key.toLowerCase().includes(searchValue)) ||
|
||||
Object.values(event.headers).some((values) =>
|
||||
values.some((value) => value.toLowerCase().includes(searchValue))
|
||||
)
|
||||
);
|
||||
}),
|
||||
[events, search]
|
||||
);
|
||||
|
||||
const formatHeaders = (headers: Record<string, string[]>) => {
|
||||
return Object.entries(headers)
|
||||
.map(([key, values]) => `${key}: ${values.join(", ")}`)
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
const formatBody = (body: string | undefined, headers: Record<string, string[]>): string => {
|
||||
if (!body) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Decode base64 first
|
||||
const decodedBody = decodeBase64Body(body);
|
||||
|
||||
const contentType = getContentType(headers);
|
||||
const isJson = contentType?.toLowerCase().includes("application/json");
|
||||
|
||||
if (isJson) {
|
||||
try {
|
||||
const parsed = JSON.parse(decodedBody);
|
||||
return JSON.stringify(parsed, null, 2);
|
||||
} catch {
|
||||
// If JSON parsing fails, return decoded body
|
||||
return decodedBody;
|
||||
}
|
||||
}
|
||||
|
||||
// For non-JSON content, return decoded body
|
||||
return decodedBody;
|
||||
};
|
||||
|
||||
const getKubectlCommand = (headers: Record<string, string[]>) => {
|
||||
const headerKey = Object.keys(headers).find((key) => key.toLowerCase() === "kubectl-command");
|
||||
return headerKey ? headers[headerKey]?.[0] : undefined;
|
||||
};
|
||||
|
||||
const toggleEvent = (eventKey: string) => {
|
||||
const willBeExpanded = !expandedEvents[eventKey];
|
||||
setExpandedEvents((prev) => ({
|
||||
...prev,
|
||||
[eventKey]: willBeExpanded
|
||||
}));
|
||||
// When expanding, show headers by default (but keep body collapsed)
|
||||
if (willBeExpanded) {
|
||||
setExpandedSections((prev) => ({
|
||||
...prev,
|
||||
[eventKey]: {
|
||||
headers: true,
|
||||
body: prev[eventKey]?.body ?? false
|
||||
}
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSection = (eventKey: string, section: "headers" | "body") => {
|
||||
setExpandedSections((prev) => ({
|
||||
...prev,
|
||||
[eventKey]: {
|
||||
...prev[eventKey],
|
||||
[section]: !prev[eventKey]?.[section]
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
const isEventExpanded = (eventKey: string) => {
|
||||
return expandedEvents[eventKey] ?? false;
|
||||
};
|
||||
|
||||
const isSectionExpanded = (eventKey: string, section: "headers" | "body") => {
|
||||
return expandedSections[eventKey]?.[section] ?? false;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
|
||||
placeholder="Search HTTP events..."
|
||||
className="flex-1 bg-mineshaft-800"
|
||||
containerClassName="bg-transparent"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex grow flex-col gap-2 overflow-y-auto text-xs">
|
||||
{filteredEvents.length > 0 ? (
|
||||
filteredEvents.map((event, index) => {
|
||||
const eventKey = `${event.timestamp}-${event.requestId}-${index}`;
|
||||
const isRequest = event.eventType === "request";
|
||||
const kubectlCommand = getKubectlCommand(event.headers);
|
||||
|
||||
const isExpanded = isEventExpanded(eventKey);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={eventKey}
|
||||
className="flex w-full flex-col rounded-md border border-mineshaft-700 bg-mineshaft-800 p-3"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleEvent(eventKey)}
|
||||
className="flex items-center justify-between text-bunker-400 transition-colors hover:text-bunker-300"
|
||||
>
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<FontAwesomeIcon
|
||||
icon={isExpanded ? faChevronUp : faChevronDown}
|
||||
className="text-xs"
|
||||
/>
|
||||
<span
|
||||
className={`rounded px-2 py-0.5 ${
|
||||
isRequest
|
||||
? "bg-blue-500/20 text-blue-400"
|
||||
: "bg-green-500/20 text-green-400"
|
||||
}`}
|
||||
>
|
||||
{isRequest ? "REQUEST" : "RESPONSE"}
|
||||
</span>
|
||||
{kubectlCommand && (
|
||||
<span
|
||||
className="rounded bg-purple-500/20 px-2 py-0.5 text-purple-400"
|
||||
title="Kubectl Command"
|
||||
>
|
||||
kubectl: {kubectlCommand}
|
||||
</span>
|
||||
)}
|
||||
<span>{new Date(event.timestamp).toLocaleString()}</span>
|
||||
<span className="text-bunker-500">•</span>
|
||||
<span className="font-mono text-xs">{event.requestId}</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div className="mt-2">
|
||||
{isRequest ? (
|
||||
<div className="font-mono text-bunker-100">
|
||||
<span className="font-semibold text-bunker-200">{event.method}</span>{" "}
|
||||
<HighlightText text={event.url} highlight={search} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="font-mono text-bunker-100">
|
||||
<span className="font-semibold text-bunker-200">Status:</span>{" "}
|
||||
<HighlightText text={event.status} highlight={search} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-2 ml-4 space-y-2 border-l-2 border-mineshaft-600 pl-3">
|
||||
{Object.keys(event.headers).length > 0 && (
|
||||
<div className="mt-2 border-t border-mineshaft-700 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleSection(eventKey, "headers")}
|
||||
className="mb-1 flex w-full items-center gap-2 text-left text-xs text-bunker-400 transition-colors hover:text-bunker-300"
|
||||
>
|
||||
<FontAwesomeIcon
|
||||
icon={
|
||||
isSectionExpanded(eventKey, "headers") ? faChevronUp : faChevronDown
|
||||
}
|
||||
className="text-xs"
|
||||
/>
|
||||
<span>Headers:</span>
|
||||
</button>
|
||||
{isSectionExpanded(eventKey, "headers") && (
|
||||
<div className="font-mono text-xs whitespace-pre-wrap text-bunker-300">
|
||||
<HighlightText text={formatHeaders(event.headers)} highlight={search} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{event.body && (
|
||||
<div className="mt-2 border-t border-mineshaft-700 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleSection(eventKey, "body")}
|
||||
className="mb-1 flex w-full items-center gap-2 text-left text-xs text-bunker-400 transition-colors hover:text-bunker-300"
|
||||
>
|
||||
<FontAwesomeIcon
|
||||
icon={isSectionExpanded(eventKey, "body") ? faChevronUp : faChevronDown}
|
||||
className="text-xs"
|
||||
/>
|
||||
<span>Body:</span>
|
||||
</button>
|
||||
{isSectionExpanded(eventKey, "body") && (
|
||||
<div className="font-mono text-xs whitespace-pre-wrap text-bunker-300">
|
||||
<HighlightText
|
||||
text={formatBody(event.body, event.headers)}
|
||||
highlight={search}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div className="flex grow items-center justify-center text-bunker-300">
|
||||
{search.length ? (
|
||||
<div className="text-center">
|
||||
<div className="mb-2">No HTTP events match search criteria</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center">
|
||||
<div className="mb-2">HTTP session logs are not yet available</div>
|
||||
<div className="text-xs text-bunker-400">
|
||||
Logs will be uploaded after the session duration has elapsed.
|
||||
<br />
|
||||
If logs do not appear after some time, please contact your Gateway administrators.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,16 @@
|
||||
import { faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
|
||||
import { PamResourceType, TPamCommandLog, TPamSession, TTerminalEvent } from "@app/hooks/api/pam";
|
||||
import {
|
||||
PamResourceType,
|
||||
THttpEvent,
|
||||
TPamCommandLog,
|
||||
TPamSession,
|
||||
TTerminalEvent
|
||||
} from "@app/hooks/api/pam";
|
||||
|
||||
import { CommandLogView } from "./CommandLogView";
|
||||
import { HttpEventView } from "./HttpEventView";
|
||||
import { TerminalEventView } from "./TerminalEventView";
|
||||
|
||||
type Props = {
|
||||
@@ -16,6 +23,7 @@ export const PamSessionLogsSection = ({ session }: Props) => {
|
||||
const isDatabaseSession =
|
||||
session.resourceType === PamResourceType.Postgres ||
|
||||
session.resourceType === PamResourceType.MySQL;
|
||||
const isHttpSession = session.resourceType === PamResourceType.Kubernetes;
|
||||
const isAwsIamSession = session.resourceType === PamResourceType.AwsIam;
|
||||
const hasLogs = session.logs.length > 0;
|
||||
|
||||
@@ -27,6 +35,7 @@ export const PamSessionLogsSection = ({ session }: Props) => {
|
||||
|
||||
{isDatabaseSession && hasLogs && <CommandLogView logs={session.logs as TPamCommandLog[]} />}
|
||||
{isSSHSession && hasLogs && <TerminalEventView events={session.logs as TTerminalEvent[]} />}
|
||||
{isHttpSession && hasLogs && <HttpEventView events={session.logs as THttpEvent[]} />}
|
||||
{isAwsIamSession && (
|
||||
<div className="flex grow items-center justify-center text-bunker-300">
|
||||
<div className="text-center">
|
||||
|
||||
@@ -685,12 +685,17 @@ const Page = () => {
|
||||
setDebouncedSearchFilter("");
|
||||
};
|
||||
|
||||
const getMergedSecretsWithPending = () => {
|
||||
const getMergedSecretsWithPending = (
|
||||
paramSecrets?: (SecretV3RawSanitized | null)[]
|
||||
): SecretV3RawSanitized[] => {
|
||||
const sanitizedParamSecrets = paramSecrets?.filter(Boolean) as
|
||||
| SecretV3RawSanitized[]
|
||||
| undefined;
|
||||
if (!isBatchMode || pendingChanges.secrets.length === 0) {
|
||||
return secrets;
|
||||
return sanitizedParamSecrets || secrets || [];
|
||||
}
|
||||
|
||||
const mergedSecrets = [...(secrets || [])] as (SecretV3RawSanitized & {
|
||||
const mergedSecrets = [...(sanitizedParamSecrets || secrets || [])] as (SecretV3RawSanitized & {
|
||||
originalKey?: string;
|
||||
})[];
|
||||
|
||||
@@ -1072,7 +1077,17 @@ const Page = () => {
|
||||
/>
|
||||
)}
|
||||
{canReadSecretRotations && Boolean(secretRotations?.length) && (
|
||||
<SecretRotationListView secretRotations={secretRotations} />
|
||||
<SecretRotationListView
|
||||
secretRotations={secretRotations}
|
||||
colWidth={colWidth}
|
||||
tags={tags}
|
||||
projectId={projectId}
|
||||
secretPath={secretPath}
|
||||
isProtectedBranch={isProtectedBranch}
|
||||
importedBy={importedBy}
|
||||
usedBySecretSyncs={usedBySecretSyncs}
|
||||
getMergedSecretsWithPending={getMergedSecretsWithPending}
|
||||
/>
|
||||
)}
|
||||
{canReadSecret && Boolean(mergedSecrets?.length) && (
|
||||
<SecretListView
|
||||
|
||||
@@ -733,7 +733,7 @@ export const SecretItem = memo(
|
||||
{(isAllowed) => (
|
||||
<IconButton
|
||||
ariaLabel="override-value"
|
||||
isDisabled={!isAllowed}
|
||||
isDisabled={!isAllowed || isRotatedSecret}
|
||||
variant="plain"
|
||||
size="sm"
|
||||
onClick={handleOverrideClick}
|
||||
@@ -742,7 +742,13 @@ export const SecretItem = memo(
|
||||
isOverridden && "w-5 text-primary"
|
||||
)}
|
||||
>
|
||||
<Tooltip content={`${isOverridden ? "Remove" : "Add"} Override`}>
|
||||
<Tooltip
|
||||
content={
|
||||
isRotatedSecret
|
||||
? "Unavailable for rotated secrets"
|
||||
: `${isOverridden ? "Remove" : "Add"} Override`
|
||||
}
|
||||
>
|
||||
<FontAwesomeSymbol
|
||||
symbolName={FontAwesomeSpriteName.Override}
|
||||
className="h-3.5 w-3.5"
|
||||
|
||||
@@ -52,6 +52,7 @@ type Props = {
|
||||
}[];
|
||||
}[];
|
||||
colWidth: number;
|
||||
excludePendingCreates?: boolean;
|
||||
};
|
||||
|
||||
export const SecretListView = ({
|
||||
@@ -64,7 +65,8 @@ export const SecretListView = ({
|
||||
isProtectedBranch = false,
|
||||
usedBySecretSyncs,
|
||||
importedBy,
|
||||
colWidth
|
||||
colWidth,
|
||||
excludePendingCreates = false
|
||||
}: Props) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { popUp, handlePopUpToggle, handlePopUpOpen, handlePopUpClose } = usePopUp([
|
||||
@@ -580,27 +582,32 @@ export const SecretListView = ({
|
||||
{FontAwesomeSpriteSymbols.map(({ icon, symbol }) => (
|
||||
<FontAwesomeIcon icon={icon} symbol={symbol} key={`font-awesome-svg-spritie-${symbol}`} />
|
||||
))}
|
||||
{secrets.map((secret) => (
|
||||
<SecretItem
|
||||
colWidth={colWidth}
|
||||
environment={environment}
|
||||
secretPath={secretPath}
|
||||
tags={wsTags}
|
||||
isSelected={Boolean(selectedSecrets?.[secret.id])}
|
||||
onToggleSecretSelect={toggleSelectedSecret}
|
||||
isVisible={isVisible}
|
||||
secret={secret}
|
||||
key={secret.id}
|
||||
onSaveSecret={handleSaveSecret}
|
||||
onDeleteSecret={onDeleteSecret}
|
||||
onDetailViewSecret={onDetailViewSecret}
|
||||
importedBy={importedBy}
|
||||
onCreateTag={onCreateTag}
|
||||
onShareSecret={onShareSecret}
|
||||
isPending={secret.isPending}
|
||||
pendingAction={secret.pendingAction}
|
||||
/>
|
||||
))}
|
||||
{secrets
|
||||
.filter((secret) => {
|
||||
if (!excludePendingCreates) return true;
|
||||
return !secret.isPending || secret.pendingAction !== PendingAction.Create;
|
||||
})
|
||||
.map((secret) => (
|
||||
<SecretItem
|
||||
colWidth={colWidth}
|
||||
environment={environment}
|
||||
secretPath={secretPath}
|
||||
tags={wsTags}
|
||||
isSelected={Boolean(selectedSecrets?.[secret.id])}
|
||||
onToggleSecretSelect={toggleSelectedSecret}
|
||||
isVisible={isVisible}
|
||||
secret={secret}
|
||||
key={secret.id}
|
||||
onSaveSecret={handleSaveSecret}
|
||||
onDeleteSecret={onDeleteSecret}
|
||||
onDetailViewSecret={onDetailViewSecret}
|
||||
importedBy={importedBy}
|
||||
onCreateTag={onCreateTag}
|
||||
onShareSecret={onShareSecret}
|
||||
isPending={secret.isPending}
|
||||
pendingAction={secret.pendingAction}
|
||||
/>
|
||||
))}
|
||||
<DeleteActionModal
|
||||
isOpen={popUp.deleteSecret.isOpen}
|
||||
deleteKey={(popUp.deleteSecret?.data as SecretV3RawSanitized)?.key}
|
||||
|
||||
@@ -18,8 +18,11 @@ import { IconButton, Modal, ModalContent, TableContainer, Tag, Tooltip } from "@
|
||||
import { ProjectPermissionSub } from "@app/context";
|
||||
import { ProjectPermissionSecretRotationActions } from "@app/context/ProjectPermissionContext/types";
|
||||
import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
|
||||
import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
|
||||
import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
|
||||
import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
|
||||
|
||||
import { SecretListView } from "../SecretListView";
|
||||
import { SecretRotationSecretRow } from "./SecretRotationSecretRow";
|
||||
|
||||
type Props = {
|
||||
@@ -28,6 +31,23 @@ type Props = {
|
||||
onRotate: () => void;
|
||||
onViewGeneratedCredentials: () => void;
|
||||
onDelete: () => void;
|
||||
projectId: string;
|
||||
secretPath?: string;
|
||||
tags?: WsTag[];
|
||||
isProtectedBranch?: boolean;
|
||||
usedBySecretSyncs?: UsedBySecretSyncs[];
|
||||
importedBy?: {
|
||||
environment: { name: string; slug: string };
|
||||
folders: {
|
||||
name: string;
|
||||
secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
|
||||
isImported: boolean;
|
||||
}[];
|
||||
}[];
|
||||
colWidth: number;
|
||||
getMergedSecretsWithPending: (
|
||||
paramSecrets?: (SecretV3RawSanitized | null)[]
|
||||
) => SecretV3RawSanitized[];
|
||||
};
|
||||
|
||||
export const SecretRotationItem = ({
|
||||
@@ -35,16 +55,40 @@ export const SecretRotationItem = ({
|
||||
onEdit,
|
||||
onRotate,
|
||||
onViewGeneratedCredentials,
|
||||
onDelete
|
||||
onDelete,
|
||||
projectId,
|
||||
secretPath = "/",
|
||||
tags = [],
|
||||
isProtectedBranch = false,
|
||||
usedBySecretSyncs,
|
||||
importedBy,
|
||||
colWidth,
|
||||
getMergedSecretsWithPending
|
||||
}: Props) => {
|
||||
const { name, type, environment, folder, secrets, description } = secretRotation;
|
||||
|
||||
const { name: rotationType, image } = SECRET_ROTATION_MAP[type];
|
||||
const [showSecrets, setShowSecrets] = useState(false);
|
||||
const [isExpanded, setIsExpanded] = useState(true);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={twMerge("group flex border-b border-mineshaft-600 hover:bg-mineshaft-700")}>
|
||||
<div
|
||||
className={twMerge(
|
||||
"group flex cursor-pointer border-b border-mineshaft-600 hover:bg-mineshaft-700"
|
||||
)}
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
setIsExpanded(!isExpanded);
|
||||
}
|
||||
}}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={`${isExpanded ? "Collapse" : "Expand"} rotation secrets for ${name}`}
|
||||
>
|
||||
<div className="text- flex w-11 items-center py-2 pl-5 text-mineshaft-400">
|
||||
<FontAwesomeIcon icon={faRotate} />
|
||||
</div>
|
||||
@@ -198,6 +242,20 @@ export const SecretRotationItem = ({
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
{isExpanded && (
|
||||
<SecretListView
|
||||
colWidth={colWidth}
|
||||
secrets={getMergedSecretsWithPending(secretRotation.secrets) || []}
|
||||
tags={tags}
|
||||
environment={environment.slug}
|
||||
projectId={projectId}
|
||||
secretPath={secretPath}
|
||||
isProtectedBranch={isProtectedBranch}
|
||||
importedBy={importedBy}
|
||||
usedBySecretSyncs={usedBySecretSyncs}
|
||||
excludePendingCreates
|
||||
/>
|
||||
)}
|
||||
<Modal onOpenChange={setShowSecrets} isOpen={showSecrets}>
|
||||
<ModalContent
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
|
||||
@@ -3,15 +3,44 @@ import { EditSecretRotationV2Modal } from "@app/components/secret-rotations-v2/E
|
||||
import { RotateSecretRotationV2Modal } from "@app/components/secret-rotations-v2/RotateSecretRotationV2Modal";
|
||||
import { ViewSecretRotationV2GeneratedCredentialsModal } from "@app/components/secret-rotations-v2/ViewSecretRotationV2GeneratedCredentials";
|
||||
import { usePopUp } from "@app/hooks";
|
||||
import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
|
||||
import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
|
||||
import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
|
||||
|
||||
import { SecretRotationItem } from "./SecretRotationItem";
|
||||
|
||||
type Props = {
|
||||
secretRotations?: TSecretRotationV2[];
|
||||
projectId: string;
|
||||
secretPath?: string;
|
||||
tags?: WsTag[];
|
||||
isProtectedBranch?: boolean;
|
||||
usedBySecretSyncs?: UsedBySecretSyncs[];
|
||||
importedBy?: {
|
||||
environment: { name: string; slug: string };
|
||||
folders: {
|
||||
name: string;
|
||||
secrets?: { secretId: string; referencedSecretKey: string; referencedSecretEnv: string }[];
|
||||
isImported: boolean;
|
||||
}[];
|
||||
}[];
|
||||
colWidth: number;
|
||||
getMergedSecretsWithPending: (
|
||||
secretParams?: (SecretV3RawSanitized | null)[]
|
||||
) => SecretV3RawSanitized[];
|
||||
};
|
||||
|
||||
export const SecretRotationListView = ({ secretRotations }: Props) => {
|
||||
export const SecretRotationListView = ({
|
||||
secretRotations,
|
||||
projectId,
|
||||
secretPath = "/",
|
||||
tags = [],
|
||||
isProtectedBranch = false,
|
||||
usedBySecretSyncs,
|
||||
importedBy,
|
||||
colWidth,
|
||||
getMergedSecretsWithPending
|
||||
}: Props) => {
|
||||
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
|
||||
"editSecretRotation",
|
||||
"rotateSecretRotation",
|
||||
@@ -31,6 +60,14 @@ export const SecretRotationListView = ({ secretRotations }: Props) => {
|
||||
handlePopUpOpen("viewSecretRotationGeneratedCredentials", secretRotation)
|
||||
}
|
||||
onDelete={() => handlePopUpOpen("deleteSecretRotation", secretRotation)}
|
||||
colWidth={colWidth}
|
||||
tags={tags}
|
||||
projectId={projectId}
|
||||
secretPath={secretPath}
|
||||
isProtectedBranch={isProtectedBranch}
|
||||
importedBy={importedBy}
|
||||
usedBySecretSyncs={usedBySecretSyncs}
|
||||
getMergedSecretsWithPending={getMergedSecretsWithPending}
|
||||
/>
|
||||
))}
|
||||
<EditSecretRotationV2Modal
|
||||
|
||||
Reference in New Issue
Block a user