1
+//! Signing in as another account takes effect on the next message.
2
+//!
3
+//! A cloud backend used to keep the session token it was built with, so after
4
+//! Reauthenticate wrote a new one the thread went on sending the old account's
5
+//! bearer until the editor restarted the agent. The token is now read from the
6
+//! stored session on every request.
7
+
8
+use std::io::{BufRead, BufReader, Read, Write};
9
+use std::net::TcpListener;
10
+use std::process::{Child, ChildStdin, Command, Stdio};
11
+use std::sync::mpsc::{Receiver, channel};
12
+use std::time::{Duration, Instant};
13
+
14
+use serde_json::{Value, json};
15
+
16
+const TIMEOUT: Duration = Duration::from_secs(60);
17
+
18
+/// Stand in for `<cloud>/chat/completions`. The `authorization` header of each
19
+/// request is forwarded to the returned receiver.
20
+fn start_fake_cloud() -> (u16, Receiver<String>) {
21
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind fake cloud");
22
+ let port = listener.local_addr().unwrap().port();
23
+ let (auth_tx, auths) = channel();
24
+
25
+ std::thread::spawn(move || {
26
+ for stream in listener.incoming() {
27
+ let Ok(mut stream) = stream else { continue };
28
+ let mut reader = BufReader::new(match stream.try_clone() {
29
+ Ok(clone) => clone,
30
+ Err(_) => continue,
31
+ });
32
+ let mut content_length = 0usize;
33
+ let mut authorization = String::new();
34
+ loop {
35
+ let mut line = String::new();
36
+ if reader.read_line(&mut line).unwrap_or(0) == 0 {
37
+ break;
38
+ }
39
+ let line = line.trim().to_string();
40
+ if line.is_empty() {
41
+ break;
42
+ }
43
+ let lower = line.to_ascii_lowercase();
44
+ if let Some(length) = lower.strip_prefix("content-length:") {
45
+ content_length = length.trim().parse().unwrap_or(0);
46
+ }
47
+ if lower.starts_with("authorization:") {
48
+ authorization = lower;
49
+ }
50
+ }
51
+ let mut body = vec![0u8; content_length];
52
+ if reader.read_exact(&mut body).is_err() {
53
+ continue;
54
+ }
55
+ let _ = auth_tx.send(authorization);
56
+
57
+ let body = format!(
58
+ "data: {}\n\ndata: [DONE]\n\n",
59
+ json!({"choices": [{"delta": {"content": "ok"}}]})
60
+ );
61
+ let response = format!(
62
+ "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\
63
+ content-length: {}\r\nconnection: close\r\n\r\n{body}",
64
+ body.len()
65
+ );
66
+ let _ = stream.write_all(response.as_bytes());
67
+ let _ = stream.flush();
68
+ }
69
+ });
70
+
71
+ (port, auths)
72
+}
73
+
74
+struct AgentUnderTest {
75
+ child: Child,
76
+ stdin: ChildStdin,
77
+ incoming: Receiver<Value>,
78
+ next_id: u64,
79
+}
80
+
81
+fn spawn_agent(cloud_port: u16, config_dir: &std::path::Path) -> AgentUnderTest {
82
+ let mut child = Command::new(env!("CARGO_BIN_EXE_sigit"))
83
+ // No provider override and no on-device model: the thread starts on a
84
+ // cloud tier because a session is stored.
85
+ .env_remove("OPENAI_BASE_URL")
86
+ .env_remove("OPENAI_API_KEY")
87
+ .env_remove("SIGIT_MODEL")
88
+ .env("SIGIT_LOCAL_INFERENCE", "off")
89
+ .env("SIGIT_CLOUD_URL", format!("http://127.0.0.1:{cloud_port}"))
90
+ .env("SIGIT_CONFIG_DIR", config_dir)
91
+ .env("SIGIT_MCP", "off")
92
+ .stdin(Stdio::piped())
93
+ .stdout(Stdio::piped())
94
+ .stderr(Stdio::null())
95
+ .spawn()
96
+ .expect("spawn sigit in ACP mode");
97
+
98
+ let stdout = child.stdout.take().unwrap();
99
+ let (message_tx, incoming) = channel();
100
+ std::thread::spawn(move || {
101
+ for line in BufReader::new(stdout).lines() {
102
+ let Ok(line) = line else { break };
103
+ if let Ok(message) = serde_json::from_str::<Value>(&line)
104
+ && message_tx.send(message).is_err()
105
+ {
106
+ break;
107
+ }
108
+ }
109
+ });
110
+
111
+ let stdin = child.stdin.take().unwrap();
112
+ AgentUnderTest {
113
+ child,
114
+ stdin,
115
+ incoming,
116
+ next_id: 0,
117
+ }
118
+}
119
+
120
+impl AgentUnderTest {
121
+ fn request(&mut self, method: &str, params: Value) -> u64 {
122
+ self.next_id += 1;
123
+ let id = self.next_id;
124
+ let mut line =
125
+ json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}).to_string();
126
+ line.push('\n');
127
+ self.stdin.write_all(line.as_bytes()).expect("write stdin");
128
+ self.stdin.flush().expect("flush stdin");
129
+ id
130
+ }
131
+
132
+ fn wait_for_response(&mut self, id: u64) -> Value {
133
+ let deadline = Instant::now() + TIMEOUT;
134
+ loop {
135
+ let remaining = deadline.saturating_duration_since(Instant::now());
136
+ let Ok(message) = self.incoming.recv_timeout(remaining) else {
137
+ panic!("timed out waiting for the response to request {id}");
138
+ };
139
+ if message["id"] == id && message.get("method").is_none() {
140
+ assert!(
141
+ message.get("error").is_none(),
142
+ "request {id} failed: {message}"
143
+ );
144
+ return message;
145
+ }
146
+ }
147
+ }
148
+
149
+ fn prompt(&mut self, session_id: &str, text: &str) {
150
+ let id = self.request(
151
+ "session/prompt",
152
+ json!({"sessionId": session_id, "prompt": [{"type": "text", "text": text}]}),
153
+ );
154
+ self.wait_for_response(id);
155
+ }
156
+}
157
+
158
+impl Drop for AgentUnderTest {
159
+ fn drop(&mut self) {
160
+ let _ = self.child.kill();
161
+ let _ = self.child.wait();
162
+ }
163
+}
164
+
165
+fn store_token(config_dir: &std::path::Path, token: &str) {
166
+ std::fs::write(
167
+ config_dir.join("credentials.toml"),
168
+ format!("access_token = \"{token}\"\nemail = \"dev@example.com\"\n"),
169
+ )
170
+ .unwrap();
171
+}
172
+
173
+#[test]
174
+fn a_new_session_token_is_used_by_the_next_turn() {
175
+ let scratch = std::env::temp_dir().join(format!("sigit_acp_reauth_{}", std::process::id()));
176
+ let config_dir = scratch.join("config");
177
+ let work_dir = scratch.join("work");
178
+ std::fs::create_dir_all(&config_dir).unwrap();
179
+ std::fs::create_dir_all(&work_dir).unwrap();
180
+ store_token(&config_dir, "token-a");
181
+
182
+ let (port, auths) = start_fake_cloud();
183
+ let mut agent = spawn_agent(port, &config_dir);
184
+
185
+ let id = agent.request(
186
+ "initialize",
187
+ json!({"protocolVersion": 1, "clientCapabilities": {}}),
188
+ );
189
+ agent.wait_for_response(id);
190
+ let id = agent.request("session/new", json!({"cwd": work_dir, "mcpServers": []}));
191
+ let session_id = agent.wait_for_response(id)["result"]["sessionId"]
192
+ .as_str()
193
+ .expect("session id")
194
+ .to_string();
195
+
196
+ agent.prompt(&session_id, "first");
197
+ let first = auths.recv_timeout(TIMEOUT).expect("first request");
198
+ assert_eq!(first, "authorization: bearer token-a");
199
+
200
+ // What Reauthenticate does once the browser flow hands back a code.
201
+ store_token(&config_dir, "token-b");
202
+
203
+ agent.prompt(&session_id, "second");
204
+ let second = auths.recv_timeout(TIMEOUT).expect("second request");
205
+ assert_eq!(second, "authorization: bearer token-b");
206
+
207
+ std::fs::remove_dir_all(&scratch).ok();
208
+}