use crate::Secret;
use capy_core::{AppError, Result};
use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex},
};
pub trait ResetDelivery: Send + Sync + 'static {
fn deliver(
&self,
message: ResetMessage,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
fn development_only(&self) -> bool {
false
}
}
pub struct ResetMessage {
pub email: String,
pub token: Secret,
pub expires_at: i64,
}
impl std::fmt::Debug for ResetMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ResetMessage([REDACTED])")
}
}
#[derive(Clone, Default)]
pub struct MemoryResetDelivery(Arc<Mutex<Vec<ResetMessage>>>);
impl MemoryResetDelivery {
pub fn take(&self) -> Vec<ResetMessage> {
std::mem::take(&mut *self.0.lock().expect("reset inbox lock"))
}
}
impl std::fmt::Debug for MemoryResetDelivery {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("MemoryResetDelivery([REDACTED])")
}
}
impl ResetDelivery for MemoryResetDelivery {
fn deliver(
&self,
message: ResetMessage,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
Box::pin(async move {
let mut inbox = self
.0
.lock()
.map_err(|_| AppError::Configuration("Reset inbox unavailable".into()))?;
if inbox.len() >= 100 {
inbox.remove(0);
}
inbox.push(message);
Ok(())
})
}
fn development_only(&self) -> bool {
true
}
}
#[derive(Clone, Debug)]
pub struct LocalResetDelivery {
directory: std::path::PathBuf,
}
impl LocalResetDelivery {
pub fn new(directory: impl Into<std::path::PathBuf>) -> Self {
Self {
directory: directory.into(),
}
}
}
impl ResetDelivery for LocalResetDelivery {
fn development_only(&self) -> bool {
true
}
fn deliver(
&self,
message: ResetMessage,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
Box::pin(async move {
#[cfg(unix)]
{
use std::{
fs::{self, DirBuilder, OpenOptions},
io::Write,
os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt},
};
for path in self.directory.ancestors() {
if path.as_os_str().is_empty() {
continue;
}
if let Ok(meta) = fs::symlink_metadata(path) {
if meta.file_type().is_symlink() {
return Err(AppError::Configuration(
"Reset inbox must not contain symlinks".into(),
));
}
}
}
match DirBuilder::new().mode(0o700).create(&self.directory) {
Ok(()) => (),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(e) => return Err(e.into()),
}
let meta = fs::symlink_metadata(&self.directory)?;
if !meta.is_dir() || meta.permissions().mode() & 0o077 != 0 {
return Err(AppError::Configuration(
"Reset inbox must be a private directory (0700).".into(),
));
}
let filename = crate::secret::random()?;
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(self.directory.join(format!("{}.json", filename.expose())))?;
let value = serde_json::json!({"email": message.email, "token": message.token.expose(), "expires_at": message.expires_at});
file.write_all(
serde_json::to_string(&value)
.map_err(|_| AppError::Configuration("Reset delivery failed".into()))?
.as_bytes(),
)?;
file.sync_all()?;
Ok(())
}
#[cfg(not(unix))]
{
let _ = message;
Err(AppError::Configuration(
"Use MemoryResetDelivery or an application-owned adapter on this platform."
.into(),
))
}
})
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::{symlink, PermissionsExt};
#[tokio::test]
async fn local_delivery_is_private_and_refuses_symlinks() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().canonicalize().unwrap();
let delivery = LocalResetDelivery::new(root.join("inbox"));
let message = || ResetMessage {
email: "user@example.com".into(),
token: Secret::new("private-reset-credential"),
expires_at: 123,
};
delivery.deliver(message()).await.unwrap();
let file = std::fs::read_dir(root.join("inbox"))
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
assert_eq!(
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
0o600
);
assert!(std::fs::read_to_string(file)
.unwrap()
.contains("private-reset-credential"));
assert!(!format!("{:?}", message()).contains("private-reset-credential"));
symlink(root.join("inbox"), root.join("linked")).unwrap();
assert!(LocalResetDelivery::new(root.join("linked"))
.deliver(message())
.await
.is_err());
}
}