Skip to content

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

80.0 KB
Raw Blame
import { ForbiddenError } from "@casl/ability";
import qs from "qs";
import { z } from "zod";

import { SecretFoldersSchema, SecretImportsSchema, SecretType } from "@app/db/schemas";
import { RemindersSchema } from "@app/db/schemas/reminders";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
import { SecretRotationV2Schema } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema";
import { DASHBOARD } from "@app/lib/api-docs";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
import { OrderByDirection } from "@app/lib/types";
import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
import { SecretNameSchema, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import {
  booleanSchema,
  SanitizedDynamicSecretSchema,
  SanitizedHoneyTokenSchema,
  SanitizedProxiedServiceSchema,
  SanitizedTagSchema,
  secretRawSchema
} from "@app/server/routes/sanitizedSchemas";
import { AuthMode } from "@app/services/auth/auth-type";
import { ResourceMetadataWithEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
import {
  SecretMetadataSearchLogicalOperator,
  SecretMetadataSearchOperator
} from "@app/services/resource-metadata/resource-metadata-types";
import {
  PersonalOverridesBehavior,
  SecretImportReferencesBehavior,
  SecretsOrderBy,
  SecretSortField
} from "@app/services/secret/secret-types";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

import { SecretMetadataQuerySchema, SecretMetadataResponseSchema } from "./dashboard-secret-metadata-schemas";
import { isInSecretSearchScope, resolveSecretDeepSearch } from "./dashboard-secret-search-fns";

const MAX_DEEP_SEARCH_LIMIT = 500; // arbitrary limit to prevent excessive results
const DEEP_SEARCH_DEFAULT_PAGE_LIMIT = 25;
const DEEP_SEARCH_MAX_PAGE_LIMIT = 100;

const SECRET_METADATA_SEARCH_MAX_FILTERS = 20;

const SecretMetadataSearchQuerySchema = z.object({
  operator: z.nativeEnum(SecretMetadataSearchLogicalOperator).default(SecretMetadataSearchLogicalOperator.And),
  filters: z
    .object({
      key: z.string().trim().min(1).max(255),
      value: z.string().trim().max(1020),
      operator: z.nativeEnum(SecretMetadataSearchOperator).default(SecretMetadataSearchOperator.Is)
    })
    .array()
    .min(1)
    .max(SECRET_METADATA_SEARCH_MAX_FILTERS)
});

export const registerDashboardRouter = async (server: FastifyZodProvider) => {
  server.route({
    method: "GET",
    url: "/accessible-secrets/metadata",
    config: { rateLimit: secretsLimit },
    schema: {
      operationId: "getAccessibleSecretMetadata",
      description: "List shared secret metadata recursively without reading secret values.",
      security: [{ bearerAuth: [] }],
      querystring: SecretMetadataQuerySchema,
      response: { 200: SecretMetadataResponseSchema }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) =>
      server.services.secret.getSecretMetadata({
        ...req.query,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId
      })
  });

  server.route({
    method: "GET",
    url: "/secrets-by-metadata",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "searchSecretsByMetadata",
      description:
        "Search a project's secrets by their metadata. Filters are supplied as nested querystring params (parsed with qs), e.g. `?projectId=<id>&operator=and&filters[0][key]=env&filters[0][value]=prod&filters[0][operator]=is`. Results are limited to secrets the requester can describe.",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z
        .object({
          projectId: z.string().trim().describe(DASHBOARD.SECRET_OVERVIEW_LIST.projectId),
          operator: z.nativeEnum(SecretMetadataSearchLogicalOperator).optional(),
          environments: z
            .string()
            .trim()
            .max(65535)
            .transform((value) => value.split(","))
            .pipe(slugSchema({ field: "Environment slug" }).array().min(1).max(1000))
            .optional()
            .describe(DASHBOARD.SECRET_OVERVIEW_LIST.environments),
          secretPath: SecretMetadataQuerySchema.shape.secretPath,
          tags: z.string().trim().transform(decodeURIComponent).optional()
        })
        .describe(
          "Metadata conditions are passed as nested `filters[<n>][key|value|operator]` params (qs syntax); `operator` is the top-level and/or combinator. `tags` is an optional comma-separated list of tag slugs that further narrows results to secrets carrying at least one of them."
        ),
      response: {
        200: z.object({
          searchLimit: z.number().describe(DASHBOARD.SECRET_METADATA_SEARCH.searchLimit),
          secrets: z
            .object({
              secretId: z.string(),
              secretKey: z.string(),
              environment: z.string(),
              secretPath: z.string(),
              tags: z
                .object({ id: z.string(), slug: z.string() })
                .array()
                .describe(DASHBOARD.SECRET_METADATA_SEARCH.tags),
              secretValueHidden: z.boolean().describe(DASHBOARD.SECRET_METADATA_LIST.secretValueHidden),
              metadata: z
                .object({
                  key: z.string(),
                  value: z.string().nullable()
                })
                .array()
            })
            .array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const rawQueryString = req.url.includes("?") ? req.url.slice(req.url.indexOf("?") + 1) : "";
      const { filters, operator } = SecretMetadataSearchQuerySchema.parse(qs.parse(rawQueryString));
      const { projectId } = req.query;
      const tagSlugs = req.query.tags?.split(",").filter((tag) => Boolean(tag.trim())) ?? [];

      const result = await server.services.resourceMetadata.searchSecretMetadata({
        filters,
        operator,
        tagSlugs,
        environments: req.query.environments,
        secretPath: req.query.secretPath,
        actor: req.permission,
        projectId
      });
      const { secrets } = result;

      await server.services.auditLog.createAuditLog({
        projectId,
        ...req.auditLogInfo,
        event: {
          type: EventType.SEARCH_SECRETS_BY_METADATA,
          metadata: {
            operator,
            filters: filters.map((filter) => ({ key: filter.key, value: filter.value, operator: filter.operator })),
            tags: tagSlugs,
            numberOfSecrets: secrets.length,
            secrets: secrets.map((secret) => ({
              id: secret.secretId,
              secretKey: secret.secretKey,
              environment: secret.environment,
              secretPath: secret.secretPath
            }))
          }
        }
      });

      return result;
    }
  });

  server.route({
    method: "GET",
    url: "/secrets-overview",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "listProjectSecretsOverview",
      description: "List project secrets overview",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim().describe(DASHBOARD.SECRET_OVERVIEW_LIST.projectId),
        environments: z
          .string()
          .trim()
          .transform(decodeURIComponent)
          .describe(DASHBOARD.SECRET_OVERVIEW_LIST.environments),
        secretPath: z
          .string()
          .trim()
          .default("/")
          .transform(removeTrailingSlash)
          .describe(DASHBOARD.SECRET_OVERVIEW_LIST.secretPath),
        offset: z.coerce.number().min(0).optional().default(0).describe(DASHBOARD.SECRET_OVERVIEW_LIST.offset),
        limit: z.coerce.number().min(1).max(100).optional().default(100).describe(DASHBOARD.SECRET_OVERVIEW_LIST.limit),
        orderBy: z
          .nativeEnum(SecretSortField)
          .default(SecretSortField.Name)
          .describe(DASHBOARD.SECRET_OVERVIEW_LIST.orderBy),
        orderDirection: z
          .nativeEnum(OrderByDirection)
          .default(OrderByDirection.ASC)
          .describe(DASHBOARD.SECRET_OVERVIEW_LIST.orderDirection),
        sortEnvironment: slugSchema().describe(DASHBOARD.SECRET_OVERVIEW_LIST.sortEnvironment).optional(),
        search: z.string().trim().describe(DASHBOARD.SECRET_OVERVIEW_LIST.search).optional(),
        tags: z.string().trim().transform(decodeURIComponent).describe(DASHBOARD.SECRET_OVERVIEW_LIST.tags).optional(),
        includeSecrets: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeSecrets),
        includeFolders: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeFolders),
        includeImports: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeImports),
        includeSecretRotations: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeSecretRotations),
        includeDynamicSecrets: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeDynamicSecrets),
        includeHoneyTokens: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeHoneyTokens),
        includeProxiedServices: booleanSchema.describe(DASHBOARD.SECRET_OVERVIEW_LIST.includeProxiedServices)
      }),
      response: {
        200: z.object({
          folders: SecretFoldersSchema.extend({ environment: z.string() }).array().optional(),
          dynamicSecrets: SanitizedDynamicSecretSchema.extend({ environment: z.string() }).array().optional(),
          honeyTokens: SanitizedHoneyTokenSchema.array().optional(),
          proxiedServices: SanitizedProxiedServiceSchema.array().optional(),
          secretRotations: z
            .intersection(
              SecretRotationV2Schema,
              z.object({
                // TODO (scott): think we can actually get rid of this and not query relations as we don't display secrets with rotations anymore
                secrets: secretRawSchema
                  .omit({ secretValue: true })
                  .extend({
                    secretValueHidden: z.boolean(),
                    secretPath: z.string().optional(),
                    secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
                    tags: SanitizedTagSchema.array().optional()
                  })
                  .nullable()
                  .array()
              })
            )
            .array()
            .optional(),
          secrets: secretRawSchema
            .omit({ secretValue: true })
            .extend({
              isHoneyTokenSecret: z.boolean().optional(),
              isEmpty: z.boolean(),
              secretValueHidden: z.boolean(),
              secretPath: z.string().optional(),
              secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
              tags: SanitizedTagSchema.array().optional(),
              reminder: RemindersSchema.extend({
                recipients: z.string().array().optional()
              }).nullish(),
              revokedProjectFolderGrant: z.boolean().optional()
            })
            .array()
            .optional(),
          imports: SecretImportsSchema.omit({ importEnv: true })
            .extend({
              importEnv: z.object({
                name: z.string(),
                slug: z.string(),
                id: z.string(),
                projectId: z.string().optional()
              }),
              sourceProjectName: z.string().optional(),
              environment: z.string(),
              isAccessRevoked: z.boolean()
            })
            .array()
            .optional(),
          importedByEnvs: z
            .object({
              environment: z.string(),
              importedBy: z
                .object({
                  environment: z.object({
                    name: z.string(),
                    slug: z.string()
                  }),
                  project: z
                    .object({
                      name: z.string(),
                      slug: z.string(),
                      id: z.string()
                    })
                    .optional(),
                  folders: z
                    .object({
                      name: z.string(),
                      isImported: z.boolean(),
                      secrets: z
                        .object({
                          secretId: z.string(),
                          referencedSecretKey: z.string(),
                          referencedSecretEnv: z.string()
                        })
                        .array()
                        .optional()
                    })
                    .array()
                })
                .array()
                .optional()
            })
            .array()
            .optional(),
          usedBySecretSyncs: z
            .object({
              name: z.string(),
              destination: z.string(),
              environment: z.string(),
              id: z.string(),
              path: z.string()
            })
            .array()
            .optional(),
          totalFolderCount: z.number().optional(),
          totalDynamicSecretCount: z.number().optional(),
          totalSecretCount: z.number().optional(),
          totalImportCount: z.number().optional(),
          totalSecretRotationCount: z.number().optional(),
          totalHoneyTokenCount: z.number().optional(),
          totalProxiedServiceCount: z.number().optional(),
          totalCount: z.number()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const {
        secretPath,
        projectId,
        limit,
        offset,
        search,
        orderBy,
        orderDirection,
        sortEnvironment,
        includeFolders,
        includeSecrets,
        includeImports,
        includeDynamicSecrets,
        includeSecretRotations,
        includeHoneyTokens,
        includeProxiedServices
      } = req.query;

      const environments = req.query.environments.split(",");
      const tagSlugs = req.query.tags?.split(",").filter(Boolean) ?? [];

      if (!projectId || environments.length === 0)
        throw new BadRequestError({ message: "Missing project id or environment(s)" });

      if (sortEnvironment && !environments.includes(sortEnvironment)) {
        throw new BadRequestError({
          message: `Sort environment '${sortEnvironment}' must be included in the requested environments`
        });
      }

      const isTimestampSort = orderBy === SecretSortField.CreatedAt || orderBy === SecretSortField.UpdatedAt;

      if (isTimestampSort && environments.length > 1 && !sortEnvironment) {
        throw new BadRequestError({
          message:
            "The 'sortEnvironment' query parameter is required for recency sorting when multiple environments are requested"
        });
      }

      const resourceOrderDirection = orderBy === SecretSortField.Name ? orderDirection : OrderByDirection.ASC;

      const { shouldUseSecretV2Bridge } = await server.services.projectBot.getBotKey(projectId);

      // prevent older projects from accessing endpoint
      if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });

      let remainingLimit = limit;
      let adjustedOffset = offset;

      let imports: Awaited<ReturnType<typeof server.services.secretImport.getImportsMultiEnv>> | undefined;
      let folders: Awaited<ReturnType<typeof server.services.folder.getFoldersMultiEnv>> | undefined;
      let secrets:
        | (Awaited<ReturnType<typeof server.services.secret.getSecretsRawMultiEnv>>[number] & {
            isEmpty: boolean;
            reminder: Awaited<ReturnType<typeof server.services.reminder.getRemindersForDashboard>>[string] | null;
          })[]
        | undefined;
      let dynamicSecrets:
        | Awaited<ReturnType<typeof server.services.dynamicSecret.listDynamicSecretsByEnvs>>
        | undefined;
      let secretRotations:
        | Awaited<ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>>
        | undefined;
      let honeyTokens: Awaited<ReturnType<typeof server.services.honeyToken.getDashboardHoneyTokens>> | undefined;
      let proxiedServices:
        | Awaited<ReturnType<typeof server.services.proxiedService.getDashboardProxiedServices>>
        | undefined;

      let totalFolderCount: number | undefined;
      let totalDynamicSecretCount: number | undefined;
      let totalSecretCount: number | undefined;
      let totalImportCount: number | undefined;
      let totalSecretRotationCount: number | undefined;
      let totalHoneyTokenCount: number | undefined;
      let totalProxiedServiceCount: number | undefined;

      if (includeImports) {
        totalImportCount = await server.services.secretImport.getProjectImportMultiEnvCount({
          actorId: req.permission.id,
          actor: req.permission.type,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          projectId,
          environments,
          path: secretPath
          // search: removing because this prevents searching imported secrets which are fetched separately client side
        });

        if (remainingLimit > 0 && totalImportCount > adjustedOffset) {
          imports = await server.services.secretImport.getImportsMultiEnv({
            actorId: req.permission.id,
            actor: req.permission.type,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            environments,
            path: secretPath,
            // search: removing because this prevents searching imported secrets which are fetched separately client side
            limit: remainingLimit,
            offset: adjustedOffset
          });

          await server.services.auditLog.createAuditLog({
            ...req.auditLogInfo,
            projectId: req.query.projectId,
            event: {
              type: EventType.GET_SECRET_IMPORTS,
              metadata: {
                environment: environments.join(","),
                folderId: imports?.[0]?.folderId,
                numberOfImports: imports.length
              }
            }
          });

          // get the count of unique folder names to properly adjust remaining limit
          const uniqueImportCount = new Set(
            imports.filter((imp) => !imp.isReserved).map((imp) => `${imp.importEnv.slug}:${imp.importPath}`)
          ).size;

          remainingLimit -= uniqueImportCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalImportCount);
        }
      }

      if (includeFolders) {
        // this is the unique count, ie duplicate folders across envs only count as 1
        totalFolderCount = await server.services.folder.getProjectFolderCount({
          actorId: req.permission.id,
          actor: req.permission.type,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          projectId: req.query.projectId,
          path: secretPath,
          environments,
          search
        });

        if (remainingLimit > 0 && totalFolderCount > adjustedOffset) {
          folders = await server.services.folder.getFoldersMultiEnv({
            actorId: req.permission.id,
            actor: req.permission.type,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            environments,
            path: secretPath,
            orderBy: SecretsOrderBy.Name,
            orderDirection: resourceOrderDirection,
            search,
            limit: remainingLimit,
            offset: adjustedOffset
          });

          // get the count of unique folder names to properly adjust remaining limit
          const uniqueFolderCount = new Set(folders.map((folder) => folder.name)).size;

          remainingLimit -= uniqueFolderCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalFolderCount);
        }
      }

      if (
        !includeDynamicSecrets &&
        !includeSecrets &&
        !includeSecretRotations &&
        !includeHoneyTokens &&
        !includeProxiedServices
      )
        return {
          imports,
          folders,
          totalImportCount,
          totalFolderCount,
          totalCount: (totalImportCount ?? 0) + (totalFolderCount ?? 0)
        };

      if (includeDynamicSecrets) {
        // this is the unique count, ie duplicate secrets across envs only count as 1
        totalDynamicSecretCount = await server.services.dynamicSecret.getCountMultiEnv({
          actor: req.permission.type,
          actorId: req.permission.id,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          projectId,
          search,
          environmentSlugs: environments,
          path: secretPath,
          isInternal: true
        });

        if (remainingLimit > 0 && totalDynamicSecretCount > adjustedOffset) {
          dynamicSecrets = await server.services.dynamicSecret.listDynamicSecretsByEnvs({
            actor: req.permission.type,
            actorId: req.permission.id,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            search,
            orderBy: SecretsOrderBy.Name,
            orderDirection: resourceOrderDirection,
            environmentSlugs: environments,
            path: secretPath,
            limit: remainingLimit,
            offset: adjustedOffset,
            isInternal: true
          });

          // get the count of unique dynamic secret names to properly adjust remaining limit
          const uniqueDynamicSecretsCount = new Set(dynamicSecrets.map((dynamicSecret) => dynamicSecret.name)).size;

          if (dynamicSecrets.length) {
            await server.services.auditLog.createAuditLog({
              ...req.auditLogInfo,
              projectId,
              event: {
                type: EventType.LIST_DYNAMIC_SECRETS,
                metadata: {
                  environment: [...new Set(dynamicSecrets.map((dynamicSecret) => dynamicSecret.environment))].join(","),
                  secretPath,
                  projectId
                }
              }
            });
          }

          remainingLimit -= uniqueDynamicSecretsCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalDynamicSecretCount);
        }
      }

      if (includeSecretRotations) {
        totalSecretRotationCount = await server.services.secretRotationV2.getDashboardSecretRotationCount(
          {
            projectId,
            search,
            environments,
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalSecretRotationCount > adjustedOffset) {
          secretRotations = await server.services.secretRotationV2.getDashboardSecretRotations(
            {
              projectId,
              search,
              orderBy: SecretsOrderBy.Name,
              orderDirection: resourceOrderDirection,
              environments,
              secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            },
            req.permission
          );

          await server.services.auditLog.createAuditLog({
            projectId,
            ...req.auditLogInfo,
            event: {
              type: EventType.GET_SECRET_ROTATIONS,
              metadata: {
                count: secretRotations.length,
                rotationIds: secretRotations.map((rotation) => rotation.id),
                secretPath,
                environment: environments.join(",")
              }
            }
          });

          // get the count of unique secret rotation names to properly adjust remaining limit
          const uniqueSecretRotationCount = new Set(secretRotations.map((rotation) => rotation.name)).size;

          remainingLimit -= uniqueSecretRotationCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalSecretRotationCount);
        }
      }

      if (includeHoneyTokens) {
        totalHoneyTokenCount = await server.services.honeyToken.getDashboardHoneyTokenCount(
          {
            projectId,
            search,
            environments,
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalHoneyTokenCount > adjustedOffset) {
          honeyTokens = await server.services.honeyToken.getDashboardHoneyTokens(
            {
              projectId,
              search,
              orderBy: SecretsOrderBy.Name,
              orderDirection: resourceOrderDirection,
              environments,
              secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            },
            req.permission
          );

          const uniqueHoneyTokenCount = new Set(honeyTokens.map((ht) => ht.name)).size;

          remainingLimit -= uniqueHoneyTokenCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalHoneyTokenCount);
        }
      }

      if (includeProxiedServices) {
        totalProxiedServiceCount = await server.services.proxiedService.getDashboardProxiedServiceCount(
          {
            projectId,
            search,
            environments,
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalProxiedServiceCount > adjustedOffset) {
          proxiedServices = await server.services.proxiedService.getDashboardProxiedServices(
            {
              projectId,
              search,
              orderBy: SecretsOrderBy.Name,
              orderDirection: resourceOrderDirection,
              environments,
              secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            },
            req.permission
          );

          // multi-env: the same service name across envs is one overview row, so decrement by unique names
          const uniqueProxiedServiceCount = new Set(proxiedServices.map((svc) => svc.name)).size;

          remainingLimit -= uniqueProxiedServiceCount;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalProxiedServiceCount);
        }
      }

      if (includeSecrets) {
        // this is the unique count, ie duplicate secrets across envs only count as 1
        totalSecretCount = await server.services.secret.getSecretsCountMultiEnv({
          actorId: req.permission.id,
          actor: req.permission.type,
          actorOrgId: req.permission.orgId,
          environments,
          actorAuthMethod: req.permission.authMethod,
          projectId,
          path: secretPath,
          search,
          tagSlugs,
          isInternal: true
        });

        if (remainingLimit > 0 && totalSecretCount > adjustedOffset) {
          const rawSecrets = await server.services.secret.getSecretsRawMultiEnv({
            personalOverridesBehavior: PersonalOverridesBehavior.IncludeAll,
            secretImportReferencesBehavior: SecretImportReferencesBehavior.SourceEnvironment,
            viewSecretValue: true,
            actorId: req.permission.id,
            actor: req.permission.type,
            actorOrgId: req.permission.orgId,
            environments,
            actorAuthMethod: req.permission.authMethod,
            projectId,
            path: secretPath,
            orderBy,
            orderDirection,
            sortEnvironment,
            search,
            tagSlugs,
            limit: remainingLimit,
            offset: adjustedOffset,
            isInternal: true
          });

          const reminders =
            rawSecrets.length > 0
              ? await server.services.reminder.getRemindersForDashboard(rawSecrets.map((s) => s.id))
              : {};

          const revokedGrantSecretIds = await server.services.secret.getSecretsWithRevokedProjectFolderGrant({
            targetProjectId: projectId,
            actorOrgId: req.permission.orgId,
            secrets: rawSecrets.map((s) => ({
              id: s.id,
              secretValue: s.secretValue,
              secretValueHidden: s.secretValueHidden
            }))
          });

          secrets = rawSecrets.map((secret) => ({
            ...secret,
            isEmpty: !secret.secretValue,
            reminder: reminders[secret.id] ?? null,
            revokedProjectFolderGrant: revokedGrantSecretIds.has(secret.id) ? true : undefined
          }));
        }
      }

      if (secrets?.length || secretRotations?.length) {
        for await (const environment of environments) {
          const secretIds = [
            ...new Set(
              [
                ...(secrets?.filter((secret) => secret.environment === environment) ?? []),
                ...(secretRotations
                  ?.filter((rotation) => rotation.environment.slug === environment)
                  .flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))) ?? [])
              ].map((secret) => secret.id)
            )
          ];

          if (secretIds) {
            await server.services.auditLog.createAuditLog({
              projectId,
              ...req.auditLogInfo,
              event: {
                type: EventType.DASHBOARD_LIST_SECRETS,
                metadata: {
                  environment,
                  secretPath,
                  numberOfSecrets: secretIds.length,
                  secretIds
                }
              }
            });

            if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
              await server.services.telemetry.sendPostHogEvents({
                event: PostHogEventTypes.SecretPulled,
                distinctId: getTelemetryDistinctId(req),
                organizationId: req.permission.orgId,
                properties: {
                  numberOfSecrets: secretIds.length,
                  projectId,
                  environment,
                  secretPath,
                  channel: getUserAgentType(req.headers["user-agent"]),
                  ...req.auditLogInfo
                }
              });
            }
          }
        }
      }

      const importedByEnvs = [];

      for await (const environment of environments) {
        const importedBy = await server.services.secretImport.getFolderIsImportedBy({
          path: secretPath,
          environment,
          projectId,
          actor: req.permission.type,
          actorId: req.permission.id,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          secrets: secrets?.filter((s) => s.environment === environment)
        });

        if (importedBy) {
          importedByEnvs.push({
            environment,
            importedBy
          });
        }
      }

      const usedBySecretSyncs: { name: string; destination: string; environment: string; id: string; path: string }[] =
        [];
      for await (const environment of environments) {
        const secretSyncs = await server.services.secretSync.listSecretSyncsBySecretPath(
          { projectId, secretPath, environment },
          req.permission
        );
        secretSyncs.forEach((sync) => {
          usedBySecretSyncs.push({
            name: sync.name,
            destination: sync.destination,
            environment,
            id: sync.id,
            path: sync.folder?.path || "/"
          });
        });
      }

      return {
        folders,
        dynamicSecrets,
        secrets,
        imports,
        secretRotations,
        honeyTokens,
        proxiedServices,
        totalFolderCount,
        totalDynamicSecretCount,
        totalImportCount,
        totalSecretCount,
        totalSecretRotationCount,
        totalHoneyTokenCount,
        totalProxiedServiceCount,
        importedByEnvs,
        usedBySecretSyncs,
        totalCount:
          (totalImportCount ?? 0) +
          (totalFolderCount ?? 0) +
          (totalDynamicSecretCount ?? 0) +
          (totalSecretCount ?? 0) +
          (totalSecretRotationCount ?? 0) +
          (totalHoneyTokenCount ?? 0) +
          (totalProxiedServiceCount ?? 0)
      };
    }
  });

  server.route({
    method: "GET",
    url: "/secrets-details",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "listProjectSecretsDetails",
      description: "List project secrets details",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim().describe(DASHBOARD.SECRET_DETAILS_LIST.projectId),
        environment: z.string().trim().describe(DASHBOARD.SECRET_DETAILS_LIST.environment),
        secretPath: z
          .string()
          .trim()
          .default("/")
          .transform(removeTrailingSlash)
          .describe(DASHBOARD.SECRET_DETAILS_LIST.secretPath),
        offset: z.coerce.number().min(0).optional().default(0).describe(DASHBOARD.SECRET_DETAILS_LIST.offset),
        limit: z.coerce.number().min(1).max(100).optional().default(100).describe(DASHBOARD.SECRET_DETAILS_LIST.limit),
        orderBy: z
          .nativeEnum(SecretsOrderBy)
          .default(SecretsOrderBy.Name)
          .describe(DASHBOARD.SECRET_DETAILS_LIST.orderBy)
          .optional(),
        orderDirection: z
          .nativeEnum(OrderByDirection)
          .default(OrderByDirection.ASC)
          .describe(DASHBOARD.SECRET_DETAILS_LIST.orderDirection)
          .optional(),
        search: z.string().trim().describe(DASHBOARD.SECRET_DETAILS_LIST.search).optional(),
        tags: z.string().trim().transform(decodeURIComponent).describe(DASHBOARD.SECRET_DETAILS_LIST.tags).optional(),
        includeSecrets: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeSecrets),
        includeFolders: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeFolders),
        includeDynamicSecrets: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeDynamicSecrets),
        includeImports: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeImports),
        includeSecretRotations: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeSecretRotations),
        includeHoneyTokens: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeHoneyTokens),
        includeProxiedServices: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeProxiedServices)
      }),
      response: {
        200: z.object({
          imports: SecretImportsSchema.omit({ importEnv: true })
            .extend({
              importEnv: z.object({
                name: z.string(),
                slug: z.string(),
                id: z.string(),
                projectId: z.string().optional()
              }),
              sourceProjectName: z.string().optional(),
              isAccessRevoked: z.boolean()
            })
            .array()
            .optional(),
          folders: SecretFoldersSchema.array().optional(),
          dynamicSecrets: SanitizedDynamicSecretSchema.array().optional(),
          honeyTokens: SanitizedHoneyTokenSchema.array().optional(),
          proxiedServices: SanitizedProxiedServiceSchema.array().optional(),
          secretRotations: z
            .intersection(
              SecretRotationV2Schema,
              z.object({
                secrets: secretRawSchema
                  .omit({ secretValue: true })
                  .extend({
                    isEmpty: z.boolean(),
                    secretValueHidden: z.boolean(),
                    secretPath: z.string().optional(),
                    secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
                    tags: SanitizedTagSchema.array().optional(),
                    reminder: RemindersSchema.extend({
                      recipients: z.string().array()
                    }).nullable()
                  })
                  .nullable()
                  .array()
              })
            )
            .array()
            .optional(),
          secrets: secretRawSchema
            .omit({ secretValue: true })
            .extend({
              isHoneyTokenSecret: z.boolean().optional(),
              isEmpty: z.boolean(),
              secretValueHidden: z.boolean(),
              secretPath: z.string().optional(),
              secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
              tags: SanitizedTagSchema.array().optional(),
              reminder: RemindersSchema.extend({
                recipients: z.string().array().optional()
              }).nullish()
            })
            .array()
            .optional(),
          totalImportCount: z.number().optional(),
          totalFolderCount: z.number().optional(),
          totalDynamicSecretCount: z.number().optional(),
          totalSecretCount: z.number().optional(),
          usedBySecretSyncs: z
            .object({
              name: z.string(),
              destination: z.string(),
              environment: z.string(),
              id: z.string(),
              path: z.string()
            })
            .array()
            .optional(),
          importedBy: z
            .object({
              environment: z.object({
                name: z.string(),
                slug: z.string()
              }),
              project: z
                .object({
                  name: z.string(),
                  slug: z.string(),
                  id: z.string()
                })
                .optional(),
              folders: z
                .object({
                  name: z.string(),
                  isImported: z.boolean(),
                  secrets: z
                    .object({
                      secretId: z.string(),
                      referencedSecretKey: z.string(),
                      referencedSecretEnv: z.string()
                    })
                    .array()
                    .optional()
                })
                .array()
            })
            .array()
            .optional(),
          totalSecretRotationCount: z.number().optional(),
          totalHoneyTokenCount: z.number().optional(),
          totalProxiedServiceCount: z.number().optional(),
          totalCount: z.number()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const {
        secretPath,
        environment,
        projectId,
        limit,
        offset,
        search,
        orderBy,
        orderDirection,
        includeFolders,
        includeSecrets,
        includeDynamicSecrets,
        includeImports,
        includeSecretRotations,
        includeHoneyTokens,
        includeProxiedServices
      } = req.query;

      if (!projectId || !environment) throw new BadRequestError({ message: "Missing project id or environment" });

      const { shouldUseSecretV2Bridge } = await server.services.projectBot.getBotKey(projectId);

      // prevent older projects from accessing endpoint
      if (!shouldUseSecretV2Bridge) throw new BadRequestError({ message: "Project version not supported" });

      // verify folder exists and user has project permission
      await server.services.folder.getFolderByPath({ projectId, environment, secretPath }, req.permission);

      const tags = req.query.tags?.split(",") ?? [];

      let remainingLimit = limit;
      let adjustedOffset = offset;

      let imports: Awaited<ReturnType<typeof server.services.secretImport.getImports>> | undefined;
      let folders: Awaited<ReturnType<typeof server.services.folder.getFolders>> | undefined;
      let secrets:
        | (Awaited<ReturnType<typeof server.services.secret.getSecretsRaw>>["secrets"][number] & {
            isEmpty: boolean;
            reminder: Awaited<ReturnType<typeof server.services.reminder.getRemindersForDashboard>>[string] | null;
          })[]
        | undefined;
      let dynamicSecrets:
        | Awaited<ReturnType<typeof server.services.dynamicSecret.listDynamicSecretsByEnv>>["dynamicSecrets"]
        | undefined;
      let secretRotations:
        | (Awaited<ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>>[number] & {
            secrets: (NonNullable<
              Awaited<
                ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>
              >[number]["secrets"][number] & {
                isEmpty: boolean;
                reminder: Awaited<ReturnType<typeof server.services.reminder.getRemindersForDashboard>>[string] | null;
              }
            > | null)[];
          })[]
        | undefined;
      let honeyTokens: Awaited<ReturnType<typeof server.services.honeyToken.getDashboardHoneyTokens>> | undefined;
      let proxiedServices:
        | Awaited<ReturnType<typeof server.services.proxiedService.getDashboardProxiedServices>>
        | undefined;

      let totalImportCount: number | undefined;
      let totalFolderCount: number | undefined;
      let totalDynamicSecretCount: number | undefined;
      let totalSecretCount: number | undefined;
      let totalSecretRotationCount: number | undefined;
      let totalHoneyTokenCount: number | undefined;
      let totalProxiedServiceCount: number | undefined;

      if (includeImports) {
        totalImportCount = await server.services.secretImport.getProjectImportCount({
          actorId: req.permission.id,
          actor: req.permission.type,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          projectId,
          environment,
          path: secretPath
          // search scott: removing for now because this prevents searching imported secrets which are fetched separately client side
        });

        if (remainingLimit > 0 && totalImportCount > adjustedOffset) {
          imports = await server.services.secretImport.getImports({
            actorId: req.permission.id,
            actor: req.permission.type,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            environment,
            path: secretPath,
            // search scott: removing for now because this prevents searching imported secrets which are fetched separately client side
            limit: remainingLimit,
            offset: adjustedOffset
          });

          await server.services.auditLog.createAuditLog({
            ...req.auditLogInfo,
            projectId: req.query.projectId,
            event: {
              type: EventType.GET_SECRET_IMPORTS,
              metadata: {
                environment,
                folderId: imports?.[0]?.folderId,
                numberOfImports: imports.length
              }
            }
          });

          remainingLimit -= imports.length;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalImportCount);
        }
      }

      if (includeFolders) {
        totalFolderCount = await server.services.folder.getProjectFolderCount({
          actorId: req.permission.id,
          actor: req.permission.type,
          actorAuthMethod: req.permission.authMethod,
          actorOrgId: req.permission.orgId,
          projectId,
          path: secretPath,
          environments: [environment],
          search
        });

        if (remainingLimit > 0 && totalFolderCount > adjustedOffset) {
          folders = await server.services.folder.getFolders({
            actorId: req.permission.id,
            actor: req.permission.type,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            environment,
            path: secretPath,
            orderBy,
            orderDirection,
            search,
            limit: remainingLimit,
            offset: adjustedOffset
          });

          remainingLimit -= folders.length;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalFolderCount);
        }
      }

      if (includeSecretRotations) {
        totalSecretRotationCount = await server.services.secretRotationV2.getDashboardSecretRotationCount(
          {
            projectId,
            search,
            environments: [environment],
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalSecretRotationCount > adjustedOffset) {
          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,
                    reminder: rotationReminders[secret.id] ?? null
                  }
                : secret
            )
          }));

          await server.services.auditLog.createAuditLog({
            projectId,
            ...req.auditLogInfo,
            event: {
              type: EventType.GET_SECRET_ROTATIONS,
              metadata: {
                count: secretRotations.length,
                rotationIds: secretRotations.map((rotation) => rotation.id),
                secretPath,
                environment
              }
            }
          });

          remainingLimit -= secretRotations.length;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalSecretRotationCount);
        }
      }

      if (includeHoneyTokens) {
        totalHoneyTokenCount = await server.services.honeyToken.getDashboardHoneyTokenCount(
          {
            projectId,
            search,
            environments: [environment],
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalHoneyTokenCount > adjustedOffset) {
          honeyTokens = await server.services.honeyToken.getDashboardHoneyTokens(
            {
              projectId,
              search,
              orderBy,
              orderDirection,
              environments: [environment],
              secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            },
            req.permission
          );

          remainingLimit -= honeyTokens.length;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalHoneyTokenCount);
        }
      }

      if (includeProxiedServices) {
        totalProxiedServiceCount = await server.services.proxiedService.getDashboardProxiedServiceCount(
          {
            projectId,
            search,
            environments: [environment],
            secretPath
          },
          req.permission
        );

        if (remainingLimit > 0 && totalProxiedServiceCount > adjustedOffset) {
          proxiedServices = await server.services.proxiedService.getDashboardProxiedServices(
            {
              projectId,
              search,
              orderBy,
              orderDirection,
              environments: [environment],
              secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            },
            req.permission
          );

          remainingLimit -= proxiedServices.length;
          adjustedOffset = 0;
        } else {
          adjustedOffset = Math.max(0, adjustedOffset - totalProxiedServiceCount);
        }
      }

      try {
        if (includeDynamicSecrets) {
          totalDynamicSecretCount = await server.services.dynamicSecret.getDynamicSecretCount({
            actor: req.permission.type,
            actorId: req.permission.id,
            actorAuthMethod: req.permission.authMethod,
            actorOrgId: req.permission.orgId,
            projectId,
            search,
            environmentSlug: environment,
            path: secretPath
          });

          if (remainingLimit > 0 && totalDynamicSecretCount > adjustedOffset) {
            const { dynamicSecrets: dynamicSecretCfgs } = await server.services.dynamicSecret.listDynamicSecretsByEnv({
              actor: req.permission.type,
              actorId: req.permission.id,
              actorAuthMethod: req.permission.authMethod,
              actorOrgId: req.permission.orgId,
              projectId,
              search,
              orderBy,
              orderDirection,
              environmentSlug: environment,
              path: secretPath,
              limit: remainingLimit,
              offset: adjustedOffset
            });

            if (dynamicSecretCfgs.length) {
              await server.services.auditLog.createAuditLog({
                ...req.auditLogInfo,
                projectId,
                event: {
                  type: EventType.LIST_DYNAMIC_SECRETS,
                  metadata: {
                    environment,
                    secretPath,
                    projectId
                  }
                }
              });
            }

            dynamicSecrets = dynamicSecretCfgs;

            remainingLimit -= dynamicSecrets.length;
            adjustedOffset = 0;
          } else {
            adjustedOffset = Math.max(0, adjustedOffset - totalDynamicSecretCount);
          }
        }
      } catch (error) {
        if (!(error instanceof ForbiddenError)) {
          throw error;
        }
      }

      try {
        if (includeSecrets) {
          totalSecretCount = await server.services.secret.getSecretsCount({
            actorId: req.permission.id,
            actor: req.permission.type,
            actorOrgId: req.permission.orgId,
            environment,
            actorAuthMethod: req.permission.authMethod,
            projectId,
            path: secretPath,
            search,
            tagSlugs: tags,
            includeTagsInSearch: true,
            includeMetadataInSearch: true,
            excludeRotatedSecrets: includeSecretRotations
          });

          if (remainingLimit > 0 && totalSecretCount > adjustedOffset) {
            const rawSecrets = (
              await server.services.secret.getSecretsRaw({
                personalOverridesBehavior: PersonalOverridesBehavior.IncludeAll,
                secretImportReferencesBehavior: SecretImportReferencesBehavior.SourceEnvironment,
                actorId: req.permission.id,
                actor: req.permission.type,
                viewSecretValue: true,
                throwOnMissingReadValuePermission: false,
                actorOrgId: req.permission.orgId,
                environment,
                actorAuthMethod: req.permission.authMethod,
                projectId,
                path: secretPath,
                orderBy,
                orderDirection,
                search,
                limit: remainingLimit,
                offset: adjustedOffset,
                tagSlugs: tags,
                includeTagsInSearch: true,
                includeMetadataInSearch: true,
                excludeRotatedSecrets: includeSecretRotations
              })
            ).secrets;

            const reminders = await server.services.reminder.getRemindersForDashboard(
              rawSecrets.map((secret) => secret.id)
            );

            secrets = rawSecrets.map((secret) => ({
              ...secret,
              isEmpty: !secret.secretValue,
              reminder: reminders[secret.id] ?? null
            }));
          }
        }
      } catch (error) {
        if (!(error instanceof ForbiddenError)) {
          throw error;
        }
      }

      const importedBy = await server.services.secretImport.getFolderIsImportedBy({
        path: secretPath,
        environment,
        projectId,
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        secrets
      });

      const secretSyncs = await server.services.secretSync.listSecretSyncsBySecretPath(
        { projectId, secretPath, environment },
        req.permission
      );
      const usedBySecretSyncs = secretSyncs.map((sync) => ({
        name: sync.name,
        destination: sync.destination,
        environment: sync.environment?.name || environment,
        id: sync.id,
        path: sync.folder?.path || "/"
      }));

      if (secrets?.length || secretRotations?.length) {
        const secretIds = [
          ...new Set(
            [
              ...(secrets ?? []),
              ...(secretRotations?.flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))) ?? [])
            ].map((secret) => secret.id)
          )
        ];

        await server.services.auditLog.createAuditLog({
          projectId,
          ...req.auditLogInfo,
          event: {
            type: EventType.DASHBOARD_LIST_SECRETS,
            metadata: {
              environment,
              secretPath,
              numberOfSecrets: secretIds.length,
              secretIds
            }
          }
        });

        if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
          await server.services.telemetry.sendPostHogEvents({
            event: PostHogEventTypes.SecretPulled,
            distinctId: getTelemetryDistinctId(req),
            organizationId: req.permission.orgId,
            properties: {
              numberOfSecrets: secretIds.length,
              projectId,
              environment,
              secretPath,
              channel: getUserAgentType(req.headers["user-agent"]),
              ...req.auditLogInfo
            }
          });
        }
      }

      return {
        imports,
        folders,
        dynamicSecrets,
        secrets,
        secretRotations,
        honeyTokens,
        proxiedServices,
        totalImportCount,
        totalFolderCount,
        totalDynamicSecretCount,
        totalSecretCount,
        totalSecretRotationCount,
        totalHoneyTokenCount,
        totalProxiedServiceCount,
        importedBy,
        usedBySecretSyncs,
        totalCount:
          (totalImportCount ?? 0) +
          (totalFolderCount ?? 0) +
          (totalDynamicSecretCount ?? 0) +
          (totalSecretCount ?? 0) +
          (totalSecretRotationCount ?? 0) +
          (totalHoneyTokenCount ?? 0) +
          (totalProxiedServiceCount ?? 0)
      };
    }
  });

  server.route({
    method: "GET",
    url: "/secrets-deep-search",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "deepSearchSecrets",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim(),
        environments: z.string().trim().transform(decodeURIComponent),
        secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
        search: z.string().trim().optional(),
        tags: z.string().trim().transform(decodeURIComponent).optional(),
        limit: z.coerce
          .number({ invalid_type_error: "Limit must be a number" })
          .int({ message: "Limit must be a whole number" })
          .min(1, { message: "Limit must be at least 1" })
          .max(DEEP_SEARCH_MAX_PAGE_LIMIT, {
            message: `Limit cannot be greater than ${DEEP_SEARCH_MAX_PAGE_LIMIT}`
          })
          .default(DEEP_SEARCH_DEFAULT_PAGE_LIMIT)
          .describe(DASHBOARD.SECRET_DEEP_SEARCH.limit),
        offset: z.coerce
          .number({ invalid_type_error: "Offset must be a number" })
          .int({ message: "Offset must be a whole number" })
          .min(0, { message: "Offset cannot be negative" })
          .max(MAX_DEEP_SEARCH_LIMIT, {
            message: `Offset cannot be greater than ${MAX_DEEP_SEARCH_LIMIT}. Narrow your search to reach more results`
          })
          .default(0)
          .describe(DASHBOARD.SECRET_DEEP_SEARCH.offset)
      }),
      response: {
        200: z.object({
          folders: SecretFoldersSchema.extend({ path: z.string() }).array().optional(),
          dynamicSecrets: SanitizedDynamicSecretSchema.extend({ path: z.string(), environment: z.string() })
            .array()
            .optional(),
          secrets: secretRawSchema
            .omit({ secretValue: true })
            .extend({
              isHoneyTokenSecret: z.boolean().optional(),
              secretValueHidden: z.boolean(),
              secretPath: z.string().optional(),
              secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
              tags: SanitizedTagSchema.array().optional()
            })
            .array()
            .optional(),
          secretRotations: SecretRotationV2Schema.array().optional(),
          totalFolderCount: z.number(),
          totalDynamicSecretCount: z.number(),
          totalSecretCount: z.number(),
          totalSecretRotationCount: z.number(),
          totalCount: z.number(),
          searchLimit: z.number(),
          isSearchLimitReached: z.boolean()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const { secretPath, projectId, search, limit, offset } = req.query;

      const environments = req.query.environments.split(",").filter((env) => Boolean(env.trim()));
      if (!environments.length) throw new BadRequestError({ message: "One or more environments required" });

      const tags = req.query.tags?.split(",").filter((tag) => Boolean(tag.trim())) ?? [];
      if (!search && !tags.length) throw new BadRequestError({ message: "Search or tags required" });

      const allFolders = await server.services.folder.getFoldersDeepByEnvs(
        {
          projectId,
          environments,
          secretPath
        },
        req.permission
      );

      const { searchName, searchPath } = resolveSecretDeepSearch(
        search,
        allFolders.map((folder) => folder.path)
      );

      const folderMappings = allFolders.map((folder) => ({
        folderId: folder.id,
        path: folder.path,
        environment: folder.environment
      }));

      const sharedFilters = {
        search: searchName,
        limit: MAX_DEEP_SEARCH_LIMIT,
        orderBy: SecretsOrderBy.Name
      };

      const { secrets, isLimitReached: isSecretLimitReached } =
        await server.services.secret.getSecretsRawByFolderMappings(
          {
            filterByAction: ProjectPermissionSecretActions.DescribeSecret,
            projectId,
            folderMappings,
            filters: {
              ...sharedFilters,
              tagSlugs: tags,
              includeTagsInSearch: true,
              includeMetadataInSearch: true
            }
          },
          req.permission
        );

      const { dynamicSecrets, isLimitReached: isDynamicSecretLimitReached } =
        await server.services.dynamicSecret.listDynamicSecretsByFolderIds(
          {
            projectId,
            folderMappings,
            filters: sharedFilters
          },
          req.permission
        );

      const { secretRotations, isLimitReached: isSecretRotationLimitReached } =
        await server.services.secretRotationV2.getQuickSearchSecretRotations(
          {
            projectId,
            folderMappings,
            filters: sharedFilters
          },
          req.permission
        );

      for await (const environment of environments) {
        const envSecrets = secrets.filter((secret) => secret.environment === environment);
        const secretCountForEnv = envSecrets.length;

        if (secretCountForEnv) {
          await server.services.auditLog.createAuditLog({
            projectId,
            ...req.auditLogInfo,
            event: {
              type: EventType.DASHBOARD_LIST_SECRETS,
              metadata: {
                environment,
                secretPath,
                numberOfSecrets: secretCountForEnv,
                secretIds: envSecrets.map((secret) => secret.id)
              }
            }
          });

          if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
            await server.services.telemetry.sendPostHogEvents({
              event: PostHogEventTypes.SecretPulled,
              distinctId: getTelemetryDistinctId(req),
              organizationId: req.permission.orgId,
              properties: {
                numberOfSecrets: secretCountForEnv,
                projectId,
                environment,
                secretPath,
                channel: getUserAgentType(req.headers["user-agent"]),
                ...req.auditLogInfo
              }
            });
          }
        }

        const secretRotationsFromEnv = secretRotations.filter((rotation) => rotation.environment.slug === environment);

        if (secretRotationsFromEnv.length) {
          await server.services.auditLog.createAuditLog({
            projectId,
            ...req.auditLogInfo,
            event: {
              type: EventType.GET_SECRET_ROTATIONS,
              metadata: {
                count: secretRotationsFromEnv.length,
                rotationIds: secretRotationsFromEnv.map((rotation) => rotation.id),
                secretPath,
                environment
              }
            }
          });
        }
      }

      const matchedSecrets = searchPath
        ? secrets.filter((secret) => isInSecretSearchScope(secret.secretPath, searchPath, secretPath))
        : secrets;

      // page secrets by rendered entry (env + path + key): a shared secret and its personal override
      // are two adjacent rows the client merges into one, so slicing raw rows would split the pair
      // across a page boundary and over-count what actually renders
      const secretUnitsByEntry = new Map<string, typeof matchedSecrets>();
      for (const secret of matchedSecrets) {
        const entryKey = `${secret.environment}\0${secret.secretPath}\0${secret.secretKey}`;
        const unit = secretUnitsByEntry.get(entryKey);
        if (unit) {
          unit.push(secret);
        } else {
          secretUnitsByEntry.set(entryKey, [secret]);
        }
      }
      const secretUnits = [...secretUnitsByEntry.values()];

      const matchedDynamicSecrets = searchPath
        ? dynamicSecrets.filter((dynamicSecret) => isInSecretSearchScope(dynamicSecret.path, searchPath, secretPath))
        : dynamicSecrets;

      const matchedSecretRotations = searchPath
        ? secretRotations.filter((rotation) => isInSecretSearchScope(rotation.folder.path, searchPath, secretPath))
        : secretRotations;

      const matchedFolders = allFolders.filter((folder) => {
        const [folderName, ...folderPathSegments] = folder.path.split("/").reverse();
        const folderPath = folderPathSegments.reverse().join("/").toLowerCase() || "/";

        if (searchPath) {
          if (searchPath === "/") {
            // only show root folders if no folder name search
            if (!searchName) return isInSecretSearchScope(folderPath, searchPath, secretPath);

            // start partial match on root folders
            return folderName.toLowerCase().startsWith(searchName.toLowerCase());
          }

          // support ending partial path match
          return (
            isInSecretSearchScope(folderPath, searchPath, secretPath) &&
            folderName.toLowerCase().startsWith(searchName.toLowerCase())
          );
        }

        // no search path, "fuzzy" match all folders
        return folderName.toLowerCase().includes(searchName.toLowerCase());
      });

      const paginate = <T>(array: T[]) => array.slice(offset, offset + limit);

      const paginatedDynamicSecrets = paginate(matchedDynamicSecrets);

      if (paginatedDynamicSecrets.length) {
        await server.services.auditLog.createAuditLog({
          projectId,
          ...req.auditLogInfo,
          event: {
            type: EventType.LIST_DYNAMIC_SECRETS,
            metadata: {
              environment: [...new Set(paginatedDynamicSecrets.map((dynamicSecret) => dynamicSecret.environment))].join(
                ","
              ),
              secretPath: [...new Set(paginatedDynamicSecrets.map((dynamicSecret) => dynamicSecret.path))].join(","),
              projectId
            }
          }
        });
      }

      return {
        secrets: paginate(secretUnits).flat(),
        dynamicSecrets: paginatedDynamicSecrets,
        secretRotations: paginate(matchedSecretRotations),
        folders: paginate(matchedFolders),
        totalFolderCount: matchedFolders.length,
        totalDynamicSecretCount: matchedDynamicSecrets.length,
        totalSecretCount: secretUnits.length,
        totalSecretRotationCount: matchedSecretRotations.length,
        totalCount:
          matchedFolders.length + matchedDynamicSecrets.length + secretUnits.length + matchedSecretRotations.length,
        searchLimit: MAX_DEEP_SEARCH_LIMIT,
        // counts only cover what the search window scanned, so flag when it filled up
        isSearchLimitReached: isSecretLimitReached || isDynamicSecretLimitReached || isSecretRotationLimitReached
      };
    }
  });

  server.route({
    method: "GET",
    url: "/secrets-by-keys",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "getSecretsByKeys",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim(),
        environment: z.string().trim(),
        secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
        keys: z.string().trim().transform(decodeURIComponent),
        viewSecretValue: booleanSchema.default(false),
        // returns unreadable values masked instead of refusing the whole request, so one shared value
        // the user cannot read does not stop the overview from loading the rest in bulk
        hideUnreadableValues: booleanSchema.default(false)
      }),
      response: {
        200: z.object({
          // TODO(scott): omit secretValue here, but requires refactor of uploading env/copy from board
          secrets: secretRawSchema
            .extend({
              secretValueHidden: z.boolean(),
              secretPath: z.string().optional(),
              secretMetadata: ResourceMetadataWithEncryptionSchema.optional(),
              tags: SanitizedTagSchema.array().optional()
            })
            .array()
            .optional()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const { secretPath, projectId, environment, viewSecretValue, hideUnreadableValues } = req.query;

      const keys = req.query.keys?.split(",").filter((key) => Boolean(key.trim())) ?? [];
      if (!keys.length) throw new BadRequestError({ message: "One or more keys required" });

      const { secrets } = await server.services.secret.getSecretsRaw({
        personalOverridesBehavior: PersonalOverridesBehavior.IncludeAll,
        secretImportReferencesBehavior: SecretImportReferencesBehavior.SourceEnvironment,
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        viewSecretValue,
        throwOnMissingReadValuePermission: !hideUnreadableValues,
        environment,
        actorAuthMethod: req.permission.authMethod,
        projectId,
        path: secretPath,
        keys
      });

      if (viewSecretValue) {
        void server.services.secretReadActivity.recordRead({
          actor: req.permission.type,
          actorId: req.permission.id,
          projectId,
          secretIds: secrets.filter((secret) => !secret.secretValueHidden).map((secret) => secret.id),
          referencesExpanded: false
        });
      }

      await server.services.auditLog.createAuditLog({
        projectId,
        ...req.auditLogInfo,
        event: {
          type: EventType.DASHBOARD_LIST_SECRETS,
          metadata: {
            environment,
            secretPath,
            numberOfSecrets: secrets.length,
            secretIds: secrets.map((secret) => secret.id)
          }
        }
      });

      // Reveal All and copying selected secrets read values here instead of /secret-value, so each
      // returned value is logged the same way to keep "who read this secret" queryable
      if (viewSecretValue) {
        await Promise.all(
          secrets
            .filter((secret) => !secret.secretValueHidden)
            .map((secret) =>
              server.services.auditLog.createAuditLog({
                projectId,
                ...req.auditLogInfo,
                event: {
                  type: EventType.DASHBOARD_GET_SECRET_VALUE,
                  metadata: {
                    environment,
                    secretPath,
                    secretKey: secret.secretKey,
                    secretId: secret.id
                  }
                }
              })
            )
        );
      }

      if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
        await server.services.telemetry.sendPostHogEvents({
          event: PostHogEventTypes.SecretPulled,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            numberOfSecrets: secrets.length,
            projectId,
            environment,
            secretPath,
            channel: getUserAgentType(req.headers["user-agent"]),
            ...req.auditLogInfo,
            actorType: req.permission.type
          }
        });
      }

      return { secrets };
    }
  });

  server.route({
    method: "GET",
    url: "/secrets/key-exists",
    config: {
      rateLimit: readLimit
    },
    schema: {
      hide: true,
      operationId: "getSecretKeyExists",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim().min(1).max(64),
        environments: z
          .string()
          .trim()
          .max(4000)
          .transform(decodeURIComponent)
          .transform((value) => value.split(",").filter(Boolean))
          .pipe(slugSchema({ field: "Environment" }).array().min(1).max(100)),
        secretPath: z.string().trim().max(1000).default("/").transform(removeTrailingSlash),
        secretKey: z.string().trim().max(500).pipe(SecretNameSchema)
      }),
      response: {
        200: z.object({
          existingEnvironments: z.string().array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT]),
    handler: async (req) => {
      const { projectId, environments, secretPath, secretKey } = req.query;

      const existingEnvironments = await server.services.secret.getSecretKeyEnvironments({
        actorId: req.permission.id,
        actor: req.permission.type,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod,
        projectId,
        environments,
        path: secretPath,
        secretKey
      });

      return { existingEnvironments };
    }
  });

  server.route({
    method: "GET",
    url: "/secret-value",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "getSecretValue",
      security: [
        {
          bearerAuth: []
        }
      ],
      querystring: z.object({
        projectId: z.string().trim(),
        environment: z.string().trim(),
        secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
        secretKey: z.string().trim(),
        isOverride: z
          .enum(["true", "false"])
          .transform((value) => value === "true")
          .optional()
      }),
      response: {
        200: z.object({
          valueOverride: z.string().optional(),
          value: z.string().optional()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const { secretPath, projectId, environment, secretKey, isOverride } = req.query;

      const secret = await server.services.secret.getSecretByNameRaw({
        actorId: req.permission.id,
        actor: req.permission.type,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        viewSecretValue: true,
        environment,
        projectId,
        path: secretPath,
        secretName: secretKey,
        includeImports: true,
        type: isOverride ? SecretType.Personal : SecretType.Shared
      });

      if (isOverride) {
        return { valueOverride: secret.secretValue };
      }

      void server.services.secretReadActivity.recordRead({
        actor: req.permission.type,
        actorId: req.permission.id,
        projectId,
        secretIds: [secret.id],
        referencesExpanded: false
      });

      await server.services.auditLog.createAuditLog({
        projectId,
        ...req.auditLogInfo,
        event: {
          type: EventType.DASHBOARD_GET_SECRET_VALUE,
          metadata: {
            environment: req.query.environment,
            secretPath: req.query.secretPath,
            secretKey,
            secretId: secret.id
          }
        }
      });

      return { value: secret.secretValue };
    }
  });

  server.route({
    url: "/secret-imports",
    method: "GET",
    config: {
      rateLimit: secretsLimit
    },
    schema: {
      operationId: "getSecretImports",
      querystring: z.object({
        projectId: z.string().trim(),
        environment: z.string().trim(),
        path: z.string().trim().default("/").transform(removeTrailingSlash)
      }),
      response: {
        200: z.object({
          secrets: z
            .object({
              secretPath: z.string(),
              environment: z.string(),
              environmentInfo: z.object({
                id: z.string(),
                name: z.string(),
                slug: z.string()
              }),
              folderId: z.string().optional(),
              secrets: secretRawSchema
                .omit({ secretValue: true })
                .extend({ isEmpty: z.boolean(), isHoneyTokenSecret: z.boolean().optional() })
                .array()
            })
            .array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const importedSecrets = await server.services.secretImport.getRawSecretsFromImports({
        actorId: req.permission.id,
        actor: req.permission.type,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        ...req.query
      });

      await server.services.auditLog.createAuditLog({
        projectId: req.query.projectId,
        ...req.auditLogInfo,
        event: {
          type: EventType.DASHBOARD_LIST_SECRETS,
          metadata: {
            environment: req.query.environment,
            secretPath: req.query.path,
            numberOfSecrets: importedSecrets.length,
            secretIds: importedSecrets.map((secret) => secret.id)
          }
        }
      });

      return {
        secrets: importedSecrets.map((importData) => ({
          ...importData,
          secrets: importData.secrets.map((secret) => ({
            ...secret,
            isEmpty: !secret.secretValue
          }))
        }))
      };
    }
  });

  server.route({
    method: "GET",
    url: "/secret-versions/:secretId",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "listSecretVersions",
      params: z.object({
        secretId: z.string()
      }),
      querystring: z.object({
        offset: z.coerce.number(),
        limit: z.coerce.number().max(1000)
      }),
      response: {
        200: z.object({
          secretVersions: secretRawSchema
            .omit({ secretValue: true })
            .extend({
              isRedacted: z.boolean(),
              redactedByActor: z
                .object({
                  username: z.string().nullable(),
                  email: z.string().nullable().optional(),
                  projectMembershipId: z.string().uuid().nullable().optional()
                })
                .nullable()
                .optional(),
              redactedAt: z.date().nullable(),
              redactedByUserId: z.string().uuid().nullable(),
              secretValueHidden: z.boolean()
            })
            .array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const secretVersions = await server.services.secret.getSecretVersions({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        limit: req.query.limit,
        offset: req.query.offset,
        secretId: req.params.secretId
      });

      return { secretVersions };
    }
  });

  server.route({
    method: "GET",
    url: "/secret-versions/:secretId/value/:version",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "getSecretVersionValue",
      params: z.object({
        secretId: z.string(),
        version: z.string()
      }),

      response: {
        200: z.object({
          value: z.string()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) => {
      const { version, secretId } = req.params;

      const [secretVersion] = await server.services.secret.getSecretVersions({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        secretId,
        secretVersions: [version]
      });

      if (!secretVersion)
        throw new NotFoundError({
          message: `Could not find secret version "${version}" for secret with ID "${secretId}`
        });

      await server.services.auditLog.createAuditLog({
        projectId: secretVersion.workspace,
        ...req.auditLogInfo,
        event: {
          type: EventType.DASHBOARD_GET_SECRET_VERSION_VALUE,
          metadata: {
            secretId,
            version
          }
        }
      });

      return { value: secretVersion.secretValue };
    }
  });

  server.route({
    method: "GET",
    url: "/folder/move-check/:folderId",
    config: {
      rateLimit: readLimit
    },
    schema: {
      operationId: "checkFolderMoveCheck",
      description: "Check whether a folder and its subtree can be moved (only static secrets allowed)",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        folderId: z.string().trim().uuid()
      }),
      querystring: z.object({
        destinationEnvironment: z.string().trim().optional(),
        destinationPath: z.string().trim().transform(prefixWithSlash).transform(removeTrailingSlash).optional()
      }),
      response: {
        200: z.object({
          canMove: z.boolean(),
          folderName: z.string(),
          blockingType: z
            .enum(["dynamic_secret", "secret_rotation", "honey_token", "secret_import", "secret_approval_policy"])
            .optional(),
          blockingPath: z.string().optional(),
          destinationBlocked: z.boolean().optional(),
          destinationBlockingPath: z.string().optional(),
          destinationPolicyName: z.string().optional(),
          hasRbacPolicies: z.boolean().optional()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    handler: async (req) =>
      server.services.folder.getFolderMoveEligibility({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        id: req.params.folderId,
        destinationEnvironment: req.query.destinationEnvironment,
        destinationPath: req.query.destinationPath
      })
  });
};