chadtmiller.com/monolith
An atproto PDS
0
0
//! The account's email: confirming it, changing it, resetting the password
//! by it, and the sign-in code: `requestEmailConfirmation`, `confirmEmail`,
//! `requestEmailUpdate`, `updateEmail`, `requestPasswordReset`,
//! `resetPassword`, and `createSession`'s `authFactorToken`, with the tokens
//! mailed for each and the mailer that sends them, as `spec/EMAIL.md` says.
//!
//! An account's email, password, whether its email is confirmed, its email
//! factor and its tokens are its `Mail`, behind a lock of its own. Each
//! change to them is an entry in `accounts.log` (`ENTRIES`), appended under
//! that lock, so that the log has an account's changes in the order they
//! were made. A change that also starts or ends sessions goes in one frame
//! with theirs. The lock is taken before the directory's, and before the
//! account's sessions'.
use crate::server::{password, password_length, valid_email};
use crate::sessions::{self, Token};
use crate::{
Account, Handler, Resp, Service, Shared, XrpcError, durable, err, internal, invalid,
invalid_token, opt, required, write,
};
use lettre::message::{Mailbox, Message, MultiPart};
use lettre::transport::smtp::authentication::Credentials;
use lettre::transport::smtp::client::{Tls, TlsParameters};
use lettre::{AsyncSmtpTransport, AsyncTransport, Tokio1Executor};
use serde_json::{Map, Value as Json, json};
use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{SystemTime, UNIX_EPOCH};
/// The kinds of `accounts.log` entry this module keeps, each naming its account by `did`.
pub(crate) const ENTRIES: &[&str] = &[
"mailToken",
"useToken",
"confirmEmail",
"emailAuthFactor",
"updateEmail",
"password",
];
/// How long a token works, in seconds, from when it was made.
const LIFE: u64 = 15 * 60;
/// What a token is for. Each is mailed as one kind of email.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) enum Purpose {
ConfirmEmail,
UpdateEmail,
ResetPassword,
AuthFactor,
/// `requestAccountDelete`'s (`spec/LIFECYCLE.md`).
DeleteAccount,
/// `requestPlcOperationSignature`'s (`spec/MIGRATION.md`).
PlcOperation,
}
impl Purpose {
const ALL: [Purpose; 6] = [
Purpose::ConfirmEmail,
Purpose::UpdateEmail,
Purpose::ResetPassword,
Purpose::AuthFactor,
Purpose::DeleteAccount,
Purpose::PlcOperation,
];
/// Its name, as the log has it.
pub fn name(self) -> &'static str {
match self {
Purpose::ConfirmEmail => "confirm_email",
Purpose::UpdateEmail => "update_email",
Purpose::ResetPassword => "reset_password",
Purpose::AuthFactor => "auth_factor",
Purpose::DeleteAccount => "delete_account",
Purpose::PlcOperation => "plc_operation",
}
}
fn of(name: &str) -> Option<Purpose> {
Purpose::ALL.into_iter().find(|p| p.name() == name)
}
/// The kind of email its token is mailed in.
pub fn kind(self) -> &'static str {
match self {
Purpose::ConfirmEmail => "confirmEmail",
Purpose::UpdateEmail => "updateEmail",
Purpose::ResetPassword => "resetPassword",
Purpose::AuthFactor => "signInAuthFactor",
Purpose::DeleteAccount => "deleteAccount",
Purpose::PlcOperation => "plcOperation",
}
}
fn subject(self) -> &'static str {
match self {
Purpose::ConfirmEmail => "Email Confirmation",
Purpose::UpdateEmail => "Email Update Requested",
Purpose::ResetPassword => "Password Reset Requested",
Purpose::AuthFactor => "Sign-in Confirmation",
Purpose::DeleteAccount => "Account Deletion Requested",
Purpose::PlcOperation => "PLC Update Operation Requested",
}
}
/// What the email asks of its reader, before the token.
fn lead(self) -> &'static str {
match self {
Purpose::ConfirmEmail => {
"To confirm this email address for your account, enter this code"
}
Purpose::UpdateEmail => "To change the email address of your account, enter this code",
Purpose::ResetPassword => "To reset the password of your account, enter this code",
Purpose::AuthFactor => "To sign in to your account, enter this code",
Purpose::DeleteAccount => "To delete your account, enter this code",
Purpose::PlcOperation => {
"To sign an operation that changes your account's DID document, enter this code"
}
}
}
/// Its email's heading in the HTML part (`spec/EMAIL.md`, "The message").
fn heading(self) -> &'static str {
match self {
Purpose::ConfirmEmail => "Confirm your email",
Purpose::UpdateEmail => "Change your email",
Purpose::ResetPassword => "Reset your password",
Purpose::AuthFactor => "Your sign-in code",
Purpose::DeleteAccount => "Delete your account",
Purpose::PlcOperation => "Confirm a change to your account",
}
}
/// The text part.
fn body(self, token: &str) -> String {
format!("{}:\n\n {token}\n\n{NOTE}\n", self.lead())
}
/// The HTML part: `web/`'s template, filled in, each value escaped.
fn html(self, host: &str, token: &str) -> String {
let lead = format!("{}.", self.lead());
[
("{{host}}", host),
("{{heading}}", self.heading()),
("{{lead}}", &lead),
("{{code}}", token),
("{{note}}", NOTE),
]
.into_iter()
.fold(TEMPLATE.to_string(), |html, (slot, value)| {
html.replace(slot, &escape(value))
})
}
}
include!(concat!(env!("OUT_DIR"), "/email.rs"));
/// What each email says of its token, after it.
const NOTE: &str = "It works for 15 minutes, once. If you did not ask for it, ignore this email.";
/// `s` as HTML text.
fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
c => out.push(c),
}
}
out
}
/// A token, as kept.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Issued {
/// In upper case, as made.
token: String,
/// When it was made, in seconds since the epoch.
made: u64,
}
/// An account's email and password, and what is known of the email.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Mail {
/// In lower case; an account without a password keeps none.
pub email: Option<String>,
/// Its password's hash; an account without one cannot log in with it.
pub password: Option<String>,
pub confirmed: bool,
/// Whether signing in with the password also needs a code mailed to the email.
pub auth_factor: bool,
/// At most one token of each purpose.
tokens: BTreeMap<Purpose, Issued>,
}
pub(crate) fn lock(m: &Mutex<Mail>) -> MutexGuard<'_, Mail> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
impl Mail {
/// An account's as it is made: its email unconfirmed, with no factor and no tokens.
pub fn new(email: Option<String>, password: Option<String>) -> Mail {
Mail {
email,
password,
confirmed: false,
auth_factor: false,
tokens: BTreeMap::new(),
}
}
fn token(&self, p: Purpose) -> Option<&str> {
self.tokens.get(&p).map(|i| i.token.as_str())
}
/// Its password reset token, if it has one.
pub(crate) fn reset_token(&self) -> Option<&str> {
self.token(Purpose::ResetPassword)
}
/// Whether `given` is the account's token of `p`: `InvalidToken` if it is
/// not, in any case, then `ExpiredToken` if it is past its 15 minutes at `now`.
pub fn check(&self, p: Purpose, given: &str, now: u64) -> Result<(), XrpcError> {
let Some(i) = self
.tokens
.get(&p)
.filter(|i| i.token == given.to_ascii_uppercase())
else {
return invalid_token();
};
if now >= i.made + LIFE {
return sessions::expired();
}
Ok(())
}
/// Make the change an entry says, as it is logged and as it is replayed.
pub(crate) fn apply(&mut self, e: &Json) -> Result<(), String> {
let text = |k: &str| {
e[k].as_str()
.ok_or_else(|| format!("an entry with no {k}: {e}"))
};
let purpose = || {
text("purpose").and_then(|p| {
Purpose::of(p).ok_or_else(|| format!("a token of no known purpose: {e}"))
})
};
let no_email = || format!("a change to the email of an account that keeps none: {e}");
match e["t"].as_str() {
Some("mailToken") => {
let (p, token) = (purpose()?, text("token")?);
let Some(made) = e["made"].as_u64() else {
return Err(format!("a token with no made: {e}"));
};
if !is_token(token) {
return Err(format!("a token not of the form: {e}"));
}
if self.email.is_none() {
return Err(no_email());
}
self.tokens.insert(
p,
Issued {
token: token.to_string(),
made,
},
);
}
Some("useToken") => {
let p = purpose()?;
if self.tokens.remove(&p).is_none() {
return Err(format!("a token used that the account does not have: {e}"));
}
}
Some("confirmEmail") => {
if self.email.is_none() {
return Err(no_email());
}
self.confirmed = true;
}
Some("emailAuthFactor") => {
let Some(on) = e["on"].as_bool() else {
return Err(format!("an email factor with no on: {e}"));
};
if on && !self.confirmed {
return Err(format!(
"the email factor turned on for an email not confirmed: {e}"
));
}
self.auth_factor = on;
}
Some("updateEmail") => {
let email = text("email")?;
if self.email.is_none() {
return Err(no_email());
}
self.email = Some(email.to_string());
self.confirmed = false;
self.auth_factor = false;
self.tokens.clear();
}
Some("password") => {
let hash = text("password")?;
if self.password.is_none() {
return Err(format!("a password set for an account without one: {e}"));
}
self.password = Some(hash.to_string());
}
t => return Err(format!("a log entry of no known type: {t:?}")),
}
Ok(())
}
/// The entries that make this mail again, after its account's entry,
/// which has its email and password, for a compacted log.
pub(crate) fn entries(&self, did: &str) -> Vec<Json> {
let confirmed = self
.confirmed
.then(|| json!({ "t": "confirmEmail", "did": did }));
let factor = self.auth_factor.then(|| factor_entry(did, true));
let tokens = self.tokens.iter().map(|(p, i)| json!({ "t": "mailToken", "did": did, "purpose": p.name(), "token": i.token, "made": i.made }));
confirmed.into_iter().chain(factor).chain(tokens).collect()
}
}
/// Which account, of those loaded, each password reset token is of, as
/// `resetPassword` is given the token alone. It holds each one's current
/// one; an account not loaded is found by the hints (`directory`).
#[derive(Default)]
pub(crate) struct Resets(Mutex<HashMap<String, String>>);
impl Resets {
fn lock(&self) -> MutexGuard<'_, HashMap<String, String>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Note the reset token of an account loaded, if it has one.
pub fn note(&self, did: &str, m: &Mail) {
if let Some(t) = m.token(Purpose::ResetPassword) {
self.lock().insert(t.to_string(), did.to_string());
}
}
/// The account, of those loaded, whose reset token this is.
pub fn of(&self, token: &str) -> Option<String> {
self.lock().get(token).cloned()
}
/// Forget a deleted account's token.
pub fn forget(&self, did: &str) {
self.lock().retain(|_, d| d != did);
}
#[cfg(test)]
pub fn snapshot(&self) -> BTreeMap<String, String> {
self.lock()
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
}
/// Make the changes `entries` say to an account's mail, under its lock, as
/// they are logged: once the frame of `change`'s, or one of the sessions'
/// with them, is written.
pub(crate) fn apply(s: &Service, did: &str, m: &mut Mail, entries: &[Json]) {
let before = m.token(Purpose::ResetPassword).map(str::to_string);
for e in entries {
m.apply(e)
.unwrap_or_else(|why| panic!("a change made under its account's lock: {why}"));
}
let after = m.token(Purpose::ResetPassword);
if before.as_deref() != after {
let mut r = s.resets.lock();
if let Some(b) = before {
r.remove(&b);
}
if let Some(a) = after {
r.insert(a.to_string(), did.to_string());
}
}
}
/// A change that could not be logged, as it is answered: nothing of it is made.
pub(crate) fn not_logged<T>(e: std::io::Error) -> Result<T, XrpcError> {
crate::ops::failed("writing accounts.log failed", e);
internal()
}
/// Log the changes `entries` say in one frame, then make them. Answers the frame.
pub(crate) fn change(
s: &Service,
did: &str,
m: &mut Mail,
entries: &[Json],
) -> Result<u64, XrpcError> {
let n = s.log.append(entries).or_else(not_logged)?;
apply(s, did, m, entries);
Ok(n)
}
/// The entry that uses up an account's token of `p`.
pub(crate) fn use_entry(did: &str, p: Purpose) -> Json {
json!({ "t": "useToken", "did": did, "purpose": p.name() })
}
fn factor_entry(did: &str, on: bool) -> Json {
json!({ "t": "emailAuthFactor", "did": did, "on": on })
}
/// The base32 alphabet of RFC 4648.
const BASE32: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// A new token: two groups of five base32 characters, 50 random bits.
fn new_token() -> String {
let c: Vec<char> = rand::random::<[u8; 10]>()
.iter()
.map(|b| char::from(BASE32[usize::from(b & 31)]))
.collect();
format!(
"{}-{}",
c[..5].iter().collect::<String>(),
c[5..].iter().collect::<String>()
)
}
fn is_token(t: &str) -> bool {
let b = t.as_bytes();
b.len() == 11
&& b[5] == b'-'
&& b.iter()
.enumerate()
.all(|(i, c)| i == 5 || BASE32.contains(c))
}
/// An email to send: a token kept, once its frame is on disk.
pub(crate) struct Outgoing {
frame: u64,
to: String,
purpose: Purpose,
token: String,
}
/// Make the account's token of `p`, in place of any before it, under its
/// lock, and log it. An account without an email is refused, as
/// `InvalidRequest`: none of the methods asks for one.
pub(crate) fn make(
s: &Service,
did: &str,
m: &mut Mail,
p: Purpose,
) -> Result<Outgoing, XrpcError> {
let Some(to) = m.email.clone() else {
return no_email();
};
let token = new_token();
let frame = change(
s,
did,
m,
&[
json!({ "t": "mailToken", "did": did, "purpose": p.name(), "token": token, "made": s.sessions.now() }),
],
)?;
Ok(Outgoing {
frame,
to,
purpose: p,
token,
})
}
/// Send a token once it is kept: a failure to send it is `500`, and the token works all the same.
pub(crate) async fn deliver(s: &Shared, out: Outgoing) -> Result<(), XrpcError> {
durable(s.log.clone(), out.frame).await?;
if let Err(why) = s.config.mailer.send(&out.to, out.purpose, &out.token).await {
// Nothing the mail holds is logged: neither its address nor its token.
let why = why
.to_string()
.replace(&out.to, "<address>")
.replace(&out.token, "<token>");
crate::ops::error(
"mailing failed",
&[
("purpose", serde_json::json!(out.purpose.kind())),
("error", serde_json::json!(why)),
],
);
return internal();
}
Ok(())
}
/// Where every email goes: an SMTP server, the development sink, both, or neither.
#[derive(Default)]
pub(crate) struct Mailer {
smtp: Option<Smtp>,
sink: Option<Arc<Sink>>,
}
struct Smtp {
transport: AsyncSmtpTransport<Tokio1Executor>,
from: Mailbox,
/// `PDS_HOSTNAME`, which the HTML part names.
host: String,
}
/// A directory each email is also written to, each in a file whose name sorts after every earlier one's.
struct Sink {
dir: PathBuf,
/// The time and counter of the last name given.
last: Mutex<(u64, u64)>,
}
impl Sink {
fn write(&self, content: &[u8]) -> std::io::Result<()> {
// The name is given, and the file put in place, under the lock, so that
// no file appears after one whose name sorts later.
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let now = u64::try_from(now).unwrap_or(u64::MAX).max(last.0);
*last = (now, last.1 + 1);
let name = format!("{now:020}-{:020}", last.1);
let tmp = self.dir.join(format!(".{name}.json"));
let mut f = std::fs::File::create(&tmp)?;
f.write_all(content)?;
drop(f);
std::fs::rename(&tmp, self.dir.join(format!("{name}.json")))
}
}
impl Mailer {
/// The mailer the environment configures: `PDS_EMAIL_SMTP_URL` and
/// `PDS_EMAIL_FROM`, both or neither, and `PDS_DEV_MAIL_DIR`.
pub fn from_env() -> Result<Mailer, String> {
Mailer::from_vars(|n| std::env::var(n).ok().filter(|v| !v.is_empty()))
}
fn from_vars(var: impl Fn(&str) -> Option<String>) -> Result<Mailer, String> {
let smtp = match (var("PDS_EMAIL_SMTP_URL"), var("PDS_EMAIL_FROM")) {
(Some(url), Some(from)) => Some(Smtp::new(
&url,
&from,
var("PDS_HOSTNAME").unwrap_or_default(),
)?),
(None, None) => None,
(Some(_), None) => {
return Err("PDS_EMAIL_SMTP_URL is set without PDS_EMAIL_FROM".into());
}
(None, Some(_)) => {
return Err("PDS_EMAIL_FROM is set without PDS_EMAIL_SMTP_URL".into());
}
};
let sink = var("PDS_DEV_MAIL_DIR").map(|dir| {
Arc::new(Sink {
dir: dir.into(),
last: Mutex::default(),
})
});
Ok(Mailer { smtp, sink })
}
/// A mailer that writes each email to `dir`, and sends none.
#[cfg(test)]
pub fn sink(dir: &std::path::Path) -> Mailer {
Mailer {
smtp: None,
sink: Some(Arc::new(Sink {
dir: dir.to_path_buf(),
last: Mutex::default(),
})),
}
}
/// Send `token` to `to` in the kind of email `p`'s tokens go in: written
/// to the sink first, if there is one, then sent by SMTP, if configured.
pub async fn send(&self, to: &str, p: Purpose, token: &str) -> Result<(), String> {
if let Some(sink) = &self.sink {
let (sink, content) = (
sink.clone(),
json!({ "to": to, "kind": p.kind(), "token": token }).to_string(),
);
let written = tokio::task::spawn_blocking(move || sink.write(content.as_bytes()))
.await
.map_err(|e| e.to_string())?;
written.map_err(|e| format!("writing to PDS_DEV_MAIL_DIR: {e}"))?;
}
if let Some(smtp) = &self.smtp {
smtp.send(to, p, token).await?;
}
Ok(())
}
}
impl Smtp {
/// An SMTP server by its URL, `smtp://[user:password@]host[:port]`,
/// upgraded with STARTTLS when it offers it, or `smtps://...`, TLS from
/// the start; the address each email is from; and the server's host.
fn new(url: &str, from: &str, hostname: String) -> Result<Smtp, String> {
let bad = |why: &str| format!("PDS_EMAIL_SMTP_URL {why}");
let u = reqwest::Url::parse(url).map_err(|e| bad(&format!("is not a URL: {e}")))?;
let wrapper = match u.scheme() {
"smtp" => false,
"smtps" => true,
_ => return Err(bad("is neither smtp:// nor smtps://")),
};
let host = u
.host_str()
.filter(|h| !h.is_empty())
.ok_or_else(|| bad("names no host"))?;
let host = host
.trim_start_matches('[')
.trim_end_matches(']')
.to_string();
let tls = TlsParameters::new(host.clone())
.map_err(|e| bad(&format!("names a host TLS cannot check: {e}")))?;
let decode = |s: &str| {
percent_encoding::percent_decode_str(s)
.decode_utf8()
.map(|s| s.into_owned())
.map_err(|_| bad("has credentials that are not UTF-8"))
};
let mut builder = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(host)
.port(u.port().unwrap_or(if wrapper { 465 } else { 25 }))
.tls(if wrapper {
Tls::Wrapper(tls)
} else {
Tls::Opportunistic(tls)
});
if !u.username().is_empty() {
builder = builder.credentials(Credentials::new(
decode(u.username())?,
decode(u.password().unwrap_or_default())?,
));
}
let from = from
.parse::<Mailbox>()
.map_err(|e| format!("PDS_EMAIL_FROM is not an address: {e}"))?;
Ok(Smtp {
transport: builder.build(),
from,
host: hostname,
})
}
async fn send(&self, to: &str, p: Purpose, token: &str) -> Result<(), String> {
let to = to
.parse::<Mailbox>()
.map_err(|e| format!("not an address SMTP takes: {e}"))?;
let message = Message::builder()
.from(self.from.clone())
.to(to)
.subject(p.subject())
.multipart(MultiPart::alternative_plain_html(
p.body(token),
p.html(&self.host, token),
))
.map_err(|e| e.to_string())?;
self.transport
.send(message)
.await
.map(drop)
.map_err(|e| e.to_string())
}
}
pub(crate) fn handler(nsid: &str) -> Option<Handler> {
Some(match nsid {
"com.atproto.server.requestEmailConfirmation" => {
Handler::Authed(sessions::access_token, |s, t, _| {
Box::pin(request_email_confirmation(s, t))
})
}
"com.atproto.server.confirmEmail" => Handler::Authed(sessions::access_token, |s, t, b| {
Box::pin(confirm_email(s, t, b))
}),
"com.atproto.server.requestEmailUpdate" => {
Handler::Authed(sessions::full_access_token, |s, t, _| {
Box::pin(request_email_update(s, t))
})
}
"com.atproto.server.updateEmail" => {
Handler::Authed(sessions::full_access_token, |s, t, b| {
Box::pin(update_email(s, t, b))
})
}
"com.atproto.server.requestPasswordReset" => {
Handler::Procedure(|s, b| Box::pin(request_password_reset(s, b)))
}
"com.atproto.server.resetPassword" => {
Handler::Procedure(|s, b| Box::pin(reset_password(s, b)))
}
_ => return None,
})
}
/// The account a token is of.
fn account(s: &Service, t: &Token) -> Result<Arc<Account>, XrpcError> {
s.account(&t.did).map_or_else(invalid_token, Ok)
}
fn no_email<T>() -> Result<T, XrpcError> {
invalid("Account does not have an email address")
}
async fn request_email_confirmation(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let a = account(&s, &t)?;
let out = {
let mut m = lock(&a.mail);
if m.email.is_none() {
return no_email();
}
make(&s, &a.did, &mut m, Purpose::ConfirmEmail)?
};
deliver(&s, out).await?;
Ok(Resp::Nothing)
}
async fn confirm_email(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let (email, token) = (
required(&b, "email")?.to_lowercase(),
required(&b, "token")?,
);
let a = account(&s, &t)?;
let now = s.sessions.now();
let n = {
let mut m = lock(&a.mail);
if m.email.as_deref() != Some(email.as_str()) {
return err(400, "InvalidEmail", "Invalid email");
}
m.check(Purpose::ConfirmEmail, token, now)?;
change(
&s,
&a.did,
&mut m,
&[
json!({ "t": "confirmEmail", "did": a.did }),
use_entry(&a.did, Purpose::ConfirmEmail),
],
)?
};
durable(s.log.clone(), n).await?;
Ok(Resp::Nothing)
}
async fn request_email_update(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let a = account(&s, &t)?;
let out = {
let mut m = lock(&a.mail);
if m.email.is_none() {
return no_email();
}
if !m.confirmed {
return Ok(Resp::Json(json!({ "tokenRequired": false })));
}
make(&s, &a.did, &mut m, Purpose::UpdateEmail)?
};
deliver(&s, out).await?;
Ok(Resp::Json(json!({ "tokenRequired": true })))
}
fn token_required<T>() -> Result<T, XrpcError> {
err(400, "TokenRequired", "Confirmation token required")
}
async fn update_email(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let email = required(&b, "email")?.to_lowercase();
let factor = b.get("emailAuthFactor").and_then(Json::as_bool);
// The empty token is none.
let token = opt(&b, "token").filter(|t| !t.is_empty());
let a = account(&s, &t)?;
let did = a.did.as_str();
let now = s.sessions.now();
// The frame to wait for, or a token to mail before asking for it.
let next: Result<u64, Outgoing> = {
let mut m = lock(&a.mail);
let same = m.email.as_deref() == Some(email.as_str());
if factor == Some(true) {
// Turning the factor on: the email does not change, and the token is not looked at.
if !(same && m.confirmed) {
return invalid("Email must be confirmed to turn on the email factor");
}
Ok(if m.auth_factor {
s.log.written()
} else {
change(&s, did, &mut m, &[factor_entry(did, true)])?
})
} else if factor == Some(false) && same {
// Turning it off takes a token mailed to the email.
if !m.auth_factor {
Ok(s.log.written())
} else if let Some(token) = token {
m.check(Purpose::UpdateEmail, token, now)?;
Ok(change(
&s,
did,
&mut m,
&[
use_entry(did, Purpose::UpdateEmail),
factor_entry(did, false),
],
)?)
} else {
Err(make(&s, did, &mut m, Purpose::UpdateEmail)?)
}
} else {
// Changing the email.
if !valid_email(&email) {
return invalid(
"This email address is not supported, please use a different email.",
);
}
match token {
Some(token) => m.check(Purpose::UpdateEmail, token, now)?,
None if m.confirmed => return token_required(),
None => {}
}
// An account without a password keeps no email, whatever it asks for.
let Some(old) = m.email.clone() else {
return Ok(Resp::Nothing);
};
// An account not loaded that may have the email is loaded
// first: then those loaded say whether it is taken.
s.load_hinted(crate::compact::EMAIL, &email);
let mut d = write(&s.directory);
if d.emails.get(&email).is_some_and(|other| other != did)
|| d.claimed_emails.contains(&email)
{
return invalid(
"This email address is already in use, please use a different email.",
);
}
let n = change(
&s,
did,
&mut m,
&[json!({ "t": "updateEmail", "did": did, "email": email })],
)?;
d.emails.remove(&old);
d.emails.insert(email.clone(), did.to_string());
Ok(n)
}
};
match next {
Ok(n) => {
durable(s.log.clone(), n).await?;
}
Err(out) => {
deliver(&s, out).await?;
return token_required();
}
}
Ok(Resp::Nothing)
}
async fn request_password_reset(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let email = required(&b, "email")?.to_lowercase();
let not_found = || invalid("account not found");
let Some(a) = s.by_email(&email) else {
return not_found();
};
let out = {
let mut m = lock(&a.mail);
// Its email may have changed since it was looked up.
if m.email.as_deref() != Some(email.as_str()) {
return not_found();
}
make(&s, &a.did, &mut m, Purpose::ResetPassword)?
};
deliver(&s, out).await?;
Ok(Resp::Nothing)
}
async fn reset_password(s: Shared, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let (token, pw) = (
required(&b, "token")?,
required(&b, "password")?.to_string(),
);
if password_length(&pw) > 256 {
return invalid("Password too long");
}
let token = token.to_ascii_uppercase();
let Some(a) = s.by_reset(&token) else {
return invalid_token();
};
let did = a.did.clone();
let now = s.sessions.now();
lock(&a.mail).check(Purpose::ResetPassword, &token, now)?;
// Hashed on the hash threads with no lock held; the token is checked
// again, as another call may have used it meanwhile.
let hash = s
.limits
.hashes
.run(move || password::hash(&pw))
.await
.map_or_else(internal, Ok)?;
let n = {
let mut m = lock(&a.mail);
m.check(Purpose::ResetPassword, &token, now)?;
let mine = [
json!({ "t": "password", "did": did, "password": hash }),
use_entry(&did, Purpose::ResetPassword),
];
// Every session it has ends, in the same frame; and of OAuth's, its
// sessions, the requests approved for it, its sign-ins on every
// device, and its passkeys, with its link to add one.
let ends = crate::oauth::Ends {
sessions: true,
requests: true,
devices: true,
passkeys: true,
..Default::default()
};
let n = s
.oauth
.end_for(&did, ends, |ended| {
let mut all = mine.to_vec();
all.extend(ended);
s.sessions.end_all(&s.log, &did, all)
})
.or_else(not_logged)?;
apply(&s, &did, &mut m, &mine);
n
};
durable(s.log.clone(), n).await?;
Ok(Resp::Nothing)
}
/// `createSession`, once it has found the account `a`, and `own` is the hash
/// of its password if the password given is that password, `app` the digest
/// of what was given: start a session, or ask for the code its email factor
/// needs. Answers the session's access and refresh tokens and the frame that
/// keeps it.
pub(crate) async fn start_session(
s: &Shared,
a: &Account,
app: &[u8; 32],
own: Option<String>,
code: Option<&str>,
) -> Result<(String, String, u64), XrpcError> {
let refuse = || XrpcError {
status: 401,
name: "AuthenticationRequired",
message: "Invalid identifier or password".into(),
};
let now = s.sessions.now();
let out = {
let mut m = lock(&a.mail);
// A password reset since it was checked makes it wrong.
let full = own.is_some() && m.password == own;
if !full && !s.sessions.has_app_password(&a.did, app) {
return Err(refuse());
}
let app = (!full).then_some(app);
match code {
Some(code) => {
m.check(Purpose::AuthFactor, code, now)?;
let used = use_entry(&a.did, Purpose::AuthFactor);
let started = s
.sessions
.start(&s.log, &a.did, app, vec![used.clone()])
.or_else(not_logged)?
.ok_or_else(refuse)?;
apply(s, &a.did, &mut m, &[used]);
return Ok(started);
}
None if full && m.auth_factor => make(s, &a.did, &mut m, Purpose::AuthFactor)?,
None => {
return s
.sessions
.start(&s.log, &a.did, app, vec![])
.or_else(not_logged)?
.ok_or_else(refuse);
}
}
};
deliver(s, out).await?;
err(
401,
"AuthFactorTokenRequired",
"A sign in code has been sent to your email address",
)
}
#[cfg(test)]
pub(crate) mod testing {
use super::*;
use crate::testing::*;
use std::path::Path;
/// The server on `dir`, writing each email to `sink`.
pub fn open_with_sink(dir: &Path, plc: &str, sink: &Path) -> Shared {
std::fs::create_dir_all(sink).unwrap();
Arc::new(
Service::open(
dir,
crate::Config {
mailer: Mailer::sink(sink),
..config(plc)
},
)
.unwrap(),
)
}
/// Every email written to `sink`, in the order of their names.
pub fn sent(sink: &Path) -> Vec<Json> {
let mut names: Vec<String> = std::fs::read_dir(sink)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
.iter()
.map(|n| serde_json::from_slice(&std::fs::read(sink.join(n)).unwrap()).unwrap())
.collect()
}
/// The token of the last email written to `sink`.
pub fn last_token(sink: &Path) -> String {
sent(sink).last().unwrap()["token"]
.as_str()
.unwrap()
.to_string()
}
}
#[cfg(test)]
mod tests {
use super::testing::*;
use super::*;
use crate::read;
use crate::testing::*;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
const REQ_CONFIRM: &str = "com.atproto.server.requestEmailConfirmation";
const CONFIRM: &str = "com.atproto.server.confirmEmail";
const REQ_UPDATE: &str = "com.atproto.server.requestEmailUpdate";
const UPDATE: &str = "com.atproto.server.updateEmail";
const REQ_RESET: &str = "com.atproto.server.requestPasswordReset";
const RESET: &str = "com.atproto.server.resetPassword";
const CREATE_SESSION: &str = "com.atproto.server.createSession";
const GET_SESSION: &str = "com.atproto.server.getSession";
const REFRESH: &str = "com.atproto.server.refreshSession";
struct Env {
plc: String,
dir: PathBuf,
sink: PathBuf,
s: Shared,
}
impl Env {
async fn new(name: &str) -> Env {
let plc = plc().await;
let dir = scratch(name);
let sink = scratch(&format!("{name}-mail"));
let s = open_with_sink(&dir, &plc, &sink);
Env { plc, dir, sink, s }
}
fn reopen(&mut self) {
self.s = open_with_sink(&self.dir, &self.plc, &self.sink);
}
fn sent(&self) -> Vec<Json> {
sent(&self.sink)
}
fn token(&self) -> String {
last_token(&self.sink)
}
async fn call(&self, nsid: &str, token: Option<&str>, body: Json) -> Result<Json, String> {
call(&self.s, nsid, token, body).await
}
async fn login(&self, id: &str, pw: &str) -> Result<Json, String> {
self.call(
CREATE_SESSION,
None,
json!({ "identifier": id, "password": pw }),
)
.await
}
async fn login_code(&self, id: &str, pw: &str, code: &str) -> Result<Json, String> {
self.call(
CREATE_SESSION,
None,
json!({ "identifier": id, "password": pw, "authFactorToken": code }),
)
.await
}
async fn session(&self, token: &str) -> Json {
self.call(GET_SESSION, Some(token), Json::Null)
.await
.unwrap()
}
/// Pass `secs` seconds.
fn skew(&self, secs: u64) {
self.s.sessions.skew.fetch_add(secs, Ordering::SeqCst);
}
/// Request a confirmation token and confirm the email with it.
async fn confirm(&self, token: &str, email: &str) {
self.call(REQ_CONFIRM, Some(token), Json::Null)
.await
.unwrap();
self.call(
CONFIRM,
Some(token),
json!({ "email": email, "token": self.token() }),
)
.await
.unwrap();
}
}
impl Drop for Env {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
let _ = std::fs::remove_dir_all(&self.sink);
}
}
fn mail(to: &str, kind: &str) -> (String, String) {
(to.to_string(), kind.to_string())
}
fn kinds(sent: &[Json]) -> Vec<(String, String)> {
sent.iter()
.map(|m| mail(m["to"].as_str().unwrap(), m["kind"].as_str().unwrap()))
.collect()
}
/// An account without a password, which keeps no email.
async fn create_without_password(s: &Shared, name: &str) -> (String, String) {
let body = json!({ "handle": format!("{name}.test"), "email": format!("{name}@mail.com") });
let got = call(s, "com.atproto.server.createAccount", None, body)
.await
.unwrap();
(
got["did"].as_str().unwrap().to_string(),
got["accessJwt"].as_str().unwrap().to_string(),
)
}
/// A session made with a new app password of the account's.
async fn app_session(e: &Env, token: &str, id: &str) -> (String, String) {
let app = e
.call(
"com.atproto.server.createAppPassword",
Some(token),
json!({ "name": format!("app{}", rand::random::<u32>()) }),
)
.await
.unwrap();
let pw = app["password"].as_str().unwrap().to_string();
let got = e.login(id, &pw).await.unwrap();
(got["accessJwt"].as_str().unwrap().to_string(), pw)
}
#[test]
fn tokens_are_of_the_form() {
let mut seen = std::collections::HashSet::new();
for _ in 0..1000 {
let t = new_token();
assert!(is_token(&t), "{t}");
assert!(
t.chars()
.all(|c| c == '-' || c.is_ascii_uppercase() || ('2'..='7').contains(&c))
);
seen.insert(t);
}
assert_eq!(seen.len(), 1000);
for bad in [
"AB2CD-EF7G",
"AB2CDEF7GH",
"AB2CD-EF7G1",
"ab2cd-ef7gh",
"AB2CD-EF7GH ",
"AB2CD_EF7GH",
] {
assert!(!is_token(bad), "{bad}");
}
}
/// `requestEmailConfirmation`'s checks, in order, and the token it mails.
#[tokio::test]
async fn request_email_confirmation() {
let e = Env::new("req-confirm").await;
let (_, alice) = create(&e.s, "alice").await;
let (_, nopw) = create_without_password(&e.s, "nopw").await;
let refresh = e.login("alice.test", "alice-pw").await.unwrap()["refreshJwt"]
.as_str()
.unwrap()
.to_string();
assert_eq!(
e.call(REQ_CONFIRM, None, Json::Null).await,
Err("AuthMissing".into())
);
assert_eq!(
e.call(REQ_CONFIRM, Some("forged"), json!({})).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(REQ_CONFIRM, Some(&refresh), Json::Null).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(REQ_CONFIRM, Some(&alice), json!({})).await,
Err("InvalidRequest".into())
);
assert_eq!(
e.call(REQ_CONFIRM, Some(&nopw), Json::Null).await,
Err("InvalidRequest".into())
);
assert!(e.sent().is_empty());
assert_eq!(
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await,
Ok(Json::Null)
);
let (app, _) = app_session(&e, &alice, "alice.test").await;
assert_eq!(
e.call(REQ_CONFIRM, Some(&app), Json::Null).await,
Ok(Json::Null)
);
let sent = e.sent();
assert_eq!(
kinds(&sent),
[
mail("alice@mail.com", "confirmEmail"),
mail("alice@mail.com", "confirmEmail")
]
);
assert!(
sent.iter().all(
|m| is_token(m["token"].as_str().unwrap()) && m.as_object().unwrap().len() == 3
)
);
assert_ne!(sent[0]["token"], sent[1]["token"]);
}
/// `confirmEmail`'s checks, in order, and the token rules: the current
/// token alone, in any case, once.
#[tokio::test]
async fn confirm_email() {
let e = Env::new("confirm").await;
let (_, alice) = create(&e.s, "alice").await;
create(&e.s, "bob").await;
let (_, nopw) = create_without_password(&e.s, "nopw").await;
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let earlier = e.token();
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let current = e.token();
let confirm = |email: &str, token: &str| json!({ "email": email, "token": token });
assert_eq!(
e.call(CONFIRM, None, confirm("alice@mail.com", ¤t))
.await,
Err("AuthMissing".into())
);
assert_eq!(
e.call(CONFIRM, Some("forged"), json!({})).await,
Err("InvalidToken".into())
);
for bad in [
json!({}),
json!({ "email": "alice@mail.com" }),
json!({ "token": current }),
json!({ "email": 1, "token": current }),
] {
assert_eq!(
e.call(CONFIRM, Some(&alice), bad.clone()).await,
Err("InvalidRequest".into()),
"{bad}"
);
}
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("bob@mail.com", ¤t))
.await,
Err("InvalidEmail".into())
);
assert_eq!(
e.call(CONFIRM, Some(&nopw), confirm("nopw@mail.com", ¤t))
.await,
Err("InvalidEmail".into())
);
// A token that is not the current one of this purpose.
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let other_purpose = e.token();
let squeezed = current.replace('-', "");
let spaced = format!(" {current}");
for bad in [
earlier.as_str(),
other_purpose.as_str(),
"AAAAA-AAAAA",
"",
squeezed.as_str(),
spaced.as_str(),
] {
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("alice@mail.com", bad))
.await,
Err("InvalidToken".into()),
"{bad}"
);
}
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(false));
// In lower case, by the email in mixed case: confirmed, and used up.
assert_eq!(
e.call(
CONFIRM,
Some(&alice),
confirm("Alice@MAIL.com", ¤t.to_lowercase())
)
.await,
Ok(Json::Null)
);
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(true));
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("alice@mail.com", ¤t))
.await,
Err("InvalidToken".into())
);
// Confirming again is allowed, with a new token.
e.confirm(&alice, "alice@mail.com").await;
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(true));
// The reset token is untouched by all this.
e.call(
RESET,
None,
json!({ "token": other_purpose, "password": "new" }),
)
.await
.unwrap();
}
/// A token works for 15 minutes; after that it is `ExpiredToken`, after
/// any check of the input, until it is replaced.
#[tokio::test]
async fn tokens_expire() {
let e = Env::new("expire").await;
let (_, alice) = create(&e.s, "alice").await;
create(&e.s, "bob").await;
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let token = e.token();
e.skew(LIFE - 1);
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let reset = e.token();
e.skew(1);
let confirm = |email: &str| json!({ "email": email, "token": token });
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("bob@mail.com")).await,
Err("InvalidEmail".into())
);
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("alice@mail.com"))
.await,
Err("ExpiredToken".into())
);
assert_eq!(
e.call(CONFIRM, Some(&alice), confirm("alice@mail.com"))
.await,
Err("ExpiredToken".into())
);
// The reset token, made later, still works.
assert_eq!(
e.call(
RESET,
None,
json!({ "token": reset, "password": "x".repeat(257) })
)
.await,
Err("InvalidRequest".into())
);
e.call(RESET, None, json!({ "token": reset, "password": "new" }))
.await
.unwrap();
// Replaced, the new one works.
e.confirm(&alice, "alice@mail.com").await;
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(true));
}
/// `requestEmailUpdate` and `updateEmail`: only the account's own
/// password's sessions; a token needed once the email is confirmed.
#[tokio::test]
async fn update_email() {
let e = Env::new("update").await;
let (alice_did, alice) = create(&e.s, "alice").await;
create(&e.s, "bob").await;
let (app, _) = app_session(&e, &alice, "alice.test").await;
// App passwords' sessions may call neither, whatever the input.
assert_eq!(
e.call(REQ_UPDATE, Some(&app), json!({})).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(UPDATE, Some(&app), json!({})).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(REQ_UPDATE, None, Json::Null).await,
Err("AuthMissing".into())
);
assert_eq!(
e.call(REQ_UPDATE, Some(&alice), json!({})).await,
Err("InvalidRequest".into())
);
for bad in [
json!({}),
json!({ "email": 1 }),
json!({ "email": "a@b.com", "token": 1 }),
json!({ "email": "a@b.com", "emailAuthFactor": "yes" }),
] {
assert_eq!(
e.call(UPDATE, Some(&alice), bad.clone()).await,
Err("InvalidRequest".into()),
"{bad}"
);
}
// Unconfirmed: no token needed, none mailed.
assert_eq!(
e.call(REQ_UPDATE, Some(&alice), Json::Null).await,
Ok(json!({ "tokenRequired": false }))
);
assert!(e.sent().is_empty());
for bad in ["not-an-email", "a@b", "Bob@Mail.com"] {
assert_eq!(
e.call(UPDATE, Some(&alice), json!({ "email": bad })).await,
Err("InvalidRequest".into()),
"{bad}"
);
}
// A token given must be the account's, needed or not.
assert_eq!(
e.call(
UPDATE,
Some(&alice),
json!({ "email": "new@mail.com", "token": "AAAAA-AAAAA" })
)
.await,
Err("InvalidToken".into())
);
e.call(
UPDATE,
Some(&alice),
json!({ "email": "New@Mail.com", "token": "" }),
)
.await
.unwrap();
assert_eq!(e.session(&alice).await["email"], json!("new@mail.com"));
assert_eq!(
e.login("new@mail.com", "alice-pw").await.unwrap()["did"],
json!(alice_did)
);
assert_eq!(
e.login("alice@mail.com", "alice-pw").await,
Err("AuthenticationRequired".into())
);
// Its old email is free.
let carol = json!({ "handle": "carol.test", "email": "alice@mail.com", "password": "pw" });
call(&e.s, "com.atproto.server.createAccount", None, carol)
.await
.unwrap();
// Confirmed: a token is needed, mailed to the email it has.
e.confirm(&alice, "new@mail.com").await;
let before = e.sent().len();
assert_eq!(
e.call(UPDATE, Some(&alice), json!({ "email": "newer@mail.com" }))
.await,
Err("TokenRequired".into())
);
assert_eq!(
e.call(
UPDATE,
Some(&alice),
json!({ "email": "newer@mail.com", "token": "" })
)
.await,
Err("TokenRequired".into())
);
assert_eq!(e.sent().len(), before);
assert_eq!(
e.call(REQ_UPDATE, Some(&alice), Json::Null).await,
Ok(json!({ "tokenRequired": true }))
);
let earlier = e.token();
assert_eq!(
e.call(REQ_UPDATE, Some(&alice), Json::Null).await,
Ok(json!({ "tokenRequired": true }))
);
let token = e.token();
assert_eq!(
kinds(&e.sent()[before..]),
[
mail("new@mail.com", "updateEmail"),
mail("new@mail.com", "updateEmail")
]
);
assert_eq!(
e.call(
UPDATE,
Some(&alice),
json!({ "email": "newer@mail.com", "token": earlier })
)
.await,
Err("InvalidToken".into())
);
// Another account's email leaves the token as it was.
assert_eq!(
e.call(
UPDATE,
Some(&alice),
json!({ "email": "bob@mail.com", "token": token })
)
.await,
Err("InvalidRequest".into())
);
// A request to confirm meanwhile is ended with every other token by the change.
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let confirm_token = e.token();
e.call(
UPDATE,
Some(&alice),
json!({ "email": "newer@mail.com", "token": token.to_lowercase() }),
)
.await
.unwrap();
let session = e.session(&alice).await;
assert_eq!(
(&session["email"], &session["emailConfirmed"]),
(&json!("newer@mail.com"), &json!(false))
);
assert_eq!(
e.call(
CONFIRM,
Some(&alice),
json!({ "email": "newer@mail.com", "token": confirm_token })
)
.await,
Err("InvalidToken".into())
);
// The same address again: unconfirmed again.
e.confirm(&alice, "newer@mail.com").await;
e.call(REQ_UPDATE, Some(&alice), Json::Null).await.unwrap();
e.call(
UPDATE,
Some(&alice),
json!({ "email": "NEWER@mail.com", "token": e.token() }),
)
.await
.unwrap();
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(false));
// Changing the email mails nothing.
assert_eq!(e.sent().last().unwrap()["kind"], json!("updateEmail"));
let n = e.sent().len();
e.call(UPDATE, Some(&alice), json!({ "email": "last@mail.com" }))
.await
.unwrap();
assert_eq!(e.sent().len(), n);
}
/// An account without a password keeps no email: `updateEmail` answers
/// as if it changed it, even to another account's.
#[tokio::test]
async fn update_email_without_a_password() {
let e = Env::new("update-nopw").await;
create(&e.s, "alice").await;
let (_, nopw) = create_without_password(&e.s, "nopw").await;
assert_eq!(
e.call(REQ_UPDATE, Some(&nopw), Json::Null).await,
Err("InvalidRequest".into())
);
assert_eq!(
e.call(
UPDATE,
Some(&nopw),
json!({ "email": "nopw@mail.com", "emailAuthFactor": true })
)
.await,
Err("InvalidRequest".into())
);
assert_eq!(
e.call(UPDATE, Some(&nopw), json!({ "email": "alice@mail.com" }))
.await,
Ok(Json::Null)
);
assert_eq!(
e.call(
UPDATE,
Some(&nopw),
json!({ "email": "x@mail.com", "token": "AAAAA-AAAAA" })
)
.await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(
UPDATE,
Some(&nopw),
json!({ "email": "x@mail.com", "emailAuthFactor": false })
)
.await,
Ok(Json::Null)
);
let session = e.session(&nopw).await;
assert!(session.get("email").is_none());
assert_eq!(read(&e.s.directory).emails.len(), 1);
}
/// The email factor: on only for a confirmed email; then signing in with
/// the account's password needs a code mailed to it, which works once;
/// off with a token mailed to the email.
#[tokio::test]
async fn email_factor() {
let e = Env::new("factor").await;
let (did, alice) = create(&e.s, "alice").await;
let (_, app_pw) = app_session(&e, &alice, "alice.test").await;
let on = json!({ "email": "alice@mail.com", "emailAuthFactor": true });
let off = |token: Option<&str>| {
let mut b = json!({ "email": "Alice@mail.com", "emailAuthFactor": false });
if let Some(t) = token {
b["token"] = json!(t);
}
b
};
// Off already: nothing to do.
assert_eq!(
e.call(UPDATE, Some(&alice), off(None)).await,
Ok(Json::Null)
);
assert_eq!(
e.call(UPDATE, Some(&alice), on.clone()).await,
Err("InvalidRequest".into())
);
e.confirm(&alice, "alice@mail.com").await;
assert_eq!(
e.call(
UPDATE,
Some(&alice),
json!({ "email": "bob@mail.com", "emailAuthFactor": true })
)
.await,
Err("InvalidRequest".into())
);
assert_eq!(
e.call(UPDATE, Some(&alice), on.clone()).await,
Ok(Json::Null)
);
assert_eq!(
e.call(UPDATE, Some(&alice), on.clone()).await,
Ok(Json::Null)
);
assert_eq!(e.session(&alice).await["emailAuthFactor"], json!(true));
let n = e.sent().len();
// A wrong password is still wrong first, code or not.
assert_eq!(
e.login("alice.test", "wrong").await,
Err("AuthenticationRequired".into())
);
assert_eq!(
e.login_code("alice.test", "wrong", "AAAAA-AAAAA").await,
Err("AuthenticationRequired".into())
);
assert_eq!(e.sent().len(), n);
assert_eq!(
e.login("alice.test", "alice-pw").await,
Err("AuthFactorTokenRequired".into())
);
let replaced = e.token();
assert_eq!(
e.login_code("alice.test", "alice-pw", "").await,
Err("AuthFactorTokenRequired".into())
);
let code = e.token();
assert_eq!(
kinds(&e.sent()[n..]),
[
mail("alice@mail.com", "signInAuthFactor"),
mail("alice@mail.com", "signInAuthFactor")
]
);
// An app password needs no code, but a code given must be right.
assert_eq!(
e.login("alice.test", &app_pw).await.unwrap()["emailAuthFactor"],
json!(true)
);
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let other = e.token();
for bad in [replaced.as_str(), "AAAAA-AAAAA", other.as_str()] {
assert_eq!(
e.login_code("alice.test", "alice-pw", bad).await,
Err("InvalidToken".into()),
"{bad}"
);
assert_eq!(
e.login_code("alice.test", &app_pw, bad).await,
Err("InvalidToken".into()),
"{bad}"
);
}
let got = e
.login_code("Alice@Mail.com", "alice-pw", &code.to_lowercase())
.await
.unwrap();
assert_eq!(got["did"], json!(did));
assert_eq!(
e.login_code("alice.test", "alice-pw", &code).await,
Err("InvalidToken".into())
);
// Off: without a token, one is mailed; a wrong one is refused.
let n = e.sent().len();
assert_eq!(
e.call(UPDATE, Some(&alice), off(None)).await,
Err("TokenRequired".into())
);
assert_eq!(
kinds(&e.sent()[n..]),
[mail("alice@mail.com", "updateEmail")]
);
let token = e.token();
assert_eq!(
e.call(UPDATE, Some(&alice), off(Some(""))).await,
Err("TokenRequired".into())
);
let earlier = token;
let token = e.token();
assert_eq!(
e.call(UPDATE, Some(&alice), off(Some(&earlier))).await,
Err("InvalidToken".into())
);
assert_eq!(
e.call(UPDATE, Some(&alice), off(Some(&token))).await,
Ok(Json::Null)
);
let session = e.session(&alice).await;
assert_eq!(
(
&session["emailAuthFactor"],
&session["emailConfirmed"],
&session["email"]
),
(&json!(false), &json!(true), &json!("alice@mail.com"))
);
assert!(e.login("alice.test", "alice-pw").await.is_ok());
// An expired code is refused as such, the session not made.
e.call(UPDATE, Some(&alice), on).await.unwrap();
assert_eq!(
e.login("alice.test", "alice-pw").await,
Err("AuthFactorTokenRequired".into())
);
e.skew(LIFE);
assert_eq!(
e.login_code("alice.test", "alice-pw", &e.token()).await,
Err("ExpiredToken".into())
);
// An account without a password has no codes.
let (_, nopw) = create_without_password(&e.s, "nopw").await;
let (_, nopw_app) = app_session(&e, &nopw, "nopw.test").await;
assert_eq!(
e.login_code("nopw.test", &nopw_app, "AAAAA-AAAAA").await,
Err("InvalidToken".into())
);
// The reset token is still the account's, unused by all this, if past its time.
assert_eq!(
e.call(RESET, None, json!({ "token": other, "password": "x" }))
.await,
Err("ExpiredToken".into())
);
}
/// `requestPasswordReset` and `resetPassword`: the token names its
/// account; the password is set, every session ended, the app passwords kept.
#[tokio::test]
async fn password_reset() {
let e = Env::new("reset").await;
let (_, alice) = create(&e.s, "alice").await;
create(&e.s, "bob").await;
create_without_password(&e.s, "nopw").await;
let first = e.login("alice.test", "alice-pw").await.unwrap();
let (app, app_pw) = app_session(&e, &alice, "alice.test").await;
let app_refresh = e.login("alice.test", &app_pw).await.unwrap()["refreshJwt"]
.as_str()
.unwrap()
.to_string();
e.confirm(&alice, "alice@mail.com").await;
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let confirm = e.token();
for (body, want) in [
(json!({}), "InvalidRequest"),
(json!({ "email": 1 }), "InvalidRequest"),
(json!({ "email": "nobody@mail.com" }), "InvalidRequest"),
(json!({ "email": "nopw@mail.com" }), "InvalidRequest"),
(json!({ "email": "not an address" }), "InvalidRequest"),
] {
assert_eq!(
e.call(REQ_RESET, None, body.clone()).await,
Err(want.into()),
"{body}"
);
}
let n = e.sent().len();
// It ignores a token, even one never given out.
assert_eq!(
call_raw(
&e.s,
REQ_RESET,
sessions::Bearer::Token("forged"),
&[],
r#"{"email":"ALICE@mail.com"}"#
)
.await,
Ok(Json::Null)
);
let earlier = e.token();
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let token = e.token();
e.call(REQ_RESET, None, json!({ "email": "bob@mail.com" }))
.await
.unwrap();
let bobs = e.token();
assert_eq!(
kinds(&e.sent()[n..]),
[
mail("alice@mail.com", "resetPassword"),
mail("alice@mail.com", "resetPassword"),
mail("bob@mail.com", "resetPassword")
]
);
let long = "๐".repeat(129);
for (body, want) in [
(json!({ "token": token }), "InvalidRequest"),
(json!({ "password": "x" }), "InvalidRequest"),
(json!({ "token": token, "password": 1 }), "InvalidRequest"),
(
json!({ "token": "AAAAA-AAAAA", "password": long }),
"InvalidRequest",
),
(json!({ "token": earlier, "password": "x" }), "InvalidToken"),
(json!({ "token": confirm, "password": "x" }), "InvalidToken"),
(
json!({ "token": "AAAAA-AAAAA", "password": "x" }),
"InvalidToken",
),
(json!({ "token": "", "password": "x" }), "InvalidToken"),
] {
assert_eq!(
e.call(RESET, Some("forged"), body.clone()).await,
Err(want.into()),
"{body}"
);
}
assert_eq!(
e.call(
RESET,
None,
json!({ "token": token.to_lowercase(), "password": "๐".repeat(128) })
)
.await,
Ok(Json::Null)
);
assert_eq!(
e.call(RESET, None, json!({ "token": token, "password": "again" }))
.await,
Err("InvalidToken".into())
);
assert_eq!(
e.login("alice.test", "alice-pw").await,
Err("AuthenticationRequired".into())
);
assert!(e.login("alice.test", &"๐".repeat(128)).await.is_ok());
// Every session before it ended, its app password's too; access tokens still work.
assert_eq!(
e.call(REFRESH, first["refreshJwt"].as_str(), Json::Null)
.await,
Err("ExpiredToken".into())
);
assert_eq!(
e.call(REFRESH, Some(&app_refresh), Json::Null).await,
Err("ExpiredToken".into())
);
assert_eq!(e.session(&app).await["handle"], json!("alice.test"));
// The app password still logs in; the email is as it was, and the other tokens.
assert!(e.login("alice.test", &app_pw).await.is_ok());
assert_eq!(e.session(&alice).await["emailConfirmed"], json!(true));
e.call(
CONFIRM,
Some(&alice),
json!({ "email": "alice@mail.com", "token": confirm }),
)
.await
.unwrap();
// Bob's token resets bob's; the empty password is allowed, and logs in.
e.call(RESET, None, json!({ "token": bobs, "password": "" }))
.await
.unwrap();
assert!(e.login("bob.test", "").await.is_ok());
assert_eq!(
e.login("bob.test", "bob-pw").await,
Err("AuthenticationRequired".into())
);
e.call(REQ_RESET, None, json!({ "email": "bob@mail.com" }))
.await
.unwrap();
e.call(
RESET,
None,
json!({ "token": e.token(), "password": "bob-pw" }),
)
.await
.unwrap();
assert!(e.login("bob.test", "bob-pw").await.is_ok());
// A token from before an email change is ended by it.
e.call(REQ_RESET, None, json!({ "email": "bob@mail.com" }))
.await
.unwrap();
let ended = e.token();
let bob = session(&e.s, "bob").await;
e.call(UPDATE, Some(&bob), json!({ "email": "robert@mail.com" }))
.await
.unwrap();
assert_eq!(
e.call(RESET, None, json!({ "token": ended, "password": "x" }))
.await,
Err("InvalidToken".into())
);
assert!(e.s.resets.snapshot().is_empty());
}
/// Of several calls at once with one token, one succeeds.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn one_token_one_use() {
let e = Env::new("races").await;
let (_, alice) = create(&e.s, "alice").await;
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let reset = e.token();
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let confirm = e.token();
let calls: Vec<_> = (0..8)
.map(|i| {
let s = e.s.clone();
let (nsid, token, body) = if i % 2 == 0 {
(
RESET,
None,
json!({ "token": reset, "password": format!("pw{i}") }),
)
} else {
(
CONFIRM,
Some(alice.clone()),
json!({ "email": "alice@mail.com", "token": confirm }),
)
};
tokio::spawn(async move { (nsid, call(&s, nsid, token.as_deref(), body).await) })
})
.collect();
let mut ok = std::collections::HashMap::new();
for c in calls {
let (nsid, got) = c.await.unwrap();
match got {
Ok(_) => *ok.entry(nsid).or_insert(0) += 1,
Err(e) => assert_eq!(e, "InvalidToken"),
}
}
assert_eq!((ok[RESET], ok[CONFIRM]), (1, 1));
}
/// The sink: each email a file of its own, in order, its name sorting after
/// every earlier one's across a restart, none left half written.
#[tokio::test]
async fn the_sink() {
let mut e = Env::new("sink").await;
let (_, alice) = create(&e.s, "alice").await;
create(&e.s, "bob").await;
for _ in 0..5 {
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
e.call(REQ_RESET, None, json!({ "email": "bob@mail.com" }))
.await
.unwrap();
}
e.reopen();
e.call(REQ_RESET, None, json!({ "email": "alice@mail.com" }))
.await
.unwrap();
let mut names: Vec<String> = std::fs::read_dir(&e.sink)
.unwrap()
.map(|f| f.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
assert_eq!(names.len(), 11);
for n in &names {
let (stem, ext) = n.split_once('.').unwrap();
assert_eq!(ext, "json");
let (time, count) = stem.split_once('-').unwrap();
assert!(
time.len() == 20
&& time.bytes().all(|b| b.is_ascii_digit())
&& count.bytes().all(|b| b.is_ascii_digit()),
"{n}"
);
}
let mut want = vec![];
for _ in 0..5 {
want.extend([
mail("alice@mail.com", "confirmEmail"),
mail("bob@mail.com", "resetPassword"),
]);
}
want.push(mail("alice@mail.com", "resetPassword"));
assert_eq!(kinds(&e.sent()), want);
// The last sent is the one that works.
let tokens: Vec<String> = e
.sent()
.iter()
.map(|m| m["token"].as_str().unwrap().to_string())
.collect();
assert_eq!(
e.call(RESET, None, json!({ "token": tokens[7], "password": "x" }))
.await,
Err("InvalidToken".into())
);
e.call(RESET, None, json!({ "token": tokens[9], "password": "x" }))
.await
.unwrap();
// Without a sink, nothing is written anywhere, and the methods answer all the same.
let plain = scratch("sink-none");
let s = open(&plain, &e.plc);
let (_, token) = create(&s, "carol").await;
assert_eq!(
call(&s, REQ_CONFIRM, Some(&token), Json::Null).await,
Ok(Json::Null)
);
assert_eq!(
call(&s, REQ_RESET, None, json!({ "email": "carol@mail.com" })).await,
Ok(Json::Null)
);
let _ = std::fs::remove_dir_all(&plain);
}
/// Tokens, confirmations, email changes, the factor and reset passwords
/// survive a restart; a token keeps its 15 minutes.
#[tokio::test]
async fn a_restart() {
let mut e = Env::new("restart").await;
let (alice_did, alice) = create(&e.s, "alice").await;
let (_, bob) = create(&e.s, "bob").await;
create(&e.s, "carol").await;
let bob_refresh = e.login("bob.test", "bob-pw").await.unwrap()["refreshJwt"]
.as_str()
.unwrap()
.to_string();
e.confirm(&alice, "alice@mail.com").await;
e.call(
UPDATE,
Some(&alice),
json!({ "email": "alice@mail.com", "emailAuthFactor": true }),
)
.await
.unwrap();
e.call(UPDATE, Some(&bob), json!({ "email": "robert@mail.com" }))
.await
.unwrap();
e.call(REQ_RESET, None, json!({ "email": "robert@mail.com" }))
.await
.unwrap();
e.call(
RESET,
None,
json!({ "token": e.token(), "password": "robert-pw" }),
)
.await
.unwrap();
e.call(REQ_RESET, None, json!({ "email": "carol@mail.com" }))
.await
.unwrap();
let carol_reset = e.token();
e.call(REQ_CONFIRM, Some(&alice), Json::Null).await.unwrap();
let alice_confirm = e.token();
e.skew(LIFE - 60);
let before = (snapshot(&e.s), e.s.resets.snapshot());
e.reopen();
assert_eq!((snapshot(&e.s), e.s.resets.snapshot()), before);
let session = e.session(&alice).await;
assert_eq!(
(&session["emailConfirmed"], &session["emailAuthFactor"]),
(&json!(true), &json!(true))
);
assert_eq!(
e.login("alice.test", "alice-pw").await,
Err("AuthFactorTokenRequired".into())
);
assert!(e.login("robert@mail.com", "robert-pw").await.is_ok());
assert_eq!(
e.login("bob@mail.com", "robert-pw").await,
Err("AuthenticationRequired".into())
);
assert_eq!(
e.call(REFRESH, Some(&bob_refresh), Json::Null).await,
Err("ExpiredToken".into())
);
// The restart's clock has no skew: tokens are as old as they were.
e.skew(LIFE - 60);
e.call(
CONFIRM,
Some(&alice),
json!({ "email": "alice@mail.com", "token": alice_confirm }),
)
.await
.unwrap();
e.skew(60);
assert_eq!(
e.call(
RESET,
None,
json!({ "token": carol_reset, "password": "x" })
)
.await,
Err("ExpiredToken".into())
);
// The account's email is its own still, and no other's.
let dave = json!({ "handle": "dave.test", "email": "robert@mail.com", "password": "pw" });
assert_eq!(
call(&e.s, "com.atproto.server.createAccount", None, dave).await,
Err("InvalidRequest".into())
);
let dave = json!({ "handle": "dave.test", "email": "bob@mail.com", "password": "pw" });
call(&e.s, "com.atproto.server.createAccount", None, dave)
.await
.unwrap();
e.reopen();
assert_eq!(
e.login("bob@mail.com", "pw").await.unwrap()["handle"],
json!("dave.test")
);
assert_eq!(
read(&e.s.directory).emails.get("alice@mail.com"),
Some(&alice_did)
);
}
/// Every account's mail, by DID, and the directory's emails.
fn snapshot(s: &Service) -> (BTreeMap<String, Mail>, BTreeMap<String, String>) {
let d = read(&s.directory);
let mails = d
.by_did
.iter()
.map(|(did, a)| (did.clone(), lock(&a.mail).clone()))
.collect();
(
mails,
d.emails
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
)
}
/// The environment: SMTP's two variables both or neither, each checked.
#[test]
fn mailer_configuration() {
let vars = |pairs: &[(&str, &str)]| {
let pairs: Vec<(String, String)> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Mailer::from_vars(move |n| pairs.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()))
};
let m = vars(&[]).unwrap();
assert!(m.smtp.is_none() && m.sink.is_none());
assert!(
vars(&[("PDS_EMAIL_SMTP_URL", "smtp://localhost")])
.err()
.unwrap()
.contains("PDS_EMAIL_FROM")
);
assert!(
vars(&[("PDS_EMAIL_FROM", "pds@example.com")])
.err()
.unwrap()
.contains("PDS_EMAIL_SMTP_URL")
);
assert!(
vars(&[
("PDS_EMAIL_SMTP_URL", "http://localhost"),
("PDS_EMAIL_FROM", "pds@example.com")
])
.is_err()
);
assert!(
vars(&[
("PDS_EMAIL_SMTP_URL", "not a url"),
("PDS_EMAIL_FROM", "pds@example.com")
])
.is_err()
);
assert!(
vars(&[
("PDS_EMAIL_SMTP_URL", "smtp://localhost"),
("PDS_EMAIL_FROM", "not an address")
])
.is_err()
);
for url in [
"smtp://localhost",
"smtps://u%40x:p%3Aw@mail.example.com:2465",
"smtp://user:pass@127.0.0.1:2525",
] {
let m = vars(&[
("PDS_EMAIL_SMTP_URL", url),
("PDS_EMAIL_FROM", "PDS <pds@example.com>"),
("PDS_DEV_MAIL_DIR", "/tmp/x"),
])
.unwrap();
assert!(m.smtp.is_some() && m.sink.is_some(), "{url}");
}
}
/// An SMTP server that takes every email, as text, and answers each
/// command as a plain server without STARTTLS would.
fn smtp_server() -> (u16, std::sync::mpsc::Receiver<String>) {
use std::io::{BufRead, BufReader};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(conn) = conn else { return };
let tx = tx.clone();
std::thread::spawn(move || {
let mut out = conn.try_clone().unwrap();
let mut lines = BufReader::new(conn);
let mut say = |s: &str| out.write_all(format!("{s}\r\n").as_bytes()).unwrap();
say("220 localhost ESMTP");
let mut text = String::new();
let mut line = String::new();
while lines.read_line(&mut line).unwrap_or(0) > 0 {
let cmd = line.trim_end().to_ascii_uppercase();
if cmd.starts_with("EHLO") || cmd.starts_with("HELO") {
say("250 localhost");
} else if cmd.starts_with("DATA") {
say("354 go on");
let mut data = String::new();
loop {
data.clear();
lines.read_line(&mut data).unwrap();
if data == ".\r\n" {
break;
}
text.push_str(&data);
}
tx.send(std::mem::take(&mut text)).unwrap();
say("250 ok");
} else if cmd.starts_with("QUIT") {
say("221 bye");
return;
} else {
text.push_str(&line);
say("250 ok");
}
line.clear();
}
});
}
});
(port, rx)
}
/// Through SMTP: to the account's email, from `PDS_EMAIL_FROM`, with its
/// kind's subject and the token; with the sink written too. A server that
/// cannot be reached is `500`, and the token kept works all the same.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn smtp() {
let (port, rx) = smtp_server();
let plc = plc().await;
let (dir, sink) = (scratch("smtp"), scratch("smtp-mail"));
std::fs::create_dir_all(&sink).unwrap();
let open_smtp = |port: u16| {
let vars = [
("PDS_EMAIL_SMTP_URL", format!("smtp://127.0.0.1:{port}")),
("PDS_EMAIL_FROM", "PDS <pds@example.com>".to_string()),
("PDS_DEV_MAIL_DIR", sink.display().to_string()),
("PDS_HOSTNAME", "pds.example".to_string()),
];
let mailer =
Mailer::from_vars(|n| vars.iter().find(|(k, _)| *k == n).map(|(_, v)| v.clone()))
.unwrap();
Arc::new(
Service::open(
&dir,
crate::Config {
mailer,
..config(&plc)
},
)
.unwrap(),
)
};
let s = open_smtp(port);
let (_, alice) = create(&s, "alice").await;
call(&s, REQ_CONFIRM, Some(&alice), Json::Null)
.await
.unwrap();
let text = rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap();
let token = last_token(&sink);
assert!(text.contains("MAIL FROM:<pds@example.com>"), "{text}");
assert!(text.contains("RCPT TO:<alice@mail.com>"), "{text}");
assert!(text.contains("Subject: Email Confirmation"), "{text}");
assert!(text.contains("To: alice@mail.com"), "{text}");
assert!(text.contains(&token), "{text}");
assert!(text.contains("multipart/alternative"), "{text}");
let (plain, html) = (
text.find("Content-Type: text/plain").expect("a text part"),
text.find("Content-Type: text/html").expect("an HTML part"),
);
assert!(plain < html, "{text}");
drop(s);
// Nothing listens: the token is kept and mailed to the sink, and the call is 500.
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let dead = closed.local_addr().unwrap().port();
drop(closed);
let s = open_smtp(dead);
assert_eq!(
call(&s, REQ_RESET, None, json!({ "email": "alice@mail.com" })).await,
Err("InternalServerError".into())
);
let token = last_token(&sink);
call(
&s,
RESET,
None,
json!({ "token": token, "password": "new" }),
)
.await
.unwrap();
assert!(session_works(&s, "alice.test", "new").await);
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&sink);
}
#[test]
fn html() {
let html = Purpose::ResetPassword.html("a<b>&\"c'", "ABCDE-FGHIJ");
assert!(html.contains("a<b>&"c'"), "{html}");
assert!(html.contains("Reset your password") && html.contains("ABCDE-FGHIJ"));
assert!(html.contains("To reset the password of your account, enter this code."));
assert!(!html.contains("{{"), "{html}");
}
async fn session_works(s: &Shared, id: &str, pw: &str) -> bool {
call(
s,
CREATE_SESSION,
None,
json!({ "identifier": id, "password": pw }),
)
.await
.is_ok()
}
}