brinkhaustools/licence/
codec.rs

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
//! Text codecs shared by the licence format: Crockford Base32, hex, canonical JSON
//! and the atomic file write used for the small state files.

use std::io::Write;
use std::path::Path;

use serde_json::Value;

const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";

/// Encode bytes as Crockford Base32 (upper case, no padding).
pub fn base32_encode(data: &[u8]) -> String {
    let mut out = String::with_capacity(data.len().div_ceil(5) * 8);
    let mut buffer: u32 = 0;
    let mut bits: u32 = 0;
    for &byte in data {
        buffer = (buffer << 8) | u32::from(byte);
        bits += 8;
        while bits >= 5 {
            bits -= 5;
            out.push(CROCKFORD[((buffer >> bits) & 0x1f) as usize] as char);
        }
    }
    if bits > 0 {
        out.push(CROCKFORD[((buffer << (5 - bits)) & 0x1f) as usize] as char);
    }
    out
}

/// Decode Crockford Base32.
///
/// Case-insensitive; whitespace and `-` are ignored (the text block is wrapped and
/// may be grouped); `O` reads as `0`, `I`/`L` as `1`. Trailing pad bits must be zero,
/// so a truncated or extended block is rejected instead of silently decoded.
pub fn base32_decode(text: &str) -> Result<Vec<u8>, String> {
    let mut out = Vec::with_capacity(text.len() * 5 / 8);
    let mut buffer: u32 = 0;
    let mut bits: u32 = 0;
    for ch in text.chars() {
        if ch.is_whitespace() || ch == '-' {
            continue;
        }
        let value = match ch.to_ascii_uppercase() {
            'O' => 0,
            'I' | 'L' => 1,
            c => match CROCKFORD.iter().position(|&a| a as char == c) {
                Some(p) => p as u32,
                None => return Err(format!("invalid character {ch:?}")),
            },
        };
        buffer = (buffer << 5) | value;
        bits += 5;
        if bits >= 8 {
            bits -= 8;
            out.push(((buffer >> bits) & 0xff) as u8);
        }
        buffer &= (1 << bits) - 1;
    }
    if bits >= 5 || buffer != 0 {
        return Err("block length does not end on a byte boundary".to_string());
    }
    Ok(out)
}

/// Wrap an encoded block into lines of `width` characters.
pub fn wrap(prefix: &str, body: &str, width: usize) -> String {
    let mut out = String::from(prefix);
    let mut line_len = prefix.len();
    for ch in body.chars() {
        if line_len == width {
            out.push('\n');
            line_len = 0;
        }
        out.push(ch);
        line_len += 1;
    }
    out
}

/// Lower-case hex.
pub fn hex_encode(data: &[u8]) -> String {
    use std::fmt::Write as _;
    data.iter().fold(String::with_capacity(data.len() * 2), |mut out, b| {
        // Writing into a String cannot fail.
        let _ = write!(out, "{b:02x}");
        out
    })
}

/// Decode hex (either case); `None` on odd length or a non-hex character.
pub fn hex_decode(text: &str) -> Option<Vec<u8>> {
    let text = text.trim();
    if text.len() % 2 == 1 {
        return None;
    }
    (0..text.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok())
        .collect()
}

/// Canonical JSON: object keys sorted, no insignificant whitespace.
///
/// Does not depend on serde_json's `preserve_order` feature, which a consumer may
/// enable for the whole build. Signatures cover the transmitted bytes, so the
/// canonical form only has to be deterministic, not identical across languages —
/// it is identical with Python's `json.dumps(sort_keys=True, separators=(",", ":"),
/// ensure_ascii=False)` for the payloads used here (integers and strings only),
/// which the shared test vectors pin.
pub fn canonical_json(value: &Value) -> String {
    let mut out = String::new();
    write_canonical(value, &mut out);
    out
}

fn write_canonical(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, key) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&Value::String((*key).clone()).to_string());
                out.push(':');
                write_canonical(&map[key.as_str()], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        scalar => out.push_str(&scalar.to_string()),
    }
}

/// Write `data` atomically: temp file in the same directory, fsync, rename.
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        if !dir.as_os_str().is_empty() {
            std::fs::create_dir_all(dir)?;
        }
    }
    let file_name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "state".to_string());
    let tmp = path.with_file_name(format!(".{file_name}.tmp"));
    {
        let mut file = std::fs::File::create(&tmp)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
        }
        file.write_all(data)?;
        file.sync_all()?;
    }
    std::fs::rename(&tmp, path)
}

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

    #[test]
    fn base32_roundtrip_all_lengths() {
        let data: Vec<u8> = (0..=255u8).collect();
        for len in 0..40 {
            let encoded = base32_encode(&data[..len]);
            assert_eq!(base32_decode(&encoded).unwrap(), &data[..len], "len {len}");
        }
    }

    #[test]
    fn base32_ignores_layout_and_maps_lookalikes() {
        let encoded = base32_encode(b"licence");
        let messy = format!("  {}\n-{}\t", &encoded[..4].to_lowercase(), &encoded[4..]);
        assert_eq!(base32_decode(&messy).unwrap(), b"licence");
        assert_eq!(base32_decode("O0").unwrap(), base32_decode("00").unwrap());
        assert_eq!(base32_decode("L0").unwrap(), vec![0x08]);
        assert_eq!(base32_decode("IO").unwrap(), vec![0x08]);
    }

    #[test]
    fn base32_rejects_garbage_and_truncation() {
        assert!(base32_decode("U0").is_err());
        let encoded = base32_encode(b"abcde12");
        assert!(base32_decode(&encoded[..encoded.len() - 1]).is_err());
    }

    #[test]
    fn hex_roundtrip() {
        assert_eq!(hex_encode(&[0, 15, 255]), "000fff");
        assert_eq!(hex_decode("000FFF").unwrap(), vec![0, 15, 255]);
        assert!(hex_decode("abc").is_none());
        assert!(hex_decode("zz").is_none());
    }

    #[test]
    fn canonical_json_sorts_nested_keys() {
        let v: Value = serde_json::from_str(r#"{"b":1,"a":{"d":[{"z":1,"y":"ä"}],"c":null}}"#)
            .unwrap();
        assert_eq!(canonical_json(&v), r#"{"a":{"c":null,"d":[{"y":"ä","z":1}]},"b":1}"#);
    }

    #[test]
    fn atomic_write_replaces_content() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sub").join("state.json");
        write_atomic(&path, b"one").unwrap();
        write_atomic(&path, b"two").unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"two");
    }
}