Skip to main content

arks_server/
lfs_locks.rs

1//! Git LFS File Locking API server (O-8) per `.spec/sot/git-lfs-locking.sot.md`.
2//!
3//! Endpoints:
4//! - `POST /info/lfs/locks` (create lock; 201 new, 409 conflict with existing lock)
5//! - `GET  /info/lfs/locks` (list locks with optional `path`, `id`, `limit`, `cursor`)
6//! - `POST /info/lfs/locks/verify` (partition locks into `ours` vs `theirs`)
7//! - `POST /info/lfs/locks/{id}/unlock` (release lock by owner or `force: true` admin)
8
9use crate::http::{HttpRequest, HttpResponse};
10use crate::web_ui::store::atomic_write_file;
11use serde::{Deserialize, Serialize};
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::time::{SystemTime, UNIX_EPOCH};
15
16pub const LFS_JSON_CONTENT_TYPE: &str = "application/vnd.git-lfs+json";
17
18#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
19pub struct LfsLockOwner {
20    pub name: String,
21}
22
23#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
24pub struct LfsLock {
25    pub id: String,
26    pub path: String,
27    pub locked_at: String,
28    pub owner: LfsLockOwner,
29}
30
31#[derive(Clone, Debug, Default, Serialize, Deserialize)]
32struct LfsLocksStore {
33    next_id: u64,
34    locks: Vec<LfsLock>,
35}
36
37fn locks_path(git_dir: &Path) -> PathBuf {
38    git_dir.join("arks-forge").join("lfs_locks.json")
39}
40
41fn load_locks(git_dir: &Path) -> LfsLocksStore {
42    let p = locks_path(git_dir);
43    fs::read(&p)
44        .ok()
45        .and_then(|b| serde_json::from_slice(&b).ok())
46        .unwrap_or_default()
47}
48
49fn save_locks(git_dir: &Path, store: &LfsLocksStore) -> std::io::Result<()> {
50    let p = locks_path(git_dir);
51    let bytes = serde_json::to_vec_pretty(store).unwrap_or_else(|_| b"{}".to_vec());
52    atomic_write_file(&p, &bytes)
53}
54
55fn now_rfc3339_utc() -> String {
56    let secs = SystemTime::now()
57        .duration_since(UNIX_EPOCH)
58        .map(|d| d.as_secs())
59        .unwrap_or(0);
60    format!("{secs}Z")
61}
62
63fn lfs_json(status: u16, value: &serde_json::Value) -> HttpResponse {
64    HttpResponse {
65        status,
66        content_type: LFS_JSON_CONTENT_TYPE.into(),
67        body: serde_json::to_vec(value).unwrap_or_else(|_| b"{}".to_vec()),
68        www_authenticate: None,
69        extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
70    }
71}
72
73fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
74    for part in query.split('&') {
75        if let Some((k, v)) = part.split_once('=') {
76            if k == key && !v.is_empty() {
77                return Some(v);
78            }
79        }
80    }
81    None
82}
83
84/// Dispatch Git LFS Locking API requests under `/info/lfs/locks*`.
85/// Returns `None` if `req.path` is not a locks endpoint.
86pub fn handle_lfs_locks(
87    git_dir: &Path,
88    req: &HttpRequest,
89    actor: Option<(&str, &str)>,
90) -> Option<HttpResponse> {
91    let path = req.path.as_str();
92    let sub = path.strip_prefix("/info/lfs/locks").or_else(|| {
93        let idx = path.find("/info/lfs/locks")?;
94        Some(&path[idx + "/info/lfs/locks".len()..])
95    })?;
96
97    match (req.method.as_str(), sub) {
98        ("GET", "" | "/") => Some(handle_list(git_dir, &req.query)),
99        ("POST", "" | "/") => Some(handle_create(git_dir, req, actor)),
100        ("POST", "/verify") => Some(handle_verify(git_dir, req, actor)),
101        ("POST", rest) if rest.starts_with('/') && rest.ends_with("/unlock") => {
102            let id = &rest[1..rest.len() - "/unlock".len()];
103            Some(handle_unlock(git_dir, req, id, actor))
104        }
105        _ => Some(lfs_json(
106            404,
107            &serde_json::json!({"message": "unknown LFS locks endpoint"}),
108        )),
109    }
110}
111
112fn handle_list(git_dir: &Path, query: &str) -> HttpResponse {
113    let store = load_locks(git_dir);
114    let filter_path = query_param(query, "path");
115    let filter_id = query_param(query, "id");
116    let limit = query_param(query, "limit")
117        .and_then(|v| v.parse::<usize>().ok())
118        .map(|n| n.clamp(1, 100));
119    let cursor = query_param(query, "cursor")
120        .and_then(|v| v.parse::<usize>().ok())
121        .unwrap_or(0);
122
123    let filtered: Vec<&LfsLock> = store
124        .locks
125        .iter()
126        .filter(|l| filter_path.is_none_or(|p| l.path == p))
127        .filter(|l| filter_id.is_none_or(|id| l.id == id))
128        .collect();
129
130    let total = filtered.len();
131    let slice: Vec<&LfsLock> = match limit {
132        Some(lim) => filtered.into_iter().skip(cursor).take(lim).collect(),
133        None => filtered.into_iter().skip(cursor).collect(),
134    };
135    let next_cursor = limit.and_then(|lim| {
136        let next = cursor + slice.len();
137        if next < total && lim > 0 {
138            Some(next.to_string())
139        } else {
140            None
141        }
142    });
143    let mut body = serde_json::json!({ "locks": slice });
144    if let Some(nc) = next_cursor {
145        body["next_cursor"] = serde_json::json!(nc);
146    }
147    lfs_json(200, &body)
148}
149
150fn handle_create(git_dir: &Path, req: &HttpRequest, actor: Option<(&str, &str)>) -> HttpResponse {
151    let Ok(val) = serde_json::from_slice::<serde_json::Value>(&req.body) else {
152        return lfs_json(400, &serde_json::json!({"message": "invalid JSON body"}));
153    };
154    let Some(lock_path) = val
155        .get("path")
156        .and_then(|v| v.as_str())
157        .map(str::trim)
158        .filter(|s| !s.is_empty())
159    else {
160        return lfs_json(400, &serde_json::json!({"message": "path is required"}));
161    };
162    let owner = actor.map(|(u, _)| u).unwrap_or("operator").to_string();
163    let mut store = load_locks(git_dir);
164    if let Some(existing) = store.locks.iter().find(|l| l.path == lock_path) {
165        return lfs_json(
166            409,
167            &serde_json::json!({
168                "lock": existing,
169                "message": "lock already exists"
170            }),
171        );
172    }
173    let id = store.next_id.max(1);
174    store.next_id = id + 1;
175    let lock = LfsLock {
176        id: id.to_string(),
177        path: lock_path.to_string(),
178        locked_at: now_rfc3339_utc(),
179        owner: LfsLockOwner { name: owner },
180    };
181    store.locks.push(lock.clone());
182    if let Err(e) = save_locks(git_dir, &store) {
183        return lfs_json(
184            500,
185            &serde_json::json!({"message": format!("failed to persist lock: {e}")}),
186        );
187    }
188    lfs_json(201, &serde_json::json!({ "lock": lock }))
189}
190
191fn handle_verify(git_dir: &Path, req: &HttpRequest, actor: Option<(&str, &str)>) -> HttpResponse {
192    let store = load_locks(git_dir);
193    let current_user = actor.map(|(u, _)| u).unwrap_or("operator");
194    let parsed = serde_json::from_slice::<serde_json::Value>(&req.body).ok();
195    let limit = parsed
196        .as_ref()
197        .and_then(|v| v.get("limit"))
198        .and_then(|v| v.as_u64())
199        .map(|n| (n as usize).clamp(1, 100));
200    let mut ours = Vec::new();
201    let mut theirs = Vec::new();
202    for l in store.locks {
203        if l.owner.name == current_user {
204            ours.push(l);
205        } else {
206            theirs.push(l);
207        }
208    }
209    if let Some(lim) = limit {
210        ours.truncate(lim);
211        theirs.truncate(lim);
212    }
213    lfs_json(200, &serde_json::json!({ "ours": ours, "theirs": theirs }))
214}
215
216fn handle_unlock(
217    git_dir: &Path,
218    req: &HttpRequest,
219    id: &str,
220    actor: Option<(&str, &str)>,
221) -> HttpResponse {
222    let force = serde_json::from_slice::<serde_json::Value>(&req.body)
223        .ok()
224        .and_then(|v| v.get("force").and_then(|f| f.as_bool()))
225        .unwrap_or(false);
226    let (current_user, role) = actor.unwrap_or(("operator", "admin"));
227    let mut store = load_locks(git_dir);
228    let Some(pos) = store.locks.iter().position(|l| l.id == id) else {
229        return lfs_json(404, &serde_json::json!({"message": "lock not found"}));
230    };
231    let is_owner = store.locks[pos].owner.name == current_user;
232    if !is_owner && !(force && role == "admin") {
233        return lfs_json(
234            403,
235            &serde_json::json!({"message": "cannot unlock another user's lock without admin force"}),
236        );
237    }
238    let removed = store.locks.remove(pos);
239    if let Err(e) = save_locks(git_dir, &store) {
240        return lfs_json(
241            500,
242            &serde_json::json!({"message": format!("failed to persist unlock: {e}")}),
243        );
244    }
245    lfs_json(200, &serde_json::json!({ "lock": removed }))
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn lfs_locks_create_conflict_verify_and_unlock_roundtrip() {
254        let dir = tempfile::TempDir::new().unwrap();
255
256        // Create lock as alice -> 201
257        let create_req = HttpRequest::new(
258            "POST",
259            "/info/lfs/locks",
260            "",
261            br#"{"path":"assets/hero.png"}"#.to_vec(),
262        );
263        let r1 = handle_lfs_locks(dir.path(), &create_req, Some(("alice", "maintainer"))).unwrap();
264        assert_eq!(r1.status, 201);
265        assert_eq!(r1.content_type, LFS_JSON_CONTENT_TYPE);
266        let v1: serde_json::Value = serde_json::from_slice(&r1.body).unwrap();
267        let lock_id = v1["lock"]["id"].as_str().unwrap().to_string();
268
269        // Duplicate create -> 409 conflict with existing lock
270        let r2 = handle_lfs_locks(dir.path(), &create_req, Some(("bob", "maintainer"))).unwrap();
271        assert_eq!(r2.status, 409);
272
273        // Verify as bob -> in theirs; as alice -> in ours
274        let ver_req = HttpRequest::new("POST", "/info/lfs/locks/verify", "", b"{}".to_vec());
275        let vb = handle_lfs_locks(dir.path(), &ver_req, Some(("bob", "maintainer"))).unwrap();
276        let vb_json: serde_json::Value = serde_json::from_slice(&vb.body).unwrap();
277        assert_eq!(vb_json["ours"].as_array().unwrap().len(), 0);
278        assert_eq!(vb_json["theirs"].as_array().unwrap().len(), 1);
279
280        // Bob cannot unlock alice's lock -> 403
281        let unlock_path = format!("/info/lfs/locks/{lock_id}/unlock");
282        let u_bob = HttpRequest::new("POST", &unlock_path, "", b"{}".to_vec());
283        assert_eq!(
284            handle_lfs_locks(dir.path(), &u_bob, Some(("bob", "maintainer")))
285                .unwrap()
286                .status,
287            403
288        );
289
290        // Alice unlocks her own lock -> 200
291        let u_alice = HttpRequest::new("POST", &unlock_path, "", b"{}".to_vec());
292        assert_eq!(
293            handle_lfs_locks(dir.path(), &u_alice, Some(("alice", "maintainer")))
294                .unwrap()
295                .status,
296            200
297        );
298    }
299}