wisegate-core 0.13.0

Core library for WiseGate reverse proxy - rate limiting, IP filtering, and request handling
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Authentication module for HTTP Basic Authentication (RFC 7617) and Bearer Token (RFC 6750).
//!
//! Provides credential storage, verification, and HTTP header parsing for
//! implementing Basic Authentication and Bearer Token authentication in WiseGate.

pub mod hash;

use base64::{Engine, engine::general_purpose::STANDARD};
use std::sync::{Arc, LazyLock};
use tokio::sync::Semaphore;

// Process-wide: permissive requests without an attributable IP are also bounded.
static AUTH_SLOTS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(4)));

#[derive(Debug)]
pub(crate) struct AuthCheckUnavailable;

/// Keep password hashing off the async executor, with no unbounded waiting queue.
pub(crate) async fn check_basic_auth_bounded(
    auth_header: Option<&str>,
    credentials: &Credentials,
) -> Result<bool, AuthCheckUnavailable> {
    check_basic_auth_with_slots(auth_header, credentials, &AUTH_SLOTS).await
}

async fn check_basic_auth_with_slots(
    auth_header: Option<&str>,
    credentials: &Credentials,
    slots: &Arc<Semaphore>,
) -> Result<bool, AuthCheckUnavailable> {
    if credentials.is_empty() {
        return Ok(true);
    }
    let Some(header) = auth_header.filter(|h| h.starts_with("Basic ")) else {
        return Ok(false);
    };
    let permit = slots
        .clone()
        .try_acquire_owned()
        .map_err(|_| AuthCheckUnavailable)?;
    let credentials = credentials.clone();
    let header = header.to_owned();
    run_auth_check(permit, move || credentials.verify(&header)).await
}

async fn run_auth_check(
    permit: tokio::sync::OwnedSemaphorePermit,
    check: impl FnOnce() -> bool + Send + 'static,
) -> Result<bool, AuthCheckUnavailable> {
    tokio::task::spawn_blocking(move || {
        // Cancellation of the requesting task must not release the slot while
        // a non-cancellable hash check is still running.
        let _permit = permit;
        check()
    })
    .await
    .map_err(|_| AuthCheckUnavailable)
}

/// A single credential entry (username and password/hash).
#[derive(Debug, Clone)]
pub struct Credential {
    username: String,
    password: String,
}

impl Credential {
    /// Creates a new credential from username and password/hash.
    pub fn new(username: String, password: String) -> Self {
        Self { username, password }
    }

    /// Parses a credential string in the format "username:password".
    ///
    /// # Errors
    ///
    /// Returns `None` if the string doesn't contain a colon or has an empty username.
    pub fn parse(value: &str) -> Option<Self> {
        let (user, pass) = value.split_once(':')?;
        if user.is_empty() {
            return None;
        }
        Some(Self::new(user.to_string(), pass.to_string()))
    }

    /// Returns the username.
    pub fn username(&self) -> &str {
        &self.username
    }

    /// Returns the password/hash.
    pub fn password(&self) -> &str {
        &self.password
    }
}

/// Stores credentials for authentication.
#[derive(Debug, Clone)]
pub struct Credentials {
    entries: Vec<Credential>,
}

impl Credentials {
    /// Creates a new empty credentials store.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Creates credentials from a slice of credential entries.
    pub fn from_entries(entries: Vec<Credential>) -> Self {
        Self { entries }
    }

    /// Returns true if no credentials are stored.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns the number of stored credentials.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Verifies credentials from an HTTP Authorization header.
    ///
    /// Expects the header value in the format `Basic {base64-encoded-credentials}`
    /// per RFC 7617.
    pub fn verify(&self, auth_header: &str) -> bool {
        let Some(encoded) = auth_header.strip_prefix("Basic ") else {
            return false;
        };

        let Ok(decoded) = STANDARD.decode(encoded.trim()) else {
            return false;
        };

        let Ok(decoded_str) = String::from_utf8(decoded) else {
            return false;
        };

        // RFC 7617: user-id cannot contain colons, password may contain colons
        let Some((user, password)) = decoded_str.split_once(':') else {
            return false;
        };

        self.check(user, password)
    }

    /// Checks if the given username and password match any stored credential.
    /// Uses constant-time comparison to prevent timing attacks.
    fn check(&self, username: &str, password: &str) -> bool {
        let mut found = false;
        for cred in &self.entries {
            // Use constant-time comparison for username to prevent enumeration
            let user_match = hash::constant_time_eq(cred.username.as_bytes(), username.as_bytes());
            // Always verify password to prevent timing leaks
            let pass_match = hash::verify(password, &cred.password);
            if user_match && pass_match {
                found = true;
            }
        }
        found
    }
}

impl Default for Credentials {
    fn default() -> Self {
        Self::new()
    }
}

/// Checks if the request has valid Basic authentication.
///
/// Returns `true` if authentication is successful or not required.
/// Returns `false` if authentication is required but failed.
///
/// # Arguments
///
/// * `auth_header` - The value of the Authorization header, if present.
/// * `credentials` - The credentials to check against.
pub fn check_basic_auth(auth_header: Option<&str>, credentials: &Credentials) -> bool {
    if credentials.is_empty() {
        // No credentials configured, authentication not required
        return true;
    }

    match auth_header {
        Some(header) => credentials.verify(header),
        None => false,
    }
}

/// Checks if the request has a valid Bearer token.
///
/// Returns `true` if authentication is successful or not required.
/// Returns `false` if authentication is required but failed.
///
/// # Arguments
///
/// * `auth_header` - The value of the Authorization header, if present.
/// * `expected_token` - The expected bearer token, if configured.
pub fn check_bearer_token(auth_header: Option<&str>, expected_token: Option<&str>) -> bool {
    let Some(expected) = expected_token else {
        // No token configured, authentication not required
        return true;
    };

    if expected.is_empty() {
        // Empty token means disabled
        return true;
    }

    let Some(header) = auth_header else {
        return false;
    };

    // RFC 6750: auth-scheme is case-insensitive
    let Some(token) = header
        .get(..7)
        .filter(|prefix| prefix.eq_ignore_ascii_case("bearer "))
        .map(|_| &header[7..])
    else {
        return false;
    };

    // Use constant-time comparison to prevent timing attacks
    hash::constant_time_eq(token.trim().as_bytes(), expected.as_bytes())
}

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

    #[tokio::test]
    async fn saturated_auth_rejects_without_waiting() {
        use futures::FutureExt;

        let slots = Arc::new(Semaphore::new(1));
        let _permit = slots.clone().try_acquire_owned().unwrap();
        let credentials = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);
        let header = format!("Basic {}", STANDARD.encode("admin:secret"));
        assert!(
            check_basic_auth_with_slots(Some(&header), &credentials, &slots)
                .now_or_never()
                .expect("saturated authentication must not queue")
                .is_err()
        );
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blocking_auth_keeps_its_slot_after_request_cancellation() {
        let slots = Arc::new(Semaphore::new(1));
        let permit = slots.clone().try_acquire_owned().unwrap();
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let (finish_tx, finish_rx) = std::sync::mpsc::channel();
        let task = tokio::spawn(run_auth_check(permit, move || {
            started_tx.send(()).unwrap();
            // Bounded even if a regression makes the assertions below panic.
            finish_rx
                .recv_timeout(std::time::Duration::from_secs(2))
                .unwrap();
            true
        }));

        // A blocking call on this single-thread executor would prevent progress.
        started_rx.await.unwrap();
        task.abort();
        assert!(task.await.unwrap_err().is_cancelled());
        assert!(slots.clone().try_acquire_owned().is_err());
        finish_tx.send(()).unwrap();
        let released =
            tokio::time::timeout(std::time::Duration::from_secs(2), slots.acquire_owned())
                .await
                .expect("slot must be released when hashing finishes")
                .unwrap();
        drop(released);
    }

    #[tokio::test]
    async fn bounded_basic_auth_preserves_valid_and_invalid_credentials() {
        let credentials = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);
        let valid = format!("Basic {}", STANDARD.encode("admin:secret"));
        let invalid = format!("Basic {}", STANDARD.encode("admin:wrong"));
        assert!(
            check_basic_auth_bounded(Some(&valid), &credentials)
                .await
                .unwrap()
        );
        assert!(
            !check_basic_auth_bounded(Some(&invalid), &credentials)
                .await
                .unwrap()
        );
        assert!(!check_basic_auth_bounded(None, &credentials).await.unwrap());
    }

    #[test]
    fn test_credential_parse_valid() {
        let cred = Credential::parse("admin:secret").unwrap();
        assert_eq!(cred.username(), "admin");
        assert_eq!(cred.password(), "secret");
    }

    #[test]
    fn test_credential_parse_with_colon_in_password() {
        let cred = Credential::parse("admin:sec:ret").unwrap();
        assert_eq!(cred.username(), "admin");
        assert_eq!(cred.password(), "sec:ret");
    }

    #[test]
    fn test_credential_parse_no_colon() {
        assert!(Credential::parse("invalid").is_none());
    }

    #[test]
    fn test_credential_parse_empty_user() {
        assert!(Credential::parse(":password").is_none());
    }

    #[test]
    fn test_credentials_empty() {
        let creds = Credentials::new();
        assert!(creds.is_empty());
        assert_eq!(creds.len(), 0);
    }

    #[test]
    fn test_credentials_from_entries() {
        let entries = vec![
            Credential::new("admin".to_string(), "secret".to_string()),
            Credential::new("user".to_string(), "pass".to_string()),
        ];
        let creds = Credentials::from_entries(entries);
        assert!(!creds.is_empty());
        assert_eq!(creds.len(), 2);
    }

    #[test]
    fn test_verify_plain_text() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);

        let header = format!("Basic {}", STANDARD.encode("admin:secret"));
        assert!(creds.verify(&header));
    }

    #[test]
    fn test_verify_wrong_password() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);

        let header = format!("Basic {}", STANDARD.encode("admin:wrong"));
        assert!(!creds.verify(&header));
    }

    #[test]
    fn test_verify_wrong_user() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);

        let header = format!("Basic {}", STANDARD.encode("wrong:secret"));
        assert!(!creds.verify(&header));
    }

    #[test]
    fn test_verify_bcrypt() {
        // bcrypt hash for "password"
        let hash = "$2y$05$bvIG6Nmid91Mu9RcmmWZfO5HJIMCT8riNW0hEp8f6/FuA2/mHZFpe";
        let creds =
            Credentials::from_entries(vec![Credential::new("user".to_string(), hash.to_string())]);

        let header = format!("Basic {}", STANDARD.encode("user:password"));
        assert!(creds.verify(&header));
    }

    #[test]
    fn test_verify_sha1() {
        // SHA1 hash for "password"
        let hash = "{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=";
        let creds =
            Credentials::from_entries(vec![Credential::new("user".to_string(), hash.to_string())]);

        let header = format!("Basic {}", STANDARD.encode("user:password"));
        assert!(creds.verify(&header));
    }

    #[test]
    fn test_verify_apr1() {
        // APR1 hash for "password"
        let hash = "$apr1$lZL6V/ci$eIMz/iKDkbtys/uU7LEK00";
        let creds =
            Credentials::from_entries(vec![Credential::new("user".to_string(), hash.to_string())]);

        let header = format!("Basic {}", STANDARD.encode("user:password"));
        assert!(creds.verify(&header));
    }

    #[test]
    fn test_verify_multiple_credentials() {
        let creds = Credentials::from_entries(vec![
            Credential::new("admin".to_string(), "admin123".to_string()),
            Credential::new("user1".to_string(), "pass1".to_string()),
            Credential::new("user2".to_string(), "pass2".to_string()),
        ]);

        assert!(creds.verify(&format!("Basic {}", STANDARD.encode("admin:admin123"))));
        assert!(creds.verify(&format!("Basic {}", STANDARD.encode("user1:pass1"))));
        assert!(creds.verify(&format!("Basic {}", STANDARD.encode("user2:pass2"))));
        assert!(!creds.verify(&format!("Basic {}", STANDARD.encode("unknown:pass"))));
    }

    #[test]
    fn test_verify_invalid_base64() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);
        assert!(!creds.verify("Basic not-valid-base64!!!"));
    }

    #[test]
    fn test_verify_non_basic_auth() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);
        assert!(!creds.verify("Bearer some-token"));
        assert!(!creds.verify("bearer some-token"));
    }

    #[test]
    fn test_verify_missing_colon_in_decoded() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);
        let header = format!("Basic {}", STANDARD.encode("no-colon-here"));
        assert!(!creds.verify(&header));
    }

    #[test]
    fn test_check_basic_auth_no_credentials() {
        let creds = Credentials::new();
        // No credentials = authentication not required
        assert!(check_basic_auth(None, &creds));
        assert!(check_basic_auth(Some("Basic anything"), &creds));
    }

    #[test]
    fn test_check_basic_auth_with_credentials() {
        let creds = Credentials::from_entries(vec![Credential::new(
            "admin".to_string(),
            "secret".to_string(),
        )]);

        // No header = fail
        assert!(!check_basic_auth(None, &creds));

        // Valid header = success
        let valid_header = format!("Basic {}", STANDARD.encode("admin:secret"));
        assert!(check_basic_auth(Some(&valid_header), &creds));

        // Invalid header = fail
        let invalid_header = format!("Basic {}", STANDARD.encode("admin:wrong"));
        assert!(!check_basic_auth(Some(&invalid_header), &creds));
    }

    // ===========================================
    // Bearer token tests
    // ===========================================

    #[test]
    fn test_check_bearer_token_no_token_configured() {
        // No token configured = always pass
        assert!(check_bearer_token(None, None));
        assert!(check_bearer_token(Some("Bearer anything"), None));
    }

    #[test]
    fn test_check_bearer_token_empty_token() {
        // Empty token = disabled
        assert!(check_bearer_token(None, Some("")));
        assert!(check_bearer_token(Some("Bearer anything"), Some("")));
    }

    #[test]
    fn test_check_bearer_token_valid() {
        let token = "my-secret-token";
        let header = "Bearer my-secret-token";
        assert!(check_bearer_token(Some(header), Some(token)));
    }

    #[test]
    fn test_check_bearer_token_valid_with_whitespace() {
        let token = "my-secret-token";
        let header = "Bearer my-secret-token ";
        assert!(check_bearer_token(Some(header), Some(token)));
    }

    #[test]
    fn test_check_bearer_token_invalid() {
        let token = "my-secret-token";
        let header = "Bearer wrong-token";
        assert!(!check_bearer_token(Some(header), Some(token)));
    }

    #[test]
    fn test_check_bearer_token_no_header() {
        let token = "my-secret-token";
        assert!(!check_bearer_token(None, Some(token)));
    }

    #[test]
    fn test_check_bearer_token_basic_auth_header() {
        // Basic auth header should not work for bearer
        let token = "my-secret-token";
        let header = format!("Basic {}", STANDARD.encode("user:pass"));
        assert!(!check_bearer_token(Some(&header), Some(token)));
    }

    #[test]
    fn test_check_bearer_token_value_case_sensitive() {
        let token = "MySecretToken";
        assert!(check_bearer_token(
            Some("Bearer MySecretToken"),
            Some(token)
        ));
        assert!(!check_bearer_token(
            Some("Bearer mysecrettoken"),
            Some(token)
        ));
    }

    #[test]
    fn test_check_bearer_token_prefix_case_insensitive() {
        // RFC 6750: auth-scheme is case-insensitive
        let token = "my-secret-token";
        assert!(check_bearer_token(
            Some("bearer my-secret-token"),
            Some(token)
        ));
        assert!(check_bearer_token(
            Some("BEARER my-secret-token"),
            Some(token)
        ));
        assert!(check_bearer_token(
            Some("Bearer my-secret-token"),
            Some(token)
        ));
    }
}