chadtmiller.com/monolith
An atproto PDS
0
0
//! Sessions' tokens, refreshing and ending sessions, and app passwords:
//! `refreshSession`, `deleteSession`, `createAppPassword`,
//! `listAppPasswords` and `revokeAppPassword`, as `spec/SESSIONS.md` says,
//! within the bounds `spec/LIMITS.md` sets.
//!
//! Tokens are JWTs signed with HS256, by a secret the server makes once and
//! keeps in `PDS_DATA_DIR/jwt.key`. An access token is checked by its
//! signature and `exp` alone. A refresh token names, by its `jti`, a session
//! the server keeps. Each account's sessions and app passwords are kept apart
//! from every other's, behind a lock of their own, and each change to them is
//! an entry in `accounts.log`, appended under that lock, so that the log has
//! an account's changes in the order they were made, and on disk before the
//! change is answered. A change is made in memory only once its entry is
//! written. Sessions past their expiry are dropped whenever the account's
//! sessions are touched, and as its account is loaded, with no entry: they
//! are expired after a restart too. An account keeps at most `MAX_SESSIONS`;
//! those dropped to keep it so are an entry of their own, in the frame of
//! the change that made one too many.
//!
//! An account's sessions and app passwords are held once the account is
//! loaded (`directory`), so every token checked loads the account it names
//! before anything reads them (`known`).
use crate::server::session_json;
use crate::{
Call, Handler, Resp, Service, Shared, Shown, XrpcError, durable, err, internal, invalid_token,
read, required, write,
};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use hmac::{Hmac, Mac};
use pds_store::Wal;
use serde_json::{Map, Value as Json, json};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};
/// The scope of a session made with the account's password.
pub(crate) const ACCESS: &str = "com.atproto.access";
/// The scope of a session made with an app password.
const APP_PASS: &str = "com.atproto.appPass";
/// The scope of a session made with a privileged app password.
pub(crate) const APP_PASS_PRIVILEGED: &str = "com.atproto.appPassPrivileged";
/// Every refresh token's scope.
const REFRESH: &str = "com.atproto.refresh";
/// The scope of the access token a taken-down account is given (`spec/LIFECYCLE.md`).
pub(crate) const TAKENDOWN: &str = "com.atproto.takendown";
/// How long an access token works, in seconds.
const ACCESS_LIFE: u64 = 2 * 60 * 60;
/// How long a refresh token, and the session it is of, works.
const REFRESH_LIFE: u64 = 90 * 24 * 60 * 60;
/// How long a refreshed session's token keeps working, from when it is first refreshed.
const GRACE: u64 = 2 * 60 * 60;
/// The most sessions an account keeps.
pub(crate) const MAX_SESSIONS: usize = 100;
/// The most app passwords an account has.
pub(crate) const MAX_APP_PASSWORDS: usize = 50;
/// The file in the data directory that holds the secret tokens are signed with.
pub(crate) const KEY_FILE: &str = "jwt.key";
/// The kinds of `accounts.log` entry this module keeps, each naming its account by `did`.
pub(crate) const ENTRIES: &[&str] = &[
"session",
"refresh",
"endSession",
"dropSessions",
"appPassword",
"revokeAppPassword",
"dropAppPasswords",
];
/// What a request's `Authorization` header holds.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Bearer<'a> {
None,
/// A `Bearer` token, its scheme in any case.
Token(&'a str),
/// A `Basic` header's credentials, which only the admin's methods take.
Basic(&'a str),
/// A `DPoP` header, the scheme in any case: an OAuth access token, not
/// yet checked, which only `scopes::look` checks.
DPoP(&'a str),
/// An OAuth access token whose call passed `scopes::look`: its session.
OAuth(&'a crate::scopes::Grant),
/// A header that is not two words separated by one space, or whose scheme
/// is none of `Bearer`, `Basic` and `DPoP`.
Malformed,
}
impl<'a> Bearer<'a> {
/// What an `Authorization` header's value holds.
pub fn of(header: Option<&'a str>) -> Bearer<'a> {
let Some(h) = header else { return Bearer::None };
let mut words = h.split(' ');
let (Some(scheme), Some(credentials), None) = (words.next(), words.next(), words.next())
else {
return Bearer::Malformed;
};
if scheme.is_empty() || credentials.is_empty() {
Bearer::Malformed
} else if scheme.eq_ignore_ascii_case("bearer") {
Bearer::Token(credentials)
} else if scheme.eq_ignore_ascii_case("basic") {
Bearer::Basic(credentials)
} else if scheme.eq_ignore_ascii_case("dpop") {
Bearer::DPoP(credentials)
} else {
Bearer::Malformed
}
}
}
/// A token the server signed, checked, or an OAuth session's.
pub(crate) struct Token {
/// Its account's DID.
pub did: String,
/// The session's scope: an OAuth session's scope tokens, separated by spaces.
pub scope: String,
/// A refresh token's session.
pub jti: Option<String>,
/// Whether it is an OAuth session's.
pub oauth: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Access,
/// An access token, or one a taken-down account was given (`spec/LIFECYCLE.md`).
AccessOrTakendown,
Refresh,
}
/// A session the server keeps.
#[derive(Clone, Debug)]
struct Session {
/// The name of the app password it was made with, if it was.
app: Option<String>,
scope: String,
/// When its refresh tokens stop working, in seconds since the epoch.
exp: u64,
/// The session refreshing it made, once it is refreshed.
next: Option<String>,
/// Where it comes among the account's sessions in the order they were
/// made, as the log has them: of two that expire at once, the older
/// is dropped first.
made: u64,
/// Whether the app password it was made with was dropped since
/// (`dropAppPasswords`): it stays, of the scope it had.
dropped: bool,
}
/// Sessions are the same whatever their place among others.
impl PartialEq for Session {
fn eq(&self, o: &Session) -> bool {
(&self.app, &self.scope, self.exp, &self.next, self.dropped)
== (&o.app, &o.scope, o.exp, &o.next, o.dropped)
}
}
impl Eq for Session {}
/// An app password, as kept.
#[derive(Clone, Debug, PartialEq, Eq)]
struct AppPassword {
name: String,
/// `sha256$<hash>`, in hex.
hash: String,
created_at: String,
privileged: bool,
}
/// A map kept as a vector in order of key: for the few sessions an account
/// keeps, one allocation, not a tree's node of room for many.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Few<V>(Vec<(String, V)>);
impl<V> Default for Few<V> {
fn default() -> Self {
Few(Vec::new())
}
}
impl<V> Few<V> {
fn at(&self, k: &str) -> Result<usize, usize> {
self.0.binary_search_by(|(x, _)| x.as_str().cmp(k))
}
fn get(&self, k: &str) -> Option<&V> {
self.at(k).ok().map(|i| &self.0[i].1)
}
fn get_mut(&mut self, k: &str) -> Option<&mut V> {
self.at(k).ok().map(|i| &mut self.0[i].1)
}
fn contains_key(&self, k: &str) -> bool {
self.at(k).is_ok()
}
fn insert(&mut self, k: String, v: V) -> Option<V> {
match self.at(&k) {
Ok(i) => Some(std::mem::replace(&mut self.0[i].1, v)),
Err(i) => {
self.0.insert(i, (k, v));
None
}
}
}
fn remove(&mut self, k: &str) -> Option<V> {
self.at(k).ok().map(|i| self.0.remove(i).1)
}
fn retain(&mut self, mut f: impl FnMut(&String, &mut V) -> bool) {
self.0.retain_mut(|(k, v)| f(k, v));
}
fn iter(&self) -> impl Iterator<Item = (&String, &V)> {
self.0.iter().map(|(k, v)| (k, v))
}
fn keys(&self) -> impl Iterator<Item = &String> {
self.0.iter().map(|(k, _)| k)
}
fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
self.0.iter_mut().map(|(_, v)| v)
}
fn len(&self) -> usize {
self.0.len()
}
fn clear(&mut self) {
self.0.clear();
}
}
/// One account's sessions and app passwords.
#[derive(Clone, Debug, Default)]
pub(crate) struct Keep {
sessions: Few<Session>,
/// In the order they were made.
passwords: Vec<AppPassword>,
/// How many sessions have been made, to give the next its place.
made: u64,
}
/// Keeps are the same whatever count of sessions made led to them.
impl PartialEq for Keep {
fn eq(&self, o: &Keep) -> bool {
let order = |k: &Keep| {
let mut ids: Vec<(&u64, &String)> =
k.sessions.iter().map(|(id, s)| (&s.made, id)).collect();
ids.sort();
ids.into_iter()
.map(|(_, id)| id.clone())
.collect::<Vec<_>>()
};
self.sessions == o.sessions && self.passwords == o.passwords && order(self) == order(o)
}
}
impl Eq for Keep {}
impl Keep {
/// 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 number = |k: &str| {
e[k].as_u64()
.ok_or_else(|| format!("an entry with no {k}: {e}"))
};
let optional = |k: &str| match e.get(k) {
None | Some(Json::Null) => Ok(None),
Some(Json::String(a)) => Ok(Some(a.clone())),
_ => Err(format!("an entry with a bad {k}: {e}")),
};
match e["t"].as_str() {
Some("session") => {
let id = text("id")?;
let app = optional("app")?;
let dropped = e.get("dropped").is_some_and(|d| d == true);
let scope = match &app {
None if dropped => {
return Err(format!("a session dropped with no app password: {e}"));
}
None => ACCESS,
// Of an app password since dropped, as a compacted log keeps it.
Some(_) if dropped => match text("scope")? {
s @ (APP_PASS | APP_PASS_PRIVILEGED) => s,
_ => return Err(format!("a session of the wrong scope: {e}")),
},
Some(a) => match self.passwords.iter().find(|p| &p.name == a) {
Some(p) if p.privileged => APP_PASS_PRIVILEGED,
Some(_) => APP_PASS,
None => {
return Err(format!(
"a session of app password {a:?}, which the account does not have"
));
}
},
};
if text("scope")? != scope {
return Err(format!("a session of the wrong scope: {e}"));
}
if self.sessions.contains_key(id) {
return Err(format!("a second session {id}"));
}
// A compacted log keeps a refreshed session's successor with it.
let next = optional("next")?;
let made = self.made_one();
self.sessions.insert(
id.to_string(),
Session {
app,
scope: scope.to_string(),
exp: number("exp")?,
next,
made,
dropped,
},
);
}
Some("refresh") => {
let (id, next, exp, next_exp) = (
text("id")?,
text("next")?,
number("exp")?,
number("nextExp")?,
);
let Some(s) = self.sessions.get_mut(id) else {
return Err(format!("a refresh of session {id}, which is not kept"));
};
if s.next.as_deref().is_some_and(|n| n != next) || next == id {
return Err(format!("a second successor of session {id}: {e}"));
}
s.next = Some(next.to_string());
s.exp = exp;
let (app, scope, dropped) = (s.app.clone(), s.scope.clone(), s.dropped);
if !self.sessions.contains_key(next) {
let made = self.made_one();
self.sessions.insert(
next.to_string(),
Session {
app,
scope,
exp: next_exp,
next: None,
made,
dropped,
},
);
}
}
Some("endSession") => {
let id = text("id")?;
if self.sessions.remove(id).is_none() {
return Err(format!("the end of session {id}, which is not kept"));
}
}
Some("dropSessions") => {
let ids = e["ids"]
.as_array()
.ok_or_else(|| format!("an entry with no ids: {e}"))?;
for id in ids {
let id = id
.as_str()
.ok_or_else(|| format!("a session id that is not a string: {e}"))?;
if self.sessions.remove(id).is_none() {
return Err(format!("the drop of session {id}, which is not kept"));
}
}
}
Some("appPassword") => {
let name = text("name")?;
let Some(privileged) = e["privileged"].as_bool() else {
return Err(format!("an app password with no privileged: {e}"));
};
if self.passwords.iter().any(|p| p.name == name) {
return Err(format!("a second app password {name:?}"));
}
self.passwords.push(AppPassword {
name: name.to_string(),
hash: text("hash")?.to_string(),
created_at: text("createdAt")?.to_string(),
privileged,
});
}
Some("revokeAppPassword") => {
let name = text("name")?;
let before = self.passwords.len();
self.passwords.retain(|p| p.name != name);
if self.passwords.len() == before {
return Err(format!(
"a revocation of app password {name:?}, which the account does not have"
));
}
self.sessions.retain(|_, s| s.app.as_deref() != Some(name));
}
Some("dropAppPasswords") => {
if self.passwords.is_empty() {
return Err(format!(
"a drop of the app passwords of an account with none: {e}"
));
}
// The sessions made with them stay, as the reference keeps them.
self.passwords.clear();
for s in self.sessions.values_mut().filter(|s| s.app.is_some()) {
s.dropped = true;
}
}
t => return Err(format!("a log entry of no known type: {t:?}")),
}
Ok(())
}
/// Drop the sessions past their expiry at `now`.
fn prune(&mut self, now: u64) {
self.sessions.retain(|_, s| s.exp > now);
}
/// The next place in the order sessions are made.
fn made_one(&mut self) -> u64 {
self.made += 1;
self.made
}
/// The sessions to drop to keep `MAX_SESSIONS`: the refreshed ones, whose
/// old tokens are in their grace, first, then those that expire soonest,
/// and of those that expire at once, the oldest.
fn overflow(&self) -> Vec<String> {
let Some(over) = self
.sessions
.len()
.checked_sub(MAX_SESSIONS)
.filter(|n| *n > 0)
else {
return vec![];
};
let mut order: Vec<(&String, &Session)> = self.sessions.iter().collect();
order.sort_by_key(|(_, s)| (s.next.is_none(), s.exp, s.made));
order
.into_iter()
.take(over)
.map(|(id, _)| id.clone())
.collect()
}
/// The app password whose digest this is, compared with every one the
/// account has, each in constant time.
fn app_password(&self, digest: &[u8; 32]) -> Option<&AppPassword> {
self.passwords.iter().fold(None, |found, p| {
let want = p
.hash
.strip_prefix("sha256$")
.and_then(|h| hex::decode(h).ok())
.unwrap_or_default();
let same = want.len() == 32
&& want
.iter()
.zip(digest)
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
== 0;
if same { Some(p) } else { found }
})
}
/// The entries that make this keep again, for a compacted log: its app
/// passwords, then its sessions but those that expired before `before`,
/// in the order they were made.
pub(crate) fn entries(&self, did: &str, before: u64) -> Vec<Json> {
let passwords = self.passwords.iter().map(|p| {
json!({ "t": "appPassword", "did": did, "name": p.name, "hash": p.hash, "createdAt": p.created_at, "privileged": p.privileged })
});
let mut kept: Vec<(&String, &Session)> = self
.sessions
.iter()
.filter(|(_, s)| s.exp > before)
.collect();
kept.sort_by_key(|(_, s)| s.made);
let sessions = kept.into_iter().map(|(id, s)| {
let mut e = json!({ "t": "session", "did": did, "id": id, "app": s.app, "scope": s.scope, "exp": s.exp, "next": s.next });
if s.dropped {
e["dropped"] = json!(true);
}
e
});
passwords.chain(sessions).collect()
}
}
/// The sessions the server gave out, and the accounts' app passwords.
pub(crate) struct Sessions {
/// The secret every token is signed with.
key: [u8; 32],
/// The server's DID, every token's audience.
aud: String,
/// Each account's, by DID.
keeps: RwLock<HashMap<String, Arc<Mutex<Keep>>>>,
/// Seconds added to the clock, for tests to see tokens expire.
#[cfg(test)]
pub skew: std::sync::atomic::AtomicU64,
/// The time the clock stands at, for tests that need it to stand
/// still; 0 while it runs.
#[cfg(test)]
frozen: std::sync::atomic::AtomicU64,
}
fn lock(k: &Mutex<Keep>) -> MutexGuard<'_, Keep> {
k.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Make a change to an account's keep, under its lock, and log it: `main`,
/// after `entries` in one frame, and, should it leave the account more than
/// `MAX_SESSIONS`, the drop of those `Keep::overflow` names. The keep changes
/// only once the frame is written. Answers the frame.
fn change(
log: &Wal,
k: &mut Keep,
did: &str,
mut entries: Vec<Json>,
main: Json,
) -> std::io::Result<u64> {
let mut next = k.clone();
next.apply(&main)
.unwrap_or_else(|why| panic!("a change made under its account's lock: {why}"));
entries.push(main);
let dropped = next.overflow();
if !dropped.is_empty() {
let d = json!({ "t": "dropSessions", "did": did, "ids": dropped });
next.apply(&d)
.unwrap_or_else(|why| panic!("dropping sessions under their account's lock: {why}"));
entries.push(d);
}
let n = log.append(&entries)?;
*k = next;
Ok(n)
}
/// A change that could not be logged, as it is answered.
fn not_logged<T>(e: std::io::Error) -> Result<T, XrpcError> {
crate::ops::failed("writing accounts.log failed", e);
internal()
}
/// A new session's id.
fn new_id() -> String {
hex::encode(rand::random::<[u8; 16]>())
}
/// An app password: four groups of four lower case letters or digits 2 to 7.
fn new_app_password() -> String {
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
let chars: Vec<char> = rand::random::<[u8; 16]>()
.iter()
.map(|b| char::from(ALPHABET[usize::from(b & 31)]))
.collect();
chars
.chunks(4)
.map(|c| c.iter().collect::<String>())
.collect::<Vec<_>>()
.join("-")
}
/// What an app password is kept as, and what `createSession` compares: its
/// SHA-256, not scrypt, and unsalted. Each is 80 random bits, beyond
/// guessing, and one digest of what `createSession` is given is compared
/// with every one an account has, so a login computes one hash for them
/// however many it has.
pub(crate) fn app_password_digest(password: &str) -> [u8; 32] {
Sha256::digest(password.as_bytes()).into()
}
fn hash_app_password(password: &str) -> String {
format!("sha256${}", hex::encode(app_password_digest(password)))
}
/// The secret tokens are signed with: read from `dir`, or made there if the
/// server is starting for the first time, written whole or not at all.
fn secret(dir: &Path, fresh: bool) -> Result<[u8; 32], String> {
let path = dir.join(KEY_FILE);
match std::fs::read(&path) {
Ok(bytes) => bytes
.try_into()
.map_err(|_| format!("{KEY_FILE} is not 32 bytes")),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && fresh => {
let key: [u8; 32] = rand::random();
let tmp = dir.join(format!("{KEY_FILE}.tmp"));
let made = (|| {
let mut f = pds_store::open_private(
&tmp,
std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true),
)?;
f.write_all(&key)?;
pds_store::sync_file(&f)?;
std::fs::rename(&tmp, &path)?;
pds_store::sync_dir(dir)
})();
made.map_err(|e| format!("{KEY_FILE}: {e}"))?;
Ok(key)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(format!(
"{KEY_FILE} is missing, and the sessions given out were signed with it"
)),
Err(e) => Err(format!("{KEY_FILE}: {e}")),
}
}
type HmacSha256 = Hmac<Sha256>;
impl Sessions {
/// A server's sessions, with none kept yet and its key not read yet
/// (`keyed`): what a start replays its sessions into before it knows
/// whether the data directory is new.
pub fn unkeyed(hostname: &str) -> Sessions {
Sessions {
key: [0; 32],
aud: format!("did:web:{hostname}"),
keeps: RwLock::default(),
#[cfg(test)]
skew: Default::default(),
#[cfg(test)]
frozen: Default::default(),
}
}
/// Its secret, read from `dir`, or made if `fresh`, when the server has
/// kept nothing before.
pub fn keyed(&mut self, dir: &Path, fresh: bool) -> Result<(), String> {
self.key = secret(dir, fresh)?;
Ok(())
}
/// The time, in seconds since the epoch.
pub fn now(&self) -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
#[cfg(test)]
let now = match self.frozen.load(std::sync::atomic::Ordering::SeqCst) {
0 => now,
frozen => frozen,
} + self.skew.load(std::sync::atomic::Ordering::SeqCst);
now
}
/// The time, in milliseconds since the epoch, on the clock `now` reads.
pub fn now_ms(&self) -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
#[cfg(test)]
let now =
match self.frozen.load(std::sync::atomic::Ordering::SeqCst) {
0 => now,
frozen => std::time::Duration::from_secs(frozen),
} + std::time::Duration::from_secs(self.skew.load(std::sync::atomic::Ordering::SeqCst));
u64::try_from(now.as_millis()).unwrap_or(u64::MAX)
}
/// Stop the clock where it is, but for what `skew` adds: a test then
/// sees a token expire at exactly the second it should.
#[cfg(test)]
pub fn freeze(&self) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.frozen.store(now, std::sync::atomic::Ordering::SeqCst);
}
fn mac(&self, header: &str, claims: &str) -> HmacSha256 {
let mut mac =
HmacSha256::new_from_slice(&self.key).expect("HMAC takes a key of any length");
mac.update(header.as_bytes());
mac.update(b".");
mac.update(claims.as_bytes());
mac
}
fn sign(&self, typ: &str, claims: &Json) -> String {
let header = B64.encode(json!({ "typ": typ, "alg": "HS256" }).to_string());
let claims = B64.encode(claims.to_string());
let sig = B64.encode(self.mac(&header, &claims).finalize().into_bytes());
format!("{header}.{claims}.{sig}")
}
/// The `typ` and claims of a token this server signed.
fn verify(&self, token: &str) -> Option<(String, Map<String, Json>)> {
let mut parts = token.split('.');
let (Some(header), Some(claims), Some(sig), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return None;
};
self.mac(header, claims)
.verify_slice(&B64.decode(sig).ok()?)
.ok()?;
let header: Json = serde_json::from_slice(&B64.decode(header).ok()?).ok()?;
if header["alg"] != "HS256" {
return None;
}
let Json::Object(claims) = serde_json::from_slice(&B64.decode(claims).ok()?).ok()? else {
return None;
};
Some((header["typ"].as_str()?.to_string(), claims))
}
/// A token of `kind`: `InvalidToken` if the server did not sign it or it
/// is of the other kind, then `ExpiredToken` if it is past its `exp`,
/// unless `expired_ok`.
fn check(&self, token: &str, kind: Kind, expired_ok: bool) -> Result<Token, XrpcError> {
let Some((typ, c)) = self.verify(token) else {
return invalid_token();
};
let text = |k: &str| c.get(k).and_then(Json::as_str);
let (Some(did), Some(scope), Some(exp)) = (
text("sub"),
text("scope"),
c.get("exp").and_then(Json::as_u64),
) else {
return invalid_token();
};
let jti = text("jti").map(str::to_string);
let right = match kind {
Kind::Access => {
typ == "at+jwt"
&& [ACCESS, APP_PASS, APP_PASS_PRIVILEGED].contains(&scope)
&& jti.is_none()
}
Kind::AccessOrTakendown => {
typ == "at+jwt"
&& [ACCESS, APP_PASS, APP_PASS_PRIVILEGED, TAKENDOWN].contains(&scope)
&& jti.is_none()
}
Kind::Refresh => typ == "refresh+jwt" && scope == REFRESH && jti.is_some(),
};
if !right || text("aud") != Some(self.aud.as_str()) {
return invalid_token();
}
if !expired_ok && self.now() >= exp {
return expired();
}
crate::ops::verified(did);
Ok(Token {
did: did.to_string(),
scope: scope.to_string(),
jti,
oauth: false,
})
}
/// An access token of a session of `scope`, and a refresh token of session `jti`, made at `now`.
fn tokens(&self, did: &str, scope: &str, jti: &str, now: u64) -> (String, String) {
let access = json!({ "scope": scope, "sub": did, "aud": self.aud, "iat": now, "exp": now + ACCESS_LIFE });
let refresh = json!({ "scope": REFRESH, "sub": did, "aud": self.aud, "jti": jti, "iat": now, "exp": now + REFRESH_LIFE });
(
self.sign("at+jwt", &access),
self.sign("refresh+jwt", &refresh),
)
}
/// An account's sessions and app passwords.
fn keep(&self, did: &str) -> Arc<Mutex<Keep>> {
if let Some(k) = read(&self.keeps).get(did) {
return k.clone();
}
write(&self.keeps)
.entry(did.to_string())
.or_default()
.clone()
}
/// An account's sessions and app passwords, as its entries of the
/// service log leave them, without the sessions past their expiry at
/// `now`: what an account loaded has (`directory`).
pub fn put(&self, did: &str, mut keep: Keep, now: u64) {
keep.prune(now);
write(&self.keeps).insert(did.to_string(), Arc::new(Mutex::new(keep)));
}
/// Start a session of an account's, made with its password or, given
/// `app_password`, the digest of what may be an app password of its:
/// logged after `before`, in one frame. Answers its access and refresh
/// tokens and the frame, or None if `app_password` is none of the
/// account's.
pub fn start(
&self,
log: &Wal,
did: &str,
app_password: Option<&[u8; 32]>,
before: Vec<Json>,
) -> std::io::Result<Option<(String, String, u64)>> {
let (id, now) = (new_id(), self.now());
let keep = self.keep(did);
let mut k = lock(&keep);
k.prune(now);
let (app, scope) = match app_password {
None => (None, ACCESS),
Some(digest) => {
let Some(p) = k.app_password(digest) else {
return Ok(None);
};
(
Some(p.name.clone()),
if p.privileged {
APP_PASS_PRIVILEGED
} else {
APP_PASS
},
)
}
};
let session = json!({ "t": "session", "did": did, "id": id, "app": app, "scope": scope, "exp": now + REFRESH_LIFE });
let n = change(log, &mut k, did, before, session)?;
drop(k);
let (access, refresh) = self.tokens(did, scope, &id, now);
Ok(Some((access, refresh, n)))
}
/// Whether `digest` is that of one of the account's app passwords.
pub fn has_app_password(&self, did: &str, digest: &[u8; 32]) -> bool {
lock(&self.keep(did)).app_password(digest).is_some()
}
/// End every session an account has, as `deleteSession` ends one, logged
/// after `before`, in one frame. The keep changes only once the frame is
/// written. Answers the frame.
pub fn end_all(&self, log: &Wal, did: &str, mut before: Vec<Json>) -> std::io::Result<u64> {
let keep = self.keep(did);
let mut k = lock(&keep);
let ended: Vec<Json> = k
.sessions
.keys()
.map(|id| json!({ "t": "endSession", "did": did, "id": id }))
.collect();
before.extend(ended);
let n = log.append(&before)?;
k.sessions.clear();
Ok(n)
}
/// Delete every app password an account has, keeping the sessions made
/// with them, logged after `before`, in one frame, as a deactivation
/// with an OAuth token does (`spec/LIFECYCLE.md`). The keep changes only
/// once the frame is written. Answers the frame.
pub fn drop_app_passwords(
&self,
log: &Wal,
did: &str,
mut before: Vec<Json>,
) -> std::io::Result<u64> {
let keep = self.keep(did);
let mut k = lock(&keep);
if k.passwords.is_empty() {
return log.append(&before);
}
let drop = json!({ "t": "dropAppPasswords", "did": did });
let mut next = k.clone();
next.apply(&drop)
.unwrap_or_else(|why| panic!("a change made under its account's lock: {why}"));
before.push(drop);
let n = log.append(&before)?;
*k = next;
Ok(n)
}
/// The tokens of a taken-down account's session, which is not kept: an
/// access token of scope `com.atproto.takendown`, and a refresh token
/// whose session is none, so that refreshing with it ends no sooner than
/// at its account's state.
pub fn takendown_tokens(&self, did: &str) -> (String, String) {
self.tokens(did, TAKENDOWN, &new_id(), self.now())
}
/// Forget a deleted account's sessions and app passwords, logged with its deletion.
pub fn forget(&self, did: &str) {
write(&self.keeps).remove(did);
}
/// Each account's keep, to compare across restarts and compactions.
#[cfg(test)]
pub fn snapshot(&self) -> std::collections::BTreeMap<String, Keep> {
read(&self.keeps)
.iter()
.map(|(did, k)| (did.clone(), lock(k).clone()))
.filter(|(_, k)| *k != Keep::default())
.collect()
}
/// How many sessions an account keeps.
#[cfg(test)]
pub fn count(&self, did: &str) -> usize {
lock(&self.keep(did)).sessions.len()
}
}
pub(crate) fn handler(nsid: &str) -> Option<Handler> {
Some(match nsid {
"com.atproto.server.refreshSession" => {
Handler::Authed(refresh_token, |s, t, _| Box::pin(refresh_session(s, t)))
}
"com.atproto.server.deleteSession" => {
Handler::Authed(ending_token, |s, t, _| Box::pin(delete_session(s, t)))
}
"com.atproto.server.createAppPassword" => Handler::Authed(full_access_token, |s, t, b| {
Box::pin(create_app_password(s, t, b))
}),
"com.atproto.server.listAppPasswords" => Handler::Query(list_app_passwords),
"com.atproto.server.revokeAppPassword" => Handler::Authed(access_token, |s, t, b| {
Box::pin(revoke_app_password(s, t, b))
}),
_ => return None,
})
}
fn auth_missing<T>() -> Result<T, XrpcError> {
err(401, "AuthMissing", "Authentication Required")
}
pub(crate) fn expired<T>() -> Result<T, XrpcError> {
err(400, "ExpiredToken", "Token has expired")
}
/// A token checked, its account loaded if there is one: what is kept of an
/// account, its sessions, app passwords and preferences among it, is held
/// from then on.
fn known(s: &Service, t: Token) -> Token {
s.account(&t.did);
t
}
/// An access token, as every method that takes a token but
/// `refreshSession` and `deleteSession` takes one: an OAuth access token
/// too, once its call passed `scopes::look`.
pub(crate) fn access_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
match b {
Bearer::None => auth_missing(),
Bearer::Token(t) => Ok(known(s, s.sessions.check(t, Kind::Access, false)?)),
Bearer::OAuth(g) => Ok(known(
s,
Token {
did: g.did.clone(),
scope: g.scope.text().to_string(),
jti: None,
oauth: true,
},
)),
Bearer::Basic(_) | Bearer::DPoP(_) | Bearer::Malformed => invalid_token(),
}
}
/// An access token, or a taken-down account's, as `deactivateAccount` and
/// the sync reads of a repository's own account take.
pub(crate) fn takendown_ok_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
match b {
Bearer::None => auth_missing(),
Bearer::Token(t) => Ok(known(
s,
s.sessions.check(t, Kind::AccessOrTakendown, false)?,
)),
Bearer::OAuth(_) => access_token(s, b),
Bearer::Basic(_) | Bearer::DPoP(_) | Bearer::Malformed => invalid_token(),
}
}
/// The token `deactivateAccount` takes: of a session made with the account's
/// password, or of a taken-down account's; not an app password's.
pub(crate) fn deactivating_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
let t = takendown_ok_token(s, b)?;
if !matches!(b, Bearer::OAuth(_)) && t.scope != ACCESS && t.scope != TAKENDOWN {
return invalid_token();
}
Ok(t)
}
/// An access token of a session made with the account's password, not an
/// app password, as `createAppPassword` and `getAccountInviteCodes` take.
pub(crate) fn full_access_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
let t = access_token(s, b)?;
if t.scope != ACCESS {
return invalid_token();
}
Ok(t)
}
/// A refresh token, by `Bearer` alone: a `Basic` or `DPoP` header is as none.
fn refresh(s: &Service, b: Bearer, expired_ok: bool) -> Result<Token, XrpcError> {
match b {
Bearer::None | Bearer::Basic(_) | Bearer::DPoP(_) | Bearer::OAuth(_) => auth_missing(),
Bearer::Token(t) => Ok(known(s, s.sessions.check(t, Kind::Refresh, expired_ok)?)),
Bearer::Malformed => invalid_token(),
}
}
fn refresh_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
refresh(s, b, false)
}
/// A refresh token for `deleteSession`, which takes one past its `exp` all the same.
fn ending_token(s: &Service, b: Bearer) -> Result<Token, XrpcError> {
refresh(s, b, true)
}
async fn refresh_session(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let Some(account) = s.account(&t.did) else {
return invalid_token();
};
let id = t.jti.unwrap_or_default();
let now = s.sessions.now();
let (next, scope, n) = {
let keep = s.sessions.keep(&t.did);
let mut k = lock(&keep);
k.prune(now);
let Some(old) = k.sessions.get(&id) else {
return expired();
};
let next = old.next.clone().unwrap_or_else(new_id);
let exp = old.exp.min(now + GRACE);
let scope = old.scope.clone();
let unchanged =
old.next.as_ref() == Some(&next) && old.exp == exp && k.sessions.contains_key(&next);
// What this answers may have been logged by another refresh: it is
// answered once that is on disk.
let n = if unchanged {
s.log.written()
} else {
let entry = json!({ "t": "refresh", "did": t.did, "id": id, "next": next, "exp": exp, "nextExp": now + REFRESH_LIFE });
change(&s.log, &mut k, &t.did, vec![], entry).or_else(not_logged)?
};
(next, scope, n)
};
durable(s.log.clone(), n).await?;
let (access, refresh) = s.sessions.tokens(&t.did, &scope, &next, now);
let mut out = session_json(&account);
out["accessJwt"] = json!(access);
out["refreshJwt"] = json!(refresh);
Ok(Resp::Json(out))
}
async fn delete_session(s: Shared, t: Token) -> Result<Resp, XrpcError> {
let id = t.jti.unwrap_or_default();
let n = {
let keep = s.sessions.keep(&t.did);
let mut k = lock(&keep);
k.prune(s.sessions.now());
if k.sessions.contains_key(&id) {
change(
&s.log,
&mut k,
&t.did,
vec![],
json!({ "t": "endSession", "did": t.did, "id": id }),
)
.or_else(not_logged)?
} else {
s.log.written()
}
};
durable(s.log.clone(), n).await?;
Ok(Resp::Nothing)
}
async fn create_app_password(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let name = required(&b, "name")?.to_string();
let privileged = b.get("privileged").and_then(Json::as_bool).unwrap_or(false);
let password = new_app_password();
let entry = json!({
"t": "appPassword", "did": t.did, "name": name, "hash": hash_app_password(&password),
"createdAt": crate::events::timestamp(), "privileged": privileged,
});
let created_at = entry["createdAt"].clone();
let n = {
let keep = s.sessions.keep(&t.did);
let mut k = lock(&keep);
if k.passwords.len() >= MAX_APP_PASSWORDS {
return err(
400,
"TooManyAppPasswords",
format!("Too many app passwords. Max: {MAX_APP_PASSWORDS}"),
);
}
// As the reference answers a name the account has already.
if k.passwords.iter().any(|p| p.name == name) {
return internal();
}
change(&s.log, &mut k, &t.did, vec![], entry).or_else(not_logged)?
};
durable(s.log.clone(), n).await?;
Ok(Resp::Json(
json!({ "name": name, "password": password, "createdAt": created_at, "privileged": privileged }),
))
}
fn list_app_passwords(
s: &Service,
call: &Call,
shown: &mut Shown,
_: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
let t = access_token(s, call.bearer)?;
let keep = s.sessions.keep(&t.did);
let passwords: Vec<Json> = lock(&keep)
.passwords
.iter()
.rev()
.map(|p| json!({ "name": p.name, "createdAt": p.created_at, "privileged": p.privileged }))
.collect();
shown.0.push((s.log.clone(), s.log.written()));
Ok(Resp::Json(json!({ "passwords": passwords })))
}
async fn revoke_app_password(s: Shared, t: Token, b: Map<String, Json>) -> Result<Resp, XrpcError> {
let name = required(&b, "name")?;
let n = {
let keep = s.sessions.keep(&t.did);
let mut k = lock(&keep);
k.prune(s.sessions.now());
if k.passwords.iter().any(|p| p.name == name) {
change(
&s.log,
&mut k,
&t.did,
vec![],
json!({ "t": "revokeAppPassword", "did": t.did, "name": name }),
)
.or_else(not_logged)?
} else {
s.log.written()
}
};
durable(s.log.clone(), n).await?;
Ok(Resp::Nothing)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::*;
use std::sync::atomic::Ordering::SeqCst;
const LOGIN: &str = "com.atproto.server.createSession";
const GET: &str = "com.atproto.server.getSession";
const REFRESH_SESSION: &str = "com.atproto.server.refreshSession";
const DELETE: &str = "com.atproto.server.deleteSession";
const CREATE_APP: &str = "com.atproto.server.createAppPassword";
const LIST_APP: &str = "com.atproto.server.listAppPasswords";
const REVOKE_APP: &str = "com.atproto.server.revokeAppPassword";
/// A JWT's header and claims.
fn decode(token: &str) -> (Json, Json) {
let parts: Vec<&str> = token.split('.').collect();
assert_eq!(parts.len(), 3, "{token}");
let part = |p: &str| serde_json::from_slice::<Json>(&B64.decode(p).unwrap()).unwrap();
(part(parts[0]), part(parts[1]))
}
fn jti(refresh: &str) -> String {
decode(refresh).1["jti"].as_str().unwrap().to_string()
}
fn tokens(got: &Json) -> (String, String) {
(
got["accessJwt"].as_str().unwrap().to_string(),
got["refreshJwt"].as_str().unwrap().to_string(),
)
}
async fn login(s: &Shared, id: &str, pw: &str) -> Result<(String, String), String> {
Ok(tokens(
&call(s, LOGIN, None, json!({ "identifier": id, "password": pw })).await?,
))
}
async fn refresh(s: &Shared, token: &str) -> Result<(String, String), String> {
Ok(tokens(
&call(s, REFRESH_SESSION, Some(token), Json::Null).await?,
))
}
fn put(did: &str, rkey: &str) -> Json {
json!({ "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record(1) })
}
fn scope(access: &str) -> String {
decode(access).1["scope"].as_str().unwrap().to_string()
}
/// Every token is a JWT with exactly the claims `SESSIONS.md` lists.
#[tokio::test]
async fn tokens_are_jwts() {
let plc = plc().await;
let dir = scratch("jwt-claims");
let s = open(&dir, &plc);
let before = s.sessions.now();
let made = call(
&s,
"com.atproto.server.createAccount",
None,
json!({ "handle": "alice.test", "email": "a@mail.com", "password": "pw" }),
)
.await
.unwrap();
let did = made["did"].as_str().unwrap().to_string();
let from_login = login(&s, "alice.test", "pw").await.unwrap();
let refreshed = refresh(&s, &from_login.1).await.unwrap();
let after = s.sessions.now();
let mut jtis = Vec::new();
for (access, refresh) in [tokens(&made), from_login, refreshed] {
let (h, c) = decode(&access);
assert_eq!(h["typ"], "at+jwt");
assert_eq!(h["alg"], "HS256");
let mut keys: Vec<&String> = c.as_object().unwrap().keys().collect();
keys.sort();
assert_eq!(keys, ["aud", "exp", "iat", "scope", "sub"]);
assert_eq!(
(c["scope"].as_str(), c["sub"].as_str(), c["aud"].as_str()),
(Some(ACCESS), Some(did.as_str()), Some("did:web:localhost"))
);
let iat = c["iat"].as_u64().unwrap();
assert!((before..=after).contains(&iat));
assert_eq!(c["exp"].as_u64().unwrap() - iat, 7200);
let (h, c) = decode(&refresh);
assert_eq!(h["typ"], "refresh+jwt");
let mut keys: Vec<&String> = c.as_object().unwrap().keys().collect();
keys.sort();
assert_eq!(keys, ["aud", "exp", "iat", "jti", "scope", "sub"]);
assert_eq!(
(c["scope"].as_str(), c["sub"].as_str(), c["aud"].as_str()),
(Some(REFRESH), Some(did.as_str()), Some("did:web:localhost"))
);
let iat = c["iat"].as_u64().unwrap();
assert!((before..=after).contains(&iat));
assert_eq!(c["exp"].as_u64().unwrap() - iat, 7_776_000);
jtis.push(jti(&refresh));
}
jtis.sort();
jtis.dedup();
assert_eq!(jtis.len(), 3);
let _ = std::fs::remove_dir_all(&dir);
}
/// The wrong token, or the wrong header, is refused, before the input is looked at.
#[tokio::test]
async fn wrong_tokens() {
let plc = plc().await;
let dir = scratch("jwt-wrong");
let s = open(&dir, &plc);
let (did, access) = create(&s, "alice").await;
let (_, refresh_jwt) = login(&s, "alice.test", "alice-pw").await.unwrap();
let bad = |e: &str| Err::<Json, String>(e.to_string());
// A refresh token where an access token is wanted, and the other way round.
for (nsid, body) in [
(GET, json!({})),
("com.atproto.repo.putRecord", put(&did, "x")),
(CREATE_APP, json!({ "name": "x" })),
(LIST_APP, json!({})),
(REVOKE_APP, json!({ "name": "x" })),
] {
assert_eq!(
call(&s, nsid, Some(&refresh_jwt), body).await,
bad("InvalidToken"),
"{nsid}"
);
}
for nsid in [REFRESH_SESSION, DELETE] {
assert_eq!(
call(&s, nsid, Some(&access), Json::Null).await,
bad("InvalidToken"),
"{nsid}"
);
assert_eq!(
call(&s, nsid, None, Json::Null).await,
bad("AuthMissing"),
"{nsid}"
);
}
// Claims changed after signing, `alg: none`, and a token never given out.
let parts: Vec<&str> = access.split('.').collect();
let (_, mut claims) = decode(&access);
claims["sub"] = json!("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa");
let changed = format!(
"{}.{}.{}",
parts[0],
B64.encode(claims.to_string()),
parts[2]
);
let none_header = B64.encode(json!({ "typ": "at+jwt", "alg": "none" }).to_string());
for forged in [
changed,
format!("{none_header}.{}.", parts[1]),
format!("{none_header}.{}.{}", parts[1], parts[2]),
"never-given-out".into(),
] {
assert_eq!(
call(&s, GET, Some(&forged), json!({})).await,
bad("InvalidToken"),
"{forged}"
);
assert_eq!(
call(
&s,
"com.atproto.repo.putRecord",
Some(&forged),
put(&did, "x")
)
.await,
bad("InvalidToken")
);
}
// The header's scheme in any case; Basic, three words or another scheme.
let raw = |nsid: &'static str, header: String, body: &'static str| {
let s = s.clone();
async move {
call_raw(&s, nsid, Bearer::of(Some(&header)), &[], body)
.await
.map(|_| ())
}
};
assert_eq!(raw(GET, format!("bearer {access}"), "").await, Ok(()));
assert_eq!(raw(LIST_APP, format!("BeArEr {access}"), "").await, Ok(()));
assert_eq!(
raw(GET, format!("Basic {access}"), "").await,
Err("InvalidToken".into())
);
assert_eq!(
raw(CREATE_APP, format!("Basic {access}"), "{}").await,
Err("InvalidToken".into())
);
for nsid in [REFRESH_SESSION, DELETE] {
assert_eq!(
raw(nsid, format!("Basic {refresh_jwt}"), "").await,
Err("AuthMissing".into()),
"{nsid}"
);
assert_eq!(
raw(nsid, format!("DPoP {refresh_jwt}"), "").await,
Err("AuthMissing".into()),
"{nsid}"
);
assert_eq!(
raw(nsid, format!("Bearer {refresh_jwt} x"), "").await,
Err("InvalidToken".into()),
"{nsid}"
);
assert_eq!(
raw(nsid, format!("Bearer {refresh_jwt}"), "").await,
Err("InvalidToken".into()),
"{nsid}"
);
assert_eq!(
raw(nsid, format!("Token {refresh_jwt}"), "").await,
Err("InvalidToken".into()),
"{nsid}"
);
// A body, after the token is checked.
assert_eq!(
raw(nsid, format!("Bearer {access}"), "{}").await,
Err("InvalidToken".into()),
"{nsid}"
);
assert_eq!(
raw(nsid, format!("Bearer {refresh_jwt}"), "{}").await,
Err("InvalidRequest".into()),
"{nsid}"
);
}
for header in [
format!("Bearer {access} x"),
"Bearer".into(),
String::new(),
format!("DPoP {access}"),
] {
assert_eq!(
raw(GET, header.clone(), "").await,
Err("InvalidToken".into()),
"{header}"
);
}
assert_eq!(
raw(REFRESH_SESSION, format!("bearer {refresh_jwt}"), "").await,
Ok(())
);
// The token before the input.
assert_eq!(
call(&s, CREATE_APP, Some("forged"), json!({ "name": 5 })).await,
bad("InvalidToken")
);
assert_eq!(
call(&s, CREATE_APP, None, json!({ "name": 5 })).await,
bad("AuthMissing")
);
assert_eq!(
call(&s, CREATE_APP, Some(&access), json!({ "name": 5 })).await,
bad("InvalidRequest")
);
assert_eq!(
call(&s, REVOKE_APP, Some(&refresh_jwt), json!({})).await,
bad("InvalidToken")
);
assert_eq!(
call(&s, REVOKE_APP, Some(&access), json!({})).await,
bad("InvalidRequest")
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Tokens past their `exp`: the wrong kind is `InvalidToken` first, and
/// `deleteSession` takes an expired refresh token.
#[tokio::test]
async fn expiry() {
let plc = plc().await;
let dir = scratch("jwt-expiry");
let s = open(&dir, &plc);
// The clock stands still but for the skew, so a token's `exp` is reached exactly.
s.sessions.freeze();
let (did, access) = create(&s, "alice").await;
let (_, r0) = login(&s, "alice.test", "alice-pw").await.unwrap();
s.sessions.skew.store(ACCESS_LIFE - 1, SeqCst);
call(&s, GET, Some(&access), json!({})).await.unwrap();
s.sessions.skew.store(ACCESS_LIFE, SeqCst);
assert_eq!(
call(&s, GET, Some(&access), json!({})).await,
Err("ExpiredToken".into())
);
assert_eq!(
call(
&s,
"com.atproto.repo.putRecord",
Some(&access),
put(&did, "x")
)
.await,
Err("ExpiredToken".into())
);
assert_eq!(
call(&s, LIST_APP, Some(&access), json!({})).await,
Err("ExpiredToken".into())
);
assert_eq!(
call(&s, REFRESH_SESSION, Some(&access), Json::Null).await,
Err("InvalidToken".into())
);
let (a1, r1) = refresh(&s, &r0).await.unwrap();
call(&s, GET, Some(&a1), json!({})).await.unwrap();
// Past the refresh token's 90 days.
s.sessions.skew.store(ACCESS_LIFE + REFRESH_LIFE, SeqCst);
assert_eq!(refresh(&s, &r1).await, Err("ExpiredToken".into()));
assert_eq!(
call(&s, GET, Some(&r1), json!({})).await,
Err("InvalidToken".into())
);
assert_eq!(
call(&s, DELETE, Some(&r1), Json::Null).await,
Ok(Json::Null)
);
// That ended its session.
s.sessions.skew.store(ACCESS_LIFE, SeqCst);
assert_eq!(refresh(&s, &r1).await, Err("ExpiredToken".into()));
let _ = std::fs::remove_dir_all(&dir);
}
/// A refresh answers the session's successor, the same one each time, and
/// the old token works for two hours from when it was first used.
#[tokio::test]
async fn rotation_and_grace() {
let plc = plc().await;
let dir = scratch("jwt-rotation");
let s = open(&dir, &plc);
s.sessions.freeze();
create(&s, "alice").await;
let (_, r0) = login(&s, "alice.test", "alice-pw").await.unwrap();
let (_, r1) = refresh(&s, &r0).await.unwrap();
assert_ne!(jti(&r1), jti(&r0));
assert_eq!(jti(&refresh(&s, &r0).await.unwrap().1), jti(&r1));
let (_, r2) = refresh(&s, &r1).await.unwrap();
assert!(jti(&r2) != jti(&r0) && jti(&r2) != jti(&r1));
assert_eq!(jti(&refresh(&s, &r1).await.unwrap().1), jti(&r2));
s.sessions.skew.store(GRACE - 1, SeqCst);
assert_eq!(jti(&refresh(&s, &r0).await.unwrap().1), jti(&r1));
s.sessions.skew.store(GRACE, SeqCst);
assert_eq!(refresh(&s, &r0).await, Err("ExpiredToken".into()));
assert_eq!(refresh(&s, &r1).await, Err("ExpiredToken".into()));
let (_, r3) = refresh(&s, &r2).await.unwrap();
// Refreshing again within the grace does not lengthen it.
s.sessions.skew.store(GRACE + GRACE / 2, SeqCst);
assert_eq!(jti(&refresh(&s, &r2).await.unwrap().1), jti(&r3));
s.sessions.skew.store(2 * GRACE, SeqCst);
assert_eq!(refresh(&s, &r2).await, Err("ExpiredToken".into()));
refresh(&s, &r3).await.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// Refreshes at once with one token all succeed, with tokens of one session.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_refreshes() {
let plc = plc().await;
let dir = scratch("jwt-concurrent");
let s = open(&dir, &plc);
let (did, _) = create(&s, "alice").await;
let (_, r0) = login(&s, "alice.test", "alice-pw").await.unwrap();
let calls: Vec<_> = (0..16)
.map(|_| {
let (s, r0) = (s.clone(), r0.clone());
tokio::spawn(async move { refresh(&s, &r0).await })
})
.collect();
let mut jtis = Vec::new();
for c in calls {
jtis.push(jti(&c.await.unwrap().unwrap().1));
}
jtis.dedup();
assert_eq!(jtis.len(), 1);
// The session createAccount made, the login's, and its one successor.
assert_eq!(s.sessions.snapshot()[&did].sessions.len(), 3);
let _ = std::fs::remove_dir_all(&dir);
}
/// `deleteSession` ends that session alone, whether or not it is kept.
#[tokio::test]
async fn delete() {
let plc = plc().await;
let dir = scratch("jwt-delete");
let s = open(&dir, &plc);
create(&s, "alice").await;
let (a0, r0) = login(&s, "alice.test", "alice-pw").await.unwrap();
let (_, other) = login(&s, "alice.test", "alice-pw").await.unwrap();
let (_, r1) = refresh(&s, &r0).await.unwrap();
assert_eq!(
call(&s, DELETE, Some(&r0), Json::Null).await,
Ok(Json::Null)
);
assert_eq!(refresh(&s, &r0).await, Err("ExpiredToken".into()));
assert_eq!(
call(&s, DELETE, Some(&r0), Json::Null).await,
Ok(Json::Null)
);
// Its access token, its successor and other sessions carry on.
call(&s, GET, Some(&a0), json!({})).await.unwrap();
let (_, r2) = refresh(&s, &r1).await.unwrap();
refresh(&s, &other).await.unwrap();
// An ended successor is kept again by its predecessor's grace.
assert_eq!(
call(&s, DELETE, Some(&r2), Json::Null).await,
Ok(Json::Null)
);
assert_eq!(refresh(&s, &r2).await, Err("ExpiredToken".into()));
let (_, again) = refresh(&s, &r1).await.unwrap();
assert_eq!(jti(&again), jti(&r2));
refresh(&s, &r2).await.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
fn is_app_password_form(p: &str) -> bool {
let groups: Vec<&str> = p.split('-').collect();
groups.len() == 4
&& groups.iter().all(|g| {
g.len() == 4
&& g.bytes()
.all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
})
}
/// App passwords made, listed, logged in with and revoked, and what their sessions may do.
#[tokio::test]
async fn app_passwords() {
let plc = plc().await;
let dir = scratch("app-passwords");
let s = open(&dir, &plc);
let (did, full) = create(&s, "alice").await;
let (_, bob) = create(&s, "bob").await;
let phone = call(&s, CREATE_APP, Some(&full), json!({ "name": "phone" }))
.await
.unwrap();
let mut keys: Vec<&String> = phone.as_object().unwrap().keys().collect();
keys.sort();
assert_eq!(keys, ["createdAt", "name", "password", "privileged"]);
assert_eq!(
(&phone["name"], &phone["privileged"]),
(&json!("phone"), &json!(false))
);
let pw = phone["password"].as_str().unwrap().to_string();
assert!(is_app_password_form(&pw), "{pw}");
assert!(phone["createdAt"].as_str().unwrap().ends_with('Z'));
let odd = call(
&s,
CREATE_APP,
Some(&full),
json!({ "name": "", "privileged": true }),
)
.await
.unwrap();
assert_eq!(
(&odd["name"], &odd["privileged"]),
(&json!(""), &json!(true))
);
assert_ne!(odd["password"], phone["password"]);
assert_eq!(
call(&s, CREATE_APP, Some(&full), json!({ "name": "phone" })).await,
Err("InternalServerError".into())
);
call(&s, CREATE_APP, Some(&bob), json!({ "name": "phone" }))
.await
.unwrap();
let listed = call(&s, LIST_APP, Some(&full), json!({})).await.unwrap();
assert_eq!(
listed,
json!({ "passwords": [
{ "name": "", "createdAt": odd["createdAt"], "privileged": true },
{ "name": "phone", "createdAt": phone["createdAt"], "privileged": false },
] })
);
// Logging in with one, by handle, email or DID, exactly as given.
for id in ["alice.test", "alice@mail.com", did.as_str()] {
let (access, _) = login(&s, id, &pw).await.unwrap();
assert_eq!(scope(&access), APP_PASS);
}
for wrong in [pw.to_uppercase(), pw.replace('-', "")] {
assert_eq!(
login(&s, "alice.test", &wrong).await,
Err("AuthenticationRequired".into())
);
}
assert_eq!(
login(&s, "bob.test", &pw).await,
Err("AuthenticationRequired".into())
);
let (privileged, _) = login(&s, "alice.test", odd["password"].as_str().unwrap())
.await
.unwrap();
assert_eq!(scope(&privileged), APP_PASS_PRIVILEGED);
// Its session does what the account's own do, but make app passwords.
let (app, app_refresh) = login(&s, "alice.test", &pw).await.unwrap();
for token in [&app, &privileged] {
assert_eq!(
call(&s, CREATE_APP, Some(token), json!({ "name": "new" })).await,
Err("InvalidToken".into())
);
assert_eq!(
call(&s, CREATE_APP, Some(token), json!({})).await,
Err("InvalidToken".into())
);
call(&s, LIST_APP, Some(token), json!({})).await.unwrap();
}
assert_eq!(
call(&s, GET, Some(&app), json!({})).await.unwrap()["did"],
json!(did)
);
call(
&s,
"com.atproto.repo.putRecord",
Some(&app),
put(&did, "by-app"),
)
.await
.unwrap();
let (app2, app_refresh2) = refresh(&s, &app_refresh).await.unwrap();
assert_eq!(scope(&app2), APP_PASS);
let (_, kept) = login(&s, "alice.test", "alice-pw").await.unwrap();
// Revoked with its own session: its sessions end, those refreshed from them too.
assert_eq!(
call(&s, REVOKE_APP, Some(&app), json!({ "name": "phone" })).await,
Ok(Json::Null)
);
assert_eq!(refresh(&s, &app_refresh).await, Err("ExpiredToken".into()));
assert_eq!(refresh(&s, &app_refresh2).await, Err("ExpiredToken".into()));
call(&s, GET, Some(&app2), json!({})).await.unwrap();
assert_eq!(
login(&s, "alice.test", &pw).await,
Err("AuthenticationRequired".into())
);
refresh(&s, &kept).await.unwrap();
assert_eq!(
call(&s, REVOKE_APP, Some(&full), json!({ "name": "nothing" })).await,
Ok(Json::Null)
);
assert_eq!(
call(&s, REVOKE_APP, Some(&full), json!({ "name": "phone" })).await,
Ok(Json::Null)
);
assert_eq!(
call(&s, LIST_APP, Some(&full), json!({})).await.unwrap()["passwords"]
.as_array()
.unwrap()
.len(),
1
);
// Bob's of the same name is his own.
assert_eq!(
call(&s, LIST_APP, Some(&bob), json!({})).await.unwrap()["passwords"][0]["name"],
json!("phone")
);
// Made again after its revocation.
call(&s, CREATE_APP, Some(&full), json!({ "name": "phone" }))
.await
.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// Of several at once with the same name, one is made.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_app_passwords() {
let plc = plc().await;
let dir = scratch("app-concurrent");
let s = open(&dir, &plc);
let (_, full) = create(&s, "alice").await;
let calls: Vec<_> = (0..12)
.map(|_| {
let (s, full) = (s.clone(), full.clone());
tokio::spawn(async move {
call(&s, CREATE_APP, Some(&full), json!({ "name": "same" })).await
})
})
.collect();
let mut made = 0;
for c in calls {
match c.await.unwrap() {
Ok(_) => made += 1,
Err(e) => assert_eq!(e, "InternalServerError"),
}
}
assert_eq!(made, 1);
assert_eq!(
call(&s, LIST_APP, Some(&full), json!({})).await.unwrap()["passwords"]
.as_array()
.unwrap()
.len(),
1
);
let _ = std::fs::remove_dir_all(&dir);
}
/// An account with no password logs in with its app passwords, by handle or DID, not email.
#[tokio::test]
async fn no_password_app_passwords() {
let plc = plc().await;
let dir = scratch("app-nopw");
let s = open(&dir, &plc);
let made = call(
&s,
"com.atproto.server.createAccount",
None,
json!({ "handle": "nopw.test", "email": "nopw@mail.com" }),
)
.await
.unwrap();
let (did, first) = (
made["did"].as_str().unwrap(),
made["accessJwt"].as_str().unwrap(),
);
let pw = call(&s, CREATE_APP, Some(first), json!({ "name": "only" }))
.await
.unwrap()["password"]
.as_str()
.unwrap()
.to_string();
for id in ["nopw.test", did] {
let (access, _) = login(&s, id, &pw).await.unwrap();
let got = call(&s, GET, Some(&access), json!({})).await.unwrap();
assert_eq!(got["did"], json!(did));
assert!(got.get("email").is_none());
}
assert_eq!(
login(&s, "nopw@mail.com", &pw).await,
Err("AuthenticationRequired".into())
);
let _ = std::fs::remove_dir_all(&dir);
}
/// Sessions, their refreshes and ends, app passwords and their
/// revocations all survive a restart, and so does the secret.
#[tokio::test]
async fn restart_keeps_sessions() {
let plc = plc().await;
let dir = scratch("sessions-restart");
let s = open(&dir, &plc);
let (_, full) = create(&s, "alice").await;
let (_, r0) = login(&s, "alice.test", "alice-pw").await.unwrap();
let (_, r1) = refresh(&s, &r0).await.unwrap();
let (_, ended) = login(&s, "alice.test", "alice-pw").await.unwrap();
call(&s, DELETE, Some(&ended), Json::Null).await.unwrap();
let pw = call(
&s,
CREATE_APP,
Some(&full),
json!({ "name": "phone", "privileged": true }),
)
.await
.unwrap()["password"]
.as_str()
.unwrap()
.to_string();
let gone = call(&s, CREATE_APP, Some(&full), json!({ "name": "gone" }))
.await
.unwrap()["password"]
.as_str()
.unwrap()
.to_string();
let (_, app_refresh) = login(&s, "alice.test", &pw).await.unwrap();
let (_, revoked) = login(&s, "alice.test", &gone).await.unwrap();
call(&s, REVOKE_APP, Some(&full), json!({ "name": "gone" }))
.await
.unwrap();
let listed = call(&s, LIST_APP, Some(&full), json!({})).await.unwrap();
let before = s.sessions.snapshot();
drop(s);
let s = open(&dir, &plc);
assert_eq!(s.sessions.snapshot(), before);
assert_eq!(
call(&s, LIST_APP, Some(&full), json!({})).await.unwrap(),
listed
);
assert_eq!(jti(&refresh(&s, &r0).await.unwrap().1), jti(&r1));
assert_eq!(refresh(&s, &ended).await, Err("ExpiredToken".into()));
assert_eq!(refresh(&s, &revoked).await, Err("ExpiredToken".into()));
let (app, _) = refresh(&s, &app_refresh).await.unwrap();
assert_eq!(scope(&app), APP_PASS_PRIVILEGED);
login(&s, "alice.test", &pw).await.unwrap();
assert_eq!(
login(&s, "alice.test", &gone).await,
Err("AuthenticationRequired".into())
);
// Without its secret, the server does not start.
drop(s);
std::fs::remove_file(dir.join(KEY_FILE)).unwrap();
assert!(try_open(&dir, &plc).err().unwrap().contains(KEY_FILE));
let _ = std::fs::remove_dir_all(&dir);
}
/// An app password is found by one digest of what is given, among all the
/// account has, exactly as given.
#[test]
fn app_password_hashes() {
let mut k = Keep::default();
let pws: Vec<String> = (0..3).map(|_| new_app_password()).collect();
for (i, pw) in pws.iter().enumerate() {
assert!(is_app_password_form(pw), "{pw}");
let e = json!({ "t": "appPassword", "did": "d", "name": format!("p{i}"), "hash": hash_app_password(pw), "createdAt": "c", "privileged": false });
k.apply(&e).unwrap();
}
for (i, pw) in pws.iter().enumerate() {
assert_eq!(
k.app_password(&app_password_digest(pw))
.map(|p| p.name.clone()),
Some(format!("p{i}"))
);
assert!(
k.app_password(&app_password_digest(&pw.to_uppercase()))
.is_none()
);
}
assert!(k.app_password(&app_password_digest("")).is_none());
k.passwords[0].hash = "nonsense".into();
assert!(k.app_password(&app_password_digest(&pws[0])).is_none());
}
/// Sessions past their expiry are dropped when the account's sessions
/// are next touched, and as the account is loaded, with nothing logged
/// of it.
#[tokio::test]
async fn expired_sessions_are_dropped() {
let plc = plc().await;
let dir = scratch("sessions-expire");
let s = open(&dir, &plc);
let (did, _) = create(&s, "alice").await;
let (_, old) = login(&s, "alice.test", "alice-pw").await.unwrap();
assert_eq!(s.sessions.count(&did), 2);
s.sessions.skew.store(10 * 24 * 60 * 60, SeqCst);
let (_, young) = login(&s, "alice.test", "alice-pw").await.unwrap();
assert_eq!(s.sessions.count(&did), 3);
// The first two expire; the third does not.
s.sessions.skew.store(REFRESH_LIFE + 60, SeqCst);
assert_eq!(refresh(&s, &old).await, Err("ExpiredToken".into()));
let log_len = s.log.len() as usize;
// Touched: they are dropped, and only the new session is logged.
login(&s, "alice.test", "alice-pw").await.unwrap();
assert_eq!(s.sessions.count(&did), 2);
let logged =
pds_store::scan(&std::fs::read(crate::log::accounts_log(&dir)).unwrap()[log_len..])
.unwrap()
.0;
assert_eq!(
logged
.iter()
.flatten()
.map(|e| e["t"].as_str().unwrap())
.collect::<Vec<_>>(),
["session"]
);
drop(s);
// And as its account is loaded: the server's clock is as it was,
// then moved on.
let s = open(&dir, &plc);
assert_eq!(s.sessions.count(&did), 4);
s.sessions.skew.store(REFRESH_LIFE + 60, SeqCst);
let keep = s.sessions.snapshot().remove(&did).unwrap();
s.sessions.put(&did, keep, s.sessions.now());
assert_eq!(s.sessions.count(&did), 2);
refresh(&s, &young).await.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// An account keeps at most `MAX_SESSIONS`: one more drops the refreshed
/// one in its grace first, the one that expires soonest, and of those
/// that expire in the same second the oldest; a dropped session's token
/// is `ExpiredToken`, after a restart too.
#[tokio::test]
async fn sessions_are_capped() {
let plc = plc().await;
let dir = scratch("sessions-cap");
let s = open(&dir, &plc);
let made = call(
&s,
"com.atproto.server.createAccount",
None,
json!({ "handle": "alice.test", "email": "a@mail.com", "password": "pw" }),
)
.await
.unwrap();
let did = made["did"].as_str().unwrap().to_string();
// The account's session, then a hundred refreshes, as fast as they go.
let mut chain = vec![tokens(&made).1];
for _ in 0..MAX_SESSIONS {
let next = refresh(&s, chain.last().unwrap()).await.unwrap().1;
chain.push(next);
}
assert_eq!(s.sessions.count(&did), MAX_SESSIONS);
assert_eq!(refresh(&s, &chain[0]).await, Err("ExpiredToken".into()));
refresh(&s, &chain[1]).await.unwrap();
let snapshot = s.sessions.snapshot();
drop(s);
let s = open(&dir, &plc);
assert_eq!(s.sessions.snapshot(), snapshot);
assert_eq!(refresh(&s, &chain[0]).await, Err("ExpiredToken".into()));
// A new session drops the next oldest refreshed one, after a restart as before.
login(&s, "alice.test", "pw").await.unwrap();
assert_eq!(refresh(&s, &chain[1]).await, Err("ExpiredToken".into()));
refresh(&s, &chain[2]).await.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// An account has at most `MAX_APP_PASSWORDS`: one more is
/// `TooManyAppPasswords`, before its name is checked.
#[tokio::test]
async fn app_passwords_are_capped() {
let plc = plc().await;
let dir = scratch("app-cap");
let s = open(&dir, &plc);
let (_, token) = create(&s, "alice").await;
for i in 0..MAX_APP_PASSWORDS {
call(
&s,
CREATE_APP,
Some(&token),
json!({ "name": format!("p{i}") }),
)
.await
.unwrap();
}
assert_eq!(
call(&s, CREATE_APP, Some(&token), json!({ "name": "one more" })).await,
Err("TooManyAppPasswords".into())
);
assert_eq!(
call(&s, CREATE_APP, Some(&token), json!({ "name": "p0" })).await,
Err("TooManyAppPasswords".into())
);
assert_eq!(
call(&s, CREATE_APP, Some(&token), json!({ "name": 5 })).await,
Err("InvalidRequest".into())
);
call(&s, REVOKE_APP, Some(&token), json!({ "name": "p0" }))
.await
.unwrap();
call(&s, CREATE_APP, Some(&token), json!({ "name": "one more" }))
.await
.unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
/// An app password's session, privileged or not, may change the handle,
/// but not make app passwords.
#[tokio::test]
async fn what_app_password_sessions_may_do() {
let plc = crate::identity::stub::Plc::start().await;
let dir = scratch("app-may");
let s = open(&dir, &plc.url);
let (did, token) = create(&s, "alice").await;
for (i, privileged) in [false, true].into_iter().enumerate() {
let app = call(
&s,
CREATE_APP,
Some(&token),
json!({ "name": format!("a{i}"), "privileged": privileged }),
)
.await
.unwrap();
let (access, _) = login(&s, &did, app["password"].as_str().unwrap())
.await
.unwrap();
assert_eq!(
call(&s, CREATE_APP, Some(&access), json!({ "name": "x" })).await,
Err("InvalidToken".into())
);
assert_eq!(
call(&s, CREATE_APP, Some(&access), json!({ "name": 5 })).await,
Err("InvalidToken".into())
);
let handle = format!("alice{i}.test");
call(
&s,
"com.atproto.identity.updateHandle",
Some(&access),
json!({ "handle": handle }),
)
.await
.unwrap();
}
let _ = std::fs::remove_dir_all(&dir);
}
}