rns-git 0.2.0

Reticulum Git transport tools
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use rns_core::msgpack::{self, Value};

use crate::{Error, Result};

pub const APP_NAME: &str = "git";
pub const ASPECT_REPOSITORIES: &str = "repositories";

pub const PATH_LIST: &str = "/git/list";
pub const PATH_FETCH: &str = "/git/fetch";
pub const PATH_PUSH: &str = "/git/push";
pub const PATH_CREATE: &str = "/git/create";
pub const PATH_FORK: &str = "/git/fork";
pub const PATH_SYNC: &str = "/git/sync";
pub const PATH_MIRROR: &str = "/git/mirror";
pub const PATH_DELETE: &str = "/git/delete";
pub const PATH_RELEASE: &str = "/mgmt/release";
pub const PATH_WORK: &str = "/mgmt/work";
pub const PATH_PERMS: &str = "/mgmt/perms";

pub const RES_OK: u8 = 0x00;
pub const RES_DISALLOWED: u8 = 0x01;
pub const RES_INVALID_REQ: u8 = 0x02;
pub const RES_NOT_FOUND: u8 = 0x03;
pub const RES_REMOTE_FAIL: u8 = 0xff;

pub const IDX_REPOSITORY: u64 = 0x00;
pub const IDX_RESULT_CODE: u64 = 0x01;
pub const IDX_GROUP: u64 = 0x02;

const ACTION_UPDATE_REF: &str = "update_ref";
const ACTION_DELETE_REF: &str = "delete_ref";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefUpdate {
    pub refname: String,
    pub old: Option<String>,
    pub new: Option<String>,
    pub force: bool,
}

pub fn status_bytes(code: u8, body: impl AsRef<[u8]>) -> Vec<u8> {
    let mut out = Vec::with_capacity(1 + body.as_ref().len());
    out.push(code);
    out.extend_from_slice(body.as_ref());
    out
}

pub fn metadata_status(code: u8) -> Vec<u8> {
    msgpack::pack(&Value::Map(vec![(
        Value::UInt(IDX_RESULT_CODE),
        Value::UInt(code as u64),
    )]))
}

pub fn repository_request(repository: &str) -> Vec<u8> {
    msgpack::pack(&Value::Map(vec![(
        Value::UInt(IDX_REPOSITORY),
        Value::Str(repository.to_string()),
    )]))
}

pub fn repository_from_request(data: &[u8]) -> Result<String> {
    let value =
        msgpack::unpack_exact(data).map_err(|e| Error::msg(format!("invalid msgpack: {e}")))?;
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("request must be a msgpack map"))?;
    map_get(map, IDX_REPOSITORY)
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("request missing repository"))
}

pub fn remote_clone_request(repository: &str, source: &str) -> Vec<u8> {
    msgpack::pack(&Value::Map(vec![
        (
            Value::UInt(IDX_REPOSITORY),
            Value::Str(repository.to_string()),
        ),
        (
            Value::Str("source".to_string()),
            Value::Str(source.to_string()),
        ),
    ]))
}

pub fn parse_remote_clone_request(data: &[u8]) -> Result<(String, String)> {
    let value =
        msgpack::unpack_exact(data).map_err(|e| Error::msg(format!("invalid msgpack: {e}")))?;
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("request must be a msgpack map"))?;
    let repo = map_get(map, IDX_REPOSITORY)
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("request missing repository"))?;
    let source = map_get_str(map, "source")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|source| !source.is_empty())
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("request missing source"))?;
    Ok((repo, source))
}

pub fn fetch_request(repository: &str, have: &[String]) -> Vec<u8> {
    fetch_request_for_refs(repository, have, &[])
}

pub fn fetch_request_for_refs(
    repository: &str,
    have: &[String],
    refs: &[(String, String)],
) -> Vec<u8> {
    msgpack::pack(&Value::Map(vec![
        (
            Value::UInt(IDX_REPOSITORY),
            Value::Str(repository.to_string()),
        ),
        (
            Value::Str("have".to_string()),
            Value::Array(have.iter().map(|v| Value::Str(v.clone())).collect()),
        ),
        (
            Value::Str("refs".to_string()),
            Value::Array(
                refs.iter()
                    .map(|(sha, refname)| {
                        Value::Map(vec![
                            (Value::Str("sha".to_string()), Value::Str(sha.clone())),
                            (Value::Str("ref".to_string()), Value::Str(refname.clone())),
                        ])
                    })
                    .collect(),
            ),
        ),
    ]))
}

pub fn parse_fetch_request(data: &[u8]) -> Result<(String, Vec<String>, Vec<(String, String)>)> {
    let value =
        msgpack::unpack_exact(data).map_err(|e| Error::msg(format!("invalid msgpack: {e}")))?;
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("request must be a msgpack map"))?;
    let repo = map_get(map, IDX_REPOSITORY)
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("request missing repository"))?;
    let have = map_get_str(map, "have")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(Value::as_str)
                .map(ToOwned::to_owned)
                .collect()
        })
        .unwrap_or_default();
    let refs = map_get_str(map, "refs")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|entry| {
                    let map = entry.as_map()?;
                    let sha = map_get_str(map, "sha")?.as_str()?.to_owned();
                    let refname = map_get_str(map, "ref")?.as_str()?.to_owned();
                    Some((sha, refname))
                })
                .collect()
        })
        .unwrap_or_default();
    Ok((repo, have, refs))
}

pub fn push_request(repository: &str, bundle: Vec<u8>, updates: Vec<RefUpdate>) -> Vec<u8> {
    msgpack::pack(&Value::Map(vec![
        (
            Value::UInt(IDX_REPOSITORY),
            Value::Str(repository.to_string()),
        ),
        (Value::Str("bundle".to_string()), Value::Bin(bundle)),
        (
            Value::Str("operations".to_string()),
            Value::Array(updates.into_iter().map(update_to_operation_value).collect()),
        ),
    ]))
}

pub fn parse_push_request(data: &[u8]) -> Result<(String, Vec<u8>, Vec<RefUpdate>)> {
    let value =
        msgpack::unpack_exact(data).map_err(|e| Error::msg(format!("invalid msgpack: {e}")))?;
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("request must be a msgpack map"))?;
    let repo = map_get(map, IDX_REPOSITORY)
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("request missing repository"))?;
    let bundle = map_get_str(map, "bundle")
        .and_then(Value::as_bin)
        .map(ToOwned::to_owned)
        .unwrap_or_default();
    let updates = if let Some(arr) = map_get_str(map, "operations").and_then(Value::as_array) {
        arr.iter()
            .map(operation_value_to_update)
            .collect::<Result<Vec<_>>>()?
    } else {
        map_get_str(map, "updates")
            .and_then(Value::as_array)
            .map(|arr| arr.iter().map(value_to_update).collect::<Result<Vec<_>>>())
            .transpose()?
            .unwrap_or_default()
    };
    Ok((repo, bundle, updates))
}

pub fn response_bin(data: &[u8]) -> Result<Vec<u8>> {
    match msgpack::unpack_exact(data).map_err(|e| Error::msg(format!("invalid response: {e}")))? {
        Value::Bin(bytes) => Ok(bytes),
        other => Err(Error::msg(format!(
            "expected binary response, got {other:?}"
        ))),
    }
}

#[allow(dead_code)]
fn update_to_value(update: RefUpdate) -> Value {
    let mut items = vec![
        (Value::Str("ref".to_string()), Value::Str(update.refname)),
        (Value::Str("force".to_string()), Value::Bool(update.force)),
    ];
    items.push((
        Value::Str("old".to_string()),
        update.old.map(Value::Str).unwrap_or(Value::Nil),
    ));
    items.push((
        Value::Str("new".to_string()),
        update.new.map(Value::Str).unwrap_or(Value::Nil),
    ));
    Value::Map(items)
}

fn update_to_operation_value(update: RefUpdate) -> Value {
    let action = if update.new.is_some() {
        ACTION_UPDATE_REF
    } else {
        ACTION_DELETE_REF
    };
    let mut items = vec![
        (
            Value::Str("action".to_string()),
            Value::Str(action.to_string()),
        ),
        (Value::Str("ref".to_string()), Value::Str(update.refname)),
        (Value::Str("force".to_string()), Value::Bool(update.force)),
    ];
    if let Some(old) = update.old {
        items.push((Value::Str("old".to_string()), Value::Str(old)));
    }
    if let Some(new) = update.new {
        items.push((Value::Str("sha".to_string()), Value::Str(new)));
    }
    Value::Map(items)
}

fn operation_value_to_update(value: &Value) -> Result<RefUpdate> {
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("operation must be a map"))?;
    let action = map_get_str(map, "action")
        .and_then(Value::as_str)
        .ok_or_else(|| Error::msg("operation missing action"))?;
    let refname = map_get_str(map, "ref")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("operation missing ref"))?;
    let old = map_get_str(map, "old")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let force = map_get_str(map, "force")
        .and_then(Value::as_bool)
        .unwrap_or(false);

    match action {
        ACTION_UPDATE_REF => {
            let new = map_get_str(map, "sha")
                .or_else(|| map_get_str(map, "new"))
                .and_then(Value::as_str)
                .map(ToOwned::to_owned)
                .ok_or_else(|| Error::msg("update_ref operation missing sha"))?;
            Ok(RefUpdate {
                refname,
                old,
                new: Some(new),
                force,
            })
        }
        ACTION_DELETE_REF => Ok(RefUpdate {
            refname,
            old,
            new: None,
            force,
        }),
        other => Err(Error::msg(format!("unknown push operation {other}"))),
    }
}

fn value_to_update(value: &Value) -> Result<RefUpdate> {
    let map = value
        .as_map()
        .ok_or_else(|| Error::msg("update must be a map"))?;
    let refname = map_get_str(map, "ref")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
        .ok_or_else(|| Error::msg("update missing ref"))?;
    let old = map_get_str(map, "old")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let new = map_get_str(map, "new")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let force = map_get_str(map, "force")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    Ok(RefUpdate {
        refname,
        old,
        new,
        force,
    })
}

fn map_get<'a>(map: &'a [(Value, Value)], key: u64) -> Option<&'a Value> {
    map.iter().find_map(|(k, v)| {
        if matches!(k, Value::UInt(v) if *v == key) {
            Some(v)
        } else {
            None
        }
    })
}

fn map_get_str<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a Value> {
    map.iter().find_map(|(k, v)| match k {
        Value::Str(s) if s == key => Some(v),
        _ => None,
    })
}

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

    #[test]
    fn repository_roundtrip_uses_upstream_index() {
        assert_eq!(
            repository_from_request(&repository_request("group/repo")).unwrap(),
            "group/repo"
        );
    }

    #[test]
    fn remote_clone_request_roundtrip_includes_source() {
        let req = remote_clone_request("group/repo", "https://example.invalid/repo.git");
        assert_eq!(
            parse_remote_clone_request(&req).unwrap(),
            (
                "group/repo".into(),
                "https://example.invalid/repo.git".into()
            )
        );
    }

    #[test]
    fn push_roundtrip_preserves_updates() {
        let update = RefUpdate {
            refname: "refs/heads/main".to_string(),
            old: None,
            new: Some("abc".to_string()),
            force: true,
        };
        let (repo, bundle, updates) = parse_push_request(&push_request(
            "repo",
            b"bundle".to_vec(),
            vec![update.clone()],
        ))
        .unwrap();
        assert_eq!(repo, "repo");
        assert_eq!(bundle, b"bundle");
        assert_eq!(updates, vec![update]);
    }

    #[test]
    fn push_request_uses_operations_field() {
        let update = RefUpdate {
            refname: "refs/heads/main".to_string(),
            old: Some("old".to_string()),
            new: Some("new".to_string()),
            force: true,
        };
        let packed = push_request("repo", Vec::new(), vec![update]);
        let value = msgpack::unpack_exact(&packed).unwrap();
        let map = value.as_map().unwrap();

        assert!(map_get_str(map, "operations").is_some());
        assert!(map_get_str(map, "updates").is_none());
    }

    #[test]
    fn parse_push_request_accepts_update_and_delete_operations() {
        let request = msgpack::pack(&Value::Map(vec![
            (Value::UInt(IDX_REPOSITORY), Value::Str("repo".into())),
            (Value::Str("bundle".into()), Value::Bin(Vec::new())),
            (
                Value::Str("operations".into()),
                Value::Array(vec![
                    Value::Map(vec![
                        (
                            Value::Str("action".into()),
                            Value::Str(ACTION_UPDATE_REF.into()),
                        ),
                        (
                            Value::Str("ref".into()),
                            Value::Str("refs/heads/main".into()),
                        ),
                        (Value::Str("sha".into()), Value::Str("new".into())),
                        (Value::Str("force".into()), Value::Bool(true)),
                    ]),
                    Value::Map(vec![
                        (
                            Value::Str("action".into()),
                            Value::Str(ACTION_DELETE_REF.into()),
                        ),
                        (
                            Value::Str("ref".into()),
                            Value::Str("refs/heads/old".into()),
                        ),
                    ]),
                ]),
            ),
        ]));

        let (_, _, updates) = parse_push_request(&request).unwrap();

        assert_eq!(
            updates,
            vec![
                RefUpdate {
                    refname: "refs/heads/main".into(),
                    old: None,
                    new: Some("new".into()),
                    force: true
                },
                RefUpdate {
                    refname: "refs/heads/old".into(),
                    old: None,
                    new: None,
                    force: false
                }
            ]
        );
    }

    #[test]
    fn parse_push_request_keeps_legacy_updates_compatibility() {
        let update = RefUpdate {
            refname: "refs/heads/main".into(),
            old: Some("old".into()),
            new: Some("new".into()),
            force: false,
        };
        let request = msgpack::pack(&Value::Map(vec![
            (Value::UInt(IDX_REPOSITORY), Value::Str("repo".into())),
            (Value::Str("bundle".into()), Value::Bin(Vec::new())),
            (
                Value::Str("updates".into()),
                Value::Array(vec![update_to_value(update.clone())]),
            ),
        ]));

        let (_, _, updates) = parse_push_request(&request).unwrap();

        assert_eq!(updates, vec![update]);
    }

    #[test]
    fn fetch_roundtrip_preserves_requested_refs() {
        let (repo, have, refs) = parse_fetch_request(&fetch_request_for_refs(
            "repo",
            &["0123456789abcdef0123456789abcdef01234567".into()],
            &[(
                "89abcdef0123456789abcdef0123456789abcdef".into(),
                "refs/heads/main".into(),
            )],
        ))
        .unwrap();

        assert_eq!(repo, "repo");
        assert_eq!(have, vec!["0123456789abcdef0123456789abcdef01234567"]);
        assert_eq!(
            refs,
            vec![(
                "89abcdef0123456789abcdef0123456789abcdef".into(),
                "refs/heads/main".into()
            )]
        );
    }

    #[test]
    fn status_response_is_status_byte_plus_payload() {
        assert_eq!(status_bytes(RES_OK, b"ok"), b"\0ok");
    }
}