use std::fmt;
use jiff::{SignedDuration, Timestamp};
use secrecy::{ExposeSecret as _, SecretString};
use serde::{Deserialize, Serialize};
#[derive(Clone)]
pub struct Credentials {
username: String,
password: SecretString,
pin: Option<SecretString>,
}
impl Credentials {
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
Self {
username: username.into(),
password: SecretString::from(password.into()),
pin: None,
}
}
#[must_use]
pub fn with_pin(mut self, pin: impl Into<String>) -> Self {
self.pin = Some(SecretString::from(pin.into()));
self
}
#[must_use]
pub fn username(&self) -> &str {
&self.username
}
#[must_use]
pub fn has_pin(&self) -> bool {
self.pin.is_some()
}
pub(crate) fn password(&self) -> &str {
self.password.expose_secret()
}
pub(crate) fn pin(&self) -> Option<&str> {
self.pin.as_ref().map(SecretString::expose_secret)
}
}
impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Credentials")
.field("username", &self.username)
.field("password", &"[redacted]")
.field("pin", &self.pin.as_ref().map(|_| "[redacted]"))
.finish()
}
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct Session {
#[serde(default = "Session::first_version")]
pub(crate) version: u32,
pub(crate) access_token: String,
pub(crate) refresh_token: String,
pub(crate) expires_at: Timestamp,
pub(crate) device_id: String,
}
impl Session {
pub const FORMAT_VERSION: u32 = 1;
fn first_version() -> u32 {
1
}
pub(crate) fn new(
access_token: String,
refresh_token: String,
expires_at: Timestamp,
device_id: String,
) -> Self {
Self {
version: Self::FORMAT_VERSION,
access_token,
refresh_token,
expires_at,
device_id,
}
}
pub(crate) fn is_fresh(&self) -> bool {
Timestamp::now() + SignedDuration::from_secs(60) < self.expires_at
}
#[must_use]
pub fn expires_at(&self) -> Timestamp {
self.expires_at
}
#[must_use]
pub fn version(&self) -> u32 {
self.version
}
#[must_use]
pub fn is_supported(&self) -> bool {
self.version == Self::FORMAT_VERSION
}
}
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("version", &self.version)
.field("access_token", &"[redacted]")
.field("refresh_token", &"[redacted]")
.field("expires_at", &self.expires_at)
.field("device_id", &self.device_id)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn session() -> Session {
Session::new(
"Bearer secret-a".into(),
"secret-r".into(),
Timestamp::now(),
"dev".into(),
)
}
#[test]
fn debug_never_prints_tokens() {
let out = format!("{:?}", session());
assert!(!out.contains("secret"), "{out}");
}
#[test]
fn debug_never_prints_password_or_pin() {
let out = format!("{:?}", Credentials::new("me", "hunter2").with_pin("4321"));
assert!(!out.contains("hunter2") && !out.contains("4321"), "{out}");
}
#[test]
fn version_defaults_to_1_and_round_trips() {
let s = session();
let json = serde_json::to_value(&s).unwrap();
assert_eq!(json["version"], 1);
assert_eq!(serde_json::from_value::<Session>(json.clone()).unwrap(), s);
let mut old = json;
old.as_object_mut().unwrap().remove("version");
let old: Session = serde_json::from_value(old).unwrap();
assert!(old.is_supported());
let mut future = serde_json::to_value(&s).unwrap();
future["version"] = 2.into();
let future: Session = serde_json::from_value(future).unwrap();
assert!(!future.is_supported());
}
}