Add SMTP mail, access-request notifications, and a shared request throttle
A new [mail] section configures an SMTP relay (SES-style STARTTLS or implicit TLS; the password is environment-only via DAILY_EPUB_MAIL__SMTP_PASS) and src/mail.rs wraps lettre in a small plain-text Mailer built once at server start. Each stored access request now emails mail.notify_to in a spawned task with the address, reason, time, and a link to /dashboard/users. POST /request-access shares the login endpoint's per-IP limiter (server.login_attempts per window). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QVPagF6jfDv78CC5Jv2wp4
This commit is contained in:
+101
-2
@@ -71,6 +71,7 @@ pub(super) async fn submit(
|
||||
return Ok(Html(view).into_response());
|
||||
}
|
||||
|
||||
let requested_at = crate::db::fmt_ts(jiff::Timestamp::now());
|
||||
sqlx::query(
|
||||
"INSERT INTO account_requests (email, reason, status, requested_at)
|
||||
VALUES (?, ?, 'open', ?)
|
||||
@@ -81,11 +82,40 @@ pub(super) async fn submit(
|
||||
)
|
||||
.bind(email)
|
||||
.bind((!reason.is_empty()).then_some(reason))
|
||||
.bind(crate::db::fmt_ts(jiff::Timestamp::now()))
|
||||
.bind(&requested_at)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.map_err(|error| WebError::Db(error.into()))?;
|
||||
|
||||
let config = state.config();
|
||||
if let (Some(mailer), Some(to)) = (
|
||||
state.mailer.clone(),
|
||||
config
|
||||
.mail
|
||||
.notify_to
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty()),
|
||||
) {
|
||||
let reason = if reason.is_empty() {
|
||||
"(no reason given)"
|
||||
} else {
|
||||
reason
|
||||
};
|
||||
let message = crate::mail::Message {
|
||||
to: to.to_string(),
|
||||
subject: format!("Access request from {email}"),
|
||||
body: format!(
|
||||
"Email: {email}\nReason: {reason}\nRequested at: {requested_at}\nReview: {}/dashboard/users\n",
|
||||
config.server.public_url.trim_end_matches('/')
|
||||
),
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = mailer.send(message).await {
|
||||
tracing::warn!(%error, "could not send access-request notification");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let mut view = template(viewer);
|
||||
view.submitted = true;
|
||||
Ok(Html(view).into_response())
|
||||
@@ -117,11 +147,15 @@ mod tests {
|
||||
use crate::server::{AppState, router};
|
||||
|
||||
async fn app() -> (tempfile::TempDir, Db, axum::Router) {
|
||||
app_with_config(Config::default()).await
|
||||
}
|
||||
|
||||
async fn app_with_config(config: Config) -> (tempfile::TempDir, Db, axum::Router) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = Db::open_and_migrate(&dir.path().join("db.sqlite"))
|
||||
.await
|
||||
.unwrap();
|
||||
let app = router(AppState::new(db.clone(), Config::default(), None));
|
||||
let app = router(AppState::new(db.clone(), config, None));
|
||||
(dir, db, app)
|
||||
}
|
||||
|
||||
@@ -156,6 +190,7 @@ mod tests {
|
||||
.uri("/request-access")
|
||||
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||
.header("sec-fetch-site", "same-origin")
|
||||
.header("x-forwarded-for", "192.0.2.30")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
@@ -209,6 +244,70 @@ mod tests {
|
||||
assert_eq!(row.get::<String, _>("status"), "open");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stored_request_queues_an_operator_notification() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = Db::open_and_migrate(&dir.path().join("db.sqlite"))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut config = Config::default();
|
||||
config.server.public_url = "https://daily.example/".into();
|
||||
config.mail.notify_to = Some("Operator <operator@example.com>".into());
|
||||
let (mailer, messages) = crate::mail::Mailer::recording();
|
||||
let mut state = AppState::new(db, config, None);
|
||||
state.mailer = Some(mailer);
|
||||
let app = router(state);
|
||||
|
||||
let (status, _) = post(&app, "email=reader%40example.com&reason=&website=").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
loop {
|
||||
if !messages
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.is_empty()
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("notification task did not run");
|
||||
|
||||
let messages = messages
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert_eq!(messages[0].to, "Operator <operator@example.com>");
|
||||
assert_eq!(
|
||||
messages[0].subject,
|
||||
"Access request from reader@example.com"
|
||||
);
|
||||
assert!(messages[0].body.contains("Email: reader@example.com"));
|
||||
assert!(messages[0].body.contains("Reason: (no reason given)"));
|
||||
assert!(messages[0].body.contains("Requested at: "));
|
||||
assert!(
|
||||
messages[0]
|
||||
.body
|
||||
.contains("Review: https://daily.example/dashboard/users")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_access_post_is_rate_limited_per_ip() {
|
||||
let mut config = Config::default();
|
||||
config.server.login_attempts = 3;
|
||||
let (_dir, _db, app) = app_with_config(config).await;
|
||||
|
||||
for _ in 0..3 {
|
||||
let (status, _) = post(&app, "email=reader%40example.com&reason=&website=").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
let (status, _) = post(&app, "email=reader%40example.com&reason=&website=").await;
|
||||
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn honeypot_pretends_success_without_storing() {
|
||||
let (_dir, db, app) = app().await;
|
||||
|
||||
@@ -205,6 +205,14 @@ pub const RESTART_REQUIRED: &[&str] = &[
|
||||
"server.session_days",
|
||||
"server.login_attempts",
|
||||
"server.login_window_minutes",
|
||||
"mail.enabled",
|
||||
"mail.smtp_host",
|
||||
"mail.smtp_port",
|
||||
"mail.smtp_starttls",
|
||||
"mail.smtp_user",
|
||||
"mail.smtp_pass",
|
||||
"mail.from",
|
||||
"mail.notify_to",
|
||||
];
|
||||
|
||||
/// Optional keys that `Config::default()` leaves unset (and therefore do not
|
||||
@@ -219,10 +227,19 @@ const OPTIONAL_KEYS: &[(&str, FieldKind)] = &[
|
||||
("server.basic_auth_pass", FieldKind::Secret),
|
||||
("bookorbit.opds_user", FieldKind::Text),
|
||||
("bookorbit.opds_pass", FieldKind::Secret),
|
||||
("mail.smtp_user", FieldKind::Text),
|
||||
("mail.smtp_pass", FieldKind::Secret),
|
||||
("mail.notify_to", FieldKind::Text),
|
||||
("xtc.settings", FieldKind::Path),
|
||||
];
|
||||
|
||||
const SECRET_SUFFIXES: &[&str] = &["api_key", "hmac_secret", "basic_auth_pass", "opds_pass"];
|
||||
const SECRET_SUFFIXES: &[&str] = &[
|
||||
"api_key",
|
||||
"hmac_secret",
|
||||
"basic_auth_pass",
|
||||
"opds_pass",
|
||||
"smtp_pass",
|
||||
];
|
||||
|
||||
const PATH_KEYS: &[&str] = &[
|
||||
"database_path",
|
||||
@@ -259,6 +276,7 @@ const GROUP_ORDER: &[&str] = &[
|
||||
"server",
|
||||
"miniflux",
|
||||
"bookorbit",
|
||||
"mail",
|
||||
];
|
||||
|
||||
/// Help text per key, seeded from the README configuration table and the
|
||||
@@ -375,6 +393,14 @@ pub const SETTINGS_HELP: &[(&str, &str)] = &[
|
||||
("bookorbit.api_url", "Base URL used by the server for BookOrbit OPDS requests; usually the loopback address."),
|
||||
("bookorbit.opds_user", "Dedicated OPDS user created in BookOrbit Settings → OPDS."),
|
||||
("bookorbit.opds_pass", "Password for bookorbit.opds_user. Environment only."),
|
||||
("mail.enabled", "Enable outbound SMTP when the relay, sender and credentials are configured. Requires a server restart."),
|
||||
("mail.smtp_host", "SMTP relay hostname, such as an AWS SES SMTP endpoint. Requires a server restart."),
|
||||
("mail.smtp_port", "SMTP relay port: usually 587 for STARTTLS or 465 for implicit TLS. Requires a server restart."),
|
||||
("mail.smtp_starttls", "Use STARTTLS when true; false uses implicit TLS. Requires a server restart."),
|
||||
("mail.smtp_user", "SMTP username. Requires a server restart."),
|
||||
("mail.smtp_pass", "SMTP password. Environment only; requires a server restart."),
|
||||
("mail.from", "Sender mailbox as an address or Name <address>. Requires a server restart."),
|
||||
("mail.notify_to", "Recipient for new access-request notifications. Requires a server restart."),
|
||||
];
|
||||
|
||||
/// `DAILY_EPUB_` + the path upper-cased with `.` → `__` (§13.1 item 2).
|
||||
@@ -1664,6 +1690,9 @@ mod tests {
|
||||
"server.basic_auth_user",
|
||||
"bookorbit.opds_user",
|
||||
"bookorbit.opds_pass",
|
||||
"mail.smtp_user",
|
||||
"mail.smtp_pass",
|
||||
"mail.notify_to",
|
||||
] {
|
||||
field(&groups, path);
|
||||
}
|
||||
@@ -1695,6 +1724,7 @@ mod tests {
|
||||
"server",
|
||||
"miniflux",
|
||||
"bookorbit",
|
||||
"mail",
|
||||
]
|
||||
);
|
||||
let anthropic = groups
|
||||
@@ -1811,6 +1841,7 @@ mod tests {
|
||||
config.server.hmac_secret = Some("hunter2-hmac".into());
|
||||
config.server.basic_auth_pass = Some("hunter2-basic".into());
|
||||
config.bookorbit.opds_pass = Some("hunter2-bookorbit".into());
|
||||
config.mail.smtp_pass = Some("hunter2-smtp".into());
|
||||
if let Some(provider) = config.providers.get_mut("deepseek") {
|
||||
provider.api_key = Some("hunter2-deepseek".into());
|
||||
}
|
||||
@@ -1821,6 +1852,7 @@ mod tests {
|
||||
"server.hmac_secret",
|
||||
"server.basic_auth_pass",
|
||||
"bookorbit.opds_pass",
|
||||
"mail.smtp_pass",
|
||||
"providers.deepseek.api_key",
|
||||
"providers.anthropic.api_key",
|
||||
] {
|
||||
|
||||
+18
-2
@@ -659,7 +659,13 @@ pub fn router(config: &crate::config::Config) -> axum::Router<crate::server::App
|
||||
.route("/login", get(session::login_page))
|
||||
.route(
|
||||
"/login",
|
||||
post(session::login).route_layer(GovernorLayer::new(governor)),
|
||||
post(session::login).route_layer(GovernorLayer::new(governor.clone())),
|
||||
);
|
||||
let access_routes = axum::Router::new()
|
||||
.route("/request-access", get(access::page))
|
||||
.route(
|
||||
"/request-access",
|
||||
post(access::submit).route_layer(GovernorLayer::new(governor)),
|
||||
);
|
||||
let account = axum::Router::new()
|
||||
.route("/account", get(session::account))
|
||||
@@ -695,12 +701,12 @@ pub fn router(config: &crate::config::Config) -> axum::Router<crate::server::App
|
||||
|
||||
axum::Router::new()
|
||||
.route("/", get(public::latest))
|
||||
.route("/request-access", get(access::page).post(access::submit))
|
||||
.route("/issues", get(public::archive))
|
||||
.route("/issues/{date}", get(public::show_issue))
|
||||
.route("/feed.xml", get(public::feed))
|
||||
.route("/robots.txt", get(public::robots))
|
||||
.route("/static/{file}", get(static_asset))
|
||||
.merge(access_routes)
|
||||
.merge(login)
|
||||
.merge(account)
|
||||
.merge(full_issues)
|
||||
@@ -1336,6 +1342,16 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
let shared = app
|
||||
.clone()
|
||||
.oneshot(post(
|
||||
"/request-access",
|
||||
"email=reader%40example.com&reason=&website=",
|
||||
"192.0.2.20",
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(shared.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
let other = app
|
||||
.oneshot(post(
|
||||
"/login",
|
||||
|
||||
Reference in New Issue
Block a user