diff --git a/app/(dashboard)/browser/page.tsx b/app/(dashboard)/browser/page.tsx index 1be4c506..a1701e7a 100644 --- a/app/(dashboard)/browser/page.tsx +++ b/app/(dashboard)/browser/page.tsx @@ -20,7 +20,11 @@ import { useDialog } from "@/lib/feedback/dialog" import { useMessage } from "@/lib/feedback/message" import { formatDateTime, formatInteger, niceBytes } from "@/lib/functions" import { normalizeDateToIso } from "@/lib/safe-date" -import { getAccountBucketUsage } from "@/lib/account-bucket-usage" +import { + getAccountBucketUsage, + getAccountBucketDisplayUsage, + getAccountBucketInitialUsage, +} from "@/lib/account-bucket-usage" import { BucketNameCell, type BucketNameRow } from "@/components/buckets/name-cell" import { loadBucketPolicyStatuses } from "@/lib/bucket-policy-status" import { BrowserContent } from "./content" @@ -35,7 +39,7 @@ interface BucketRow { IsPublic?: boolean } -type BucketViewRow = BucketRow & BucketNameRow +type BucketViewRow = BucketRow & BucketNameRow & { InitialUsage?: boolean } function BrowserBucketsPage() { const { t } = useTranslation() @@ -146,10 +150,19 @@ function BrowserBucketsPage() { const usageLoading = accountInfoLoading || !hasFetchedPolicy const bucketUsage = useMemo(() => getAccountBucketUsage(userInfo), [userInfo]) + const displayUsage = useMemo(() => getAccountBucketDisplayUsage(userInfo), [userInfo]) + const initialUsage = useMemo(() => getAccountBucketInitialUsage(userInfo), [userInfo]) + useEffect(() => { + if (!hasFetchedPolicy || data.length === 0) return + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") void fetchUserPolicy() + }, 30000) + return () => window.clearInterval(timer) + }, [hasFetchedPolicy, data.length, fetchUserPolicy]) const rowsWithUsage = useMemo( () => data.map((row) => { - const usage = bucketUsage.get(row.Name) + const usage = displayUsage.get(row.Name) const BucketHref = `/browser?bucket=${encodeURIComponent(row.Name)}` if (!usage) return { ...row, BucketHref } @@ -159,9 +172,10 @@ function BrowserBucketsPage() { Count: usage.objectsCount, Size: niceBytes(String(usage.sizeBytes)), SizeBytes: usage.sizeBytes, + InitialUsage: usage.initial, } }), - [bucketUsage, data], + [displayUsage, data], ) const filteredData = useMemo( () => @@ -193,7 +207,12 @@ function BrowserBucketsPage() { meta: { align: "end" }, cell: ({ row }) => typeof row.original.Count === "number" ? ( - formatInteger(row.original.Count) + + {formatInteger(row.original.Count)} + {row.original.InitialUsage && ( + {t("Initial statistics")} + )} + ) : usageLoading ? ( ) : ( @@ -319,9 +338,10 @@ function BrowserBucketsPage() { bucket.Name)} usage={bucketUsage} + initialUsage={initialUsage} unavailable={pending || loadError} usageLoading={pending || usageLoading} - usageAvailable={!usageLoading && Array.isArray(userInfo?.buckets)} + usageAvailable={Array.isArray(userInfo?.buckets)} /> getAccountBucketUsage(userInfo), [userInfo]) + const bucketUsage = React.useMemo(() => getAccountBucketDisplayUsage(userInfo), [userInfo]) + React.useEffect(() => { + if (!hasFetchedPolicy || data.length === 0) return + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") void fetchUserPolicy() + }, 30000) + return () => window.clearInterval(timer) + }, [hasFetchedPolicy, data.length, fetchUserPolicy]) const rowsWithUsage = React.useMemo( () => data.map((row) => { @@ -136,6 +143,7 @@ export function BucketList({ title, emptyDescription, getBucketHref }: BucketLis Count: usage.objectsCount, Size: niceBytes(String(usage.sizeBytes)), SizeBytes: usage.sizeBytes, + InitialUsage: usage.initial, } }), [bucketUsage, data, getBucketHref], @@ -166,7 +174,12 @@ export function BucketList({ title, emptyDescription, getBucketHref }: BucketLis meta: { align: "end" }, cell: ({ row }) => typeof row.original.Count === "number" ? ( - formatInteger(row.original.Count) + + {formatInteger(row.original.Count)} + {row.original.InitialUsage && ( + {t("Initial statistics")} + )} + ) : usageLoading ? ( ) : ( diff --git a/components/buckets/usage-overview.tsx b/components/buckets/usage-overview.tsx index 00b76857..72dc4b94 100644 --- a/components/buckets/usage-overview.tsx +++ b/components/buckets/usage-overview.tsx @@ -11,15 +11,20 @@ export function BucketUsageOverview({ unavailable, usageAvailable = true, usageLoading = false, + initialUsage = new Map(), }: { names: string[] usage: Map usageLoading?: boolean usageAvailable?: boolean unavailable: boolean + initialUsage?: ReadonlyMap }) { const { t, i18n } = useTranslation() - const summary = !unavailable && usageAvailable ? summarizeBucketUsage(names, usage) : undefined + const complete = !unavailable && usageAvailable ? summarizeBucketUsage(names, usage) : undefined + const initial = complete && complete.measuredBuckets === 0 ? summarizeBucketUsage(names, initialUsage) : undefined + const showingInitial = initial && initial.measuredBuckets > 0 + const summary = showingInitial ? initial : complete const hasValues = summary && (summary.measuredBuckets > 0 || names.length === 0) const measurementReported = summary && (names.length === 0 || names.some((name) => usage.has(name))) const statisticsState = usageLoading @@ -33,7 +38,11 @@ export function BucketUsageOverview({ ? t("Loading…") : t("Usage unavailable") const distribution = - summary && summary.measuredBuckets === names.length && summary.sizeBytes !== undefined && summary.sizeBytes > 0 + !showingInitial && + summary && + summary.measuredBuckets === names.length && + summary.sizeBytes !== undefined && + summary.sizeBytes > 0 ? names .map((name) => ({ name, size: usage.get(name)!.sizeBytes })) .filter((bucket) => bucket.size > 0) @@ -72,7 +81,9 @@ export function BucketUsageOverview({
{summary.sizeBytes !== undefined && (
-
{t("Measured size")}
+
+ {t(showingInitial ? "Scanned size" : "Measured size")} +
{niceBytes(String(summary.sizeBytes))}
@@ -80,7 +91,9 @@ export function BucketUsageOverview({ )} {summary.objectsCount !== undefined && (
-
{t("Measured objects")}
+
+ {t(showingInitial ? "Scanned objects" : "Measured objects")} +
{formatInteger(summary.objectsCount)}
@@ -101,7 +114,7 @@ export function BucketUsageOverview({
{hasValues && (

- {coverage} + {showingInitial ? t("Initial statistics") : coverage}

)}
diff --git a/hooks/use-permissions.tsx b/hooks/use-permissions.tsx index 911f95e8..14a77067 100644 --- a/hooks/use-permissions.tsx +++ b/hooks/use-permissions.tsx @@ -95,6 +95,7 @@ export function PermissionsProvider({ children }: { children: React.ReactNode }) const [hasResolvedAdmin, setHasResolvedAdmin] = useState(false) const [hasFetchedPolicy, setHasFetchedPolicy] = useState(false) const requestEpochRef = useRef(0) + const userPolicyRequestRef = useRef(0) const [permissionRevision, setPermissionRevision] = useState(0) const identityKey = JSON.stringify([ isAuthenticated, @@ -166,35 +167,51 @@ export function PermissionsProvider({ children }: { children: React.ReactNode }) const fetchUserPolicy = useCallback(async () => { if (!api) return const requestEpoch = requestEpochRef.current + const requestId = userPolicyRequestRef.current + 1 + userPolicyRequestRef.current = requestId + // Same-identity refreshes may overlap; only the newest request can publish. + const isCurrentRequest = () => + requestEpoch === requestEpochRef.current && requestId === userPolicyRequestRef.current setIsLoading(true) // /is-admin includes IAM administrators; /account/info reports caller.is_owner. const ownerRequest = api.get("/account/info", { suppress403Redirect: true }).then( (info) => { - if (requestEpoch === requestEpochRef.current) setIsOwner((info as { is_admin?: unknown })?.is_admin === true) + if (isCurrentRequest()) setIsOwner((info as { is_admin?: unknown })?.is_admin === true) }, () => { - if (requestEpoch === requestEpochRef.current) setIsOwner(false) + if (isCurrentRequest()) setIsOwner(false) }, ) try { - const info = (await api.get("/accountinfo", { suppress403Redirect: true })) as Record - if (requestEpoch !== requestEpochRef.current) return - setUserInfo(info) - const policyStr = info?.policy as string - if (policyStr) { - setUserPolicy(JSON.parse(policyStr) as ConsolePolicy) - } else { - setUserPolicy(null) + const info = (await api.get("/accountinfo?view=snapshot", { suppress403Redirect: true })) as Record< + string, + unknown + > + if (!isCurrentRequest()) return + const policyStr = info?.policy + if (policyStr !== undefined && policyStr !== null && typeof policyStr !== "string") { + throw new SyntaxError("Account policy must be a JSON string") } + const nextPolicy = policyStr ? (JSON.parse(policyStr) as ConsolePolicy) : null + setUserInfo(info) + setUserPolicy(nextPolicy) permissionClient.invalidate() } catch (e) { - if (requestEpoch !== requestEpochRef.current) return + if (!isCurrentRequest()) return console.error("Failed to fetch user policy", e) - setUserInfo(null) - setUserPolicy(null) + const status = e && typeof e === "object" && "status" in e ? e.status : undefined + const temporaryFailure = + !(e instanceof SyntaxError) && + (status === undefined || (typeof status === "number" && status >= 500 && status < 600)) + // Transient failures retain this identity's last successful snapshot. + if (!temporaryFailure) { + setUserInfo(null) + setUserPolicy(null) + permissionClient.invalidate() + } } finally { - if (requestEpoch === requestEpochRef.current) { + if (isCurrentRequest()) { setIsLoading(false) setHasFetchedPolicy(true) } diff --git a/i18n/locales/ar-MA.json b/i18n/locales/ar-MA.json index c693cd92..d58c5533 100644 --- a/i18n/locales/ar-MA.json +++ b/i18n/locales/ar-MA.json @@ -1,4 +1,7 @@ { + "Initial statistics": "الإحصاءات الأولية · غير مكتملة", + "Scanned size": "الحجم الذي تم فحصه", + "Scanned objects": "الكائنات التي تم فحصها", "Statistics pending": "في انتظار الإحصاءات", "Statistics unavailable": "الإحصاءات غير متاحة", "Cluster scanner status": "حالة ماسح العنقود", diff --git a/i18n/locales/de-DE.json b/i18n/locales/de-DE.json index 8c74a05b..3bab62c5 100644 --- a/i18n/locales/de-DE.json +++ b/i18n/locales/de-DE.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Erste Statistik · Unvollständig", + "Scanned size": "Erfasste Größe", + "Scanned objects": "Erfasste Objekte", "Statistics pending": "Statistik ausstehend", "Statistics unavailable": "Statistik nicht verfügbar", "Cluster scanner status": "Scannerstatus des Clusters", diff --git a/i18n/locales/en-US.json b/i18n/locales/en-US.json index bf5d334e..dcd2b5eb 100644 --- a/i18n/locales/en-US.json +++ b/i18n/locales/en-US.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Initial statistics · Partial", + "Scanned size": "Scanned size", + "Scanned objects": "Scanned objects", "Statistics pending": "Awaiting statistics", "Statistics unavailable": "Statistics unavailable", "Cluster scanner status": "Cluster scanner status", diff --git a/i18n/locales/es-ES.json b/i18n/locales/es-ES.json index 70eed4f7..f4632d59 100644 --- a/i18n/locales/es-ES.json +++ b/i18n/locales/es-ES.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Estadísticas iniciales · Parciales", + "Scanned size": "Tamaño analizado", + "Scanned objects": "Objetos analizados", "Statistics pending": "Estadísticas pendientes", "Statistics unavailable": "Estadísticas no disponibles", "Cluster scanner status": "Estado del escáner del clúster", diff --git a/i18n/locales/fr-FR.json b/i18n/locales/fr-FR.json index b0654442..5807ac7e 100644 --- a/i18n/locales/fr-FR.json +++ b/i18n/locales/fr-FR.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Premières statistiques · Partielles", + "Scanned size": "Taille analysée", + "Scanned objects": "Objets analysés", "Statistics pending": "Statistiques en attente", "Statistics unavailable": "Statistiques indisponibles", "Cluster scanner status": "État de l’analyse du cluster", diff --git a/i18n/locales/id-ID.json b/i18n/locales/id-ID.json index e197072c..8d140cc3 100644 --- a/i18n/locales/id-ID.json +++ b/i18n/locales/id-ID.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Statistik awal · Belum lengkap", + "Scanned size": "Ukuran dipindai", + "Scanned objects": "Objek dipindai", "Statistics pending": "Menunggu statistik", "Statistics unavailable": "Statistik tidak tersedia", "Cluster scanner status": "Status pemindai klaster", diff --git a/i18n/locales/it-IT.json b/i18n/locales/it-IT.json index 0285f9c1..f8956e58 100644 --- a/i18n/locales/it-IT.json +++ b/i18n/locales/it-IT.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Statistiche iniziali · Parziali", + "Scanned size": "Dimensione analizzata", + "Scanned objects": "Oggetti analizzati", "Statistics pending": "Statistiche in attesa", "Statistics unavailable": "Statistiche non disponibili", "Cluster scanner status": "Stato della scansione del cluster", diff --git a/i18n/locales/ja-JP.json b/i18n/locales/ja-JP.json index 9260344a..302e69e4 100644 --- a/i18n/locales/ja-JP.json +++ b/i18n/locales/ja-JP.json @@ -1,4 +1,7 @@ { + "Initial statistics": "初回統計 · 未完了", + "Scanned size": "スキャン済みサイズ", + "Scanned objects": "スキャン済みオブジェクト", "Statistics pending": "統計待ち", "Statistics unavailable": "統計を取得できません", "Cluster scanner status": "クラスターのスキャナー状態", diff --git a/i18n/locales/ko-KR.json b/i18n/locales/ko-KR.json index 45974cde..276d5768 100644 --- a/i18n/locales/ko-KR.json +++ b/i18n/locales/ko-KR.json @@ -1,4 +1,7 @@ { + "Initial statistics": "첫 통계 · 미완료", + "Scanned size": "스캔된 용량", + "Scanned objects": "스캔된 객체", "Statistics pending": "통계 대기 중", "Statistics unavailable": "통계를 사용할 수 없음", "Cluster scanner status": "클러스터 스캐너 상태", diff --git a/i18n/locales/pt-BR.json b/i18n/locales/pt-BR.json index 51f5d611..4acbb007 100644 --- a/i18n/locales/pt-BR.json +++ b/i18n/locales/pt-BR.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Estatísticas iniciais · Parciais", + "Scanned size": "Tamanho verificado", + "Scanned objects": "Objetos verificados", "Statistics pending": "Estatísticas pendentes", "Statistics unavailable": "Estatísticas indisponíveis", "Cluster scanner status": "Estado do scanner do cluster", diff --git a/i18n/locales/ru-RU.json b/i18n/locales/ru-RU.json index 052ef80e..20868511 100644 --- a/i18n/locales/ru-RU.json +++ b/i18n/locales/ru-RU.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Первичная статистика · Неполная", + "Scanned size": "Просканированный объём", + "Scanned objects": "Просканированные объекты", "Statistics pending": "Статистика ожидается", "Statistics unavailable": "Статистика недоступна", "Cluster scanner status": "Состояние сканера кластера", diff --git a/i18n/locales/tr-TR.json b/i18n/locales/tr-TR.json index 05858858..8aad1901 100644 --- a/i18n/locales/tr-TR.json +++ b/i18n/locales/tr-TR.json @@ -1,4 +1,7 @@ { + "Initial statistics": "İlk istatistikler · Kısmi", + "Scanned size": "Taranan boyut", + "Scanned objects": "Taranan nesneler", "Statistics pending": "İstatistikler bekleniyor", "Statistics unavailable": "İstatistikler kullanılamıyor", "Cluster scanner status": "Küme tarayıcısının durumu", diff --git a/i18n/locales/vi-VN.json b/i18n/locales/vi-VN.json index d79fd853..6e482139 100644 --- a/i18n/locales/vi-VN.json +++ b/i18n/locales/vi-VN.json @@ -1,4 +1,7 @@ { + "Initial statistics": "Thống kê đầu tiên · Chưa hoàn tất", + "Scanned size": "Dung lượng đã quét", + "Scanned objects": "Đối tượng đã quét", "Statistics pending": "Chờ thống kê", "Statistics unavailable": "Không có thống kê", "Cluster scanner status": "Trạng thái trình quét của cụm", diff --git a/i18n/locales/zh-CN.json b/i18n/locales/zh-CN.json index 8ae07273..3b9af2a4 100644 --- a/i18n/locales/zh-CN.json +++ b/i18n/locales/zh-CN.json @@ -1,4 +1,7 @@ { + "Initial statistics": "首次统计 · 未完成", + "Scanned size": "已扫描容量", + "Scanned objects": "已扫描对象数", "Statistics pending": "待统计", "Statistics unavailable": "统计不可用", "Cluster scanner status": "集群扫描器状态", diff --git a/i18n/locales/zh-TW.json b/i18n/locales/zh-TW.json index 5700ffb8..d76ab443 100644 --- a/i18n/locales/zh-TW.json +++ b/i18n/locales/zh-TW.json @@ -1,4 +1,7 @@ { + "Initial statistics": "首次統計 · 未完成", + "Scanned size": "已掃描容量", + "Scanned objects": "已掃描物件數", "Statistics pending": "待統計", "Statistics unavailable": "統計無法取得", "Cluster scanner status": "叢集掃描器狀態", diff --git a/lib/account-bucket-usage.js b/lib/account-bucket-usage.js index 0fc0ac82..3ecb8868 100644 --- a/lib/account-bucket-usage.js +++ b/lib/account-bucket-usage.js @@ -20,6 +20,10 @@ export function getAccountBucketUsage(accountInfo) { const { name, objects, size } = bucket if (typeof name !== "string" || !name) continue + if (bucket.usage_value_state === "observed") { + usage.set(name, null) + continue + } if (objects === undefined && size === undefined) { usage.set(name, null) continue @@ -41,10 +45,54 @@ export function getAccountBucketUsage(accountInfo) { return usage } +/** + * Explicitly authorized first measurements, kept outside the complete sum. + * Missing flags, failed requests and malformed complete values never fall back. + * @param {Record | null | undefined} accountInfo + * @returns {Map} + */ +export function getAccountBucketInitialUsage(accountInfo) { + const complete = getAccountBucketUsage(accountInfo) + const statuses = getAccountBucketScanStatus(accountInfo) + /** @type {Map} */ + const initial = new Map() + for (const bucket of Array.isArray(accountInfo?.buckets) ? accountInfo.buckets : []) { + if ( + !bucket || + bucket.initial_scan !== true || + bucket.objects !== undefined || + bucket.size !== undefined || + complete.get(bucket.name) !== null + ) + continue + const progress = statuses.get(bucket.name)?.progress + if ( + !progress || + progress.stage === "enumerating" || + progress.objectsCount === undefined || + progress.sizeBytes === undefined + ) + continue + initial.set(bucket.name, { objectsCount: progress.objectsCount, sizeBytes: progress.sizeBytes, initial: true }) + } + return initial +} + +/** + * Complete measurements always win; initial values remain explicitly marked. + * @param {Record | null | undefined} accountInfo + * @returns {Map} + */ +export function getAccountBucketDisplayUsage(accountInfo) { + const usage = getAccountBucketUsage(accountInfo) + for (const [name, initial] of getAccountBucketInitialUsage(accountInfo)) usage.set(name, initial) + return usage +} + /** * Sum only reported measurements within the visible namespace. * @param {string[]} names - * @param {Map} usage + * @param {ReadonlyMap} usage * @returns {{ measuredBuckets: number, objectsCount: number | undefined, sizeBytes: number | undefined }} */ export function summarizeBucketUsage(names, usage) { diff --git a/tests/hooks/effective-permissions.test.ts b/tests/hooks/effective-permissions.test.ts index 262ef684..9539bcef 100644 --- a/tests/hooks/effective-permissions.test.ts +++ b/tests/hooks/effective-permissions.test.ts @@ -59,7 +59,7 @@ async function mount( const api = { resolveUrl: (path: string) => `https://fixture.invalid${path}`, async get(path: string) { - return path === "/accountinfo" ? { policy: identityPolicy } : { is_admin: false } + return path === "/accountinfo?view=snapshot" ? { policy: identityPolicy } : { is_admin: false } }, async post(_path: string, body: { checks: PermissionRequest[] }, options: { suppressBodyLogging?: boolean }) { assert.equal(options.suppressBodyLogging, true) diff --git a/tests/hooks/use-permissions-refresh.test.ts b/tests/hooks/use-permissions-refresh.test.ts index b88549ec..a509e64e 100644 --- a/tests/hooks/use-permissions-refresh.test.ts +++ b/tests/hooks/use-permissions-refresh.test.ts @@ -82,6 +82,11 @@ const policy = JSON.stringify({ Statement: [{ Effect: "Allow", Action: ["console:Browser"], Resource: ["*"] }], }) const accountInfo = (objects = 1) => ({ policy, buckets: [{ name: "test-bucket", objects, size: objects * 100 }] }) +const temporaryFailures = [ + ["network", () => new TypeError("Network unavailable")], + ["HTTP 500", () => Object.assign(new Error("Server error"), { status: 500 })], + ["HTTP 503", () => Object.assign(new Error("Service unavailable"), { status: 503 })], +] as const type Credentials = { AccessKeyId: string; SecretAccessKey: string; SessionToken: string } type Api = { get: (path: string) => Promise @@ -101,13 +106,21 @@ type UsageTable = { function makeApi( isAdmin = false, effective?: (check: PermissionRequest) => PermissionResult | Promise, + deferOwners = false, ) { const requests: ReturnType>[] = [] + const ownerRequests: ReturnType>[] = [] const permissionRequests: PermissionRequest[] = [] const api: Api = { get(path) { - if (path === "/is-admin" || path === "/account/info") return Promise.resolve({ is_admin: isAdmin }) - assert.equal(path, "/accountinfo") + if (path === "/is-admin") return Promise.resolve({ is_admin: isAdmin }) + if (path === "/account/info") { + const request = Promise.withResolvers() + ownerRequests.push(request) + if (!deferOwners) request.resolve({ is_admin: isAdmin }) + return request.promise + } + assert.equal(path, "/accountinfo?view=snapshot") const request = Promise.withResolvers() requests.push(request) return request.promise @@ -123,7 +136,7 @@ function makeApi( } } } - return { api, requests, permissionRequests } + return { api, requests, ownerRequests, permissionRequests } } async function mountBrowser( @@ -135,6 +148,7 @@ async function mountBrowser( isAdmin?: boolean search?: string effective?: (check: PermissionRequest) => PermissionResult | Promise + deferOwners?: boolean } = {}, ) { const browser = new Window() @@ -144,7 +158,24 @@ async function mountBrowser( ) for (const [key, value] of Object.entries(globals)) Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }) - const initial = makeApi(options.isAdmin, options.effective) + const initial = makeApi(options.isAdmin, options.effective, options.deferOwners) + const pollTimers = new Map, () => void>() + const setInterval = browser.setInterval.bind(browser) + const clearInterval = browser.clearInterval.bind(browser) + t.mock.method( + browser, + "setInterval", + (callback: Parameters[0], delay?: number, ...args: unknown[]) => { + if (delay !== 30000) return setInterval(callback, delay, ...args) + const timer = setInterval(() => {}, delay) + pollTimers.set(timer, () => callback(...args)) + return timer + }, + ) + t.mock.method(browser, "clearInterval", (timer: ReturnType) => { + pollTimers.delete(timer) + clearInterval(timer) + }) let api = initial.api let credentials: Credentials | undefined = { AccessKeyId: "first", SecretAccessKey: "secret", SessionToken: "token" } let isAdmin = false @@ -283,6 +314,7 @@ async function mountBrowser( listBuckets, getBucketPolicyStatus, requests: initial.requests, + ownerRequests: initial.ownerRequests, permissionRequests: initial.permissionRequests, get mounts() { return mounts @@ -300,6 +332,16 @@ async function mountBrowser( assert.ok(initial.requests[index], `accountinfo request ${index} exists`) await act(async () => initial.requests[index].resolve(info)) }, + async resolveOwner(index: number, owner: boolean) { + assert.ok(initial.ownerRequests[index], `owner request ${index} exists`) + await act(async () => initial.ownerRequests[index].resolve({ is_admin: owner })) + }, + async poll() { + assert.equal(pollTimers.size, 1, "one active bucket usage polling timer") + await act(async () => { + for (const callback of pollTimers.values()) callback() + }) + }, async refresh() { const button = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "Refresh") assert.ok(button, "Browser refresh button remains available") @@ -467,6 +509,78 @@ test("manual refresh and returning to Browser still force fresh buckets and acco assert.deepEqual([mounted.mounts, mounted.unmounts, mounted.requests.length], [2, 1, 4]) }) +for (const surface of ["Browser", "BucketList"] as const) { + for (const olderOutcome of ["success", "failure"] as const) { + test(`${surface} ignores an older polling ${olderOutcome} after a newer manual refresh completes`, async (t) => { + const errors = t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t, { surface }) + await mounted.resolve(0) + if (surface === "Browser") await mounted.resolve(1) + const older = mounted.requests.length + await mounted.poll() + await mounted.refresh() + assert.equal(mounted.requests.length, older + 2) + const latest = accountInfo(90) + await mounted.resolve(older + 1, latest) + const revision = mounted.permissions.permissionVersion + if (olderOutcome === "success") await mounted.resolve(older, accountInfo(7)) + else await act(async () => mounted.requests[older].reject(new Error("Older polling request failed"))) + + assert.equal(mounted.permissions.userInfo, latest) + assert.equal(mounted.permissions.permissionVersion, revision) + assert.equal(mounted.permissions.isLoading, false) + assert.equal(mounted.permissions.hasFetchedPolicy, true) + assert.equal(JSON.parse(mounted.container.querySelector("output")!.textContent)[0].Count, 90) + assert.equal(mounted.unmounts, 0) + assert.equal(errors.mock.callCount(), 0) + }) + } +} + +for (const olderOutcome of ["success", "failure"] as const) { + test(`an older ${olderOutcome} cannot clear loading or publish while the latest refresh is pending`, async (t) => { + const errors = t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t) + await mounted.resolve(0) + await mounted.resolve(1) + const previous = mounted.permissions.userInfo + const older = mounted.requests.length + await mounted.poll() + await mounted.refresh() + if (olderOutcome === "success") await mounted.resolve(older, accountInfo(7)) + else await act(async () => mounted.requests[older].reject(new Error("Older polling request failed"))) + + assert.equal(mounted.permissions.userInfo, previous) + assert.equal(mounted.permissions.isLoading, true) + assert.equal(mounted.permissions.hasFetchedPolicy, true) + assert.equal(errors.mock.callCount(), 0) + await mounted.resolve(older + 1, accountInfo(90)) + assert.equal(mounted.permissions.isLoading, false) + assert.equal(JSON.parse(mounted.container.querySelector("output")!.textContent)[0].Count, 90) + }) +} + +for (const olderOutcome of ["grant", "deny", "failure"] as const) { + test(`an older owner ${olderOutcome} cannot replace the latest same-identity owner result`, async (t) => { + const mounted = await mountBrowser(t, { deferOwners: true }) + await mounted.resolve(0) + await mounted.resolve(1) + const older = mounted.requests.length + await mounted.poll() + await mounted.refresh() + await mounted.resolve(older + 1, accountInfo(90)) + const latestOwner = olderOutcome !== "grant" + await mounted.resolveOwner(older + 1, latestOwner) + const context = { bucket: "test-bucket", objectKey: "unfinished/" } + assert.equal(mounted.permissions.canCapability("objects.forceCleanup", context), latestOwner) + + if (olderOutcome === "failure") + await act(async () => mounted.ownerRequests[older].reject(new Error("Older owner request failed"))) + else await mounted.resolveOwner(older, olderOutcome === "grant") + assert.equal(mounted.permissions.canCapability("objects.forceCleanup", context), latestOwner) + }) +} + for (const surface of ["Browser", "BucketList"] as const) { test(`${surface} renders complete bucket statistics without scanner details`, async (t) => { const mounted = await mountBrowser(t, { surface }) @@ -539,15 +653,28 @@ test("the first denied policy never mounts Browser and redirects to forbidden", ) }) -for (const fails of [false, true]) { - test(`a refresh ${fails ? "failure" : "revoking Browser permission"} removes Browser and redirects to forbidden`, async (t) => { +for (const failure of ["revoked policy", "HTTP 401", "HTTP 403", "malformed policy", "invalid policy type"] as const) { + test(`a refresh with ${failure} clears permission data and removes Browser`, async (t) => { const mounted = await mountBrowser(t) await mounted.resolve(0) - if (fails) { + if (failure === "HTTP 401" || failure === "HTTP 403") { + const errors = t.mock.method(console, "error", () => {}) + await act(async () => + mounted.requests[1].reject( + Object.assign(new Error("Access denied"), { status: failure === "HTTP 401" ? 401 : 403 }), + ), + ) + assert.equal(errors.mock.callCount(), 1) + } else if (failure === "malformed policy" || failure === "invalid policy type") { const errors = t.mock.method(console, "error", () => {}) - await act(async () => mounted.requests[1].reject(new Error("Policy unavailable"))) + await mounted.resolve(1, { + ...accountInfo(90), + policy: failure === "malformed policy" ? "{" : { toString: "invalid" }, + }) assert.equal(errors.mock.callCount(), 1) } else await mounted.resolve(1, { policy: "" }) + if (failure !== "revoked policy") assert.equal(mounted.permissions.userInfo, null) + assert.equal(mounted.permissions.userPolicy, null) assert.equal(mounted.container.querySelector("main"), null) assert.equal(mounted.unmounts, 1) assert.equal(mounted.firstRoute.route, "/403/") @@ -558,6 +685,105 @@ for (const fails of [false, true]) { }) } +for (const status of [401, 403]) { + test(`HTTP ${status} revalidates cached bucket-only access instead of retaining a stale grant`, async (t) => { + t.mock.method(console, "error", () => {}) + let allowed = true + const mounted = await mountBrowser(t, { + search: "bucket=alice-data", + effective: ({ action, bucket }) => ({ + decision: allowed && action === "s3:ListBucket" && bucket === "alice-data" ? "allowed" : "denied", + }), + }) + await mounted.resolve(0, { policy: "" }) + assert.ok(mounted.container.querySelector('[data-scoped-bucket="alice-data"]')) + allowed = false + const request = mounted.requests.length + await act(async () => { + void mounted.permissions.fetchUserPolicy() + }) + await act(async () => mounted.requests[request].reject(Object.assign(new Error("Access denied"), { status }))) + assert.equal(mounted.permissions.userInfo, null) + assert.equal(mounted.container.querySelector('[data-scoped-bucket="alice-data"]'), null) + assert.ok(mounted.router.replace.mock.calls.some((call) => call.arguments[0] === "/403/")) + }) +} + +for (const surface of ["Browser", "BucketList"] as const) { + for (const [failure, makeError] of temporaryFailures) { + test(`${surface} retains completed usage and permission after a ${failure} polling failure`, async (t) => { + const errors = t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t, { surface }) + const complete = accountInfo(90) + await mounted.resolve(0, complete) + if (surface === "Browser") await mounted.resolve(1, complete) + const previousPolicy = mounted.permissions.userPolicy + const revision = mounted.permissions.permissionVersion + const page = mounted.container.querySelector("main") + const request = mounted.requests.length + await mounted.poll() + await act(async () => mounted.requests[request].reject(makeError())) + + assert.equal(mounted.permissions.userInfo, complete) + assert.equal(mounted.permissions.userPolicy, previousPolicy) + assert.equal(mounted.permissions.permissionVersion, revision) + assert.equal(mounted.permissions.isLoading, false) + assert.equal(mounted.permissions.hasFetchedPolicy, true) + assert.equal(mounted.container.querySelector("main"), page) + assert.equal(JSON.parse(mounted.container.querySelector("output")!.textContent)[0].Count, 90) + assert.equal(mounted.router.replace.mock.callCount(), 0) + assert.equal(errors.mock.callCount(), 1) + + await mounted.refresh() + await mounted.resolve(request + 1, accountInfo(120)) + assert.equal(JSON.parse(mounted.container.querySelector("output")!.textContent)[0].Count, 120) + }) + } +} + +for (const [failure, makeError] of temporaryFailures) { + test(`an initial ${failure} account request remains unknown without fabricating a prior result`, async (t) => { + t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t) + await act(async () => mounted.requests[0].reject(makeError())) + assert.equal(mounted.permissions.userInfo, null) + assert.equal(mounted.permissions.userPolicy, null) + assert.equal(mounted.permissions.isLoading, false) + assert.equal(mounted.permissions.hasFetchedPolicy, true) + assert.equal(mounted.container.querySelector("main"), null) + }) +} + +test("a temporary failure for a new identity never restores the previous identity's complete usage", async (t) => { + t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t) + await mounted.resolve(0, accountInfo(90)) + await mounted.resolve(1, accountInfo(90)) + const request = mounted.requests.length + await mounted.changeIdentity({ AccessKeyId: "second", SecretAccessKey: "secret", SessionToken: "token" }) + await act(async () => mounted.requests[request].reject(new TypeError("Network unavailable"))) + assert.equal(mounted.permissions.userInfo, null) + assert.equal(mounted.permissions.userPolicy, null) + assert.equal(mounted.permissions.canAccessPath("/browser"), false) + assert.equal(mounted.container.querySelector("main"), null) +}) + +test("a newer transient failure retains the last complete value and still rejects an older in-flight result", async (t) => { + t.mock.method(console, "error", () => {}) + const mounted = await mountBrowser(t) + const complete = accountInfo(90) + await mounted.resolve(0, complete) + await mounted.resolve(1, complete) + const older = mounted.requests.length + await mounted.poll() + await mounted.refresh() + await act(async () => mounted.requests[older + 1].reject(Object.assign(new Error("Unavailable"), { status: 503 }))) + await mounted.resolve(older, accountInfo(7)) + assert.equal(mounted.permissions.userInfo, complete) + assert.equal(JSON.parse(mounted.container.querySelector("output")!.textContent)[0].Count, 90) + assert.equal(mounted.router.replace.mock.callCount(), 0) +}) + for (const change of ["access key", "secret", "session token", "api", "logout"] as const) { test(`${change} discards an old in-flight policy refresh`, async (t) => { const mounted = await mountBrowser(t) diff --git a/tests/lib/bucket-scan-progress.test.ts b/tests/lib/bucket-scan-progress.test.ts index e821bf38..e8a8b9f9 100644 --- a/tests/lib/bucket-scan-progress.test.ts +++ b/tests/lib/bucket-scan-progress.test.ts @@ -3,6 +3,8 @@ import assert from "node:assert/strict" import { getAccountBucketScanStatus, getAccountBucketUsage, + getAccountBucketInitialUsage, + getAccountBucketDisplayUsage, summarizeBucketUsage, } from "../../lib/account-bucket-usage.js" @@ -15,6 +17,59 @@ const progress = { sources_total: 2, } +test("only an explicit initial scan can supply display usage without a full measurement", () => { + const response = { + buckets: [ + { name: "initial", initial_scan: true, scan_progress: progress }, + { name: "legacy", scan_progress: progress }, + { name: "recovery", initial_scan: false, scan_progress: progress }, + ], + } + assert.equal(getAccountBucketInitialUsage(response).size, 1) + assert.deepEqual(getAccountBucketDisplayUsage(response).get("initial"), { + objectsCount: 7, + sizeBytes: 71, + initial: true, + }) + assert.equal(getAccountBucketDisplayUsage(response).get("legacy"), null) + assert.equal(getAccountBucketDisplayUsage(response).get("recovery"), null) + assert.equal(summarizeBucketUsage(["initial"], getAccountBucketUsage(response)).measuredBuckets, 0) +}) + +test("complete statistics always win and malformed complete fields cannot fall back to progress", () => { + const response = { + buckets: [ + { name: "complete", objects: 90, size: 900, initial_scan: true, scan_progress: progress }, + { name: "malformed", objects: "90", size: 900, initial_scan: true, scan_progress: progress }, + ], + } + assert.equal(getAccountBucketInitialUsage(response).size, 0) + assert.deepEqual(getAccountBucketDisplayUsage(response).get("complete"), { objectsCount: 90, sizeBytes: 900 }) + assert.equal(getAccountBucketDisplayUsage(response).has("malformed"), false) +}) + +test("initial enumeration and failed requests remain unmeasured", () => { + const response = { + buckets: [ + { + name: "initial", + initial_scan: true, + scan_progress: { ...progress, stage: "enumerating", objects: null, size: null }, + }, + ], + } + assert.equal(getAccountBucketInitialUsage(response).size, 0) + assert.equal(getAccountBucketDisplayUsage(response).get("initial"), null) + assert.equal(getAccountBucketInitialUsage(null).size, 0) +}) + +test("initial progress replaces a sample and never adds cycle work", () => { + for (const objects of [7, 7, 9, 9]) { + const response = { buckets: [{ name: "initial", initial_scan: true, scan_progress: { ...progress, objects } }] } + assert.equal(getAccountBucketDisplayUsage(response).get("initial")?.objectsCount, objects) + } +}) + test("partial scanner usage is visible separately and cannot enter bucket or overview totals", () => { const response = { buckets: [ diff --git a/tests/lib/bucket-usage-source.test.js b/tests/lib/bucket-usage-source.test.js index 5c4f527c..cb373583 100644 --- a/tests/lib/bucket-usage-source.test.js +++ b/tests/lib/bucket-usage-source.test.js @@ -8,7 +8,7 @@ for (const file of bucketPages) { test(`${file} uses accountinfo as the bucket statistics source`, async () => { const source = await readFile(file, "utf8") - assert.match(source, /getAccountBucketUsage\(userInfo\)/) + assert.match(source, /getAccountBucketDisplayUsage\(userInfo\)/) assert.match(source, /fetchUserPolicy\(\)/) if (file.includes("app/(dashboard)/browser/page.tsx")) { assert.match(source, /useEffect\(\(\) => \{\s*fetchBuckets\(\{ force: true \}\)/)