Base: codex-main originale (prima del fork aKode)
This commit is contained in:
1275
codex-rs/tui/src/ide_context/ipc.rs
Normal file
1275
codex-rs/tui/src/ide_context/ipc.rs
Normal file
File diff suppressed because it is too large
Load Diff
372
codex-rs/tui/src/ide_context/prompt.rs
Normal file
372
codex-rs/tui/src/ide_context/prompt.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
//! Prompt rendering for IDE context injected into TUI user turns.
|
||||
|
||||
use codex_app_server_protocol::UserInput;
|
||||
|
||||
use super::IdeContext;
|
||||
|
||||
const MAX_ACTIVE_SELECTION_CHARS: usize = 40_000;
|
||||
const MAX_OPEN_TABS: usize = 100;
|
||||
const MAX_OPEN_TABS_CHARS: usize = 20_000;
|
||||
|
||||
pub(crate) fn apply_ide_context_to_user_input(
|
||||
context: &IdeContext,
|
||||
items: &mut Vec<UserInput>,
|
||||
) -> bool {
|
||||
let Some(context_text) = render_prompt_context(context) else {
|
||||
return false;
|
||||
};
|
||||
crate::user_prompt::apply_prompt_context_to_user_input(&context_text, items);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn has_prompt_context(context: &IdeContext) -> bool {
|
||||
render_prompt_context(context).is_some()
|
||||
}
|
||||
|
||||
fn render_prompt_context(context: &IdeContext) -> Option<String> {
|
||||
let mut ide_context_section = String::new();
|
||||
|
||||
if let Some(active_file) = &context.active_file {
|
||||
ide_context_section.push_str(&format!(
|
||||
"\n## Active file: {}\n",
|
||||
active_file.descriptor.path
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(active_file) = &context.active_file {
|
||||
let selected_ranges = if active_file.selections.is_empty() {
|
||||
std::slice::from_ref(&active_file.selection)
|
||||
} else {
|
||||
active_file.selections.as_slice()
|
||||
}
|
||||
.iter()
|
||||
.filter(|range| range.start != range.end)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !selected_ranges.is_empty()
|
||||
&& (active_file.active_selection_content.is_empty() || selected_ranges.len() > 1)
|
||||
{
|
||||
if selected_ranges.len() == 1 {
|
||||
ide_context_section.push_str("\n## Active selection range:\n");
|
||||
} else {
|
||||
ide_context_section.push_str("\n## Active selection ranges:\n");
|
||||
}
|
||||
for range in selected_ranges {
|
||||
// Render ranges as 1-based positions for the prompt.
|
||||
let start_line = range.start.line + 1;
|
||||
let start_column = range.start.character + 1;
|
||||
let end_line = range.end.line + 1;
|
||||
let end_column = range.end.character + 1;
|
||||
ide_context_section.push_str(&format!(
|
||||
"- {}: line {start_line}, column {start_column} to line {end_line}, column {end_column}\n",
|
||||
active_file.descriptor.path
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(active_file) = &context.active_file
|
||||
&& !active_file.active_selection_content.is_empty()
|
||||
{
|
||||
ide_context_section.push_str("\n## Active selection of the file:\n");
|
||||
let selection = active_file.active_selection_content.as_str();
|
||||
if let Some((truncate_at, _)) = selection.char_indices().nth(MAX_ACTIVE_SELECTION_CHARS) {
|
||||
ide_context_section.push_str(&selection[..truncate_at]);
|
||||
ide_context_section.push_str(&format!(
|
||||
"\n[Selection truncated to {MAX_ACTIVE_SELECTION_CHARS} characters.]\n"
|
||||
));
|
||||
} else {
|
||||
ide_context_section.push_str(selection);
|
||||
}
|
||||
}
|
||||
|
||||
if !context.open_tabs.is_empty() {
|
||||
ide_context_section.push_str("\n## Open tabs:\n");
|
||||
let mut rendered_tabs = 0;
|
||||
let mut rendered_tab_chars = 0;
|
||||
for tab in &context.open_tabs {
|
||||
if rendered_tabs >= MAX_OPEN_TABS {
|
||||
break;
|
||||
}
|
||||
|
||||
let tab_line = format!("- {}: {}\n", tab.label, tab.path);
|
||||
if rendered_tab_chars + tab_line.len() > MAX_OPEN_TABS_CHARS {
|
||||
break;
|
||||
}
|
||||
|
||||
ide_context_section.push_str(&tab_line);
|
||||
rendered_tabs += 1;
|
||||
rendered_tab_chars += tab_line.len();
|
||||
}
|
||||
|
||||
let omitted_tabs = context.open_tabs.len() - rendered_tabs;
|
||||
if omitted_tabs > 0 {
|
||||
ide_context_section.push_str(&format!("[{omitted_tabs} open tabs omitted.]\n"));
|
||||
}
|
||||
}
|
||||
|
||||
if ide_context_section.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(format!(
|
||||
"# Context from my IDE setup:\n{ide_context_section}"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::ActiveFile;
|
||||
use super::super::FileDescriptor;
|
||||
use super::super::IdeContext;
|
||||
use super::super::Position;
|
||||
use super::super::Range;
|
||||
use super::*;
|
||||
use codex_app_server_protocol::ByteRange;
|
||||
use codex_app_server_protocol::TextElement;
|
||||
use codex_protocol_test_support::ContentItemTestExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn descriptor(label: &str, path: &str) -> FileDescriptor {
|
||||
FileDescriptor {
|
||||
label: label.to_string(),
|
||||
path: path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_question_reply_stays_recognizable_with_ide_context() {
|
||||
use codex_context_fragments::AnsweredQuestion;
|
||||
use codex_context_fragments::ContextualUserFragment;
|
||||
|
||||
let context = IdeContext {
|
||||
active_file: None,
|
||||
open_tabs: vec![descriptor("lib.rs", "src/lib.rs")],
|
||||
};
|
||||
let mut expected = vec![
|
||||
UserInput::Text {
|
||||
text: AnsweredQuestion::new(
|
||||
"question-id",
|
||||
"Where?",
|
||||
"Staging\n## My request for Codex:\nKeep this literal",
|
||||
)
|
||||
.render()
|
||||
.expect_text(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
UserInput::Skill {
|
||||
name: "route".into(),
|
||||
path: std::path::PathBuf::from("route/SKILL.md"),
|
||||
},
|
||||
];
|
||||
let mut items = expected.clone();
|
||||
let replies = crate::async_question_reply::parse_input(&items);
|
||||
let display = crate::chatwidget::ChatWidget::user_message_display_from_inputs(&items);
|
||||
assert_eq!(
|
||||
display.message,
|
||||
"> Where?\n\nStaging\n## My request for Codex:\nKeep this literal"
|
||||
);
|
||||
let UserInput::Text { text, .. } = &mut expected[0] else {
|
||||
panic!("reply text");
|
||||
};
|
||||
*text = format!(
|
||||
"# Context from my IDE setup:\n\n## Open tabs:\n- lib.rs: src/lib.rs\n\n## My request for Codex:\n{text}"
|
||||
);
|
||||
assert!(apply_ide_context_to_user_input(&context, &mut items));
|
||||
assert_eq!(items, expected);
|
||||
assert_eq!(crate::async_question_reply::parse_input(&items), replies);
|
||||
assert_eq!(
|
||||
crate::chatwidget::ChatWidget::user_message_display_from_inputs(&items),
|
||||
display
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_prompt_context_matches_app_format() {
|
||||
let context = IdeContext {
|
||||
active_file: Some(ActiveFile {
|
||||
descriptor: descriptor("lib.rs", "src/lib.rs"),
|
||||
selection: Range {
|
||||
start: Position {
|
||||
line: 4,
|
||||
character: 0,
|
||||
},
|
||||
end: Position {
|
||||
line: 6,
|
||||
character: 1,
|
||||
},
|
||||
},
|
||||
active_selection_content: "fn selected() {}".to_string(),
|
||||
selections: Vec::new(),
|
||||
}),
|
||||
open_tabs: vec![
|
||||
descriptor("lib.rs", "src/lib.rs"),
|
||||
descriptor("main.rs", "src/main.rs"),
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
render_prompt_context(&context),
|
||||
Some(
|
||||
"# Context from my IDE setup:\n\n## Active file: src/lib.rs\n\n## Active selection of the file:\nfn selected() {}\n## Open tabs:\n- lib.rs: src/lib.rs\n- main.rs: src/main.rs\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_prompt_context_omits_empty_context() {
|
||||
let context = IdeContext {
|
||||
active_file: None,
|
||||
open_tabs: Vec::new(),
|
||||
};
|
||||
|
||||
assert_eq!(render_prompt_context(&context), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_ide_context_uses_desktop_prompt_request_delimiter() {
|
||||
let context = IdeContext {
|
||||
active_file: Some(ActiveFile {
|
||||
descriptor: descriptor("lib.rs", "src/lib.rs"),
|
||||
selection: Range {
|
||||
start: Position {
|
||||
line: 0,
|
||||
character: 0,
|
||||
},
|
||||
end: Position {
|
||||
line: 0,
|
||||
character: 0,
|
||||
},
|
||||
},
|
||||
active_selection_content: String::new(),
|
||||
selections: Vec::new(),
|
||||
}),
|
||||
open_tabs: Vec::new(),
|
||||
};
|
||||
let text = "Ask $figma".to_string();
|
||||
let mut items = vec![
|
||||
UserInput::LocalImage {
|
||||
path: PathBuf::from("/tmp/screenshot.png"),
|
||||
detail: None,
|
||||
},
|
||||
UserInput::Text {
|
||||
text,
|
||||
text_elements: vec![TextElement::new(
|
||||
ByteRange { start: 4, end: 10 },
|
||||
Some("$figma".to_string()),
|
||||
)],
|
||||
},
|
||||
];
|
||||
|
||||
assert!(apply_ide_context_to_user_input(&context, &mut items));
|
||||
|
||||
let expected_prefix = "# Context from my IDE setup:\n\n## Active file: src/lib.rs\n\n## My request for Codex:\n";
|
||||
let prefix_len = expected_prefix.len();
|
||||
assert_eq!(
|
||||
items,
|
||||
vec![
|
||||
UserInput::LocalImage {
|
||||
path: PathBuf::from("/tmp/screenshot.png"),
|
||||
detail: None,
|
||||
},
|
||||
UserInput::Text {
|
||||
text: format!("{expected_prefix}Ask $figma"),
|
||||
text_elements: vec![TextElement::new(
|
||||
ByteRange {
|
||||
start: prefix_len + 4,
|
||||
end: prefix_len + 10,
|
||||
},
|
||||
Some("$figma".to_string()),
|
||||
)],
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_prompt_context_includes_selection_ranges_without_content() {
|
||||
let first_range = Range {
|
||||
start: Position {
|
||||
line: 1,
|
||||
character: 2,
|
||||
},
|
||||
end: Position {
|
||||
line: 1,
|
||||
character: 5,
|
||||
},
|
||||
};
|
||||
let second_range = Range {
|
||||
start: Position {
|
||||
line: 3,
|
||||
character: 0,
|
||||
},
|
||||
end: Position {
|
||||
line: 4,
|
||||
character: 1,
|
||||
},
|
||||
};
|
||||
let context = IdeContext {
|
||||
active_file: Some(ActiveFile {
|
||||
descriptor: descriptor("lib.rs", "src/lib.rs"),
|
||||
selection: first_range.clone(),
|
||||
active_selection_content: String::new(),
|
||||
selections: vec![first_range, second_range],
|
||||
}),
|
||||
open_tabs: Vec::new(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
render_prompt_context(&context),
|
||||
Some(
|
||||
"# Context from my IDE setup:\n\n## Active file: src/lib.rs\n\n## Active selection ranges:\n- src/lib.rs: line 2, column 3 to line 2, column 6\n- src/lib.rs: line 4, column 1 to line 5, column 2\n"
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_prompt_context_truncates_large_selection() {
|
||||
let context = IdeContext {
|
||||
active_file: Some(ActiveFile {
|
||||
descriptor: descriptor("large.txt", "large.txt"),
|
||||
selection: Range {
|
||||
start: Position {
|
||||
line: 0,
|
||||
character: 0,
|
||||
},
|
||||
end: Position {
|
||||
line: 0,
|
||||
character: 1,
|
||||
},
|
||||
},
|
||||
active_selection_content: format!("{}tail", "a".repeat(MAX_ACTIVE_SELECTION_CHARS)),
|
||||
selections: Vec::new(),
|
||||
}),
|
||||
open_tabs: Vec::new(),
|
||||
};
|
||||
|
||||
let rendered = render_prompt_context(&context).expect("rendered IDE context");
|
||||
assert!(rendered.contains(&format!(
|
||||
"[Selection truncated to {MAX_ACTIVE_SELECTION_CHARS} characters.]"
|
||||
)));
|
||||
assert!(!rendered.contains("tail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_prompt_context_omits_excess_open_tabs() {
|
||||
let open_tabs = (0..MAX_OPEN_TABS + 2)
|
||||
.map(|index| descriptor(&format!("file-{index}.rs"), &format!("src/file-{index}.rs")))
|
||||
.collect::<Vec<_>>();
|
||||
let context = IdeContext {
|
||||
active_file: None,
|
||||
open_tabs,
|
||||
};
|
||||
|
||||
let rendered = render_prompt_context(&context).expect("rendered IDE context");
|
||||
assert!(rendered.contains("- file-99.rs: src/file-99.rs\n"));
|
||||
assert!(!rendered.contains("- file-100.rs: src/file-100.rs\n"));
|
||||
assert!(rendered.contains("[2 open tabs omitted.]\n"));
|
||||
}
|
||||
}
|
||||
337
codex-rs/tui/src/ide_context/windows_pipe.rs
Normal file
337
codex-rs/tui/src/ide_context/windows_pipe.rs
Normal file
@@ -0,0 +1,337 @@
|
||||
//! Windows named-pipe transport for the IDE context IPC client.
|
||||
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
use std::time::Instant;
|
||||
|
||||
use windows_sys::Win32::Foundation::ERROR_IO_PENDING;
|
||||
use windows_sys::Win32::Foundation::ERROR_NOT_FOUND;
|
||||
use windows_sys::Win32::Foundation::GENERIC_READ;
|
||||
use windows_sys::Win32::Foundation::GENERIC_WRITE;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::Foundation::WAIT_FAILED;
|
||||
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
|
||||
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
|
||||
use windows_sys::Win32::Security::EqualSid;
|
||||
use windows_sys::Win32::Security::GetTokenInformation;
|
||||
use windows_sys::Win32::Security::TOKEN_QUERY;
|
||||
use windows_sys::Win32::Security::TOKEN_USER;
|
||||
use windows_sys::Win32::Security::TokenUser;
|
||||
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OVERLAPPED;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
|
||||
use windows_sys::Win32::Storage::FileSystem::ReadFile;
|
||||
use windows_sys::Win32::Storage::FileSystem::SECURITY_IDENTIFICATION;
|
||||
use windows_sys::Win32::Storage::FileSystem::SECURITY_SQOS_PRESENT;
|
||||
use windows_sys::Win32::Storage::FileSystem::WriteFile;
|
||||
use windows_sys::Win32::System::IO::CancelIoEx;
|
||||
use windows_sys::Win32::System::IO::GetOverlappedResult;
|
||||
use windows_sys::Win32::System::IO::OVERLAPPED;
|
||||
use windows_sys::Win32::System::Pipes::GetNamedPipeServerProcessId;
|
||||
use windows_sys::Win32::System::Threading::CreateEventW;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcessToken;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
use windows_sys::Win32::System::Threading::WaitForSingleObject;
|
||||
use windows_sys::core::BOOL;
|
||||
|
||||
const TRUE: BOOL = 1;
|
||||
const FALSE: BOOL = 0;
|
||||
|
||||
pub(super) struct WindowsPipeStream {
|
||||
handle: OwnedHandle,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
impl WindowsPipeStream {
|
||||
pub(super) fn connect(pipe_path: PathBuf, deadline: Instant) -> io::Result<Self> {
|
||||
let wide_path = pipe_path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let handle = unsafe {
|
||||
CreateFileW(
|
||||
wide_path.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL
|
||||
| FILE_FLAG_OVERLAPPED
|
||||
| SECURITY_SQOS_PRESENT
|
||||
| SECURITY_IDENTIFICATION,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
// SAFETY: CreateFileW returned an owned pipe handle.
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
validate_pipe_server_owner(handle.as_raw_handle())?;
|
||||
|
||||
Ok(Self { handle, deadline })
|
||||
}
|
||||
|
||||
pub(super) fn set_deadline(&mut self, deadline: Instant) {
|
||||
self.deadline = deadline;
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for WindowsPipeStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let bytes_to_read = u32::try_from(buf.len()).unwrap_or(u32::MAX);
|
||||
let mut operation = OverlappedOperation::new()?;
|
||||
let result = unsafe {
|
||||
ReadFile(
|
||||
self.handle.as_raw_handle(),
|
||||
buf.as_mut_ptr(),
|
||||
bytes_to_read,
|
||||
ptr::null_mut(),
|
||||
operation.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
|
||||
operation.complete(self.handle.as_raw_handle(), result, self.deadline)
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for WindowsPipeStream {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let bytes_to_write = u32::try_from(buf.len()).unwrap_or(u32::MAX);
|
||||
let mut operation = OverlappedOperation::new()?;
|
||||
let result = unsafe {
|
||||
WriteFile(
|
||||
self.handle.as_raw_handle(),
|
||||
buf.as_ptr(),
|
||||
bytes_to_write,
|
||||
ptr::null_mut(),
|
||||
operation.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
|
||||
operation.complete(self.handle.as_raw_handle(), result, self.deadline)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct OverlappedOperation {
|
||||
event: OwnedHandle,
|
||||
overlapped: OVERLAPPED,
|
||||
}
|
||||
|
||||
impl OverlappedOperation {
|
||||
fn new() -> io::Result<Self> {
|
||||
let event = unsafe { CreateEventW(ptr::null(), TRUE, FALSE, ptr::null()) };
|
||||
if event.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let mut overlapped = unsafe { std::mem::zeroed::<OVERLAPPED>() };
|
||||
overlapped.hEvent = event;
|
||||
Ok(Self {
|
||||
// SAFETY: CreateEventW returned an owned event handle.
|
||||
event: unsafe { OwnedHandle::from_raw_handle(event) },
|
||||
overlapped,
|
||||
})
|
||||
}
|
||||
|
||||
fn as_mut_ptr(&mut self) -> *mut OVERLAPPED {
|
||||
&mut self.overlapped
|
||||
}
|
||||
|
||||
fn complete(
|
||||
&mut self,
|
||||
handle: HANDLE,
|
||||
initial_result: BOOL,
|
||||
deadline: Instant,
|
||||
) -> io::Result<usize> {
|
||||
if initial_result == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
// Use a zero wait after the deadline so pending overlapped I/O still flows through
|
||||
// cancel_and_timeout instead of returning while the OS operation owns this OVERLAPPED.
|
||||
match unsafe {
|
||||
WaitForSingleObject(self.event.as_raw_handle(), remaining_timeout_ms(deadline))
|
||||
} {
|
||||
WAIT_OBJECT_0 => {}
|
||||
WAIT_TIMEOUT => return Err(self.cancel_and_timeout(handle)),
|
||||
WAIT_FAILED => return Err(io::Error::last_os_error()),
|
||||
other => {
|
||||
return Err(io::Error::other(format!(
|
||||
"unexpected WaitForSingleObject result: {other}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut bytes_transferred = 0;
|
||||
let result = unsafe {
|
||||
GetOverlappedResult(handle, self.as_mut_ptr(), &mut bytes_transferred, FALSE)
|
||||
};
|
||||
if result == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
Ok(bytes_transferred as usize)
|
||||
}
|
||||
|
||||
fn cancel_and_timeout(&mut self, handle: HANDLE) -> io::Error {
|
||||
let cancel_result = unsafe { CancelIoEx(handle, self.as_mut_ptr()) };
|
||||
if cancel_result == 0 {
|
||||
let cancel_error = io::Error::last_os_error();
|
||||
if cancel_error.raw_os_error() != Some(ERROR_NOT_FOUND as i32) {
|
||||
return cancel_error;
|
||||
}
|
||||
|
||||
// ERROR_NOT_FOUND means the operation completed before cancellation was issued. Drain
|
||||
// it without waiting so the timeout path cannot block past the caller's deadline.
|
||||
let mut bytes_transferred = 0;
|
||||
unsafe {
|
||||
GetOverlappedResult(handle, self.as_mut_ptr(), &mut bytes_transferred, FALSE)
|
||||
};
|
||||
return timeout_io_error();
|
||||
}
|
||||
|
||||
let mut bytes_transferred = 0;
|
||||
unsafe {
|
||||
GetOverlappedResult(handle, self.as_mut_ptr(), &mut bytes_transferred, TRUE);
|
||||
}
|
||||
timeout_io_error()
|
||||
}
|
||||
}
|
||||
|
||||
struct TokenUserBuffer {
|
||||
buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl TokenUserBuffer {
|
||||
fn sid(&self) -> io::Result<windows_sys::Win32::Security::PSID> {
|
||||
if self.buffer.len() < std::mem::size_of::<TOKEN_USER>() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"token user buffer is too small",
|
||||
));
|
||||
}
|
||||
|
||||
// GetTokenInformation writes TOKEN_USER into a byte buffer. Vec<u8> has
|
||||
// no TOKEN_USER alignment guarantee, so copy the fixed header out with
|
||||
// an unaligned read before using its SID pointer.
|
||||
let token_user =
|
||||
unsafe { std::ptr::read_unaligned(self.buffer.as_ptr() as *const TOKEN_USER) };
|
||||
Ok(token_user.User.Sid)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_pipe_server_owner(pipe_handle: HANDLE) -> io::Result<()> {
|
||||
let mut server_process_id = 0;
|
||||
let result = unsafe { GetNamedPipeServerProcessId(pipe_handle, &mut server_process_id) };
|
||||
if result == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let server_process =
|
||||
unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, server_process_id) };
|
||||
if server_process.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: OpenProcess returned an owned process handle.
|
||||
let server_process = unsafe { OwnedHandle::from_raw_handle(server_process) };
|
||||
let server_token = open_process_token(server_process.as_raw_handle())?;
|
||||
let current_token = open_process_token(unsafe { GetCurrentProcess() })?;
|
||||
let server_user = token_user(server_token.as_raw_handle())?;
|
||||
let current_user = token_user(current_token.as_raw_handle())?;
|
||||
|
||||
if unsafe { EqualSid(server_user.sid()?, current_user.sid()?) } == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"IDE context provider is not owned by the current user",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_process_token(process: HANDLE) -> io::Result<OwnedHandle> {
|
||||
let mut token = ptr::null_mut();
|
||||
let result = unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) };
|
||||
if result == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
// SAFETY: OpenProcessToken returned an owned token handle.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(token) })
|
||||
}
|
||||
|
||||
fn token_user(token: HANDLE) -> io::Result<TokenUserBuffer> {
|
||||
let mut return_length = 0;
|
||||
unsafe {
|
||||
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut return_length);
|
||||
}
|
||||
if return_length == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let mut buffer = vec![0_u8; return_length as usize];
|
||||
let result = unsafe {
|
||||
GetTokenInformation(
|
||||
token,
|
||||
TokenUser,
|
||||
buffer.as_mut_ptr() as *mut _,
|
||||
return_length,
|
||||
&mut return_length,
|
||||
)
|
||||
};
|
||||
if result == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
Ok(TokenUserBuffer { buffer })
|
||||
}
|
||||
|
||||
fn remaining_timeout_ms(deadline: Instant) -> u32 {
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let millis = deadline.duration_since(now).as_millis().max(1);
|
||||
u32::try_from(millis).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
fn timeout_io_error() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for IDE context")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_pipe_tests.rs"]
|
||||
mod tests;
|
||||
102
codex-rs/tui/src/ide_context/windows_pipe_tests.rs
Normal file
102
codex-rs/tui/src/ide_context/windows_pipe_tests.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
use windows_sys::Win32::Foundation::ERROR_PIPE_CONNECTED;
|
||||
use windows_sys::Win32::Security::RevertToSelf;
|
||||
use windows_sys::Win32::Security::SecurityIdentification;
|
||||
use windows_sys::Win32::Security::TokenImpersonationLevel;
|
||||
use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
|
||||
use windows_sys::Win32::System::Pipes::ConnectNamedPipe;
|
||||
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
|
||||
use windows_sys::Win32::System::Pipes::ImpersonateNamedPipeClient;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_WAIT;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentThread;
|
||||
use windows_sys::Win32::System::Threading::OpenThreadToken;
|
||||
|
||||
#[test]
|
||||
fn pipe_server_cannot_impersonate_client() {
|
||||
let pipe_path = PathBuf::from(format!(
|
||||
r"\\.\pipe\codex-ide-context-{}",
|
||||
uuid::Uuid::new_v4()
|
||||
));
|
||||
let wide_path = pipe_path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let pipe = unsafe {
|
||||
CreateNamedPipeW(
|
||||
wide_path.as_ptr(),
|
||||
PIPE_ACCESS_DUPLEX,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
|
||||
/*nmaxinstances*/ 1,
|
||||
/*noutbuffersize*/ 1024,
|
||||
/*ninbuffersize*/ 1024,
|
||||
/*ndefaulttimeout*/ 0,
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(pipe, INVALID_HANDLE_VALUE);
|
||||
let pipe = unsafe { OwnedHandle::from_raw_handle(pipe) };
|
||||
|
||||
let server = std::thread::spawn(move || {
|
||||
if unsafe { ConnectNamedPipe(pipe.as_raw_handle(), ptr::null_mut()) } == FALSE {
|
||||
assert_eq!(
|
||||
io::Error::last_os_error().raw_os_error(),
|
||||
Some(ERROR_PIPE_CONNECTED as i32)
|
||||
);
|
||||
}
|
||||
|
||||
let mut message = [0_u8];
|
||||
let mut bytes_read = 0;
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
ReadFile(
|
||||
pipe.as_raw_handle(),
|
||||
message.as_mut_ptr(),
|
||||
message.len() as u32,
|
||||
&mut bytes_read,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
},
|
||||
FALSE
|
||||
);
|
||||
assert_ne!(
|
||||
unsafe { ImpersonateNamedPipeClient(pipe.as_raw_handle()) },
|
||||
FALSE
|
||||
);
|
||||
|
||||
let mut token = ptr::null_mut();
|
||||
assert_ne!(
|
||||
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token) },
|
||||
FALSE
|
||||
);
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let mut impersonation_level = 0;
|
||||
let mut return_length = 0;
|
||||
let result = unsafe {
|
||||
GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
TokenImpersonationLevel,
|
||||
(&raw mut impersonation_level).cast(),
|
||||
std::mem::size_of_val(&impersonation_level) as u32,
|
||||
&mut return_length,
|
||||
)
|
||||
};
|
||||
let reverted = unsafe { RevertToSelf() };
|
||||
assert_ne!(result, FALSE);
|
||||
assert_ne!(reverted, FALSE);
|
||||
impersonation_level
|
||||
});
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 5);
|
||||
let mut stream = WindowsPipeStream::connect(pipe_path, deadline).expect("connect pipe client");
|
||||
stream.write_all(&[1]).expect("write pipe message");
|
||||
|
||||
assert_eq!(
|
||||
server.join().expect("join pipe server"),
|
||||
SecurityIdentification
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user