Skip to content

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

improvement(secrets): add environment-scoped recency sorting (#8022)

Andrew Huang6195ee9be458
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index b0701df774..0ae24e588d 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1534,6 +1534,8 @@ export const DASHBOARD = {
limit: "The number of secrets/folders to return.",
orderBy: "The column to order secrets/folders by.",
orderDirection: "The direction to order secrets/folders in.",
+ sortEnvironment:
+ "The environment slug whose secret timestamps determine recency ordering. Required for multi-environment recency sorting.",
search: "The text string to filter secret keys and folder names by.",
tags: "The tags to filter secrets by (comma separated, ie 'tags=billing,engineering').",
includeSecrets: "Whether to include project secrets in the response.",
diff --git a/backend/src/server/routes/v1/dashboard-router.ts b/backend/src/server/routes/v1/dashboard-router.ts
index badc66e507..f169e2d3ac 100644
--- a/backend/src/server/routes/v1/dashboard-router.ts
+++ b/backend/src/server/routes/v1/dashboard-router.ts
@@ -12,6 +12,7 @@ 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 { 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";
@@ -33,7 +34,8 @@ import {
import {
PersonalOverridesBehavior,
SecretImportReferencesBehavior,
- SecretsOrderBy
+ SecretsOrderBy,
+ SecretSortField
} from "@app/services/secret/secret-types";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -194,15 +196,14 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
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(SecretsOrderBy)
- .default(SecretsOrderBy.Name)
- .describe(DASHBOARD.SECRET_OVERVIEW_LIST.orderBy)
- .optional(),
+ .nativeEnum(SecretSortField)
+ .default(SecretSortField.Name)
+ .describe(DASHBOARD.SECRET_OVERVIEW_LIST.orderBy),
orderDirection: z
.nativeEnum(OrderByDirection)
.default(OrderByDirection.ASC)
- .describe(DASHBOARD.SECRET_OVERVIEW_LIST.orderDirection)
- .optional(),
+ .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),
@@ -335,6 +336,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
search,
orderBy,
orderDirection,
+ sortEnvironment,
includeFolders,
includeSecrets,
includeImports,
@@ -350,6 +352,23 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
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
@@ -458,8 +477,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
projectId,
environments,
path: secretPath,
- orderBy,
- orderDirection,
+ orderBy: SecretsOrderBy.Name,
+ orderDirection: resourceOrderDirection,
search,
limit: remainingLimit,
offset: adjustedOffset
@@ -512,8 +531,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
actorOrgId: req.permission.orgId,
projectId,
search,
- orderBy,
- orderDirection,
+ orderBy: SecretsOrderBy.Name,
+ orderDirection: resourceOrderDirection,
environmentSlugs: environments,
path: secretPath,
limit: remainingLimit,
@@ -562,8 +581,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
{
projectId,
search,
- orderBy,
- orderDirection,
+ orderBy: SecretsOrderBy.Name,
+ orderDirection: resourceOrderDirection,
environments,
secretPath,
limit: remainingLimit,
@@ -612,8 +631,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
{
projectId,
search,
- orderBy,
- orderDirection,
+ orderBy: SecretsOrderBy.Name,
+ orderDirection: resourceOrderDirection,
environments,
secretPath,
limit: remainingLimit,
@@ -647,8 +666,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
{
projectId,
search,
- orderBy,
- orderDirection,
+ orderBy: SecretsOrderBy.Name,
+ orderDirection: resourceOrderDirection,
environments,
secretPath,
limit: remainingLimit,
@@ -696,6 +715,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
path: secretPath,
orderBy,
orderDirection,
+ sortEnvironment,
search,
tagSlugs,
limit: remainingLimit,
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index f7effe98ee..4932335b69 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -16,6 +16,7 @@ import {
TFindOpt
} from "@app/lib/knex";
import { OrderByDirection } from "@app/lib/types";
+import { SecretSortField } from "@app/services/secret/secret-types";
import type { TFindSecretsByFolderIdsFilter } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
export const SecretServiceCacheKeys = {
@@ -728,6 +729,11 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
filters?: TFindSecretsByFolderIdsFilter;
}) => {
const { folderIds, tx, filters } = dto;
+ const timestampOrderBy =
+ filters?.orderBy === SecretSortField.CreatedAt || filters?.orderBy === SecretSortField.UpdatedAt
+ ? filters.orderBy
+ : undefined;
+ const sortDirection = filters?.orderDirection ?? OrderByDirection.ASC;
let { userId } = dto;
try {
// check if not uui then userId id is null (corner case because service token's ID is not UUI in effort to keep backwards compatibility from mongo)
@@ -800,14 +806,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
});
}
})
- .select(
- selectAllTableCols(TableName.SecretV2),
- db.raw(
- `DENSE_RANK() OVER (ORDER BY "${TableName.SecretV2}".key ${
- filters?.orderDirection ?? OrderByDirection.ASC
- }) as rank`
- )
- )
+ .select(selectAllTableCols(TableName.SecretV2))
.select(db.ref("id").withSchema(TableName.Reminder).as("reminderId"))
.select(db.ref("message").withSchema(TableName.Reminder).as("reminderNote"))
.select(db.ref("repeatDays").withSchema(TableName.Reminder).as("reminderRepeatDays"))
@@ -848,9 +847,61 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
.orderBy(`${TableName.SecretTag}.createdAt`, "asc", "first")
.orderBy(`${TableName.SecretTag}.id`, "asc", "first");
+ if (timestampOrderBy) {
+ const sortFolderIds = filters?.sortFolderIds ?? folderIds;
+ const sortFolderBindings = Object.fromEntries(
+ sortFolderIds.map((folderId, index) => [`sortFolderId${index}`, folderId])
+ );
+ const sortFolderPlaceholders = sortFolderIds.map((_, index) => `:sortFolderId${index}`).join(", ");
+ const timestampValue = sortFolderIds.length
+ ? db.raw(
+ `COALESCE(
+ MAX(:timestampColumn:) FILTER (WHERE :folderColumn: IN (${sortFolderPlaceholders}) AND :typeColumn: = :sharedType) OVER (PARTITION BY :keyColumn:),
+ MAX(:timestampColumn:) FILTER (WHERE :folderColumn: IN (${sortFolderPlaceholders}) AND :typeColumn: = :personalType) OVER (PARTITION BY :keyColumn:)
+ ) AS "sortValue"`,
+ {
+ timestampColumn: `${TableName.SecretV2}.${timestampOrderBy}`,
+ folderColumn: `${TableName.SecretV2}.folderId`,
+ typeColumn: `${TableName.SecretV2}.type`,
+ keyColumn: `${TableName.SecretV2}.key`,
+ sharedType: SecretType.Shared,
+ personalType: SecretType.Personal,
+ ...sortFolderBindings
+ }
+ )
+ : db.raw('NULL AS "sortValue"');
+ void query.select(timestampValue);
+ } else {
+ void query.select(db.raw(`DENSE_RANK() OVER (ORDER BY "${TableName.SecretV2}".key ${sortDirection}) as rank`));
+ }
+
let secs: Awaited<typeof query>;
- if (filters?.limit) {
+ if (timestampOrderBy) {
+ const rankedQuery = (tx || db)
+ .with("matching", query)
+ .with("ranked", (qb) =>
+ qb
+ .select("matching.*")
+ .select(db.raw(`DENSE_RANK() OVER (ORDER BY "sortValue" ${sortDirection} NULLS LAST, "key" ASC) AS rank`))
+ .from("matching")
+ )
+ .select("*")
+ .from<Awaited<typeof query>[number]>("ranked")
+ .orderBy("sortValue", sortDirection, "last")
+ .orderBy("key", OrderByDirection.ASC)
+ .orderBy("id", OrderByDirection.ASC)
+ .orderBy("metadataCreatedAt", "asc", "first")
+ .orderBy("metadataId", "asc", "first")
+ .orderBy("tagCreatedAt", "asc", "first")
+ .orderBy("tagId", "asc", "first");
+
+ if (filters?.limit) {
+ const rankOffset = (filters.offset ?? 0) + 1;
+ void rankedQuery.where("rank", ">=", rankOffset).andWhere("rank", "<", rankOffset + filters.limit);
+ }
+ secs = await rankedQuery;
+ } else if (filters?.limit) {
const rankOffset = (filters?.offset ?? 0) + 1; // ranks start at 1
secs = await (tx || db)
.with("w", query)
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index 19bd2c02c7..fab54e78b0 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -63,6 +63,7 @@ import { TSecretQueueFactory } from "../secret/secret-queue";
import {
PersonalOverridesBehavior,
SecretImportReferencesBehavior,
+ SecretSortField,
TGetASecretByIdDTO,
TRedactSecretVersionValueDTO
} from "../secret/secret-types";
@@ -111,6 +112,7 @@ import {
TGetASecretDTO,
TGetSecretReferencesTreeDTO,
TGetSecretsDTO,
+ TGetSecretsMultiEnvDTO,
TGetSecretsRawByFolderMappingsDTO,
TGetSecretVersionsDTO,
TMoveSecretsDTO,
@@ -1269,13 +1271,7 @@ export const secretV2BridgeServiceFactory = ({
actorAuthMethod,
isInternal,
...params
- }: Pick<
- TGetSecretsDTO,
- "actorId" | "actor" | "path" | "projectId" | "actorOrgId" | "actorAuthMethod" | "search" | "tagSlugs"
- > & {
- environments: string[];
- isInternal?: boolean;
- }) => {
+ }: TGetSecretsMultiEnvDTO) => {
const { permission } = await permissionService.getProjectPermission({
actor,
actorId,
@@ -1305,11 +1301,24 @@ export const secretV2BridgeServiceFactory = ({
environment: folder.environment.slug
}));
+ const isTimestampSort =
+ params.orderBy === SecretSortField.CreatedAt || params.orderBy === SecretSortField.UpdatedAt;
+ const sortEnvironment = params.sortEnvironment ?? (environments.length === 1 ? environments[0] : undefined);
+ if (isTimestampSort && !sortEnvironment) {
+ throw new BadRequestError({
+ message: "A sort environment is required for timestamp sorting when multiple environments are requested"
+ });
+ }
+
+ const sortFolderIds = isTimestampSort
+ ? folders.filter((folder) => folder.environment.slug === sortEnvironment).map((folder) => folder.id)
+ : undefined;
+
const { secrets } = await getSecretsByFolderMappings(
{
projectId,
folderMappings,
- filters: params,
+ filters: { ...params, sortFolderIds },
userId: actorId,
filterByAction: ProjectPermissionSecretActions.DescribeSecret
},
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index a6d9f2c810..f5b492d4e7 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@ -15,7 +15,8 @@ import { TSecretQueueFactory } from "@app/services/secret/secret-queue";
import {
PersonalOverridesBehavior,
SecretImportReferencesBehavior,
- SecretsOrderBy
+ type SecretsOrderBy,
+ SecretSortField
} from "@app/services/secret/secret-types";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
@@ -491,8 +492,9 @@ export type TGetSecretReferencesDTO = {
export type TFindSecretsByFolderIdsFilter = {
limit?: number;
offset?: number;
- orderBy?: SecretsOrderBy;
+ orderBy?: SecretsOrderBy | SecretSortField;
orderDirection?: OrderByDirection;
+ sortFolderIds?: string[];
search?: string;
tagSlugs?: string[];
metadataFilter?: { key?: string; value?: string }[];
@@ -502,6 +504,26 @@ export type TFindSecretsByFolderIdsFilter = {
excludeRotatedSecrets?: boolean;
};
+export type TGetSecretsMultiEnvDTO = Pick<
+ TGetSecretsDTO,
+ | "actorId"
+ | "actor"
+ | "path"
+ | "projectId"
+ | "actorOrgId"
+ | "actorAuthMethod"
+ | "search"
+ | "tagSlugs"
+ | "orderDirection"
+ | "limit"
+ | "offset"
+> & {
+ orderBy?: SecretSortField;
+ sortEnvironment?: string;
+ environments: string[];
+ isInternal?: boolean;
+};
+
export type TGetSecretsRawByFolderMappingsDTO = {
projectId: string;
folderMappings: { folderId: string; path: string; environment: string }[];
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 4c2565c69b..00c44d376a 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -85,6 +85,7 @@ import { TSecretQueueFactory } from "./secret-queue";
import {
SecretOperations,
SecretProtectionType,
+ SecretSortField,
TAttachSecretTagsDTO,
TBackFillSecretReferencesDTO,
TCreateBulkSecretDTO,
@@ -1259,9 +1260,11 @@ export const secretServiceFactory = ({
actorAuthMethod,
environments,
...params
- }: Omit<TGetSecretsRawDTO, "environment" | "includeImports" | "expandSecretReferences" | "recursive"> & {
+ }: Omit<TGetSecretsRawDTO, "environment" | "includeImports" | "expandSecretReferences" | "recursive" | "orderBy"> & {
environments: string[];
isInternal?: boolean;
+ orderBy?: SecretSortField;
+ sortEnvironment?: string;
}) => {
const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.ts
index 29388f8903..ff9ae3cfb6 100644
--- a/backend/src/services/secret/secret-types.ts
+++ b/backend/src/services/secret/secret-types.ts
@@ -194,6 +194,12 @@ export enum SecretsOrderBy {
Name = "name" // "key" for secrets but using name for use across resources
}
+export enum SecretSortField {
+ Name = "name",
+ CreatedAt = "createdAt",
+ UpdatedAt = "updatedAt"
+}
+
export enum PersonalOverridesBehavior {
Priority = "priority", // used in v4 router when includePersonalOverrides is true
IncludeAll = "include-all", // used in deprecated v3 secret router to keep existing behavior
diff --git a/frontend/src/hooks/api/dashboard/queries.tsx b/frontend/src/hooks/api/dashboard/queries.tsx
index 4b896c03da..cf332476a5 100644
--- a/frontend/src/hooks/api/dashboard/queries.tsx
+++ b/frontend/src/hooks/api/dashboard/queries.tsx
@@ -213,6 +213,7 @@ export const useGetProjectSecretsOverview = (
limit = 100,
orderBy = DashboardSecretsOrderBy.Name,
orderDirection = OrderByDirection.ASC,
+ sortEnvironment,
search = "",
tags,
includeSecrets,
@@ -247,6 +248,7 @@ export const useGetProjectSecretsOverview = (
limit,
orderBy,
orderDirection,
+ sortEnvironment,
offset,
projectId,
includeSecrets,
@@ -266,6 +268,7 @@ export const useGetProjectSecretsOverview = (
limit,
orderBy,
orderDirection,
+ sortEnvironment,
offset,
projectId,
includeSecrets,
diff --git a/frontend/src/hooks/api/dashboard/types.ts b/frontend/src/hooks/api/dashboard/types.ts
index 90b7dd64f2..fb331eedf2 100644
--- a/frontend/src/hooks/api/dashboard/types.ts
+++ b/frontend/src/hooks/api/dashboard/types.ts
@@ -125,7 +125,9 @@ export type DashboardProjectSecretsDetails = Omit<
};
export enum DashboardSecretsOrderBy {
- Name = "name"
+ Name = "name",
+ CreatedAt = "createdAt",
+ UpdatedAt = "updatedAt"
}
export type TGetDashboardProjectSecretsOverviewDTO = {
@@ -135,6 +137,7 @@ export type TGetDashboardProjectSecretsOverviewDTO = {
limit?: number;
orderBy?: DashboardSecretsOrderBy;
orderDirection?: OrderByDirection;
+ sortEnvironment?: string;
search?: string;
tags?: Record<string, boolean>;
includeSecrets?: boolean;
@@ -149,9 +152,10 @@ export type TGetDashboardProjectSecretsOverviewDTO = {
export type TGetDashboardProjectSecretsDetailsDTO = Omit<
TGetDashboardProjectSecretsOverviewDTO,
- "environments"
+ "environments" | "orderBy" | "sortEnvironment"
> & {
environment: string;
+ orderBy?: DashboardSecretsOrderBy.Name;
includeImports?: boolean;
tags: Record<string, boolean>;
};
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index 287bb520eb..87ee44c7a4 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -11,9 +11,14 @@ import { AxiosError } from "axios";
import {
ArrowDownZAIcon,
ArrowUpAZIcon,
+ ArrowUpDownIcon,
+ CalendarArrowDownIcon,
+ CalendarArrowUpIcon,
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
+ ClockArrowDownIcon,
+ ClockArrowUpIcon,
CopyIcon,
DownloadIcon,
EyeIcon,
@@ -82,6 +87,10 @@ import {
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
PageHeader,
Pagination,
@@ -298,7 +307,7 @@ const OVERVIEW_BATCH_MODE_KEY = "overview-batch-mode-enabled";
const getSecretSortValue = (orderBy: DashboardSecretsOrderBy, orderDirection: OrderByDirection) =>
`${orderBy}:${orderDirection}`;
-const SECRET_NAME_SORT_OPTIONS = [
+const SECRET_SORT_OPTIONS = [
{
label: "Name (A to Z)",
Icon: ArrowUpAZIcon,
@@ -310,11 +319,33 @@ const SECRET_NAME_SORT_OPTIONS = [
Icon: ArrowDownZAIcon,
orderBy: DashboardSecretsOrderBy.Name,
orderDirection: OrderByDirection.DESC
+ },
+ {
+ label: "Last Edited (New)",
+ Icon: ClockArrowUpIcon,
+ orderBy: DashboardSecretsOrderBy.UpdatedAt,
+ orderDirection: OrderByDirection.DESC
+ },
+ {
+ label: "Last Edited (Old)",
+ Icon: ClockArrowDownIcon,
+ orderBy: DashboardSecretsOrderBy.UpdatedAt,
+ orderDirection: OrderByDirection.ASC
+ },
+ {
+ label: "Created (New)",
+ Icon: CalendarArrowUpIcon,
+ orderBy: DashboardSecretsOrderBy.CreatedAt,
+ orderDirection: OrderByDirection.DESC
+ },
+ {
+ label: "Created (Old)",
+ Icon: CalendarArrowDownIcon,
+ orderBy: DashboardSecretsOrderBy.CreatedAt,
+ orderDirection: OrderByDirection.ASC
}
] as const;
-const SECRET_SORT_OPTIONS = SECRET_NAME_SORT_OPTIONS;
-
const OverviewPageContent = () => {
const { t } = useTranslation();
@@ -416,6 +447,7 @@ const OverviewPageContent = () => {
} = usePagination<DashboardSecretsOrderBy>(DashboardSecretsOrderBy.Name, {
initPerPage: getUserTablePreference("secretOverviewTable", PreferenceKey.PerPage, 100)
});
+ const [sortEnvironment, setSortEnvironment] = useState<string>();
const handlePerPageChange = (newPerPage: number) => {
setPerPage(newPerPage);
@@ -576,8 +608,39 @@ const OverviewPageContent = () => {
[userAvailableEnvs]
);
+ const shouldClearSortEnvironment = Boolean(
+ sortEnvironment &&
+ (visibleEnvs.length === 1 ||
+ !visibleEnvs.some((environment) => environment.slug === sortEnvironment))
+ );
+ const isTimestampSort =
+ orderBy === DashboardSecretsOrderBy.CreatedAt || orderBy === DashboardSecretsOrderBy.UpdatedAt;
+ const shouldResetTimestampSort =
+ isTimestampSort && visibleEnvs.length > 1 && (!sortEnvironment || shouldClearSortEnvironment);
+
+ useEffect(() => {
+ if (shouldClearSortEnvironment) {
+ setSortEnvironment(undefined);
+ }
+
+ if (shouldResetTimestampSort) {
+ setOrderBy(DashboardSecretsOrderBy.Name);
+ setOrderDirection(OrderByDirection.ASC);
+ }
+
+ if (shouldClearSortEnvironment || shouldResetTimestampSort) {
+ setPage(1);
+ }
+ }, [
+ shouldClearSortEnvironment,
+ shouldResetTimestampSort,
+ setOrderBy,
+ setOrderDirection,
+ setPage
+ ]);
+
const handleSecretSortChange = useCallback(
- (value: string) => {
+ (value: string, environment?: string) => {
const option = SECRET_SORT_OPTIONS.find(
({ orderBy: nextOrderBy, orderDirection: nextOrderDirection }) =>
getSecretSortValue(nextOrderBy, nextOrderDirection) === value
@@ -587,6 +650,7 @@ const OverviewPageContent = () => {
setOrderBy(option.orderBy);
setOrderDirection(option.orderDirection);
+ setSortEnvironment(environment);
setPage(1);
},
[setOrderBy, setOrderDirection, setPage]
@@ -597,6 +661,15 @@ const OverviewPageContent = () => {
getSecretSortValue(option.orderBy, option.orderDirection) ===
getSecretSortValue(orderBy, orderDirection)
);
+ const ActiveSecretSortIcon = activeSecretSort?.Icon ?? ArrowUpDownIcon;
+ let activeSecretSortScope = "";
+ if (sortEnvironment) {
+ activeSecretSortScope = ` in ${
+ visibleEnvs.find((environment) => environment.slug === sortEnvironment)?.name ??
+ sortEnvironment
+ }`;
+ }
+
const relevantPendingApprovalsCount = useMemo(() => {
// Reviewers see project-wide pending requests (existing behavior).
if (canApproveAny) return pendingApprovalsCount;
@@ -868,6 +941,7 @@ const OverviewPageContent = () => {
secretPath,
orderDirection,
orderBy,
+ sortEnvironment,
includeFolders: isFilteredByResources ? filter.folder : true,
includeDynamicSecrets: isFilteredByResources ? filter.dynamic : true,
includeSecrets: activeTagSlugs.length > 0 || (isFilteredByResources ? filter.secret : true),
@@ -886,7 +960,9 @@ const OverviewPageContent = () => {
data: overview,
isPlaceholderData,
isFetching: isOverviewFetching
- } = useGetProjectSecretsOverview(overviewQueryParams, { enabled: isProjectV3 });
+ } = useGetProjectSecretsOverview(overviewQueryParams, {
+ enabled: isProjectV3 && !shouldClearSortEnvironment && !shouldResetTimestampSort
+ });
const isOverviewPending = isOverviewLoading || isPlaceholderData;
const showDelayedOverviewSkeleton = useDelayedLoading(isPlaceholderData, {
resetKey: JSON.stringify(overviewQueryParams)
@@ -3101,7 +3177,7 @@ const OverviewPageContent = () => {
<button
type="button"
className="flex h-full w-full cursor-pointer items-center justify-between px-3 text-left focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
- aria-label={`Sort secrets. Current order: ${activeSecretSort?.label ?? "Name (A to Z)"}`}
+ aria-label={`Sort secrets. Current order: ${activeSecretSort?.label ?? "Name (A to Z)"}${activeSecretSortScope}`}
>
<span className="text-sm font-medium text-muted">Name</span>
<ChevronDownIcon className="size-3.5 shrink-0 text-muted" />
@@ -3116,10 +3192,16 @@ const OverviewPageContent = () => {
{visibleEnvs.length > 1 ? "Sort secret names" : "Sort secrets"}
</DropdownMenuLabel>
<DropdownMenuRadioGroup
- value={getSecretSortValue(orderBy, orderDirection)}
+ value={
+ sortEnvironment ? "" : getSecretSortValue(orderBy, orderDirection)
+ }
onValueChange={(value) => handleSecretSortChange(value)}
>
- {SECRET_SORT_OPTIONS.map((option) => (
+ {SECRET_SORT_OPTIONS.filter(
+ ({ orderBy: sortField }) =>
+ visibleEnvs.length === 1 ||
+ sortField === DashboardSecretsOrderBy.Name
+ ).map((option) => (
<DropdownMenuRadioItem
key={getSecretSortValue(option.orderBy, option.orderDirection)}
value={getSecretSortValue(option.orderBy, option.orderDirection)}
@@ -3145,17 +3227,71 @@ const OverviewPageContent = () => {
<button
type="button"
title={name}
- aria-label={`Open ${name} environment menu`}
+ aria-label={`Open ${name} environment menu${
+ sortEnvironment === slug
+ ? `. Currently sorting by ${activeSecretSort?.label ?? "recency"}`
+ : ""
+ }`}
className="flex h-full w-full min-w-[240px] cursor-pointer items-center justify-center gap-x-2 px-3 text-sm font-medium text-muted hover:bg-foreground/5 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
>
- <span className="min-w-0 truncate">{name}</span>
- <ChevronDownIcon className="size-3.5 shrink-0" />
+ <span
+ className={twMerge(
+ "min-w-0 truncate",
+ sortEnvironment === slug && "text-foreground"
+ )}
+ >
+ {name}
+ </span>
+ {sortEnvironment === slug ? (
+ <ActiveSecretSortIcon className="size-3.5 shrink-0 text-foreground" />
+ ) : (
+ <ChevronDownIcon className="size-3.5 shrink-0" />
+ )}
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
onCloseAutoFocus={(event) => event.preventDefault()}
>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <ArrowUpDownIcon />
+ Sort Secrets by Recency
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent>
+ <DropdownMenuLabel>Use {name} Timestamps</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={
+ sortEnvironment === slug
+ ? getSecretSortValue(orderBy, orderDirection)
+ : ""
+ }
+ onValueChange={(value) =>
+ handleSecretSortChange(value, slug)
+ }
+ >
+ {SECRET_SORT_OPTIONS.filter(
+ ({ orderBy: sortField }) =>
+ sortField !== DashboardSecretsOrderBy.Name
+ ).map((option) => (
+ <DropdownMenuRadioItem
+ key={getSecretSortValue(
+ option.orderBy,
+ option.orderDirection
+ )}
+ value={getSecretSortValue(
+ option.orderBy,
+ option.orderDirection
+ )}
+ >
+ <option.Icon />
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ <DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
navigator.clipboard.writeText(slug);