Skip to content

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

feat: add revert sidecar and down migration to pam-revamp migration

bernie-gbf0052f5e345
diff --git a/backend/src/db/migrations/20260612142201_pam-revamp.ts b/backend/src/db/migrations/20260612142201_pam-revamp.ts
index 03a98aa623..52d9fe3d50 100644
--- a/backend/src/db/migrations/20260612142201_pam-revamp.ts
+++ b/backend/src/db/migrations/20260612142201_pam-revamp.ts
@@ -29,6 +29,7 @@ import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/
// tables for ~15 statements x org count (12+ min at Cloud scale); chunked inserts take seconds.
const PROJECT_INSERT_CHUNK = 500;
const TEMPLATE_INSERT_CHUNK = 1000;
+const BACKUP_TABLE = "pam_revamp_backup";
type TMembershipActor = {
actorUserId?: string | null;
@@ -79,6 +80,14 @@ const backfillPamProjectsForAllOrgs = async (knex: Knex) => {
orgToPamProject.set(orgId, id);
}
+ await knex(BACKUP_TABLE).insert(
+ insertedProjects.map(({ id, orgId }) => ({
+ entityType: "created_project",
+ entityId: id,
+ before: { orgId }
+ }))
+ );
+
const templateRows = insertedProjects.flatMap(({ id: projectId }) =>
DEFAULT_ACCOUNT_TEMPLATES.map((template) => ({
projectId,
@@ -106,6 +115,20 @@ export async function up(knex: Knex): Promise<void> {
return;
}
+ // Sidecar recording the before-state of everything this migration overwrites in place,
+ // written in the same transaction. down() replays it verbatim; drop once rollback is moot.
+ await knex.schema.createTable(BACKUP_TABLE, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.string("entityType").notNullable();
+ t.index("entityType");
+ t.string("entityId", 36).notNullable();
+ t.jsonb("before").nullable();
+ t.binary("beforeCredentials").nullable();
+ t.binary("beforeSessionKey").nullable();
+ t.binary("beforeLogsBlob").nullable();
+ t.timestamps(true, true, true);
+ });
+
await knex.schema.createTable(TableName.PamAccountTemplate, (t) => {
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
@@ -268,6 +291,8 @@ export async function up(knex: Knex): Promise<void> {
.where(`${TableName.PamResource}.projectId`, oldProjectId)
.select(
`${TableName.PamAccount}.id as accountId`,
+ `${TableName.PamAccount}.name as accountName`,
+ `${TableName.PamAccount}.projectId as accountProjectId`,
`${TableName.PamAccount}.encryptedCredentials`,
`${TableName.PamResource}.resourceType`,
`${TableName.PamResource}.encryptedConnectionDetails`,
@@ -285,6 +310,12 @@ export async function up(knex: Knex): Promise<void> {
`PAM migration: no template for resource account [accountId=${account.accountId}] [type=${account.resourceType}]`
);
}
+ await knex(BACKUP_TABLE).insert({
+ entityType: "account",
+ entityId: account.accountId,
+ before: { projectId: account.accountProjectId, name: account.accountName },
+ beforeCredentials: account.encryptedCredentials
+ });
await knex(TableName.PamAccount)
.where("id", account.accountId)
.update({
@@ -304,6 +335,8 @@ export async function up(knex: Knex): Promise<void> {
.where(`${TableName.PamDomain}.projectId`, oldProjectId)
.select(
`${TableName.PamAccount}.id as accountId`,
+ `${TableName.PamAccount}.name as accountName`,
+ `${TableName.PamAccount}.projectId as accountProjectId`,
`${TableName.PamAccount}.encryptedCredentials`,
`${TableName.PamDomain}.domainType`,
`${TableName.PamDomain}.encryptedConnectionDetails`,
@@ -321,6 +354,12 @@ export async function up(knex: Knex): Promise<void> {
`PAM migration: no template for domain account [accountId=${account.accountId}] [type=${account.domainType}]`
);
}
+ await knex(BACKUP_TABLE).insert({
+ entityType: "account",
+ entityId: account.accountId,
+ before: { projectId: account.accountProjectId, name: account.accountName },
+ beforeCredentials: account.encryptedCredentials
+ });
await knex(TableName.PamAccount)
.where("id", account.accountId)
.update({
@@ -517,6 +556,14 @@ export async function up(knex: Knex): Promise<void> {
continue;
}
+ await knex(BACKUP_TABLE).insert({
+ entityType: "session",
+ entityId: session.id,
+ before: { projectId: session.projectId },
+ beforeSessionKey: session.encryptedSessionKey,
+ beforeLogsBlob: session.encryptedLogsBlob
+ });
+
const updates: Record<string, Buffer | string | undefined> = { projectId: sessionNewProjectId };
if (!projectCipherCache.has(session.projectId)) {
@@ -572,6 +619,133 @@ export async function up(knex: Knex): Promise<void> {
await knex(TableName.PamAccount).update({ credentialConfigured: true });
}
-export async function down(): Promise<void> {
- // No down migration or it will error
+// Replays the pam_revamp_backup sidecar verbatim: no re-derivation, no crypto. Only valid
+// while old-world zombie projects still exist. Post-rollback, the old app release must be
+// deployed and the PamDefaultProject:* keystore cache keys cleared.
+export async function down(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(BACKUP_TABLE))) {
+ if (!(await knex.schema.hasTable(TableName.PamAccountTemplate))) return;
+ throw new Error(`PAM revert: ${BACKUP_TABLE} table is missing; restore from a database backup instead`);
+ }
+
+ // Accounts created after the migration have no old-world home; a human must export or
+ // delete them before reverting
+ const strayAccounts = (await knex(TableName.PamAccount)
+ .whereNotIn("id", knex(BACKUP_TABLE).where("entityType", "account").select(knex.raw(`"entityId"::uuid`)))
+ .select("id")) as Array<{ id: string }>;
+ if (strayAccounts.length > 0) {
+ throw new Error(
+ `PAM revert: ${strayAccounts.length} account(s) were created after the migration; export or delete them first [ids=${strayAccounts
+ .map((a) => a.id)
+ .join(", ")}]`
+ );
+ }
+
+ const accountBackups = await knex(BACKUP_TABLE).where("entityType", "account");
+ for (const backup of accountBackups) {
+ const before = backup.before as { projectId: string; name: string };
+ await knex(TableName.PamAccount).where("id", backup.entityId).update({
+ projectId: before.projectId,
+ name: before.name,
+ folderId: null,
+ encryptedCredentials: backup.beforeCredentials
+ });
+ }
+
+ const sessionBackups = await knex(BACKUP_TABLE).where("entityType", "session");
+ for (const backup of sessionBackups) {
+ const before = backup.before as { projectId: string };
+ await knex(TableName.PamSession).where("id", backup.entityId).update({
+ projectId: before.projectId,
+ encryptedSessionKey: backup.beforeSessionKey,
+ encryptedLogsBlob: backup.beforeLogsBlob
+ });
+ }
+
+ // Drop the new account columns before deleting created projects: templateId's RESTRICT FK
+ // would otherwise block the template cascade
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.dropUnique(["folderId", "name"]);
+ t.dropForeign(["folderId"]);
+ t.dropColumn("templateId");
+ t.dropColumn("encryptedConnectionDetails");
+ t.dropColumn("encryptedInternalMetadata");
+ t.dropColumn("gatewayId");
+ t.dropColumn("gatewayPoolId");
+ t.dropColumn("recordingConnectionId");
+ t.dropColumn("settingsOverrides");
+ t.dropColumn("credentialConfigured");
+ });
+
+ // Cascades clean up the created projects' memberships, templates, folders, and any
+ // post-migration sessions
+ const createdProjectIds = (await knex(BACKUP_TABLE).where("entityType", "created_project").select("entityId")).map(
+ (r: { entityId: string }) => r.entityId
+ );
+ for (let i = 0; i < createdProjectIds.length; i += PROJECT_INSERT_CHUNK) {
+ await knex(TableName.Project)
+ .whereIn("id", createdProjectIds.slice(i, i + PROJECT_INSERT_CHUNK))
+ .delete();
+ }
+
+ await dropOnUpdateTrigger(knex, TableName.PamFolder);
+ await knex.schema.dropTable(TableName.PamFolder);
+
+ // Old-shape folders table from 20250917052037_pam.ts (dead unfinished feature; rows were
+ // never used so only the schema is restored)
+ await knex.schema.createTable(TableName.PamFolder, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.string("projectId").notNullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ t.index("projectId");
+
+ t.uuid("parentId").nullable();
+ t.foreign("parentId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");
+ t.index("parentId");
+
+ t.string("name").notNullable();
+ t.index("name");
+
+ t.unique(["projectId", "parentId", "name"], {
+ indexName: "uidx_pam_folder_children_name",
+ predicate: knex.whereNotNull("parentId")
+ });
+
+ t.unique(["projectId", "name"], {
+ indexName: "uidx_pam_folder_root_name",
+ predicate: knex.whereNull("parentId")
+ });
+
+ t.text("description").nullable();
+
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.PamFolder);
+
+ await knex.schema.alterTable(TableName.PamAccount, (t) => {
+ t.foreign("folderId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");
+ t.string("projectId").notNullable().alter();
+ });
+
+ await knex.raw(`
+ ALTER TABLE ${TableName.PamAccount}
+ ADD CONSTRAINT chk_pam_account_parent
+ CHECK (
+ (("resourceId" IS NOT NULL AND "domainId" IS NULL) OR ("resourceId" IS NULL AND "domainId" IS NOT NULL))
+ )
+ `);
+
+ await knex.schema.alterTable(TableName.PamSession, (t) => {
+ t.renameColumn("accountType", "resourceType");
+ t.dropColumn("folderName");
+ t.dropColumn("selectedHost");
+ t.string("resourceName").notNullable().alter();
+ });
+
+ await dropOnUpdateTrigger(knex, TableName.PamAccountTemplate);
+ await knex.schema.dropTable(TableName.PamAccountTemplate);
+
+ await knex.schema.dropTable(BACKUP_TABLE);
}