Skip to content

Commit 492cfb3

Browse files
fix(config): refuse secret writes during a reset and clear the guard when it fails
This branch had no write guard at all. There was no reset flag, storeSecret() had nothing telling it a reset was in progress, and resetAllState() cleared the two caches, advanced the state-write generations, deleted every global-state and secret key in a single Promise.all and reinitialized - with the success path as the only path. So a save issued while a reset was still inside its deletes could land after the deletes and put back a value the user had just erased. This commit introduces that guard; it is not repairing an existing one, and a reviewer reading this PR should read the refusal as new behaviour rather than as a bug fix to code that already refused writes. What lands: a resetting field, a rejection at the top of storeSecret() (SettingsWriteError with the key in failed, so a caller can tell a refused save from a committed one), resetting raised as the first statement of resetAllState() and lowered in a finally wrapping the whole body. The body itself is unchanged: this lineage has no pending-write barrier and no write-owner clears, and importing #2235's would have imported a different unit's design rather than answering this unit's defect. Two cases, because the guard has two halves and the refusal is the new observable on this branch, so it is tested on its own rather than as a phase of the leak case: - refuses a secret write issued while a reset is still inside its delete pass - accepts a secret write again after a reset whose delete pass rejected Assertions read captured call arguments (mockSecrets.store.mock.calls filtered on the key) and the cache and storage read-backs, not toHaveBeenCalledWith: that matcher compares the way toEqual does and drops undefined-valued keys, so a loose matcher would pass on a tree where nothing is refused at all. Controls, measured in four steps rather than described. Baseline at 509f92c: Test Files 10 passed (10), Tests 318 passed (318). Refusal case alone with production untouched: 1 failed | 318 passed (319), AssertionError: expected undefined to be an instance of SettingsWriteError - with no refusal the mid-reset save simply succeeds. Guard and refusal with the flag lowered only on the success path: 10 passed (10), 319 passed (319), which is the shape this branch would have had if the flag were added without a finally. Leak case then added against exactly that shape - the negative control for the finally - fails 1 of 320 with the production consequence in the message: promise rejected "SettingsWriteError: Could not store apiKey: secret writes are refused while state is being reset" instead of resolving. With the try/finally: Test Files 10 passed (10), Tests 320 passed (320), identical before and after prettier. gates: tsc -p . --noEmit exit 0, eslint --max-warnings=0 --no-warn-ignored on both files exit 0, and the recorded suppression counts for the two touched files are unchanged at 1 and 5 across a --prune-suppressions run; prettier --check exit 0 on the working copies and exit 0 on the HEAD copies fed through the same invocation, so a format failure here would be this commit's. src/eslint-suppressions.json untouched. Size posture, with the pair printed rather than recalled. scripts/stryker-diff.mjs ci --base e943530 (main's tip, this PR's recorded base) --head 509f92c (this commit's parent) reports the extension bucket at 500 changed executable lines - exactly at MAX_CHANGED_LINES 500, with nothing to spare before this commit. The same command on the head being pushed here reports 518, so this commit is what starts the gate failing on #2236 rather than a commit continuing a failure the branch already had. The diff is 28 added / 14 deleted in src/core/config/ContextProxy.ts plus 69 lines in its spec, and the spec half is excluded from the bucket by the /__tests__/ segment at scripts/stryker-diff.mjs:85. Neither run could start Stryker locally (spawnSync node_modules\.bin\stryker ENOENT for both packages), so no mutants were scored here and only the size line is a real measurement; it belongs in the PR body or the maintainers' queue rather than being argued in a commit on a branch declared final. This is not an answer to a review row on this PR: the one live row here (ClineProvider.ts:5024, root comment 4477459238) is a custom-modes write-path question and is being read against this head separately. It ports the answer measured on vps2/n2-viewstates-durability for the same defect in this file so that the three sibling units do not ship three different answers to one bug.
1 parent 509f92c commit 492cfb3

2 files changed

Lines changed: 97 additions & 14 deletions

File tree

‎src/core/config/ContextProxy.ts‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@ export class ContextProxy {
8686
private stateWriteGenerations = new Map<GlobalStateKey, number>()
8787
private secretCache: SecretState
8888
private _isInitialized = false
89+
// Raised for the whole duration of a reset and cleared in a finally, so a reset that fails
90+
// mid-way cannot leave the store refusing every later secret write; see resetAllState.
91+
private resetting = false
8992

9093
constructor(context: vscode.ExtensionContext) {
9194
this.originalContext = context
@@ -486,6 +489,13 @@ export class ContextProxy {
486489
}
487490

488491
storeSecret(key: SecretStateKey, value?: string) {
492+
// Refused rather than deferred: a deferred secret write would re-store exactly the value the
493+
// user asked to erase, and a silently dropped one would lose the save.
494+
if (this.resetting) {
495+
return Promise.reject(
496+
new SettingsWriteError([], [key], new Error("secret writes are refused while state is being reset")),
497+
)
498+
}
489499
// Update cache.
490500
const owner = {}
491501
this.secretWriteOwner.set(key, owner)
@@ -759,22 +769,26 @@ export class ContextProxy {
759769
* @returns A promise that resolves when all reset operations are complete
760770
*/
761771
public async resetAllState() {
762-
// Clear in-memory caches
763-
this.stateCache = {}
764-
this.secretCache = {}
765-
// A write that started before this reset must not restore its pre-reset value when it
766-
// rejects afterwards, so advance every generation the pending writes still hold.
767-
for (const key of this.stateWriteGenerations.keys()) {
768-
this.stateWriteGenerations.set(key, (this.stateWriteGenerations.get(key) ?? 0) + 1)
769-
}
772+
this.resetting = true
773+
try {
774+
this.stateCache = {}
775+
this.secretCache = {}
776+
// A write that started before this reset must not restore its pre-reset value when it
777+
// rejects afterwards, so advance every generation the pending writes still hold.
778+
for (const key of this.stateWriteGenerations.keys()) {
779+
this.stateWriteGenerations.set(key, (this.stateWriteGenerations.get(key) ?? 0) + 1)
780+
}
770781

771-
await Promise.all([
772-
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
773-
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
774-
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
775-
])
782+
await Promise.all([
783+
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
784+
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
785+
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
786+
])
776787

777-
await this.initialize()
788+
await this.initialize()
789+
} finally {
790+
this.resetting = false
791+
}
778792
}
779793

780794
private static _instance: ContextProxy | null = null

‎src/core/config/__tests__/ContextProxy.spec.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,75 @@ describe("ContextProxy", () => {
162162
// that storage no longer holds.
163163
expect(proxy.getGlobalState("apiProvider")).toBeUndefined()
164164
})
165+
// This branch carried no write guard at all before these two cases: resetAllState cleared the
166+
// caches and deleted storage with nothing telling storeSecret that a reset was running, so a
167+
// save issued mid-reset could land after the deletes and resurrect a value the user had just
168+
// erased. The refusal is the new observable here rather than an existing one, so it gets its
169+
// own case instead of being a phase of the leak case.
170+
it("refuses a secret write issued while a reset is still inside its delete pass", async () => {
171+
const erases: { reject: (error: Error) => void }[] = []
172+
mockSecrets.delete.mockImplementation((key: string) => {
173+
if (key === "apiKey") {
174+
return new Promise<void>((_, reject) => {
175+
erases.push({ reject })
176+
})
177+
}
178+
return Promise.resolve()
179+
})
180+
181+
const resetting = proxy.resetAllState()
182+
// The reset yields before it reaches its delete pass, so let it get there before asking the
183+
// store to write.
184+
await new Promise<void>((resolve) => {
185+
setTimeout(resolve, 10)
186+
})
187+
expect(erases.length).toBe(1)
188+
189+
const refused = await proxy.storeSecret("apiKey", "saved-mid-reset").then(
190+
() => undefined,
191+
(error: unknown) => error,
192+
)
193+
expect(refused).toBeInstanceOf(SettingsWriteError)
194+
expect(String((refused as Error).message)).toContain("secret writes are refused while state is being reset")
195+
// Refused rather than deferred: a deferred write would re-store the value this reset is
196+
// in the middle of erasing.
197+
// Refused rather than deferred, and not silently written either: the cache the reset already
198+
// cleared stays empty and no store call was made for the key.
199+
expect(proxy.getSecret("apiKey")).toBeUndefined()
200+
expect(mockSecrets.store.mock.calls.filter((call: readonly unknown[]) => call[0] === "apiKey").length).toBe(
201+
0,
202+
)
203+
204+
erases.forEach((erase) => {
205+
erase.reject(new Error("keychain locked"))
206+
})
207+
await expect(resetting).rejects.toThrow("keychain locked")
208+
})
209+
it("accepts a secret write again after a reset whose delete pass rejected", async () => {
210+
const durable = new Map<string, string | undefined>()
211+
mockSecrets.get.mockImplementation(async (key: string) => durable.get(key))
212+
mockSecrets.store.mockImplementation(async (key: string, value: string) => {
213+
durable.set(key, value)
214+
})
215+
mockSecrets.delete.mockImplementation(async (key: string) => {
216+
if (key === "apiKey") {
217+
throw new Error("keychain locked")
218+
}
219+
durable.delete(key)
220+
})
221+
222+
await expect(proxy.resetAllState()).rejects.toThrow("keychain locked")
223+
224+
// The half that bites: the delete pass is a single Promise.all, so one keychain rejection
225+
// rejects resetAllState itself. Unless the guard is lowered on that path too, every later
226+
// save is refused for the life of the instance while resetState() has already aborted on the
227+
// same error, so the user cannot get a key back without restarting the extension host.
228+
// Measured as a save that resolves and reads back through storage and cache, not as an
229+
// absence of errors.
230+
await expect(proxy.storeSecret("apiKey", "written-after-failed-reset")).resolves.toBeUndefined()
231+
expect(await mockSecrets.get("apiKey")).toBe("written-after-failed-reset")
232+
expect(proxy.getSecret("apiKey")).toBe("written-after-failed-reset")
233+
})
165234

166235
it("should bypass cache for pass-through state keys", async () => {
167236
// Setup mock return value

0 commit comments

Comments
 (0)