LINE1 10 20 30 40 50 60 70 80 90 1001use anyhow::Context;2#[cfg(not(feature = "testing"))]3use anyhow::anyhow;4#[cfg(not(feature = "testing"))]5use anyhow::bail;6use serde::Deserialize;7use std::fmt;8#[cfg(not(feature = "testing"))]9use std::time::Duration;1011#[cfg(not(feature = "testing"))]12use crate::server_url::TwigUrl;1314#[derive(Clone, Copy, Debug, Eq, PartialEq)]15pub enum ApiMethod {16 Get,17 Post,18 Patch,19 Put,20 Delete,21}2223#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]24pub enum ApiRoot {25 #[default]26 V1,27 Root,28}2930impl ApiMethod {31 #[cfg(not(feature = "testing"))]32 fn as_reqwest(self) -> reqwest::Method {33 match self {34 Self::Get => reqwest::Method::GET,35 Self::Post => reqwest::Method::POST,36 Self::Patch => reqwest::Method::PATCH,37 Self::Put => reqwest::Method::PUT,38 Self::Delete => reqwest::Method::DELETE,39 }40 }41}4243#[derive(Clone, Debug, PartialEq)]44pub enum ApiBody {45 Empty,46 Json(serde_json::Value),47 Binary(Vec<u8>),48}4950#[derive(Clone, Debug, PartialEq)]51pub struct ApiRequest {52 pub method: ApiMethod,53 pub root: ApiRoot,54 55 pub path_segments: Vec<String>,56 pub query: Vec<(String, String)>,57 pub body: ApiBody,58}5960impl ApiRequest {61 pub fn new(method: ApiMethod, path_segments: Vec<String>) -> Self {62 Self {63 method,64 root: ApiRoot::V1,65 path_segments,66 query: Vec::new(),67 body: ApiBody::Empty,68 }69 }7071 pub fn root_api(mut self) -> Self {72 self.root = ApiRoot::Root;73 self74 }7576 pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {77 self.query.push((key.into(), value.into()));78 self79 }8081 pub fn json(mut self, body: serde_json::Value) -> Self {82 self.body = ApiBody::Json(body);83 self84 }8586 pub fn binary(mut self, body: Vec<u8>) -> Self {87 self.body = ApiBody::Binary(body);88 self89 }90}9192#[derive(Clone, Debug, Eq, PartialEq)]93pub struct ApiResponse {94 pub status: u16,95 pub content_type: Option<String>,96 pub body: Vec<u8>,97}9899#[derive(Deserialize)]100struct ErrorEnvelope {101 error: ApiErrorBody,102}103104#[derive(Deserialize)]105struct ApiErrorBody {106 code: String,107 message: String,108}109110#[derive(Clone, Debug, Eq, PartialEq)]111pub struct ApiError {112 pub status: u16,113 pub code: String,114 pub message: String,115}116117impl fmt::Display for ApiError {118 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {119 write!(120 formatter,121 "Twig API returned HTTP {} ({}): {}",122 self.status, self.code, self.message123 )124 }125}126127impl std::error::Error for ApiError {}128129impl ApiResponse {130 pub fn ensure_success(self) -> anyhow::Result<Self> {131 if (200..300).contains(&self.status) {132 return Ok(self);133 }134135 if let Ok(envelope) = serde_json::from_slice::<ErrorEnvelope>(&self.body) {136 return Err(ApiError {137 status: self.status,138 code: envelope.error.code,139 message: envelope.error.message,140 }141 .into());142 }143144 Err(ApiError {145 status: self.status,146 code: "invalid_error_response".to_owned(),147 message: "the response did not contain a valid API error".to_owned(),148 }149 .into())150 }151152 pub fn json_value(&self) -> anyhow::Result<serde_json::Value> {153 serde_json::from_slice(&self.body).context("Twig returned invalid JSON")154 }155}156157pub trait TwigApi {158 async fn execute(&self, request: ApiRequest) -> anyhow::Result<ApiResponse>;159}160161#[cfg(not(feature = "testing"))]162pub struct HttpTwigApi {163 client: reqwest::Client,164 server: TwigUrl,165 token: String,166}167168#[cfg(not(feature = "testing"))]169impl HttpTwigApi {170 pub fn new(server: TwigUrl, token: String) -> anyhow::Result<Self> {171 if token.is_empty() {172 bail!("Twig access token is empty; run `tree auth` to connect");173 }174 let client = reqwest::Client::builder()175 .timeout(Duration::from_mins(10))176 .redirect(reqwest::redirect::Policy::none())177 .build()178 .context("Failed to initialize Twig API client")?;179 Ok(Self {180 client,181 server,182 token,183 })184 }185186 fn endpoint(&self, request: &ApiRequest) -> anyhow::Result<reqwest::Url> {187 let root = match request.root {188 ApiRoot::V1 => "/api/v1/",189 ApiRoot::Root => "/api/",190 };191 let mut endpoint = self192 .server193 .as_url()194 .join(root)195 .context("Could not construct Twig API endpoint")?;196 {197 let mut segments = endpoint198 .path_segments_mut()199 .map_err(|()| anyhow!("Twig API URL cannot contain path segments"))?;200 segments.pop_if_empty();201 for segment in &request.path_segments {202 segments.push(segment);203 }204 }205 if !request.query.is_empty() {206 endpoint207 .query_pairs_mut()208 .extend_pairs(request.query.iter().map(|(key, value)| (key, value)));209 }210 Ok(endpoint)211 }212}213214#[cfg(not(feature = "testing"))]215impl TwigApi for HttpTwigApi {216 async fn execute(&self, request: ApiRequest) -> anyhow::Result<ApiResponse> {217 let endpoint = self.endpoint(&request)?;218 let mut builder = self219 .client220 .request(request.method.as_reqwest(), endpoint)221 .bearer_auth(&self.token);222 builder = match request.body {223 ApiBody::Empty => builder,224 ApiBody::Json(body) => builder.json(&body),225 ApiBody::Binary(body) => builder226 .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")227 .body(body),228 };229230 let response = builder231 .send()232 .await233 .context("Could not reach the Twig API")?;234 let status = response.status().as_u16();235 let content_type = response236 .headers()237 .get(reqwest::header::CONTENT_TYPE)238 .and_then(|value| value.to_str().ok())239 .map(str::to_owned);240 let body = response241 .bytes()242 .await243 .context("Could not read the Twig API response")?244 .to_vec();245 Ok(ApiResponse {246 status,247 content_type,248 body,249 })250 }251}252253#[cfg(all(test, not(feature = "testing")))]254mod tests {255 use wiremock::{256 Mock, MockServer, ResponseTemplate,257 matchers::{body_json, header, method, path, query_param},258 };259260 use super::{ApiBody, ApiMethod, ApiRequest, HttpTwigApi, TwigApi};261 use crate::server_url::TwigUrl;262263 fn api(server: &MockServer) -> HttpTwigApi {264 HttpTwigApi::new(265 TwigUrl::parse(&server.uri()).expect("valid mock server URL"),266 "test-pat".to_owned(),267 )268 .expect("HTTP API adapter")269 }270271 #[tokio::test]272 async fn api_request_sends_bearer_auth_and_encodes_query_values() {273 let server = MockServer::start().await;274 let mock = Mock::given(method("GET"))275 .and(path("/api/v1/namespaces/acme/repositories/tooling/commits"))276 .and(query_param("ref", "feature/docs"))277 .and(header("authorization", "Bearer test-pat"))278 .respond_with(279 ResponseTemplate::new(200)280 .insert_header("content-type", "application/json")281 .set_body_string("[]"),282 )283 .expect(1)284 .mount_as_scoped(&server)285 .await;286 let request = ApiRequest::new(287 ApiMethod::Get,288 ["namespaces", "acme", "repositories", "tooling", "commits"]289 .into_iter()290 .map(str::to_owned)291 .collect(),292 )293 .query("ref", "feature/docs");294295 let response = api(&server)296 .execute(request)297 .await298 .expect("authenticated API response")299 .ensure_success()300 .expect("success status");301302 assert_eq!(response.body, b"[]");303 assert_eq!(mock.received_requests().await.len(), 1);304 }305306 #[tokio::test]307 async fn version_route_uses_the_authenticated_root_api_path() {308 let server = MockServer::start().await;309 let mock = Mock::given(method("GET"))310 .and(path("/api/version"))311 .and(header("authorization", "Bearer test-pat"))312 .respond_with(313 ResponseTemplate::new(200)314 .insert_header("content-type", "application/json")315 .set_body_string(r#"{"version":"0.3.17"}"#),316 )317 .expect(1)318 .mount_as_scoped(&server)319 .await;320 let response = api(&server)321 .execute(ApiRequest::new(ApiMethod::Get, vec!["version".into()]).root_api())322 .await323 .expect("version response")324 .ensure_success()325 .expect("version request succeeds");326 assert_eq!(response.json_value().unwrap()["version"], "0.3.17");327 assert_eq!(mock.received_requests().await.len(), 1);328 }329330 #[tokio::test]331 async fn identifiers_are_encoded_as_individual_path_segments() {332 let server = MockServer::start().await;333 let mock = Mock::given(method("GET"))334 .and(path(335 "/api/v1/namespaces/team%2Fname/repositories/repo%20name",336 ))337 .respond_with(ResponseTemplate::new(200).set_body_string("{}"))338 .expect(1)339 .mount_as_scoped(&server)340 .await;341342 api(&server)343 .execute(ApiRequest::new(344 ApiMethod::Get,345 ["namespaces", "team/name", "repositories", "repo name"]346 .into_iter()347 .map(str::to_owned)348 .collect(),349 ))350 .await351 .expect("request succeeds");352 assert_eq!(mock.received_requests().await.len(), 1);353 }354355 #[tokio::test]356 async fn json_and_binary_bodies_use_their_documented_content_types() {357 let server = MockServer::start().await;358 let json = Mock::given(method("PATCH"))359 .and(path("/api/v1/namespaces/acme"))360 .and(header("content-type", "application/json"))361 .and(body_json(serde_json::json!({"name":"new-name"})))362 .respond_with(ResponseTemplate::new(200).set_body_string("{}"))363 .expect(1)364 .mount_as_scoped(&server)365 .await;366 api(&server)367 .execute(368 ApiRequest::new(ApiMethod::Patch, vec!["namespaces".into(), "acme".into()])369 .json(serde_json::json!({"name":"new-name"})),370 )371 .await372 .expect("JSON request");373 assert_eq!(json.received_requests().await.len(), 1);374375 let binary = Mock::given(method("PUT"))376 .and(path(377 "/api/v1/namespaces/acme/repositories/tooling/binaries/1.2.3/tool",378 ))379 .and(header("content-type", "application/octet-stream"))380 .and(wiremock::matchers::body_bytes(vec![0, 255, 10]))381 .respond_with(ResponseTemplate::new(200).set_body_string("{}"))382 .expect(1)383 .mount_as_scoped(&server)384 .await;385 api(&server)386 .execute(387 ApiRequest::new(388 ApiMethod::Put,389 [390 "namespaces",391 "acme",392 "repositories",393 "tooling",394 "binaries",395 "1.2.3",396 "tool",397 ]398 .into_iter()399 .map(str::to_owned)400 .collect(),401 )402 .binary(vec![0, 255, 10]),403 )404 .await405 .expect("binary request");406 assert_eq!(binary.received_requests().await.len(), 1);407 }408409 #[tokio::test]410 async fn binary_download_returns_the_original_response_bytes() {411 let server = MockServer::start().await;412 let mock = Mock::given(method("GET"))413 .and(path(414 "/api/v1/namespaces/acme/repositories/tooling/binaries/latest/tool",415 ))416 .and(header("authorization", "Bearer test-pat"))417 .respond_with(418 ResponseTemplate::new(200)419 .insert_header("content-type", "application/octet-stream")420 .set_body_bytes(vec![0, 255, 10]),421 )422 .expect(1)423 .mount_as_scoped(&server)424 .await;425 let response = api(&server)426 .execute(ApiRequest::new(427 ApiMethod::Get,428 [429 "namespaces",430 "acme",431 "repositories",432 "tooling",433 "binaries",434 "latest",435 "tool",436 ]437 .into_iter()438 .map(str::to_owned)439 .collect(),440 ))441 .await442 .expect("binary response")443 .ensure_success()444 .expect("download succeeded");445 assert_eq!(response.body, [0, 255, 10]);446 assert_eq!(447 response.content_type.as_deref(),448 Some("application/octet-stream")449 );450 assert_eq!(mock.received_requests().await.len(), 1);451 }452453 #[tokio::test]454 async fn stale_content_head_is_reported_without_retry() {455 let server = MockServer::start().await;456 let mock = Mock::given(method("PUT"))457 .and(path(458 "/api/v1/namespaces/acme/repositories/tooling/contents",459 ))460 .and(query_param("ref", "main"))461 .and(query_param("path", "README.md"))462 .and(header("authorization", "Bearer test-pat"))463 .and(body_json(serde_json::json!({464 "content":"hello",465 "encoding":"utf8",466 "message":"Update README",467 "expected_head":"stale-head"468 })))469 .respond_with(ResponseTemplate::new(409).set_body_string(470 r#"{"error":{"code":"conflict","message":"The branch has changed"}}"#,471 ))472 .expect(1)473 .mount_as_scoped(&server)474 .await;475 let response = api(&server)476 .execute(477 ApiRequest::new(478 ApiMethod::Put,479 ["namespaces", "acme", "repositories", "tooling", "contents"]480 .into_iter()481 .map(str::to_owned)482 .collect(),483 )484 .query("ref", "main")485 .query("path", "README.md")486 .json(serde_json::json!({487 "content":"hello",488 "encoding":"utf8",489 "message":"Update README",490 "expected_head":"stale-head"491 })),492 )493 .await494 .expect("HTTP request completes");495 let error = response496 .ensure_success()497 .expect_err("stale branch head must conflict")498 .to_string();499 assert!(error.contains("HTTP 409 (conflict)"));500 assert!(error.contains("The branch has changed"));501 assert_eq!(mock.received_requests().await.len(), 1);502 }503504 #[test]505 fn empty_access_tokens_are_rejected_before_a_client_is_created() {506 let error = HttpTwigApi::new(507 TwigUrl::parse("http://127.0.0.1:1/").expect("valid loopback URL"),508 String::new(),509 )510 .err()511 .expect("empty token must not create an authenticated client")512 .to_string();513 assert!(error.contains("access token is empty"));514 }515516 #[tokio::test]517 async fn errors_expose_stable_api_code_and_message_without_raw_body_fallback() {518 let server = MockServer::start().await;519 Mock::given(method("GET"))520 .and(path("/api/v1/me"))521 .respond_with(ResponseTemplate::new(403).set_body_string(522 r#"{"error":{"code":"forbidden","message":"The required permission is not granted"}}"#,523 ))524 .mount(&server)525 .await;526 let error = api(&server)527 .execute(ApiRequest::new(ApiMethod::Get, vec!["me".into()]))528 .await529 .expect("HTTP request")530 .ensure_success()531 .expect_err("403 must be an error")532 .to_string();533 assert!(error.contains("HTTP 403 (forbidden)"));534 assert!(error.contains("The required permission is not granted"));535536 let malformed = super::ApiResponse {537 status: 500,538 content_type: Some("application/json".into()),539 body: b"internal database secret".to_vec(),540 }541 .ensure_success()542 .expect_err("500 must be an error")543 .to_string();544 assert!(malformed.contains("HTTP 500"));545 assert!(!malformed.contains("database secret"));546 }547548 #[tokio::test]549 async fn api_client_does_not_follow_redirects() {550 let server = MockServer::start().await;551 Mock::given(method("GET"))552 .and(path("/api/v1/me"))553 .respond_with(554 ResponseTemplate::new(302).insert_header("location", "https://other.example/me"),555 )556 .mount(&server)557 .await;558 let response = api(&server)559 .execute(ApiRequest::new(ApiMethod::Get, vec!["me".into()]))560 .await561 .expect("redirect response")562 .ensure_success()563 .expect_err("redirect is not successful");564 assert!(response.to_string().contains("HTTP 302"));565 }566567 #[test]568 fn request_builder_types_cover_all_body_modes() {569 let request = ApiRequest::new(ApiMethod::Delete, vec!["content".into()]);570 assert_eq!(request.body, ApiBody::Empty);571 }572}