1use crate::http::{HttpRequest, HttpResponse};
7use sha2::{Digest, Sha256};
8use std::collections::HashMap;
9use std::sync::{Mutex, OnceLock};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12pub const DEFAULT_PER_PAGE: usize = 30;
13pub const MAX_PER_PAGE: usize = 100;
14pub const DEFAULT_API_RATE_LIMIT_PER_MIN: u32 = 10_000;
15pub const DEFAULT_MAX_BODY_BYTES: usize = 64 * 1024 * 1024;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct PageParams {
19 pub page: usize,
20 pub per_page: usize,
21}
22
23impl PageParams {
24 pub fn from_query(query: &str) -> Self {
25 let mut page = 1usize;
26 let mut per_page = DEFAULT_PER_PAGE;
27 for part in query.split('&') {
28 if let Some((k, v)) = part.split_once('=') {
29 match k {
30 "page" => {
31 if let Ok(p) = v.parse::<usize>() {
32 page = p.max(1);
33 }
34 }
35 "per_page" => {
36 if let Ok(pp) = v.parse::<usize>() {
37 per_page = pp.clamp(1, MAX_PER_PAGE);
38 }
39 }
40 _ => {}
41 }
42 }
43 }
44 Self { page, per_page }
45 }
46}
47
48pub fn paginate_slice<T>(items: &[T], params: PageParams) -> (&[T], usize) {
50 let total = items.len();
51 let start = params
52 .page
53 .saturating_sub(1)
54 .saturating_mul(params.per_page);
55 if start >= total {
56 return (&items[total..total], total);
57 }
58 let end = start.saturating_add(params.per_page).min(total);
59 (&items[start..end], total)
60}
61
62pub fn format_link_header(base_path: &str, params: PageParams, total: usize) -> Option<String> {
64 let last_page = total.div_ceil(params.per_page).max(1);
65 if last_page <= 1 && params.page == 1 {
66 return None;
67 }
68 let mut links = Vec::new();
69 let pp = params.per_page;
70 if params.page < last_page {
71 links.push(format!(
72 "<{base_path}?page={}&per_page={pp}>; rel=\"next\"",
73 params.page + 1
74 ));
75 }
76 if params.page > 1 {
77 let prev = (params.page - 1).min(last_page);
78 links.push(format!(
79 "<{base_path}?page={prev}&per_page={pp}>; rel=\"prev\""
80 ));
81 }
82 links.push(format!("<{base_path}?page=1&per_page={pp}>; rel=\"first\""));
83 links.push(format!(
84 "<{base_path}?page={last_page}&per_page={pp}>; rel=\"last\""
85 ));
86 Some(links.join(", "))
87}
88
89pub fn attach_pagination_headers(
91 resp: &mut HttpResponse,
92 base_path: &str,
93 params: PageParams,
94 total: usize,
95) {
96 resp.extra_headers
97 .push(("X-Total-Count".into(), total.to_string()));
98 if let Some(link) = format_link_header(base_path, params, total) {
99 resp.extra_headers.push(("Link".into(), link));
100 }
101}
102
103pub fn compute_etag(body: &[u8]) -> String {
105 let digest = Sha256::digest(body);
106 let mut hex = String::with_capacity(32);
107 for b in &digest[..16] {
108 hex.push_str(&format!("{b:02x}"));
109 }
110 format!("\"sha256-{hex}\"")
111}
112
113pub fn apply_etag_and_conditional_get(req: &HttpRequest, resp: &mut HttpResponse) {
115 if resp.status != 200 {
116 return;
117 }
118 let etag = compute_etag(&resp.body);
119 resp.extra_headers.push(("ETag".into(), etag.clone()));
120 if let Some(inm) = req.header("if-none-match") {
121 let matches = inm.split(',').map(str::trim).any(|cand| {
122 cand == "*" || cand == etag || cand.strip_prefix("W/") == Some(etag.as_str())
123 });
124 if matches {
125 resp.status = 304;
126 resp.body.clear();
127 }
128 }
129}
130
131pub fn check_if_match(
134 req: &HttpRequest,
135 current_etag: &str,
136 required: bool,
137) -> Result<(), HttpResponse> {
138 match req.header("if-match") {
139 Some(hdr) => {
140 let ok = hdr
141 .split(',')
142 .map(str::trim)
143 .any(|cand| cand == "*" || cand == current_etag);
144 if ok {
145 Ok(())
146 } else {
147 Err(crate::web::api::problem::problem_response(
148 412,
149 "precondition-failed",
150 "Precondition Failed",
151 "If-Match ETag does not match current resource state",
152 &req.path,
153 ))
154 }
155 }
156 None if required => Err(crate::web::api::problem::problem_response(
157 428,
158 "precondition-required",
159 "Precondition Required",
160 "If-Match header is required for this update",
161 &req.path,
162 )),
163 None => Ok(()),
164 }
165}
166
167#[derive(Clone, Copy, Debug)]
168pub struct RateLimitDecision {
169 pub allowed: bool,
170 pub limit: u32,
171 pub remaining: u32,
172 pub reset_secs: u64,
173 pub reset_unix: u64,
174}
175
176#[derive(Default)]
177struct RateWindow {
178 window_start: u64,
179 count: u32,
180}
181
182static GLOBAL_API_LIMITER: OnceLock<Mutex<HashMap<String, RateWindow>>> = OnceLock::new();
183
184fn now_unix_u64() -> u64 {
185 SystemTime::now()
186 .duration_since(UNIX_EPOCH)
187 .map(|d| d.as_secs())
188 .unwrap_or(0)
189}
190
191pub fn configured_api_rate_limit() -> u32 {
192 std::env::var("ARKS_API_RATE_LIMIT_PER_MIN")
193 .ok()
194 .and_then(|v| v.trim().parse::<u32>().ok())
195 .unwrap_or(DEFAULT_API_RATE_LIMIT_PER_MIN)
196}
197
198pub fn check_api_rate_limit(client_key: &str) -> RateLimitDecision {
201 check_api_rate_limit_with_cap(client_key, configured_api_rate_limit())
202}
203
204pub fn check_api_rate_limit_with_cap(client_key: &str, limit: u32) -> RateLimitDecision {
205 let now = now_unix_u64();
206 if limit == 0 {
207 return RateLimitDecision {
208 allowed: true,
209 limit: 0,
210 remaining: 0,
211 reset_secs: 60,
212 reset_unix: now + 60,
213 };
214 }
215 let map = GLOBAL_API_LIMITER.get_or_init(|| Mutex::new(HashMap::new()));
216 let Ok(mut guard) = map.lock() else {
217 return RateLimitDecision {
218 allowed: true,
219 limit,
220 remaining: limit,
221 reset_secs: 60,
222 reset_unix: now + 60,
223 };
224 };
225 let win = guard.entry(client_key.to_string()).or_default();
226 if now.saturating_sub(win.window_start) >= 60 {
227 win.window_start = now;
228 win.count = 0;
229 }
230 let reset_unix = win.window_start + 60;
231 let reset_secs = reset_unix.saturating_sub(now).max(1);
232 if win.count >= limit {
233 RateLimitDecision {
234 allowed: false,
235 limit,
236 remaining: 0,
237 reset_secs,
238 reset_unix,
239 }
240 } else {
241 win.count += 1;
242 RateLimitDecision {
243 allowed: true,
244 limit,
245 remaining: limit.saturating_sub(win.count),
246 reset_secs,
247 reset_unix,
248 }
249 }
250}
251
252pub fn attach_rate_limit_headers(resp: &mut HttpResponse, dec: RateLimitDecision) {
254 if dec.limit == 0 {
255 return;
256 }
257 resp.extra_headers
258 .push(("RateLimit-Policy".into(), format!("{};w=60", dec.limit)));
259 resp.extra_headers.push((
260 "RateLimit".into(),
261 format!(
262 "limit={}, remaining={}, reset={}",
263 dec.limit, dec.remaining, dec.reset_secs
264 ),
265 ));
266 resp.extra_headers
267 .push(("X-RateLimit-Limit".into(), dec.limit.to_string()));
268 resp.extra_headers
269 .push(("X-RateLimit-Remaining".into(), dec.remaining.to_string()));
270 resp.extra_headers
271 .push(("X-RateLimit-Reset".into(), dec.reset_unix.to_string()));
272}
273
274pub fn rate_limit_exceeded_response(path: &str, dec: RateLimitDecision) -> HttpResponse {
276 let mut resp = crate::web::api::problem::problem_response(
277 429,
278 "rate-limit-exceeded",
279 "Too Many Requests",
280 "API rate limit exceeded; retry after reset window",
281 path,
282 );
283 resp.extra_headers
284 .push(("Retry-After".into(), dec.reset_secs.to_string()));
285 attach_rate_limit_headers(&mut resp, dec);
286 resp
287}
288
289pub fn check_body_quota(req: &HttpRequest) -> Result<(), HttpResponse> {
291 let max_bytes = std::env::var("ARKS_MAX_BODY_BYTES")
292 .ok()
293 .and_then(|v| v.trim().parse::<usize>().ok())
294 .unwrap_or(DEFAULT_MAX_BODY_BYTES);
295 if max_bytes > 0 && req.body.len() > max_bytes {
296 return Err(crate::web::api::problem::problem_response(
297 413,
298 "payload-too-large",
299 "Payload Too Large",
300 format!("Request body exceeds maximum allowed size ({max_bytes} bytes)"),
301 &req.path,
302 ));
303 }
304 Ok(())
305}
306
307pub fn check_storage_quota(
309 path: &str,
310 used_bytes: u64,
311 incoming_bytes: u64,
312 max_bytes: u64,
313) -> Result<(), HttpResponse> {
314 if max_bytes > 0 && used_bytes.saturating_add(incoming_bytes) > max_bytes {
315 return Err(crate::web::api::problem::problem_response(
316 507,
317 "insufficient-storage",
318 "Insufficient Storage",
319 format!("Storage quota exceeded (limit {max_bytes} bytes)"),
320 path,
321 ));
322 }
323 Ok(())
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 #[test]
331 fn pagination_clamps_per_page_and_formats_rfc8288_links() {
332 let p = PageParams::from_query("page=2&per_page=999");
333 assert_eq!(p.page, 2);
334 assert_eq!(p.per_page, MAX_PER_PAGE);
335
336 let items: Vec<usize> = (0..75).collect();
337 let p2 = PageParams::from_query("page=2&per_page=30");
338 let (slice, total) = paginate_slice(&items, p2);
339 assert_eq!(total, 75);
340 assert_eq!(slice.len(), 30);
341 assert_eq!(slice[0], 30);
342
343 let link = format_link_header("/repos/a/b/issues", p2, total).unwrap();
344 assert!(link.contains("page=3&per_page=30>; rel=\"next\""));
345 assert!(link.contains("page=1&per_page=30>; rel=\"prev\""));
346 assert!(link.contains("page=1&per_page=30>; rel=\"first\""));
347 assert!(link.contains("page=3&per_page=30>; rel=\"last\""));
348 }
349
350 #[test]
351 fn etag_conditional_get_and_if_match_preconditions() {
352 let mut resp = HttpResponse {
353 status: 200,
354 content_type: "application/json".into(),
355 body: br#"{"id":1}"#.to_vec(),
356 www_authenticate: None,
357 extra_headers: Vec::new(),
358 };
359 let req0 = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
360 apply_etag_and_conditional_get(&req0, &mut resp);
361 let etag = resp
362 .extra_headers
363 .iter()
364 .find(|(k, _)| k == "ETag")
365 .unwrap()
366 .1
367 .clone();
368 assert!(etag.starts_with("\"sha256-"));
369
370 let mut resp2 = HttpResponse {
371 status: 200,
372 content_type: "application/json".into(),
373 body: br#"{"id":1}"#.to_vec(),
374 www_authenticate: None,
375 extra_headers: Vec::new(),
376 };
377 let req_inm = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new())
378 .with_header("If-None-Match", &etag);
379 apply_etag_and_conditional_get(&req_inm, &mut resp2);
380 assert_eq!(resp2.status, 304);
381 assert!(resp2.body.is_empty());
382
383 let req_bad = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new())
384 .with_header("If-Match", "\"sha256-stale\"");
385 assert_eq!(
386 check_if_match(&req_bad, &etag, false).unwrap_err().status,
387 412
388 );
389
390 let req_missing = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new());
391 assert_eq!(
392 check_if_match(&req_missing, &etag, true)
393 .unwrap_err()
394 .status,
395 428
396 );
397 }
398
399 #[test]
400 fn rate_limiter_emits_ietf_and_compat_headers_and_429() {
401 let key = "test-rate-limit-client-1";
402 let d1 = check_api_rate_limit_with_cap(key, 2);
403 assert!(d1.allowed && d1.remaining == 1);
404 let d2 = check_api_rate_limit_with_cap(key, 2);
405 assert!(d2.allowed && d2.remaining == 0);
406 let d3 = check_api_rate_limit_with_cap(key, 2);
407 assert!(!d3.allowed && d3.remaining == 0);
408
409 let resp = rate_limit_exceeded_response("/api/v1/issues", d3);
410 assert_eq!(resp.status, 429);
411 assert!(
412 resp.extra_headers
413 .iter()
414 .any(|(k, _)| k == "RateLimit-Policy")
415 );
416 assert!(resp.extra_headers.iter().any(|(k, _)| k == "RateLimit"));
417 assert!(
418 resp.extra_headers
419 .iter()
420 .any(|(k, _)| k == "X-RateLimit-Limit")
421 );
422 assert!(resp.extra_headers.iter().any(|(k, _)| k == "Retry-After"));
423 }
424
425 #[test]
426 fn storage_quota_returns_507() {
427 let err = check_storage_quota("/info/lfs/objects", 900, 200, 1000).unwrap_err();
428 assert_eq!(err.status, 507);
429 }
430}