monochromatic-git-policy-cli 0.5.4

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! What:
//!  A minimal D-Bus client for the user session bus: authenticate as the current user, say `Hello`, and call methods of
//!  `org.freedesktop.systemd1.Manager` with string arguments, each bounded by one deadline for the whole exchange.
//! Why:
//!  The wrapper provisions socket activation itself, and may start no program to do it (`systemctl` would be one). The
//!  supported surface of the user manager is its D-Bus API (`org.freedesktop.systemd1(5)`), reached through the session
//!  bus; the manager's own private socket is documented as private to systemd. Only `Reload` and `StartUnit` are needed,
//!  both with at most two string arguments, so the writer and the reader below cover exactly the types those calls and
//!  the bus's replies use (`s`, `o`, `g`, `u`) and stop at anything else. The reader is total over arbitrary bytes (a
//!  fuzz target holds it to that). The comparison with a D-Bus crate is in `doc/planning/cli-git-resident-service.md`,
//!  "Provisioning".
//!
//! In TS you'd write (pseudocode):
//! ```ts
//! const bus = await connect(address, 5000); await bus.startUnit('cli-git.socket', 'replace'); // throws with the error name
//! ```

use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::time::{Duration, Instant};

/// The manager's object path.
pub const MANAGER_PATH: &str = "/org/freedesktop/systemd1";

/// The manager's interface.
pub const MANAGER_INTERFACE: &str = "org.freedesktop.systemd1.Manager";

/// How long the whole exchange (connect, authenticate, say hello, make the calls) may take; a stuck bus never holds a
///  commit longer.
pub const EXCHANGE_WAIT: Duration = Duration::from_secs(20);

/// The bus daemon's name, object and interface, for `Hello`.
const BUS_NAME: &str = "org.freedesktop.DBus";
const BUS_PATH: &str = "/org/freedesktop/DBus";

/// The manager's bus name.
pub const MANAGER_NAME: &str = "org.freedesktop.systemd1";

/// The most bytes of one reply this client accepts.
const MAX_REPLY_BYTES: usize = 1 << 20;

/// Message type of a method call.
const METHOD_CALL: u8 = 1;

/// Message type of a successful reply.
const METHOD_RETURN: u8 = 2;

/// Message type of an error reply.
const ERROR: u8 = 3;

/// Header field code of the number of the call a reply answers.
const FIELD_REPLY_SERIAL: u8 = 5;

/// Header field codes.
const FIELD_PATH: u8 = 1;
const FIELD_INTERFACE: u8 = 2;
const FIELD_MEMBER: u8 = 3;
const FIELD_ERROR_NAME: u8 = 4;
const FIELD_DESTINATION: u8 = 6;
const FIELD_SIGNATURE: u8 = 8;

/// Why a call did not succeed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CallError {
    /// The socket could not be reached or the connection broke.
    Connection(String),
    /// The manager refused the authentication.
    Authentication(String),
    /// The manager answered with an error.
    Manager {
        /// The error's name, for example `org.freedesktop.systemd1.NoSuchUnit`.
        name: String,
        /// The error's text, when it gave one.
        text: String,
    },
    /// The reply was not a message this client reads.
    Malformed(String),
}

/// Appends values in D-Bus little-endian wire form.
struct Writer {
    bytes: Vec<u8>,
}

impl Writer {
    fn align(&mut self, boundary: usize) {
        while self.bytes.len() % boundary != 0 {
            self.bytes.push(0);
        }
    }

    fn unsigned(&mut self, value: u32) {
        self.align(4);
        self.bytes.extend(value.to_le_bytes());
    }

    fn text(&mut self, value: &str) {
        self.unsigned(u32::try_from(value.len()).unwrap_or(u32::MAX));
        self.bytes.extend(value.as_bytes());
        self.bytes.push(0);
    }

    fn signature(&mut self, value: &str) {
        self.bytes.push(u8::try_from(value.len()).unwrap_or(u8::MAX));
        self.bytes.extend(value.as_bytes());
        self.bytes.push(0);
    }

    /// One header field: its code, then a variant holding a string-like or signature value.
    fn field(&mut self, code: u8, kind: char, value: &str) {
        self.align(8);
        self.bytes.push(code);
        self.signature(&kind.to_string());
        if kind == 'g' {
            self.signature(value);
        } else {
            self.text(value);
        }
    }
}

/// Where a method call goes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Target {
    /// The bus name of the receiver.
    pub destination: &'static str,
    /// The object path.
    pub path: &'static str,
    /// The interface.
    pub interface: &'static str,
    /// The method.
    pub member: &'static str,
}

/// `Hello` on the bus daemon, the first call of every connection.
pub const HELLO: Target = Target { destination: BUS_NAME, path: BUS_PATH, interface: BUS_NAME, member: "Hello" };

/// `Reload` on the user manager.
pub const RELOAD: Target = Target { destination: MANAGER_NAME, path: MANAGER_PATH, interface: MANAGER_INTERFACE, member: "Reload" };

/// `StartUnit` on the user manager.
pub const START_UNIT: Target = Target { destination: MANAGER_NAME, path: MANAGER_PATH, interface: MANAGER_INTERFACE, member: "StartUnit" };

/// What:
///  The bytes of a method call with string arguments.
/// Why:
///   Kept apart from the socket so a test can read them back and compare them with the specification's layout.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// encodeCall(serial, START_UNIT, ['cli-git.socket', 'replace'])
/// ```
pub fn encode_call(serial: u32, target: &Target, arguments: &[&str]) -> Vec<u8> {
    let mut body: Writer = Writer { bytes: Vec::new() };
    for argument in arguments {
        body.text(argument);
    }
    let mut fields: Writer = Writer { bytes: vec![0; 16] };
    fields.field(FIELD_PATH, 'o', target.path);
    fields.field(FIELD_DESTINATION, 's', target.destination);
    fields.field(FIELD_INTERFACE, 's', target.interface);
    fields.field(FIELD_MEMBER, 's', target.member);
    if !arguments.is_empty() {
        fields.field(FIELD_SIGNATURE, 'g', &"s".repeat(arguments.len()));
    }
    // The first sixteen bytes are the fixed header and the array length, filled in below.
    let array_length: u32 = u32::try_from(fields.bytes.len() - 16).unwrap_or(u32::MAX);
    fields.align(8);
    let mut message: Vec<u8> = fields.bytes;
    message[0] = b'l';
    message[1] = METHOD_CALL;
    message[2] = 0;
    message[3] = 1;
    message[4..8].copy_from_slice(&u32::try_from(body.bytes.len()).unwrap_or(u32::MAX).to_le_bytes());
    message[8..12].copy_from_slice(&serial.to_le_bytes());
    message[12..16].copy_from_slice(&array_length.to_le_bytes());
    message.extend(body.bytes);
    return message;
}

/// A reply: its type, the error name its header carries, and the first string of its body.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Reply {
    /// Message type: 2 for a return, 3 for an error, 4 for a signal.
    pub kind: u8,
    /// The number of the call this message answers.
    pub reply_serial: Option<u32>,
    /// The error name of an error reply.
    pub error_name: Option<String>,
    /// The first string argument of the body, which an error reply uses for its text.
    pub first_text: Option<String>,
}

fn read_u32(bytes: &[u8], at: usize) -> Option<u32> {
    return bytes.get(at..at.checked_add(4)?).map(|slice| { return u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]); });
}

fn read_text(bytes: &[u8], at: usize) -> Option<(String, usize)> {
    let length: usize = usize::try_from(read_u32(bytes, at)?).ok()?;
    let start: usize = at.checked_add(4)?;
    let text: &[u8] = bytes.get(start..start.checked_add(length)?)?;
    return Some((String::from_utf8_lossy(text).into_owned(), start.saturating_add(length).saturating_add(1)));
}

fn aligned(offset: usize, boundary: usize) -> usize {
    return offset.checked_add(boundary - 1).map_or(usize::MAX, |sum| { return sum / boundary * boundary; });
}

/// What:
///  Reads a complete reply message.
/// Why:
///   Only the type, the error name and the first string of the body matter; a header field of a kind this reader does not
///  know ends the walk of the header, which is safe because the fields it needs come first in what the manager sends or
///  are looked for before any unknown kind.
///
/// In TS you'd write (pseudocode):
/// ```ts
/// decodeReply(bytes)
/// ```
pub fn decode_reply(bytes: &[u8]) -> Result<Reply, CallError> {
    let malformed = |what: &str| { return CallError::Malformed(what.to_string()); };
    if bytes.len() < 16 || bytes[0] != b'l' {
        return Err(malformed("the reply is not a little-endian message"));
    }
    let kind: u8 = bytes[1];
    let body_length: usize = usize::try_from(read_u32(bytes, 4).ok_or_else(|| { return malformed("no body length"); })?).unwrap_or(usize::MAX);
    let fields_length: usize = usize::try_from(read_u32(bytes, 12).ok_or_else(|| { return malformed("no header length"); })?).unwrap_or(usize::MAX);
    let fields_end: usize = 16usize.saturating_add(fields_length);
    let body_start: usize = aligned(fields_end, 8);
    if bytes.len() < body_start.saturating_add(body_length) || fields_end > bytes.len() {
        return Err(malformed("the reply is shorter than it says"));
    }
    let mut error_name: Option<String> = None;
    let mut reply_serial: Option<u32> = None;
    let mut signature: String = String::new();
    let mut at: usize = 16;
    while at < fields_end {
        at = aligned(at, 8);
        let (Some(&code), Some(&signature_length)) = (bytes.get(at), bytes.get(at.saturating_add(1))) else { break };
        let kind_at: usize = at.saturating_add(2);
        let Some(&value_kind) = bytes.get(kind_at) else { break };
        let value_at: usize = kind_at.saturating_add(usize::from(signature_length)).saturating_add(1);
        match (value_kind, code) {
            (b's' | b'o', _) => {
                let Some((text, next)) = read_text(bytes, aligned(value_at, 4)) else { break };
                if code == FIELD_ERROR_NAME {
                    error_name = Some(text);
                }
                at = next;
            }
            (b'g', _) => {
                let length: usize = usize::from(*bytes.get(value_at).unwrap_or(&0));
                if code == FIELD_SIGNATURE {
                    let start: usize = value_at.saturating_add(1);
                    signature = String::from_utf8_lossy(bytes.get(start..start.saturating_add(length)).unwrap_or_default()).into_owned();
                }
                at = value_at.saturating_add(length).saturating_add(2);
            }
            (b'u', _) => {
                let number_at: usize = aligned(value_at, 4);
                if code == FIELD_REPLY_SERIAL {
                    reply_serial = read_u32(bytes, number_at);
                }
                at = number_at.saturating_add(4);
            }
            _ => break,
        }
    }
    let first_text: Option<String> = if signature.starts_with('s') {
        read_text(bytes, aligned(body_start, 4)).map(|(text, _)| { return text; })
    } else {
        None
    };
    return Ok(Reply { kind, reply_serial, error_name, first_text });
}

/// The user id as the ASCII digits the `EXTERNAL` mechanism sends, written in hexadecimal.
fn external_identity() -> String {
    // SAFETY: `geteuid` takes no arguments and cannot fail.
    let user: u32 = unsafe { libc::geteuid() };
    return user.to_string().bytes().map(|byte| { return format!("{byte:02x}"); }).collect();
}

/// The time left of the exchange, or an error when it ran out.
fn remaining(deadline: Instant) -> Result<Duration, CallError> {
    let left: Duration = deadline.saturating_duration_since(Instant::now());
    return if left.is_zero() { Err(CallError::Connection(String::from("the bus did not answer in time"))) } else { Ok(left) };
}

fn read_line(stream: &mut UnixStream, deadline: Instant) -> Result<String, CallError> {
    let mut line: Vec<u8> = Vec::new();
    let mut one: [u8; 1] = [0];
    while line.len() < 4096 {
        stream.set_read_timeout(Some(remaining(deadline)?)).map_err(|error| { return CallError::Connection(error.to_string()); })?;
        stream.read_exact(&mut one).map_err(|error| { return CallError::Authentication(error.to_string()); })?;
        if one[0] == b'\n' {
            return Ok(String::from_utf8_lossy(line.as_slice()).trim_end_matches('\r').to_string());
        }
        line.push(one[0]);
    }
    return Err(CallError::Authentication(String::from("the answer is too long")));
}

/// Reads exactly one message from the stream.
fn read_message(stream: &mut UnixStream, deadline: Instant) -> Result<Vec<u8>, CallError> {
    let mut header: Vec<u8> = vec![0; 16];
    stream.set_read_timeout(Some(remaining(deadline)?)).map_err(|error| { return CallError::Connection(error.to_string()); })?;
    stream.read_exact(header.as_mut_slice()).map_err(|error| { return CallError::Connection(error.to_string()); })?;
    let body_length: usize = usize::try_from(read_u32(header.as_slice(), 4).unwrap_or(0)).unwrap_or(usize::MAX);
    let fields_length: usize = usize::try_from(read_u32(header.as_slice(), 12).unwrap_or(0)).unwrap_or(usize::MAX);
    let rest: usize = aligned(16usize.saturating_add(fields_length), 8).saturating_add(body_length).saturating_sub(16);
    if rest > MAX_REPLY_BYTES {
        return Err(CallError::Malformed(String::from("the reply is larger than this client reads")));
    }
    let mut remainder: Vec<u8> = vec![0; rest];
    stream.set_read_timeout(Some(remaining(deadline)?)).map_err(|error| { return CallError::Connection(error.to_string()); })?;
    stream.read_exact(remainder.as_mut_slice()).map_err(|error| { return CallError::Connection(error.to_string()); })?;
    header.extend(remainder);
    return Ok(header);
}

/// The path of the session bus socket: the `unix:path=` entry of the address variable, else `$XDG_RUNTIME_DIR/bus`.
pub fn session_bus_path(address: Option<&str>, runtime_dir: Option<&Path>) -> Option<std::path::PathBuf> {
    let from_address: Option<std::path::PathBuf> = address.and_then(|list| {
        return list.split(';').find_map(|entry| {
            let rest: &str = entry.strip_prefix("unix:")?;
            let path: &str = rest.split(',').find_map(|option| { return option.strip_prefix("path="); })?;
            // Escapes (`%xx`) in a path are not read; a path that uses them falls back to the default location.
            return if path.contains('%') || path.is_empty() { None } else { Some(std::path::PathBuf::from(path)) };
        });
    });
    return from_address.or_else(|| { return runtime_dir.map(|directory| { return directory.join("bus"); }); });
}

/// An authenticated connection to the session bus, past `Hello`.
pub struct Bus {
    stream: UnixStream,
    deadline: Instant,
    serial: u32,
}

/// Methods over a connection.
impl Bus {
    /// What:
    ///  Connects to the bus socket, authenticates as the current user and says `Hello`, all within `wait`.
    /// Why:
    ///   The deadline of the whole exchange starts here, so every later call shares what is left of it.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// const bus = await Bus.connect(path, 20000)
    /// ```
    pub fn connect(socket: &Path, wait: Duration) -> Result<Bus, CallError> {
        let deadline: Instant = Instant::now() + wait;
        let mut stream: UnixStream = UnixStream::connect(socket).map_err(|error| { return CallError::Connection(error.to_string()); })?;
        stream.set_write_timeout(Some(wait)).map_err(|error| { return CallError::Connection(error.to_string()); })?;
        let mut hello: Vec<u8> = vec![0];
        hello.extend(format!("AUTH EXTERNAL {}\r\n", external_identity()).as_bytes());
        stream.write_all(hello.as_slice()).map_err(|error| { return CallError::Authentication(error.to_string()); })?;
        let answer: String = read_line(&mut stream, deadline)?;
        if !answer.starts_with("OK ") {
            return Err(CallError::Authentication(answer));
        }
        stream.write_all(b"BEGIN\r\n").map_err(|error| { return CallError::Authentication(error.to_string()); })?;
        let mut bus: Bus = Bus { stream, deadline, serial: 0 };
        bus.call(&HELLO, &[])?;
        return Ok(bus);
    }

    /// What:
    ///  Makes one method call and waits for the reply that answers it, skipping the signals the bus sends meanwhile.
    /// Why:
    ///   A return is the receiver's confirmation (a reload returns after the units are read); an error reply comes back
    ///  with its name and text so the caller can say what to do.
    ///
    /// In TS you'd write (pseudocode):
    /// ```ts
    /// await bus.call(RELOAD, [])
    /// ```
    pub fn call(&mut self, target: &Target, arguments: &[&str]) -> Result<Reply, CallError> {
        self.serial += 1;
        let serial: u32 = self.serial;
        self.stream.write_all(encode_call(serial, target, arguments).as_slice()).map_err(|error| { return CallError::Connection(error.to_string()); })?;
        loop {
            let reply: Reply = decode_reply(read_message(&mut self.stream, self.deadline)?.as_slice())?;
            if reply.reply_serial != Some(serial) || !matches!(reply.kind, METHOD_RETURN | ERROR) {
                continue;
            }
            return match (reply.kind, reply.error_name.clone()) {
                (METHOD_RETURN, _) => Ok(reply),
                (_, Some(name)) => Err(CallError::Manager { name, text: reply.first_text.unwrap_or_default() }),
                _ => Err(CallError::Malformed(String::from("an error reply without a name"))),
            };
        }
    }

    /// Reloads the user manager's unit files.
    pub fn reload(&mut self) -> Result<(), CallError> {
        return self.call(&RELOAD, &[]).map(drop);
    }

    /// Starts a unit, replacing a queued job for it.
    pub fn start_unit(&mut self, name: &str) -> Result<(), CallError> {
        return self.call(&START_UNIT, &[name, "replace"]).map(drop);
    }
}

/// Client controls stay out of the release executable.
#[cfg(test)]
#[path = "systemd_dbus_tests.rs"]
mod tests;