From 82bd2d2586aa68b79311f6502da1f0baa1510a8b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 23:09:39 -0600 Subject: [PATCH] fix(aggregator): sanitize malformed SaaS feed rows --- pm-stack/aggregator/src/feed.ts | 102 ++++++++++++ pm-stack/aggregator/src/sources/live.ts | 10 +- pm-stack/aggregator/test/feed.test.ts | 1 - .../aggregator/test/saas-feed-gate.test.ts | 147 ++++++++++++++++++ 4 files changed, 256 insertions(+), 4 deletions(-) create mode 100644 pm-stack/aggregator/test/saas-feed-gate.test.ts diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 641567437..e532c6b02 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -55,6 +55,9 @@ export interface FleetFeed { /** Rows loadFeed's charges sanitization dropped (#2445), set only * when drops occurred; absent on raw parsed feeds and clean loads. */ chargesDropped?: number; + /** SaaS service rows loadFeed's sanitization dropped (#2451), set + * only when drops occurred; absent on raw parsed feeds and clean loads. */ + saasDropped?: number; /** Sandbox-server + Jules sessions, pre-classification (render classifies). */ attention: SessionFeedEntry[]; /** Jules keeper totals (slice 2); absent when the keeper state is unreadable. */ @@ -442,6 +445,102 @@ export function isChargeRow(v: unknown): v is ChargeRow { ); } +const SAAS_GROUPS = ["database", "object-storage", "compute", "dev-platform", "domains", "account-tooling"]; +const USAGE_UNITS = [ + "pct", + "usd", + "cny", + "count", + "gb", + "tokens", + "minutes", + "hours", + "ms", + "rows", + "ops", + "neurons", + "other", +]; +const USAGE_SOURCE_CLASSES = ["api", "console", "manual", "estimate", "invoice"]; + +function isUsageMetric(v: unknown): boolean { + if (!isRecord(v)) return false; + return ( + typeof v.id === "string" && + typeof v.label === "string" && + (v.used === null || isFiniteNumber(v.used)) && + (v.limit === null || isFiniteNumber(v.limit)) && + typeof v.unit === "string" && + USAGE_UNITS.includes(v.unit) && + (v.percent === undefined || isFiniteNumber(v.percent)) && + (v.lowerBound === undefined || typeof v.lowerBound === "boolean") && + typeof v.highlight === "boolean" && + (v.note === undefined || typeof v.note === "string") + ); +} + +function isPaygEstimate(v: unknown): boolean { + if (!isRecord(v)) return false; + return ( + isFiniteNumber(v.low) && + isFiniteNumber(v.high) && + typeof v.period === "string" && + (v.note === undefined || typeof v.note === "string") + ); +} + +function isSaasService(v: unknown): v is SaasService { + if (!isRecord(v)) return false; + const sources = v.sources; + const sourcesValid = + sources === undefined || + (isRecord(sources) && + typeof sources.quotaViewSection === "string" && + (typeof sources.trackerRow === "string" || sources.trackerRow === null) && + typeof sources.baselineDoc === "string"); + return ( + typeof v.id === "string" && + typeof v.name === "string" && + typeof v.group === "string" && + SAAS_GROUPS.includes(v.group) && + typeof v.plan === "string" && + (v.status === "active" || v.status === "candidate" || v.status === "no-account" || v.status === "unknown") && + Array.isArray(v.metrics) && + v.metrics.every(isUsageMetric) && + (v.paygEstimate === null || isPaygEstimate(v.paygEstimate)) && + (v.paygNote === undefined || typeof v.paygNote === "string") && + (v.billedUsd === undefined || v.billedUsd === null || isFiniteNumber(v.billedUsd)) && + (typeof v.measuredAt === "string" || v.measuredAt === null) && + typeof v.sourceClass === "string" && + USAGE_SOURCE_CLASSES.includes(v.sourceClass) && + typeof v.sourceNote === "string" && + sourcesValid && + (v.nextDate === undefined || typeof v.nextDate === "string" || v.nextDate === null) && + isFiniteNumber(v.cadenceDays) && + isStringArray(v.conflicts) && + Array.isArray(v.reads) && + v.reads.every((read) => isRecord(read) && typeof read.at === "string" && typeof read.text === "string") && + (v.usageNote === undefined || typeof v.usageNote === "string") + ); +} + +export interface SaasSanitization { + /** Renderer-safe services, or undefined when the optional section is absent/non-array. */ + rows?: SaasService[]; + /** Invalid array elements, or one when a present section is not an array. */ + dropped: number; +} + +/** Drop malformed service rows at the feed boundary (#2451). One bad + * service must not take down usage(); non-arrays are treated as absent + * so they cannot silently choose the feed usage branch. */ +export function sanitizeSaasServices(v: unknown): SaasSanitization { + if (v === undefined) return { dropped: 0 }; + if (!Array.isArray(v)) return { dropped: 1 }; + const rows = v.filter(isSaasService); + return { rows, dropped: v.length - rows.length }; +} + /** The choices block renderQuota dereferences (hasHeadroom et al.). */ function isQuotaChoices(v: unknown): boolean { if (!isRecord(v)) return false; @@ -574,6 +673,7 @@ export async function loadFeed(path: string): Promise { // attached to the feed so they are visible, not swallowed. const san = sanitizeQuotaView(parsed.quota); const meta = sanitizeFeedMetadata(parsed.meta); + const saas = sanitizeSaasServices(parsed.saas); // Same drop-and-count treatment for chargesAttention elements // (#2439): the gate has already pinned the section to array-or- // absent, so arrayOf cannot return null here; malformed entries @@ -600,6 +700,8 @@ export async function loadFeed(path: string): Promise { ...parsed, meta, quota: san.view, + saas: saas.rows, + saasDropped: saas.dropped || undefined, quotaDropped: { pools: san.droppedPools, windows: san.droppedWindows, burn: san.droppedBurn }, ...(charges ? { chargesAttention: charges.values } : {}), ...(charges && charges.dropped > 0 ? { chargesAttentionDropped: charges.dropped } : {}), diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index d6d2fa290..d2e517fa4 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -909,6 +909,10 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise ({ kind: "unmatched-charge", label: `${u.merchant} — unrecognized SaaS/AI charge`, @@ -918,7 +922,7 @@ export function liveSource(cfg: Config, opts?: { standingAuto?: () => Promise Promise Promise { + test("drops null rows and preserves valid services in a mixed array", async () => { + const loaded = await load([VALID, null]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBe(1); + }); + + test("a null-only array drops all services but keeps the feed", async () => { + const loaded = await load([null]); + expect(loaded).not.toBeNull(); + expect(loaded?.saas).toEqual([]); + expect(loaded?.saasDropped).toBe(1); + }); + + test("non-array strings and objects are treated as absent and counted", async () => { + for (const invalid of ["oops", { id: "turso" }]) { + const loaded = await load(invalid); + expect(loaded).not.toBeNull(); + expect(loaded?.saas).toBeUndefined(); + expect(loaded?.saasDropped).toBe(1); + expect(sanitizeSaasServices(invalid)).toEqual({ dropped: 1 }); + } + }); + + test("service rows missing metrics or conflicts drop individually", async () => { + const { metrics: _metrics, ...withoutMetrics } = VALID; + const { conflicts: _conflicts, ...withoutConflicts } = VALID; + const loaded = await load([withoutMetrics, VALID, withoutConflicts]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBe(2); + }); + + test("valid remainder renders and contributes attention flags", async () => { + const src = await sourceWith([VALID, null]); + const usage = await src.usage(); + expect(usage.services).toEqual([VALID]); + expect(usage.attention).toContainEqual( + expect.objectContaining({ kind: "over-limit", label: "Turso — Rows" }), + ); + const html = renderQuota(await src.quota(), src.provenance(), usage); + expect(html).toContain("Turso"); + expect(src.provenance().usage).toContain("dropped 1 malformed SaaS service row(s)"); + }); + + test("all-dropped and non-array sections expose loss on the fallback path", async () => { + for (const malformed of [[null], { invalid: true }]) { + const src = await sourceWith(malformed); + const usage = await src.usage(); + expect(usage.services.length).toBeGreaterThan(0); + expect(src.provenance().usage).toContain("dropped 1 malformed SaaS service row(s)"); + expect(src.provenance().usage).toContain("direct read"); + } + }); + + test("clean and collector-shaped services are unchanged with no diagnostic", async () => { + const collectorServices = extractSaasServices(VIEW); + expect(collectorServices.length).toBeGreaterThan(0); + expect(sanitizeSaasServices(collectorServices)).toEqual({ rows: collectorServices, dropped: 0 }); + const collectorFeed = await load(collectorServices); + expect(collectorFeed?.saas).toEqual(collectorServices); + expect(collectorFeed?.saasDropped).toBeUndefined(); + + const loaded = await load([VALID]); + expect(loaded?.saas).toEqual([VALID]); + expect(loaded?.saasDropped).toBeUndefined(); + const src = await sourceWith([VALID]); + await src.usage(); + expect(src.provenance().usage).not.toContain("sanitized at load"); + }); +});