Skip to main content

capy_auth/
delivery.rs

1use crate::Secret;
2use capy_core::{AppError, Result};
3use std::{
4    future::Future,
5    pin::Pin,
6    sync::{Arc, Mutex},
7};
8
9/// Application-owned delivery. Never put reset credentials in logs or request URLs.
10pub trait ResetDelivery: Send + Sync + 'static {
11    /// Deliver the reset credential using an application-owned mail/notification adapter.
12    /// Complete only once accepted for delivery; avoid including secrets in error messages.
13    fn deliver(
14        &self,
15        message: ResetMessage,
16    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
17    /// Mark adapters that must never run in production.
18    fn development_only(&self) -> bool {
19        false
20    }
21}
22/// Explicit delivery payload, redacted in Debug and not serializable.
23pub struct ResetMessage {
24    /// Canonical recipient address, for delivery only.
25    pub email: String,
26    /// Single-use credential. Prefer a URL fragment on a frontend reset page, never a query.
27    pub token: Secret,
28    /// Absolute Unix expiration seconds.
29    pub expires_at: i64,
30}
31impl std::fmt::Debug for ResetMessage {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str("ResetMessage([REDACTED])")
34    }
35}
36/// In-memory delivery for local development and tests. Refused in production.
37/// An application can expose a local CLI inbox without logging credentials.
38#[derive(Clone, Default)]
39pub struct MemoryResetDelivery(Arc<Mutex<Vec<ResetMessage>>>);
40impl MemoryResetDelivery {
41    /// Drain the local inbox. The caller is responsible for keeping returned secrets private.
42    pub fn take(&self) -> Vec<ResetMessage> {
43        std::mem::take(&mut *self.0.lock().expect("reset inbox lock"))
44    }
45}
46impl std::fmt::Debug for MemoryResetDelivery {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_str("MemoryResetDelivery([REDACTED])")
49    }
50}
51impl ResetDelivery for MemoryResetDelivery {
52    fn deliver(
53        &self,
54        message: ResetMessage,
55    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
56        Box::pin(async move {
57            let mut inbox = self
58                .0
59                .lock()
60                .map_err(|_| AppError::Configuration("Reset inbox unavailable".into()))?;
61            // Bound local memory even when an application never drains it.
62            if inbox.len() >= 100 {
63                inbox.remove(0);
64            }
65            inbox.push(message);
66            Ok(())
67        })
68    }
69    fn development_only(&self) -> bool {
70        true
71    }
72}
73
74/// Development-only private file inbox. Unix files are created with mode 0600 in a
75/// mode 0700 directory; production refuses this adapter. No reset secrets are logged.
76#[derive(Clone, Debug)]
77pub struct LocalResetDelivery {
78    directory: std::path::PathBuf,
79}
80impl LocalResetDelivery {
81    /// Select an application-owned private directory outside frontend/public assets.
82    pub fn new(directory: impl Into<std::path::PathBuf>) -> Self {
83        Self {
84            directory: directory.into(),
85        }
86    }
87}
88impl ResetDelivery for LocalResetDelivery {
89    fn development_only(&self) -> bool {
90        true
91    }
92    fn deliver(
93        &self,
94        message: ResetMessage,
95    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
96        Box::pin(async move {
97            #[cfg(unix)]
98            {
99                use std::{
100                    fs::{self, DirBuilder, OpenOptions},
101                    io::Write,
102                    os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt},
103                };
104                // Refuse symlinks anywhere in the configured path, including existing parents.
105                for path in self.directory.ancestors() {
106                    if path.as_os_str().is_empty() {
107                        continue;
108                    }
109                    if let Ok(meta) = fs::symlink_metadata(path) {
110                        if meta.file_type().is_symlink() {
111                            return Err(AppError::Configuration(
112                                "Reset inbox must not contain symlinks".into(),
113                            ));
114                        }
115                    }
116                }
117                match DirBuilder::new().mode(0o700).create(&self.directory) {
118                    Ok(()) => (),
119                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => (),
120                    Err(e) => return Err(e.into()),
121                }
122                let meta = fs::symlink_metadata(&self.directory)?;
123                if !meta.is_dir() || meta.permissions().mode() & 0o077 != 0 {
124                    return Err(AppError::Configuration(
125                        "Reset inbox must be a private directory (0700).".into(),
126                    ));
127                }
128                let filename = crate::secret::random()?;
129                let mut file = OpenOptions::new()
130                    .write(true)
131                    .create_new(true)
132                    .mode(0o600)
133                    .open(self.directory.join(format!("{}.json", filename.expose())))?;
134                // This file is the explicit delivery channel, never a log or public DTO.
135                let value = serde_json::json!({"email": message.email, "token": message.token.expose(), "expires_at": message.expires_at});
136                file.write_all(
137                    serde_json::to_string(&value)
138                        .map_err(|_| AppError::Configuration("Reset delivery failed".into()))?
139                        .as_bytes(),
140                )?;
141                file.sync_all()?;
142                Ok(())
143            }
144            #[cfg(not(unix))]
145            {
146                let _ = message;
147                Err(AppError::Configuration(
148                    "Use MemoryResetDelivery or an application-owned adapter on this platform."
149                        .into(),
150                ))
151            }
152        })
153    }
154}
155
156#[cfg(all(test, unix))]
157mod tests {
158    use super::*;
159    use std::os::unix::fs::{symlink, PermissionsExt};
160    #[tokio::test]
161    async fn local_delivery_is_private_and_refuses_symlinks() {
162        let temp = tempfile::tempdir().unwrap();
163        let root = temp.path().canonicalize().unwrap();
164        let delivery = LocalResetDelivery::new(root.join("inbox"));
165        let message = || ResetMessage {
166            email: "user@example.com".into(),
167            token: Secret::new("private-reset-credential"),
168            expires_at: 123,
169        };
170        delivery.deliver(message()).await.unwrap();
171        let file = std::fs::read_dir(root.join("inbox"))
172            .unwrap()
173            .next()
174            .unwrap()
175            .unwrap()
176            .path();
177        assert_eq!(
178            std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
179            0o600
180        );
181        assert!(std::fs::read_to_string(file)
182            .unwrap()
183            .contains("private-reset-credential"));
184        assert!(!format!("{:?}", message()).contains("private-reset-credential"));
185        symlink(root.join("inbox"), root.join("linked")).unwrap();
186        assert!(LocalResetDelivery::new(root.join("linked"))
187            .deliver(message())
188            .await
189            .is_err());
190    }
191}