Skip to content

Commit d5c69d3

Browse files
committed
fix(webview): validate the webview-supplied view state id before adopting it
The stable view state id arrives over the webview postMessage channel, so the declared string type is not a guarantee: a crafted message could carry a non-string value (which the sanitizer would crash on), an unbounded string (unbounded growth in the shared viewStates map), or an id another live view already owns (adopting it would load that view's pinned profile, overlay and mode here, and let this webview overwrite that view's persisted entry). setViewStateId now rejects non-strings, bounds the key length, and refuses ids claimed by another live instance; a refused view stays on its temporary id and keeps working against the shared state. The specs gain an afterEach that clears the static instance registry (the suites construct providers directly and never dispose most of them), and the three shared-view handoff tests now dispose the writer before the next view adopts the id - the ownership rule the writer released the id under is exactly what those tests assert, and the durable entry stays in storage across the handoff. Proofs: ClineProvider.sticky-mode.spec 33/33 (3 new tests: non-string, oversized, claimed-by-another-view), ClineProvider.spec 317/317, webviewMessageHandler.spec 92/92; negative controls: disabling the ownership check reddens exactly the claim test, widening the length bound reddens exactly the oversized test, restores byte-exact (hash match); eslint --max-warnings=0 clean; tsc clean except the two known local telemetry-dist noise lines; prettier ALL-MATCHED on touched files.
1 parent 67a9649 commit d5c69d3

3 files changed

Lines changed: 90 additions & 4 deletions

File tree

‎src/core/webview/ClineProvider.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ export class ClineProvider
259259
private static activeInstances: Set<ClineProvider> = new Set()
260260
private static nextViewId = 0
261261
private static readonly MAX_PERSISTED_VIEW_STATES = 50
262+
private static readonly MAX_VIEW_STATE_ID_LENGTH = 64
262263
private static persistedViewStateWriteQueue: Promise<void> = Promise.resolve()
263264
private disposables: vscode.Disposable[] = []
264265
private webviewDisposables: vscode.Disposable[] = []
@@ -716,7 +717,18 @@ export class ClineProvider
716717
* The identifier is sanitized so it remains a safe object key in the shared viewStates map.
717718
*/
718719
public async setViewStateId(viewStateId: string | undefined): Promise<void> {
719-
const normalizedViewStateId = viewStateId?.trim().replace(/[^A-Za-z0-9_-]/g, "_")
720+
// The webview generates this id on purpose - it has to survive a webview reload,
721+
// which recreates the view on both sides - so the host cannot mint it instead.
722+
// What the host owns is which view may hold a given persisted key, so everything
723+
// below validates the supplied value before it becomes one.
724+
if (typeof viewStateId !== "string") {
725+
// A crafted postMessage can carry any JSON value here even though the message
726+
// type declares a string; the persisted key must stay a string.
727+
this.log(`[setViewStateId] Ignoring a non-string viewStateId for view ${this.viewId}.`)
728+
return
729+
}
730+
731+
const normalizedViewStateId = viewStateId.trim().replace(/[^A-Za-z0-9_-]/g, "_")
720732

721733
if (
722734
!normalizedViewStateId ||
@@ -728,6 +740,29 @@ export class ClineProvider
728740
return
729741
}
730742

743+
// Bound the key: the webview generates a UUID, so a much longer value is not a
744+
// view id, and an unbounded key is unbounded growth in the shared viewStates map.
745+
if (normalizedViewStateId.length > ClineProvider.MAX_VIEW_STATE_ID_LENGTH) {
746+
this.log(
747+
`[setViewStateId] Ignoring an oversized viewStateId (${normalizedViewStateId.length} chars) for view ${this.viewId}.`,
748+
)
749+
return
750+
}
751+
752+
const claimant = ClineProvider.getAllInstances().find(
753+
(instance) => instance !== this && instance.viewStateId === normalizedViewStateId,
754+
)
755+
if (claimant) {
756+
// Ownership check: a key another live view holds must not be adopted. Doing so
757+
// would load that view's pinned profile, nested overlay, and mode into this
758+
// provider, and this webview could then overwrite that view's persisted entry.
759+
// Staying on the temporary id keeps this view working against the shared state.
760+
this.log(
761+
`[setViewStateId] Refusing viewStateId ${normalizedViewStateId} for view ${this.viewId}: already claimed by live view ${claimant.viewId}.`,
762+
)
763+
return
764+
}
765+
731766
const previousViewStateId = this.viewStateId
732767

733768
this.viewStateId = normalizedViewStateId

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,13 @@ describe("ClineProvider", () => {
501501
let mockPostMessage: any
502502
let updateGlobalStateSpy: any
503503

504+
afterEach(() => {
505+
// Tests construct providers directly and many never dispose them; clear the
506+
// static registry so a leaked instance cannot claim stable view state ids
507+
// ahead of a later test.
508+
ClineProvider["activeInstances"] = new Set()
509+
})
510+
504511
beforeEach(() => {
505512
vi.clearAllMocks()
506513

@@ -2275,6 +2282,10 @@ describe("ClineProvider", () => {
22752282
})
22762283
// @ts-ignore - Replace providerSettingsManager with a test double for the profile lookup.
22772284
provider.providerSettingsManager = { getProfile: getProfileSpy }
2285+
// The ownership check requires the writer to release the id before the
2286+
// next view adopts it; the durable entry it wrote stays in storage.
2287+
await writer.dispose()
2288+
22782289
await provider.contextProxy.setValue(
22792290
"viewStates",
22802291
mockContext.globalState.get<RooCodeSettings["viewStates"]>("viewStates"),
@@ -2287,7 +2298,6 @@ describe("ClineProvider", () => {
22872298
})
22882299
expect(getProfileSpy).toHaveBeenCalledWith({ name: "my-profile" })
22892300
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Loaded state for viewId"))
2290-
await writer.dispose()
22912301
await provider.dispose()
22922302
})
22932303

@@ -2415,6 +2425,10 @@ describe("ClineProvider", () => {
24152425
}
24162426
// A pre-load buffer write that was never persisted must not be merged over the load.
24172427
provider["viewLocalState"] = { mode: "architect" }
2428+
// The ownership check requires the writer to release the id before the
2429+
// next view adopts it; the durable entry it wrote stays in storage.
2430+
await writer.dispose()
2431+
24182432
await provider.contextProxy.setValue(
24192433
"viewStates",
24202434
mockContext.globalState.get<RooCodeSettings["viewStates"]>("viewStates"),
@@ -2426,7 +2440,6 @@ describe("ClineProvider", () => {
24262440
apiProvider: providerIdentifiers.openrouter,
24272441
openRouterModelId: "model-x",
24282442
})
2429-
await writer.dispose()
24302443
await provider.dispose()
24312444
})
24322445

@@ -2765,6 +2778,10 @@ describe("ClineProvider", () => {
27652778
getModeConfigId: vi.fn().mockResolvedValue(undefined),
27662779
}
27672780
vi.spyOn(provider, "postStateToWebview").mockResolvedValue(undefined)
2781+
// The ownership check requires the writer to release the id before the
2782+
// next view adopts it; the durable entry it wrote stays in storage.
2783+
await writer.dispose()
2784+
27682785
await provider.contextProxy.setValue(
27692786
"viewStates",
27702787
mockContext.globalState.get<RooCodeSettings["viewStates"]>("viewStates"),
@@ -2777,7 +2794,6 @@ describe("ClineProvider", () => {
27772794
// The buffer must track the activated profile so getValues() agrees with the proxy.
27782795
expect(provider.getValues().currentApiConfigName).toBe("new-profile")
27792796
expect(provider.contextProxy.getValue("currentApiConfigName")).toBe("new-profile")
2780-
await writer.dispose()
27812797
await provider.dispose()
27822798
})
27832799

‎src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ vi.mock("@roo-code/cloud", () => ({
121121
get instance() {
122122
return {
123123
isAuthenticated: vi.fn().mockReturnValue(false),
124+
on: vi.fn(),
125+
off: vi.fn(),
124126
}
125127
},
126128
},
@@ -1911,4 +1913,37 @@ describe("ClineProvider - Sticky Mode", () => {
19111913
})
19121914
})
19131915
})
1916+
1917+
describe("setViewStateId input validation", () => {
1918+
it("ignores a non-string viewStateId from a crafted message", async () => {
1919+
const before = provider["viewStateId"]
1920+
// A crafted postMessage can carry any JSON value despite the declared type.
1921+
await provider.setViewStateId(42 as unknown as string)
1922+
expect(provider["viewStateId"]).toBe(before)
1923+
})
1924+
1925+
it("ignores an oversized viewStateId", async () => {
1926+
const before = provider["viewStateId"]
1927+
await provider.setViewStateId("x".repeat(200))
1928+
expect(provider["viewStateId"]).toBe(before)
1929+
})
1930+
1931+
it("refuses a viewStateId already claimed by another live view", async () => {
1932+
const other = new ClineProvider(
1933+
mockContext,
1934+
mockOutputChannel,
1935+
"sidebar",
1936+
new ContextProxy(mockContext),
1937+
new WebviewFocusTracker(),
1938+
)
1939+
try {
1940+
await other.setViewStateId("claimed-by-other-view")
1941+
await provider.setViewStateId("claimed-by-other-view")
1942+
expect(provider["viewStateId"]).not.toBe("claimed-by-other-view")
1943+
expect(other["viewStateId"]).toBe("claimed-by-other-view")
1944+
} finally {
1945+
await other.dispose()
1946+
}
1947+
})
1948+
})
19141949
})

0 commit comments

Comments
 (0)