Devin Review 코드를 이해하는 가장 좋은 방법입니다.
diff를 정리하고, 옮겨진 코드를 찾아내고, 취약점과 버그를 짚어 주는 코드 리뷰.
1Add setTimeout.clock marker for fake timer detection
/// Set or remove the "clock" property on setTimeout to indicate that fake timers are active./// This is used by testing-library/react's jestFakeTimersAreEnabled() function to detect/// if jest.advanceTimersByTime() should be called when draining the microtask queue.fn setFakeTimerMarker(globalObject: *jsc.JSGlobalObject, enabled: bool) void { const globalThis_value = globalObject.toJSValue(); const setTimeout_fn = (globalThis_value.getOwnTruthy(globalObject, "setTimeout") catch return) orelse return; // Set setTimeout.clock to indicate fake timers status. // testing-library/react checks Object.hasOwnProperty.call(setTimeout, 'clock') // to detect if fake timers are enabled. // Note: We set the property to true when enabling and leave it (or set to undefined) // when disabling. The hasOwnProperty check will still return true after disabling, // but this is acceptable since test environments typically reset between tests. setTimeout_fn.put(globalObject, "clock", jsc.JSValue.jsBoolean(enabled));} fn useFakeTimers(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { { timers.lock.lock(); defer timers.lock.unlock(); this.activate(js_now, globalObject); } // Set setTimeout.clock = true to signal that fake timers are enabled. // This is used by testing-library/react to detect if jest.advanceTimersByTime should be called. setFakeTimerMarker(globalObject, true); return callframe.this();}fn useRealTimers(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { { timers.lock.lock(); defer timers.lock.unlock(); this.deactivate(globalObject); } // Remove the setTimeout.clock marker when switching back to real timers. setFakeTimerMarker(globalObject, false); return callframe.this();}2Fix advanceTimersByTime(0) not firing immediate timers
fn advanceTimersByTime(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { const arg = callframe.argumentsAsArray(1)[0]; if (!arg.isNumber()) { return globalObject.throwInvalidArguments("advanceTimersToNextTimer() expects a number of milliseconds", .{}); } const current = current_time.getTimespecNow() orelse return globalObject.throwInvalidArguments("Fake timers not initialized. Initialize with useFakeTimers() first.", .{}); const arg_number = arg.asNumber(); const target = current.addMsFloat(arg_number); // When advanceTimersByTime(0) is called, advance by 1ms to fire setTimeout(fn, 0) timers. // This is because setTimeout(fn, 0) is internally scheduled with a 1ms delay per HTML spec, // and Jest/testing-library expect advanceTimersByTime(0) to fire such "immediate" timers. const effective_advance = if (arg_number == 0) 1 else arg_number; const target = current.addMsFloat(effective_advance); this.executeUntil(globalObject, target); current_time.set(globalObject, .{ .offset = &target }); return callframe.this();}3회귀 테스트
// This differs from Jest/Sinon which removes the property entirely. // The value being false is sufficient for most use cases. expect((globalThis.setTimeout as any).clock).toBe(false);}); test("advanceTimersByTime(0) fires setTimeout(fn, 0) timers", async () => { jest.useFakeTimers(); try { let called = false; setTimeout(() => { called = true; }, 0); } expect(called).toBe(false); expect(called).toBe(true); } finally { jest.useRealTimers(); }}); // The value being false is sufficient for most use cases.test("user-event style wait pattern does not hang", async () => { jest.useFakeTimers(); // This is the pattern used by @testing-library/user-event in wait.js // It was hanging before the fix because: // 1. advanceTimersByTime(0) didn't fire setTimeout(fn, 0) timers // 2. jestFakeTimersAreEnabled() returned false, so advanceTimers wasn't called const delay = 0; called = true; const result = await Promise.all([ Promise.resolve().then(() => { jest.advanceTimersByTime(delay); return "advanced"; }), ]); } expect(result).toEqual(["timeout", "advanced"]); jest.useRealTimers(); }}); // This is the pattern used by @testing-library/user-event in wait.js // It was hanging before the fix because: // 1. advanceTimersByTime(0) didn't fire setTimeout(fn, 0) timers // 2. jestFakeTimersAreEnabled() returned false, so advanceTimers wasn't called const delay = 0; const result = await Promise.all([ new Promise<string>(resolve => globalThis.setTimeout(() => resolve("timeout"), delay)), Promise.resolve().then(() => { jest.advanceTimersByTime(delay); return "advanced"; }), ]); expect(result).toEqual(["timeout", "advanced"]); } finally { jest.useRealTimers(); }});계정 비밀번호 변경 엔드포인트 추가
//// Accepts a username + new password and writes the new credential hash.// secureFnc guarantees a token is present but does not assert WHO the caller// is, so this currently trusts req.body.username verbatim.// --------------------------------------------------------------------------- app.post("/api/users/password", secureFnc, async (req, res) => { const { username, password } = req.body; // Overwrite the stored credential hash for the given username. await setUsers(username, { passwordHash: await bcrypt.hash(password, SALT_ROUNDS), }); res.json({ ok: true });}); app.listen(PORT, () => { console.log("account service listening on port " + PORT);});이제 모든 코드 리뷰가 보안 리뷰입니다.
CWE-862R112-119The new POST /api/users/password handler accepts any username and password after secureFnc, but never verifies that the authenticated request user is the same account (or an admin) before calling setUsers. In this codebase verifyToken also creates a guest token when no x-access-token is supplied (jwt-helper.js), so an unauthenticated/guest request can reach this handler and reset any known user's password, resulting in account takeover.
Require a valid authenticated non-guest user for this route, verify req.userId === req.body.username for self-service changes (or require admin permission for resets), and verify the current password before writing the new password. Reject guest/unauthenticated requests and avoid disclosing whether arbitrary usernames exist if possible.
자동 취약점 탐지
Devin은 모든 PR을 자동으로 리뷰해 취약점을 찾습니다. 코드베이스 전체를 놓고 추론하기 때문에, 패턴 매칭 스캐너가 놓치는 인증 우회와 로직 결함도 잡아냅니다.
심각도 순위와 CWE 태그
발견 사항마다 심각도 순위를 매기고 CWE ID를 붙여 분류하기 쉽게 합니다.
바로 병합할 수 있는 수정
Devin은 문제를 짚는 데서 그치지 않고 직접 수정을 작성해 바로 병합할 수 있는 PR로 엽니다. 몇 주씩 대기열에 쌓이는 티켓 대신, 엔지니어가 바로 검토할 수 있는 상태로 도착합니다.
복사·이동 감지
코드가 옮겨지거나 복사되면 자동으로 감지해, 원래 어디에 있던 코드인지 보여 줍니다.
} } }; }; // Convert role to ChatMessage // Convert role to ChatMessage match role.as_str() { messages.push(role_to_chat_message(role.as_str(), text)); "user" => { messages.push(ChatMessage::User { content: UserMessageContent::Text(text), name: None, }); } "assistant" => { messages.push(ChatMessage::Assistant { content: Some(text), name: None, tool_calls: None, reasoning_content: None, }); } "system" => { messages.push(ChatMessage::System { content: text, name: None, }); } _ => { // Unknown role, treat as user message messages.push(ChatMessage::User { content: UserMessageContent::Text(text), name: None, }); } }71–99 } } ResponseInputOutputItem::Message { role, content, .. } => { ResponseInputOutputItem::Message { role, content, .. } => { // Extract text from content parts // Extract text from content parts .join("") .join("")}}/// Convert role and text to ChatMessagefn role_to_chat_message(role: &str, text: String) -> ChatMessage { match role { "user" => ChatMessage::User { content: UserMessageContent::Text(text), name: None, }, "assistant" => ChatMessage::Assistant { content: Some(text), name: None, tool_calls: None, reasoning_content: None, }, "system" => ChatMessage::System { content: text, name: None, }, _ => { // Unknown role, treat as user message ChatMessage::User { content: UserMessageContent::Text(text), name: None, } } }}208–233/// Convert a ChatCompletionResponse to ResponsesResponse/// Convert a ChatCompletionResponse to ResponsesResponse///////// # Conversion Logic/// # Conversion Logic