1use serde::Deserialize;
7use serde_json::Value;
8use subspace_core::credentials::Credential;
9use subspace_core::http::status as http_status;
10use subspace_core::http::{Error, agent};
11use ureq::Body;
12use ureq::http::Response;
13
14const USER_AGENT: &str = "subspace";
15const API_VERSION: &str = "2022-11-28";
16const ERROR_BODY_LIMIT_BYTES: u64 = subspace_core::http::ERROR_BODY_BYTES;
17pub const JSON: &str = "application/vnd.github+json";
18pub const RAW: &str = "application/vnd.github.raw+json";
19
20mod graphql;
21mod mapping;
22pub(crate) use graphql::post_bound_graphql;
23pub use graphql::post_graphql;
24
25pub use mapping::{
26 Failure, account_label, http_failure, is_access_refusal, not_found, rejected, status,
27 unexpected,
28};
29
30use mapping::{is_rate_limit, is_sso};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Api {
34 GraphQl,
35 Rest,
36}
37
38#[derive(Debug, Clone, Default, Deserialize)]
39pub struct GraphQlError {
40 #[serde(default, rename = "type")]
41 pub kind: Option<String>,
42 #[serde(default)]
43 pub message: Option<String>,
44 #[serde(default)]
45 pub extensions: Option<Extensions>,
46}
47
48#[derive(Debug, Clone, Default, Deserialize)]
49pub struct Extensions {
50 #[serde(default)]
51 pub code: Option<String>,
52}
53
54const GRAPHQL_NOT_FOUND: &str = "Could not resolve to a";
57
58pub fn is_not_found(error: &Error) -> bool {
64 match error {
65 Error::Status { status, .. } if *status == http_status::NOT_FOUND => true,
66 Error::Status { status, message } if *status == http_status::BAD_REQUEST => {
67 message.starts_with(GRAPHQL_NOT_FOUND)
68 }
69 _ => false,
70 }
71}
72
73pub fn graphql_failure(account: &str, errors: &[GraphQlError]) -> Error {
75 let message = |error: &GraphQlError| error.message.clone().unwrap_or_default();
76 if let Some(sso) = errors.iter().find(|error| is_sso(&message(error))) {
77 return status(http_status::FORBIDDEN, message(sso));
78 }
79 let limited = errors.iter().any(|error| {
80 error.kind.as_deref() == Some("RATE_LIMITED") || is_rate_limit(&message(error))
81 });
82 if limited {
83 return status(
84 http_status::TOO_MANY_REQUESTS,
85 format!("GitHub rate limit reached for {account}; try again in a few minutes."),
86 );
87 }
88 let first = errors.first();
89 let text = first
90 .and_then(|error| error.message.clone())
91 .unwrap_or_else(|| "GitHub returned an error.".to_owned());
92 let kind = first.and_then(|error| error.kind.as_deref());
93 if kind == Some("FORBIDDEN") {
94 return status(http_status::FORBIDDEN, text);
95 }
96 let has_code = first
97 .and_then(|error| error.extensions.as_ref())
98 .and_then(|extensions| extensions.code.as_ref())
99 .is_some();
100 let invalid = matches!(kind, Some("NOT_FOUND" | "UNPROCESSABLE" | "INVALID")) || has_code;
101 status(
102 if invalid {
103 http_status::BAD_REQUEST
104 } else {
105 http_status::BAD_GATEWAY
106 },
107 text,
108 )
109}
110
111#[derive(Debug, Default, Deserialize)]
112pub struct GraphQlResponse {
113 #[serde(default)]
114 pub data: Option<Value>,
115 #[serde(default)]
116 pub errors: Vec<GraphQlError>,
117 #[serde(default)]
118 pub message: Option<String>,
119}
120
121pub fn graphql_data(
124 account: &str,
125 response: GraphQlResponse,
126 partial: bool,
127) -> Result<Value, Error> {
128 let data = response.data.filter(|data| !data.is_null());
129 if !response.errors.is_empty() && !(partial && data.is_some()) {
130 return Err(graphql_failure(account, &response.errors));
131 }
132 data.ok_or_else(|| status(http_status::BAD_GATEWAY, "GitHub returned no data."))
133}
134
135fn header<'a>(response: &'a Response<Body>, name: &str) -> Option<&'a str> {
136 response.headers().get(name)?.to_str().ok()
137}
138
139fn network(_: ureq::Error) -> Error {
140 Error::Network("GitHub could not be reached.".into())
141}
142
143fn check(
145 credential: &Credential,
146 account: &str,
147 api: Api,
148 mut response: Response<Body>,
149) -> Result<Response<Body>, Error> {
150 let code = response.status().as_u16();
151 if response.status().is_success() {
152 return Ok(response);
153 }
154 if code == http_status::UNAUTHORIZED {
155 return Err(rejected(credential, account));
156 }
157 let text = response
158 .body_mut()
159 .with_config()
160 .limit(ERROR_BODY_LIMIT_BYTES)
161 .read_to_string()
162 .unwrap_or_default();
163 let message = serde_json::from_str::<GraphQlResponse>(&text)
164 .ok()
165 .and_then(|body| body.message)
166 .unwrap_or_default();
167 if code == http_status::BAD_REQUEST {
168 return Err(status(http_status::BAD_REQUEST, message));
169 }
170 Err(http_failure(
171 account,
172 api,
173 Failure {
174 status: code,
175 remaining: header(&response, "x-ratelimit-remaining"),
176 reset: header(&response, "x-ratelimit-reset"),
177 retry_after: header(&response, "retry-after"),
178 message: &message,
179 },
180 ))
181}
182
183pub fn get_rest(
185 url: &str,
186 credential: &Credential,
187 account: &str,
188 accept: &str,
189) -> Result<Response<Body>, Error> {
190 get_rest_version(url, credential, account, accept, API_VERSION)
191}
192
193pub fn get_rest_version(
194 url: &str,
195 credential: &Credential,
196 account: &str,
197 accept: &str,
198 version: &str,
199) -> Result<Response<Body>, Error> {
200 let authorization = credential.authorization();
201 let response = agent()
202 .get(url)
203 .header("Authorization", authorization.expose())
204 .header("Accept", accept)
205 .header("X-GitHub-Api-Version", version)
206 .header("User-Agent", USER_AGENT)
207 .call()
208 .map_err(network)?;
209 check(credential, account, Api::Rest, response)
210}
211
212pub const COPILOT_INTEGRATION_ID: &str = "copilot-4-cli";
214pub const COPILOT_API_VERSION: &str = "2026-01-09";
216pub const EVENT_STREAM: &str = "text/event-stream";
217
218pub fn get_copilot(
222 url: &str,
223 credential: &Credential,
224 account: &str,
225 accept: &str,
226) -> Result<Response<Body>, Error> {
227 let authorization = credential.authorization();
228 let response = agent()
229 .get(url)
230 .header("Authorization", authorization.expose())
231 .header("Accept", accept)
232 .header("Copilot-Integration-Id", COPILOT_INTEGRATION_ID)
233 .header("X-GitHub-Api-Version", COPILOT_API_VERSION)
234 .header("User-Agent", USER_AGENT)
235 .call()
236 .map_err(network)?;
237 check(credential, account, Api::Rest, response)
238}
239
240pub fn is_api_version_rejection(error: &Error) -> bool {
241 matches!(error, Error::Status { status: http_status::BAD_REQUEST, message } if {
242 let message = message.to_ascii_lowercase();
243 message.contains("api version") || message.contains("api-version") || message.contains("unsupported version")
244 })
245}
246
247pub fn post_rest_json(
250 url: &str,
251 credential: &Credential,
252 account: &str,
253 body: &str,
254 version: &str,
255) -> Result<(u16, String), Error> {
256 post_rest_json_request(agent().post(url), credential, account, body, version)
257}
258
259pub(crate) fn post_rest_json_request(
262 request: ureq::RequestBuilder<ureq::typestate::WithBody>,
263 credential: &Credential,
264 account: &str,
265 body: &str,
266 version: &str,
267) -> Result<(u16, String), Error> {
268 let response = request
269 .header("Authorization", credential.authorization().expose())
270 .header("Content-Type", "application/json")
271 .header("Accept", JSON)
272 .header("X-GitHub-Api-Version", version)
273 .header("User-Agent", USER_AGENT)
274 .send(body)
275 .map_err(network)?;
276 let code = response.status().as_u16();
277 let mut response = response;
278 let text = response
279 .body_mut()
280 .with_config()
281 .limit(subspace_core::http::MAX_BODY_BYTES)
282 .read_to_string()
283 .map_err(network)?;
284 if !http_status::is_success(code) {
285 if code == http_status::UNAUTHORIZED {
286 return Err(rejected(credential, account));
287 }
288 let message = serde_json::from_str::<GraphQlResponse>(&text)
289 .ok()
290 .and_then(|body| body.message)
291 .unwrap_or_default();
292 if code == http_status::BAD_REQUEST {
293 return Err(status(http_status::BAD_REQUEST, message));
294 }
295 return Err(http_failure(
296 account,
297 Api::Rest,
298 Failure {
299 status: code,
300 remaining: None,
301 reset: None,
302 retry_after: None,
303 message: &message,
304 },
305 ));
306 }
307 Ok((code, text))
308}
309
310pub fn read_limited(mut response: Response<Body>, max: usize) -> Result<Vec<u8>, Error> {
312 let too_large = || {
313 status(
314 http_status::PAYLOAD_TOO_LARGE,
315 format!("The file is larger than {} MB.", max / 1024 / 1024),
316 )
317 };
318 let declared = header(&response, "content-length").and_then(|value| value.parse::<u64>().ok());
319 if declared.is_some_and(|length| length > max as u64) {
320 return Err(too_large());
321 }
322 response
323 .body_mut()
324 .with_config()
325 .limit(max as u64)
326 .read_to_vec()
327 .map_err(|error| match error {
328 ureq::Error::BodyExceedsLimit(_) => too_large(),
329 other => network(other),
330 })
331}
332
333#[cfg(test)]
334mod tests {
335 use serde_json::json;
336 use subspace_core::Secret;
337 use subspace_core::credentials::{Credential, Scheme, Source};
338 use subspace_core::http::Error;
339
340 use super::mapping::reset_hint;
341 use super::{
342 Api, Failure, GraphQlError, GraphQlResponse, graphql_data, graphql_failure, http_failure,
343 is_access_refusal, is_not_found, rejected,
344 };
345
346 fn code(error: &Error) -> u16 {
347 match error {
348 Error::Status { status, .. } => *status,
349 _ => 0,
350 }
351 }
352
353 fn failure(
354 status: u16,
355 remaining: Option<&'static str>,
356 message: &'static str,
357 ) -> Failure<'static> {
358 Failure {
359 status,
360 remaining,
361 reset: Some("1790000000"),
362 retry_after: None,
363 message,
364 }
365 }
366
367 #[test]
368 fn rate_limits_name_the_reset_time() {
369 let error = http_failure("ann", Api::Rest, failure(403, Some("0"), ""));
370 assert_eq!(code(&error), 429);
371 assert!(
372 error
373 .to_string()
374 .starts_with("GitHub rate limit reached for ann; it resets at ")
375 );
376 assert!(error.to_string().ends_with(" UTC."));
377 let by_message = http_failure(
378 "ann",
379 Api::GraphQl,
380 failure(429, None, "API rate limit exceeded"),
381 );
382 assert_eq!(code(&by_message), 429);
383 let secondary = Failure {
384 retry_after: Some("60"),
385 ..failure(403, None, "You have been blocked for a while.")
386 };
387 let secondary = http_failure("ann", Api::Rest, secondary);
388 assert_eq!(
389 code(&secondary),
390 429,
391 "a 403 with Retry-After is a rate limit"
392 );
393 for api in [Api::Rest, Api::GraphQl] {
394 let refused = http_failure("ann", api, failure(403, Some("4999"), "Not allowed"));
395 assert_eq!(code(&refused), 403, "a plain 403 stays an access refusal");
396 }
397 assert_eq!(reset_hint(None), "; try again in a few minutes");
398 assert_eq!(reset_hint(Some("0")), "; try again in a few minutes");
399 assert_eq!(reset_hint(Some("3600")), "; it resets at 01:00 UTC");
400 }
401
402 #[test]
403 fn sso_timeouts_and_not_found() {
404 let sso = http_failure(
405 "ann",
406 Api::Rest,
407 failure(
408 403,
409 None,
410 "Resource protected by organization SAML enforcement.",
411 ),
412 );
413 assert_eq!(code(&sso), 403);
414 assert_eq!(
415 code(&http_failure("ann", Api::GraphQl, failure(502, None, ""))),
416 504
417 );
418 assert_eq!(
419 code(&http_failure("ann", Api::Rest, failure(502, None, ""))),
420 502
421 );
422 assert_eq!(
423 code(&http_failure("ann", Api::Rest, failure(404, None, ""))),
424 404
425 );
426 assert_eq!(
427 code(&http_failure("ann", Api::GraphQl, failure(404, None, ""))),
428 502
429 );
430 assert_eq!(
431 code(&http_failure("ann", Api::Rest, failure(403, None, "nope"))),
432 403,
433 "lost access stays a refusal, not a transient failure"
434 );
435 let plain = http_failure("ann", Api::Rest, failure(403, None, "nope"));
436 assert!(
437 is_access_refusal(&plain),
438 "a plain 403 is one item's refusal"
439 );
440 let sso = http_failure(
441 "ann",
442 Api::Rest,
443 failure(
444 403,
445 None,
446 "Resource protected by organization SAML enforcement.",
447 ),
448 );
449 assert_eq!(code(&sso), 403);
450 assert!(!is_access_refusal(&sso), "an SSO requirement is not");
451 }
452
453 fn errors(value: serde_json::Value) -> Vec<GraphQlError> {
454 serde_json::from_value(value).unwrap()
455 }
456
457 #[test]
458 fn graphql_errors_map_by_type() {
459 let cases = [
460 (json!([{"type": "FORBIDDEN", "message": "x"}]), 403),
461 (json!([{"message": "Resource protected by SSO"}]), 403),
462 (json!([{"type": "RATE_LIMITED"}]), 429),
463 (json!([{"type": "NOT_FOUND", "message": "gone"}]), 400),
464 (
465 json!([{"message": "bad", "extensions": {"code": "undefinedField"}}]),
466 400,
467 ),
468 (json!([{"message": "boom"}]), 502),
469 ];
470 for (value, expected) in cases {
471 assert_eq!(
472 code(&graphql_failure("ann", &errors(value.clone()))),
473 expected,
474 "{value}"
475 );
476 }
477 }
478
479 #[test]
480 fn only_a_graphql_not_found_400_is_not_found() {
481 let missing = json!([{"type": "NOT_FOUND",
482 "message": "Could not resolve to a Repository with the name 'octo-org/api'."}]);
483 assert!(is_not_found(&graphql_failure("ann", &errors(missing))));
484 let invalid = json!([{"message": "Field 'x' doesn't exist on type 'PullRequest'",
485 "extensions": {"code": "undefinedField"}}]);
486 let invalid = graphql_failure("ann", &errors(invalid));
487 assert_eq!(code(&invalid), 400);
488 assert!(!is_not_found(&invalid), "a rejected query is not");
489 assert!(is_not_found(&super::not_found()));
490 }
491
492 #[test]
493 fn partial_data_is_kept_only_when_asked() {
494 let response = || GraphQlResponse {
495 data: Some(json!({"search": {}})),
496 errors: errors(json!([{"type": "FORBIDDEN", "message": "SAML"}])),
497 message: None,
498 };
499 assert!(graphql_data("ann", response(), true).is_ok());
500 assert_eq!(
501 code(&graphql_data("ann", response(), false).unwrap_err()),
502 403
503 );
504 let empty = GraphQlResponse::default();
505 assert_eq!(code(&graphql_data("ann", empty, true).unwrap_err()), 502);
506 }
507
508 #[test]
509 fn a_rejected_token_names_its_source_and_keeps_401() {
510 let credential = |source| Credential {
511 value: Secret::new("t"),
512 scheme: Scheme::Bearer,
513 source,
514 };
515 let env = rejected(&credential(Source::Environment("GH_TOKEN")), "ann");
516 assert_eq!(code(&env), 401);
517 assert_eq!(env.to_string(), "GitHub rejected the token in GH_TOKEN.");
518 let cli = rejected(
519 &credential(Source::GhCli {
520 login: "ann".into(),
521 }),
522 "ann",
523 );
524 assert_eq!(
525 cli.to_string(),
526 "GitHub token rejected for ann; run gh auth login."
527 );
528 }
529}