pub struct Token(/* private fields */);Expand description
Validated bearer token.
Debug output is redacted.
Use Self::verify for inbound checks.
Use Self::expose only when the raw value is required.
§Example
use solti_model::Token;
let token = Token::new("secret").unwrap();
assert!(token.verify("secret"));
assert!(!token.verify("other"));
assert_eq!(format!("{token:?}"), "Token(***redacted***)");Implementations§
Source§impl Token
impl Token
Sourcepub fn new(token: impl Into<String>) -> ModelResult<Self>
pub fn new(token: impl Into<String>) -> ModelResult<Self>
Wraps a raw token.
Surrounding whitespace is trimmed.
§Errors
Returns ModelError::Invalid when the trimmed value is empty.
§Example
use solti_model::Token;
let token = Token::new(" secret\n").unwrap();
assert_eq!(token.expose(), "secret");Sourcepub fn generate() -> ModelResult<Self>
pub fn generate() -> ModelResult<Self>
Generates a random token.
The token uses 256 bits from the operating system entropy source.
It uses unpadded base64url and starts with solti_agt_.
The token is not persisted.
§Errors
Returns ModelError::Invalid when the entropy source is unavailable.
§Example
use solti_model::Token;
let token = Token::generate()?;
assert!(token.expose().starts_with("solti_agt_"));
assert!(token.verify(token.expose()));Sourcepub fn from_env(var: &str) -> ModelResult<Self>
pub fn from_env(var: &str) -> ModelResult<Self>
Reads a token from an environment variable.
§Errors
Returns ModelError::Invalid when the variable is absent or the value is empty.
§Example
use solti_model::Token;
let token = Token::from_env("SOLTI_AGENT_TOKEN")?;Sourcepub fn from_file(path: impl AsRef<Path>) -> ModelResult<Self>
pub fn from_file(path: impl AsRef<Path>) -> ModelResult<Self>
Reads a token from a UTF-8 file.
Surrounding whitespace is trimmed.
§Errors
Returns ModelError::Invalid when the file cannot be read or the value is empty.
§Example
use solti_model::Token;
let token = Token::from_file("/run/secrets/solti-agent-token")?;Sourcepub fn expose(&self) -> &str
pub fn expose(&self) -> &str
Returns the raw token.
Inbound verification should use Self::verify.
Sourcepub fn verify(&self, candidate: &str) -> bool
pub fn verify(&self, candidate: &str) -> bool
Verifies a candidate value.
The comparison is constant-time for equal-length strings.
A length mismatch returns false.
§Example
use solti_model::Token;
let token = Token::new("secret").unwrap();
assert!(token.verify("secret"));
assert!(!token.verify("Secret"));