use crate::http::{HttpRequest, HttpResponse};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
pub const DEFAULT_PER_PAGE: usize = 30;
pub const MAX_PER_PAGE: usize = 100;
pub const DEFAULT_API_RATE_LIMIT_PER_MIN: u32 = 10_000;
pub const DEFAULT_MAX_BODY_BYTES: usize = 64 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PageParams {
pub page: usize,
pub per_page: usize,
}
impl PageParams {
pub fn from_query(query: &str) -> Self {
let mut page = 1usize;
let mut per_page = DEFAULT_PER_PAGE;
for part in query.split('&') {
if let Some((k, v)) = part.split_once('=') {
match k {
"page" => {
if let Ok(p) = v.parse::<usize>() {
page = p.max(1);
}
}
"per_page" => {
if let Ok(pp) = v.parse::<usize>() {
per_page = pp.clamp(1, MAX_PER_PAGE);
}
}
_ => {}
}
}
}
Self { page, per_page }
}
}
pub fn paginate_slice<T>(items: &[T], params: PageParams) -> (&[T], usize) {
let total = items.len();
let start = params
.page
.saturating_sub(1)
.saturating_mul(params.per_page);
if start >= total {
return (&items[total..total], total);
}
let end = start.saturating_add(params.per_page).min(total);
(&items[start..end], total)
}
pub fn format_link_header(base_path: &str, params: PageParams, total: usize) -> Option<String> {
let last_page = total.div_ceil(params.per_page).max(1);
if last_page <= 1 && params.page == 1 {
return None;
}
let mut links = Vec::new();
let pp = params.per_page;
if params.page < last_page {
links.push(format!(
"<{base_path}?page={}&per_page={pp}>; rel=\"next\"",
params.page + 1
));
}
if params.page > 1 {
let prev = (params.page - 1).min(last_page);
links.push(format!(
"<{base_path}?page={prev}&per_page={pp}>; rel=\"prev\""
));
}
links.push(format!("<{base_path}?page=1&per_page={pp}>; rel=\"first\""));
links.push(format!(
"<{base_path}?page={last_page}&per_page={pp}>; rel=\"last\""
));
Some(links.join(", "))
}
pub fn attach_pagination_headers(
resp: &mut HttpResponse,
base_path: &str,
params: PageParams,
total: usize,
) {
resp.extra_headers
.push(("X-Total-Count".into(), total.to_string()));
if let Some(link) = format_link_header(base_path, params, total) {
resp.extra_headers.push(("Link".into(), link));
}
}
pub fn compute_etag(body: &[u8]) -> String {
let digest = Sha256::digest(body);
let mut hex = String::with_capacity(32);
for b in &digest[..16] {
hex.push_str(&format!("{b:02x}"));
}
format!("\"sha256-{hex}\"")
}
pub fn apply_etag_and_conditional_get(req: &HttpRequest, resp: &mut HttpResponse) {
if resp.status != 200 {
return;
}
let etag = compute_etag(&resp.body);
resp.extra_headers.push(("ETag".into(), etag.clone()));
if let Some(inm) = req.header("if-none-match") {
let matches = inm.split(',').map(str::trim).any(|cand| {
cand == "*" || cand == etag || cand.strip_prefix("W/") == Some(etag.as_str())
});
if matches {
resp.status = 304;
resp.body.clear();
}
}
}
pub fn check_if_match(
req: &HttpRequest,
current_etag: &str,
required: bool,
) -> Result<(), HttpResponse> {
match req.header("if-match") {
Some(hdr) => {
let ok = hdr
.split(',')
.map(str::trim)
.any(|cand| cand == "*" || cand == current_etag);
if ok {
Ok(())
} else {
Err(crate::web::api::problem::problem_response(
412,
"precondition-failed",
"Precondition Failed",
"If-Match ETag does not match current resource state",
&req.path,
))
}
}
None if required => Err(crate::web::api::problem::problem_response(
428,
"precondition-required",
"Precondition Required",
"If-Match header is required for this update",
&req.path,
)),
None => Ok(()),
}
}
#[derive(Clone, Copy, Debug)]
pub struct RateLimitDecision {
pub allowed: bool,
pub limit: u32,
pub remaining: u32,
pub reset_secs: u64,
pub reset_unix: u64,
}
#[derive(Default)]
struct RateWindow {
window_start: u64,
count: u32,
}
static GLOBAL_API_LIMITER: OnceLock<Mutex<HashMap<String, RateWindow>>> = OnceLock::new();
fn now_unix_u64() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
pub fn configured_api_rate_limit() -> u32 {
std::env::var("ARKS_API_RATE_LIMIT_PER_MIN")
.ok()
.and_then(|v| v.trim().parse::<u32>().ok())
.unwrap_or(DEFAULT_API_RATE_LIMIT_PER_MIN)
}
pub fn check_api_rate_limit(client_key: &str) -> RateLimitDecision {
check_api_rate_limit_with_cap(client_key, configured_api_rate_limit())
}
pub fn check_api_rate_limit_with_cap(client_key: &str, limit: u32) -> RateLimitDecision {
let now = now_unix_u64();
if limit == 0 {
return RateLimitDecision {
allowed: true,
limit: 0,
remaining: 0,
reset_secs: 60,
reset_unix: now + 60,
};
}
let map = GLOBAL_API_LIMITER.get_or_init(|| Mutex::new(HashMap::new()));
let Ok(mut guard) = map.lock() else {
return RateLimitDecision {
allowed: true,
limit,
remaining: limit,
reset_secs: 60,
reset_unix: now + 60,
};
};
let win = guard.entry(client_key.to_string()).or_default();
if now.saturating_sub(win.window_start) >= 60 {
win.window_start = now;
win.count = 0;
}
let reset_unix = win.window_start + 60;
let reset_secs = reset_unix.saturating_sub(now).max(1);
if win.count >= limit {
RateLimitDecision {
allowed: false,
limit,
remaining: 0,
reset_secs,
reset_unix,
}
} else {
win.count += 1;
RateLimitDecision {
allowed: true,
limit,
remaining: limit.saturating_sub(win.count),
reset_secs,
reset_unix,
}
}
}
pub fn attach_rate_limit_headers(resp: &mut HttpResponse, dec: RateLimitDecision) {
if dec.limit == 0 {
return;
}
resp.extra_headers
.push(("RateLimit-Policy".into(), format!("{};w=60", dec.limit)));
resp.extra_headers.push((
"RateLimit".into(),
format!(
"limit={}, remaining={}, reset={}",
dec.limit, dec.remaining, dec.reset_secs
),
));
resp.extra_headers
.push(("X-RateLimit-Limit".into(), dec.limit.to_string()));
resp.extra_headers
.push(("X-RateLimit-Remaining".into(), dec.remaining.to_string()));
resp.extra_headers
.push(("X-RateLimit-Reset".into(), dec.reset_unix.to_string()));
}
pub fn rate_limit_exceeded_response(path: &str, dec: RateLimitDecision) -> HttpResponse {
let mut resp = crate::web::api::problem::problem_response(
429,
"rate-limit-exceeded",
"Too Many Requests",
"API rate limit exceeded; retry after reset window",
path,
);
resp.extra_headers
.push(("Retry-After".into(), dec.reset_secs.to_string()));
attach_rate_limit_headers(&mut resp, dec);
resp
}
pub fn check_body_quota(req: &HttpRequest) -> Result<(), HttpResponse> {
let max_bytes = std::env::var("ARKS_MAX_BODY_BYTES")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(DEFAULT_MAX_BODY_BYTES);
if max_bytes > 0 && req.body.len() > max_bytes {
return Err(crate::web::api::problem::problem_response(
413,
"payload-too-large",
"Payload Too Large",
format!("Request body exceeds maximum allowed size ({max_bytes} bytes)"),
&req.path,
));
}
Ok(())
}
pub fn check_storage_quota(
path: &str,
used_bytes: u64,
incoming_bytes: u64,
max_bytes: u64,
) -> Result<(), HttpResponse> {
if max_bytes > 0 && used_bytes.saturating_add(incoming_bytes) > max_bytes {
return Err(crate::web::api::problem::problem_response(
507,
"insufficient-storage",
"Insufficient Storage",
format!("Storage quota exceeded (limit {max_bytes} bytes)"),
path,
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pagination_clamps_per_page_and_formats_rfc8288_links() {
let p = PageParams::from_query("page=2&per_page=999");
assert_eq!(p.page, 2);
assert_eq!(p.per_page, MAX_PER_PAGE);
let items: Vec<usize> = (0..75).collect();
let p2 = PageParams::from_query("page=2&per_page=30");
let (slice, total) = paginate_slice(&items, p2);
assert_eq!(total, 75);
assert_eq!(slice.len(), 30);
assert_eq!(slice[0], 30);
let link = format_link_header("/repos/a/b/issues", p2, total).unwrap();
assert!(link.contains("page=3&per_page=30>; rel=\"next\""));
assert!(link.contains("page=1&per_page=30>; rel=\"prev\""));
assert!(link.contains("page=1&per_page=30>; rel=\"first\""));
assert!(link.contains("page=3&per_page=30>; rel=\"last\""));
}
#[test]
fn etag_conditional_get_and_if_match_preconditions() {
let mut resp = HttpResponse {
status: 200,
content_type: "application/json".into(),
body: br#"{"id":1}"#.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let req0 = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new());
apply_etag_and_conditional_get(&req0, &mut resp);
let etag = resp
.extra_headers
.iter()
.find(|(k, _)| k == "ETag")
.unwrap()
.1
.clone();
assert!(etag.starts_with("\"sha256-"));
let mut resp2 = HttpResponse {
status: 200,
content_type: "application/json".into(),
body: br#"{"id":1}"#.to_vec(),
www_authenticate: None,
extra_headers: Vec::new(),
};
let req_inm = HttpRequest::new("GET", "/api/v1/issues", "", Vec::new())
.with_header("If-None-Match", &etag);
apply_etag_and_conditional_get(&req_inm, &mut resp2);
assert_eq!(resp2.status, 304);
assert!(resp2.body.is_empty());
let req_bad = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new())
.with_header("If-Match", "\"sha256-stale\"");
assert_eq!(
check_if_match(&req_bad, &etag, false).unwrap_err().status,
412
);
let req_missing = HttpRequest::new("PATCH", "/api/v1/issues/1", "", Vec::new());
assert_eq!(
check_if_match(&req_missing, &etag, true)
.unwrap_err()
.status,
428
);
}
#[test]
fn rate_limiter_emits_ietf_and_compat_headers_and_429() {
let key = "test-rate-limit-client-1";
let d1 = check_api_rate_limit_with_cap(key, 2);
assert!(d1.allowed && d1.remaining == 1);
let d2 = check_api_rate_limit_with_cap(key, 2);
assert!(d2.allowed && d2.remaining == 0);
let d3 = check_api_rate_limit_with_cap(key, 2);
assert!(!d3.allowed && d3.remaining == 0);
let resp = rate_limit_exceeded_response("/api/v1/issues", d3);
assert_eq!(resp.status, 429);
assert!(
resp.extra_headers
.iter()
.any(|(k, _)| k == "RateLimit-Policy")
);
assert!(resp.extra_headers.iter().any(|(k, _)| k == "RateLimit"));
assert!(
resp.extra_headers
.iter()
.any(|(k, _)| k == "X-RateLimit-Limit")
);
assert!(resp.extra_headers.iter().any(|(k, _)| k == "Retry-After"));
}
#[test]
fn storage_quota_returns_507() {
let err = check_storage_quota("/info/lfs/objects", 900, 200, 1000).unwrap_err();
assert_eq!(err.status, 507);
}
}