From ae22d5dd960c930f0fefc42b337d9c066e4af1be Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:33:21 +0200 Subject: [PATCH] Online mode: players named in commands are their accounts An online-mode server checks players by their account's UUID, so op, whitelist, ban and pardon now resolve a name as vanilla's CachedUserNameToIdResolver does: a player on the server, then one seen since the start (in memory; vanilla also keeps usercache.json), then the services' profiles/getByName endpoint through the discovery document. A name with no account is "That player does not exist", with vanilla's "Couldn't find profile with name" warning. Offline servers keep the offline profiles. horizon-server does the same while the server is stopped (op, whitelist add, and the players init writes), and removes entries by the name already on the list. `init --offline` (or HORIZON_ONLINE=false) sets online-mode off; init's note now warns about offline servers only. The online-mode harness adds a sixth login: `whitelist add` for the player who joined earlier needs no lookup and lets them in, and an unknown name is looked up and refused, on vanilla's server and on Horizon's (43 checks). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/src/game/dedicated.rs | 100 ++++++++++++++------ crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-server-files/Cargo.toml | 4 +- crates/horizon-server-files/src/lib.rs | 8 +- crates/horizon-server-files/src/profiles.rs | 100 ++++++++++++++++++++ crates/horizon-server/src/config.rs | 2 +- crates/horizon-server/src/init.rs | 36 ++++--- crates/horizon-server/src/lists.rs | 27 +++++- crates/horizon-server/src/main.rs | 3 +- tools/test_online_mode_parity.py | 53 ++++++++++- 11 files changed, 282 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-server-files/src/profiles.rs diff --git a/Cargo.lock b/Cargo.lock index 1d5897d11..aadf1e1c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1573,6 +1573,7 @@ dependencies = [ "horizon-protocol", "horizon-world", "log", + "ureq", ] [[package]] diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 6f1ba3fee..9bc1e1fce 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -58,6 +58,21 @@ struct Setup { } static SETUP: OnceLock>> = OnceLock::new(); +/// CachedUserNameToIdResolver, kept in memory only (vanilla also saves it to +/// usercache.json): players who joined, and accounts found by name, by name +/// in lower case. +static USER_CACHE: OnceLock>> = OnceLock::new(); + +/// PlayerList.placeNewPlayer adds the player to the name cache. +pub(super) fn remember(name: &str, uuid: u128) { + let user = NameAndId { + id: uuid, + name: name.to_owned(), + }; + let cache = USER_CACHE.get_or_init(Default::default); + cache.lock().unwrap().insert(name.to_lowercase(), user); +} + /// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. pub(super) fn log(level: &str, message: &str) { log_from("Server thread", level, message); @@ -316,6 +331,8 @@ struct ServerState { /// When the last passes of the loop ended, for the tick rate horizon-server shows. ticks: std::collections::VecDeque, paused: bool, + /// online-mode: names given to commands are looked up as accounts. + online: bool, } impl Game<'_> { @@ -512,6 +529,7 @@ impl Game<'_> { empty_ticks: 0, ticks: Default::default(), paused: false, + online: props.online_mode, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -640,23 +658,46 @@ impl Game<'_> { host.hub.resend_commands(); } - /// A known player by name: online first, else the offline profile. - fn resolve(&self, name: &str) -> NameAndId { - self.lan - .as_ref() - .and_then(|h| { - h.hub - .guests - .iter() - .find(|g| g.name.eq_ignore_ascii_case(name)) - }) - .map_or_else( - || NameAndId::offline(name), - |g| NameAndId { - id: g.uuid, - name: g.name.clone(), - }, - ) + /// A player on the server, by name. + fn online_player(&self, name: &str) -> Option { + let hub = &self.lan.as_ref()?.hub; + let g = hub + .guests + .iter() + .find(|g| g.name.eq_ignore_ascii_case(name))?; + Some(NameAndId { + id: g.uuid, + name: g.name.clone(), + }) + } + + /// GameProfileArgument: a player on the server, else one seen since the + /// start, else the name resolved as the server's mode says (an online + /// server asks the services, an offline one makes the offline profile). + /// None, told to the console: no such account. + fn resolve(&self, name: &str, online: bool) -> Option { + let user = self.online_player(name).or_else(|| { + let key = name.to_lowercase(); + let cache = USER_CACHE.get_or_init(Default::default); + if let Some(user) = cache.lock().unwrap().get(&key) { + return Some(user.clone()); + } + let user = horizon_server_files::profiles::resolve(name, online); + let Some(user) = user else { + if online { + log("WARN", &format!("Couldn't find profile with name: {key}")); + } + return None; + }; + if online { + cache.lock().unwrap().insert(key, user.clone()); + } + Some(user) + }); + if user.is_none() { + self.console_reply(Text::translate("argument.player.unknown", &[])); + } + user } /// MinecraftServer.sendSystemMessage: what the console is told. @@ -739,7 +780,9 @@ impl Game<'_> { )); } "op" | "deop" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let level = 4; let changed = { let mut l = state.lists.lock().unwrap(); @@ -769,7 +812,9 @@ impl Game<'_> { } "whitelist" => self.console_whitelist(state, &rest), "ban" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let reason = (rest.len() > 1).then(|| rest[1..].join(" ")); let added = state.lists.lock().unwrap().bans.add(BanEntry::new( user.clone(), @@ -859,7 +904,9 @@ impl Game<'_> { } } "pardon" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0], state.online) else { + return; + }; let removed = state.lists.lock().unwrap().bans.remove(&user); let key = if removed { "commands.pardon.success" @@ -925,15 +972,10 @@ impl Game<'_> { } } "kick" if !rest.is_empty() => { - let user = self.resolve(rest[0]); - let online = self - .lan - .as_ref() - .is_some_and(|h| h.hub.guests.iter().any(|g| g.uuid == user.id)); - if !online { + let Some(user) = self.online_player(rest[0]) else { self.console_reply(Text::translate("argument.entity.notfound.player", &[])); return; - } + }; let reason = if rest.len() > 1 { Tag::String(JavaString::from(rest[1..].join(" ").as_str())) } else { @@ -1013,7 +1055,9 @@ impl Game<'_> { self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); } ["add", name] | ["remove", name] => { - let user = self.resolve(name); + let Some(user) = self.resolve(name, state.online) else { + return; + }; let mut l = state.lists.lock().unwrap(); let (ok, key) = if rest[0] == "add" { if l.white.contains(&user) { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index c416c202f..3e570f5ef 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -673,6 +673,7 @@ impl Game<'_> { && let Some(g) = host.hub.guest(conn) { // PlayerList.placeNewPlayer, then the broadcast join message. + super::dedicated::remember(&g.name, g.uuid); let [x, y, z] = g.position; super::dedicated::log( "INFO", diff --git a/crates/horizon-server-files/Cargo.toml b/crates/horizon-server-files/Cargo.toml index 52114718d..184dadc90 100644 --- a/crates/horizon-server-files/Cargo.toml +++ b/crates/horizon-server-files/Cargo.toml @@ -4,13 +4,15 @@ version = "0.1.0" edition.workspace = true license.workspace = true rust-version = "1.90" -description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans" +description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans, and account lookups" [dependencies] horizon-core = { path = "../horizon-core" } horizon-protocol = { path = "../horizon-protocol" } horizon-world = { path = "../horizon-world" } log = "0.4" +# Online mode: finding accounts by name (the services' profiles endpoint). +ureq = { version = "2", default-features = false, features = ["tls"] } [lints] workspace = true diff --git a/crates/horizon-server-files/src/lib.rs b/crates/horizon-server-files/src/lib.rs index 30c75c869..babb02771 100644 --- a/crates/horizon-server-files/src/lib.rs +++ b/crates/horizon-server-files/src/lib.rs @@ -1,10 +1,12 @@ //! The dedicated server's files and settings, ported from //! net.minecraft.server.dedicated and net.minecraft.server.players: -//! server.properties, eula.txt and the four user lists. The game's dedicated -//! server (`horizon-client --dedicated`) reads them, and `horizon-server` -//! manages them; this crate needs neither a window nor the game. +//! server.properties, eula.txt, the four user lists and looking players up +//! by name in online mode. The game's dedicated server +//! (`horizon-client --dedicated`) reads them, and `horizon-server` manages +//! them; this crate needs neither a window nor the game. pub mod eula; pub mod java_properties; pub mod json; +pub mod profiles; pub mod properties; pub mod user_lists; diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs new file mode 100644 index 000000000..a093fbfb1 --- /dev/null +++ b/crates/horizon-server-files/src/profiles.rs @@ -0,0 +1,100 @@ +//! Finding a player's account by name, as an online-mode server does for the +//! names given to `op`, `whitelist` and `ban` (CachedUserNameToIdResolver, +//! MinecraftServicesProfileRepository.findProfileByName): the services' +//! `profiles` / `getByName` endpoint, found through the discovery document. +use crate::{ + json::{self, Json}, + user_lists::NameAndId, +}; +use std::time::Duration; + +/// Mojang's services discovery document. +pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client"; + +/// The discovery document's URL: `HORIZON_API_DISCOVERY` overrides it like +/// authlib's `-Dminecraft.api.discovery.host`. +pub fn discovery_url() -> String { + std::env::var("HORIZON_API_DISCOVERY") + .ok() + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned()) +} + +/// StringUtil.isValidPlayerName: at most 16 UTF-16 units, none a control +/// character, a space or above ASCII. +pub fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// How a server resolves a name it was given (CachedUserNameToIdResolver.get, +/// without the usercache.json cache): an offline server makes the offline +/// profile; an online one asks the services (for the name in lower case) and +/// knows nobody they don't. +pub fn resolve(name: &str, online: bool) -> Option { + if online && valid_player_name(name) { + find_by_name(&discovery_url(), &name.to_ascii_lowercase()) + } else { + (!online).then(|| NameAndId::offline(name)) + } +} + +/// MinecraftServicesProfileRepository.findProfileByName: the account named +/// `name` (any case), or None when there is none or the services don't +/// answer (vanilla logs both as "Couldn't find profile with name"). +pub fn find_by_name(discovery: &str, name: &str) -> Option { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build(); + let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?; + let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase()); + found(&agent.get(&url).call().ok()?.into_string().ok()?, name) +} + +/// MinecraftServicesDiscoveryService.getUrl(service, endpoint). +fn endpoint(doc: &Json, service: &str, name: &str) -> Option { + doc.get("discovery")? + .get(service)? + .get("endpoints")? + .get(name)? + .get("uri")? + .as_string() +} + +/// The answer, authlib's NameAndId: `{"id", "name"}`, the id undashed. +pub fn found(answer: &str, name: &str) -> Option { + let profile = json::parse(answer, true).ok()?; + let found = profile.get("name")?.as_string()?; + let id = profile.get("id")?.as_string()?.replace('-', ""); + (found.eq_ignore_ascii_case(name) && id.len() == 32).then_some(())?; + Some(NameAndId { + id: u128::from_str_radix(&id, 16).ok()?, + name: found, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_answers() { + assert!(valid_player_name("Alex_123")); + assert!(!valid_player_name("two words")); + assert!(!valid_player_name("ThisNameIsTooLong")); + assert!(!valid_player_name("caf\u{e9}")); + assert_eq!(resolve("Alex", false), Some(NameAndId::offline("Alex"))); + assert_eq!(resolve("not valid", true), None); + let answer = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"#; + assert_eq!( + found(answer, "notch"), + Some(NameAndId { + id: 0x069a79f444e94726a5befca90e38aaf5, + name: "Notch".into() + }) + ); + assert_eq!(found(answer, "Steve"), None); + assert_eq!(found("{}", "Notch"), None); + assert_eq!(found("", "Notch"), None); + } +} diff --git a/crates/horizon-server/src/config.rs b/crates/horizon-server/src/config.rs index c62869e27..3c389f858 100644 --- a/crates/horizon-server/src/config.rs +++ b/crates/horizon-server/src/config.rs @@ -23,7 +23,7 @@ motd = "A Minecraft Server" port = 25565 bind = "" # listen on every address, or only on this one (server-ip) max_players = 20 -online_mode = true # not supported by Horizon yet: the server runs offline and says so +online_mode = true # check players' Minecraft accounts (false: anyone joins under any name) whitelist = true # only whitelisted players and operators can join enforce_whitelist = false # kick online players taken off the whitelist view_distance = 10 diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 37e43df80..757b6def8 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -6,7 +6,7 @@ use crate::{config, config::Config, engine}; use horizon_server_files::{ eula, java_properties::now_millis, - user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}, + user_lists::{OpEntry, OpList, WhiteEntry, WhiteList}, }; use std::{ io::{BufRead, IsTerminal, Write}, @@ -23,6 +23,8 @@ pub struct Answers { pub whitelist: Option, pub players: Vec, pub op: Option, + /// online-mode (true unless set): players' Minecraft accounts are checked. + pub online: Option, /// Take the default for every question not answered by a flag. pub yes: bool, } @@ -30,7 +32,7 @@ pub struct Answers { impl Answers { /// The answers in the environment, for containers: `HORIZON_EULA=true`, `HORIZON_WORLD`, /// `HORIZON_SEED`, `HORIZON_PORT`, `HORIZON_WHITELIST=true|false`, `HORIZON_PLAYERS` (names separated by - /// commas) and `HORIZON_OP`. Flags given on the command line win. + /// commas), `HORIZON_OP` and `HORIZON_ONLINE=true|false`. Flags given on the command line win. pub fn from_env() -> Result { let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); let flag = |name: &str| var(name).map(|v| v.eq_ignore_ascii_case("true")); @@ -54,6 +56,7 @@ impl Answers { }) .unwrap_or_default(), op: var("HORIZON_OP"), + online: flag("HORIZON_ONLINE"), yes: false, }) } @@ -172,6 +175,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { } // 4. Who may join. + if let Some(online) = answers.online { + cfg.server.online_mode = online; + } cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| { prompt.yes( "Only let in players you list (whitelist)?", @@ -193,7 +199,7 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { .yes(&format!("Make {first} an operator?"), true) .then(|| first.clone()) }); - add_players(dir, &players, op.as_deref())?; + add_players(dir, &players, op.as_deref(), cfg.server.online_mode)?; // 5. The game and its files. match engine::program(&cfg, dir) { @@ -213,24 +219,29 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { toml_path.display(), dir.display() ); - if cfg.server.online_mode { + if !cfg.server.online_mode { println!( - "Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \ - keep the whitelist on, or play on a LAN or a tailnet." + "Note: online mode is off, so anyone can join under any name: keep the whitelist on, or play on a \ + LAN or a tailnet." ); } Ok(()) } -/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the -/// server runs offline. -fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> { +/// Adds players to the whitelist (and one as an operator) in vanilla's files, with the profiles the server +/// will see: offline ones, or in online mode their accounts. +fn add_players( + dir: &Path, + players: &[String], + op: Option<&str>, + online: bool, +) -> Result<(), String> { if !players.is_empty() { let mut white = WhiteList::new(dir.join("whitelist.json")); let _ = white.load(); for name in players { white.add(WhiteEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, }); } println!("Whitelisted: {}", players.join(", ")); @@ -239,7 +250,7 @@ fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), S let mut ops = OpList::new(dir.join("ops.json")); let _ = ops.load(); ops.add(OpEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, level: 4, bypasses_player_limit: false, }); @@ -264,6 +275,8 @@ mod tests { whitelist: Some(true), players: vec!["Alex".into(), "Steve".into()], op: Some("Alex".into()), + // Offline: no account lookups in a test. + online: Some(false), yes: true, }; run(&dir, answers).unwrap(); @@ -277,6 +290,7 @@ mod tests { ("survival", "12345", 25599) ); assert!(eula::agreed(&dir.join("eula.txt")).unwrap()); + assert!(!cfg.server.online_mode); let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap(); assert!( white.contains("\"Alex\"") && white.contains("\"Steve\""), diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs index 398ccfe10..a6c466666 100644 --- a/crates/horizon-server/src/lists.rs +++ b/crates/horizon-server/src/lists.rs @@ -20,7 +20,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { let message = match (command, args.as_slice()) { ("op", [name]) => { let mut ops = load(OpList::new(ops_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if ops.contains(&user) { "Nothing changed. The player already is an operator".to_owned() } else { @@ -34,7 +34,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("deop", [name]) => { let mut ops = load(OpList::new(ops_path))?; - if ops.remove(&NameAndId::offline(name)) { + let user = listed(ops.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| ops.remove(&user)) { format!("Made {name} no longer a server operator") } else { "Nothing changed. The player is not an operator".to_owned() @@ -42,7 +43,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["add", name]) => { let mut white = load(WhiteList::new(white_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if white.contains(&user) { "Player is already whitelisted".to_owned() } else { @@ -52,7 +53,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["remove", name]) => { let mut white = load(WhiteList::new(white_path))?; - if white.remove(&NameAndId::offline(name)) { + let user = listed(white.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| white.remove(&user)) { format!("Removed {name} from the whitelist") } else { "Player is not whitelisted".to_owned() @@ -97,6 +99,23 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { Ok(()) } +/// The profile a running server would store for `name`: the offline one, or in online mode the account the +/// services know by that name. +pub fn account(name: &str, online: bool) -> Result { + horizon_server_files::profiles::resolve(name, online).ok_or_else(|| { + if online { + format!("That player does not exist (no Minecraft account is named {name}, or the services didn't answer)") + } else { + "That player does not exist".to_owned() + } + }) +} + +/// The entry already on a list under `name` (any case), so removing needs no lookup. +fn listed<'a>(mut users: impl Iterator, name: &str) -> Option { + users.find(|u| u.name.eq_ignore_ascii_case(name)).cloned() +} + /// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it). fn load( mut list: horizon_server_files::user_lists::UserList, diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index af45015de..c37da27a5 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -23,7 +23,7 @@ Usage: horizon-server [--dir DIR] init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags: --eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME - --yes) + --offline --yes) run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It restarts the game if it crashes. start Run the server in the background (its output goes to logs/supervisor.log) @@ -150,6 +150,7 @@ fn init_answers(args: &[String]) -> Result { "--no-whitelist" => answers.whitelist = Some(false), "--player" => answers.players.push(value(arg)?), "--op" => answers.op = Some(value(arg)?), + "--offline" => answers.online = Some(false), other => return Err(format!("init: unknown option {other}")), } } diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py index 8e349bf0d..e6679b7b5 100644 --- a/tools/test_online_mode_parity.py +++ b/tools/test_online_mode_parity.py @@ -21,7 +21,10 @@ Also checked, with vanilla's messages: - a token the session service rejects ("Failed to log in: Invalid session"); - a join the session service forgets (the server: "Failed to verify username!"); - no account at all (the client refuses before joining); -- a verified player the whitelist refuses. +- a verified player the whitelist refuses; +- `whitelist add` in online mode: a player who joined before is known by name + and let in; another name is looked up through the services' profile lookup, + and one with no account is refused ("That player does not exist"). Horizon's dedicated server then runs the same steps in online mode (`HORIZON_API_DISCOVERY` points it at the mock too): it must give the client @@ -100,6 +103,14 @@ class Services: query = dict(urllib.parse.parse_qsl(url.query)) if url.path == '/minecraft/client': return self.reply(200, services.discovery()) + if url.path.startswith('/users/profiles/minecraft/'): + # profiles/getByName: the account with that name, ignoring case. + name = urllib.parse.unquote(url.path.rsplit('/', 1)[1]) + with services.lock: + services.log.append(('lookup', name)) + if name.lower() == PLAYER.lower(): + return self.reply(200, {'id': PLAYER_UUID, 'name': PLAYER}) + return self.reply(404, {'error': 'NOT_FOUND', 'errorMessage': f'Couldn\'t find any profile with name {name}'}) if url.path == '/session/minecraft/hasJoined': with services.lock: ok = services.joined.get(query.get('username')) == query.get('serverId') @@ -107,11 +118,15 @@ class Services: if ok: return self.reply(200, {'id': PLAYER_UUID, 'name': query['username'], 'properties': []}) return self.reply(204) + with services.lock: + services.log.append(('unknown', url.path)) self.reply(404, {'error': 'NotFound', 'path': url.path}) def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}') if self.path != '/session/minecraft/join': + with services.lock: + services.log.append(('unknown', self.path)) return self.reply(404, {'error': 'NotFound'}) token, profile, server_id = body.get('accessToken'), body.get('selectedProfile'), body.get('serverId') accepted = token in (GOOD, FORGET) and profile == PLAYER_UUID @@ -135,7 +150,8 @@ class Services: 'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined', getProfileById='/session/minecraft/profile/{profileId}'), 'player': {'endpoints': {}}, - 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}}}, + 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}, + 'getByName': {'uri': self.url + '/users/profiles/minecraft/{name}'}}}, 'telemetry': {'endpoints': {}}, }} @@ -189,8 +205,19 @@ def player_lines(lines): return out +def wait_after(server, mark, pattern, timeout=30): + """A line matching `pattern` among those the server printed after `mark`.""" + regex = re.compile(pattern) + deadline = time.time() + timeout + while time.time() < deadline: + if any(regex.search(l) for l in server.lines[mark:]): + return + time.sleep(0.2) + raise AssertionError(f'no {pattern!r} after line {mark} of {server.log_path.name}') + + def run_side(label, command, binary, build, services, discovery): - """The five logins against one server; its checks and its log about the player.""" + """The six logins against one server; its checks and its log about the player.""" port = free_port() directory = build / label shutil.rmtree(directory, ignore_errors=True) @@ -261,6 +288,24 @@ def run_side(label, command, binary, build, services, discovery): check('not whitelisted: client message', got['error'], 'disconnected: You are not white-listed on this server!') check('not whitelisted: verified first', [(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', True)]) + + # 6. Whitelisted by name: the server knows the player from their first join (its name cache), so it + # asks the services nothing, and lets them in. + mark = len(server.lines) + server.console('whitelist add tester') + wait_after(server, mark, r'Added Tester to the whitelist') + check('whitelist add: known player, no lookup', services.take_log(), []) + got = run_client(binary, build, port, f'{label}-whitelisted', GOOD, discovery) + wait_after(server, mark, r'Tester left the game') + check('whitelisted: connected throughout', got['error'], None) + services.take_log() + # A name nobody joined with: the server looks the account up, and there is none. + mark = len(server.lines) + server.console('whitelist add Nobody') + wait_after(server, mark, r'That player does not exist') + check('whitelist add: lookup failure logged', + any("Couldn't find profile with name: nobody" in l for l in server.lines[mark:]), True) + check('whitelist add: no such account', services.take_log(), [('lookup', 'nobody')]) time.sleep(1) finally: server.stop() @@ -310,7 +355,7 @@ def main(): java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks), scope='Online-mode login against vanilla\'s dedicated server and Horizon\'s, with a mock session service: ' 'server hash, RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten ' - 'join, no account, whitelist; the servers\' log lines about the player.')) + 'join, no account, whitelist, whitelist add by account name; the servers\' log lines about the player.')) print(f'online mode: {len(checks)} checks ok')