capy-auth 0.10.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
use crate::Secret;
use capy_core::{AppError, Result};
use std::{
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex},
};

/// Application-owned delivery. Never put reset credentials in logs or request URLs.
pub trait ResetDelivery: Send + Sync + 'static {
    /// Deliver the reset credential using an application-owned mail/notification adapter.
    /// Complete only once accepted for delivery; avoid including secrets in error messages.
    fn deliver(
        &self,
        message: ResetMessage,
    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
    /// Mark adapters that must never run in production.
    fn development_only(&self) -> bool {
        false
    }
}
/// Explicit delivery payload, redacted in Debug and not serializable.
pub struct ResetMessage {
    /// Canonical recipient address, for delivery only.
    pub email: String,
    /// Single-use credential. Prefer a URL fragment on a frontend reset page, never a query.
    pub token: Secret,
    /// Absolute Unix expiration seconds.
    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])")
    }
}
/// In-memory delivery for local development and tests. Refused in production.
/// An application can expose a local CLI inbox without logging credentials.
#[derive(Clone, Default)]
pub struct MemoryResetDelivery(Arc<Mutex<Vec<ResetMessage>>>);
impl MemoryResetDelivery {
    /// Drain the local inbox. The caller is responsible for keeping returned secrets private.
    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()))?;
            // Bound local memory even when an application never drains it.
            if inbox.len() >= 100 {
                inbox.remove(0);
            }
            inbox.push(message);
            Ok(())
        })
    }
    fn development_only(&self) -> bool {
        true
    }
}

/// Development-only private file inbox. Unix files are created with mode 0600 in a
/// mode 0700 directory; production refuses this adapter. No reset secrets are logged.
#[derive(Clone, Debug)]
pub struct LocalResetDelivery {
    directory: std::path::PathBuf,
}
impl LocalResetDelivery {
    /// Select an application-owned private directory outside frontend/public assets.
    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},
                };
                // Refuse symlinks anywhere in the configured path, including existing parents.
                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())))?;
                // This file is the explicit delivery channel, never a log or public DTO.
                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());
    }
}