Skip to content

Commit e5cd3e0

Browse files
committed
fix(review): resolve pre-merge checks for security, persistence integrity, lifecycle, and tests
1 parent 894987d commit e5cd3e0

24 files changed

Lines changed: 314 additions & 90 deletions

File tree

‎packages/cloud/src/CloudSettingsService.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type UserFeatures,
1313
type UserSettingsConfig,
1414
type UserSettingsData,
15+
type CloudUserInfo,
1516
OrganizationAllowList,
1617
OrganizationSettings,
1718
organizationSettingsSchema,
@@ -23,6 +24,7 @@ import { getRooCodeApiUrl } from "./config.js"
2324
import { RefreshTimer } from "./RefreshTimer.js"
2425

2526
const ORGANIZATION_SETTINGS_CACHE_KEY = "organization-settings"
27+
const ORGANIZATION_ID_CACHE_KEY = "organization-settings-org-id"
2628
const USER_SETTINGS_CACHE_KEY = "user-settings"
2729

2830
const parseExtensionSettingsResponse = (data: unknown) => {
@@ -55,6 +57,7 @@ export class CloudSettingsService extends EventEmitter<SettingsServiceEvents> im
5557
private authService: AuthService
5658
private settings: OrganizationSettings | undefined = undefined
5759
private userSettings: UserSettingsData | undefined = undefined
60+
private currentOrganizationId: string | null = null
5861
private timer: RefreshTimer
5962
private log: (...args: unknown[]) => void
6063

@@ -99,6 +102,24 @@ export class CloudSettingsService extends EventEmitter<SettingsServiceEvents> im
99102
}
100103
})
101104

105+
this.authService.on("user-info", async (data: { userInfo: CloudUserInfo }) => {
106+
try {
107+
const newOrgId = data.userInfo?.organizationId || null
108+
if (newOrgId !== this.currentOrganizationId) {
109+
this.currentOrganizationId = newOrgId
110+
this.settings = undefined
111+
await this.context.globalState.update(ORGANIZATION_SETTINGS_CACHE_KEY, undefined)
112+
await this.context.globalState.update(ORGANIZATION_ID_CACHE_KEY, newOrgId)
113+
this.emit("settings-updated", {} as Record<string, never>)
114+
if (this.authService.hasActiveSession()) {
115+
await this.fetchSettings()
116+
}
117+
}
118+
} catch (error) {
119+
this.log(`[cloud-settings] error processing user-info: ${error}`, error)
120+
}
121+
})
122+
102123
if (this.authService.hasActiveSession()) {
103124
this.timer.start()
104125
}
@@ -170,24 +191,44 @@ export class CloudSettingsService extends EventEmitter<SettingsServiceEvents> im
170191
// Store settings in separate globalState values
171192
if (this.settings) {
172193
await this.context.globalState.update(ORGANIZATION_SETTINGS_CACHE_KEY, this.settings)
194+
await this.context.globalState.update(ORGANIZATION_ID_CACHE_KEY, this.currentOrganizationId)
173195
}
174196

175197
if (this.userSettings) {
176198
await this.context.globalState.update(USER_SETTINGS_CACHE_KEY, this.userSettings)
177199
}
178200
}
179201

202+
private getCurrentOrganizationId(): string | null {
203+
return this.authService.getUserInfo?.()?.organizationId || this.authService.getStoredOrganizationId?.() || null
204+
}
205+
180206
private loadCachedSettings(): void {
181-
// Load settings from separate globalState values
182207
this.settings = this.context.globalState.get<OrganizationSettings>(ORGANIZATION_SETTINGS_CACHE_KEY)
183208
this.userSettings = this.context.globalState.get<UserSettingsData>(USER_SETTINGS_CACHE_KEY)
209+
210+
const cachedOrgId = this.context.globalState.get<string | null>(ORGANIZATION_ID_CACHE_KEY) ?? null
211+
const currentOrgId = this.getCurrentOrganizationId()
212+
this.currentOrganizationId = currentOrgId
213+
214+
if (currentOrgId && cachedOrgId !== currentOrgId) {
215+
this.settings = undefined
216+
}
184217
}
185218

186219
public getAllowList(): OrganizationAllowList {
220+
const currentOrgId = this.getCurrentOrganizationId()
221+
if (currentOrgId && (!this.settings || this.currentOrganizationId !== currentOrgId)) {
222+
return { allowAll: false, providers: {} }
223+
}
187224
return this.settings?.allowList || ORGANIZATION_ALLOW_ALL
188225
}
189226

190227
public getSettings(): OrganizationSettings | undefined {
228+
const currentOrgId = this.getCurrentOrganizationId()
229+
if (currentOrgId && this.currentOrganizationId !== currentOrgId) {
230+
return undefined
231+
}
191232
return this.settings
192233
}
193234

@@ -287,6 +328,7 @@ export class CloudSettingsService extends EventEmitter<SettingsServiceEvents> im
287328

288329
// Clear both cache keys
289330
await this.context.globalState.update(ORGANIZATION_SETTINGS_CACHE_KEY, undefined)
331+
await this.context.globalState.update(ORGANIZATION_ID_CACHE_KEY, undefined)
290332
await this.context.globalState.update(USER_SETTINGS_CACHE_KEY, undefined)
291333
}
292334

‎packages/cloud/src/__tests__/CloudSettingsService.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ describe("CloudSettingsService", () => {
2121
hasActiveSession: ReturnType<typeof vi.fn>
2222
on: ReturnType<typeof vi.fn>
2323
getStoredOrganizationId: ReturnType<typeof vi.fn>
24+
getUserInfo?: ReturnType<typeof vi.fn>
2425
}
2526
let mockRefreshTimer: {
2627
start: ReturnType<typeof vi.fn>
@@ -535,6 +536,58 @@ describe("CloudSettingsService", () => {
535536
expect(mockContext.globalState.update).toHaveBeenCalledWith("organization-settings", undefined)
536537
expect(mockContext.globalState.update).toHaveBeenCalledWith("user-settings", undefined)
537538
})
539+
540+
it("should invalidate settings and return fail-closed allow list when user switches to another organization while refresh is pending", async () => {
541+
mockAuthService.getStoredOrganizationId = vi.fn().mockReturnValue("org-allow-all")
542+
mockAuthService.hasActiveSession = vi.fn().mockReturnValue(true)
543+
await cloudSettingsService.initialize()
544+
545+
// Cache initial settings for org-allow-all
546+
vi.mocked(fetch).mockResolvedValueOnce({
547+
ok: true,
548+
json: vi.fn().mockResolvedValue({
549+
organization: {
550+
version: 1,
551+
defaultSettings: {},
552+
allowList: { allowAll: true, providers: {} },
553+
},
554+
user: mockUserSettings,
555+
}),
556+
} as unknown as Response)
557+
558+
mockAuthService.getSessionToken = vi.fn().mockReturnValue("token")
559+
const timerCallback = vi.mocked(RefreshTimer).mock.calls[0]?.[0]?.callback
560+
await timerCallback?.()
561+
562+
expect(cloudSettingsService.getAllowList().allowAll).toBe(true)
563+
564+
// Get the user-info handler
565+
const userInfoHandler = mockAuthService.on.mock.calls.find((call: string[]) => call[0] === "user-info")?.[1]
566+
expect(userInfoHandler).toBeDefined()
567+
568+
// Mock fetch to simulate delayed/failed refresh for new organization
569+
vi.mocked(fetch).mockResolvedValueOnce({
570+
ok: false,
571+
status: 500,
572+
statusText: "Internal Server Error",
573+
} as unknown as Response)
574+
575+
// Switch to org-restricted
576+
mockAuthService.getStoredOrganizationId = vi.fn().mockReturnValue("org-restricted")
577+
mockAuthService.getUserInfo = vi.fn().mockReturnValue({ organizationId: "org-restricted" })
578+
579+
await userInfoHandler({
580+
userInfo: { organizationId: "org-restricted" },
581+
})
582+
583+
// Cached settings must be invalidated, getSettings returns undefined, and allowList fails closed
584+
expect(cloudSettingsService.getSettings()).toBeUndefined()
585+
expect(cloudSettingsService.getAllowList()).toEqual({
586+
allowAll: false,
587+
providers: {},
588+
})
589+
expect(mockContext.globalState.update).toHaveBeenCalledWith("organization-settings", undefined)
590+
})
538591
})
539592

540593
describe("isTaskSyncEnabled", () => {

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,56 @@ describe("ContextProxy", () => {
287287
expect(proxy.getGlobalState("mode")).toBe("test-mode")
288288
})
289289

290+
it("waits for delayed operations to settle before rejecting when an operation fails", async () => {
291+
let delayedOperationSettled = false
292+
const delayedPromise = new Promise<void>((resolve) => {
293+
setTimeout(() => {
294+
delayedOperationSettled = true
295+
resolve()
296+
}, 50)
297+
})
298+
299+
vi.spyOn(proxy, "setValue").mockImplementation((key) => {
300+
if (key === "apiModelId") {
301+
return Promise.reject(new Error("Failed to write apiModelId"))
302+
}
303+
if (key === "mode") {
304+
return delayedPromise
305+
}
306+
return Promise.resolve()
307+
})
308+
309+
await expect(
310+
proxy.setValues({
311+
apiModelId: "gpt-4",
312+
mode: "test-mode",
313+
}),
314+
).rejects.toThrow("Failed to write apiModelId")
315+
316+
expect(delayedOperationSettled).toBe(true)
317+
})
318+
319+
it("throws the first rejection in input order when multiple operations fail", async () => {
320+
vi.spyOn(proxy, "setValue").mockImplementation((key) => {
321+
if (key === "apiModelId") {
322+
return new Promise((_, reject) =>
323+
setTimeout(() => reject(new Error("First error: apiModelId")), 30),
324+
)
325+
}
326+
if (key === "mode") {
327+
return new Promise((_, reject) => setTimeout(() => reject(new Error("Second error: mode")), 10))
328+
}
329+
return Promise.resolve()
330+
})
331+
332+
await expect(
333+
proxy.setValues({
334+
apiModelId: "gpt-4",
335+
mode: "test-mode",
336+
}),
337+
).rejects.toThrow("First error: apiModelId")
338+
})
339+
290340
it("should handle both secret and global state keys", async () => {
291341
// Spy on storeSecret and updateGlobalState
292342
const storeSecretSpy = vi.spyOn(proxy, "storeSecret")

0 commit comments

Comments
 (0)