gitea-sdk-rs 0.1.0

Rust SDK for the Gitea API
Documentation
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Copyright 2026 infinitete. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//! HTTP request helpers for the Gitea API client.

use bytes::Bytes;
use reqwest::header::HeaderMap;

use crate::Client;
use crate::Response;
use crate::response::response_from_reqwest;

// ── HTTP request pipeline (mirrors go-sdk/gitea/client.go) ─────────

impl Client {
    /// Prepare a [`reqwest::RequestBuilder`] with URL, auth headers, and
    /// caller headers.  The caller is responsible for attaching the body
    /// (via `.body()` or `.multipart()`), then calling
    /// [`Self::finish_request`] to build, sign, and return.
    fn prepare_request(
        &self,
        method: &reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
    ) -> crate::Result<(reqwest::Client, reqwest::RequestBuilder, String, bool)> {
        let http_client = self.http_client();

        let (base_url, access_token, otp, username, password, sudo, user_agent, debug) = {
            let config = self.read_config();
            (
                config.base_url.clone(),
                config.access_token.clone(),
                config.otp.clone(),
                config.username.clone(),
                config.password.clone(),
                config.sudo.clone(),
                config.user_agent.clone(),
                config.debug,
            )
        };

        let url = format!("{base_url}/api/v1{path}");

        let mut req = http_client
            .request(method.clone(), &url)
            .header("Accept", "application/json");

        // Auth header injection — exact order from Go SDK doRequest:
        // 1. Token → Authorization: token {access_token}
        if !access_token.is_empty() {
            req = req.header("Authorization", format!("token {access_token}"));
        }
        // 2. OTP → X-GITEA-OTP
        if !otp.is_empty() {
            req = req.header("X-GITEA-OTP", &*otp);
        }
        // 3. Basic Auth
        if !username.is_empty() {
            req = req.basic_auth(&*username, Some(&*password));
        }
        // 4. Sudo
        if !sudo.is_empty() {
            req = req.header("Sudo", &*sudo);
        }
        // 5. User-Agent
        if !user_agent.is_empty() {
            req = req.header("User-Agent", &*user_agent);
        }

        if let Some(hdrs) = headers {
            for (k, v) in hdrs.iter() {
                req = req.header(k, v);
            }
        }

        Ok((http_client, req, url, debug))
    }

    /// Build a [`reqwest::Request`] from a builder, apply debug logging and
    /// SSH signing.
    fn finish_request(
        &self,
        http_client: reqwest::Client,
        req: reqwest::RequestBuilder,
        method: &reqwest::Method,
        url: &str,
        debug: bool,
    ) -> crate::Result<(reqwest::Client, reqwest::Request)> {
        if debug {
            tracing::debug!("{}: {}", method, url);
        }

        let mut built_req = req.build()?;

        {
            let signer = self.ssh_signer();
            if let Some(ref signer) = *signer {
                let use_legacy = self.should_use_legacy_ssh();
                crate::auth::ssh_sign::sign_request(&mut built_req, signer, use_legacy)?;
            }
        }

        Ok((http_client, built_req))
    }

    /// Layer 0 (internal): Build and send a request, returning the raw
    /// `reqwest::Response` so that higher layers can decide how to consume
    /// the body.
    ///
    /// Auth header injection order matches Go SDK `doRequest` exactly:
    /// token → OTP → basic auth → sudo → user-agent → caller headers.
    async fn do_request_raw<B: Into<reqwest::Body>>(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        body: Option<B>,
    ) -> crate::Result<reqwest::Response> {
        let (http_client, req, url, debug) = self.prepare_request(&method, path, headers)?;
        let req = if let Some(b) = body { req.body(b) } else { req };
        let (http_client, built_req) =
            self.finish_request(http_client, req, &method, &url, debug)?;
        let resp = http_client.execute(built_req).await?;
        Ok(resp)
    }

    /// Layer 1: Status check only, discards the body.
    ///
    /// Used for DELETE and other operations where only the status code matters.
    /// Matches Go SDK `doRequestWithStatusHandle`.
    pub(crate) async fn do_request_with_status_handle<B: Into<reqwest::Body>>(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        body: Option<B>,
    ) -> crate::Result<Response> {
        let resp = self.do_request_raw(method, path, headers, body).await?;
        let response = response_from_reqwest(&resp);

        // Check for errors — reads and discards the body on error.
        let status = resp.status().as_u16();
        if status / 100 != 2 {
            let err_bytes = resp.bytes().await.unwrap_or_default();
            status_code_to_err(status, &err_bytes)?;
        }

        Ok(response)
    }

    /// Layer 2: Return status code without checking for errors.
    ///
    /// Matches Go SDK `getStatusCode`.
    pub(crate) async fn get_status_code<B: Into<reqwest::Body>>(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        body: Option<B>,
    ) -> crate::Result<(u16, Response)> {
        let resp = self.do_request_raw(method, path, headers, body).await?;
        let response = response_from_reqwest(&resp);
        let status = resp.status().as_u16();
        Ok((status, response))
    }

    /// Layer 3: Read response body and check for errors.
    ///
    /// Returns `(body bytes, Response)` on success (2xx).
    /// Matches Go SDK `getResponse`.
    pub(crate) async fn get_response<B: Into<reqwest::Body>>(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        body: Option<B>,
    ) -> crate::Result<(Bytes, Response)> {
        let resp = self.do_request_raw(method, path, headers, body).await?;
        let response = response_from_reqwest(&resp);
        let status = resp.status().as_u16();

        if status / 100 != 2 {
            let err_bytes = resp.bytes().await.unwrap_or_default();
            status_code_to_err(status, &err_bytes)?;
            // Unreachable: status_code_to_err returns Err for non-2xx.
            unreachable!()
        }

        let data = resp.bytes().await?;
        Ok((data, response))
    }

    /// Layer 4: Read response body, check for errors, and deserialize JSON.
    ///
    /// Returns `(T, Response)` on success.
    /// Matches Go SDK `getParsedResponse`.
    pub(crate) async fn get_parsed_response<
        T: serde::de::DeserializeOwned,
        B: Into<reqwest::Body>,
    >(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        body: Option<B>,
    ) -> crate::Result<(T, Response)> {
        let (data, response) = self.get_response(method, path, headers, body).await?;
        let value: T = serde_json::from_slice(&data)?;
        Ok((value, response))
    }

    /// Layer 5: Send a multipart request, check for errors, and deserialize JSON.
    ///
    /// Returns `(T, Response)` on success.
    /// Used for file upload endpoints (e.g. release attachments).
    pub(crate) async fn get_parsed_response_multipart<T: serde::de::DeserializeOwned>(
        &self,
        method: reqwest::Method,
        path: &str,
        headers: Option<&HeaderMap>,
        form: reqwest::multipart::Form,
    ) -> crate::Result<(T, Response)> {
        let (http_client, req, url, debug) = self.prepare_request(&method, path, headers)?;
        let (http_client, built_req) =
            self.finish_request(http_client, req.multipart(form), &method, &url, debug)?;
        let resp = http_client.execute(built_req).await?;
        let response = response_from_reqwest(&resp);
        let status = resp.status().as_u16();

        if status / 100 != 2 {
            let err_bytes = resp.bytes().await.unwrap_or_default();
            status_code_to_err(status, &err_bytes)?;
            unreachable!()
        }

        let data = resp.bytes().await?.to_vec();
        let value: T = serde_json::from_slice(&data)?;
        Ok((value, response))
    }
}

// ── Error mapping (pure function, no Client dependency) ─────────────

/// Convert an HTTP status code and response body into an appropriate
/// [`crate::Error`] variant.
///
/// Returns `Ok(())` for 2xx status codes. For non-2xx:
/// - If the body is valid JSON with a `"message"` field → [`Error::Api`](crate::Error::Api)
/// - Otherwise → [`Error::UnknownApi`](crate::Error::UnknownApi)
///
/// Matches Go SDK `statusCodeToErr`.
fn status_code_to_err(status: u16, body: &[u8]) -> crate::Result<()> {
    if status / 100 == 2 {
        return Ok(());
    }

    if let Ok(err_map) = serde_json::from_slice::<serde_json::Value>(body)
        && let Some(message) = err_map.get("message").and_then(|v| v.as_str())
    {
        return Err(crate::Error::Api {
            status,
            message: message.to_string(),
            body: body.to_vec(),
        });
    }

    Err(crate::Error::UnknownApi {
        status,
        body: String::from_utf8_lossy(body).to_string(),
    })
}

// ── Tests ───────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_status_code_to_err_success() {
        assert!(status_code_to_err(200, b"").is_ok());
        assert!(status_code_to_err(201, b"created").is_ok());
        assert!(status_code_to_err(299, b"").is_ok());
    }

    #[test]
    fn test_status_code_to_err_api_error() {
        let body = br#"{"message":"Not Found"}"#;
        let err = status_code_to_err(404, body).unwrap_err();
        match err {
            crate::Error::Api {
                status,
                message,
                body: err_body,
            } => {
                assert_eq!(status, 404);
                assert_eq!(message, "Not Found");
                assert_eq!(err_body, body.as_slice());
            }
            other => panic!("expected Error::Api, got: {other}"),
        }
    }

    #[test]
    fn test_status_code_to_err_unknown_api() {
        let body = b"Internal Server Error";
        let err = status_code_to_err(500, body).unwrap_err();
        match err {
            crate::Error::UnknownApi {
                status,
                body: err_body,
            } => {
                assert_eq!(status, 500);
                assert_eq!(err_body, "Internal Server Error");
            }
            other => panic!("expected Error::UnknownApi, got: {other}"),
        }
    }

    #[test]
    fn test_status_code_to_err_json_no_message() {
        let body = br#"{"error":"bad request"}"#;
        let err = status_code_to_err(400, body).unwrap_err();
        match err {
            crate::Error::UnknownApi {
                status,
                body: err_body,
            } => {
                assert_eq!(status, 400);
                assert_eq!(err_body, r#"{"error":"bad request"}"#);
            }
            other => panic!("expected Error::UnknownApi, got: {other}"),
        }
    }

    #[test]
    fn test_status_code_to_err_empty_body() {
        let body = b"";
        let err = status_code_to_err(500, body).unwrap_err();
        match err {
            crate::Error::UnknownApi {
                status,
                body: err_body,
            } => {
                assert_eq!(status, 500);
                assert!(err_body.is_empty());
            }
            other => panic!("expected Error::UnknownApi, got: {other}"),
        }
    }

    #[test]
    fn test_status_code_to_err_array_body() {
        // Valid JSON array but not an object with "message".
        let body = b"[]";
        let err = status_code_to_err(500, body).unwrap_err();
        match err {
            crate::Error::UnknownApi { status, .. } => {
                assert_eq!(status, 500);
            }
            other => panic!("expected Error::UnknownApi, got: {other}"),
        }
    }

    #[test]
    fn test_status_code_to_err_message_with_number() {
        // "message" is not a string — should fall through to UnknownApi.
        let body = br#"{"message":42}"#;
        let err = status_code_to_err(422, body).unwrap_err();
        assert!(
            matches!(err, crate::Error::UnknownApi { .. }),
            "expected Error::UnknownApi when message is not a string, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_do_request_raw_signs_when_ssh_signer_present() {
        use wiremock::matchers::{header_exists, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/api/v1/version"))
            .and(header_exists("Signature"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"version": "1.22.0"})),
            )
            .mount(&server)
            .await;

        let tmp = std::env::temp_dir().join("gitea_sdk_test_ssh_wiremock_sign");
        std::fs::write(
            &tmp,
            include_bytes!("../../tests/ssh_fixtures/id_ed25519_test"),
        )
        .expect("write temp key");

        let client = crate::Client::builder(&server.uri())
            .ssh_cert("test-principal", &tmp, None::<&str>)
            .expect("ssh_cert should succeed")
            .build()
            .expect("build should succeed");

        let (version, _resp) = client
            .miscellaneous()
            .get_version()
            .await
            .expect("get_version should succeed");
        assert_eq!(version, "1.22.0");
        let _ = std::fs::remove_file(&tmp);
    }

    #[tokio::test]
    async fn test_do_request_raw_no_signature_when_no_ssh_signer() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/api/v1/version"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"version": "1.22.0"})),
            )
            .mount(&server)
            .await;

        let client = crate::Client::builder(&server.uri())
            .build()
            .expect("build should succeed");

        let (version, _resp) = client
            .miscellaneous()
            .get_version()
            .await
            .expect("get_version should succeed");
        assert_eq!(version, "1.22.0");
    }
}