entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! RFC 3986 percent-encoding for URLs.
//!
//! Provides encoding and decoding of URL strings using percent-encoding as
//! defined in RFC 3986. The unreserved character set (`ALPHA / DIGIT / "-" /
//! "." / "_" / "~"`) is never encoded.

use core::fmt;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Uppercase hex digits used in percent-encoding output.
const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";

/// Returns `true` if the byte is an RFC 3986 unreserved character.
///
/// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
#[inline]
const fn is_unreserved(byte: u8) -> bool {
    matches!(byte, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~')
}

/// Returns `true` if the byte is a character that `url_encode` preserves
/// (unreserved characters plus commonly-preserved URL structural characters).
///
/// `url_encode` is a "path-safe" encoder: it preserves the characters that are
/// meaningful in a full URL so that a URL passed through it stays intact.
/// `url_encode_component` is stricter — it only preserves unreserved chars.
///
/// Preserved set (superset of unreserved):
///   unreserved / `:` / `/` / `?` / `#` / `[` / `]` / `@`
///   `!` / `$` / `&` / `'` / `(` / `)` / `*` / `+` / `,` / `;` / `=`
#[inline]
const fn is_url_safe(byte: u8) -> bool {
    is_unreserved(byte)
        || matches!(
            byte,
            b':' | b'/'
                | b'?'
                | b'#'
                | b'['
                | b']'
                | b'@'
                | b'!'
                | b'$'
                | b'&'
                | b'\''
                | b'('
                | b')'
                | b'*'
                | b'+'
                | b','
                | b';'
                | b'='
        )
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UrlDecodeErrorKind {
    /// A `%` is not followed by exactly two hex digits.
    InvalidPercentSequence,
    /// The decoded bytes do not form valid UTF-8.
    InvalidUtf8,
}

/// Error returned when URL percent-decoding fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlDecodeError {
    kind: UrlDecodeErrorKind,
}

impl UrlDecodeError {
    const fn new(kind: UrlDecodeErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for UrlDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            UrlDecodeErrorKind::InvalidPercentSequence => {
                write!(f, "url: invalid percent-encoded sequence")
            }
            UrlDecodeErrorKind::InvalidUtf8 => {
                write!(f, "url: decoded bytes are not valid UTF-8")
            }
        }
    }
}

impl std::error::Error for UrlDecodeError {}

// ---------------------------------------------------------------------------
// Encoding
// ---------------------------------------------------------------------------

/// Percent-encode a URL string, preserving reserved and unreserved characters.
///
/// Characters that are part of the general URL syntax (`:`, `/`, `?`, `#`,
/// `@`, etc.) and the unreserved set are passed through unchanged. All other
/// bytes (including multi-byte UTF-8 sequences) are percent-encoded.
///
/// Use [`url_encode_component`] when encoding a value that will be embedded
/// inside a query parameter or path segment.
#[must_use]
pub fn url_encode(input: &str) -> String {
    encode_impl(input, is_url_safe)
}

/// Percent-encode a URL component, encoding everything except unreserved characters.
///
/// Only the RFC 3986 unreserved characters (`ALPHA / DIGIT / "-" / "." / "_" / "~"`)
/// are passed through. Everything else — including reserved characters like `&`,
/// `=`, `/` — is percent-encoded.
#[must_use]
pub fn url_encode_component(input: &str) -> String {
    encode_impl(input, is_unreserved)
}

/// Shared encoding implementation parameterised by a predicate that decides
/// which bytes to preserve.
fn encode_impl(input: &str, preserve: fn(u8) -> bool) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());

    for &byte in bytes {
        if preserve(byte) {
            out.push(byte);
        } else {
            out.push(b'%');
            out.push(HEX_UPPER[(byte >> 4) as usize]);
            out.push(HEX_UPPER[(byte & 0x0F) as usize]);
        }
    }

    // NOTE: unreserved ASCII chars and percent-encoded sequences are all
    // ASCII, so from_utf8 cannot fail in practice. We avoid `unsafe`
    // to maintain the crate's deny(unsafe_code) policy.
    // SAFETY (logical): all bytes pushed to `out` are either preserved
    // ASCII chars or percent-encoded hex sequences; the unwrap is
    // unreachable.
    #[allow(clippy::expect_used)]
    String::from_utf8(out).expect("url-encoded output is always valid ASCII")
}

// ---------------------------------------------------------------------------
// Decoding
// ---------------------------------------------------------------------------

/// Decode a percent-encoded URL string.
///
/// Each `%XX` sequence is replaced with the byte whose value is `XX` (two
/// hex digits, case-insensitive). The resulting bytes must form valid UTF-8.
///
/// # Errors
///
/// Returns [`UrlDecodeError`] if the input contains an invalid percent-encoding
/// sequence or the decoded bytes are not valid UTF-8.
pub fn url_decode(input: &str) -> Result<String, UrlDecodeError> {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err(UrlDecodeError::new(
                    UrlDecodeErrorKind::InvalidPercentSequence,
                ));
            }
            let high = hex_value(bytes[i + 1])?;
            let low = hex_value(bytes[i + 2])?;
            out.push((high << 4) | low);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }

    String::from_utf8(out).map_err(|_| UrlDecodeError::new(UrlDecodeErrorKind::InvalidUtf8))
}

/// Convert an ASCII hex digit to its 4-bit value.
#[inline]
fn hex_value(byte: u8) -> Result<u8, UrlDecodeError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        _ => Err(UrlDecodeError::new(
            UrlDecodeErrorKind::InvalidPercentSequence,
        )),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- url_encode ---

    #[test]
    fn encode_empty() {
        assert_eq!(url_encode(""), "");
    }

    #[test]
    fn encode_unreserved_passthrough() {
        let unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
        assert_eq!(url_encode(unreserved), unreserved);
    }

    #[test]
    fn encode_preserves_reserved_characters() {
        let reserved = ":/?#[]@!$&'()*+,;=";
        assert_eq!(url_encode(reserved), reserved);
    }

    #[test]
    fn encode_space() {
        assert_eq!(url_encode("hello world"), "hello%20world");
    }

    #[test]
    fn encode_utf8_multibyte() {
        // U+00E9 (e-acute) is 0xC3 0xA9 in UTF-8.
        assert_eq!(url_encode("\u{00E9}"), "%C3%A9");
    }

    // --- url_encode_component ---

    #[test]
    fn component_encode_empty() {
        assert_eq!(url_encode_component(""), "");
    }

    #[test]
    fn component_encode_unreserved_passthrough() {
        let unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
        assert_eq!(url_encode_component(unreserved), unreserved);
    }

    #[test]
    fn component_encode_reserved_characters() {
        // url_encode_component must encode reserved characters.
        assert_eq!(url_encode_component("a=b&c=d"), "a%3Db%26c%3Dd");
    }

    #[test]
    fn component_encode_slash() {
        assert_eq!(
            url_encode_component("path/to/resource"),
            "path%2Fto%2Fresource"
        );
    }

    #[test]
    fn component_encode_space() {
        assert_eq!(url_encode_component("hello world"), "hello%20world");
    }

    #[test]
    fn component_encode_utf8_multibyte() {
        assert_eq!(url_encode_component("\u{00E9}"), "%C3%A9");
    }

    #[test]
    fn component_encode_all_ascii_special() {
        // Every non-unreserved ASCII printable char should be encoded.
        for byte in 0x20u8..=0x7E {
            let ch = byte as char;
            let s = ch.to_string();
            let encoded = url_encode_component(&s);
            if is_unreserved(byte) {
                assert_eq!(encoded, s, "unreserved char {ch:?} should not be encoded");
            } else {
                assert!(
                    encoded.starts_with('%'),
                    "non-unreserved char {ch:?} should be percent-encoded, got {encoded:?}"
                );
            }
        }
    }

    // --- url_decode ---

    #[test]
    fn decode_empty() {
        assert_eq!(url_decode("").unwrap(), "");
    }

    #[test]
    fn decode_no_percent() {
        assert_eq!(url_decode("hello").unwrap(), "hello");
    }

    #[test]
    fn decode_space() {
        assert_eq!(url_decode("hello%20world").unwrap(), "hello world");
    }

    #[test]
    fn decode_uppercase_hex() {
        assert_eq!(url_decode("%2F").unwrap(), "/");
    }

    #[test]
    fn decode_lowercase_hex() {
        assert_eq!(url_decode("%2f").unwrap(), "/");
    }

    #[test]
    fn decode_mixed_case_hex() {
        assert_eq!(url_decode("%2F%2f").unwrap(), "//");
    }

    #[test]
    fn decode_utf8_multibyte() {
        assert_eq!(url_decode("%C3%A9").unwrap(), "\u{00E9}");
    }

    #[test]
    fn decode_preserves_unreserved() {
        let input = "abcABC123-._~";
        assert_eq!(url_decode(input).unwrap(), input);
    }

    // --- Round-trip ---

    #[test]
    fn round_trip_component() {
        let inputs = [
            "",
            "hello",
            "hello world",
            "a=b&c=d",
            "path/to/resource",
            "caf\u{00E9}",
            "100%",
            "\u{1F600}",
        ];
        for &input in &inputs {
            let encoded = url_encode_component(input);
            let decoded = url_decode(&encoded).unwrap();
            assert_eq!(decoded, input, "round-trip failed for {input:?}");
        }
    }

    #[test]
    fn round_trip_ascii_range() {
        // Every printable ASCII character should round-trip through component encoding.
        for byte in 0x20u8..=0x7E {
            let s = String::from(byte as char);
            let encoded = url_encode_component(&s);
            let decoded = url_decode(&encoded).unwrap();
            assert_eq!(decoded, s, "round-trip failed for byte {byte:#04X}");
        }
    }

    // --- Error cases ---

    #[test]
    fn decode_rejects_incomplete_percent_at_end() {
        let err = url_decode("abc%2").unwrap_err();
        assert_eq!(
            err,
            UrlDecodeError::new(UrlDecodeErrorKind::InvalidPercentSequence)
        );
    }

    #[test]
    fn decode_rejects_percent_at_very_end() {
        let err = url_decode("abc%").unwrap_err();
        assert_eq!(
            err,
            UrlDecodeError::new(UrlDecodeErrorKind::InvalidPercentSequence)
        );
    }

    #[test]
    fn decode_rejects_invalid_hex_digits() {
        let err = url_decode("%GG").unwrap_err();
        assert_eq!(
            err,
            UrlDecodeError::new(UrlDecodeErrorKind::InvalidPercentSequence)
        );
    }

    #[test]
    fn decode_rejects_percent_with_non_hex() {
        assert!(url_decode("%ZZ").is_err());
        assert!(url_decode("% 0").is_err());
    }

    #[test]
    fn decode_rejects_invalid_utf8() {
        // 0xFF is not valid as a start byte in UTF-8.
        let err = url_decode("%FF").unwrap_err();
        assert_eq!(err, UrlDecodeError::new(UrlDecodeErrorKind::InvalidUtf8));
    }

    // --- Display ---

    #[test]
    fn error_display_messages() {
        let pct = UrlDecodeError::new(UrlDecodeErrorKind::InvalidPercentSequence);
        assert_eq!(pct.to_string(), "url: invalid percent-encoded sequence");

        let utf8 = UrlDecodeError::new(UrlDecodeErrorKind::InvalidUtf8);
        assert_eq!(utf8.to_string(), "url: decoded bytes are not valid UTF-8");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(UrlDecodeError::new(
            UrlDecodeErrorKind::InvalidPercentSequence,
        ));
        let _ = err.to_string();
    }
}