Skip to content

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

feat: implemented ssh password api

=9e0836cedc6a
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
index c2302d8fff..3f2a1e2644 100644
--- a/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
@@ -12,6 +12,7 @@ import { registerOktaClientSecretRotationRouter } from "./okta-client-secret-rot
import { registerOracleDBCredentialsRotationRouter } from "./oracledb-credentials-rotation-router";
import { registerPostgresCredentialsRotationRouter } from "./postgres-credentials-rotation-router";
import { registerRedisCredentialsRotationRouter } from "./redis-credentials-rotation-router";
+import { registerSshPasswordRotationRouter } from "./ssh-password-rotation-router";
export * from "./secret-rotation-v2-router";
@@ -30,5 +31,6 @@ export const SECRET_ROTATION_REGISTER_ROUTER_MAP: Record<
[SecretRotation.OktaClientSecret]: registerOktaClientSecretRotationRouter,
[SecretRotation.RedisCredentials]: registerRedisCredentialsRotationRouter,
[SecretRotation.MongoDBCredentials]: registerMongoDBCredentialsRotationRouter,
- [SecretRotation.DatabricksServicePrincipalSecret]: registerDatabricksServicePrincipalSecretRotationRouter
+ [SecretRotation.DatabricksServicePrincipalSecret]: registerDatabricksServicePrincipalSecretRotationRouter,
+ [SecretRotation.SshPassword]: registerSshPasswordRotationRouter
};
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
index 58dd509786..0fa0dab6a9 100644
--- a/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
@@ -14,6 +14,7 @@ import { OracleDBCredentialsRotationListItemSchema } from "@app/ee/services/secr
import { PostgresCredentialsRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/postgres-credentials";
import { RedisCredentialsRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/redis-credentials";
import { SecretRotationV2Schema } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema";
+import { SshPasswordRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/ssh-password";
import { ApiDocsTags, SecretRotations } from "@app/lib/api-docs";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -31,7 +32,8 @@ const SecretRotationV2OptionsSchema = z.discriminatedUnion("type", [
OktaClientSecretRotationListItemSchema,
RedisCredentialsRotationListItemSchema,
MongoDBCredentialsRotationListItemSchema,
- DatabricksServicePrincipalSecretRotationListItemSchema
+ DatabricksServicePrincipalSecretRotationListItemSchema,
+ SshPasswordRotationListItemSchema
]);
export const registerSecretRotationV2Router = async (server: FastifyZodProvider) => {
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/ssh-password-rotation-router.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/ssh-password-rotation-router.ts
new file mode 100644
index 0000000000..ade2e23c73
--- /dev/null
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/ssh-password-rotation-router.ts
@@ -0,0 +1,82 @@
+import { z } from "zod";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import {
+ CreateSshPasswordRotationSchema,
+ SshPasswordRotationGeneratedCredentialsSchema,
+ SshPasswordRotationSchema,
+ TSshPasswordRotation,
+ UpdateSshPasswordRotationSchema
+} from "@app/ee/services/secret-rotation-v2/ssh-password";
+import { ApiDocsTags, SecretRotations } from "@app/lib/api-docs";
+import { writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { registerSecretRotationEndpoints } from "./secret-rotation-v2-endpoints";
+
+export const registerSshPasswordRotationRouter = async (server: FastifyZodProvider) => {
+ // Register standard CRUD endpoints
+ registerSecretRotationEndpoints({
+ type: SecretRotation.SshPassword,
+ server,
+ responseSchema: SshPasswordRotationSchema,
+ createSchema: CreateSshPasswordRotationSchema,
+ updateSchema: UpdateSshPasswordRotationSchema,
+ generatedCredentialsSchema: SshPasswordRotationGeneratedCredentialsSchema
+ });
+
+ // Add reconcile endpoint for SSH password rotation
+ server.route({
+ method: "POST",
+ url: "/:rotationId/reconcile",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretRotations],
+ description:
+ "Reconcile SSH password rotation credentials. This operation uses the SSH app connection credentials to reset the password when credentials are out of sync.",
+ params: z.object({
+ rotationId: z.string().uuid().describe(SecretRotations.RECONCILE.rotationId)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ reconciled: z.boolean(),
+ secretRotation: SshPasswordRotationSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { rotationId } = req.params;
+
+ const result = await server.services.secretRotationV2.reconcileSshPasswordRotation(
+ { rotationId },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: result.secretRotation.projectId,
+ event: {
+ type: EventType.RECONCILE_SECRET_ROTATION,
+ metadata: {
+ type: SecretRotation.SshPassword,
+ rotationId,
+ reconciled: result.reconciled
+ }
+ }
+ });
+
+ return {
+ message: result.message,
+ reconciled: result.reconciled,
+ secretRotation: result.secretRotation as TSshPasswordRotation
+ };
+ }
+ });
+};
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index c5f2db964b..55ae9ca195 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -487,6 +487,7 @@ export enum EventType {
UPDATE_SECRET_ROTATION = "update-secret-rotation",
DELETE_SECRET_ROTATION = "delete-secret-rotation",
SECRET_ROTATION_ROTATE_SECRETS = "secret-rotation-rotate-secrets",
+ RECONCILE_SECRET_ROTATION = "reconcile-secret-rotation",
PROJECT_ACCESS_REQUEST = "project-access-request",
@@ -3702,6 +3703,15 @@ interface RotateSecretRotationEvent {
};
}
+interface ReconcileSecretRotationEvent {
+ type: EventType.RECONCILE_SECRET_ROTATION;
+ metadata: {
+ type: string;
+ rotationId: string;
+ reconciled: boolean;
+ };
+}
+
interface MicrosoftTeamsWorkflowIntegrationCreateEvent {
type: EventType.MICROSOFT_TEAMS_WORKFLOW_INTEGRATION_CREATE;
metadata: {
@@ -5204,6 +5214,7 @@ export type Event =
| UpdateSecretRotationEvent
| DeleteSecretRotationEvent
| RotateSecretRotationEvent
+ | ReconcileSecretRotationEvent
| MicrosoftTeamsWorkflowIntegrationCreateEvent
| MicrosoftTeamsWorkflowIntegrationDeleteEvent
| MicrosoftTeamsWorkflowIntegrationCheckInstallationStatusEvent
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
index c9a1078c39..16f7a4d5fd 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
@@ -10,7 +10,8 @@ export enum SecretRotation {
OktaClientSecret = "okta-client-secret",
RedisCredentials = "redis-credentials",
MongoDBCredentials = "mongodb-credentials",
- DatabricksServicePrincipalSecret = "databricks-service-principal-secret"
+ DatabricksServicePrincipalSecret = "databricks-service-principal-secret",
+ SshPassword = "ssh-password"
}
export enum SecretRotationStatus {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
index d24c6be970..da8d54babb 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
@@ -28,6 +28,7 @@ import {
TSecretRotationV2Raw,
TUpdateSecretRotationV2DTO
} from "./secret-rotation-v2-types";
+import { SSH_PASSWORD_ROTATION_LIST_OPTION, TSshPasswordRotation } from "./ssh-password";
const SECRET_ROTATION_LIST_OPTIONS: Record<SecretRotation, TSecretRotationV2ListItem> = {
[SecretRotation.PostgresCredentials]: POSTGRES_CREDENTIALS_ROTATION_LIST_OPTION,
@@ -41,7 +42,8 @@ const SECRET_ROTATION_LIST_OPTIONS: Record<SecretRotation, TSecretRotationV2List
[SecretRotation.OktaClientSecret]: OKTA_CLIENT_SECRET_ROTATION_LIST_OPTION,
[SecretRotation.RedisCredentials]: REDIS_CREDENTIALS_ROTATION_LIST_OPTION,
[SecretRotation.MongoDBCredentials]: MONGODB_CREDENTIALS_ROTATION_LIST_OPTION,
- [SecretRotation.DatabricksServicePrincipalSecret]: DATABRICKS_SERVICE_PRINCIPAL_SECRET_ROTATION_LIST_OPTION
+ [SecretRotation.DatabricksServicePrincipalSecret]: DATABRICKS_SERVICE_PRINCIPAL_SECRET_ROTATION_LIST_OPTION,
+ [SecretRotation.SshPassword]: SSH_PASSWORD_ROTATION_LIST_OPTION
};
export const listSecretRotationOptions = () => {
@@ -272,6 +274,17 @@ export const throwOnImmutableParameterUpdate = (
throw new BadRequestError({ message: "Cannot update rotation method or DN" });
}
break;
+ case SecretRotation.SshPassword:
+ if (
+ haveUnequalProperties(
+ updatePayload.parameters as TSshPasswordRotation["parameters"],
+ secretRotation.parameters as TSshPasswordRotation["parameters"],
+ ["rotationMethod", "username"]
+ )
+ ) {
+ throw new BadRequestError({ message: "Cannot update rotation method or username" });
+ }
+ break;
default:
// do nothing
}
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
index 616d8efc32..aa926e725b 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
@@ -13,7 +13,8 @@ export const SECRET_ROTATION_NAME_MAP: Record<SecretRotation, string> = {
[SecretRotation.OktaClientSecret]: "Okta Client Secret",
[SecretRotation.RedisCredentials]: "Redis Credentials",
[SecretRotation.MongoDBCredentials]: "MongoDB Credentials",
- [SecretRotation.DatabricksServicePrincipalSecret]: "Databricks Service Principal Secret"
+ [SecretRotation.DatabricksServicePrincipalSecret]: "Databricks Service Principal Secret",
+ [SecretRotation.SshPassword]: "SSH Password"
};
export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnection> = {
@@ -28,5 +29,6 @@ export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnectio
[SecretRotation.OktaClientSecret]: AppConnection.Okta,
[SecretRotation.RedisCredentials]: AppConnection.Redis,
[SecretRotation.MongoDBCredentials]: AppConnection.MongoDB,
- [SecretRotation.DatabricksServicePrincipalSecret]: AppConnection.Databricks
+ [SecretRotation.DatabricksServicePrincipalSecret]: AppConnection.Databricks,
+ [SecretRotation.SshPassword]: AppConnection.SSH
};
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
index a907ac11e5..4c377de801 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
@@ -89,6 +89,12 @@ import { mongodbCredentialsRotationFactory } from "./mongodb-credentials/mongodb
import { oktaClientSecretRotationFactory } from "./okta-client-secret/okta-client-secret-rotation-fns";
import { redisCredentialsRotationFactory } from "./redis-credentials/redis-credentials-rotation-fns";
import { TSecretRotationV2DALFactory } from "./secret-rotation-v2-dal";
+import { sshPasswordRotationFactory } from "./ssh-password/ssh-password-rotation-fns";
+import { SshPasswordRotationMethod } from "./ssh-password/ssh-password-rotation-schemas";
+import {
+ TSshPasswordRotation,
+ TSshPasswordRotationGeneratedCredentials
+} from "./ssh-password/ssh-password-rotation-types";
export type TSecretRotationV2ServiceFactoryDep = {
secretRotationV2DAL: TSecretRotationV2DALFactory;
@@ -139,7 +145,8 @@ const SECRET_ROTATION_FACTORY_MAP: Record<SecretRotation, TRotationFactoryImplem
[SecretRotation.RedisCredentials]: redisCredentialsRotationFactory as TRotationFactoryImplementation,
[SecretRotation.MongoDBCredentials]: mongodbCredentialsRotationFactory as TRotationFactoryImplementation,
[SecretRotation.DatabricksServicePrincipalSecret]:
- databricksServicePrincipalSecretRotationFactory as TRotationFactoryImplementation
+ databricksServicePrincipalSecretRotationFactory as TRotationFactoryImplementation,
+ [SecretRotation.SshPassword]: sshPasswordRotationFactory as TRotationFactoryImplementation
};
export const secretRotationV2ServiceFactory = ({
@@ -1374,6 +1381,166 @@ export const secretRotationV2ServiceFactory = ({
return secretRotations as TSecretRotationV2[];
};
+ const reconcileSshPasswordRotation = async ({ rotationId }: { rotationId: string }, actor: OrgServiceActor) => {
+ const plan = await licenseService.getPlan(actor.orgId);
+
+ if (!plan.secretRotation)
+ throw new BadRequestError({
+ message:
+ "Failed to reconcile secret rotation due to plan restriction. Upgrade plan to reconcile secret rotations."
+ });
+
+ const secretRotation = await secretRotationV2DAL.findById(rotationId);
+
+ if (!secretRotation)
+ throw new NotFoundError({
+ message: `Could not find Secret Rotation with ID "${rotationId}"`
+ });
+
+ if (secretRotation.type !== SecretRotation.SshPassword)
+ throw new BadRequestError({
+ message: "Reconcile operation is only supported for SSH Password rotations"
+ });
+
+ const { projectId, environment, folder, connection, encryptedGeneratedCredentials, parameters, folderId } =
+ secretRotation;
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.SecretManager,
+ projectId
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionSecretRotationActions.Edit,
+ subject(ProjectPermissionSub.SecretRotation, {
+ environment: environment.slug,
+ secretPath: folder.path
+ })
+ );
+
+ const sshParams = parameters as TSshPasswordRotation["parameters"];
+
+ // Only allow reconcile for self-rotation mode
+ if (sshParams.rotationMethod !== SshPasswordRotationMethod.LoginAsTarget) {
+ throw new BadRequestError({
+ message: "Reconcile operation is only supported for self-rotation mode SSH Password rotations"
+ });
+ }
+
+ // Get current generated credentials
+ const generatedCredentials = await decryptSecretRotationCredentials({
+ projectId,
+ encryptedGeneratedCredentials,
+ kmsService
+ });
+
+ const activeCredentials = generatedCredentials[
+ secretRotation.activeIndex
+ ] as TSshPasswordRotationGeneratedCredentials[number];
+ const appConnection = await decryptAppConnection(connection, kmsService);
+
+ // Use the rotation factory to perform a rotation using the app connection credentials
+ const rotationFactory = SECRET_ROTATION_FACTORY_MAP[SecretRotation.SshPassword](
+ {
+ ...secretRotation,
+ // Override rotation method to managed so it uses the app connection credentials
+ parameters: {
+ ...sshParams,
+ rotationMethod: SshPasswordRotationMethod.LoginAsRoot
+ },
+ connection: appConnection
+ } as TSecretRotationV2WithConnection,
+ appConnectionDAL,
+ kmsService,
+ gatewayService,
+ gatewayV2Service
+ );
+
+ // Issue new credentials using managed mode (app connection credentials)
+ const updatedRotation = await rotationFactory.issueCredentials(
+ async (newCredentials) => {
+ const sshCredentials = newCredentials as TSshPasswordRotationGeneratedCredentials[number];
+ const updatedCredentials = [...generatedCredentials];
+ updatedCredentials[secretRotation.activeIndex] = sshCredentials;
+
+ const encryptedUpdatedCredentials = await encryptSecretRotationCredentials({
+ projectId,
+ generatedCredentials: updatedCredentials as TSecretRotationV2GeneratedCredentials,
+ kmsService
+ });
+
+ return secretRotationV2DAL.transaction(async (tx) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ // Update the password secret with the new value
+ const secretsMapping = secretRotation.secretsMapping as TSshPasswordRotation["secretsMapping"];
+
+ await fnSecretBulkUpdate({
+ folderId,
+ orgId: connection.orgId,
+ tx,
+ inputSecrets: [
+ {
+ filter: {
+ key: secretsMapping.password,
+ folderId,
+ type: SecretType.Shared
+ },
+ data: {
+ encryptedValue: encryptor({
+ plainText: Buffer.from(sshCredentials.password)
+ }).cipherTextBlob,
+ references: []
+ }
+ }
+ ],
+ secretDAL: secretV2BridgeDAL,
+ secretVersionDAL: secretVersionV2BridgeDAL,
+ secretVersionTagDAL: secretVersionTagV2BridgeDAL,
+ folderCommitService,
+ actor: { type: ActorType.PLATFORM },
+ secretTagDAL,
+ resourceMetadataDAL
+ });
+
+ return secretRotationV2DAL.updateById(
+ rotationId,
+ {
+ encryptedGeneratedCredentials: encryptedUpdatedCredentials,
+ lastRotatedAt: new Date(),
+ rotationStatus: SecretRotationStatus.Success
+ },
+ tx
+ );
+ });
+ },
+ { password: activeCredentials.password }
+ );
+
+ await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
+ await snapshotService.performSnapshot(folder.id);
+ await secretQueueService.syncSecrets({
+ orgId: connection.orgId,
+ secretPath: folder.path,
+ projectId,
+ environmentSlug: environment.slug,
+ excludeReplication: true
+ });
+
+ return {
+ message: "SSH password credentials reconciled successfully",
+ reconciled: true,
+ secretRotation: await expandSecretRotation(updatedRotation, kmsService)
+ };
+ };
+
return {
listSecretRotationOptions,
listSecretRotationsByProjectId,
@@ -1387,6 +1554,7 @@ export const secretRotationV2ServiceFactory = ({
rotateGeneratedCredentials,
getDashboardSecretRotationCount,
getDashboardSecretRotations,
- getQuickSearchSecretRotations
+ getQuickSearchSecretRotations,
+ reconcileSshPasswordRotation
};
};
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
index adccfea73d..1cec901e85 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
@@ -88,6 +88,13 @@ import {
} from "./redis-credentials/redis-credentials-rotation-types";
import { TSecretRotationV2DALFactory } from "./secret-rotation-v2-dal";
import { SecretRotation } from "./secret-rotation-v2-enums";
+import {
+ TSshPasswordRotation,
+ TSshPasswordRotationGeneratedCredentials,
+ TSshPasswordRotationInput,
+ TSshPasswordRotationListItem,
+ TSshPasswordRotationWithConnection
+} from "./ssh-password";
export type TSecretRotationV2 =
| TPostgresCredentialsRotation
@@ -101,7 +108,8 @@ export type TSecretRotationV2 =
| TOktaClientSecretRotation
| TRedisCredentialsRotation
| TMongoDBCredentialsRotation
- | TDatabricksServicePrincipalSecretRotation;
+ | TDatabricksServicePrincipalSecretRotation
+ | TSshPasswordRotation;
export type TSecretRotationV2WithConnection =
| TPostgresCredentialsRotationWithConnection
@@ -115,7 +123,8 @@ export type TSecretRotationV2WithConnection =
| TOktaClientSecretRotationWithConnection
| TRedisCredentialsRotationWithConnection
| TMongoDBCredentialsRotationWithConnection
- | TDatabricksServicePrincipalSecretRotationWithConnection;
+ | TDatabricksServicePrincipalSecretRotationWithConnection
+ | TSshPasswordRotationWithConnection;
export type TSecretRotationV2GeneratedCredentials =
| TSqlCredentialsRotationGeneratedCredentials
@@ -125,7 +134,8 @@ export type TSecretRotationV2GeneratedCredentials =
| TAwsIamUserSecretRotationGeneratedCredentials
| TOktaClientSecretRotationGeneratedCredentials
| TRedisCredentialsRotationGeneratedCredentials
- | TDatabricksServicePrincipalSecretRotationGeneratedCredentials;
+ | TDatabricksServicePrincipalSecretRotationGeneratedCredentials
+ | TSshPasswordRotationGeneratedCredentials;
export type TSecretRotationV2Input =
| TPostgresCredentialsRotationInput
@@ -139,7 +149,8 @@ export type TSecretRotationV2Input =
| TOktaClientSecretRotationInput
| TRedisCredentialsRotationInput
| TMongoDBCredentialsRotationInput
- | TDatabricksServicePrincipalSecretRotationInput;
+ | TDatabricksServicePrincipalSecretRotationInput
+ | TSshPasswordRotationInput;
export type TSecretRotationV2ListItem =
| TPostgresCredentialsRotationListItem
@@ -153,9 +164,13 @@ export type TSecretRotationV2ListItem =
| TOktaClientSecretRotationListItem
| TRedisCredentialsRotationListItem
| TMongoDBCredentialsRotationListItem
- | TDatabricksServicePrincipalSecretRotationListItem;
+ | TDatabricksServicePrincipalSecretRotationListItem
+ | TSshPasswordRotationListItem;
-export type TSecretRotationV2TemporaryParameters = TLdapPasswordRotationInput["temporaryParameters"] | undefined;
+export type TSecretRotationV2TemporaryParameters =
+ | TLdapPasswordRotationInput["temporaryParameters"]
+ | TSshPasswordRotationInput["temporaryParameters"]
+ | undefined;
export type TSecretRotationV2Raw = NonNullable<Awaited<ReturnType<TSecretRotationV2DALFactory["findById"]>>>;
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
index a7633e0d54..10c614a9a6 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
@@ -12,6 +12,7 @@ import { OktaClientSecretRotationSchema } from "@app/ee/services/secret-rotation
import { OracleDBCredentialsRotationSchema } from "@app/ee/services/secret-rotation-v2/oracledb-credentials";
import { PostgresCredentialsRotationSchema } from "@app/ee/services/secret-rotation-v2/postgres-credentials";
import { RedisCredentialsRotationSchema } from "@app/ee/services/secret-rotation-v2/redis-credentials";
+import { SshPasswordRotationSchema } from "@app/ee/services/secret-rotation-v2/ssh-password";
export const SecretRotationV2Schema = z.discriminatedUnion("type", [
PostgresCredentialsRotationSchema,
@@ -25,5 +26,6 @@ export const SecretRotationV2Schema = z.discriminatedUnion("type", [
OktaClientSecretRotationSchema,
RedisCredentialsRotationSchema,
MongoDBCredentialsRotationSchema,
- DatabricksServicePrincipalSecretRotationSchema
+ DatabricksServicePrincipalSecretRotationSchema,
+ SshPasswordRotationSchema
]);
diff --git a/backend/src/ee/services/secret-rotation-v2/ssh-password/index.ts b/backend/src/ee/services/secret-rotation-v2/ssh-password/index.ts
new file mode 100644
index 0000000000..0a86f81272
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/ssh-password/index.ts
@@ -0,0 +1,4 @@
+export * from "./ssh-password-rotation-constants";
+export * from "./ssh-password-rotation-fns";
+export * from "./ssh-password-rotation-schemas";
+export * from "./ssh-password-rotation-types";
diff --git a/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-constants.ts b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-constants.ts
new file mode 100644
index 0000000000..6e846bf1b7
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-constants.ts
@@ -0,0 +1,16 @@
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { TSshPasswordRotationListItem } from "./ssh-password-rotation-types";
+
+export const SSH_PASSWORD_ROTATION_LIST_OPTION: TSshPasswordRotationListItem = {
+ name: "SSH Password",
+ type: SecretRotation.SshPassword,
+ connection: AppConnection.SSH,
+ template: {
+ secretsMapping: {
+ username: "SSH_USERNAME",
+ password: "SSH_PASSWORD"
+ }
+ }
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-fns.ts
new file mode 100644
index 0000000000..a44945938d
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-fns.ts
@@ -0,0 +1,302 @@
+import { Client } from "ssh2";
+
+import {
+ TRotationFactory,
+ TRotationFactoryGetSecretsPayload,
+ TRotationFactoryIssueCredentials,
+ TRotationFactoryRevokeCredentials,
+ TRotationFactoryRotateCredentials
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import {
+ executeWithPotentialGateway,
+ getSshConnectionClient,
+ SshConnectionMethod,
+ TSshConnectionConfig
+} from "@app/services/app-connection/ssh";
+
+import { generatePassword } from "../shared/utils";
+import { SshPasswordRotationMethod } from "./ssh-password-rotation-schemas";
+import {
+ TSshPasswordRotationGeneratedCredentials,
+ TSshPasswordRotationInput,
+ TSshPasswordRotationWithConnection
+} from "./ssh-password-rotation-types";
+
+// Execute command over SSH and return stdout
+const executeCommand = (client: Client, command: string): Promise<string> => {
+ return new Promise((resolve, reject) => {
+ client.exec(command, (err, stream) => {
+ if (err) {
+ reject(new Error(`SSH exec error: ${err.message}`));
+ return;
+ }
+
+ let stdout = "";
+ let stderr = "";
+
+ stream.on("close", (code: number) => {
+ if (code !== 0) {
+ reject(new Error(`Command failed with exit code ${code}: ${stderr || "Unknown error"}`));
+ } else {
+ resolve(stdout);
+ }
+ });
+
+ stream.on("data", (data: Buffer) => {
+ stdout += data.toString();
+ });
+
+ stream.stderr.on("data", (data: Buffer) => {
+ stderr += data.toString();
+ });
+ });
+ });
+};
+
+// Change password for managed rotation (admin changing another user's password)
+const changeManagedPassword = async (client: Client, username: string, newPassword: string): Promise<void> => {
+ // Using base64 encoding to avoid any shell escaping issues
+ const encodedPassword = Buffer.from(`${username}:${newPassword}`).toString("base64");
+ const command = `echo '${encodedPassword}' | base64 -d | sudo chpasswd`;
+
+ try {
+ await executeCommand(client, command);
+ } catch (error) {
+ logger.error(error, "SSH Password Rotation: Failed to change password (managed)");
+ throw new Error(`Failed to change password: ${(error as Error).message}`);
+ }
+};
+
+// Change password for self rotation (user changing their own password)
+// Uses interactive shell to handle passwd command prompts
+const changeSelfPassword = async (client: Client, oldPassword: string, newPassword: string): Promise<void> => {
+ return new Promise((resolve, reject) => {
+ client.shell((err, stream) => {
+ if (err) {
+ reject(new Error(`Failed to start shell: ${err.message}`));
+ return;
+ }
+
+ let output = "";
+ let step = 0;
+ let completed = false;
+ let errorMessage = "";
+
+ const timeout = setTimeout(() => {
+ if (!completed) {
+ stream.end("exit\n");
+ reject(new Error(`Password change timed out. Output: ${output}`));
+ }
+ }, 30000); // 30 second timeout
+
+ stream.on("data", (data: Buffer) => {
+ const text = data.toString();
+ output += text;
+ const lower = text.toLowerCase();
+
+ // Handle passwd prompts step by step
+ if (step === 0 && lower.includes("password")) {
+ // Current/old password prompt (could be "Current password:", "Old password:", etc.)
+ stream.write(`${oldPassword}\n`);
+ step = 1;
+ } else if (step === 1 && lower.includes("new password")) {
+ // New password prompt
+ stream.write(`${newPassword}\n`);
+ step = 2;
+ } else if (
+ step === 2 &&
+ (lower.includes("retype") || lower.includes("again") || lower.includes("new password"))
+ ) {
+ // Confirm new password prompt
+ stream.write(`${newPassword}\n`);
+ step = 3;
+ } else if (
+ step >= 1 &&
+ (lower.includes("error") ||
+ lower.includes("fail") ||
+ lower.includes("unchanged") ||
+ lower.includes("authentication"))
+ ) {
+ // Password change failed
+ errorMessage = text.trim();
+ } else if (
+ step === 3 &&
+ (lower.includes("success") || lower.includes("updated") || lower.includes("changed"))
+ ) {
+ // Password changed successfully
+ completed = true;
+ clearTimeout(timeout);
+ stream.end("exit\n");
+ }
+ });
+
+ stream.on("close", () => {
+ clearTimeout(timeout);
+ if (completed || step >= 3) {
+ // If we got to step 3 without explicit error, consider it success
+ if (errorMessage && !completed) {
+ reject(new Error(`Password change failed: ${errorMessage}`));
+ } else {
+ resolve();
+ }
+ } else {
+ reject(new Error(`Password change incomplete (step ${step}). Output: ${output}`));
+ }
+ });
+
+ stream.on("error", (streamErr: Error) => {
+ clearTimeout(timeout);
+ reject(new Error(`Stream error: ${streamErr.message}`));
+ });
+
+ // Initiate passwd command
+ stream.write("passwd\n");
+ });
+ });
+};
+
+export const sshPasswordRotationFactory: TRotationFactory<
+ TSshPasswordRotationWithConnection,
+ TSshPasswordRotationGeneratedCredentials,
+ TSshPasswordRotationInput["temporaryParameters"]
+> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service) => {
+ const { connection, parameters, secretsMapping, activeIndex } = secretRotation;
+ const { username, passwordRequirements, rotationMethod = SshPasswordRotationMethod.LoginAsRoot } = parameters;
+
+ // Helper to verify SSH credentials work
+ const $verifyCredentials = async (targetUsername: string, targetPassword: string): Promise<void> => {
+ const verifyConfig: TSshConnectionConfig = {
+ method: SshConnectionMethod.Password,
+ app: connection.app,
+ orgId: connection.orgId,
+ gatewayId: connection.gatewayId,
+ credentials: {
+ host: connection.credentials.host,
+ port: connection.credentials.port,
+ username: targetUsername,
+ password: targetPassword
+ }
+ };
+
+ try {
+ await executeWithPotentialGateway(verifyConfig, gatewayV2Service, async (targetHost, targetPort) => {
+ const client = await getSshConnectionClient(verifyConfig, targetHost, targetPort);
+ client.destroy();
+ });
+ } catch (error) {
+ throw new Error(`Failed to verify credentials - ${(error as Error).message}`);
+ }
+ };
+
+ // Main password rotation logic
+ const $rotatePassword = async (currentPassword?: string): Promise<{ username: string; password: string }> => {
+ const { credentials } = connection;
+ const newPassword = generatePassword(passwordRequirements);
+
+ const isSelfRotation = rotationMethod === SshPasswordRotationMethod.LoginAsTarget;
+ if (username === credentials.username)
+ throw new BadRequestError({ message: "Provided username is used in Infisical app connections." });
+
+ // Determine which credentials to use for the SSH connection
+ let connectConfig: TSshConnectionConfig;
+
+ if (isSelfRotation && currentPassword) {
+ // For self-rotation with current password, connect as the target user
+ connectConfig = {
+ method: SshConnectionMethod.Password,
+ app: connection.app,
+ orgId: connection.orgId,
+ gatewayId: connection.gatewayId,
+ credentials: {
+ host: credentials.host,
+ port: credentials.port,
+ username,
+ password: currentPassword
+ }
+ };
+ } else {
+ // For managed rotation, connect with the app connection credentials (admin)
+ connectConfig = {
+ method: connection.method,
+ app: connection.app,
+ orgId: connection.orgId,
+ gatewayId: connection.gatewayId,
+ credentials: connection.credentials
+ } as TSshConnectionConfig;
+ }
+
+ await executeWithPotentialGateway(connectConfig, gatewayV2Service, async (targetHost, targetPort) => {
+ const client = await getSshConnectionClient(connectConfig, targetHost, targetPort);
+
+ try {
+ if (isSelfRotation && currentPassword) {
+ // Self rotation: user changes their own password using passwd command
+ await changeSelfPassword(client, currentPassword, newPassword);
+ } else {
+ // Managed rotation: admin changes user's password using sudo chpasswd
+ await changeManagedPassword(client, username, newPassword);
+ }
+ } finally {
+ client.destroy();
+ }
+ });
+
+ // Verify the new credentials work
+ await $verifyCredentials(username, newPassword);
+
+ return { username, password: newPassword };
+ };
+
+ const issueCredentials: TRotationFactoryIssueCredentials<
+ TSshPasswordRotationGeneratedCredentials,
+ TSshPasswordRotationInput["temporaryParameters"]
+ > = async (callback, temporaryParameters) => {
+ // For both self and managed rotation, we need the current password for initial setup
+ // Self rotation: to authenticate as the user and change their own password
+ // Managed rotation: to verify the temporary password works before rotating
+ const credentials = await $rotatePassword(temporaryParameters?.password);
+ return callback(credentials);
+ };
+
+ const revokeCredentials: TRotationFactoryRevokeCredentials<TSshPasswordRotationGeneratedCredentials> = async (
+ credentialsToRevoke,
+ callback
+ ) => {
+ const currentPassword = credentialsToRevoke[activeIndex].password;
+ // We just rotate to a new password, essentially revoking old credentials
+ // For self rotation: we need current password to authenticate
+ // For managed rotation: admin uses their own credentials
+ await $rotatePassword(currentPassword);
+ return callback();
+ };
+
+ const rotateCredentials: TRotationFactoryRotateCredentials<TSshPasswordRotationGeneratedCredentials> = async (
+ _,
+ callback,
+ activeCredentials
+ ) => {
+ // For both methods, pass the current password
+ // Self rotation: needed to authenticate as the user
+ // Managed rotation: admin doesn't need it but it's harmless to pass
+ const credentials = await $rotatePassword(activeCredentials.password);
+ return callback(credentials);
+ };
+
+ const getSecretsPayload: TRotationFactoryGetSecretsPayload<TSshPasswordRotationGeneratedCredentials> = (
+ generatedCredentials
+ ) => {
+ return [
+ { key: secretsMapping.username, value: generatedCredentials.username },
+ { key: secretsMapping.password, value: generatedCredentials.password }
+ ];
+ };
+
+ return {
+ issueCredentials,
+ revokeCredentials,
+ rotateCredentials,
+ getSecretsPayload
+ };
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-schemas.ts
new file mode 100644
index 0000000000..84ed709916
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-schemas.ts
@@ -0,0 +1,88 @@
+import { z } from "zod";
+
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import {
+ BaseCreateSecretRotationSchema,
+ BaseSecretRotationSchema,
+ BaseUpdateSecretRotationSchema
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-schemas";
+import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/shared/general";
+import { SecretRotations } from "@app/lib/api-docs";
+import { SecretNameSchema } from "@app/server/lib/schemas";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+export enum SshPasswordRotationMethod {
+ LoginAsTarget = "login-as-target",
+ LoginAsRoot = "login-as-root"
+}
+
+export const SshPasswordRotationGeneratedCredentialsSchema = z
+ .object({
+ username: z.string(),
+ password: z.string()
+ })
+ .array()
+ .min(1)
+ .max(2);
+
+const SshPasswordRotationParametersSchema = z.object({
+ username: z.string().trim().min(1, "Username required").describe(SecretRotations.PARAMETERS.SSH_PASSWORD.username),
+ passwordRequirements: PasswordRequirementsSchema.optional(),
+ rotationMethod: z
+ .nativeEnum(SshPasswordRotationMethod)
+ .optional()
+ .describe(SecretRotations.PARAMETERS.SSH_PASSWORD.rotationMethod)
+});
+
+const SshPasswordRotationSecretsMappingSchema = z.object({
+ username: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.SSH_PASSWORD.username),
+ password: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.SSH_PASSWORD.password)
+});
+
+export const SshPasswordRotationTemplateSchema = z.object({
+ secretsMapping: z.object({
+ username: z.string(),
+ password: z.string()
+ })
+});
+
+export const SshPasswordRotationSchema = BaseSecretRotationSchema(SecretRotation.SshPassword).extend({
+ type: z.literal(SecretRotation.SshPassword),
+ parameters: SshPasswordRotationParametersSchema,
+ secretsMapping: SshPasswordRotationSecretsMappingSchema
+});
+
+export const CreateSshPasswordRotationSchema = BaseCreateSecretRotationSchema(SecretRotation.SshPassword)
+ .extend({
+ parameters: SshPasswordRotationParametersSchema,
+ secretsMapping: SshPasswordRotationSecretsMappingSchema,
+ temporaryParameters: z
+ .object({
+ password: z.string().min(1, "Password required").describe(SecretRotations.PARAMETERS.SSH_PASSWORD.password)
+ })
+ .optional()
+ })
+ .superRefine((val, ctx) => {
+ // Password is required for both rotation methods during initial setup
+ // Self rotation: needed to authenticate as the user
+ // Managed rotation: needed to verify initial credentials
+ if (!val.temporaryParameters?.password) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Current password is required for initial rotation setup",
+ path: ["temporaryParameters", "password"]
+ });
+ }
+ });
+
+export const UpdateSshPasswordRotationSchema = BaseUpdateSecretRotationSchema(SecretRotation.SshPassword).extend({
+ parameters: SshPasswordRotationParametersSchema.optional(),
+ secretsMapping: SshPasswordRotationSecretsMappingSchema.optional()
+});
+
+export const SshPasswordRotationListItemSchema = z.object({
+ name: z.literal("SSH Password"),
+ connection: z.literal(AppConnection.SSH),
+ type: z.literal(SecretRotation.SshPassword),
+ template: SshPasswordRotationTemplateSchema
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-types.ts b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-types.ts
new file mode 100644
index 0000000000..b15d8b9633
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/ssh-password/ssh-password-rotation-types.ts
@@ -0,0 +1,22 @@
+import { z } from "zod";
+
+import { TSshConnection } from "@app/services/app-connection/ssh";
+
+import {
+ CreateSshPasswordRotationSchema,
+ SshPasswordRotationGeneratedCredentialsSchema,
+ SshPasswordRotationListItemSchema,
+ SshPasswordRotationSchema
+} from "./ssh-password-rotation-schemas";
+
+export type TSshPasswordRotation = z.infer<typeof SshPasswordRotationSchema>;
+
+export type TSshPasswordRotationInput = z.infer<typeof CreateSshPasswordRotationSchema>;
+
+export type TSshPasswordRotationListItem = z.infer<typeof SshPasswordRotationListItemSchema>;
+
+export type TSshPasswordRotationWithConnection = TSshPasswordRotation & {
+ connection: TSshConnection;
+};
+
+export type TSshPasswordRotationGeneratedCredentials = z.infer<typeof SshPasswordRotationGeneratedCredentialsSchema>;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 198d4b2717..4056df2aae 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2884,6 +2884,9 @@ export const SecretRotations = {
ROTATE: (type: SecretRotation) => ({
rotationId: `The ID of the ${SECRET_ROTATION_NAME_MAP[type]} Rotation to rotate generated credentials for.`
}),
+ RECONCILE: {
+ rotationId: "The ID of the SSH Password Rotation to reconcile credentials for."
+ },
PARAMETERS: {
SQL_CREDENTIALS: {
username1:
@@ -2906,6 +2909,12 @@ export const SecretRotations = {
'Whether the rotation should be performed by the LDAP "connection-principal" or the "target-principal" (defaults to \'connection-principal\').',
password: 'The password of the provided principal if "parameters.rotationMethod" is set to "target-principal".'
},
+ SSH_PASSWORD: {
+ username: "The username of the Unix/Linux user account to rotate the password for.",
+ rotationMethod:
+ 'Whether the rotation should be performed using "self" (the target user\'s own credentials) or "managed" (the SSH connection\'s admin credentials). Defaults to "managed".',
+ password: 'The current password of the target user if "parameters.rotationMethod" is set to "managed".'
+ },
GENERAL: {
PASSWORD_REQUIREMENTS: {
base: "The password requirements to use when generating the new password.",
@@ -2967,6 +2976,10 @@ export const SecretRotations = {
dn: "The name of the secret that the Distinguished Name (DN) or User Principal Name (UPN) of the principal will be mapped to.",
password: "The name of the secret that the rotated password will be mapped to."
},
+ SSH_PASSWORD: {
+ username: "The name of the secret that the username will be mapped to.",
+ password: "The name of the secret that the rotated password will be mapped to."
+ },
AWS_IAM_USER_SECRET: {
accessKeyId: "The name of the secret that the access key ID will be mapped to.",
secretAccessKey: "The name of the secret that the rotated secret access key will be mapped to."