8000 dashboard: persisted share stats always fit the budget they are read back under · Issue #339 · stratum-mining/sv2-ui · GitHub
[go: up one dir, main page]

Skip to content

dashboard: persisted share stats always fit the budget they are read back under #339

Open

Description

@lucasbalieiro

Affected layers

  • Frontend (src/): affected. usePersistentState in src/hooks/usePersistentDashboardMetrics.ts applies the 2 MiB limit only when it reads localStorage; every update serializes the whole merged state and writes it without a size check. The entry, key and label caps count JavaScript characters, not JSON characters: JSON.stringify writes each control character as six characters and each quote or backslash as two. The labels are taken from sv2-apps: shares_rejected_by_reason is keyed by the error_code of SubmitShares.Error, a 255-byte protocol string chosen by the upstream pool. On the current stratum main branch the client share accounting counts only the known codes individually and groups the rest under one label, so an unmodified current build emits a fixed set; sv2-ui does not pin that behavior.
  • Backend (server/): not affected. Dashboard state is not stored there.
  • shared/: not affected. shared/openapi.json declares shares_rejected_by_reason as an object with arbitrary string property names, so the schema bounds neither the labels nor their number.

Problem

A response with 256 entries, each carrying 32 labels of 128 characters, passes every cap. With control characters in the labels it serializes to 6.27 million characters; with quotes alone to 2.14 million; with plain ASCII to 1.11 million. The limit the loader enforces is 2,097,152.

Every change in a counter rebuilds the full string on the UI thread and tries to store it. When the string exceeds the browser's quota, commonly 5 MiB per origin, setItem throws, the error is swallowed, and the oversized state stays in memory and is serialized again on the next change. When the string fits the quota but exceeds 2 MiB, the write succeeds and the next page load discards it, because the loader rejects stored strings over 2 MiB. The lifetime share statistics then restart from zero without any notice.

Impact

The operator pays CPU and memory in the dashboard tab, and loses the persisted share statistics. It needs a monitoring response whose rejection reason labels carry control characters, quotes or backslashes in volume: control of the monitoring service, for example from a compromised mining container, or an upstream pool sending such error codes through an sv2-apps build that passes them on. Severity low.

Expected outcome

  • Every state the dashboard writes to localStorage is one it reads back after a reload: the serialized size never exceeds the limit the loader applies.
  • Telemetry within the caps, 256 entries with 32 labels of 128 characters each, cannot push the serialized size over that limit, whatever characters the labels contain.
  • A response with such labels never resets the lifetime share statistics.
  • A regression test asserts the serialized size for such a response, with entries built from a representative /server/channels payload as docs/monitoring-api-compatibility.md asks.

Possible approach (non-binding)

Measure keys and labels by their JSON-encoded length, as the Loupe suggestion does, so that the caps bound what gets stored; or check the serialized size before the write and drop labels until it fits; or raise the read limit to the worst case the caps allow. The size assertion in the Loupe PoC fits next to the storage-size test in src/hooks/usePersistentDashboardMetrics.test.ts.

Loupe findings

Related issues and PRs

Loupe export for #339 (finding #51)

Finding

  • repo: stratum-mining/sv2-ui (https://github.com/stratum-mining/sv2-ui.git)
  • reviewed revision: b610455ac2d1e017c1df5db8787c0b2e505eabdc
  • title: Enforce the storage budget before serializing telemetry
  • severity: low
  • location: src/hooks/usePersistentDashboardMetrics.ts:400-402
  • cwe: CWE-400
  • scanner: llm-code-review
  • fingerprint: 408dde8b0946a31fb95ae7dec9db4483d14448da9dd2cc556fc7383b2b40853e

Description

The hook enforces a two-million-character limit only when reading localStorage, but always serializes and attempts to write the entire merged state. The entry/reason character-count caps do not bound JSON's encoded size: control characters occupy one JavaScript character while JSON.stringify expands each to a six-character escape. A response containing 256 entries with 32 distinct 128-character reason labels per entry therefore passes every current cap yet serializes to over six million characters, as the PoC shows. Repeated changing counters synchronously rebuild this string on the UI thread; setItem commonly fails quota, the exception is swallowed, and the oversized React state remains active. Any successful write is then rejected by this hook's own 2 MiB read limit on reload, silently discarding metrics. A malicious/compromised upstream monitoring response can thus cause repeated CPU/memory pressure and persistent-stat loss. The repository declares reason labels only as arbitrary string keys; an out-of-tree monitoring service might enforce a narrower charset, which is an exploitability dependency not verifiable here. Finding #8071 was reviewed: it covers missing cardinality/length limits, whereas this is a JSON-escaping bypass of those limits and the write-only size check.

Proof of Concept

diff --git a/src/hooks/usePersistentDashboardMetrics.storage-size.test.ts b/src/hooks/usePersistentDashboardMetrics.storage-size.test.ts
new file mode 100644
--- /dev/null
+++ b/src/hooks/usePersistentDashboardMetrics.storage-size.test.ts
@@ -0,0 +1,28 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { mergeShareStatsEntries } from './usePersistentDashboardMetrics.js';
+
+test('merged share stats stay within the persistence size budget', () => {
+  const reasons = Object.fromEntries(
+    Array.from({ length: 32 }, (_, index) => [
+      `${'\0'.repeat(126)}${index.toString().padStart(2, '0')}`,
+      1,
+    ]),
+  );
+  const entries = Array.from({ length: 256 }, (_, index) => ({
+    key: `channel:${index}`,
+    acknowledged: 1,
+    submitted: 1,
+    rejected: 1,
+    rejectedByReason: reasons,
+  }));
+
+  const { next } = mergeShareStatsEntries({}, entries);
+  const serialized = JSON.stringify(next);
+
+  assert.ok(
+    serialized.length <= 2 * 1024 * 1024,
+    `bounded telemetry expanded to ${serialized.length} persisted characters`,
+  );
+});

Suggested Fix

diff --git a/src/hooks/usePersistentDashboardMetrics.ts b/src/hooks/usePersistentDashboardMetrics.ts
--- a/src/hooks/usePersistentDashboardMetrics.ts
+++ b/src/hooks/usePersistentDashboardMetrics.ts
@@ -57,14 +57,18 @@
 function normalizeCount(value: unknown): number {
   return typeof value === 'number' && Number.isFinite(value) ? Math.max(0, value) : 0;
 }
 
+function fitsJsonStringLength(value: string, maxLength: number): boolean {
+  return JSON.stringify(value).length - 2 <= maxLength;
+}
+
 // Keeps at most MAX_REJECTION_REASONS labels of at most MAX_REASON_LENGTH
-// characters, preferring the highest counts (the display sorts by count too).
+// JSON-encoded characters, preferring the highest counts (the display sorts by count too).
 function clampReasons(reasons: Record<string, number>): Record<string, number> {
   return Object.fromEntries(
     Object.entries(reasons)
-      .filter(([reason]) => reason.length <= MAX_REASON_LENGTH)
+      .filter(([reason]) => fitsJsonStringLength(reason, MAX_REASON_LENGTH))
       .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
       .slice(0, MAX_REJECTION_REASONS),
   );
 }
@@ -84,5 +88,5 @@
 export function normalizeMetricKey(key: string): string {
-  return key === AGGREGATE_KEY || key.length <= MAX_ENTRY_KEY_LENGTH
+  return key === AGGREGATE_KEY || fitsJsonStringLength(key, MAX_ENTRY_KEY_LENGTH)
     ? key
     : `h:${hashString(key)}`;
 }
@@ -169,9 +173,9 @@
     const rejectedByReason =
       storedReasons && typeof storedReasons === 'object' && !Array.isArray(storedReasons)
         ? Object.fromEntries(
             Object.entries(storedReasons)
-              .filter(([reason]) => reason.length <= MAX_REASON_LENGTH)
+              .filter(([reason]) => fitsJsonStringLength(reason, MAX_REASON_LENGTH))
               .slice(-MAX_REJECTION_REASONS)
               .map(([reason, count]) => [reason, normalizeCount(count)]),
           )
         : {};
@@ -275,5 +279,5 @@
     const rejectedByReason = { ...current.rejectedByReason };
 
     const incomingReasons = Object.entries(entry.rejectedByReason ?? {})
-      .filter(([reason]) => reason.length <= MAX_REASON_LENGTH)
+      .filter(([reason]) => fitsJsonStringLength(reason, MAX_REASON_LENGTH))
       .slice(-MAX_REJECTION_REASONS);

This finding was discovered by Project Loupe.

Activity

  1. added
    area:dashboard
    and removed on Oct 14, 2026
  2. changed the title [-]Enforce the storage budget before serializing telemetry[/-] [+]dashboard: persisted share stats always fit the budget they are read back under[/+] on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:dashboard

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0