//! Invite codes, as `spec/LIMITS.md` says: the admin's `createInviteCode` //! and `createInviteCodes`, an account's `getAccountInviteCodes`, and the //! codes `createAccount` uses. //! //! Each code made is an `invite` entry in `accounts.log`, and each use of //! one an `inviteUse` entry in the frame of the account it made, so a code //! and its uses survive as accounts do. A `createAccount` holds a use of its //! code from when it checks it until its account is logged or refused, so //! several at once with one code make no more accounts than it has uses left. use crate::sessions::{Bearer, Token, full_access_token}; use crate::{Call, Handler, Resp, Service, Shared, Shown, XrpcError, durable, err, internal}; use base64::Engine; use serde_json::{Map, Value as Json, json}; use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, PoisonError}; /// The kinds of `accounts.log` entry this module keeps. pub(crate) const ENTRIES: &[&str] = &["invite", "inviteUse"]; /// Who the admin is, as a code made by or for the admin names it. const ADMIN: &str = "admin"; pub(crate) fn handler(nsid: &str) -> Option { Some(match nsid { "com.atproto.server.createInviteCode" => { Handler::Authed(admin, |s, _, b| Box::pin(create_invite_code(s, b))) } "com.atproto.server.createInviteCodes" => { Handler::Authed(admin, |s, _, b| Box::pin(create_invite_codes(s, b))) } "com.atproto.server.getAccountInviteCodes" => Handler::Query(get_account_invite_codes), _ => return None, }) } /// A code, as kept. #[derive(Debug, PartialEq, Eq)] struct Code { for_account: String, created_by: String, /// How many accounts may be created with it. available: i64, created_at: String, /// Each use, `(usedBy, usedAt)`, oldest first. uses: Vec<(String, String)>, /// Uses held by `createAccount`s under way. held: i64, } #[derive(Default)] struct State { codes: HashMap, /// Every code, in the order made. order: Vec, /// Each account's codes, in the order made. by_account: HashMap>, } impl State { fn apply(&mut self, e: &Json) -> Result<(), String> { let text = |k: &str| { e[k].as_str() .map(str::to_string) .ok_or_else(|| format!("an entry with no {k}: {e}")) }; match e["t"].as_str() { Some("invite") => { let code = text("code")?; if self.codes.contains_key(&code) { return Err(format!("a second invite code {code}")); } let available = e["available"] .as_i64() .ok_or_else(|| format!("an invite code with no available: {e}"))?; let c = Code { for_account: text("forAccount")?, created_by: text("createdBy")?, available, created_at: text("createdAt")?, uses: vec![], held: 0, }; self.by_account .entry(c.for_account.clone()) .or_default() .push(code.clone()); self.order.push(code.clone()); self.codes.insert(code, c); } Some("inviteUse") => { let code = text("code")?; let c = self .codes .get_mut(&code) .ok_or_else(|| format!("a use of invite code {code}, which was not made"))?; c.uses.push((text("usedBy")?, text("usedAt")?)); } t => return Err(format!("a log entry of no known type: {t:?}")), } Ok(()) } } /// The invite codes the server made, and their uses. #[derive(Default)] pub(crate) struct Invites(Mutex); impl Invites { fn lock(&self) -> MutexGuard<'_, State> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// Replay an entry of `accounts.log` of the kinds in `ENTRIES`. pub fn replay(&self, e: &Json) -> Result<(), String> { self.lock().apply(e) } /// The entries that make these codes again, for a compacted log. pub fn entries(&self) -> Vec { let st = self.lock(); let codes = st.order.iter().map(|code| (code, &st.codes[code])); let made = codes.clone().map(|(code, c)| { json!({ "t": "invite", "code": code, "forAccount": c.for_account, "createdBy": c.created_by, "available": c.available, "createdAt": c.created_at }) }); let used = codes.flat_map(|(code, c)| c.uses.iter().map(move |(by, at)| json!({ "t": "inviteUse", "code": code, "usedBy": by, "usedAt": at }))); made.collect::>() .into_iter() .chain(used.collect::>()) .collect() } /// Hold a use of `code`, if the server made it, exactly as given, and /// fewer accounts were made or are being made with it than its `available`. pub fn hold(s: &Shared, code: &str) -> Option { let mut st = s.invites.lock(); let c = st.codes.get_mut(code)?; if c.uses.len() as i64 + c.held >= c.available { return None; } c.held += 1; Some(Held { s: s.clone(), code: code.to_string(), used: false, }) } /// Every code, to compare across restarts. #[cfg(test)] pub fn snapshot(&self) -> Vec { let st = self.lock(); st.order .iter() .map(|code| format!("{code} {:?}", st.codes[code])) .collect() } } /// A use of a code held for an account being created; let go when dropped, /// unless the account was made with it. pub(crate) struct Held { s: Shared, code: String, used: bool, } impl Held { /// The entry of its use by `did`, at `at`, to log with the account. pub fn entry(&self, did: &str, at: &str) -> Json { json!({ "t": "inviteUse", "code": self.code, "usedBy": did, "usedAt": at }) } /// The account is logged: the use is its. pub fn used(mut self, did: &str, at: &str) { let mut st = self.s.invites.lock(); if let Some(c) = st.codes.get_mut(&self.code) { c.held -= 1; c.uses.push((did.to_string(), at.to_string())); } self.used = true; } } impl Drop for Held { fn drop(&mut self) { if !self.used && let Some(c) = self.s.invites.lock().codes.get_mut(&self.code) { c.held -= 1; } } } /// The admin's `Basic` auth, `admin` and `PDS_ADMIN_PASSWORD`, compared in /// constant time; anything else, and anything at all with no password set, /// is `401 AuthenticationRequired`. pub(crate) fn admin(s: &Service, b: Bearer) -> Result { let refuse = || err(401, "AuthenticationRequired", "Authentication Required"); let (Bearer::Basic(credentials), Some(password)) = ( b, s.config.admin_password.as_ref().filter(|p| !p.is_empty()), ) else { return refuse(); }; let Ok(given) = base64::engine::general_purpose::STANDARD.decode(credentials) else { return refuse(); }; // Digests compared, so that not even the length shows. let (given, want) = ( Sha256::digest(&given), Sha256::digest(format!("{ADMIN}:{password}").as_bytes()), ); if given .iter() .zip(want.iter()) .fold(0u8, |acc, (a, b)| acc | (a ^ b)) != 0 { return refuse(); } Ok(Token { did: ADMIN.to_string(), scope: ADMIN.to_string(), jti: None, oauth: false, }) } /// A new code: the server's hostname with each `.` made `-`, then two groups /// of five lower case letters or digits 2 to 7. fn new_code(hostname: &str) -> String { const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567"; let chars: String = rand::random::<[u8; 10]>() .iter() .map(|b| char::from(ALPHABET[usize::from(b & 31)])) .collect(); format!( "{}-{}-{}", hostname.replace('.', "-"), &chars[..5], &chars[5..] ) } /// Make codes for each account given, `count` each, of `uses` uses: logged in /// one frame, and on disk before they are answered. Answers each account's codes. async fn make( s: &Shared, accounts: &[String], count: i64, uses: i64, ) -> Result>, XrpcError> { let at = crate::events::timestamp(); let n = { let mut st = s.invites.lock(); let mut made: Vec> = Vec::with_capacity(accounts.len()); let mut entries = Vec::new(); for account in accounts { let mut codes = Vec::new(); for _ in 0..count.max(0) { let code = std::iter::repeat_with(|| new_code(&s.config.hostname)) .find(|c| !st.codes.contains_key(c) && !codes.contains(c)) .expect("a code"); entries.push(json!({ "t": "invite", "code": code, "forAccount": account, "createdBy": ADMIN, "available": uses, "createdAt": at })); codes.push(code); } made.push(codes); } if entries.is_empty() { return Ok(made); } let n = match s.log.append(&entries) { Ok(n) => n, Err(e) => { crate::ops::failed("writing accounts.log failed", e); return internal(); } }; for e in &entries { st.apply(e).map_err(|why| XrpcError { status: 500, name: "InternalServerError", message: why, })?; } (n, made) }; durable(s.log.clone(), n.0).await?; Ok(n.1) } async fn create_invite_code(s: Shared, b: Map) -> Result { let uses = b.get("useCount").and_then(Json::as_i64).unwrap_or(0); let account = b .get("forAccount") .and_then(Json::as_str) .unwrap_or(ADMIN) .to_string(); let made = make(&s, &[account], 1, uses).await?; Ok(Resp::Json(json!({ "code": made[0][0] }))) } async fn create_invite_codes(s: Shared, b: Map) -> Result { let count = b.get("codeCount").and_then(Json::as_i64).unwrap_or(1); let uses = b.get("useCount").and_then(Json::as_i64).unwrap_or(0); let accounts: Vec = match b.get("forAccounts").and_then(Json::as_array) { Some(a) => a .iter() .filter_map(Json::as_str) .map(str::to_string) .collect(), None => vec![ADMIN.to_string()], }; let made = make(&s, &accounts, count, uses).await?; let codes: Vec = accounts .iter() .zip(made) .map(|(account, codes)| json!({ "account": account, "codes": codes })) .collect(); Ok(Resp::Json(json!({ "codes": codes }))) } /// The codes for the token's account, a session of its own password's. fn get_account_invite_codes( s: &Service, call: &Call, shown: &mut Shown, p: &Map, ) -> Result { let t = full_access_token(s, call.bearer)?; crate::lifecycle::gate(s, call.nsid, &t.did)?; let include_used = p.get("includeUsed").and_then(Json::as_bool).unwrap_or(true); let st = s.invites.lock(); let codes: Vec = st .by_account .get(&t.did) .into_iter() .flatten() .map(|code| (code, &st.codes[code])) .filter(|(_, c)| include_used || (c.uses.len() as i64) < c.available) .map(|(code, c)| { let uses: Vec = c.uses.iter().rev().map(|(by, at)| json!({ "usedBy": by, "usedAt": at })).collect(); json!({ "code": code, "available": c.available, "disabled": false, "forAccount": c.for_account, "createdBy": c.created_by, "createdAt": c.created_at, "uses": uses, }) }) .collect(); drop(st); shown.0.push((s.log.clone(), s.log.written())); Ok(Resp::Json(json!({ "codes": codes }))) } #[cfg(test)] mod tests { use super::*; use crate::testing::*; const CREATE_CODE: &str = "com.atproto.server.createInviteCode"; const CREATE_CODES: &str = "com.atproto.server.createInviteCodes"; const LIST: &str = "com.atproto.server.getAccountInviteCodes"; const CREATE: &str = "com.atproto.server.createAccount"; fn basic(user_password: &str) -> String { format!( "Basic {}", base64::engine::general_purpose::STANDARD.encode(user_password) ) } async fn as_admin(s: &Shared, nsid: &str, body: Json) -> Result { let h = basic(&format!("admin:{ADMIN_PASSWORD}")); call_raw(s, nsid, Bearer::of(Some(&h)), &[], &body.to_string()).await } fn account(name: &str, code: Option<&str>) -> Json { let mut b = json!({ "handle": format!("{name}.test"), "email": format!("{name}@mail.com"), "password": "pw" }); if let Some(c) = code { b["inviteCode"] = json!(c); } b } /// Only the admin's `Basic` auth makes codes, checked before the input. #[tokio::test] async fn only_the_admin_makes_codes() { let plc = plc().await; let dir = scratch("invite-admin"); let s = open(&dir, &plc); let (_, token) = create(&s, "alice").await; let wrong = [ Bearer::None, Bearer::Token(&token), Bearer::Basic("not base64!"), Bearer::Basic(&basic("admin:wrong")["Basic ".len()..]), Bearer::Basic(&basic(&format!("root:{ADMIN_PASSWORD}"))["Basic ".len()..]), ]; for b in wrong { for body in [r#"{"useCount":1}"#, r#"{"useCount":"x"}"#] { assert_eq!( call_raw(&s, CREATE_CODE, b, &[], body).await, Err("AuthenticationRequired".into()), "{b:?}" ); } } assert_eq!( as_admin(&s, CREATE_CODE, json!({ "useCount": "x" })).await, Err("InvalidRequest".into()) ); let code = as_admin(&s, CREATE_CODE, json!({ "useCount": 1 })) .await .unwrap()["code"] .as_str() .unwrap() .to_string(); let (prefix, rest) = code.split_at("localhost-".len()); assert_eq!(prefix, "localhost-"); assert!( rest.len() == 11 && rest.as_bytes()[5] == b'-' && rest .bytes() .filter(|c| *c != b'-') .all(|c| matches!(c, b'a'..=b'z' | b'2'..=b'7')), "{code}" ); // With no admin password set, no request is the admin. drop(s); let s = open_with(&dir, &plc, |c| c.admin_password = None); assert_eq!( as_admin(&s, CREATE_CODE, json!({ "useCount": 1 })).await, Err("AuthenticationRequired".into()) ); // An empty one is none: neither `admin:` nor the usual password is the admin. drop(s); let s = open_with(&dir, &plc, |c| c.admin_password = Some(String::new())); assert_eq!( call_raw( &s, CREATE_CODE, Bearer::of(Some(&basic("admin:"))), &[], r#"{"useCount":1}"# ) .await, Err("AuthenticationRequired".into()) ); assert_eq!( as_admin(&s, CREATE_CODE, json!({ "useCount": 1 })).await, Err("AuthenticationRequired".into()) ); let _ = std::fs::remove_dir_all(&dir); } /// Codes for accounts, used by `createAccount`, listed by the account /// they are for, newest use first, and all of it after a restart. #[tokio::test] async fn codes_are_made_used_and_listed() { let plc = plc().await; let dir = scratch("invite-use"); let s = open(&dir, &plc); let (alice, token) = create(&s, "alice").await; let got = as_admin( &s, CREATE_CODES, json!({ "codeCount": 2, "useCount": 2, "forAccounts": [alice, "did:plc:elsewhere"] }), ) .await .unwrap(); let codes = got["codes"].as_array().unwrap(); assert_eq!( (codes.len(), &codes[0]["account"], &codes[1]["account"]), (2, &json!(alice), &json!("did:plc:elsewhere")) ); let mine: Vec = codes[0]["codes"] .as_array() .unwrap() .iter() .map(|c| c.as_str().unwrap().to_string()) .collect(); assert_eq!(mine.len(), 2); assert_eq!( as_admin( &s, CREATE_CODES, json!({ "codeCount": 2, "useCount": 1, "forAccounts": [] }) ) .await .unwrap(), json!({ "codes": [] }) ); assert_eq!( as_admin(&s, CREATE_CODES, json!({ "codeCount": 0, "useCount": 1 })) .await .unwrap(), json!({ "codes": [{ "account": "admin", "codes": [] }] }) ); let none = as_admin(&s, CREATE_CODE, json!({ "useCount": 0 })) .await .unwrap()["code"] .as_str() .unwrap() .to_string(); // Not required: none, or an empty one, is none; one not available is refused. create(&s, "bob").await; call(&s, CREATE, None, account("carol", Some(""))) .await .unwrap(); for bad in [none.as_str(), "nope", &mine[0].to_uppercase()] { assert_eq!( call(&s, CREATE, None, account("dave", Some(bad))).await, Err("InvalidInviteCode".into()), "{bad}" ); } let dave = call(&s, CREATE, None, account("dave", Some(&mine[0]))) .await .unwrap(); let erin = call(&s, CREATE, None, account("erin", Some(&mine[0]))) .await .unwrap(); assert_eq!( call(&s, CREATE, None, account("fred", Some(&mine[0]))).await, Err("InvalidInviteCode".into()) ); let list = |s: &Shared, include: Option| { let (s, token) = (s.clone(), token.clone()); async move { let p: Vec<(String, String)> = include .map(|i| ("includeUsed".to_string(), i.to_string())) .into_iter() .collect(); call_with(&s, LIST, Some(&token), &p, Json::Null) .await .unwrap()["codes"] .as_array() .unwrap() .clone() } }; let all = list(&s, None).await; assert_eq!(all.len(), 2); let used = all.iter().find(|c| c["code"] == json!(mine[0])).unwrap(); assert_eq!( ( &used["available"], &used["disabled"], &used["forAccount"], &used["createdBy"] ), (&json!(2), &json!(false), &json!(alice), &json!("admin")) ); let by: Vec<&Json> = used["uses"] .as_array() .unwrap() .iter() .map(|u| &u["usedBy"]) .collect(); assert_eq!(by, [&erin["did"], &dave["did"]]); assert_eq!(list(&s, Some(false)).await.len(), 1); // A restart has the same codes and uses. let before = s.invites.snapshot(); drop(s); let s = open(&dir, &plc); assert_eq!(s.invites.snapshot(), before); assert_eq!(list(&s, None).await, all); let _ = std::fs::remove_dir_all(&dir); } /// An app password's session, a refresh token, a `Basic` header: each is /// `InvalidToken` to `getAccountInviteCodes`; none is `AuthMissing`. #[tokio::test] async fn listing_takes_the_accounts_own_session() { let plc = plc().await; let dir = scratch("invite-list"); let s = open(&dir, &plc); let (_, token) = create(&s, "alice").await; let app = call( &s, "com.atproto.server.createAppPassword", Some(&token), json!({ "name": "x", "privileged": true }), ) .await .unwrap(); let login = json!({ "identifier": "alice.test", "password": app["password"] }); let session = call(&s, "com.atproto.server.createSession", None, login) .await .unwrap(); for t in [ session["accessJwt"].as_str().unwrap(), session["refreshJwt"].as_str().unwrap(), ] { assert_eq!( call_with(&s, LIST, Some(t), &[], Json::Null).await, Err("InvalidToken".into()) ); } let h = basic(&format!("admin:{ADMIN_PASSWORD}")); assert_eq!( call_raw(&s, LIST, Bearer::of(Some(&h)), &[], "").await, Err("InvalidToken".into()) ); assert_eq!( call_with(&s, LIST, None, &[], Json::Null).await, Err("AuthMissing".into()) ); assert_eq!( call_with(&s, LIST, Some(&token), &[], Json::Null) .await .unwrap(), json!({ "codes": [] }) ); let _ = std::fs::remove_dir_all(&dir); } /// With codes required: none or an empty one is refused before the email /// is checked; one not available after the handle, before a handle taken. /// Many at once with a code of one use make one account. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn codes_required() { let plc = plc().await; let dir = scratch("invite-required"); let s = open_with(&dir, &plc, |c| c.invite_required = true); let described = call(&s, "com.atproto.server.describeServer", None, json!({})) .await .unwrap(); assert_eq!(described["inviteCodeRequired"], json!(true)); let code = |n: i64| { let s = s.clone(); async move { as_admin(&s, CREATE_CODE, json!({ "useCount": n })) .await .unwrap()["code"] .as_str() .unwrap() .to_string() } }; let first = code(1).await; call(&s, CREATE, None, account("alice", Some(&first))) .await .unwrap(); let cases = [ ( json!({ "handle": "x.test", "password": "x".repeat(257) }), "InvalidRequest", ), ( json!({ "handle": "bob.test", "email": "bad", "password": "pw" }), "InvalidInviteCode", ), ( json!({ "handle": "bob.test", "email": "bad", "password": "pw", "inviteCode": "" }), "InvalidInviteCode", ), ( json!({ "handle": "bob.test", "email": "bad", "password": "pw", "inviteCode": "nope" }), "InvalidRequest", ), ( json!({ "handle": "ab.test", "email": "b@mail.com", "password": "pw", "inviteCode": "nope" }), "InvalidHandle", ), ( json!({ "handle": "alice.test", "email": "b@mail.com", "password": "pw", "inviteCode": "nope" }), "InvalidInviteCode", ), ( json!({ "handle": "alice.test", "email": "b@mail.com", "password": "pw", "inviteCode": first }), "InvalidInviteCode", ), ]; for (body, want) in cases { assert_eq!( call(&s, CREATE, None, body.clone()).await, Err(want.to_string()), "{body}" ); } let one = code(1).await; let tries: Vec<_> = (0..8) .map(|i| { let (s, one) = (s.clone(), one.clone()); tokio::spawn(async move { call(&s, CREATE, None, account(&format!("racer{i}"), Some(&one))).await }) }) .collect(); let mut made = 0; for t in tries { if t.await.unwrap().is_ok() { made += 1; } } assert_eq!(made, 1); // A refused createAccount uses nothing. let two = code(1).await; assert_eq!(call(&s, CREATE, None, json!({ "handle": "alice.test", "email": "z@mail.com", "password": "pw", "inviteCode": two })).await, Err("InvalidRequest".into())); call(&s, CREATE, None, account("zed", Some(&two))) .await .unwrap(); let _ = std::fs::remove_dir_all(&dir); } }