File size: 10,968 Bytes
854994d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | use std::collections::HashMap;
use std::io;
use std::io::Read;
use std::io::Write;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
use http::header::AUTHORIZATION;
use pretty_assertions::assert_eq;
use super::*;
const BASE_URL: &str = "https://chatgpt.com/backend-api";
const BY_REPO_URL: &str =
"https://chatgpt.com/backend-api/wham/environments/by-repo/github/openai/codex";
const GLOBAL_URL: &str = "https://chatgpt.com/backend-api/wham/environments";
#[tokio::test]
async fn production_http_forwards_headers_and_decodes_response() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))
.expect("environment HTTP listener should bind");
let address = listener
.local_addr()
.expect("environment HTTP listener should have an address");
listener
.set_nonblocking(true)
.expect("environment HTTP listener should become nonblocking");
let server = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(10);
let (mut stream, _) = loop {
match listener.accept() {
Ok(connection) => break connection,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
assert!(
Instant::now() < deadline,
"environment HTTP listener should receive a request"
);
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("environment HTTP listener should accept: {error}"),
}
};
stream
.set_nonblocking(false)
.expect("environment HTTP stream should become blocking");
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.expect("environment HTTP stream should get a read timeout");
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
loop {
let bytes_read = stream
.read(&mut buffer)
.expect("environment HTTP request should read");
if bytes_read == 0 {
break;
}
request.extend_from_slice(&buffer[..bytes_read]);
if request.windows(4).any(|window| window == b"\r\n\r\n") {
break;
}
}
let body = r#"[{"id":"env-real","label":"Real"}]"#;
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.expect("environment HTTP response should write");
String::from_utf8(request).expect("environment HTTP request should be UTF-8")
});
let http = RouteAwareClientPool::new_without_request_logging(
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
ClientRouteClass::Api,
);
let base_url = format!("http://{address}");
let headers =
HeaderMap::from_iter([(AUTHORIZATION, HeaderValue::from_static("Bearer real-token"))]);
let selection = tokio::time::timeout(
Duration::from_secs(10),
autodetect_environment_id_with_origins(
&http,
&base_url,
&headers,
/*desired_label*/ None,
&[],
),
)
.await
.expect("environment request should finish")
.expect("environment response should decode");
let request = server
.join()
.expect("environment HTTP server should finish");
assert_eq!(
selection,
AutodetectSelection {
id: "env-real".to_string(),
label: Some("Real".to_string()),
}
);
assert!(request.starts_with("GET /api/codex/environments HTTP/1.1\r\n"));
assert!(
request
.to_ascii_lowercase()
.contains("authorization: bearer real-token\r\n")
);
}
#[tokio::test]
async fn autodetect_requests_exact_repository_endpoint_and_decodes_selection() {
let http = FakeHttp::new(HashMap::from([(
BY_REPO_URL.to_string(),
json_response(r#"[{"id":"env-repo","label":"Repository","is_pinned":true}]"#),
)]));
let headers = HeaderMap::from_iter([(
AUTHORIZATION,
HeaderValue::from_static("Bearer forwarded-token"),
)]);
let selection = autodetect_environment_id_with_origins(
&http,
BASE_URL,
&headers,
Some("Repository".to_string()),
&[SanitizedGitUrl::try_from("git@github.com:openai/codex.git").expect("valid Git remote")],
)
.await
.expect("repository environment should be selected");
assert_eq!(
selection,
AutodetectSelection {
id: "env-repo".to_string(),
label: Some("Repository".to_string()),
}
);
assert_eq!(
http.requests(),
vec![RecordedRequest {
url: BY_REPO_URL.to_string(),
headers,
}]
);
}
/// Repository discovery must accept credential-bearing origins without exposing credentials.
#[tokio::test]
async fn autodetect_sanitizes_credential_bearing_git_origins() {
let http = FakeHttp::new(HashMap::from([(
BY_REPO_URL.to_string(),
json_response(r#"[{"id":"env-repo","label":"Repository"}]"#),
)]));
let selection = autodetect_environment_id_with_origins(
&http,
BASE_URL,
&HeaderMap::new(),
/*desired_label*/ None,
&[SanitizedGitUrl::try_from(
"https://alice:synthetic-git-secret@github.com/openai/codex.git",
)
.expect("valid Git remote")],
)
.await
.expect("repository environment should be selected");
assert_eq!(
selection,
AutodetectSelection {
id: "env-repo".to_string(),
label: Some("Repository".to_string()),
}
);
assert_eq!(http.requested_urls(), vec![BY_REPO_URL.to_string()]);
}
/// Removing an SCP remote username must not prevent repository-specific discovery.
#[tokio::test]
async fn autodetect_recognizes_sanitized_scp_git_origins() {
let http = FakeHttp::new(HashMap::from([(
BY_REPO_URL.to_string(),
json_response(r#"[{"id":"env-repo","label":"Repository"}]"#),
)]));
let selection = autodetect_environment_id_with_origins(
&http,
BASE_URL,
&HeaderMap::new(),
/*desired_label*/ None,
&[
SanitizedGitUrl::try_from("org-123@github.com:openai/codex.git")
.expect("valid Git remote"),
],
)
.await
.expect("repository environment should be selected");
assert_eq!(
selection,
AutodetectSelection {
id: "env-repo".to_string(),
label: Some("Repository".to_string()),
}
);
assert_eq!(http.requested_urls(), vec![BY_REPO_URL.to_string()]);
}
#[tokio::test]
async fn autodetect_falls_back_to_exact_global_endpoint_and_decodes_selection() {
let http = FakeHttp::new(HashMap::from([
(BY_REPO_URL.to_string(), json_response("[]")),
(
GLOBAL_URL.to_string(),
json_response(r#"[{"id":"env-global","label":"Global"}]"#),
),
]));
let selection = autodetect_environment_id_with_origins(
&http,
BASE_URL,
&HeaderMap::new(),
/*desired_label*/ None,
&[SanitizedGitUrl::try_from("git@github.com:openai/codex.git").expect("valid Git remote")],
)
.await
.expect("global environment should be selected");
assert_eq!(
selection,
AutodetectSelection {
id: "env-global".to_string(),
label: Some("Global".to_string()),
}
);
assert_eq!(
http.requested_urls(),
vec![BY_REPO_URL.to_string(), GLOBAL_URL.to_string()]
);
}
#[tokio::test]
async fn list_requests_exact_repository_and_global_endpoints_and_merges_results() {
let http = FakeHttp::new(HashMap::from([
(
BY_REPO_URL.to_string(),
json_response(r#"[{"id":"env-repo","label":"Repository"}]"#),
),
(
GLOBAL_URL.to_string(),
json_response(
r#"[{"id":"env-repo","is_pinned":true},{"id":"env-global","label":"Global"}]"#,
),
),
]));
let rows = list_environments_with_origins(
&http,
BASE_URL,
&HeaderMap::new(),
&[
SanitizedGitUrl::try_from("https://github.com/openai/codex.git")
.expect("valid Git remote"),
],
)
.await
.expect("environment list should decode");
assert_eq!(
rows.into_iter()
.map(|row| (row.id, row.label, row.is_pinned, row.repo_hints))
.collect::<Vec<_>>(),
vec![
(
"env-repo".to_string(),
Some("Repository".to_string()),
true,
Some("openai/codex".to_string()),
),
(
"env-global".to_string(),
Some("Global".to_string()),
false,
None,
),
]
);
assert_eq!(
http.requested_urls(),
vec![BY_REPO_URL.to_string(), GLOBAL_URL.to_string()]
);
}
struct FakeHttp {
responses: HashMap<String, EnvironmentResponse>,
requests: Mutex<Vec<RecordedRequest>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct RecordedRequest {
url: String,
headers: HeaderMap,
}
impl FakeHttp {
fn new(responses: HashMap<String, EnvironmentResponse>) -> Self {
Self {
responses,
requests: Mutex::new(Vec::new()),
}
}
fn requests(&self) -> Vec<RecordedRequest> {
self.requests.lock().expect("request lock").clone()
}
fn requested_urls(&self) -> Vec<String> {
self.requests
.lock()
.expect("request lock")
.iter()
.map(|request| request.url.clone())
.collect()
}
}
impl EnvironmentHttp for FakeHttp {
async fn get(&self, url: &str, headers: &HeaderMap) -> anyhow::Result<EnvironmentResponse> {
self.requests
.lock()
.expect("request lock")
.push(RecordedRequest {
url: url.to_string(),
headers: headers.clone(),
});
self.responses
.get(url)
.cloned()
.ok_or_else(|| anyhow::anyhow!("unexpected URL: {url}"))
}
}
fn json_response(body: &str) -> EnvironmentResponse {
EnvironmentResponse {
status: StatusCode::OK,
content_type: "application/json".to_string(),
body: body.to_string(),
}
}
|