Skip to content

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

23.5 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-base-to-string */
import { z } from "zod";

import { SecretApprovalRequestsSchema, SecretFoldersSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { removeTrailingSlash } from "@app/lib/fn";
import { isValidFolderName } from "@app/lib/validator";
import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
import { SecretNameSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { booleanSchema, secretRawSchema } from "@app/server/routes/sanitizedSchemas";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { commitChangesResponseSchema, resourceChangeSchema } from "@app/services/folder-commit/folder-commit-schemas";
import { ResourceMetadataWithEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

const commitChangeSummarySchema = z.object({
  secretCount: z.number(),
  folderCount: z.number(),
  addedCount: z.number(),
  updatedCount: z.number(),
  deletedCount: z.number()
});

const commitHistoryItemSchema = z.object({
  id: z.string(),
  folderId: z.string(),
  actorType: z.string(),
  actorMetadata: z.unknown().optional(),
  message: z.string().optional().nullable(),
  commitId: z.string(),
  createdAt: z.string().or(z.date()),
  envId: z.string(),
  summary: commitChangeSummarySchema
});

const commitAuthorSchema = z.object({
  actorId: z.string().nullable(),
  actorType: z.string(),
  name: z.string().nullable()
});

const CommitSecretSchema = secretRawSchema.extend({
  secretValueHidden: z.boolean()
});

const CommitApprovalSchema = SecretApprovalRequestsSchema.pick({
  id: true,
  slug: true,
  policyId: true,
  folderId: true,
  status: true,
  hasMerged: true,
  commitMessage: true,
  committerUserId: true,
  committerIdentityId: true,
  createdAt: true,
  updatedAt: true
});

const CommitFolderSchema = SecretFoldersSchema.pick({
  id: true,
  name: true,
  description: true,
  envId: true,
  parentId: true,
  version: true,
  createdAt: true,
  updatedAt: true
});

const folderStateSchema = z.array(
  z.object({
    type: z.string(),
    id: z.string(),
    versionId: z.string(),
    secretKey: z.string().optional(),
    secretVersion: z.number().optional(),
    folderName: z.string().optional(),
    folderVersion: z.number().optional()
  })
);

// Bounds match what the columns behind these actually permit, so no existing resource can be
// locked out: project ids are varchar(36) rather than uuid (they still hold pre-uuid ids), env
// slugs are varchar(255), and a path is at most buildFolderPath's 20 levels of varchar(255) names
const folderScopeQuerySchema = z.object({
  environment: z.string().trim().min(1).max(255),
  path: z.string().trim().max(6144).default("/").transform(removeTrailingSlash),
  projectId: z.string().trim().min(1).max(36)
});

export const registerPITRouter = async (server: FastifyZodProvider) => {
  // Get commits count for a folder
  server.route({
    method: "GET",
    url: "/commits/count",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "getFolderCommitsCount",
      querystring: z.object({
        environment: z.string().trim(),
        path: z.string().trim().default("/").transform(removeTrailingSlash),
        projectId: z.string().trim()
      }),
      response: {
        200: z.object({
          count: z.number(),
          folderId: z.string()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.getCommitsCount({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        environment: req.query.environment,
        path: req.query.path
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.GET_PROJECT_PIT_COMMIT_COUNT,
          metadata: {
            environment: req.query.environment,
            path: req.query.path,
            commitCount: result.count.toString()
          }
        }
      });

      return result;
    }
  });

  // Get all commits for a folder
  server.route({
    method: "GET",
    url: "/commits",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "listFolderCommits",
      querystring: folderScopeQuerySchema.extend({
        offset: z.coerce.number().min(0).default(0),
        limit: z.coerce.number().min(1).max(100).default(20),
        search: z
          .string()
          .trim()
          .max(255)
          .optional()
          .describe(
            "Match commits by message, commit ID prefix, author, or the key or name of any resource they changed."
          ),
        sort: z.enum(["asc", "desc"]).default("desc"),
        actorId: z
          .string()
          .trim()
          .uuid()
          .optional()
          .describe("Only return commits made by the user or machine identity with this ID."),
        actorType: z.nativeEnum(ActorType).optional().describe("Only return commits made by this type of actor.")
      }),
      response: {
        200: z.object({
          commits: commitHistoryItemSchema.array(),
          total: z.number(),
          hasMore: z.boolean()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.getCommitsForFolder({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        environment: req.query.environment,
        path: req.query.path,
        offset: req.query.offset,
        limit: req.query.limit,
        search: req.query.search,
        sort: req.query.sort,
        authorFilter: { actorId: req.query.actorId, actorType: req.query.actorType }
      });

      // Every commit on an author-filtered page belongs to that author, so the readable label
      // the audit log needs for the actor filter comes off the page without a second lookup
      const filteredActor = req.query.actorId
        ? (result.commits[0]?.actorMetadata as { name?: string; email?: string } | undefined)
        : undefined;

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.GET_PROJECT_PIT_COMMITS,
          metadata: {
            environment: req.query.environment,
            path: req.query.path,
            commitCount: result.commits.length.toString(),
            offset: req.query.offset.toString(),
            limit: req.query.limit.toString(),
            search: req.query.search,
            sort: req.query.sort,
            filteredActorId: req.query.actorId,
            filteredActorName: filteredActor?.email || filteredActor?.name,
            filteredActorType: req.query.actorType
          }
        }
      });

      return result;
    }
  });

  // Get the distinct authors that have committed to a folder
  server.route({
    method: "GET",
    url: "/commits/authors",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "listFolderCommitAuthors",
      querystring: folderScopeQuerySchema,
      response: {
        200: z.object({
          authors: commitAuthorSchema.array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.getCommitAuthorsForFolder({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        environment: req.query.environment,
        path: req.query.path
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.GET_PROJECT_PIT_COMMIT_AUTHORS,
          metadata: {
            environment: req.query.environment,
            path: req.query.path,
            authorCount: result.authors.length.toString()
          }
        }
      });

      return result;
    }
  });

  // Get commit changes for a specific commit
  server.route({
    method: "GET",
    url: "/commits/:commitId/changes",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "getFolderCommitChanges",
      params: z.object({
        commitId: z.string().trim()
      }),
      querystring: z.object({
        projectId: z.string().trim()
      }),
      response: {
        200: commitChangesResponseSchema
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.getCommitChanges({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        commitId: req.params.commitId
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.GET_PROJECT_PIT_COMMIT_CHANGES,
          metadata: {
            commitId: req.params.commitId,
            changesCount: (result.changes.changes?.length || 0).toString()
          }
        }
      });

      return result;
    }
  });

  // Retrieve rollback changes for a commit
  server.route({
    method: "GET",
    url: "/commits/:commitId/compare",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "compareFolderCommit",
      params: z.object({
        commitId: z.string().trim()
      }),
      querystring: z.object({
        folderId: z.string().trim(),
        deepRollback: booleanSchema.default(false),
        projectId: z.string().trim()
      }),
      response: {
        200: z.array(
          z.object({
            folderId: z.string(),
            folderName: z.string(),
            folderPath: z.string().optional(),
            changes: z.array(resourceChangeSchema)
          })
        )
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const { diffs, environment, folderPath } = await server.services.pit.compareCommitChanges({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        commitId: req.params.commitId,
        folderId: req.query.folderId,
        deepRollback: req.query.deepRollback
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.PIT_COMPARE_FOLDER_STATES,
          metadata: {
            targetCommitId: req.params.commitId,
            folderId: req.query.folderId,
            deepRollback: req.query.deepRollback,
            diffsCount: diffs.length.toString(),
            environment,
            folderPath
          }
        }
      });

      return diffs;
    }
  });

  // Rollback to a previous commit
  server.route({
    method: "POST",
    url: "/commits/:commitId/rollback",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "rollbackFolderCommit",
      params: z.object({
        commitId: z.string().trim()
      }),
      body: z.object({
        folderId: z.string().trim(),
        deepRollback: z.boolean().default(false),
        message: z.string().max(256).trim().optional(),
        environment: z.string().trim(),
        projectId: z.string().trim()
      }),
      response: {
        200: z.object({
          success: z.boolean(),
          secretChangesCount: z.number().optional(),
          folderChangesCount: z.number().optional(),
          totalChanges: z.number().optional()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.rollbackToCommit({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.body.projectId,
        commitId: req.params.commitId,
        folderId: req.body.folderId,
        deepRollback: req.body.deepRollback,
        message: req.body.message
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.body.projectId,
        event: {
          type: EventType.PIT_ROLLBACK_COMMIT,
          metadata: {
            targetCommitId: req.params.commitId,
            environment: req.body.environment,
            folderId: req.body.folderId,
            deepRollback: req.body.deepRollback,
            message: req.body.message || "Rollback to previous commit",
            totalChanges: result.totalChanges?.toString() || "0"
          }
        }
      });

      await server.services.telemetry.sendPostHogEvents({
        event: PostHogEventTypes.SecretRollbackPerformed,
        distinctId: getTelemetryDistinctId(req),
        organizationId: req.permission.orgId,
        properties: {
          projectId: req.body.projectId,
          environment: req.body.environment,
          commitId: req.params.commitId,
          deepRollback: req.body.deepRollback,
          totalChanges: result.totalChanges || 0
        }
      });

      return result;
    }
  });

  // Revert commit
  server.route({
    method: "POST",
    url: "/commits/:commitId/revert",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "revertFolderCommit",
      params: z.object({
        commitId: z.string().trim()
      }),
      body: z.object({
        projectId: z.string().trim()
      }),
      response: {
        200: z.object({
          success: z.boolean(),
          message: z.string(),
          originalCommitId: z.string(),
          revertCommitId: z.string().optional(),
          changesReverted: z.number().optional()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.revertCommit({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.body.projectId,
        commitId: req.params.commitId
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.body.projectId,
        event: {
          type: EventType.PIT_REVERT_COMMIT,
          metadata: {
            commitId: req.params.commitId,
            revertCommitId: result.revertCommitId,
            changesReverted: result.changesReverted?.toString()
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.SecretRevertPerformed,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            projectId: req.body.projectId,
            commitId: req.params.commitId,
            changesReverted: result.changesReverted
          }
        })
        .catch(() => {});

      return result;
    }
  });

  // Folder state at commit
  server.route({
    method: "GET",
    url: "/commits/:commitId",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "getFolderStateAtCommit",
      params: z.object({
        commitId: z.string().trim()
      }),
      querystring: z.object({
        folderId: z.string().trim(),
        projectId: z.string().trim()
      }),
      response: {
        200: folderStateSchema
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.getFolderStateAtCommit({
        actor: req.permission?.type,
        actorId: req.permission?.id,
        actorOrgId: req.permission?.orgId,
        actorAuthMethod: req.permission?.authMethod,
        projectId: req.query.projectId,
        commitId: req.params.commitId
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.query.projectId,
        event: {
          type: EventType.PIT_GET_FOLDER_STATE,
          metadata: {
            commitId: req.params.commitId,
            folderId: req.query.folderId,
            resourceCount: result.length.toString()
          }
        }
      });

      return result;
    }
  });

  server.route({
    method: "POST",
    url: "/batch/commit",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      hide: true,
      operationId: "createBatchFolderCommit",
      description: "Commit changes",
      security: [
        {
          bearerAuth: []
        }
      ],
      body: z.object({
        projectId: z.string().trim(),
        environment: z.string().trim(),
        secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
        message: z.string().trim().max(255).optional(),
        changes: z.object({
          secrets: z.object({
            create: z
              .array(
                z.object({
                  secretKey: SecretNameSchema,
                  secretValue: z.string().transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim())),
                  secretComment: z.string().trim().optional().default(""),
                  skipMultilineEncoding: z.boolean().optional(),
                  metadata: z.record(z.string()).optional(),
                  secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
                  tagIds: z.string().array().optional()
                })
              )
              .optional(),
            update: z
              .array(
                z.object({
                  secretKey: SecretNameSchema,
                  newSecretName: SecretNameSchema.optional(),
                  secretValue: z
                    .string()
                    .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim()))
                    .optional(),
                  secretComment: z.string().trim().optional().default(""),
                  skipMultilineEncoding: z
                    .boolean()
                    .nullish()
                    .transform((val) => (val === null ? false : val)),
                  metadata: z.record(z.string()).optional(),
                  secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
                  tagIds: z.string().array().optional()
                })
              )
              .optional(),
            delete: z
              .array(
                z.object({
                  secretKey: SecretNameSchema
                })
              )
              .optional()
          }),
          folders: z.object({
            create: z
              .array(
                z.object({
                  folderName: z
                    .string()
                    .trim()
                    .refine((name) => isValidFolderName(name), {
                      message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
                    }),
                  description: z.string().optional()
                })
              )
              .optional(),
            update: z
              .array(
                z.object({
                  folderName: z
                    .string()
                    .trim()
                    .refine((name) => isValidFolderName(name), {
                      message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
                    }),
                  description: z.string().nullable().optional(),
                  id: z.string()
                })
              )
              .optional(),
            delete: z
              .array(
                z.object({
                  folderName: z
                    .string()
                    .trim()
                    .refine((name) => isValidFolderName(name), {
                      message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
                    }),
                  id: z.string()
                })
              )
              .optional()
          })
        })
      }),
      response: {
        200: z.object({
          commitId: z.string().uuid().nullable(),
          approval: CommitApprovalSchema.nullable(),
          secrets: z.object({
            created: CommitSecretSchema.array(),
            updated: CommitSecretSchema.array(),
            deleted: CommitSecretSchema.array()
          }),
          folders: z.object({
            created: CommitFolderSchema.array(),
            updated: CommitFolderSchema.array(),
            deleted: CommitFolderSchema.array()
          })
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const result = await server.services.pit.processNewCommitRaw({
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod,
        projectId: req.body.projectId,
        environment: req.body.environment,
        secretPath: req.body.secretPath,
        message: req.body.message || "",
        changes: {
          secrets: req.body.changes.secrets,
          folders: req.body.changes.folders
        }
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        projectId: req.body.projectId,
        event: {
          type: EventType.PIT_PROCESS_NEW_COMMIT_RAW,
          metadata: {
            commitId: result.commitId,
            approvalId: result.approval?.id,
            approvalSlug: result.approval?.slug,
            projectId: req.body.projectId,
            environment: req.body.environment,
            secretPath: req.body.secretPath,
            message: req.body.message || ""
          }
        }
      });

      for await (const event of result.secretMutationEvents) {
        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          orgId: req.permission.orgId,
          projectId: req.body.projectId,
          event
        });
      }

      const foldersToCreate = req.body.changes.folders?.create;
      if (foldersToCreate && foldersToCreate.length > 0) {
        await Promise.all(
          foldersToCreate.map((folder) =>
            server.services.telemetry.sendPostHogEvents({
              event: PostHogEventTypes.SecretFolderCreated,
              distinctId: getTelemetryDistinctId(req),
              organizationId: req.permission.orgId,
              properties: {
                projectId: req.body.projectId,
                environment: req.body.environment,
                folderName: folder.folderName
              }
            })
          )
        );
      }

      return {
        commitId: result.commitId ?? null,
        approval: result.approval ?? null,
        secrets: result.secrets,
        folders: result.folders
      };
    }
  });
};