Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ axum = "0.8.9"
chacha20poly1305 = "0.11.0"
chrono = "0.4.45"
hex = "0.4.3"
hmac = "0.13.0"
imap = "2"
imap-proto = "0.10"
libsql = { version = "0.9.30", default-features = false, features = ["core"] }
Expand Down
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ the accumulated damage of clients that disagree about dates and folder names.

## Self-hosting (Docker)

Requirements: Docker (or Podman) with compose, and an always-on box. mailgrep
has **no authentication**; the network is the trust boundary. Run it on a
private network (Tailscale, WireGuard, LAN) and never expose it publicly.
Requirements: Docker (or Podman) with compose, and an always-on box. Set
`MAILGREP_PASSWORD` to require a login; without it, the network is the only
trust boundary. Either way, run it on a private network (Tailscale, WireGuard,
LAN) and never expose it publicly: a single shared password is a second lock,
not a public-internet login.

```sh
mkdir mailgrep && cd mailgrep
Expand All @@ -51,6 +53,8 @@ curl -O https://raw.githubusercontent.com/samvdst/mailgrep/main/docker-compose.y
# The key that encrypts your IMAP credentials at rest. Generate once and keep it:
# losing it means re-entering your accounts.
echo "MAILGREP_KEY=$(openssl rand -hex 32)" > .env
# The login password (optional; omit to run without a login).
echo "MAILGREP_PASSWORD=$(openssl rand -base64 18)" >> .env

docker compose up -d # pulls ghcr.io/samvdst/mailgrep
```
Expand Down Expand Up @@ -127,6 +131,7 @@ rather than pretending to a unified relevance.
| Env var | Default | Purpose |
|---|---|---|
| `MAILGREP_KEY` | - | 64 hex chars; encrypts IMAP credentials at rest (required to add accounts) |
| `MAILGREP_PASSWORD` | - | login password; unset means no login. Sessions last 30 days; changing it (or `MAILGREP_KEY`) signs everyone out |
| `MAILGREP_DATA` | `/data` (image) | state directory |
| `MAILGREP_BIND` | `0.0.0.0:8025` | listen address |
| `MAILGREP_WEB` | `/app/web/dist` | SPA assets |
Expand Down Expand Up @@ -175,7 +180,7 @@ regenerates them and CI rejects stale bindings.

No IMAP writes (skewed dates are flagged, never "repaired"), no OCR or
attachment content indexing (use something like Paperless-ngx for that), no
LLM query parsing, no auth (private network only), no real-time IDLE sync.
LLM query parsing, no user accounts (one shared password at most), no real-time IDLE sync.
Semantic search is designed for as a future separate mode: the tables exist,
nothing is generated yet.

Expand Down
8 changes: 5 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@ security problems before a fix is released.
## Design notes relevant to security

- mailgrep is **read-only against IMAP**: it never writes to your mailbox.
- v1 ships **without authentication**: the network is the trust boundary.
Run it only on a private network (Tailscale, WireGuard, LAN). Do not
expose it to the public internet.
- Authentication is a single optional password (`MAILGREP_PASSWORD`); the
session is a stateless HMAC-signed `HttpOnly`, `SameSite=Strict` cookie.
Without it, the network is the only trust boundary. Either way, run it only
on a private network (Tailscale, WireGuard, LAN). Do not expose it to the
public internet.
- IMAP credentials are encrypted at rest (XChaCha20-Poly1305) with a key
supplied via `MAILGREP_KEY`, never stored beside the ciphertext.
- Message HTML is sanitised server-side (ammonia) and rendered in a
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ services:
# 64 hex chars; encrypts IMAP credentials at rest. Generate with:
# openssl rand -hex 32
MAILGREP_KEY: "${MAILGREP_KEY:?set MAILGREP_KEY in .env}"
# login password; leave unset to run without a login
MAILGREP_PASSWORD: "${MAILGREP_PASSWORD:-}"
volumes:
- mailgrep-data:/data

Expand Down
93 changes: 89 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
//! JSON HTTP API. One screen, everything is a query.

use crate::api_types::*;
use crate::auth::{self, Auth};
use crate::crypto::Crypto;
use crate::index::{Indexes, SearchOptions};
use crate::queryparse::{Clause, FilterField};
use crate::source::{FixtureSource, MailSource};
use crate::store::{Account, Store};
use crate::sync::ProgressMap;
use anyhow::{Context, Result};
use axum::extract::{Path, Query, State};
use axum::http::{StatusCode, header};
use axum::extract::{Path, Query, Request, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{Json, Router};
Expand All @@ -21,6 +23,8 @@ pub struct App {
pub store: Store,
pub indexes: Indexes,
pub crypto: Option<Crypto>,
/// `None` when no MAILGREP_PASSWORD is configured.
pub auth: Option<Auth>,
pub progress: ProgressMap,
}

Expand Down Expand Up @@ -75,7 +79,11 @@ pub fn make_source(account: &Account, crypto: &Option<Crypto>) -> Result<Box<dyn
// ---------- router ----------

pub fn router(app: SharedApp) -> Router {
Router::new()
let public = Router::new()
.route("/api/auth", get(auth_status))
.route("/api/login", post(login))
.route("/api/logout", post(logout));
let protected = Router::new()
.route("/api/status", get(status))
.route("/api/accounts", get(list_accounts).post(add_account))
.route("/api/accounts/{id}", delete(remove_account))
Expand Down Expand Up @@ -104,7 +112,84 @@ pub fn router(app: SharedApp) -> Router {
.route("/api/merge", post(merge))
.route("/api/unmerge", post(unmerge))
.route("/api/merges", get(merges))
.with_state(app)
.route_layer(middleware::from_fn_with_state(app.clone(), require_session));
public.merge(protected).with_state(app)
}

// ---------- auth ----------

fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}

fn session_cookie(headers: &HeaderMap) -> Option<&str> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(';'))
.find_map(|c| c.trim().strip_prefix(auth::COOKIE)?.strip_prefix('='))
}

fn authenticated(app: &App, headers: &HeaderMap) -> bool {
match &app.auth {
None => true,
Some(auth) => session_cookie(headers).is_some_and(|t| auth.verify(t, now_secs())),
}
}

async fn require_session(State(app): State<SharedApp>, request: Request, next: Next) -> Response {
if authenticated(&app, request.headers()) {
next.run(request).await
} else {
ApiError(StatusCode::UNAUTHORIZED, "login required".into()).into_response()
}
}

/// Set-Cookie value; `Secure` when the request came in over HTTPS via a proxy,
/// so plain-HTTP access on a LAN still works.
fn set_cookie(headers: &HeaderMap, value: &str, max_age: i64) -> String {
let https = headers
.get("x-forwarded-proto")
.is_some_and(|v| v.as_bytes().eq_ignore_ascii_case(b"https"));
format!(
"{}={value}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Strict{}",
auth::COOKIE,
if https { "; Secure" } else { "" }
)
}

async fn auth_status(State(app): State<SharedApp>, headers: HeaderMap) -> Json<AuthStatus> {
Json(AuthStatus {
required: app.auth.is_some(),
authenticated: authenticated(&app, &headers),
})
}

async fn login(
State(app): State<SharedApp>,
headers: HeaderMap,
Json(body): Json<LoginBody>,
) -> ApiResult<Response> {
let Some(auth) = &app.auth else {
return Ok(Json(OkResponse { ok: true }).into_response());
};
let _serialised = auth.attempts.lock().await;
if !auth.check_password(&body.password) {
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
tracing::warn!("failed login attempt");
return Err(ApiError(StatusCode::UNAUTHORIZED, "wrong password".into()));
}
let cookie = set_cookie(&headers, &auth.issue(now_secs()), auth::SESSION_SECS);
Ok(([(header::SET_COOKIE, cookie)], Json(OkResponse { ok: true })).into_response())
}

async fn logout(headers: HeaderMap) -> Response {
let cookie = set_cookie(&headers, "", 0);
([(header::SET_COOKIE, cookie)], Json(OkResponse { ok: true })).into_response()
}

// ---------- status ----------
Expand Down
13 changes: 13 additions & 0 deletions src/api_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ pub struct ErrorResponse {
pub error: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct AuthStatus {
pub required: bool,
pub authenticated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct LoginBody {
pub password: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export)]
pub struct StatusResponse {
Expand Down
96 changes: 96 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
//! Optional single-password login (MAILGREP_PASSWORD). Sessions are
//! stateless signed cookies, `<expiry>.<hmac>`, keyed on the password and
//! MAILGREP_KEY: changing either signs everyone out.

use hmac::{Hmac, KeyInit, Mac};
use sha2::{Digest, Sha256};

pub const COOKIE: &str = "mailgrep_session";
pub const SESSION_SECS: i64 = 30 * 24 * 3600;

pub struct Auth {
key: [u8; 32],
password_mac: Vec<u8>,
/// Held across failed attempts so guessing is serialised and slowed.
pub attempts: tokio::sync::Mutex<()>,
}

impl Auth {
/// `None` when MAILGREP_PASSWORD is unset or empty: no login required.
pub fn from_env() -> Option<Self> {
let password = std::env::var("MAILGREP_PASSWORD").ok().filter(|p| !p.is_empty())?;
let secret = std::env::var("MAILGREP_KEY").unwrap_or_default();
Some(Self::new(&password, secret.as_bytes()))
}

pub fn new(password: &str, secret: &[u8]) -> Self {
let mut hasher = Sha256::new();
hasher.update(b"mailgrep-session\0");
hasher.update(secret);
hasher.update(b"\0");
hasher.update(password.as_bytes());
let key: [u8; 32] = hasher.finalize().into();
let mut auth = Self {
key,
password_mac: Vec::new(),
attempts: Default::default(),
};
auth.password_mac = auth.mac(b"password", password.as_bytes()).finalize().into_bytes().to_vec();
auth
}

fn mac(&self, domain: &[u8], data: &[u8]) -> Hmac<Sha256> {
let mut mac = Hmac::<Sha256>::new_from_slice(&self.key).expect("hmac takes any key length");
mac.update(domain);
mac.update(b"\0");
mac.update(data);
mac
}

/// Constant-time password check.
pub fn check_password(&self, candidate: &str) -> bool {
self.mac(b"password", candidate.as_bytes())
.verify_slice(&self.password_mac)
.is_ok()
}

pub fn issue(&self, now: i64) -> String {
let expiry = (now + SESSION_SECS).to_string();
let sig = self.mac(b"session", expiry.as_bytes()).finalize().into_bytes();
format!("{expiry}.{}", hex::encode(sig))
}

pub fn verify(&self, token: &str, now: i64) -> bool {
let Some((expiry, sig)) = token.split_once('.') else {
return false;
};
let (Ok(exp), Ok(sig)) = (expiry.parse::<i64>(), hex::decode(sig)) else {
return false;
};
exp > now && self.mac(b"session", expiry.as_bytes()).verify_slice(&sig).is_ok()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn password_and_sessions() {
let auth = Auth::new("hunter2", b"key");
assert!(auth.check_password("hunter2"));
assert!(!auth.check_password("hunter3"));
assert!(!auth.check_password(""));

let token = auth.issue(1_000);
assert!(auth.verify(&token, 1_000));
assert!(!auth.verify(&token, 1_000 + SESSION_SECS));
assert!(!auth.verify(&token.replace('.', ".0"), 1_000));
assert!(!auth.verify("garbage", 1_000));

let (_, sig) = token.split_once('.').unwrap();
assert!(!auth.verify(&format!("{}.{sig}", 1_000 + 10 * SESSION_SECS), 1_000));
assert!(!Auth::new("other", b"key").verify(&token, 1_000));
assert!(!Auth::new("hunter2", b"other").verify(&token, 1_000));
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod api;
pub mod api_types;
pub mod auth;
pub mod config;
pub mod crypto;
pub mod imapsource;
Expand Down
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use mailgrep::{api, crypto, index, store};
use mailgrep::{api, auth, crypto, index, store};
use axum::Router;
use std::path::PathBuf;
use std::sync::Arc;
Expand Down Expand Up @@ -29,10 +29,16 @@ async fn main() -> Result<()> {
}
};

let auth = auth::Auth::from_env();
if auth.is_none() {
tracing::warn!("MAILGREP_PASSWORD not set: no login required, the network is the only protection");
}

let app = Arc::new(api::App {
store,
indexes,
crypto,
auth,
progress: Default::default(),
});

Expand Down
Loading
Loading