Skip to content

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

fix(dashboard): size the deep search pager on the largest resource type

Claude440cda3dc256
diff --git a/backend/e2e-test/routes/v1/dashboard-deep-search.spec.ts b/backend/e2e-test/routes/v1/dashboard-deep-search.spec.ts
index cfb1af81c1..1b568416e8 100644
--- a/backend/e2e-test/routes/v1/dashboard-deep-search.spec.ts
+++ b/backend/e2e-test/routes/v1/dashboard-deep-search.spec.ts
@@ -3,7 +3,9 @@ import { seedData1 } from "@app/db/seed-data";
type TDeepSearchResponse = {
secrets?: { secretKey: string }[];
+ folders?: { name: string }[];
totalSecretCount: number;
+ totalFolderCount: number;
totalCount: number;
searchLimit: number;
isSearchLimitReached: boolean;
@@ -48,6 +50,40 @@ const deleteSecret = async (key: string) => {
expect(res.statusCode).toBe(200);
};
+const createFolder = async (name: string) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ name,
+ path: TEST_PATH
+ }
+ });
+ expect(res.statusCode).toBe(200);
+ return res.json().folder as { id: string };
+};
+
+const deleteFolder = async (id: string) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/folders/${id}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ path: TEST_PATH
+ }
+ });
+ expect(res.statusCode).toBe(200);
+};
+
const deepSearch = async (pagination?: { limit?: number; offset?: number }) => {
const params = new URLSearchParams({
projectId: seedData1.projectV3.id,
@@ -121,4 +157,39 @@ describe("Dashboard - deep search pagination", async () => {
expect(res.statusCode).toBe(422);
});
+
+ describe("with a folder matching the same term", async () => {
+ const folderName = `${SEARCH_TERM}_FOLDER`;
+ let folderId: string;
+
+ beforeAll(async () => {
+ folderId = (await createFolder(folderName)).id;
+ });
+
+ afterAll(async () => {
+ await deleteFolder(folderId);
+ });
+
+ test("counts and pages each resource type on its own offset", async () => {
+ const firstPageRes = await deepSearch({ limit: 2, offset: 0 });
+ expect(firstPageRes.statusCode).toBe(200);
+ const firstPage = JSON.parse(firstPageRes.payload) as TDeepSearchResponse;
+
+ expect(firstPage.totalFolderCount).toBe(1);
+ expect(firstPage.totalSecretCount).toBe(secretKeys.length);
+ expect(firstPage.folders?.map((folder) => folder.name)).toEqual([folderName]);
+ expect(firstPage.secrets?.map((secret) => secret.secretKey)).toEqual(secretKeys.slice(0, 2));
+
+ // the folder bucket is exhausted a page before the secret bucket, so a pager sized on the sum of the
+ // counts would offer pages that hold nothing
+ const secondPageRes = await deepSearch({ limit: 2, offset: 2 });
+ expect(secondPageRes.statusCode).toBe(200);
+ const secondPage = JSON.parse(secondPageRes.payload) as TDeepSearchResponse;
+
+ expect(secondPage.totalFolderCount).toBe(1);
+ expect(secondPage.folders ?? []).toEqual([]);
+ expect(secondPage.secrets?.map((secret) => secret.secretKey)).toEqual(secretKeys.slice(2));
+ expect(secondPage.isSearchLimitReached).toBe(false);
+ });
+ });
});
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 7f9a4a20d8..b848ffc63f 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
@@ -692,11 +692,13 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
.select(db.ref("id").withSchema(TableName.SecretTag).as("tagId"))
.select(db.ref("color").withSchema(TableName.SecretTag).as("tagColor"))
.select(db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"))
+ .select(db.ref("createdAt").withSchema(TableName.SecretTag).as("tagCreatedAt"))
.select(
db.ref("id").withSchema(TableName.ResourceMetadata).as("metadataId"),
db.ref("key").withSchema(TableName.ResourceMetadata).as("metadataKey"),
db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue"),
- db.ref("encryptedValue").withSchema(TableName.ResourceMetadata).as("metadataEncryptedValue")
+ db.ref("encryptedValue").withSchema(TableName.ResourceMetadata).as("metadataEncryptedValue"),
+ db.ref("createdAt").withSchema(TableName.ResourceMetadata).as("metadataCreatedAt")
)
.select(db.ref("rotationId").withSchema(TableName.SecretRotationV2SecretMapping))
.select(db.ref("honeyTokenId").withSchema(TableName.HoneyTokenSecretMapping).as("honeyTokenId"))
@@ -729,9 +731,14 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
.from<Awaited<typeof query>[number]>("w")
.where("w.rank", ">=", rankOffset)
.andWhere("w.rank", "<", rankOffset + filters.limit)
- // a CTE does not carry its inner ordering, so re-state it here to keep paging deterministic
- .orderBy("key", filters?.orderDirection ?? OrderByDirection.ASC)
- .orderBy("id", OrderByDirection.ASC);
+ // a CTE does not carry its inner ordering, so re-state it in full: paging needs the key order, and the
+ // join rows need the metadata/tag order the inner query set, which a partial re-sort would scramble
+ .orderBy("key", filters.orderDirection ?? OrderByDirection.ASC)
+ .orderBy("id", OrderByDirection.ASC)
+ .orderBy("metadataCreatedAt", "asc", "first")
+ .orderBy("metadataId", "asc", "first")
+ .orderBy("tagCreatedAt", "asc", "first")
+ .orderBy("tagId", "asc", "first");
} else {
secs = await 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 268afe2b31..29c864d0c7 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
@@ -1123,13 +1123,22 @@ export const secretV2BridgeServiceFactory = ({
) => {
const groupedFolderMappings = groupBy(folderMappings, (folderMapping) => folderMapping.folderId);
- const secrets = await secretDAL.findByFolderIds({
+ const { limit } = filters;
+
+ // findByFolderIds windows on distinct keys, so scan one key past the limit to tell a full window from a truncated one
+ const scannedSecrets = await secretDAL.findByFolderIds({
folderIds: folderMappings.map((folderMapping) => folderMapping.folderId),
userId,
tx: undefined,
- filters
+ filters: limit ? { ...filters, limit: limit + 1 } : filters
});
+ const scannedKeys = [...new Set(scannedSecrets.map((secret) => secret.key))];
+ const isLimitReached = limit ? scannedKeys.length > limit : false;
+ const secrets = isLimitReached
+ ? scannedSecrets.filter((secret) => secret.key !== scannedKeys[scannedKeys.length - 1])
+ : scannedSecrets;
+
const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.SecretManager,
projectId
@@ -1182,12 +1191,9 @@ export const secretV2BridgeServiceFactory = ({
);
});
- // findByFolderIds limits on distinct keys, so a fully consumed limit means matches may exist beyond it
- const matchedKeyCount = new Set(secrets.map((secret) => secret.key)).size;
-
return {
secrets: decryptedSecrets,
- isLimitReached: filters.limit ? matchedKeyCount >= filters.limit : false
+ isLimitReached
};
};
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
index fa3c69fd28..2225568b4a 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
@@ -248,12 +248,16 @@ const Content = ({
.filter((group) => group.total > 0);
}, [folders, secrets, dynamicSecrets, secretRotations, environments, envIdToSlug, showType]);
- // pages advance every resource type at once, so counting every visible match keeps them all reachable
- const visibleResultCount =
- (showType(RowType.Folder) ? totalFolderCount : 0) +
- (showType(RowType.Secret) ? totalSecretCount : 0) +
- (showType(RowType.DynamicSecret) ? totalDynamicSecretCount : 0) +
- (showType(RowType.SecretRotation) ? totalSecretRotationCount : 0);
+ // the endpoint applies one offset to each resource type independently, so the largest type sets the page count
+ const visibleResultCount = Math.max(
+ showType(RowType.Folder) ? totalFolderCount : 0,
+ showType(RowType.Secret) ? totalSecretCount : 0,
+ showType(RowType.DynamicSecret) ? totalDynamicSecretCount : 0,
+ showType(RowType.SecretRotation) ? totalSecretRotationCount : 0
+ );
+
+ // the endpoint rejects an offset past its search window, so stop the pager at the last page it accepts
+ const pageableResultCount = Math.min(visibleResultCount, searchLimit + perPage);
useEffect(() => {
setPage(1);
@@ -545,14 +549,14 @@ const Content = ({
showType(RowType.SecretRotation) ? totalSecretRotationCount : 0
}
/>
- {isSearchLimitReached && (
+ {(isSearchLimitReached || pageableResultCount < visibleResultCount) && (
<span className="text-xs text-accent">
- {`Only the first ${searchLimit} matches per resource type are searched. Narrow your search to reach the rest.`}
+ {`Only the first ${searchLimit} matches per resource type can be reached. Narrow your search to see the rest.`}
</span>
)}
</div>
}
- count={visibleResultCount}
+ count={pageableResultCount}
page={page}
perPage={perPage}
perPageList={QUICK_SEARCH_PER_PAGE_OPTIONS}