mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-22 03:25:56 +00:00
feat(phase15): release and security hardening, DPAPI key store, probe & protocol hardening, secret redaction, audit and readiness report
This commit is contained in:
1 parent
b69fa6b867
commit
51e0f136d6
207 files changed
+38235
-7770
No files matched your search
@@ -11,7 +11,10 @@ use coa_control_proto::app;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::service::{AccountRow, CharInfo, ClaimExport, PreflightVerdict, Presence, RealmBackend, RealmInfo, RemoteImportOutcome, RemoteImportParams};
|
||||
use super::service::{
|
||||
AccountRow, CharInfo, ClaimExport, PreflightVerdict, Presence, RealmBackend, RealmInfo,
|
||||
RemoteImportOutcome, RemoteImportParams,
|
||||
};
|
||||
use crate::portable::realm;
|
||||
use crate::portable::service::access::RealmAccess;
|
||||
use crate::portable::service::runtime::PortableRuntime;
|
||||
@@ -46,20 +49,36 @@ fn is_internal(upper: &str) -> bool {
|
||||
}
|
||||
|
||||
impl LocalBackend {
|
||||
pub fn new(portable: Arc<PortableRuntime>, settings_dir: impl Into<PathBuf>, descriptors: impl Into<PathBuf>, installs: Installs) -> Self {
|
||||
Self { portable, settings_dir: settings_dir.into(), descriptors: descriptors.into(), installs }
|
||||
pub fn new(
|
||||
portable: Arc<PortableRuntime>,
|
||||
settings_dir: impl Into<PathBuf>,
|
||||
descriptors: impl Into<PathBuf>,
|
||||
installs: Installs,
|
||||
) -> Self {
|
||||
Self {
|
||||
portable,
|
||||
settings_dir: settings_dir.into(),
|
||||
descriptors: descriptors.into(),
|
||||
installs,
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, local_id: &str) -> Result<RealmAccess> {
|
||||
find_access(&self.descriptors, &(self.installs)(), local_id).ok_or_else(|| Error::Invalid("That realm is not known to this Manager.".into()))
|
||||
find_access(&self.descriptors, &(self.installs)(), local_id)
|
||||
.ok_or_else(|| Error::Invalid("That realm is not known to this Manager.".into()))
|
||||
}
|
||||
|
||||
fn account(&self, local_id: &str, filter: &str) -> Result<Option<AccountRow>> {
|
||||
let db = self.access(local_id)?.db()?;
|
||||
let out = db.query(&format!("SELECT id, username FROM acore_auth.account WHERE {filter} LIMIT 1;"))?;
|
||||
let out = db.query(&format!(
|
||||
"SELECT id, username FROM acore_auth.account WHERE {filter} LIMIT 1;"
|
||||
))?;
|
||||
Ok(out.lines().find(|l| !l.trim().is_empty()).and_then(|l| {
|
||||
let mut c = l.split('\t');
|
||||
Some(AccountRow { id: c.next()?.trim().parse().ok()?, username: c.next()?.trim().to_string() })
|
||||
Some(AccountRow {
|
||||
id: c.next()?.trim().parse().ok()?,
|
||||
username: c.next()?.trim().to_string(),
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -67,7 +86,10 @@ impl LocalBackend {
|
||||
impl RealmBackend for LocalBackend {
|
||||
fn info(&self, local_id: &str) -> Result<RealmInfo> {
|
||||
let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id);
|
||||
Ok(RealmInfo { automatic: cfg.as_ref().is_none_or(|c| !c.existing_only), route: cfg.and_then(|c| c.route) })
|
||||
Ok(RealmInfo {
|
||||
automatic: cfg.as_ref().is_none_or(|c| !c.existing_only),
|
||||
route: cfg.and_then(|c| c.route),
|
||||
})
|
||||
}
|
||||
|
||||
fn account_by_name(&self, local_id: &str, username: &str) -> Result<Option<AccountRow>> {
|
||||
@@ -92,27 +114,50 @@ impl RealmBackend for LocalBackend {
|
||||
if is_internal(&n) {
|
||||
return Err(Error::Invalid("That name is reserved.".into()));
|
||||
}
|
||||
self.access(local_id)?.ra()?.set_account_password(&n, password)
|
||||
self.access(local_id)?
|
||||
.ra()?
|
||||
.set_account_password(&n, password)
|
||||
}
|
||||
|
||||
fn check_login(&self, local_id: &str, username: &str, password: &str) -> Result<Option<AccountRow>> {
|
||||
fn check_login(
|
||||
&self,
|
||||
local_id: &str,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<Option<AccountRow>> {
|
||||
let n = name(username)?;
|
||||
if is_internal(&n) || !app::valid_password_for_link(password) {
|
||||
return Ok(None);
|
||||
}
|
||||
let db = self.access(local_id)?.db()?;
|
||||
let out = db.query(&format!("SELECT id, username, HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username = '{n}' LIMIT 1;"))?;
|
||||
let Some(line) = out.lines().find(|l| !l.trim().is_empty()) else { return Ok(None) };
|
||||
let Some(line) = out.lines().find(|l| !l.trim().is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let c: Vec<&str> = line.split('\t').map(str::trim).collect();
|
||||
if c.len() < 4 {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Ok(salt), Ok(stored)) = (hex::decode(c[2]), hex::decode(c[3])) else { return Ok(None) };
|
||||
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else { return Ok(None) };
|
||||
let (Ok(salt), Ok(stored)) = (hex::decode(c[2]), hex::decode(c[3])) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let computed = crate::srp6::verifier(&n, password, &salt);
|
||||
// both are fixed-size secrets of equal length; compare without an early exit
|
||||
let equal = stored.len() == 32 && computed.iter().zip(&stored).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0;
|
||||
Ok(equal.then(|| AccountRow { id: c[0].parse().unwrap_or(0), username: c[1].to_string() }).filter(|r| r.id != 0))
|
||||
let equal = stored.len() == 32
|
||||
&& computed
|
||||
.iter()
|
||||
.zip(&stored)
|
||||
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
|
||||
== 0;
|
||||
Ok(equal
|
||||
.then(|| AccountRow {
|
||||
id: c[0].parse().unwrap_or(0),
|
||||
username: c[1].to_string(),
|
||||
})
|
||||
.filter(|r| r.id != 0))
|
||||
}
|
||||
|
||||
fn presence(&self, local_id: &str, account_id: u32) -> Result<Presence> {
|
||||
@@ -120,40 +165,82 @@ impl RealmBackend for LocalBackend {
|
||||
let out = db.query(&format!("SELECT (SELECT online FROM acore_auth.account WHERE id = {account_id}), (SELECT COUNT(*) FROM acore_characters.characters WHERE account = {account_id} AND online = 1);"))?;
|
||||
let line = out.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
|
||||
let mut c = line.split('\t').map(str::trim);
|
||||
let account_online = c.next().is_some_and(|v| !v.is_empty() && v != "NULL" && v != "0");
|
||||
let account_online = c
|
||||
.next()
|
||||
.is_some_and(|v| !v.is_empty() && v != "NULL" && v != "0");
|
||||
let online_characters = c.next().and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
Ok(Presence { account_online, online_characters })
|
||||
Ok(Presence {
|
||||
account_online,
|
||||
online_characters,
|
||||
})
|
||||
}
|
||||
|
||||
fn characters(&self, local_id: &str, account_id: u32) -> Result<Vec<CharInfo>> {
|
||||
let db = self.access(local_id)?.db()?;
|
||||
let list = realm::inspect_characters(&db).map_err(|e| unavailable("reading characters", e))?;
|
||||
let list =
|
||||
realm::inspect_characters(&db).map_err(|e| unavailable("reading characters", e))?;
|
||||
Ok(list
|
||||
.into_iter()
|
||||
.filter(|c| c.account == account_id)
|
||||
.map(|c| CharInfo { guid: c.local_guid, name: c.name.clone(), class: c.class, race: c.race, level: c.level, eligible: c.eligible(), reasons: c.blockers.iter().map(|b| b.code().to_string()).collect() })
|
||||
.map(|c| CharInfo {
|
||||
guid: c.local_guid,
|
||||
name: c.name.clone(),
|
||||
class: c.class,
|
||||
race: c.race,
|
||||
level: c.level,
|
||||
eligible: c.eligible(),
|
||||
reasons: c.blockers.iter().map(|b| b.code().to_string()).collect(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn is_portable(&self, local_id: &str, guid: u32) -> Result<bool> {
|
||||
let id = local_id.to_string();
|
||||
self.portable.call(move |s| s.is_portable_here(&id, guid)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("portable engine", e))
|
||||
self.portable
|
||||
.call(move |s| s.is_portable_here(&id, guid))
|
||||
.map_err(|e| unavailable("portable engine", e))?
|
||||
.map_err(|e| unavailable("portable engine", e))
|
||||
}
|
||||
|
||||
fn export(&self, local_id: &str, _account_id: u32, guid: u32) -> Result<ClaimExport> {
|
||||
let id = local_id.to_string();
|
||||
let bundle = self.portable.call(move |s| s.export_for_claim(&id, guid)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("export", e))?;
|
||||
Ok(ClaimExport { character_id: bundle.character_id.as_uuid(), payload: bundle.payload, sha256: bundle.content_hash, collections: bundle.collections })
|
||||
let bundle = self
|
||||
.portable
|
||||
.call(move |s| s.export_for_claim(&id, guid))
|
||||
.map_err(|e| unavailable("portable engine", e))?
|
||||
.map_err(|e| unavailable("export", e))?;
|
||||
Ok(ClaimExport {
|
||||
character_id: bundle.character_id.as_uuid(),
|
||||
payload: bundle.payload,
|
||||
sha256: bundle.content_hash,
|
||||
collections: bundle.collections,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_transfer(&self, local_id: &str, character_id: Uuid, revision: u64) -> Result<PreflightVerdict> {
|
||||
fn check_transfer(
|
||||
&self,
|
||||
local_id: &str,
|
||||
character_id: Uuid,
|
||||
revision: u64,
|
||||
) -> Result<PreflightVerdict> {
|
||||
let id = local_id.to_string();
|
||||
let cid = crate::portable::CharacterId::from_uuid(character_id).map_err(|e| unavailable("character id", e))?;
|
||||
self.portable.call(move |s| s.check_remote_transfer(&id, cid, revision)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("check transfer", e))
|
||||
let cid = crate::portable::CharacterId::from_uuid(character_id)
|
||||
.map_err(|e| unavailable("character id", e))?;
|
||||
self.portable
|
||||
.call(move |s| s.check_remote_transfer(&id, cid, revision))
|
||||
.map_err(|e| unavailable("portable engine", e))?
|
||||
.map_err(|e| unavailable("check transfer", e))
|
||||
}
|
||||
|
||||
fn import_remote(&self, local_id: &str, params: RemoteImportParams) -> Result<RemoteImportOutcome> {
|
||||
fn import_remote(
|
||||
&self,
|
||||
local_id: &str,
|
||||
params: RemoteImportParams,
|
||||
) -> Result<RemoteImportOutcome> {
|
||||
let id = local_id.to_string();
|
||||
self.portable.call(move |s| s.import_remote_character(&id, params)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("import remote", e))
|
||||
self.portable
|
||||
.call(move |s| s.import_remote_character(&id, params))
|
||||
.map_err(|e| unavailable("portable engine", e))?
|
||||
.map_err(|e| unavailable("import remote", e))
|
||||
}
|
||||
}
|
||||
@@ -33,21 +33,45 @@ impl DirectIngress {
|
||||
local_auth_port: u16,
|
||||
local_world_port: u16,
|
||||
) -> Result<Self> {
|
||||
let auth_listener = TcpListener::bind(format!("0.0.0.0:{auth_bind_port}"))
|
||||
.map_err(|e| Error::Invalid(format!("Cannot bind direct auth listener on port {auth_bind_port}: {e}")))?;
|
||||
auth_listener.set_nonblocking(true).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let auth_actual_port = auth_listener.local_addr().map_err(|e| Error::Invalid(e.to_string()))?.port();
|
||||
let auth_listener =
|
||||
TcpListener::bind(format!("0.0.0.0:{auth_bind_port}")).map_err(|e| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot bind direct auth listener on port {auth_bind_port}: {e}"
|
||||
))
|
||||
})?;
|
||||
auth_listener
|
||||
.set_nonblocking(true)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let auth_actual_port = auth_listener
|
||||
.local_addr()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?
|
||||
.port();
|
||||
|
||||
let world_listener = TcpListener::bind(format!("0.0.0.0:{world_bind_port}"))
|
||||
.map_err(|e| Error::Invalid(format!("Cannot bind direct world listener on port {world_bind_port}: {e}")))?;
|
||||
world_listener.set_nonblocking(true).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let world_actual_port = world_listener.local_addr().map_err(|e| Error::Invalid(e.to_string()))?.port();
|
||||
let world_listener =
|
||||
TcpListener::bind(format!("0.0.0.0:{world_bind_port}")).map_err(|e| {
|
||||
Error::Invalid(format!(
|
||||
"Cannot bind direct world listener on port {world_bind_port}: {e}"
|
||||
))
|
||||
})?;
|
||||
world_listener
|
||||
.set_nonblocking(true)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let world_actual_port = world_listener
|
||||
.local_addr()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?
|
||||
.port();
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut threads = Vec::new();
|
||||
|
||||
let effective_world_port = if ext_world_port == 0 { world_actual_port } else { ext_world_port };
|
||||
let world_target = Arc::new(std::sync::RwLock::new(format!("{public_ip}:{effective_world_port}")));
|
||||
let effective_world_port = if ext_world_port == 0 {
|
||||
world_actual_port
|
||||
} else {
|
||||
ext_world_port
|
||||
};
|
||||
let world_target = Arc::new(std::sync::RwLock::new(format!(
|
||||
"{public_ip}:{effective_world_port}"
|
||||
)));
|
||||
|
||||
// Spawn Auth listener thread
|
||||
let stop_auth = stop.clone();
|
||||
@@ -63,7 +87,8 @@ impl DirectIngress {
|
||||
std::thread::Builder::new()
|
||||
.name("direct-auth-worker".into())
|
||||
.spawn(move || {
|
||||
let _ = handle_auth_client(client_stream, local_auth_port, target);
|
||||
let _ =
|
||||
handle_auth_client(client_stream, local_auth_port, target);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -127,7 +152,10 @@ impl DirectIngress {
|
||||
}
|
||||
|
||||
pub fn world_target(&self) -> String {
|
||||
self.world_target.read().map(|s| s.clone()).unwrap_or_default()
|
||||
self.world_target
|
||||
.read()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
@@ -152,8 +180,12 @@ fn handle_auth_client(
|
||||
let _ = client.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
let _ = server.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
|
||||
let mut client_read = client.try_clone().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut server_write = server.try_clone().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut client_read = client
|
||||
.try_clone()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut server_write = server
|
||||
.try_clone()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
|
||||
let done = Arc::new(AtomicBool::new(false));
|
||||
let done_c = done.clone();
|
||||
@@ -170,7 +202,10 @@ fn handle_auth_client(
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::TimedOut => {
|
||||
Err(ref e)
|
||||
if e.kind() == std::io::ErrorKind::WouldBlock
|
||||
|| e.kind() == std::io::ErrorKind::TimedOut =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
@@ -190,7 +225,10 @@ fn handle_auth_client(
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
let chunk = &buf[..n];
|
||||
let current_target = world_target.read().map(|s| s.clone()).unwrap_or_else(|_| "127.0.0.1:8085".to_string());
|
||||
let current_target = world_target
|
||||
.read()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_else(|_| "127.0.0.1:8085".to_string());
|
||||
match coa_control_proto::relay::rewrite_realm_list_address(chunk, ¤t_target) {
|
||||
Ok(Some(rewritten)) => {
|
||||
if client.write_all(&rewritten).is_err() {
|
||||
@@ -204,7 +242,10 @@ fn handle_auth_client(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::TimedOut => {
|
||||
Err(ref e)
|
||||
if e.kind() == std::io::ErrorKind::WouldBlock
|
||||
|| e.kind() == std::io::ErrorKind::TimedOut =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
@@ -219,18 +260,19 @@ fn handle_auth_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_world_client(
|
||||
mut client: TcpStream,
|
||||
local_world_port: u16,
|
||||
) -> Result<()> {
|
||||
fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<()> {
|
||||
let mut server = TcpStream::connect(format!("127.0.0.1:{local_world_port}"))
|
||||
.map_err(|e| Error::Invalid(format!("Cannot connect to local worldserver: {e}")))?;
|
||||
|
||||
let _ = client.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
let _ = server.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
|
||||
let mut client_read = client.try_clone().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut server_write = server.try_clone().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut client_read = client
|
||||
.try_clone()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut server_write = server
|
||||
.try_clone()
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
|
||||
let done = Arc::new(AtomicBool::new(false));
|
||||
let done_c = done.clone();
|
||||
@@ -246,7 +288,10 @@ fn handle_world_client(
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::TimedOut => {
|
||||
Err(ref e)
|
||||
if e.kind() == std::io::ErrorKind::WouldBlock
|
||||
|| e.kind() == std::io::ErrorKind::TimedOut =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
@@ -268,7 +313,10 @@ fn handle_world_client(
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::TimedOut => {
|
||||
Err(ref e)
|
||||
if e.kind() == std::io::ErrorKind::WouldBlock
|
||||
|| e.kind() == std::io::ErrorKind::TimedOut =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(_) => break,
|
||||
@@ -360,7 +408,10 @@ mod tests {
|
||||
let mut auth_buf = [0u8; 512];
|
||||
let an = client_auth.read(&mut auth_buf).unwrap();
|
||||
let payload = String::from_utf8_lossy(&auth_buf[..an]);
|
||||
assert!(payload.contains("198.51.100.1:8085"), "Expected rewritten world address, got: {payload}");
|
||||
assert!(
|
||||
payload.contains("198.51.100.1:8085"),
|
||||
"Expected rewritten world address, got: {payload}"
|
||||
);
|
||||
drop(client_auth);
|
||||
t_auth.join().unwrap();
|
||||
|
||||
@@ -384,10 +435,14 @@ mod tests {
|
||||
desired_world_port,
|
||||
mock_auth_port,
|
||||
mock_world_port,
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let actual_ingress_world = ingress.world_port();
|
||||
assert_ne!(actual_ingress_world, desired_world_port, "Actual ingress port must not be 8085");
|
||||
assert_ne!(
|
||||
actual_ingress_world, desired_world_port,
|
||||
"Actual ingress port must not be 8085"
|
||||
);
|
||||
|
||||
// The router / NAT-PMP assigns an external mapped world port != 8085 and != actual ingress port
|
||||
let external_mapped_world_port = 48085;
|
||||
@@ -426,7 +481,8 @@ mod tests {
|
||||
let _ = stream.shutdown(std::net::Shutdown::Write);
|
||||
});
|
||||
|
||||
let mut client_auth = TcpStream::connect(format!("127.0.0.1:{}", ingress.auth_port())).unwrap();
|
||||
let mut client_auth =
|
||||
TcpStream::connect(format!("127.0.0.1:{}", ingress.auth_port())).unwrap();
|
||||
client_auth.write_all(b"AUTH_HELLO").unwrap();
|
||||
let mut auth_buf = [0u8; 512];
|
||||
let an = client_auth.read(&mut auth_buf).unwrap();
|
||||
|
||||
@@ -64,11 +64,20 @@ impl ActiveMapping {
|
||||
pub fn cleanup(&mut self) {
|
||||
match self {
|
||||
ActiveMapping::None => {}
|
||||
ActiveMapping::Upnp { gateway, auth_port, world_port } => {
|
||||
ActiveMapping::Upnp {
|
||||
gateway,
|
||||
auth_port,
|
||||
world_port,
|
||||
} => {
|
||||
let _ = upnp::remove_mapping(gateway, *auth_port);
|
||||
let _ = upnp::remove_mapping(gateway, *world_port);
|
||||
}
|
||||
ActiveMapping::NatPmp { gateway, auth_internal, world_internal, .. } => {
|
||||
ActiveMapping::NatPmp {
|
||||
gateway,
|
||||
auth_internal,
|
||||
world_internal,
|
||||
..
|
||||
} => {
|
||||
let _ = nat_pmp::delete_mapping(*gateway, *auth_internal);
|
||||
let _ = nat_pmp::delete_mapping(*gateway, *world_internal);
|
||||
}
|
||||
@@ -84,10 +93,7 @@ pub struct DirectRouteManager {
|
||||
}
|
||||
|
||||
impl DirectRouteManager {
|
||||
pub fn start(
|
||||
registry_base_url: Option<String>,
|
||||
service: Arc<HostService>,
|
||||
) -> Self {
|
||||
pub fn start(registry_base_url: Option<String>, service: Arc<HostService>) -> Self {
|
||||
let status = Arc::new(RwLock::new(RouteStatus::Probing));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
@@ -109,7 +115,10 @@ impl DirectRouteManager {
|
||||
}
|
||||
|
||||
pub fn status(&self) -> RouteStatus {
|
||||
self.status.read().map(|s| s.clone()).unwrap_or(RouteStatus::Probing)
|
||||
self.status
|
||||
.read()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or(RouteStatus::Probing)
|
||||
}
|
||||
|
||||
pub fn is_direct_ready(&self) -> bool {
|
||||
@@ -148,13 +157,16 @@ fn probe_endpoints(base_url: Option<&str>, ports: &[u16]) -> bool {
|
||||
ports: ports.to_vec(),
|
||||
};
|
||||
let body_str = serde_json::to_string(&probe_body).unwrap_or_default();
|
||||
if let Ok(resp) = c.post(&probe_url)
|
||||
if let Ok(resp) = c
|
||||
.post(&probe_url)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body_str)
|
||||
.send()
|
||||
{
|
||||
if let Ok(text) = resp.text() {
|
||||
if let Ok(p_resp) = serde_json::from_str::<coa_control_proto::coord::ProbeResponse>(&text) {
|
||||
if let Ok(p_resp) =
|
||||
serde_json::from_str::<coa_control_proto::coord::ProbeResponse>(&text)
|
||||
{
|
||||
return p_resp.all_reachable;
|
||||
}
|
||||
}
|
||||
@@ -162,7 +174,14 @@ fn probe_endpoints(base_url: Option<&str>, ports: &[u16]) -> bool {
|
||||
}
|
||||
false
|
||||
} else {
|
||||
std::env::var("COA_TEST_FORCE_DIRECT_VERIFIED").is_ok()
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
std::env::var("COA_TEST_FORCE_DIRECT_VERIFIED").is_ok()
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,9 +213,12 @@ fn attempt_route_discovery(
|
||||
) {
|
||||
// 1. Discover local LAN address
|
||||
let Some(lan_ip) = net::lan_ip() else {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "No usable local network address found.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "No usable local network address found.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
return;
|
||||
};
|
||||
@@ -240,7 +262,9 @@ fn attempt_route_discovery(
|
||||
if let Some(c) = client {
|
||||
if let Ok(resp) = c.get(&probe_url).send() {
|
||||
if let Ok(text) = resp.text() {
|
||||
if let Ok(p_resp) = serde_json::from_str::<coa_control_proto::coord::ProbeResponse>(&text) {
|
||||
if let Ok(p_resp) =
|
||||
serde_json::from_str::<coa_control_proto::coord::ProbeResponse>(&text)
|
||||
{
|
||||
probe_ip = p_resp.client_ip.parse::<Ipv4Addr>().ok();
|
||||
}
|
||||
}
|
||||
@@ -251,18 +275,26 @@ fn attempt_route_discovery(
|
||||
let public_ip = discovered_public_ip.or(probe_ip);
|
||||
|
||||
let Some(public_ip) = public_ip else {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "Could not discover public IPv4 address.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "Could not discover public IPv4 address.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
return;
|
||||
};
|
||||
|
||||
// 4. CGNAT check
|
||||
if net::is_cgnat_range(public_ip) {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: format!("Carrier-grade NAT detected ({public_ip}); direct routing unavailable."),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: format!(
|
||||
"Carrier-grade NAT detected ({public_ip}); direct routing unavailable."
|
||||
),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
return;
|
||||
};
|
||||
@@ -295,22 +327,23 @@ fn attempt_route_discovery(
|
||||
local_world,
|
||||
) {
|
||||
Ok(ing) => Ok(ing),
|
||||
Err(_) => {
|
||||
DirectIngress::start(
|
||||
0,
|
||||
0,
|
||||
public_ip.to_string(),
|
||||
desired_world_port,
|
||||
local_auth,
|
||||
local_world,
|
||||
)
|
||||
}
|
||||
Err(_) => DirectIngress::start(
|
||||
0,
|
||||
0,
|
||||
public_ip.to_string(),
|
||||
desired_world_port,
|
||||
local_auth,
|
||||
local_world,
|
||||
),
|
||||
};
|
||||
|
||||
let Ok(mut ingress) = ingress else {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "Cannot bind direct ingress listeners.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "Cannot bind direct ingress listeners.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
return;
|
||||
};
|
||||
@@ -348,11 +381,16 @@ fn attempt_route_discovery(
|
||||
if matches!(active_mapping, ActiveMapping::None) {
|
||||
if let Some(gw) = default_gw {
|
||||
let lifetime = 3600;
|
||||
if let Some(a_ext) = nat_pmp::request_mapping(gw, bound_auth_port, bound_auth_port, lifetime) {
|
||||
if let Some(w_ext) = nat_pmp::request_mapping(gw, bound_world_port, bound_world_port, lifetime) {
|
||||
if let Some(a_ext) =
|
||||
nat_pmp::request_mapping(gw, bound_auth_port, bound_auth_port, lifetime)
|
||||
{
|
||||
if let Some(w_ext) =
|
||||
nat_pmp::request_mapping(gw, bound_world_port, bound_world_port, lifetime)
|
||||
{
|
||||
mapped_auth_port = a_ext;
|
||||
mapped_world_port = w_ext;
|
||||
let renew_at = std::time::Instant::now() + Duration::from_secs(lifetime as u64 / 2);
|
||||
let renew_at =
|
||||
std::time::Instant::now() + Duration::from_secs(lifetime as u64 / 2);
|
||||
active_mapping = ActiveMapping::NatPmp {
|
||||
gateway: gw,
|
||||
auth_internal: bound_auth_port,
|
||||
@@ -372,9 +410,12 @@ fn attempt_route_discovery(
|
||||
}
|
||||
|
||||
if matches!(active_mapping, ActiveMapping::None) {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "Router port mapping (UPnP/NAT-PMP) failed or unsupported.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "Router port mapping (UPnP/NAT-PMP) failed or unsupported.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
ingress.stop();
|
||||
return;
|
||||
@@ -385,7 +426,10 @@ fn attempt_route_discovery(
|
||||
ingress.update_external_world_endpoint(&public_ip.to_string(), mapped_world_port);
|
||||
|
||||
// 7. External Reachability Verification Probe
|
||||
let verified = probe_endpoints(registry_base_url.as_deref(), &[mapped_auth_port, mapped_world_port]);
|
||||
let verified = probe_endpoints(
|
||||
registry_base_url.as_deref(),
|
||||
&[mapped_auth_port, mapped_world_port],
|
||||
);
|
||||
|
||||
if !verified {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
@@ -399,12 +443,15 @@ fn attempt_route_discovery(
|
||||
|
||||
// 8. DIRECT_READY: update status and register direct route with HostService
|
||||
let direct_endpoint = format!("{public_ip}:{mapped_auth_port}");
|
||||
set_status(status, RouteStatus::DirectReady {
|
||||
public_ip: public_ip.to_string(),
|
||||
auth_port: mapped_auth_port,
|
||||
world_port: mapped_world_port,
|
||||
method: method.to_string(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::DirectReady {
|
||||
public_ip: public_ip.to_string(),
|
||||
auth_port: mapped_auth_port,
|
||||
world_port: mapped_world_port,
|
||||
method: method.to_string(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(Some(direct_endpoint));
|
||||
|
||||
// 9. Route Health, Renewal, and Network Change Monitoring Loop
|
||||
@@ -417,9 +464,12 @@ fn attempt_route_discovery(
|
||||
// Network change detection
|
||||
let current_lan_ip = net::lan_ip();
|
||||
if current_lan_ip != Some(last_lan_ip) {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "Local network interface address changed.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "Local network interface address changed.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
active_mapping.cleanup();
|
||||
ingress.stop();
|
||||
@@ -436,17 +486,28 @@ fn attempt_route_discovery(
|
||||
world_external,
|
||||
lifetime_secs,
|
||||
ref mut renew_at,
|
||||
} = active_mapping {
|
||||
} = active_mapping
|
||||
{
|
||||
if std::time::Instant::now() >= *renew_at {
|
||||
let ra = nat_pmp::request_mapping(gateway, auth_internal, auth_external, lifetime_secs);
|
||||
let rw = nat_pmp::request_mapping(gateway, world_internal, world_external, lifetime_secs);
|
||||
let ra =
|
||||
nat_pmp::request_mapping(gateway, auth_internal, auth_external, lifetime_secs);
|
||||
let rw = nat_pmp::request_mapping(
|
||||
gateway,
|
||||
world_internal,
|
||||
world_external,
|
||||
lifetime_secs,
|
||||
);
|
||||
if ra == Some(auth_external) && rw == Some(world_external) {
|
||||
*renew_at = std::time::Instant::now() + Duration::from_secs(lifetime_secs as u64 / 2);
|
||||
*renew_at =
|
||||
std::time::Instant::now() + Duration::from_secs(lifetime_secs as u64 / 2);
|
||||
need_probe = true;
|
||||
} else {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: "NAT-PMP port mapping renewal failed.".into(),
|
||||
});
|
||||
set_status(
|
||||
status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "NAT-PMP port mapping renewal failed.".into(),
|
||||
},
|
||||
);
|
||||
service.set_direct_route(None);
|
||||
active_mapping.cleanup();
|
||||
ingress.stop();
|
||||
@@ -459,7 +520,10 @@ fn attempt_route_discovery(
|
||||
if need_probe || last_health_check.elapsed() >= Duration::from_secs(30) {
|
||||
last_health_check = std::time::Instant::now();
|
||||
if registry_base_url.is_some() {
|
||||
let still_reachable = probe_endpoints(registry_base_url.as_deref(), &[mapped_auth_port, mapped_world_port]);
|
||||
let still_reachable = probe_endpoints(
|
||||
registry_base_url.as_deref(),
|
||||
&[mapped_auth_port, mapped_world_port],
|
||||
);
|
||||
if !still_reachable {
|
||||
set_status(status, RouteStatus::RelayOnly {
|
||||
reason: format!("Periodic external reachability probe failed on {public_ip}:{mapped_auth_port},{mapped_world_port}."),
|
||||
@@ -507,11 +571,13 @@ mod tests {
|
||||
world_port: 8085,
|
||||
method: "nat_pmp".into(),
|
||||
}));
|
||||
set_status(&status, RouteStatus::RelayOnly {
|
||||
reason: "Renewal failed".into(),
|
||||
});
|
||||
set_status(
|
||||
&status,
|
||||
RouteStatus::RelayOnly {
|
||||
reason: "Renewal failed".into(),
|
||||
},
|
||||
);
|
||||
let cur = status.read().unwrap().clone();
|
||||
assert!(matches!(cur, RouteStatus::RelayOnly { .. }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,12 @@ enum Stage {
|
||||
AwaitFirst,
|
||||
AwaitThird(Responder),
|
||||
AwaitPlayerProof(Channel),
|
||||
Ready { channel: Channel, player: Uuid, public_key: String, session: Session },
|
||||
Ready {
|
||||
channel: Channel,
|
||||
player: Uuid,
|
||||
public_key: String,
|
||||
session: Session,
|
||||
},
|
||||
}
|
||||
|
||||
struct Conn {
|
||||
@@ -60,11 +65,20 @@ pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
|
||||
|
||||
impl HostLink {
|
||||
/// `url` is the Coordinator's host endpoint, e.g. `wss://registry.example/coord/v1/host`.
|
||||
pub fn start(url: String, realm_id: RealmId, key: SigningKey, service: Arc<HostService>, clock: Clock) -> HostLink {
|
||||
pub fn start(
|
||||
url: String,
|
||||
realm_id: RealmId,
|
||||
key: SigningKey,
|
||||
service: Arc<HostService>,
|
||||
clock: Clock,
|
||||
) -> HostLink {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let status = Arc::new(Mutex::new(LinkStatus::default()));
|
||||
let (s, st) = (stop.clone(), status.clone());
|
||||
let join = std::thread::Builder::new().name("control-host".into()).spawn(move || run(&url, realm_id, &key, &service, &clock, &s, &st)).ok();
|
||||
let join = std::thread::Builder::new()
|
||||
.name("control-host".into())
|
||||
.spawn(move || run(&url, realm_id, &key, &service, &clock, &s, &st))
|
||||
.ok();
|
||||
HostLink { stop, status, join }
|
||||
}
|
||||
|
||||
@@ -92,7 +106,15 @@ fn set(status: &Mutex<LinkStatus>, f: impl FnOnce(&mut LinkStatus)) {
|
||||
}
|
||||
}
|
||||
|
||||
fn run(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, clock: &Clock, stop: &AtomicBool, status: &Mutex<LinkStatus>) {
|
||||
fn run(
|
||||
url: &str,
|
||||
realm: RealmId,
|
||||
key: &SigningKey,
|
||||
service: &HostService,
|
||||
clock: &Clock,
|
||||
stop: &AtomicBool,
|
||||
status: &Mutex<LinkStatus>,
|
||||
) {
|
||||
let mut failures = 0u32;
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
let began = Instant::now();
|
||||
@@ -108,8 +130,17 @@ fn run(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, clock
|
||||
return;
|
||||
}
|
||||
// a link that held for a while starts the backoff over
|
||||
failures = if began.elapsed() > Duration::from_secs(60) { 1 } else { failures.saturating_add(1) };
|
||||
let wait = super::super::realm_registry::host::backoff(failures, Duration::from_secs(2), Duration::from_secs(60), 0.5);
|
||||
failures = if began.elapsed() > Duration::from_secs(60) {
|
||||
1
|
||||
} else {
|
||||
failures.saturating_add(1)
|
||||
};
|
||||
let wait = super::super::realm_registry::host::backoff(
|
||||
failures,
|
||||
Duration::from_secs(2),
|
||||
Duration::from_secs(60),
|
||||
0.5,
|
||||
);
|
||||
let end = Instant::now() + wait;
|
||||
while Instant::now() < end && !stop.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
@@ -117,16 +148,31 @@ fn run(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, clock
|
||||
}
|
||||
}
|
||||
|
||||
fn session(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, clock: &Clock, stop: &AtomicBool, status: &Mutex<LinkStatus>) -> Result<(), LinkError> {
|
||||
fn session(
|
||||
url: &str,
|
||||
realm: RealmId,
|
||||
key: &SigningKey,
|
||||
service: &HostService,
|
||||
clock: &Clock,
|
||||
stop: &AtomicBool,
|
||||
status: &Mutex<LinkStatus>,
|
||||
) -> Result<(), LinkError> {
|
||||
let mut ws = transport::connect(url, POLL)?;
|
||||
let nonce = match transport::next_frame(&mut ws, Duration::from_secs(15))? {
|
||||
Frame::Challenge { nonce, .. } => nonce,
|
||||
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
|
||||
};
|
||||
transport::send_text(&mut ws, &coord::sign_host_hello(key, &realm, &nonce, clock()))?;
|
||||
transport::send_text(
|
||||
&mut ws,
|
||||
&coord::sign_host_hello(key, &realm, &nonce, clock()),
|
||||
)?;
|
||||
match transport::next_frame(&mut ws, Duration::from_secs(15))? {
|
||||
Frame::HostReady { .. } => {}
|
||||
_ => return Err(LinkError::Protocol("the Coordinator did not accept the hello".into())),
|
||||
_ => {
|
||||
return Err(LinkError::Protocol(
|
||||
"the Coordinator did not accept the hello".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
set(status, |s| {
|
||||
s.connected = true;
|
||||
@@ -138,23 +184,43 @@ fn session(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, c
|
||||
while !stop.load(Ordering::SeqCst) {
|
||||
match transport::poll(&mut ws)? {
|
||||
None => {}
|
||||
Some(Message::Text(t)) => match coord::parse_text(t.as_str()).map_err(LinkError::from)? {
|
||||
Frame::Open { conn, client_ip } => {
|
||||
if conns.len() >= MAX_CHANNELS || conns.contains_key(&conn) {
|
||||
transport::send_text(&mut ws, &Frame::Close { conn, reason: Some("busy".into()) })?;
|
||||
} else {
|
||||
conns.insert(conn, Conn { stage: Some(Stage::AwaitFirst), opened: Instant::now(), last: Instant::now(), client_ip });
|
||||
Some(Message::Text(t)) => {
|
||||
match coord::parse_text(t.as_str()).map_err(LinkError::from)? {
|
||||
Frame::Open { conn, client_ip } => {
|
||||
if conns.len() >= MAX_CHANNELS || conns.contains_key(&conn) {
|
||||
transport::send_text(
|
||||
&mut ws,
|
||||
&Frame::Close {
|
||||
conn,
|
||||
reason: Some("busy".into()),
|
||||
},
|
||||
)?;
|
||||
} else {
|
||||
conns.insert(
|
||||
conn,
|
||||
Conn {
|
||||
stage: Some(Stage::AwaitFirst),
|
||||
opened: Instant::now(),
|
||||
last: Instant::now(),
|
||||
client_ip,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Frame::Close { conn, .. } => {
|
||||
conns.remove(&conn);
|
||||
}
|
||||
Frame::Error { code, message } => {
|
||||
return Err(transport::from_error_frame(code, &message))
|
||||
}
|
||||
_ => return Err(LinkError::Protocol("an unexpected control frame".into())),
|
||||
}
|
||||
Frame::Close { conn, .. } => {
|
||||
conns.remove(&conn);
|
||||
}
|
||||
Frame::Error { code, message } => return Err(transport::from_error_frame(code, &message)),
|
||||
_ => return Err(LinkError::Protocol("an unexpected control frame".into())),
|
||||
},
|
||||
}
|
||||
Some(Message::Binary(data)) => {
|
||||
let (conn, frame) = coord::split_binary(&data).map_err(LinkError::from)?;
|
||||
let Some(c) = conns.get_mut(&conn) else { continue };
|
||||
let Some(c) = conns.get_mut(&conn) else {
|
||||
continue;
|
||||
};
|
||||
c.last = Instant::now();
|
||||
match step(c, frame, realm, key, service, status) {
|
||||
Ok(out) => {
|
||||
@@ -165,21 +231,45 @@ fn session(url: &str, realm: RealmId, key: &SigningKey, service: &HostService, c
|
||||
Err(why) => {
|
||||
tracing::debug!(%realm, conn, reason = %why, "channel closed");
|
||||
conns.remove(&conn);
|
||||
transport::send_text(&mut ws, &Frame::Close { conn, reason: Some("closed".into()) })?;
|
||||
transport::send_text(
|
||||
&mut ws,
|
||||
&Frame::Close {
|
||||
conn,
|
||||
reason: Some("closed".into()),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Message::Close(_)) => return Err(LinkError::Io("the Coordinator closed the connection".into())),
|
||||
Some(Message::Close(_)) => {
|
||||
return Err(LinkError::Io(
|
||||
"the Coordinator closed the connection".into(),
|
||||
))
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
let now = Instant::now();
|
||||
let expired: Vec<u32> = conns.iter().filter(|(_, c)| now.duration_since(c.opened) > CHANNEL_LIFETIME || now.duration_since(c.last) > CHANNEL_IDLE).map(|(k, _)| *k).collect();
|
||||
let expired: Vec<u32> = conns
|
||||
.iter()
|
||||
.filter(|(_, c)| {
|
||||
now.duration_since(c.opened) > CHANNEL_LIFETIME
|
||||
|| now.duration_since(c.last) > CHANNEL_IDLE
|
||||
})
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for conn in expired {
|
||||
conns.remove(&conn);
|
||||
transport::send_text(&mut ws, &Frame::Close { conn, reason: Some("expired".into()) })?;
|
||||
transport::send_text(
|
||||
&mut ws,
|
||||
&Frame::Close {
|
||||
conn,
|
||||
reason: Some("expired".into()),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
if last_ping.elapsed() > Duration::from_secs(20) {
|
||||
ws.send(Message::Ping(Vec::new().into())).map_err(|e| LinkError::Io(e.to_string()))?;
|
||||
ws.send(Message::Ping(Vec::new().into()))
|
||||
.map_err(|e| LinkError::Io(e.to_string()))?;
|
||||
last_ping = Instant::now();
|
||||
}
|
||||
set(status, |s| s.channels = conns.len());
|
||||
@@ -193,7 +283,14 @@ fn seal_all(channel: &mut Channel, message: &[u8]) -> Result<Vec<Vec<u8>>, Strin
|
||||
}
|
||||
|
||||
/// Advance one channel by one frame; the frames to send back, or the reason to close it.
|
||||
fn step(c: &mut Conn, frame: &[u8], realm: RealmId, key: &SigningKey, service: &HostService, status: &Mutex<LinkStatus>) -> Result<Vec<Vec<u8>>, String> {
|
||||
fn step(
|
||||
c: &mut Conn,
|
||||
frame: &[u8],
|
||||
realm: RealmId,
|
||||
key: &SigningKey,
|
||||
service: &HostService,
|
||||
status: &Mutex<LinkStatus>,
|
||||
) -> Result<Vec<Vec<u8>>, String> {
|
||||
let stage = c.stage.take().ok_or("a channel in no state")?;
|
||||
match stage {
|
||||
Stage::AwaitFirst => {
|
||||
@@ -204,7 +301,10 @@ fn step(c: &mut Conn, frame: &[u8], realm: RealmId, key: &SigningKey, service: &
|
||||
Stage::AwaitThird(responder) => {
|
||||
let mut channel = responder.finish(frame).map_err(|e| e.to_string())?;
|
||||
let proof = noise::host_proof(key, &realm, &channel);
|
||||
let frames = seal_all(&mut channel, &serde_json::to_vec(&proof).map_err(|e| e.to_string())?)?;
|
||||
let frames = seal_all(
|
||||
&mut channel,
|
||||
&serde_json::to_vec(&proof).map_err(|e| e.to_string())?,
|
||||
)?;
|
||||
c.stage = Some(Stage::AwaitPlayerProof(channel));
|
||||
Ok(frames)
|
||||
}
|
||||
@@ -213,28 +313,47 @@ fn step(c: &mut Conn, frame: &[u8], realm: RealmId, key: &SigningKey, service: &
|
||||
c.stage = Some(Stage::AwaitPlayerProof(channel));
|
||||
return Ok(vec![]);
|
||||
};
|
||||
let proof: PlayerProof = serde_json::from_slice(&message).map_err(|_| "a player proof is not valid".to_string())?;
|
||||
let proof: PlayerProof = serde_json::from_slice(&message)
|
||||
.map_err(|_| "a player proof is not valid".to_string())?;
|
||||
noise::verify_player_proof(&proof, &realm, &channel).map_err(|e| e.to_string())?;
|
||||
if !service.key_matches(&proof.player_id, &proof.public_key) {
|
||||
return Err("the player id belongs to another key".into());
|
||||
}
|
||||
c.stage = Some(Stage::Ready { channel, player: proof.player_id, public_key: proof.public_key, session: Session::with_client_ip(c.client_ip.clone()) });
|
||||
c.stage = Some(Stage::Ready {
|
||||
channel,
|
||||
player: proof.player_id,
|
||||
public_key: proof.public_key,
|
||||
session: Session::with_client_ip(c.client_ip.clone()),
|
||||
});
|
||||
Ok(vec![])
|
||||
}
|
||||
Stage::Ready { mut channel, player, public_key, mut session } => {
|
||||
Stage::Ready {
|
||||
mut channel,
|
||||
player,
|
||||
public_key,
|
||||
mut session,
|
||||
} => {
|
||||
let message = channel.open_frame(frame).map_err(|e| e.to_string())?;
|
||||
let out = match message {
|
||||
None => vec![],
|
||||
Some(bytes) => {
|
||||
let response = match app::decode_request(&bytes) {
|
||||
Ok(request) => service.handle(&mut session, &player, &public_key, request),
|
||||
Err(_) => Response::Error { code: AppError::Invalid, message: "That request is not valid.".into() },
|
||||
Err(_) => Response::Error {
|
||||
code: AppError::Invalid,
|
||||
message: "That request is not valid.".into(),
|
||||
},
|
||||
};
|
||||
set(status, |s| s.requests += 1);
|
||||
seal_all(&mut channel, &app::encode_response(&response))?
|
||||
}
|
||||
};
|
||||
c.stage = Some(Stage::Ready { channel, player, public_key, session });
|
||||
c.stage = Some(Stage::Ready {
|
||||
channel,
|
||||
player,
|
||||
public_key,
|
||||
session,
|
||||
});
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,14 +42,35 @@ struct Running {
|
||||
direct_route: Option<crate::control::direct_route::DirectRouteManager>,
|
||||
}
|
||||
|
||||
|
||||
impl HostControl {
|
||||
/// `url_override` replaces the Registry address from the settings (`COA_REGISTRY_URL` in tests and deployments).
|
||||
pub fn start(settings_dir: PathBuf, keys: Arc<dyn KeyStore>, store: Arc<Mutex<ControlStore>>, backend: Arc<dyn RealmBackend>, url_override: Option<String>) -> HostControl {
|
||||
Self::start_with(settings_dir, keys, store, backend, url_override, system_clock(), Duration::from_secs(2))
|
||||
pub fn start(
|
||||
settings_dir: PathBuf,
|
||||
keys: Arc<dyn KeyStore>,
|
||||
store: Arc<Mutex<ControlStore>>,
|
||||
backend: Arc<dyn RealmBackend>,
|
||||
url_override: Option<String>,
|
||||
) -> HostControl {
|
||||
Self::start_with(
|
||||
settings_dir,
|
||||
keys,
|
||||
store,
|
||||
backend,
|
||||
url_override,
|
||||
system_clock(),
|
||||
Duration::from_secs(2),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn start_with(settings_dir: PathBuf, keys: Arc<dyn KeyStore>, store: Arc<Mutex<ControlStore>>, backend: Arc<dyn RealmBackend>, url_override: Option<String>, clock: Clock, every: Duration) -> HostControl {
|
||||
pub fn start_with(
|
||||
settings_dir: PathBuf,
|
||||
keys: Arc<dyn KeyStore>,
|
||||
store: Arc<Mutex<ControlStore>>,
|
||||
backend: Arc<dyn RealmBackend>,
|
||||
url_override: Option<String>,
|
||||
clock: Clock,
|
||||
every: Duration,
|
||||
) -> HostControl {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let status = Arc::new(Mutex::new(BTreeMap::new()));
|
||||
let (s, st) = (stop.clone(), status.clone());
|
||||
@@ -59,24 +80,65 @@ impl HostControl {
|
||||
let mut running: BTreeMap<String, Running> = BTreeMap::new();
|
||||
while !s.load(Ordering::SeqCst) {
|
||||
let wanted = wanted(&settings_dir, keys.as_ref(), url_override.as_deref());
|
||||
running.retain(|id, r| wanted.get(id).is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url));
|
||||
running.retain(|id, r| {
|
||||
wanted
|
||||
.get(id)
|
||||
.is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url)
|
||||
});
|
||||
for (local_id, (realm_id, url, base, key)) in wanted {
|
||||
if running.contains_key(&local_id) {
|
||||
continue;
|
||||
}
|
||||
let service = Arc::new(HostService::new(&local_id, realm_id, store.clone(), backend.clone()));
|
||||
let relay_link = crate::control::transport::relay_url(&base, "/relay/v1/host")
|
||||
.map(|r_url| {
|
||||
let rl = crate::control::relay_link::RelayLink::start(r_url, realm_id, key.clone());
|
||||
service.set_relay(rl.clone());
|
||||
rl
|
||||
});
|
||||
let direct_route = Some(crate::control::direct_route::DirectRouteManager::start(Some(base.clone()), service.clone()));
|
||||
let link = HostLink::start(url.clone(), realm_id, key, service, clock.clone());
|
||||
running.insert(local_id, Running { realm_id, url, link, relay_link, direct_route });
|
||||
let service = Arc::new(HostService::new(
|
||||
&local_id,
|
||||
realm_id,
|
||||
store.clone(),
|
||||
backend.clone(),
|
||||
));
|
||||
let relay_link =
|
||||
crate::control::transport::relay_url(&base, "/relay/v1/host").map(
|
||||
|r_url| {
|
||||
let rl = crate::control::relay_link::RelayLink::start(
|
||||
r_url,
|
||||
realm_id,
|
||||
key.clone(),
|
||||
);
|
||||
service.set_relay(rl.clone());
|
||||
rl
|
||||
},
|
||||
);
|
||||
let direct_route =
|
||||
Some(crate::control::direct_route::DirectRouteManager::start(
|
||||
Some(base.clone()),
|
||||
service.clone(),
|
||||
));
|
||||
let link =
|
||||
HostLink::start(url.clone(), realm_id, key, service, clock.clone());
|
||||
running.insert(
|
||||
local_id,
|
||||
Running {
|
||||
realm_id,
|
||||
url,
|
||||
link,
|
||||
relay_link,
|
||||
direct_route,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Ok(mut st) = st.lock() {
|
||||
*st = running.iter().map(|(id, r)| (id.clone(), HostControlRealm { local_id: id.clone(), realm_id: r.realm_id.to_string(), link: r.link.status() })).collect();
|
||||
*st = running
|
||||
.iter()
|
||||
.map(|(id, r)| {
|
||||
(
|
||||
id.clone(),
|
||||
HostControlRealm {
|
||||
local_id: id.clone(),
|
||||
realm_id: r.realm_id.to_string(),
|
||||
link: r.link.status(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let end = std::time::Instant::now() + every;
|
||||
while std::time::Instant::now() < end && !s.load(Ordering::SeqCst) {
|
||||
@@ -86,12 +148,18 @@ impl HostControl {
|
||||
running.clear();
|
||||
})
|
||||
.ok();
|
||||
HostControl { stop, status, join: Mutex::new(join) }
|
||||
HostControl {
|
||||
stop,
|
||||
status,
|
||||
join: Mutex::new(join),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn status(&self) -> Vec<HostControlRealm> {
|
||||
self.status.lock().map(|s| s.values().cloned().collect()).unwrap_or_default()
|
||||
self.status
|
||||
.lock()
|
||||
.map(|s| s.values().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
@@ -112,15 +180,22 @@ type Wanted = BTreeMap<String, (RealmId, String, String, ed25519_dalek::SigningK
|
||||
|
||||
fn wanted(dir: &std::path::Path, keys: &dyn KeyStore, url_override: Option<&str>) -> Wanted {
|
||||
let mut out = Wanted::new();
|
||||
let Ok(s) = settings::load(dir) else { return out };
|
||||
let base = url_override.map(str::to_string).unwrap_or_else(|| s.effective_url().to_string());
|
||||
let Some(url) = coordinator_url(&base, "/coord/v1/host") else { return out };
|
||||
let Ok(s) = settings::load(dir) else {
|
||||
return out;
|
||||
};
|
||||
let base = url_override
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| s.effective_url().to_string());
|
||||
let Some(url) = coordinator_url(&base, "/coord/v1/host") else {
|
||||
return out;
|
||||
};
|
||||
for (local_id, cfg) in s.realms {
|
||||
let (true, Some(realm)) = (cfg.enabled, cfg.realm_id) else { continue };
|
||||
let (true, Some(realm)) = (cfg.enabled, cfg.realm_id) else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(Some(key)) = keys.load(&realm) {
|
||||
out.insert(local_id, (realm, url.clone(), base.clone(), key));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -36,15 +36,29 @@ impl PlayerIdentity {
|
||||
/// The stored identity, or a new one when the player has none yet.
|
||||
pub fn load_or_create(secrets: &dyn SecretStore) -> Result<PlayerIdentity> {
|
||||
if let Some(bytes) = secrets.get(NAME)? {
|
||||
let stored: Stored = serde_json::from_slice(&bytes).map_err(|_| Error::Invalid("the player identity is damaged".into()))?;
|
||||
let seed: [u8; 32] = B64.decode(&stored.seed).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| Error::Invalid("the player identity is damaged".into()))?;
|
||||
return Ok(PlayerIdentity { player_id: stored.player_id, key: SigningKey::from_bytes(&seed) });
|
||||
let stored: Stored = serde_json::from_slice(&bytes)
|
||||
.map_err(|_| Error::Invalid("the player identity is damaged".into()))?;
|
||||
let seed: [u8; 32] = B64
|
||||
.decode(&stored.seed)
|
||||
.ok()
|
||||
.and_then(|b| b.try_into().ok())
|
||||
.ok_or_else(|| Error::Invalid("the player identity is damaged".into()))?;
|
||||
return Ok(PlayerIdentity {
|
||||
player_id: stored.player_id,
|
||||
key: SigningKey::from_bytes(&seed),
|
||||
});
|
||||
}
|
||||
let mut seed = [0u8; 32];
|
||||
seed[..16].copy_from_slice(Uuid::new_v4().as_bytes());
|
||||
seed[16..].copy_from_slice(Uuid::new_v4().as_bytes());
|
||||
let id = PlayerIdentity { player_id: Uuid::now_v7(), key: SigningKey::from_bytes(&seed) };
|
||||
let stored = Stored { player_id: id.player_id, seed: B64.encode(seed) };
|
||||
let id = PlayerIdentity {
|
||||
player_id: Uuid::now_v7(),
|
||||
key: SigningKey::from_bytes(&seed),
|
||||
};
|
||||
let stored = Stored {
|
||||
player_id: id.player_id,
|
||||
seed: B64.encode(seed),
|
||||
};
|
||||
secrets.put(NAME, &serde_json::to_vec(&stored)?)?;
|
||||
Ok(id)
|
||||
}
|
||||
@@ -64,9 +78,20 @@ mod tests {
|
||||
let secrets = MemoryStore::default();
|
||||
let a = PlayerIdentity::load_or_create(&secrets).unwrap();
|
||||
let b = PlayerIdentity::load_or_create(&secrets).unwrap();
|
||||
assert_eq!((a.player_id, a.key.to_bytes()), (b.player_id, b.key.to_bytes()));
|
||||
assert_ne!(PlayerIdentity::load_or_create(&MemoryStore::default()).unwrap().player_id, a.player_id);
|
||||
assert!(!format!("{a:?}").contains(&B64.encode(a.key.to_bytes())), "the key is not printed");
|
||||
assert_eq!(
|
||||
(a.player_id, a.key.to_bytes()),
|
||||
(b.player_id, b.key.to_bytes())
|
||||
);
|
||||
assert_ne!(
|
||||
PlayerIdentity::load_or_create(&MemoryStore::default())
|
||||
.unwrap()
|
||||
.player_id,
|
||||
a.player_id
|
||||
);
|
||||
assert!(
|
||||
!format!("{a:?}").contains(&B64.encode(a.key.to_bytes())),
|
||||
"the key is not printed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -74,6 +99,10 @@ mod tests {
|
||||
let secrets = MemoryStore::default();
|
||||
secrets.put(NAME, b"garbage").unwrap();
|
||||
assert!(PlayerIdentity::load_or_create(&secrets).is_err());
|
||||
assert_eq!(secrets.get(NAME).unwrap().unwrap(), b"garbage", "nothing was overwritten");
|
||||
assert_eq!(
|
||||
secrets.get(NAME).unwrap().unwrap(),
|
||||
b"garbage",
|
||||
"nothing was overwritten"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -32,9 +32,17 @@ pub struct RealmTarget {
|
||||
impl RealmTarget {
|
||||
/// From the Registry's public record of the realm; the key published there is what the Host must prove it holds.
|
||||
pub fn from_detail(registry_url: &str, detail: &RealmDetail) -> Result<RealmTarget> {
|
||||
let key = coord::decode_public_key(&detail.public_key).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let coordinator = transport::coordinator_url(registry_url, "/coord/v1/player").ok_or_else(|| Error::Invalid("the Registry address is not usable for a connection".into()))?;
|
||||
Ok(RealmTarget { realm_id: detail.realm_id, key, coordinator })
|
||||
let key = coord::decode_public_key(&detail.public_key)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let coordinator =
|
||||
transport::coordinator_url(registry_url, "/coord/v1/player").ok_or_else(|| {
|
||||
Error::Invalid("the Registry address is not usable for a connection".into())
|
||||
})?;
|
||||
Ok(RealmTarget {
|
||||
realm_id: detail.realm_id,
|
||||
key,
|
||||
coordinator,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +57,10 @@ impl ControlFail {
|
||||
pub fn code(&self) -> String {
|
||||
match self {
|
||||
ControlFail::Link(e) => e.code().to_string(),
|
||||
ControlFail::App { code, .. } => serde_json::to_value(code).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "error".into()),
|
||||
ControlFail::App { code, .. } => serde_json::to_value(code)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(str::to_string))
|
||||
.unwrap_or_else(|| "error".into()),
|
||||
ControlFail::Local(_) => "local".into(),
|
||||
}
|
||||
}
|
||||
@@ -120,21 +131,33 @@ fn secret_name(realm: &RealmId) -> String {
|
||||
}
|
||||
|
||||
fn clock() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn expect<T>(response: Response, ok: impl FnOnce(Response) -> std::result::Result<T, Response>) -> R<T> {
|
||||
fn expect<T>(
|
||||
response: Response,
|
||||
ok: impl FnOnce(Response) -> std::result::Result<T, Response>,
|
||||
) -> R<T> {
|
||||
match ok(response) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(Response::Error { code, message }) => Err(ControlFail::App { code, message }),
|
||||
Err(_) => Err(ControlFail::Link(LinkError::Protocol("the answer does not match the question".into()))),
|
||||
Err(_) => Err(ControlFail::Link(LinkError::Protocol(
|
||||
"the answer does not match the question".into(),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayerControl {
|
||||
pub fn open(dir: &Path, secrets: Arc<dyn SecretStore>) -> Result<Self> {
|
||||
let identity = PlayerIdentity::load_or_create(secrets.as_ref())?;
|
||||
Ok(Self { identity, secrets, store: Mutex::new(ControlStore::open(dir)?) })
|
||||
Ok(Self {
|
||||
identity,
|
||||
secrets,
|
||||
store: Mutex::new(ControlStore::open(dir)?),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn secret_store_kind(&self) -> &'static str {
|
||||
@@ -142,21 +165,30 @@ impl PlayerControl {
|
||||
}
|
||||
|
||||
fn store(&self) -> R<std::sync::MutexGuard<'_, ControlStore>> {
|
||||
self.store.lock().map_err(|_| ControlFail::Local("the control database is busy".into()))
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| ControlFail::Local("the control database is busy".into()))
|
||||
}
|
||||
|
||||
/// The credentials the realm has confirmed (a password still waiting for the realm's confirmation is not one).
|
||||
pub fn credentials(&self, realm: &RealmId) -> Result<Option<Credentials>> {
|
||||
Ok(self.raw_credentials(realm)?.filter(|c| !c.username.is_empty()))
|
||||
Ok(self
|
||||
.raw_credentials(realm)?
|
||||
.filter(|c| !c.username.is_empty()))
|
||||
}
|
||||
|
||||
fn raw_credentials(&self, realm: &RealmId) -> Result<Option<Credentials>> {
|
||||
let Some(bytes) = self.secrets.get(&secret_name(realm))? else { return Ok(None) };
|
||||
serde_json::from_slice(&bytes).map(Some).map_err(|_| Error::Invalid("the saved credentials for this server are damaged".into()))
|
||||
let Some(bytes) = self.secrets.get(&secret_name(realm))? else {
|
||||
return Ok(None);
|
||||
};
|
||||
serde_json::from_slice(&bytes)
|
||||
.map(Some)
|
||||
.map_err(|_| Error::Invalid("the saved credentials for this server are damaged".into()))
|
||||
}
|
||||
|
||||
fn save_credentials(&self, realm: &RealmId, c: &Credentials) -> Result<()> {
|
||||
self.secrets.put(&secret_name(realm), &serde_json::to_vec(c)?)
|
||||
self.secrets
|
||||
.put(&secret_name(realm), &serde_json::to_vec(c)?)
|
||||
}
|
||||
|
||||
/// Forget the account on a realm (the saved password and the name). The account itself stays on the realm.
|
||||
@@ -167,7 +199,10 @@ impl PlayerControl {
|
||||
}
|
||||
|
||||
pub fn known_account(&self, realm: &RealmId) -> R<Option<(String, AccountKind)>> {
|
||||
Ok(self.store()?.player_realm(&realm.to_string())?.map(|r| (r.username, r.kind)))
|
||||
Ok(self
|
||||
.store()?
|
||||
.player_realm(&realm.to_string())?
|
||||
.map(|r| (r.username, r.kind)))
|
||||
}
|
||||
|
||||
/// Open a verified channel to the realm's Host. The realm's key is pinned the first time: the Registry says which key a realm id has, and a Registry (or anything between) that later
|
||||
@@ -176,35 +211,75 @@ impl PlayerControl {
|
||||
let id = target.realm_id.to_string();
|
||||
let key = coord::encode_public_key(&target.key);
|
||||
match self.store()?.realm_pin(&id)? {
|
||||
Some(pinned) if pinned != key => return Err(ControlFail::Link(LinkError::Auth("this realm's key is not the one it had when you first joined it".into()))),
|
||||
Some(pinned) if pinned != key => {
|
||||
return Err(ControlFail::Link(LinkError::Auth(
|
||||
"this realm's key is not the one it had when you first joined it".into(),
|
||||
)))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let channel = PlayerChannel::connect(&target.coordinator, &target.realm_id, &target.key, &self.identity, &clock)?;
|
||||
let channel = PlayerChannel::connect(
|
||||
&target.coordinator,
|
||||
&target.realm_id,
|
||||
&target.key,
|
||||
&self.identity,
|
||||
&clock,
|
||||
)?;
|
||||
self.store()?.realm_pin_set(&id, &key)?;
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
pub fn welcome(&self, ch: &mut PlayerChannel) -> R<(bool, bool, Option<String>)> {
|
||||
let r = ch.request(&Request::Hello { protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION, client: "coa-manager".into() })?;
|
||||
let r = ch.request(&Request::Hello {
|
||||
protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION,
|
||||
client: "coa-manager".into(),
|
||||
})?;
|
||||
expect(r, |r| match r {
|
||||
Response::Welcome { automatic, existing_only, route, .. } => Ok((automatic, existing_only, route)),
|
||||
Response::Welcome {
|
||||
automatic,
|
||||
existing_only,
|
||||
route,
|
||||
..
|
||||
} => Ok((automatic, existing_only, route)),
|
||||
other => Err(other),
|
||||
})
|
||||
}
|
||||
|
||||
/// The account on this realm: reused when the player has one, created otherwise (on realms that create accounts). The generated password is saved *before* it is
|
||||
/// sent, so a crash between the Host creating the account and the player learning of it leaves a password that the next call sets again.
|
||||
pub fn ensure_account(&self, ch: &mut PlayerChannel, realm: &RealmId, preferred: Option<&str>) -> R<AccountOutcome> {
|
||||
pub fn ensure_account(
|
||||
&self,
|
||||
ch: &mut PlayerChannel,
|
||||
realm: &RealmId,
|
||||
preferred: Option<&str>,
|
||||
) -> R<AccountOutcome> {
|
||||
let saved = self.raw_credentials(realm)?;
|
||||
// saved credentials with no account name are a password that was made but never confirmed by the realm: it is sent again, as a new one
|
||||
let have = saved.as_ref().is_some_and(|c| !c.username.is_empty());
|
||||
let password = saved.as_ref().map(|c| c.password.clone()).unwrap_or_else(app::generate_password);
|
||||
let password = saved
|
||||
.as_ref()
|
||||
.map(|c| c.password.clone())
|
||||
.unwrap_or_else(app::generate_password);
|
||||
if saved.is_none() {
|
||||
self.save_credentials(realm, &Credentials { username: String::new(), password: password.clone() })?;
|
||||
self.save_credentials(
|
||||
realm,
|
||||
&Credentials {
|
||||
username: String::new(),
|
||||
password: password.clone(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
let r = ch.request(&Request::Provision { desired: preferred.map(str::to_string), password: password.clone(), have_credentials: have })?;
|
||||
let r = ch.request(&Request::Provision {
|
||||
desired: preferred.map(str::to_string),
|
||||
password: password.clone(),
|
||||
have_credentials: have,
|
||||
})?;
|
||||
let (username, created, reset) = expect(r, |r| match r {
|
||||
Response::Provisioned { username, created, reset } => Ok((username, created, reset)),
|
||||
Response::Provisioned {
|
||||
username,
|
||||
created,
|
||||
reset,
|
||||
} => Ok((username, created, reset)),
|
||||
other => Err(other),
|
||||
})
|
||||
.inspect_err(|e| {
|
||||
@@ -213,25 +288,52 @@ impl PlayerControl {
|
||||
let _ = self.secrets.delete(&secret_name(realm));
|
||||
}
|
||||
})?;
|
||||
self.save_credentials(realm, &Credentials { username: username.clone(), password })?;
|
||||
self.save_credentials(
|
||||
realm,
|
||||
&Credentials {
|
||||
username: username.clone(),
|
||||
password,
|
||||
},
|
||||
)?;
|
||||
// an account the player linked stays a linked one when the realm confirms it again
|
||||
let kind = match self.store()?.player_realm(&realm.to_string())? {
|
||||
Some(known) if known.username == username => known.kind,
|
||||
_ => AccountKind::Generated,
|
||||
};
|
||||
self.store()?.player_realm_set(&realm.to_string(), &username, kind)?;
|
||||
Ok(AccountOutcome { username, created, password_reset: reset })
|
||||
self.store()?
|
||||
.player_realm_set(&realm.to_string(), &username, kind)?;
|
||||
Ok(AccountOutcome {
|
||||
username,
|
||||
created,
|
||||
password_reset: reset,
|
||||
})
|
||||
}
|
||||
|
||||
/// One-time link of an account the realm already has.
|
||||
pub fn link_existing(&self, ch: &mut PlayerChannel, realm: &RealmId, login: &str, password: &str) -> R<String> {
|
||||
let r = ch.request(&Request::Link { login: login.to_string(), password: password.to_string() })?;
|
||||
pub fn link_existing(
|
||||
&self,
|
||||
ch: &mut PlayerChannel,
|
||||
realm: &RealmId,
|
||||
login: &str,
|
||||
password: &str,
|
||||
) -> R<String> {
|
||||
let r = ch.request(&Request::Link {
|
||||
login: login.to_string(),
|
||||
password: password.to_string(),
|
||||
})?;
|
||||
let username = expect(r, |r| match r {
|
||||
Response::Linked { username } => Ok(username),
|
||||
other => Err(other),
|
||||
})?;
|
||||
self.save_credentials(realm, &Credentials { username: username.clone(), password: password.to_string() })?;
|
||||
self.store()?.player_realm_set(&realm.to_string(), &username, AccountKind::Linked)?;
|
||||
self.save_credentials(
|
||||
realm,
|
||||
&Credentials {
|
||||
username: username.clone(),
|
||||
password: password.to_string(),
|
||||
},
|
||||
)?;
|
||||
self.store()?
|
||||
.player_realm_set(&realm.to_string(), &username, AccountKind::Linked)?;
|
||||
Ok(username)
|
||||
}
|
||||
|
||||
@@ -246,17 +348,47 @@ impl PlayerControl {
|
||||
pub fn claim(&self, ch: &mut PlayerChannel, token: u32) -> R<Claimed> {
|
||||
let r = ch.request(&Request::Claim { token })?;
|
||||
let (character_id, sha256, payload, collections) = expect(r, |r| match r {
|
||||
Response::Claimed { character_id, sha256, payload, collections } => Ok((character_id, sha256, payload, collections)),
|
||||
Response::Claimed {
|
||||
character_id,
|
||||
sha256,
|
||||
payload,
|
||||
collections,
|
||||
} => Ok((character_id, sha256, payload, collections)),
|
||||
other => Err(other),
|
||||
})?;
|
||||
let payload = base64::engine::general_purpose::STANDARD.decode(payload).map_err(|_| ControlFail::Link(LinkError::Protocol("the character data is not valid".into())))?;
|
||||
let hash: [u8; 32] = hex::decode(&sha256).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| ControlFail::Link(LinkError::Protocol("the character hash is not valid".into())))?;
|
||||
Ok(Claimed { character_id, payload, sha256: hash, collections })
|
||||
let payload = base64::engine::general_purpose::STANDARD
|
||||
.decode(payload)
|
||||
.map_err(|_| {
|
||||
ControlFail::Link(LinkError::Protocol(
|
||||
"the character data is not valid".into(),
|
||||
))
|
||||
})?;
|
||||
let hash: [u8; 32] = hex::decode(&sha256)
|
||||
.ok()
|
||||
.and_then(|b| b.try_into().ok())
|
||||
.ok_or_else(|| {
|
||||
ControlFail::Link(LinkError::Protocol(
|
||||
"the character hash is not valid".into(),
|
||||
))
|
||||
})?;
|
||||
Ok(Claimed {
|
||||
character_id,
|
||||
payload,
|
||||
sha256: hash,
|
||||
collections,
|
||||
})
|
||||
}
|
||||
|
||||
/// Tell the Host the character is safely stored here; only then is the claim final.
|
||||
pub fn acknowledge(&self, ch: &mut PlayerChannel, character_id: Uuid, realm: &RealmId, name: &str) -> R<()> {
|
||||
self.store()?.player_claim_add(&realm.to_string(), &character_id, name)?;
|
||||
pub fn acknowledge(
|
||||
&self,
|
||||
ch: &mut PlayerChannel,
|
||||
character_id: Uuid,
|
||||
realm: &RealmId,
|
||||
name: &str,
|
||||
) -> R<()> {
|
||||
self.store()?
|
||||
.player_claim_add(&realm.to_string(), &character_id, name)?;
|
||||
let r = ch.request(&Request::ClaimAck { character_id })?;
|
||||
expect(r, |r| match r {
|
||||
Response::Done => Ok(()),
|
||||
@@ -298,19 +430,40 @@ impl PlayerControl {
|
||||
};
|
||||
let r = ch.request(&offer)?;
|
||||
let mut offset = match r {
|
||||
Response::TransferReady { received_offset, .. } => received_offset,
|
||||
Response::TransferCommitted { local_guid, session_id, projected_level, notes, .. } => {
|
||||
let _ = ch.request(&Request::TransferAck { transfer_id, character_id });
|
||||
return Ok(RemoteTransferOutcome { local_guid, session_id, projected_level, notes });
|
||||
Response::TransferReady {
|
||||
received_offset, ..
|
||||
} => received_offset,
|
||||
Response::TransferCommitted {
|
||||
local_guid,
|
||||
session_id,
|
||||
projected_level,
|
||||
notes,
|
||||
..
|
||||
} => {
|
||||
let _ = ch.request(&Request::TransferAck {
|
||||
transfer_id,
|
||||
character_id,
|
||||
});
|
||||
return Ok(RemoteTransferOutcome {
|
||||
local_guid,
|
||||
session_id,
|
||||
projected_level,
|
||||
notes,
|
||||
});
|
||||
}
|
||||
Response::Error { code, message } => return Err(ControlFail::App { code, message }),
|
||||
_ => return Err(ControlFail::Link(LinkError::Protocol("unexpected response to transfer offer".into()))),
|
||||
_ => {
|
||||
return Err(ControlFail::Link(LinkError::Protocol(
|
||||
"unexpected response to transfer offer".into(),
|
||||
)))
|
||||
}
|
||||
};
|
||||
|
||||
const CHUNK_SIZE: usize = 128 * 1024;
|
||||
while offset < payload.len() {
|
||||
let end = (offset + CHUNK_SIZE).min(payload.len());
|
||||
let chunk_data = base64::engine::general_purpose::STANDARD.encode(&payload[offset..end]);
|
||||
let chunk_data =
|
||||
base64::engine::general_purpose::STANDARD.encode(&payload[offset..end]);
|
||||
let chunk_req = Request::TransferChunk {
|
||||
transfer_id,
|
||||
offset,
|
||||
@@ -318,24 +471,44 @@ impl PlayerControl {
|
||||
};
|
||||
let cr = ch.request(&chunk_req)?;
|
||||
match cr {
|
||||
Response::TransferChunkAck { received_offset, .. } => {
|
||||
Response::TransferChunkAck {
|
||||
received_offset, ..
|
||||
} => {
|
||||
offset = received_offset;
|
||||
}
|
||||
Response::Error { code, message } => return Err(ControlFail::App { code, message }),
|
||||
_ => return Err(ControlFail::Link(LinkError::Protocol("unexpected response to transfer chunk".into()))),
|
||||
Response::Error { code, message } => {
|
||||
return Err(ControlFail::App { code, message })
|
||||
}
|
||||
_ => {
|
||||
return Err(ControlFail::Link(LinkError::Protocol(
|
||||
"unexpected response to transfer chunk".into(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let commit_req = Request::TransferCommit { transfer_id };
|
||||
let commit_resp = ch.request(&commit_req)?;
|
||||
let outcome = expect(commit_resp, |r| match r {
|
||||
Response::TransferCommitted { local_guid, session_id, projected_level, notes, .. } => {
|
||||
Ok(RemoteTransferOutcome { local_guid, session_id, projected_level, notes })
|
||||
}
|
||||
Response::TransferCommitted {
|
||||
local_guid,
|
||||
session_id,
|
||||
projected_level,
|
||||
notes,
|
||||
..
|
||||
} => Ok(RemoteTransferOutcome {
|
||||
local_guid,
|
||||
session_id,
|
||||
projected_level,
|
||||
notes,
|
||||
}),
|
||||
other => Err(other),
|
||||
})?;
|
||||
|
||||
let _ = ch.request(&Request::TransferAck { transfer_id, character_id });
|
||||
let _ = ch.request(&Request::TransferAck {
|
||||
transfer_id,
|
||||
character_id,
|
||||
});
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
@@ -344,24 +517,29 @@ impl PlayerControl {
|
||||
&self,
|
||||
ch: &mut PlayerChannel,
|
||||
) -> R<crate::control::relay_link::RelayAllocationInfo> {
|
||||
let req = Request::AllocateRelay { player_id: self.identity.player_id };
|
||||
let req = Request::AllocateRelay {
|
||||
player_id: self.identity.player_id,
|
||||
};
|
||||
let resp = ch.request(&req)?;
|
||||
expect(resp, |r| match r {
|
||||
Response::RelayAllocated { relay_host, auth_port, world_port, token, expires_at } => {
|
||||
Ok(crate::control::relay_link::RelayAllocationInfo {
|
||||
relay_host,
|
||||
auth_port,
|
||||
world_port,
|
||||
token,
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
Response::RelayAllocated {
|
||||
relay_host,
|
||||
auth_port,
|
||||
world_port,
|
||||
token,
|
||||
expires_at,
|
||||
} => Ok(crate::control::relay_link::RelayAllocationInfo {
|
||||
relay_host,
|
||||
auth_port,
|
||||
world_port,
|
||||
token,
|
||||
expires_at,
|
||||
}),
|
||||
other => Err(other),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemoteTransferOutcome {
|
||||
pub local_guid: u32,
|
||||
|
||||
@@ -15,4 +15,3 @@ pub mod secrets;
|
||||
pub mod service;
|
||||
pub mod store;
|
||||
pub mod transport;
|
||||
|
||||
@@ -9,7 +9,8 @@ pub const NAT_PMP_PORT: u16 = 5351;
|
||||
/// Request the external (public) IPv4 address from the NAT-PMP gateway.
|
||||
pub fn query_external_ip(gateway: Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
let sock = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
sock.set_read_timeout(Some(Duration::from_millis(800))).ok()?;
|
||||
sock.set_read_timeout(Some(Duration::from_millis(800)))
|
||||
.ok()?;
|
||||
let target = SocketAddr::V4(SocketAddrV4::new(gateway, NAT_PMP_PORT));
|
||||
|
||||
// NAT-PMP External Address Request: Version 0 (1 byte), Opcode 0 (1 byte)
|
||||
@@ -44,7 +45,8 @@ pub fn request_mapping(
|
||||
lifetime_secs: u32,
|
||||
) -> Option<u16> {
|
||||
let sock = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
sock.set_read_timeout(Some(Duration::from_millis(1000))).ok()?;
|
||||
sock.set_read_timeout(Some(Duration::from_millis(1000)))
|
||||
.ok()?;
|
||||
let target = SocketAddr::V4(SocketAddrV4::new(gateway, NAT_PMP_PORT));
|
||||
|
||||
// NAT-PMP TCP Mapping Request:
|
||||
@@ -107,11 +109,17 @@ mod tests {
|
||||
req_map[8..12].copy_from_slice(&3600u32.to_be_bytes());
|
||||
assert_eq!(req_map[1], 2);
|
||||
assert_eq!(u16::from_be_bytes([req_map[4], req_map[5]]), 3724);
|
||||
assert_eq!(u32::from_be_bytes([req_map[8], req_map[9], req_map[10], req_map[11]]), 3600);
|
||||
assert_eq!(
|
||||
u32::from_be_bytes([req_map[8], req_map[9], req_map[10], req_map[11]]),
|
||||
3600
|
||||
);
|
||||
|
||||
// Test timeout on unanswering gateway
|
||||
assert_eq!(query_external_ip(Ipv4Addr::new(127, 0, 0, 1)), None);
|
||||
assert_eq!(request_mapping(Ipv4Addr::new(127, 0, 0, 1), 3724, 3724, 3600), None);
|
||||
assert_eq!(
|
||||
request_mapping(Ipv4Addr::new(127, 0, 0, 1), 3724, 3724, 3600),
|
||||
None
|
||||
);
|
||||
assert!(!delete_mapping(Ipv4Addr::new(127, 0, 0, 1), 3724));
|
||||
}
|
||||
}
|
||||
@@ -23,16 +23,32 @@ const ANSWER: Duration = Duration::from_secs(60);
|
||||
|
||||
impl PlayerChannel {
|
||||
/// `coordinator` is the Coordinator's player endpoint without the query, e.g. `wss://registry.example/coord/v1/player`.
|
||||
pub fn connect(coordinator: &str, realm: &RealmId, realm_key: &VerifyingKey, identity: &PlayerIdentity, clock: &dyn Fn() -> i64) -> Result<PlayerChannel, LinkError> {
|
||||
let mut ws = transport::connect(&format!("{coordinator}?realm={realm}"), Duration::from_millis(500))?;
|
||||
pub fn connect(
|
||||
coordinator: &str,
|
||||
realm: &RealmId,
|
||||
realm_key: &VerifyingKey,
|
||||
identity: &PlayerIdentity,
|
||||
clock: &dyn Fn() -> i64,
|
||||
) -> Result<PlayerChannel, LinkError> {
|
||||
let mut ws = transport::connect(
|
||||
&format!("{coordinator}?realm={realm}"),
|
||||
Duration::from_millis(500),
|
||||
)?;
|
||||
let nonce = match transport::next_frame(&mut ws, STEP)? {
|
||||
Frame::Challenge { nonce, .. } => nonce,
|
||||
_ => return Err(LinkError::Protocol("a challenge was expected".into())),
|
||||
};
|
||||
transport::send_text(&mut ws, &coord::sign_player_hello(&identity.key, &identity.player_id, realm, &nonce, clock()))?;
|
||||
transport::send_text(
|
||||
&mut ws,
|
||||
&coord::sign_player_hello(&identity.key, &identity.player_id, realm, &nonce, clock()),
|
||||
)?;
|
||||
let conn = match transport::next_frame(&mut ws, STEP)? {
|
||||
Frame::PlayerReady { conn, .. } => conn,
|
||||
_ => return Err(LinkError::Protocol("the Coordinator did not accept the hello".into())),
|
||||
_ => {
|
||||
return Err(LinkError::Protocol(
|
||||
"the Coordinator did not accept the hello".into(),
|
||||
))
|
||||
}
|
||||
};
|
||||
let (initiator, msg1) = Initiator::start().map_err(LinkError::from)?;
|
||||
transport::send_binary(&mut ws, msg1)?;
|
||||
@@ -41,10 +57,14 @@ impl PlayerChannel {
|
||||
transport::send_binary(&mut ws, msg3)?;
|
||||
// the Host proves it holds the realm's key on this very channel before anything private is said
|
||||
let proof_bytes = next_message(&mut ws, &mut channel, STEP)?;
|
||||
let proof: HostProof = serde_json::from_slice(&proof_bytes).map_err(|_| LinkError::Auth("the host's proof is not valid".into()))?;
|
||||
let proof: HostProof = serde_json::from_slice(&proof_bytes)
|
||||
.map_err(|_| LinkError::Auth("the host's proof is not valid".into()))?;
|
||||
noise::verify_host_proof(&proof, realm_key, realm, &channel).map_err(LinkError::from)?;
|
||||
let mine = noise::player_proof(&identity.key, realm, &identity.player_id, &channel);
|
||||
for f in channel.seal(&serde_json::to_vec(&mine).map_err(|e| LinkError::Protocol(e.to_string()))?).map_err(LinkError::from)? {
|
||||
for f in channel
|
||||
.seal(&serde_json::to_vec(&mine).map_err(|e| LinkError::Protocol(e.to_string()))?)
|
||||
.map_err(LinkError::from)?
|
||||
{
|
||||
transport::send_binary(&mut ws, f)?;
|
||||
}
|
||||
Ok(PlayerChannel { ws, channel, conn })
|
||||
@@ -55,7 +75,11 @@ impl PlayerChannel {
|
||||
}
|
||||
|
||||
pub fn request(&mut self, request: &Request) -> Result<Response, LinkError> {
|
||||
for f in self.channel.seal(&app::encode_request(request)).map_err(LinkError::from)? {
|
||||
for f in self
|
||||
.channel
|
||||
.seal(&app::encode_request(request))
|
||||
.map_err(LinkError::from)?
|
||||
{
|
||||
transport::send_binary(&mut self.ws, f)?;
|
||||
}
|
||||
let bytes = next_message(&mut self.ws, &mut self.channel, ANSWER)?;
|
||||
@@ -79,12 +103,16 @@ fn next_binary(ws: &mut Ws, total: Duration) -> Result<Vec<u8>, LinkError> {
|
||||
Some(tungstenite::Message::Text(t)) => {
|
||||
// an error frame from the Coordinator (the Host went away, a limit was hit)
|
||||
return match coord::parse_text(t.as_str()).map_err(LinkError::from)? {
|
||||
Frame::Error { code, message } => Err(transport::from_error_frame(code, &message)),
|
||||
Frame::Error { code, message } => {
|
||||
Err(transport::from_error_frame(code, &message))
|
||||
}
|
||||
Frame::Close { .. } => Err(LinkError::HostOffline),
|
||||
_ => Err(LinkError::Protocol("an unexpected control frame".into())),
|
||||
};
|
||||
}
|
||||
Some(tungstenite::Message::Close(_)) => return Err(LinkError::Io("the connection was closed".into())),
|
||||
Some(tungstenite::Message::Close(_)) => {
|
||||
return Err(LinkError::Io("the connection was closed".into()))
|
||||
}
|
||||
Some(_) => continue,
|
||||
}
|
||||
}
|
||||
@@ -94,7 +122,9 @@ fn next_binary(ws: &mut Ws, total: Duration) -> Result<Vec<u8>, LinkError> {
|
||||
fn next_message(ws: &mut Ws, channel: &mut Channel, total: Duration) -> Result<Vec<u8>, LinkError> {
|
||||
let end = std::time::Instant::now() + total;
|
||||
loop {
|
||||
let left = end.checked_duration_since(std::time::Instant::now()).ok_or(LinkError::Timeout)?;
|
||||
let left = end
|
||||
.checked_duration_since(std::time::Instant::now())
|
||||
.ok_or(LinkError::Timeout)?;
|
||||
let frame = next_binary(ws, left)?;
|
||||
if let Some(m) = channel.open_frame(&frame).map_err(LinkError::from)? {
|
||||
return Ok(m);
|
||||
|
||||
@@ -34,7 +34,11 @@ pub struct RelayStatus {
|
||||
pub struct RelayLink {
|
||||
stop: Arc<AtomicBool>,
|
||||
status: Arc<Mutex<RelayStatus>>,
|
||||
alloc_tx: Sender<(Uuid, Option<String>, Sender<Result<RelayAllocationInfo, LinkError>>)>,
|
||||
alloc_tx: Sender<(
|
||||
Uuid,
|
||||
Option<String>,
|
||||
Sender<Result<RelayAllocationInfo, LinkError>>,
|
||||
)>,
|
||||
join: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
@@ -48,24 +52,25 @@ pub struct RelayAllocationInfo {
|
||||
}
|
||||
|
||||
impl RelayProvider for RelayLink {
|
||||
fn allocate(&self, player_id: &Uuid, client_ip: Option<&str>) -> crate::error::Result<RelayAllocationInfo> {
|
||||
fn allocate(
|
||||
&self,
|
||||
player_id: &Uuid,
|
||||
client_ip: Option<&str>,
|
||||
) -> crate::error::Result<RelayAllocationInfo> {
|
||||
let (tx, rx) = channel();
|
||||
self.alloc_tx
|
||||
.send((*player_id, client_ip.map(|s| s.to_string()), tx))
|
||||
.map_err(|_| crate::error::Error::Invalid("relay link worker thread not running".to_string()))?;
|
||||
.map_err(|_| {
|
||||
crate::error::Error::Invalid("relay link worker thread not running".to_string())
|
||||
})?;
|
||||
rx.recv_timeout(Duration::from_secs(10))
|
||||
.map_err(|_| crate::error::Error::Invalid("relay allocation timed out".to_string()))?
|
||||
.map_err(|e| crate::error::Error::Invalid(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl RelayLink {
|
||||
pub fn start(
|
||||
url: String,
|
||||
realm_id: RealmId,
|
||||
key: SigningKey,
|
||||
) -> Arc<Self> {
|
||||
pub fn start(url: String, realm_id: RealmId, key: SigningKey) -> Arc<Self> {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let status = Arc::new(Mutex::new(RelayStatus::default()));
|
||||
let (alloc_tx, alloc_rx) = channel();
|
||||
@@ -115,7 +120,11 @@ fn run(
|
||||
url: &str,
|
||||
realm: RealmId,
|
||||
key: &SigningKey,
|
||||
alloc_rx: Receiver<(Uuid, Option<String>, Sender<Result<RelayAllocationInfo, LinkError>>)>,
|
||||
alloc_rx: Receiver<(
|
||||
Uuid,
|
||||
Option<String>,
|
||||
Sender<Result<RelayAllocationInfo, LinkError>>,
|
||||
)>,
|
||||
stop: &AtomicBool,
|
||||
status: &Mutex<RelayStatus>,
|
||||
) {
|
||||
@@ -160,7 +169,11 @@ fn session(
|
||||
url: &str,
|
||||
realm: RealmId,
|
||||
key: &SigningKey,
|
||||
alloc_rx: &Receiver<(Uuid, Option<String>, Sender<Result<RelayAllocationInfo, LinkError>>)>,
|
||||
alloc_rx: &Receiver<(
|
||||
Uuid,
|
||||
Option<String>,
|
||||
Sender<Result<RelayAllocationInfo, LinkError>>,
|
||||
)>,
|
||||
stop: &AtomicBool,
|
||||
status: &Mutex<RelayStatus>,
|
||||
) -> Result<(), LinkError> {
|
||||
@@ -180,7 +193,7 @@ fn session(
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
got.ok_or_else(|| LinkError::Timeout)?
|
||||
got.ok_or(LinkError::Timeout)?
|
||||
}
|
||||
};
|
||||
|
||||
@@ -224,7 +237,8 @@ fn session(
|
||||
tracing::info!(%realm, "relay link active");
|
||||
|
||||
let mut streams: HashMap<u32, StreamWorker> = HashMap::new();
|
||||
let mut pending_allocs: HashMap<u64, Sender<Result<RelayAllocationInfo, LinkError>>> = HashMap::new();
|
||||
let mut pending_allocs: HashMap<u64, Sender<Result<RelayAllocationInfo, LinkError>>> =
|
||||
HashMap::new();
|
||||
let req_counter = AtomicU64::new(1);
|
||||
let (ws_out_tx, ws_out_rx) = channel::<TunnelMsg>();
|
||||
|
||||
@@ -250,7 +264,9 @@ fn session(
|
||||
|
||||
// Keepalive
|
||||
if last_ping.elapsed() > Duration::from_secs(30) {
|
||||
let _ = ws.send(Message::Text(serde_json::to_string(&TunnelMsg::Ping).unwrap().into()));
|
||||
let _ = ws.send(Message::Text(
|
||||
serde_json::to_string(&TunnelMsg::Ping).unwrap().into(),
|
||||
));
|
||||
last_ping = Instant::now();
|
||||
}
|
||||
|
||||
@@ -259,7 +275,9 @@ fn session(
|
||||
match transport::poll(&mut ws)? {
|
||||
None => break,
|
||||
Some(Message::Text(text)) => {
|
||||
let Ok(msg) = serde_json::from_str::<TunnelMsg>(&text) else { continue };
|
||||
let Ok(msg) = serde_json::from_str::<TunnelMsg>(&text) else {
|
||||
continue;
|
||||
};
|
||||
match msg {
|
||||
TunnelMsg::AllocateOk {
|
||||
request_id,
|
||||
@@ -284,7 +302,9 @@ fn session(
|
||||
let _ = tx.send(Err(LinkError::Protocol(error)));
|
||||
}
|
||||
}
|
||||
TunnelMsg::Connect { stream_id, target, .. } => {
|
||||
TunnelMsg::Connect {
|
||||
stream_id, target, ..
|
||||
} => {
|
||||
// Strictly predefined local targets: Auth (3724) or World (8085)
|
||||
let local_port = target.local_port();
|
||||
match TcpStream::connect(("127.0.0.1", local_port)) {
|
||||
@@ -298,14 +318,18 @@ fn session(
|
||||
|
||||
// Reply ConnectOk
|
||||
let ok_msg = TunnelMsg::ConnectOk { stream_id };
|
||||
let _ = ws.send(Message::Text(serde_json::to_string(&ok_msg).unwrap().into()));
|
||||
let _ = ws.send(Message::Text(
|
||||
serde_json::to_string(&ok_msg).unwrap().into(),
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
let err_msg = TunnelMsg::ConnectErr {
|
||||
stream_id,
|
||||
error: e.to_string(),
|
||||
};
|
||||
let _ = ws.send(Message::Text(serde_json::to_string(&err_msg).unwrap().into()));
|
||||
let _ = ws.send(Message::Text(
|
||||
serde_json::to_string(&err_msg).unwrap().into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
set_status(status, |s| s.active_streams = streams.len());
|
||||
@@ -331,7 +355,9 @@ fn session(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(Message::Close(_)) => return Err(LinkError::Io("relay closed connection".into())),
|
||||
Some(Message::Close(_)) => {
|
||||
return Err(LinkError::Io("relay closed connection".into()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -364,7 +390,10 @@ fn spawn_local_tcp_bridge(
|
||||
}
|
||||
Ok(n) => {
|
||||
let chunk = base64::engine::general_purpose::STANDARD.encode(&buf[..n]);
|
||||
if to_tunnel_read.send(TunnelMsg::Data { stream_id, chunk }).is_err() {
|
||||
if to_tunnel_read
|
||||
.send(TunnelMsg::Data { stream_id, chunk })
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,13 @@ pub trait SecretStore: Send + Sync {
|
||||
}
|
||||
|
||||
fn check_name(name: &str) -> Result<()> {
|
||||
if name.is_empty() || name.len() > 96 || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) || name.starts_with('.') {
|
||||
if name.is_empty()
|
||||
|| name.len() > 96
|
||||
|| !name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
|
||||
|| name.starts_with('.')
|
||||
{
|
||||
return Err(Error::Invalid("a secret has an invalid name".into()));
|
||||
}
|
||||
Ok(())
|
||||
@@ -43,11 +49,16 @@ pub fn default_store(dir: &Path) -> Box<dyn SecretStore> {
|
||||
}
|
||||
|
||||
fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
let dir = path.parent().ok_or_else(|| Error::Invalid("a secret has no folder".into()))?;
|
||||
let dir = path
|
||||
.parent()
|
||||
.ok_or_else(|| Error::Invalid("a secret has no folder".into()))?;
|
||||
fs::create_dir_all(dir)?;
|
||||
let tmp = dir.join(format!(".{}.tmp", uuid::Uuid::new_v4().simple()));
|
||||
let result = (|| -> Result<()> {
|
||||
let mut f = fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let mut f = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)?;
|
||||
restrict(&tmp)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()?;
|
||||
@@ -70,12 +81,24 @@ fn restrict(file: &Path) -> Result<()> {
|
||||
|
||||
#[cfg(windows)]
|
||||
fn restrict(file: &Path) -> Result<()> {
|
||||
let user = std::env::var("USERNAME").map_err(|_| Error::Invalid("the current user is unknown".into()))?;
|
||||
let user = std::env::var("USERNAME")
|
||||
.map_err(|_| Error::Invalid("the current user is unknown".into()))?;
|
||||
let domain = std::env::var("USERDOMAIN").unwrap_or_default();
|
||||
let who = if domain.is_empty() { user } else { format!("{domain}\\{user}") };
|
||||
let out = std::process::Command::new("icacls").arg(file).arg("/inheritance:r").arg("/grant:r").arg(format!("{who}:(F)")).output()?;
|
||||
let who = if domain.is_empty() {
|
||||
user
|
||||
} else {
|
||||
format!("{domain}\\{user}")
|
||||
};
|
||||
let out = std::process::Command::new("icacls")
|
||||
.arg(file)
|
||||
.arg("/inheritance:r")
|
||||
.arg("/grant:r")
|
||||
.arg(format!("{who}:(F)"))
|
||||
.output()?;
|
||||
if !out.status.success() {
|
||||
return Err(Error::Invalid("a secret file's permissions could not be restricted".into()));
|
||||
return Err(Error::Invalid(
|
||||
"a secret file's permissions could not be restricted".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -141,16 +164,27 @@ pub struct MemoryStore(Mutex<std::collections::HashMap<String, Vec<u8>>>);
|
||||
impl SecretStore for MemoryStore {
|
||||
fn get(&self, name: &str) -> Result<Option<Vec<u8>>> {
|
||||
check_name(name)?;
|
||||
Ok(self.0.lock().map_err(|_| Error::Invalid("a lock was poisoned".into()))?.get(name).cloned())
|
||||
Ok(self
|
||||
.0
|
||||
.lock()
|
||||
.map_err(|_| Error::Invalid("a lock was poisoned".into()))?
|
||||
.get(name)
|
||||
.cloned())
|
||||
}
|
||||
fn put(&self, name: &str, value: &[u8]) -> Result<()> {
|
||||
check_name(name)?;
|
||||
self.0.lock().map_err(|_| Error::Invalid("a lock was poisoned".into()))?.insert(name.to_string(), value.to_vec());
|
||||
self.0
|
||||
.lock()
|
||||
.map_err(|_| Error::Invalid("a lock was poisoned".into()))?
|
||||
.insert(name.to_string(), value.to_vec());
|
||||
Ok(())
|
||||
}
|
||||
fn delete(&self, name: &str) -> Result<()> {
|
||||
check_name(name)?;
|
||||
self.0.lock().map_err(|_| Error::Invalid("a lock was poisoned".into()))?.remove(name);
|
||||
self.0
|
||||
.lock()
|
||||
.map_err(|_| Error::Invalid("a lock was poisoned".into()))?
|
||||
.remove(name);
|
||||
Ok(())
|
||||
}
|
||||
fn kind(&self) -> &'static str {
|
||||
@@ -165,13 +199,18 @@ pub use dpapi::DpapiStore;
|
||||
mod dpapi {
|
||||
use super::*;
|
||||
use windows_sys::Win32::Foundation::LocalFree;
|
||||
use windows_sys::Win32::Security::Cryptography::{CryptProtectData, CryptUnprotectData, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB};
|
||||
use windows_sys::Win32::Security::Cryptography::{
|
||||
CryptProtectData, CryptUnprotectData, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB,
|
||||
};
|
||||
|
||||
/// Mixed into every blob: a different program running as the same user does not decrypt the Manager's secrets by accident.
|
||||
const ENTROPY: &[u8] = b"coa-server-manager/secret-store/v1";
|
||||
|
||||
fn blob(data: &[u8]) -> CRYPT_INTEGER_BLOB {
|
||||
CRYPT_INTEGER_BLOB { cbData: data.len() as u32, pbData: data.as_ptr() as *mut u8 }
|
||||
CRYPT_INTEGER_BLOB {
|
||||
cbData: data.len() as u32,
|
||||
pbData: data.as_ptr() as *mut u8,
|
||||
}
|
||||
}
|
||||
|
||||
fn take(out: CRYPT_INTEGER_BLOB) -> Vec<u8> {
|
||||
@@ -183,8 +222,21 @@ mod dpapi {
|
||||
pub fn protect(plain: &[u8]) -> Result<Vec<u8>> {
|
||||
let input = blob(plain);
|
||||
let entropy = blob(ENTROPY);
|
||||
let mut out = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() };
|
||||
let ok = unsafe { CryptProtectData(&input, std::ptr::null(), &entropy, std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut out) };
|
||||
let mut out = CRYPT_INTEGER_BLOB {
|
||||
cbData: 0,
|
||||
pbData: std::ptr::null_mut(),
|
||||
};
|
||||
let ok = unsafe {
|
||||
CryptProtectData(
|
||||
&input,
|
||||
std::ptr::null(),
|
||||
&entropy,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
CRYPTPROTECT_UI_FORBIDDEN,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
return Err(Error::Invalid("Windows could not protect a secret".into()));
|
||||
}
|
||||
@@ -194,8 +246,21 @@ mod dpapi {
|
||||
pub fn unprotect(sealed: &[u8]) -> Result<Vec<u8>> {
|
||||
let input = blob(sealed);
|
||||
let entropy = blob(ENTROPY);
|
||||
let mut out = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() };
|
||||
let ok = unsafe { CryptUnprotectData(&input, std::ptr::null_mut(), &entropy, std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut out) };
|
||||
let mut out = CRYPT_INTEGER_BLOB {
|
||||
cbData: 0,
|
||||
pbData: std::ptr::null_mut(),
|
||||
};
|
||||
let ok = unsafe {
|
||||
CryptUnprotectData(
|
||||
&input,
|
||||
std::ptr::null_mut(),
|
||||
&entropy,
|
||||
std::ptr::null(),
|
||||
std::ptr::null(),
|
||||
CRYPTPROTECT_UI_FORBIDDEN,
|
||||
&mut out,
|
||||
)
|
||||
};
|
||||
if ok == 0 {
|
||||
return Err(Error::Invalid("a secret could not be unlocked (it was made by another Windows user or on another computer)".into()));
|
||||
}
|
||||
@@ -218,7 +283,9 @@ mod dpapi {
|
||||
impl SecretStore for DpapiStore {
|
||||
fn get(&self, name: &str) -> Result<Option<Vec<u8>>> {
|
||||
check_name(name)?;
|
||||
read_file(&self.path(name))?.map(|b| unprotect(&b)).transpose()
|
||||
read_file(&self.path(name))?
|
||||
.map(|b| unprotect(&b))
|
||||
.transpose()
|
||||
}
|
||||
fn put(&self, name: &str, value: &[u8]) -> Result<()> {
|
||||
check_name(name)?;
|
||||
@@ -241,14 +308,24 @@ mod tests {
|
||||
fn round_trip(store: &dyn SecretStore) {
|
||||
assert_eq!(store.get("realm-abc").unwrap(), None);
|
||||
store.put("realm-abc", b"hunter2-secret").unwrap();
|
||||
assert_eq!(store.get("realm-abc").unwrap().as_deref(), Some(b"hunter2-secret".as_slice()));
|
||||
assert_eq!(
|
||||
store.get("realm-abc").unwrap().as_deref(),
|
||||
Some(b"hunter2-secret".as_slice())
|
||||
);
|
||||
store.put("realm-abc", b"another").unwrap();
|
||||
assert_eq!(store.get("realm-abc").unwrap().as_deref(), Some(b"another".as_slice()), "replaced");
|
||||
assert_eq!(
|
||||
store.get("realm-abc").unwrap().as_deref(),
|
||||
Some(b"another".as_slice()),
|
||||
"replaced"
|
||||
);
|
||||
store.delete("realm-abc").unwrap();
|
||||
store.delete("realm-abc").unwrap();
|
||||
assert_eq!(store.get("realm-abc").unwrap(), None);
|
||||
for bad in ["", "../x", "a/b", "a b", ".hidden", &"x".repeat(97)] {
|
||||
assert!(store.put(bad, b"x").is_err() && store.get(bad).is_err(), "{bad:?}");
|
||||
assert!(
|
||||
store.put(bad, b"x").is_err() && store.get(bad).is_err(),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,15 +343,27 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = DpapiStore::new(dir.path().join("secrets"));
|
||||
round_trip(&store);
|
||||
store.put("player-key", b"VERY-SECRET-PLAYER-KEY-0123456789").unwrap();
|
||||
store
|
||||
.put("player-key", b"VERY-SECRET-PLAYER-KEY-0123456789")
|
||||
.unwrap();
|
||||
let raw = fs::read(dir.path().join("secrets").join("player-key.dpapi")).unwrap();
|
||||
assert!(!raw.windows(11).any(|w| w == b"VERY-SECRET"), "the file holds no plaintext");
|
||||
assert!(
|
||||
!raw.windows(11).any(|w| w == b"VERY-SECRET"),
|
||||
"the file holds no plaintext"
|
||||
);
|
||||
assert!(raw.len() > 40);
|
||||
let mut tampered = raw.clone();
|
||||
let last = tampered.len() - 1;
|
||||
tampered[last] ^= 1;
|
||||
fs::write(dir.path().join("secrets").join("player-key.dpapi"), tampered).unwrap();
|
||||
assert!(store.get("player-key").is_err(), "a damaged blob is an error, not garbage");
|
||||
fs::write(
|
||||
dir.path().join("secrets").join("player-key.dpapi"),
|
||||
tampered,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
store.get("player-key").is_err(),
|
||||
"a damaged blob is an error, not garbage"
|
||||
);
|
||||
assert_eq!(store.kind(), "dpapi");
|
||||
}
|
||||
}
|
||||
+1343
-239
File diff suppressed because it is too large.
Load diff
@@ -195,7 +195,8 @@ impl ControlStore {
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> Result<Self> {
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(db)?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))
|
||||
.map_err(db)?;
|
||||
let _ = conn.pragma_update(None, "journal_mode", "WAL");
|
||||
conn.execute_batch(SCHEMA).map_err(db)?;
|
||||
Ok(Self { conn })
|
||||
@@ -211,7 +212,11 @@ impl ControlStore {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn host_player_of_account(&self, realm: &str, account_id: u32) -> Result<Option<HostPlayer>> {
|
||||
pub fn host_player_of_account(
|
||||
&self,
|
||||
realm: &str,
|
||||
account_id: u32,
|
||||
) -> Result<Option<HostPlayer>> {
|
||||
self.conn
|
||||
.query_row("SELECT player_id, public_key, account_id, username, kind FROM host_player WHERE realm_local_id = ?1 AND account_id = ?2", params![realm, account_id], row_player)
|
||||
.optional()
|
||||
@@ -219,7 +224,15 @@ impl ControlStore {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn host_bind_player(&self, realm: &str, player: &Uuid, public_key: &str, account_id: u32, username: &str, kind: AccountKind) -> Result<()> {
|
||||
pub fn host_bind_player(
|
||||
&self,
|
||||
realm: &str,
|
||||
player: &Uuid,
|
||||
public_key: &str,
|
||||
account_id: u32,
|
||||
username: &str,
|
||||
kind: AccountKind,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute("INSERT INTO host_player(realm_local_id, player_id, public_key, account_id, username, kind, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", params![realm, player.to_string(), public_key, account_id, username, kind.as_str(), now()])
|
||||
.map_err(db)?;
|
||||
@@ -227,7 +240,12 @@ impl ControlStore {
|
||||
}
|
||||
|
||||
pub fn host_forget_player(&self, realm: &str, player: &Uuid) -> Result<()> {
|
||||
self.conn.execute("DELETE FROM host_player WHERE realm_local_id = ?1 AND player_id = ?2", params![realm, player.to_string()]).map_err(db)?;
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM host_player WHERE realm_local_id = ?1 AND player_id = ?2",
|
||||
params![realm, player.to_string()],
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -241,11 +259,19 @@ impl ControlStore {
|
||||
|
||||
pub fn host_claims_of(&self, realm: &str, player: &Uuid) -> Result<Vec<HostClaim>> {
|
||||
let mut stmt = self.conn.prepare("SELECT local_guid, character_id, player_id, state FROM host_claim WHERE realm_local_id = ?1 AND player_id = ?2 ORDER BY local_guid").map_err(db)?;
|
||||
let rows = stmt.query_map(params![realm, player.to_string()], row_claim).map_err(db)?;
|
||||
let rows = stmt
|
||||
.query_map(params![realm, player.to_string()], row_claim)
|
||||
.map_err(db)?;
|
||||
rows.map(|r| r.map_err(db)?).collect()
|
||||
}
|
||||
|
||||
pub fn host_claim_set(&self, realm: &str, local_guid: u32, character: &Uuid, player: &Uuid) -> Result<()> {
|
||||
pub fn host_claim_set(
|
||||
&self,
|
||||
realm: &str,
|
||||
local_guid: u32,
|
||||
character: &Uuid,
|
||||
player: &Uuid,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO host_claim(realm_local_id, local_guid, character_id, player_id, state, claimed_at) VALUES (?1, ?2, ?3, ?4, 'exported', ?5)
|
||||
@@ -256,12 +282,21 @@ impl ControlStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn host_claim_acknowledge(&self, realm: &str, character: &Uuid, player: &Uuid) -> Result<bool> {
|
||||
pub fn host_claim_acknowledge(
|
||||
&self,
|
||||
realm: &str,
|
||||
character: &Uuid,
|
||||
player: &Uuid,
|
||||
) -> Result<bool> {
|
||||
let n = self.conn.execute("UPDATE host_claim SET state = 'acknowledged' WHERE realm_local_id = ?1 AND character_id = ?2 AND player_id = ?3", params![realm, character.to_string(), player.to_string()]).map_err(db)?;
|
||||
Ok(n == 1)
|
||||
}
|
||||
|
||||
pub fn host_claim_of_character(&self, realm: &str, character: &Uuid) -> Result<Option<HostClaim>> {
|
||||
pub fn host_claim_of_character(
|
||||
&self,
|
||||
realm: &str,
|
||||
character: &Uuid,
|
||||
) -> Result<Option<HostClaim>> {
|
||||
self.conn
|
||||
.query_row("SELECT local_guid, character_id, player_id, state FROM host_claim WHERE realm_local_id = ?1 AND character_id = ?2 LIMIT 1", params![realm, character.to_string()], row_claim)
|
||||
.optional()
|
||||
@@ -281,7 +316,11 @@ impl ControlStore {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub fn host_transfer_latest(&self, realm: &str, character_id: &Uuid) -> Result<Option<HostTransfer>> {
|
||||
pub fn host_transfer_latest(
|
||||
&self,
|
||||
realm: &str,
|
||||
character_id: &Uuid,
|
||||
) -> Result<Option<HostTransfer>> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
|
||||
@@ -339,7 +378,14 @@ impl ControlStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn host_transfer_commit(&self, transfer_id: &Uuid, local_guid: u32, session_id: &Uuid, projected_level: Option<u32>, notes: &[String]) -> Result<()> {
|
||||
pub fn host_transfer_commit(
|
||||
&self,
|
||||
transfer_id: &Uuid,
|
||||
local_guid: u32,
|
||||
session_id: &Uuid,
|
||||
projected_level: Option<u32>,
|
||||
notes: &[String],
|
||||
) -> Result<()> {
|
||||
let notes_json = serde_json::to_string(notes).unwrap_or_default();
|
||||
self.conn
|
||||
.execute(
|
||||
@@ -356,7 +402,12 @@ impl ControlStore {
|
||||
}
|
||||
|
||||
pub fn host_transfer_delete(&self, transfer_id: &Uuid) -> Result<()> {
|
||||
self.conn.execute("DELETE FROM host_transfer WHERE transfer_id = ?1", params![transfer_id.to_string()]).map_err(db)?;
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM host_transfer WHERE transfer_id = ?1",
|
||||
params![transfer_id.to_string()],
|
||||
)
|
||||
.map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -364,12 +415,27 @@ impl ControlStore {
|
||||
|
||||
pub fn player_realm(&self, realm_id: &str) -> Result<Option<PlayerRealm>> {
|
||||
self.conn
|
||||
.query_row("SELECT realm_id, username, kind FROM player_realm WHERE realm_id = ?1", [realm_id], |r| Ok(PlayerRealm { realm_id: r.get(0)?, username: r.get(1)?, kind: AccountKind::parse(&r.get::<_, String>(2)?) }))
|
||||
.query_row(
|
||||
"SELECT realm_id, username, kind FROM player_realm WHERE realm_id = ?1",
|
||||
[realm_id],
|
||||
|r| {
|
||||
Ok(PlayerRealm {
|
||||
realm_id: r.get(0)?,
|
||||
username: r.get(1)?,
|
||||
kind: AccountKind::parse(&r.get::<_, String>(2)?),
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn player_realm_set(&self, realm_id: &str, username: &str, kind: AccountKind) -> Result<()> {
|
||||
pub fn player_realm_set(
|
||||
&self,
|
||||
realm_id: &str,
|
||||
username: &str,
|
||||
kind: AccountKind,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO player_realm(realm_id, username, kind, created_at) VALUES (?1, ?2, ?3, ?4)
|
||||
@@ -381,13 +447,22 @@ impl ControlStore {
|
||||
}
|
||||
|
||||
pub fn player_realm_remove(&self, realm_id: &str) -> Result<()> {
|
||||
self.conn.execute("DELETE FROM player_realm WHERE realm_id = ?1", [realm_id]).map_err(db)?;
|
||||
self.conn
|
||||
.execute("DELETE FROM player_realm WHERE realm_id = ?1", [realm_id])
|
||||
.map_err(db)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The public key a realm had when this player first reached it. A realm id never changes its key (a new key is a new realm), so a different one is refused.
|
||||
pub fn realm_pin(&self, realm_id: &str) -> Result<Option<String>> {
|
||||
self.conn.query_row("SELECT public_key FROM realm_pin WHERE realm_id = ?1", [realm_id], |r| r.get(0)).optional().map_err(db)
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT public_key FROM realm_pin WHERE realm_id = ?1",
|
||||
[realm_id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(db)
|
||||
}
|
||||
|
||||
pub fn realm_pin_set(&self, realm_id: &str, public_key: &str) -> Result<()> {
|
||||
@@ -402,7 +477,11 @@ impl ControlStore {
|
||||
|
||||
pub fn player_claims(&self, realm_id: &str) -> Result<Vec<(Uuid, String)>> {
|
||||
let mut stmt = self.conn.prepare("SELECT character_id, name FROM player_claim WHERE realm_id = ?1 ORDER BY claimed_at").map_err(db)?;
|
||||
let rows = stmt.query_map([realm_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(db)?;
|
||||
let rows = stmt
|
||||
.query_map([realm_id], |r| {
|
||||
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
|
||||
})
|
||||
.map_err(db)?;
|
||||
rows.map(|r| {
|
||||
let (id, name) = r.map_err(db)?;
|
||||
Ok((uuid(id)?, name))
|
||||
@@ -412,13 +491,32 @@ impl ControlStore {
|
||||
}
|
||||
|
||||
fn row_player(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostPlayer>> {
|
||||
let (id, key, account, username, kind): (String, String, u32, String, String) = (r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?);
|
||||
Ok(uuid(id).map(|player_id| HostPlayer { player_id, public_key: key, account_id: account, username, kind: AccountKind::parse(&kind) }))
|
||||
let (id, key, account, username, kind): (String, String, u32, String, String) =
|
||||
(r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?);
|
||||
Ok(uuid(id).map(|player_id| HostPlayer {
|
||||
player_id,
|
||||
public_key: key,
|
||||
account_id: account,
|
||||
username,
|
||||
kind: AccountKind::parse(&kind),
|
||||
}))
|
||||
}
|
||||
|
||||
fn row_claim(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostClaim>> {
|
||||
let (guid, cid, pid, state): (u32, String, String, String) = (r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?);
|
||||
Ok((|| Ok(HostClaim { local_guid: guid, character_id: uuid(cid)?, player_id: uuid(pid)?, state: if state == "acknowledged" { ClaimState::Acknowledged } else { ClaimState::Exported } }))())
|
||||
let (guid, cid, pid, state): (u32, String, String, String) =
|
||||
(r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?);
|
||||
Ok((|| {
|
||||
Ok(HostClaim {
|
||||
local_guid: guid,
|
||||
character_id: uuid(cid)?,
|
||||
player_id: uuid(pid)?,
|
||||
state: if state == "acknowledged" {
|
||||
ClaimState::Acknowledged
|
||||
} else {
|
||||
ClaimState::Exported
|
||||
},
|
||||
})
|
||||
})())
|
||||
}
|
||||
|
||||
fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>> {
|
||||
@@ -435,9 +533,13 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
|
||||
let session_str: Option<String> = r.get(10)?;
|
||||
let projected_level: Option<u32> = r.get(11)?;
|
||||
let notes_str: Option<String> = r.get(12)?;
|
||||
let notes = notes_str.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok()).unwrap_or_default();
|
||||
let notes = notes_str
|
||||
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let coll_str: Option<String> = r.get(13)?;
|
||||
let collections = coll_str.and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok()).unwrap_or_default();
|
||||
let collections = coll_str
|
||||
.and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
Ok((|| {
|
||||
Ok(HostTransfer {
|
||||
realm_local_id,
|
||||
@@ -466,16 +568,43 @@ mod tests {
|
||||
fn a_player_owns_one_account_per_realm_and_an_account_one_player() {
|
||||
let s = ControlStore::open_in_memory().unwrap();
|
||||
let (a, b) = (Uuid::now_v7(), Uuid::now_v7());
|
||||
s.host_bind_player("srv-1", &a, "KEY-A", 7, "DMITRY", AccountKind::Generated).unwrap();
|
||||
assert!(s.host_bind_player("srv-1", &a, "KEY-A", 8, "OTHER", AccountKind::Generated).is_err(), "one account per player and realm");
|
||||
assert!(s.host_bind_player("srv-1", &b, "KEY-B", 7, "DMITRY", AccountKind::Linked).is_err(), "one player per account");
|
||||
s.host_bind_player("srv-2", &a, "KEY-A", 7, "DMITRY", AccountKind::Generated).unwrap();
|
||||
s.host_bind_player("srv-1", &a, "KEY-A", 7, "DMITRY", AccountKind::Generated)
|
||||
.unwrap();
|
||||
assert!(
|
||||
s.host_bind_player("srv-1", &a, "KEY-A", 8, "OTHER", AccountKind::Generated)
|
||||
.is_err(),
|
||||
"one account per player and realm"
|
||||
);
|
||||
assert!(
|
||||
s.host_bind_player("srv-1", &b, "KEY-B", 7, "DMITRY", AccountKind::Linked)
|
||||
.is_err(),
|
||||
"one player per account"
|
||||
);
|
||||
s.host_bind_player("srv-2", &a, "KEY-A", 7, "DMITRY", AccountKind::Generated)
|
||||
.unwrap();
|
||||
let p = s.host_player("srv-1", &a).unwrap().unwrap();
|
||||
assert_eq!((p.account_id, p.username.as_str(), p.public_key.as_str(), p.kind), (7, "DMITRY", "KEY-A", AccountKind::Generated));
|
||||
assert_eq!(s.host_player_of_account("srv-1", 7).unwrap().unwrap().player_id, a);
|
||||
assert_eq!(
|
||||
(
|
||||
p.account_id,
|
||||
p.username.as_str(),
|
||||
p.public_key.as_str(),
|
||||
p.kind
|
||||
),
|
||||
(7, "DMITRY", "KEY-A", AccountKind::Generated)
|
||||
);
|
||||
assert_eq!(
|
||||
s.host_player_of_account("srv-1", 7)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.player_id,
|
||||
a
|
||||
);
|
||||
assert!(s.host_player("srv-1", &b).unwrap().is_none());
|
||||
s.host_forget_player("srv-1", &a).unwrap();
|
||||
assert!(s.host_player("srv-1", &a).unwrap().is_none() && s.host_player("srv-2", &a).unwrap().is_some());
|
||||
assert!(
|
||||
s.host_player("srv-1", &a).unwrap().is_none()
|
||||
&& s.host_player("srv-2", &a).unwrap().is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -483,14 +612,27 @@ mod tests {
|
||||
let s = ControlStore::open_in_memory().unwrap();
|
||||
let (p, q, c) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
|
||||
s.host_claim_set("srv-1", 50, &c, &p).unwrap();
|
||||
assert_eq!(s.host_claim("srv-1", 50).unwrap().unwrap().state, ClaimState::Exported);
|
||||
assert_eq!(
|
||||
s.host_claim("srv-1", 50).unwrap().unwrap().state,
|
||||
ClaimState::Exported
|
||||
);
|
||||
s.host_claim_set("srv-1", 50, &c, &p).unwrap();
|
||||
s.host_claim_set("srv-1", 50, &Uuid::now_v7(), &q).unwrap();
|
||||
let held = s.host_claim("srv-1", 50).unwrap().unwrap();
|
||||
assert_eq!((held.player_id, held.character_id), (p, c), "another player cannot take over a claim");
|
||||
assert!(!s.host_claim_acknowledge("srv-1", &c, &q).unwrap(), "only the claiming player acknowledges");
|
||||
assert_eq!(
|
||||
(held.player_id, held.character_id),
|
||||
(p, c),
|
||||
"another player cannot take over a claim"
|
||||
);
|
||||
assert!(
|
||||
!s.host_claim_acknowledge("srv-1", &c, &q).unwrap(),
|
||||
"only the claiming player acknowledges"
|
||||
);
|
||||
assert!(s.host_claim_acknowledge("srv-1", &c, &p).unwrap());
|
||||
assert_eq!(s.host_claim("srv-1", 50).unwrap().unwrap().state, ClaimState::Acknowledged);
|
||||
assert_eq!(
|
||||
s.host_claim("srv-1", 50).unwrap().unwrap().state,
|
||||
ClaimState::Acknowledged
|
||||
);
|
||||
assert_eq!(s.host_claims_of("srv-1", &p).unwrap().len(), 1);
|
||||
assert!(s.host_claims_of("srv-1", &q).unwrap().is_empty());
|
||||
}
|
||||
@@ -500,22 +642,37 @@ mod tests {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
{
|
||||
let s = ControlStore::open(dir.path()).unwrap();
|
||||
s.player_realm_set("realm-1", "DMITRY_7K4M", AccountKind::Generated).unwrap();
|
||||
s.player_claim_add("realm-1", &Uuid::now_v7(), "Thrall").unwrap();
|
||||
s.player_realm_set("realm-1", "DMITRY_7K4M", AccountKind::Generated)
|
||||
.unwrap();
|
||||
s.player_claim_add("realm-1", &Uuid::now_v7(), "Thrall")
|
||||
.unwrap();
|
||||
}
|
||||
let s = ControlStore::open(dir.path()).unwrap();
|
||||
assert_eq!(s.player_realm("realm-1").unwrap().unwrap().username, "DMITRY_7K4M");
|
||||
assert_eq!(
|
||||
s.player_realm("realm-1").unwrap().unwrap().username,
|
||||
"DMITRY_7K4M"
|
||||
);
|
||||
assert_eq!(s.player_claims("realm-1").unwrap().len(), 1);
|
||||
s.player_realm_remove("realm-1").unwrap();
|
||||
assert!(s.player_realm("realm-1").unwrap().is_none());
|
||||
let raw = std::fs::read(dir.path().join("control.sqlite")).unwrap();
|
||||
assert!(!String::from_utf8_lossy(&raw).to_lowercase().contains("password"), "the schema has no password column");
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&raw)
|
||||
.to_lowercase()
|
||||
.contains("password"),
|
||||
"the schema has no password column"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_transfer_roundtrip_and_lifecycle() {
|
||||
let s = ControlStore::open_in_memory().unwrap();
|
||||
let (p, c, t, sid) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
|
||||
let (p, c, t, sid) = (
|
||||
Uuid::now_v7(),
|
||||
Uuid::now_v7(),
|
||||
Uuid::now_v7(),
|
||||
Uuid::now_v7(),
|
||||
);
|
||||
let transfer = HostTransfer {
|
||||
realm_local_id: "live".into(),
|
||||
transfer_id: t,
|
||||
@@ -541,7 +698,8 @@ mod tests {
|
||||
let got = s.host_transfer("live", &t).unwrap().unwrap();
|
||||
assert_eq!(got.received_size, 2048);
|
||||
|
||||
s.host_transfer_commit(&t, 101, &sid, Some(60), &["projected 60".into()]).unwrap();
|
||||
s.host_transfer_commit(&t, 101, &sid, Some(60), &["projected 60".into()])
|
||||
.unwrap();
|
||||
let got = s.host_transfer("live", &t).unwrap().unwrap();
|
||||
assert_eq!(got.state, TransferState::Committed);
|
||||
assert_eq!(got.local_guid, Some(101));
|
||||
|
||||
@@ -44,7 +44,9 @@ impl std::fmt::Display for LinkError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
LinkError::HostOffline => write!(f, "The server's Manager is not online right now."),
|
||||
LinkError::HostBusy => write!(f, "The server's Manager is busy; try again in a moment."),
|
||||
LinkError::HostBusy => {
|
||||
write!(f, "The server's Manager is busy; try again in a moment.")
|
||||
}
|
||||
LinkError::RateLimited => write!(f, "Too many attempts; wait a minute."),
|
||||
LinkError::Auth(m) => write!(f, "The server could not be verified: {m}"),
|
||||
LinkError::Protocol(m) => write!(f, "The connection broke the protocol: {m}"),
|
||||
@@ -79,7 +81,10 @@ pub fn from_error_frame(code: ErrorCode, message: &str) -> LinkError {
|
||||
/// `http(s)://host[:port]` -> `ws(s)://host[:port]` + `path`. The Registry's address is the Coordinator's address (one front door).
|
||||
pub fn coordinator_url(registry_url: &str, path: &str) -> Option<String> {
|
||||
let base = registry_url.trim().trim_end_matches('/');
|
||||
let rest = base.strip_prefix("https://").map(|r| format!("wss://{r}")).or_else(|| base.strip_prefix("http://").map(|r| format!("ws://{r}")))?;
|
||||
let rest = base
|
||||
.strip_prefix("https://")
|
||||
.map(|r| format!("wss://{r}"))
|
||||
.or_else(|| base.strip_prefix("http://").map(|r| format!("ws://{r}")))?;
|
||||
Some(format!("{rest}{path}"))
|
||||
}
|
||||
|
||||
@@ -87,9 +92,9 @@ pub fn relay_url(registry_url: &str, path: &str) -> Option<String> {
|
||||
coordinator_url(registry_url, path)
|
||||
}
|
||||
|
||||
|
||||
pub fn connect(url: &str, read_timeout: Duration) -> Result<Ws, LinkError> {
|
||||
let (mut ws, _) = tungstenite::connect(url).map_err(|e| LinkError::Io(clean(&e.to_string())))?;
|
||||
let (mut ws, _) =
|
||||
tungstenite::connect(url).map_err(|e| LinkError::Io(clean(&e.to_string())))?;
|
||||
set_timeouts(&mut ws, read_timeout);
|
||||
Ok(ws)
|
||||
}
|
||||
@@ -115,8 +120,14 @@ pub fn set_timeouts(ws: &mut Ws, read: Duration) {
|
||||
pub fn poll(ws: &mut Ws) -> Result<Option<Message>, LinkError> {
|
||||
match ws.read() {
|
||||
Ok(m) => Ok(Some(m)),
|
||||
Err(tungstenite::Error::Io(e)) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => Ok(None),
|
||||
Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => Err(LinkError::Io("the connection was closed".into())),
|
||||
Err(tungstenite::Error::Io(e))
|
||||
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
Err(tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed) => {
|
||||
Err(LinkError::Io("the connection was closed".into()))
|
||||
}
|
||||
Err(e) => Err(LinkError::Io(clean(&e.to_string()))),
|
||||
}
|
||||
}
|
||||
@@ -138,18 +149,26 @@ pub fn next_frame(ws: &mut Ws, total: Duration) -> Result<Frame, LinkError> {
|
||||
return Ok(frame);
|
||||
}
|
||||
Some(Message::Ping(_) | Message::Pong(_)) => continue,
|
||||
Some(Message::Close(_)) => return Err(LinkError::Io("the connection was closed".into())),
|
||||
Some(_) => return Err(LinkError::Protocol("a binary frame arrived where a control frame was expected".into())),
|
||||
Some(Message::Close(_)) => {
|
||||
return Err(LinkError::Io("the connection was closed".into()))
|
||||
}
|
||||
Some(_) => {
|
||||
return Err(LinkError::Protocol(
|
||||
"a binary frame arrived where a control frame was expected".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_text(ws: &mut Ws, frame: &Frame) -> Result<(), LinkError> {
|
||||
ws.send(Message::Text(coord::to_text(frame).into())).map_err(|e| LinkError::Io(clean(&e.to_string())))
|
||||
ws.send(Message::Text(coord::to_text(frame).into()))
|
||||
.map_err(|e| LinkError::Io(clean(&e.to_string())))
|
||||
}
|
||||
|
||||
pub fn send_binary(ws: &mut Ws, data: Vec<u8>) -> Result<(), LinkError> {
|
||||
ws.send(Message::Binary(data.into())).map_err(|e| LinkError::Io(clean(&e.to_string())))
|
||||
ws.send(Message::Binary(data.into()))
|
||||
.map_err(|e| LinkError::Io(clean(&e.to_string())))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -158,17 +177,41 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_coordinator_address_follows_the_registrys() {
|
||||
assert_eq!(coordinator_url("https://registry.example/", "/coord/v1/host").unwrap(), "wss://registry.example/coord/v1/host");
|
||||
assert_eq!(coordinator_url("http://127.0.0.1:8080", "/coord/v1/player?realm=x").unwrap(), "ws://127.0.0.1:8080/coord/v1/player?realm=x");
|
||||
assert!(coordinator_url("ftp://x", "/").is_none() && coordinator_url("registry.example", "/").is_none());
|
||||
assert_eq!(
|
||||
coordinator_url("https://registry.example/", "/coord/v1/host").unwrap(),
|
||||
"wss://registry.example/coord/v1/host"
|
||||
);
|
||||
assert_eq!(
|
||||
coordinator_url("http://127.0.0.1:8080", "/coord/v1/player?realm=x").unwrap(),
|
||||
"ws://127.0.0.1:8080/coord/v1/player?realm=x"
|
||||
);
|
||||
assert!(
|
||||
coordinator_url("ftp://x", "/").is_none()
|
||||
&& coordinator_url("registry.example", "/").is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coordinator_refusals_become_messages_a_player_can_act_on() {
|
||||
assert_eq!(from_error_frame(ErrorCode::HostOffline, "").code(), "host_offline");
|
||||
assert_eq!(from_error_frame(ErrorCode::UnknownRealm, "").code(), "host_offline");
|
||||
assert_eq!(from_error_frame(ErrorCode::HostBusy, "").code(), "host_busy");
|
||||
assert_eq!(from_error_frame(ErrorCode::RateLimited, "").code(), "rate_limited");
|
||||
assert_eq!(LinkError::HostOffline.to_string(), "The server's Manager is not online right now.");
|
||||
assert_eq!(
|
||||
from_error_frame(ErrorCode::HostOffline, "").code(),
|
||||
"host_offline"
|
||||
);
|
||||
assert_eq!(
|
||||
from_error_frame(ErrorCode::UnknownRealm, "").code(),
|
||||
"host_offline"
|
||||
);
|
||||
assert_eq!(
|
||||
from_error_frame(ErrorCode::HostBusy, "").code(),
|
||||
"host_busy"
|
||||
);
|
||||
assert_eq!(
|
||||
from_error_frame(ErrorCode::RateLimited, "").code(),
|
||||
"rate_limited"
|
||||
);
|
||||
assert_eq!(
|
||||
LinkError::HostOffline.to_string(),
|
||||
"The server's Manager is not online right now."
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user