use garrison::prelude::GarrisonConfig;
use thiserror::Error;
pub const MIN_JWT_SECRET_BYTES: usize = 32;
#[derive(Debug, Error)]
pub enum GarrisonConfigError {
#[error("jwt_secret must not be empty or missing")]
EmptySecret,
#[error("weak jwt_secret: length {len} < {min} bytes (HS256 minimum)")]
WeakSecret {
len: usize,
min: usize,
},
}
pub fn build_garrison_config(jwt_secret: &str) -> Result<GarrisonConfig, GarrisonConfigError> {
if jwt_secret.is_empty() {
return Err(GarrisonConfigError::EmptySecret);
}
if jwt_secret.len() < MIN_JWT_SECRET_BYTES {
return Err(GarrisonConfigError::WeakSecret {
len: jwt_secret.len(),
min: MIN_JWT_SECRET_BYTES,
});
}
let mut config = GarrisonConfig::default_config();
config.token_style = "jwt".to_string();
config.jwt_algorithm = "HS256".to_string();
config.jwt_secret = jwt_secret.to_string().into();
config.is_read_cookie = false;
config.is_write_cookie = false;
config.frontend_separation = true;
Ok(config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build_garrison_config_rejects_empty_secret() {
let result = build_garrison_config("");
assert!(
matches!(result, Err(GarrisonConfigError::EmptySecret)),
"empty jwt_secret must be rejected with EmptySecret, got: {:?}",
result
);
}
#[test]
fn test_build_garrison_config_rejects_weak_secret() {
let weak = "too_short"; let result = build_garrison_config(weak);
assert!(
matches!(result, Err(GarrisonConfigError::WeakSecret { len: 9, min: 32 })),
"weak jwt_secret (<32 bytes) must be rejected with WeakSecret {{ len: 9, min: 32 }}, got: {:?}",
result
);
}
#[test]
fn test_build_garrison_config_strong_secret_returns_jwt_config() {
let strong = "a-very-strong-secret-key-32-bytes-or-more!!"; let result = build_garrison_config(strong);
assert!(result.is_ok(), "strong jwt_secret must be accepted");
let config = result.unwrap();
assert_eq!(
config.token_style, "jwt",
"token_style must be 'jwt' for crawlrs garrison auth"
);
}
#[test]
fn test_build_garrison_config_boundary_32_bytes_accepted() {
let boundary = "0123456789abcdef0123456789abcdef"; let result = build_garrison_config(boundary);
assert!(
result.is_ok(),
"32-byte jwt_secret (boundary) must be accepted"
);
}
#[test]
fn test_build_garrison_config_business_fields_overridden() {
let strong = "a-very-strong-secret-key-32-bytes-or-more!!";
let config = build_garrison_config(strong).unwrap();
assert!(
!config.is_read_cookie,
"is_read_cookie must be false (frontend separation)"
);
assert!(
!config.is_write_cookie,
"is_write_cookie must be false (frontend separation)"
);
assert!(
config.frontend_separation,
"frontend_separation must be true"
);
assert_eq!(config.jwt_algorithm, "HS256", "jwt_algorithm must be HS256");
}
}