Phase 10.1: Registry protocol 2 (structured listing), migration 2, v1 refused explicitly

Listing (rates, modules, region, account provisioning), population with players and bots apart,
level cap and ruleset derived from the hash-checked capabilities. Realm records from protocol 1
keep their id, key and creation time and are republished in place. Host publishes the real
values: rates from the effective worldserver configuration, modules from the module catalog,
players/bots from the realm database.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-10-07 21:31:45 +05:00
1 parent 3e57d32c90
commit e39cecb333
28 files changed
+1012 -397

No files matched your search

+44 -20
View File
@@ -12,13 +12,14 @@ use coa_core::realm_registry::{AdvertSource, FileKeyStore, KeyStore, LocalAdvert
use coa_registry::api::ApiConfig;
use coa_registry::limits::Rate;
use coa_registry::store::MemoryStore;
use coa_registry_proto::{AccountProvisioning, ModuleEntry, Population, Rates};
use common::*;
struct Source(Mutex<LocalAdvert>);
impl Source {
fn new(level: u32) -> Arc<Self> {
Arc::new(Self(Mutex::new(LocalAdvert { running: true, capabilities: Some(caps(level)), player_count: Some(3), player_capacity: None, manager_version: "0.6.6".into() })))
Arc::new(Self(Mutex::new(LocalAdvert { running: true, capabilities: Some(caps(level)), population: Population { players: 3, bots: 7, capacity: None }, rates: Rates { xp_kill: Some(2.0), ..Rates::default() }, modules: vec![ModuleEntry { id: "playerbots".into(), version: Some("1.4.2".into()), enabled: true }], account_provisioning: AccountProvisioning { automatic: false, existing_only: true }, manager_version: "0.6.6".into() })))
}
fn set(&self, f: impl FnOnce(&mut LocalAdvert)) {
f(&mut self.0.lock().unwrap());
@@ -87,16 +88,18 @@ fn state(host: &RegistryHost, rig: &Rig) -> PublishState {
fn a_fresh_realm_makes_an_identity_registers_and_heartbeats() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Friends' realm", "Plain text.", "en", rig.now()).unwrap();
host.publish("srv-1", "Friends' realm", "Plain text.", "en", None, rig.now()).unwrap();
let realm = host.realm_id("srv-1").expect("an identity was made");
assert!(rig.dir.path().join("keys").join(format!("{realm}.key")).is_file());
rig.pass(&mut host, 0);
assert_eq!(state(&host, &rig), PublishState::Online);
let rec = host.registry_record("srv-1").unwrap();
assert_eq!((rec.realm_id, rec.display_name.as_str(), rec.published, rec.online, rec.metadata_revision), (realm, "Friends' realm", true, true, 1));
assert_eq!((rec.realm_id, rec.listing.display_name.as_str(), rec.published, rec.online, rec.metadata_revision), (realm, "Friends' realm", true, true, 1));
assert_eq!(Some(rec.public_key.clone()), host.public_key("srv-1"));
assert_eq!(rec.player_count, Some(3));
assert_eq!((rec.population.players, rec.population.bots), (3, 7), "players and bots arrive separately");
assert_eq!(rec.listing.rates.xp_kill, Some(2.0));
assert_eq!(rec.level_cap, Some(60));
let before = rec.last_seen_at;
rig.pass(&mut host, 35);
@@ -118,7 +121,7 @@ fn a_manager_restart_keeps_the_realm_id_and_the_key() {
let mut rig = Rig::new();
let (realm, key) = {
let mut host = rig.open();
host.publish("srv-1", "Restarting", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Restarting", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
assert_eq!(state(&host, &rig), PublishState::Online);
(host.realm_id("srv-1").unwrap(), host.public_key("srv-1").unwrap())
@@ -138,7 +141,7 @@ fn a_manager_restart_keeps_the_realm_id_and_the_key() {
fn changed_capabilities_reach_the_registry_with_the_next_heartbeat() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Caps", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Caps", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
rig.source.set(|a| a.capabilities = Some(caps(70)));
rig.pass(&mut host, 35);
@@ -147,18 +150,18 @@ fn changed_capabilities_reach_the_registry_with_the_next_heartbeat() {
rig.pass(&mut host, 35);
assert_eq!(host.registry_record("srv-1").unwrap().metadata_revision, 2, "and then nothing is rewritten");
// a rename
host.publish("srv-1", "Renamed", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Renamed", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
rig.pass(&mut host, 0);
let rec = host.registry_record("srv-1").unwrap();
assert_eq!(rec.display_name, "Renamed");
assert_eq!(rec.listing.display_name, "Renamed");
}
#[test]
fn missing_heartbeats_make_the_realm_offline_and_it_comes_back() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Gone and back", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Gone and back", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
// the Manager is closed: nothing is sent
rig.server.advance(125);
@@ -174,7 +177,7 @@ fn missing_heartbeats_make_the_realm_offline_and_it_comes_back() {
fn a_stopped_realm_sends_no_heartbeats_and_goes_offline() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Stoppable", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Stoppable", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
rig.source.set(|a| a.running = false);
for _ in 0..5 {
@@ -191,7 +194,7 @@ fn a_stopped_realm_sends_no_heartbeats_and_goes_offline() {
fn unpublishing_stops_the_publication_and_the_identity_is_kept() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Brief", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Brief", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
let realm = host.realm_id("srv-1").unwrap();
host.unpublish("srv-1", rig.now()).unwrap();
@@ -200,7 +203,7 @@ fn unpublishing_stops_the_publication_and_the_identity_is_kept() {
assert!(!host.registry_record("srv-1").unwrap().published);
rig.pass(&mut host, 60);
assert!(!host.registry_record("srv-1").unwrap().published, "no heartbeat republishes it");
host.publish("srv-1", "Brief", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Brief", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
let rec = host.registry_record("srv-1").unwrap();
assert_eq!((rec.realm_id, rec.published, rec.online), (realm, true, true), "the same realm id, published again");
@@ -211,7 +214,7 @@ fn a_registry_that_is_down_is_retried_with_a_growing_delay_and_nothing_else_happ
let mut rig = Rig::new();
let mut host = RegistryHost::open(rig.dir.path(), rig.keys(), rig.source.clone(), rig.clock(), Timing::default(), rig.now()).unwrap();
host.set_url(Some("http://127.0.0.1:9"), rig.now()).unwrap();
host.publish("srv-1", "Offline registry", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Offline registry", "", "en", None, rig.now()).unwrap();
let mut waits = Vec::new();
for _ in 0..6 {
host.tick(rig.now());
@@ -234,7 +237,7 @@ fn a_registry_that_is_down_is_retried_with_a_growing_delay_and_nothing_else_happ
fn a_refusal_that_repeating_cannot_fix_stops_the_publication() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Contested", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Contested", "", "en", None, rig.now()).unwrap();
// somebody else got to this realm id first with another key
let mut squatter = Host::new(&rig.server, 99);
squatter.realm = host.realm_id("srv-1").unwrap();
@@ -255,7 +258,7 @@ fn a_refusal_that_repeating_cannot_fix_stops_the_publication() {
fn a_registry_that_lost_its_data_gets_the_realm_again() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Amnesia", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Amnesia", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
rig.store.forget_all();
rig.pass(&mut host, 35);
@@ -269,22 +272,22 @@ fn a_registry_that_lost_its_data_gets_the_realm_again() {
fn the_host_never_publishes_what_is_not_discovery_metadata() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Plain", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Plain", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
let rec = host.registry_record("srv-1").unwrap();
let json = serde_json::to_string(&rec).unwrap().to_lowercase();
for word in ["password", "credential", "secret", "snapshot", "inventory", "canonical", "character_id", "ra_user", "mysql", "token"] {
assert!(!json.contains(word), "the Registry's record mentions {word}: {json}");
}
assert!(host.publish("srv-1", &"x".repeat(81), "", "en", rig.now()).is_err());
assert!(host.publish("srv-1", "ok", "", "not a language", rig.now()).is_err());
assert!(host.publish("srv-1", &"x".repeat(81), "", "en", None, rig.now()).is_err());
assert!(host.publish("srv-1", "ok", "", "not a language", None, rig.now()).is_err());
}
#[test]
fn a_realm_whose_key_is_gone_is_stopped_and_publishing_again_makes_a_new_identity() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Lost key", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Lost key", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
let old = host.realm_id("srv-1").unwrap();
drop(host);
@@ -294,8 +297,29 @@ fn a_realm_whose_key_is_gone_is_stopped_and_publishing_again_makes_a_new_identit
let s = host.status(rig.now());
assert_eq!(s.realms[0].state, PublishState::Rejected);
assert!(s.realms[0].last_error.as_deref().unwrap_or("").contains("key is missing"), "{:?}", s.realms[0].last_error);
host.publish("srv-1", "Lost key", "", "en", rig.now()).unwrap();
host.publish("srv-1", "Lost key", "", "en", None, rig.now()).unwrap();
rig.pass(&mut host, 0);
assert_eq!(state(&host, &rig), PublishState::Online);
assert_ne!(host.realm_id("srv-1").unwrap(), old, "a new identity, not the old id with a guessed key");
}
#[test]
fn a_changed_rate_or_module_reaches_the_registry_with_the_next_heartbeat_and_counts_move_without_a_revision() {
let mut rig = Rig::new();
let mut host = rig.open();
host.publish("srv-1", "Rates", "", "en", Some("EU"), rig.now()).unwrap();
rig.pass(&mut host, 0);
let first = host.registry_record("srv-1").unwrap();
assert_eq!((first.listing.region.as_deref(), first.metadata_revision), (Some("EU"), 1));
rig.source.set(|a| {
a.rates.xp_kill = Some(5.0);
a.modules.push(ModuleEntry { id: "content-scaling".into(), version: None, enabled: true });
});
rig.pass(&mut host, 35);
let rec = host.registry_record("srv-1").unwrap();
assert_eq!((rec.listing.rates.xp_kill, rec.listing.modules.len(), rec.metadata_revision), (Some(5.0), 2, 2));
rig.source.set(|a| a.population = Population { players: 18, bots: 46, capacity: Some(100) });
rig.pass(&mut host, 35);
let rec = host.registry_record("srv-1").unwrap();
assert_eq!((rec.population.players, rec.population.bots, rec.population.capacity, rec.metadata_revision), (18, 46, Some(100), 2), "players and bots separately; population is not a metadata change");
}
+38 -9
View File
@@ -38,12 +38,12 @@ fn gate_1_to_12_against_the_node() {
// 1. a fresh realm generates its identity and registers (through the Host Manager code)
let dir = tempfile::tempdir().unwrap();
let keys: Arc<dyn KeyStore> = Arc::new(FileKeyStore::new(dir.path().join("keys")));
let source = Arc::new(Fixed(LocalAdvert { running: true, capabilities: Some(caps(60)), player_count: Some(2), player_capacity: None, manager_version: "0.6.6".into() }));
let source = Arc::new(Fixed(LocalAdvert { running: true, capabilities: Some(caps(60)), population: Population { players: 2, bots: 7, capacity: None }, rates: Rates { xp_kill: Some(2.0), ..Rates::default() }, modules: vec![ModuleEntry { id: "playerbots".into(), version: Some("1.4.2".into()), enabled: true }], account_provisioning: AccountProvisioning { automatic: false, existing_only: true }, manager_version: "0.6.6".into() }));
let t0 = Instant::now();
let mut elapsed = Duration::ZERO;
let mut host = RegistryHost::open(dir.path(), keys.clone(), source.clone(), system_clock(), Timing::default(), t0).unwrap();
host.set_url(Some(&base), t0).unwrap();
host.publish("srv-gate", "Gate realm", "Phase 10 gate", "en", t0).unwrap();
host.publish("srv-gate", "Gate realm", "Phase 10.1 gate", "en", Some("EU"), t0).unwrap();
host.tick(t0);
assert_eq!(host.status(t0).realms[0].state, PublishState::Online, "{:?}", host.status(t0));
let realm = host.realm_id("srv-gate").unwrap();
@@ -73,7 +73,7 @@ fn gate_1_to_12_against_the_node() {
pass(4, &format!("heartbeat moved last_seen_at {} -> {}", rec2.last_seen_at, rec3.last_seen_at));
// 6. a capability change updates the record with the next heartbeat
let source2 = Arc::new(Fixed(LocalAdvert { running: true, capabilities: Some(caps(70)), player_count: Some(3), player_capacity: None, manager_version: "0.6.6".into() }));
let source2 = Arc::new(Fixed(LocalAdvert { running: true, capabilities: Some(caps(70)), population: Population { players: 3, bots: 7, capacity: None }, rates: Rates { xp_kill: Some(2.0), ..Rates::default() }, modules: vec![ModuleEntry { id: "playerbots".into(), version: Some("1.4.2".into()), enabled: true }], account_provisioning: AccountProvisioning { automatic: false, existing_only: true }, manager_version: "0.6.6".into() }));
drop(host);
let mut host = RegistryHost::open(dir.path(), keys.clone(), source2, system_clock(), Timing::default(), t0).unwrap();
host.set_url(Some(&base), t0).unwrap();
@@ -103,7 +103,7 @@ fn gate_1_to_12_against_the_node() {
assert_eq!((r.status, r.code().as_str()), (403, "realm_key_mismatch"));
let r = thief.heartbeat(60, true);
assert_eq!((r.status, r.code().as_str()), (401, "invalid_signature"));
assert_eq!(h.me().body["display_name"], "Raw realm");
assert_eq!(h.me().body["listing"]["display_name"], "Raw realm");
pass(7, "same RealmId signed by another key: register 403 realm_key_mismatch, heartbeat 401 invalid_signature, record untouched");
h.sync_clock();
@@ -134,14 +134,14 @@ fn gate_1_to_12_against_the_node() {
h.sync_clock();
let mut hv = sign_request(&h.key, "POST", &path, &h.realm, h.ts + 1, &body).pairs();
hv[0] = (sign_header_version(), "2".into());
hv[0] = (sign_header_version(), "1".into());
let r = h.send_with("POST", &path, &body, &hv);
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"));
let mut v2 = h.heartbeat_body(60, false);
v2.protocol_version = 2;
v2.protocol_version = 1;
let r = h.send("POST", &path, &serde_json::to_vec(&v2).unwrap());
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"));
pass(10, "protocol version 2 (header and body): 400 unsupported_protocol_version");
pass(10, "protocol version 1 and 3 (header and body): 400 unsupported_protocol_version");
let big = vec![b'x'; MAX_REQUEST_BYTES + 1];
let r = h.send("POST", PATH_REGISTER, &big);
@@ -150,7 +150,7 @@ fn gate_1_to_12_against_the_node() {
let base_body = serde_json::to_value(hostile.register_body("Hostile", 60)).unwrap();
for (field, value) in [("display_name", json!("x".repeat(500))), ("description", json!("d".repeat(5000))), ("language", json!("<script>alert(1)</script>")), ("display_name", json!("evil\u{202E}name"))] {
let mut v = base_body.clone();
v[field] = value;
v["listing"][field] = value;
let r = hostile.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap());
assert_eq!(r.status, 400, "{field}");
}
@@ -232,7 +232,8 @@ fn gate_persist_probe_read() {
h.key = ed25519_dalek::SigningKey::from_bytes(&bytes.try_into().unwrap());
h.sync_clock();
let me = h.me();
assert_eq!((me.status, me.body["display_name"].as_str(), me.body["published"].as_bool()), (200, Some("Persist realm"), Some(true)), "{:?}", me.body);
assert_eq!((me.status, me.body["listing"]["display_name"].as_str(), me.body["published"].as_bool()), (200, Some("Persist realm"), Some(true)), "{:?}", me.body);
assert_eq!((me.body["listing"]["rates"]["xp_kill"].as_f64(), me.body["listing"]["modules"][0]["id"].as_str(), me.body["population"]["bots"].as_u64(), me.body["level_cap"].as_u64()), (Some(2.0), Some("playerbots"), Some(4), Some(60)), "the structured metadata survived: {:?}", me.body);
h.sync_clock();
assert_eq!(h.heartbeat(60, false).status, 200, "and it can still heartbeat with its own key");
println!("PERSIST_OK {realm}");
@@ -253,3 +254,31 @@ fn gate_registration_rate_limit() {
assert!(ok >= 1 && limited >= 1 && ok + limited == 13, "{codes:?}");
println!("GATE LIMIT PASS registrations from one address: {ok} accepted, {limited} refused with 429 ({codes:?})");
}
/// A record written by protocol 1 (`PERSIST_REALM`/`PERSIST_SEED` of the Phase-10 probe) is republished under protocol 2 by the same key: the identity and creation time are kept.
#[test]
#[ignore]
fn gate_v1_record_republishes_under_v2() {
let Some(base) = base() else { return };
let (Ok(realm), Ok(seed)) = (std::env::var("PERSIST_REALM"), std::env::var("PERSIST_SEED")) else { return };
let mut h = Host::remote(&base);
h.realm = RealmId::parse(&realm).unwrap();
let bytes: Vec<u8> = (0..seed.len() / 2).map(|i| u8::from_str_radix(&seed[2 * i..2 * i + 2], 16).unwrap()).collect();
h.key = ed25519_dalek::SigningKey::from_bytes(&bytes.try_into().unwrap());
h.sync_clock();
let before = h.me();
assert_eq!(before.status, 200, "the protocol-1 record is still there and its key still works: {:?}", before.body);
let created = before.body["created_at"].as_i64().unwrap();
assert!(before.body["listing"]["rates"]["xp_kill"].is_null(), "nothing structured was ever advertised for it");
assert_eq!(before.body["level_cap"], 60, "the cap of the capabilities it already held");
h.sync_clock();
let revision_before = before.body["metadata_revision"].as_u64().unwrap();
let r = h.register("Persist realm", 60);
assert_eq!((r.status, r.body["created"].as_bool()), (200, Some(false)), "{:?}", r.body);
assert_eq!(r.body["metadata_revision"].as_u64(), Some(revision_before + 1), "the upgrade is one metadata revision");
h.sync_clock();
let after = h.me();
assert_eq!(after.body["created_at"].as_i64(), Some(created), "the creation time is kept");
assert_eq!((after.body["listing"]["rates"]["xp_kill"].as_f64(), after.body["public_key"].as_str()), (Some(2.0), before.body["public_key"].as_str()));
println!("GATE_UPGRADE realm {realm} created_at {created} revision {revision_before} -> {}", revision_before + 1);
}
@@ -9,7 +9,7 @@ remote() { ssh "$VPS" "$1"; }
wait_healthy() { # $1 container, $2 seconds
i=0; while [ $i -lt "$2" ]; do
s=$(remote "sudo docker inspect -f '{{.State.Health.Status}}' $1 2>/dev/null"); [ "$s" = healthy ] && return 0; i=$((i+2)); sleep 2; done; return 1; }
wait_api() { i=0; while [ $i -lt 90 ]; do code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$REGISTRY_URL/registry/v1/healthz"); [ "$code" = 200 ] && return 0; i=$((i+2)); sleep 2; done; return 1; }
wait_api() { i=0; while [ $i -lt 90 ]; do code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' "$REGISTRY_URL/registry/v2/healthz"); [ "$code" = 200 ] && return 0; i=$((i+2)); sleep 2; done; return 1; }
out=$(run cargo test --test live_vps gate_persist_probe_write -- --ignored --nocapture | grep PERSIST_REALM)
set -- $out; REALM=$2; SEED=$3
@@ -24,12 +24,12 @@ remote "sudo docker restart coa-registry-registry-1 >/dev/null"; wait_healthy co
echo "--- 14a. PostgreSQL container restart (health is degraded meanwhile, then recovers by itself)"
remote "sudo docker restart coa-postgres-postgres-1 >/dev/null"
sleep 1; echo "health during the restart: $(curl -s -m 5 -o /dev/null -w '%{http_code}' "$REGISTRY_URL/registry/v1/healthz")"
sleep 1; echo "health during the restart: $(curl -s -m 5 -o /dev/null -w '%{http_code}' "$REGISTRY_URL/registry/v2/healthz")"
wait_healthy coa-postgres-postgres-1 90 && wait_api && check "14a: after restarting PostgreSQL (the Registry container was not restarted)"
echo "--- 14b. both stopped, PostgreSQL started later than the Registry (the Registry waits for it)"
remote "sudo docker stop coa-registry-registry-1 coa-postgres-postgres-1 >/dev/null; sudo docker start coa-registry-registry-1 >/dev/null"
sleep 6; echo "Registry up without a database: health $(curl -s -m 5 -o /dev/null -w '%{http_code}' "$REGISTRY_URL/registry/v1/healthz")"
sleep 6; echo "Registry up without a database: health $(curl -s -m 5 -o /dev/null -w '%{http_code}' "$REGISTRY_URL/registry/v2/healthz")"
remote "sudo docker start coa-postgres-postgres-1 >/dev/null"
wait_healthy coa-postgres-postgres-1 90 && wait_healthy coa-registry-registry-1 120 && wait_api && check "14b: after a cold start in the wrong order"
@@ -0,0 +1,17 @@
-- Registry schema, migration 2 (protocol 2: the structured listing). Forward-only; every realm keeps its id, its key, its creation time and its capabilities.
-- A record written under protocol 1 has advert_version = 1: it is kept, and it is not shown in a public list until its Host republishes under protocol 2.
ALTER TABLE realms RENAME COLUMN player_count TO players;
ALTER TABLE realms RENAME COLUMN player_capacity TO capacity;
ALTER TABLE realms
ADD COLUMN bots integer NOT NULL DEFAULT 0 CHECK (bots BETWEEN 0 AND 100000),
ADD COLUMN region text CHECK (region IS NULL OR char_length(region) BETWEEN 2 AND 16),
ADD COLUMN rates jsonb NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(rates) = 'object' AND octet_length(rates::text) <= 1024),
ADD COLUMN modules jsonb NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(modules) = 'array' AND octet_length(modules::text) <= 16384),
ADD COLUMN account_automatic boolean NOT NULL DEFAULT false,
ADD COLUMN account_existing_only boolean NOT NULL DEFAULT true,
ADD COLUMN listing_hash text CHECK (listing_hash IS NULL OR listing_hash ~ '^[0-9a-f]{64}$'),
ADD COLUMN level_cap integer CHECK (level_cap IS NULL OR level_cap BETWEEN 1 AND 255),
ADD COLUMN advert_version smallint NOT NULL DEFAULT 1 CHECK (advert_version IN (1, 2));
-- the level cap of a protocol-1 record is in the capabilities it already holds
UPDATE realms SET level_cap = (capabilities -> 'progression' ->> 'max_player_level')::integer
WHERE jsonb_typeof(capabilities -> 'progression') = 'object' AND (capabilities -> 'progression' ->> 'max_player_level') ~ '^[0-9]{1,3}$';
+23 -16
View File
@@ -111,15 +111,23 @@ impl From<StoreError> for ApiError {
pub fn router<S: Store>(state: Arc<AppState<S>>) -> Router {
Router::new()
.route("/registry/v1/healthz", get(healthz::<S>))
.route("/registry/v1/realms/register", post(register::<S>))
.route("/registry/v1/realms/{realm_id}/heartbeat", post(heartbeat::<S>))
.route("/registry/v1/realms/{realm_id}/unpublish", post(unpublish::<S>))
.route("/registry/v1/realms/{realm_id}", get(self_info::<S>))
.fallback(|| async { ApiError::new(StatusCode::NOT_FOUND, ErrorCode::MalformedRequest, "no such endpoint") })
.route("/registry/v2/healthz", get(healthz::<S>))
.route("/registry/v2/realms/register", post(register::<S>))
.route("/registry/v2/realms/{realm_id}/heartbeat", post(heartbeat::<S>))
.route("/registry/v2/realms/{realm_id}/unpublish", post(unpublish::<S>))
.route("/registry/v2/realms/{realm_id}/self", get(self_info::<S>))
.fallback(fallback)
.with_state(state)
}
/// Protocol 1 is refused explicitly (the policy of `docs/REGISTRY_PROTOCOL.md`): a Host that still speaks it is told so and stops; nothing is silently accepted or migrated.
async fn fallback(uri: Uri) -> ApiError {
if uri.path() == PATH_PREFIX_V1 || uri.path().starts_with("/registry/v1/") {
return ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::UnsupportedProtocolVersion, format!("protocol version 1 is no longer supported; this Registry speaks protocol {REGISTRY_PROTOCOL_VERSION} under {PATH_PREFIX}"));
}
ApiError::new(StatusCode::NOT_FOUND, ErrorCode::MalformedRequest, "no such endpoint")
}
fn client_ip(headers: &HeaderMap, peer: SocketAddr, trust_proxy: bool) -> IpAddr {
if trust_proxy {
if let Some(last) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()).and_then(|v| v.rsplit(',').next()) {
@@ -247,6 +255,7 @@ async fn register<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Peer
created,
metadata_revision: row.metadata_revision,
published: row.published,
listing_hash: row.listing_hash.clone(),
capabilities_hash: row.capabilities_hash.clone(),
server_time: now,
heartbeat_interval_secs: HEARTBEAT_INTERVAL_SECS,
@@ -300,7 +309,7 @@ async fn heartbeat<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Pee
hb.validate().map_err(|e| ApiError::new(StatusCode::BAD_REQUEST, ErrorCode::InvalidMetadata, e.to_string()))?;
let now = st.now();
let out = st.store.heartbeat(&realm, &hb, now, ts).await?;
let resp = HeartbeatResponse { protocol_version: REGISTRY_PROTOCOL_VERSION, metadata_revision: out.metadata_revision, published: true, capabilities_hash: out.capabilities_hash.clone(), resend_capabilities: out.resend_capabilities, server_time: now };
let resp = HeartbeatResponse { protocol_version: REGISTRY_PROTOCOL_VERSION, metadata_revision: out.metadata_revision, published: true, listing_hash: out.listing_hash.clone(), capabilities_hash: out.capabilities_hash.clone(), resend_listing: out.resend_listing, resend_capabilities: out.resend_capabilities, server_time: now };
let (status, response) = json(&resp);
Ok((status, response, out.capabilities_hash))
}
@@ -331,27 +340,25 @@ async fn unpublish<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Pee
finish("unpublish", realm_for_log.as_ref(), started, result)
}
fn self_response(row: RealmRow, now: i64, ttl: u64) -> SelfResponse {
pub fn detail_of(row: RealmRow, now: i64, ttl: u64) -> RealmDetail {
let online = row.published && now - row.last_seen_at <= ttl as i64;
SelfResponse {
RealmDetail {
protocol_version: REGISTRY_PROTOCOL_VERSION,
realm_id: row.realm_id,
public_key: sign::encode_public_key(&ed25519_dalek::VerifyingKey::from_bytes(&row.public_key).expect("a stored key was validated on the way in")),
display_name: row.display_name,
description: row.description,
language: row.language,
listing: row.listing,
ruleset: row.ruleset,
manager_version: row.manager_version,
level_cap: row.level_cap,
population: row.population,
capabilities: row.capabilities,
capabilities_hash: row.capabilities_hash,
listing_hash: row.listing_hash,
metadata_revision: row.metadata_revision,
published: row.published,
online,
created_at: row.created_at,
updated_at: row.updated_at,
last_seen_at: row.last_seen_at,
player_count: row.player_count,
player_capacity: row.player_capacity,
server_time: now,
}
}
@@ -372,7 +379,7 @@ async fn self_info<S: Store>(State(st): State<Arc<AppState<S>>>, ConnectInfo(Pee
realm_for_log = Some(realm);
let row = st.store.get(&realm).await?.ok_or(StoreError::Unknown)?;
let caps = row.capabilities_hash.clone();
let (status, response) = json(&self_response(row, st.now(), st.cfg.online_ttl_secs));
let (status, response) = json(&detail_of(row, st.now(), st.cfg.online_ttl_secs));
Ok((status, response, caps))
}
.await;
+1 -1
View File
@@ -32,7 +32,7 @@ fn healthcheck() -> i32 {
let port = addr.rsplit(':').next().unwrap_or("8080");
let Ok(mut s) = std::net::TcpStream::connect(format!("127.0.0.1:{port}")) else { return 1 };
let _ = s.set_read_timeout(Some(Duration::from_secs(3)));
if s.write_all(b"GET /registry/v1/healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").is_err() {
if s.write_all(b"GET /registry/v2/healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").is_err() {
return 1;
}
let mut out = String::new();
+90 -32
View File
@@ -3,13 +3,16 @@
use std::time::Duration;
use coa_registry_proto::caps::{AdvertisedCapabilities, Ruleset};
use coa_registry_proto::{HeartbeatRequest, RealmId, RegisterRequest};
use coa_registry_proto::{AccountProvisioning, HeartbeatRequest, Listing, ModuleEntry, Population, Rates, RealmId, RegisterRequest};
use deadpool_postgres::{Manager, ManagerConfig, Object, Pool, RecyclingMethod, Runtime};
use tokio_postgres::{NoTls, Row};
use crate::store::*;
const MIGRATIONS: &[(i32, &str, &str)] = &[(1, "realms", include_str!("../migrations/0001_realms.sql"))];
const MIGRATIONS: &[(i32, &str, &str)] = &[
(1, "realms", include_str!("../migrations/0001_realms.sql")),
(2, "protocol_v2", include_str!("../migrations/0002_protocol_v2.sql")),
];
pub struct PgConfig {
pub host: String,
@@ -47,7 +50,7 @@ impl PgStore {
Ok(Self { pool })
}
async fn conn(&self) -> StoreResult<Object> {
pub(crate) async fn conn(&self) -> StoreResult<Object> {
self.pool.get().await.map_err(backend)
}
@@ -81,16 +84,32 @@ impl PgStore {
}
}
const COLUMNS: &str = "realm_id::text, public_key, EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint, EXTRACT(EPOCH FROM last_seen_at)::bigint, published, display_name, description, language, ruleset, manager_version, capabilities, capabilities_hash, metadata_revision, last_request_ts, player_count, player_capacity";
pub(crate) const COLUMNS: &str = "realm_id::text, public_key, EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint, EXTRACT(EPOCH FROM last_seen_at)::bigint, published, display_name, description, language, region, rates, modules, account_automatic, account_existing_only, manager_version, listing_hash, ruleset, level_cap, capabilities, capabilities_hash, players, bots, capacity, metadata_revision, last_request_ts, advert_version";
fn to_row(r: &Row) -> StoreResult<RealmRow> {
pub(crate) fn to_row(r: &Row) -> StoreResult<RealmRow> {
let id: String = r.get(0);
let key: Vec<u8> = r.get(1);
let ruleset: String = r.get(9);
let caps: serde_json::Value = r.get(11);
let revision: i64 = r.get(13);
let count: Option<i32> = r.get(15);
let capacity: Option<i32> = r.get(16);
let rates: serde_json::Value = r.get(10);
let modules: serde_json::Value = r.get(11);
let ruleset: String = r.get(16);
let level_cap: Option<i32> = r.get(17);
let caps: serde_json::Value = r.get(18);
let players: Option<i32> = r.get(20);
let bots: i32 = r.get(21);
let capacity: Option<i32> = r.get(22);
let revision: i64 = r.get(23);
let version: i16 = r.get(25);
let listing = Listing {
display_name: r.get(6),
description: r.get(7),
language: r.get(8),
region: r.get(9),
rates: serde_json::from_value::<Rates>(rates).unwrap_or_default(),
modules: serde_json::from_value::<Vec<ModuleEntry>>(modules).unwrap_or_default(),
account_provisioning: AccountProvisioning { automatic: r.get(12), existing_only: r.get(13) },
manager_version: r.get(14),
};
let stored_hash: Option<String> = r.get(15);
Ok(RealmRow {
realm_id: RealmId::parse(&id).map_err(backend)?,
public_key: key.try_into().map_err(|_| StoreError::Backend("a stored key is not 32 bytes".into()))?,
@@ -98,21 +117,20 @@ fn to_row(r: &Row) -> StoreResult<RealmRow> {
updated_at: r.get(3),
last_seen_at: r.get(4),
published: r.get(5),
display_name: r.get(6),
description: r.get(7),
language: r.get(8),
listing_hash: stored_hash.unwrap_or_else(|| listing.hash()),
listing,
ruleset: match ruleset.as_str() {
"coa" => Ruleset::Coa,
"wildcard" => Ruleset::Wildcard,
other => return Err(StoreError::Backend(format!("a stored ruleset is unknown: {other}"))),
},
manager_version: r.get(10),
level_cap: level_cap.map(|n| n as u32),
capabilities: serde_json::from_value::<AdvertisedCapabilities>(caps).map_err(backend)?,
capabilities_hash: r.get(12),
capabilities_hash: r.get(19),
population: Population { players: players.unwrap_or(0) as u32, bots: bots as u32, capacity: capacity.map(|n| n as u32) },
metadata_revision: revision as u64,
last_request_ts: r.get(14),
player_count: count.map(|n| n as u32),
player_capacity: capacity.map(|n| n as u32),
last_request_ts: r.get(24),
advert_version: version as u8,
})
}
@@ -120,6 +138,15 @@ fn caps_json(c: &AdvertisedCapabilities) -> StoreResult<serde_json::Value> {
serde_json::to_value(c).map_err(backend)
}
struct ListingColumns {
rates: serde_json::Value,
modules: serde_json::Value,
}
fn listing_columns(l: &Listing) -> StoreResult<ListingColumns> {
Ok(ListingColumns { rates: serde_json::to_value(&l.rates).map_err(backend)?, modules: serde_json::to_value(&l.modules).map_err(backend)? })
}
impl Store for PgStore {
async fn ping(&self) -> bool {
match self.pool.get().await {
@@ -149,14 +176,17 @@ impl Store for PgStore {
let existing = existing.as_ref().map(to_row).transpose()?;
let (row, created) = plan_register(existing.as_ref(), req, key, now, ts)?;
let caps = caps_json(&row.capabilities)?;
let cols = listing_columns(&row.listing)?;
let ruleset = row.ruleset.as_str();
let players = (row.player_count.map(|n| n as i32), row.player_capacity.map(|n| n as i32));
let (players, bots, capacity) = (row.population.players as i32, row.population.bots as i32, row.population.capacity.map(|n| n as i32));
let level_cap = row.level_cap.map(|n| n as i32);
let l = &row.listing;
if created {
let n = tx
.execute(
"INSERT INTO realms (realm_id, public_key, created_at, updated_at, last_seen_at, published, display_name, description, language, ruleset, manager_version, capabilities, capabilities_hash, metadata_revision, last_request_ts, player_count, player_capacity) \
VALUES ($1::text::uuid, $2, to_timestamp($3::bigint), to_timestamp($3::bigint), to_timestamp($3::bigint), true, $4, $5, $6, $7, $8, $9, $10, 1, $11, $12, $13) ON CONFLICT (realm_id) DO NOTHING",
&[&id, &row.public_key.as_slice(), &now, &row.display_name, &row.description, &row.language, &ruleset, &row.manager_version, &caps, &row.capabilities_hash, &ts, &players.0, &players.1],
"INSERT INTO realms (realm_id, public_key, created_at, updated_at, last_seen_at, published, display_name, description, language, region, rates, modules, account_automatic, account_existing_only, manager_version, listing_hash, ruleset, level_cap, capabilities, capabilities_hash, players, bots, capacity, metadata_revision, last_request_ts, advert_version) \
VALUES ($1::text::uuid, $2, to_timestamp($3::bigint), to_timestamp($3::bigint), to_timestamp($3::bigint), true, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, 1, $21, 2) ON CONFLICT (realm_id) DO NOTHING",
&[&id, &row.public_key.as_slice(), &now, &l.display_name, &l.description, &l.language, &l.region, &cols.rates, &cols.modules, &l.account_provisioning.automatic, &l.account_provisioning.existing_only, &l.manager_version, &row.listing_hash, &ruleset, &level_cap, &caps, &row.capabilities_hash, &players, &bots, &capacity, &ts],
)
.await
.map_err(backend)?;
@@ -166,8 +196,8 @@ impl Store for PgStore {
}
} else {
tx.execute(
"UPDATE realms SET updated_at = to_timestamp($2::bigint), last_seen_at = to_timestamp($3::bigint), published = true, display_name = $4, description = $5, language = $6, ruleset = $7, manager_version = $8, capabilities = $9, capabilities_hash = $10, metadata_revision = $11, last_request_ts = $12, player_count = $13, player_capacity = $14 WHERE realm_id = $1::text::uuid",
&[&id, &row.updated_at, &now, &row.display_name, &row.description, &row.language, &ruleset, &row.manager_version, &caps, &row.capabilities_hash, &(row.metadata_revision as i64), &ts, &players.0, &players.1],
"UPDATE realms SET updated_at = to_timestamp($2::bigint), last_seen_at = to_timestamp($3::bigint), published = true, display_name = $4, description = $5, language = $6, region = $7, rates = $8, modules = $9, account_automatic = $10, account_existing_only = $11, manager_version = $12, listing_hash = $13, ruleset = $14, level_cap = $15, capabilities = $16, capabilities_hash = $17, players = $18, bots = $19, capacity = $20, metadata_revision = $21, last_request_ts = $22, advert_version = 2 WHERE realm_id = $1::text::uuid",
&[&id, &row.updated_at, &now, &l.display_name, &l.description, &l.language, &l.region, &cols.rates, &cols.modules, &l.account_provisioning.automatic, &l.account_provisioning.existing_only, &l.manager_version, &row.listing_hash, &ruleset, &level_cap, &caps, &row.capabilities_hash, &players, &bots, &capacity, &(row.metadata_revision as i64), &ts],
)
.await
.map_err(backend)?;
@@ -183,26 +213,54 @@ impl Store for PgStore {
let text = id.to_string();
let tx = c.transaction().await.map_err(backend)?;
let r = tx
.query_opt("SELECT published, last_request_ts, capabilities_hash, display_name, description, language, manager_version, metadata_revision FROM realms WHERE realm_id = $1::text::uuid FOR UPDATE", &[&text])
.query_opt("SELECT published, last_request_ts, capabilities_hash, listing_hash, metadata_revision, advert_version, display_name, description, language, region, rates, modules, account_automatic, account_existing_only, manager_version FROM realms WHERE realm_id = $1::text::uuid FOR UPDATE", &[&text])
.await
.map_err(backend)?
.ok_or(StoreError::Unknown)?;
let revision: i64 = r.get(7);
let view = HeartbeatView { published: r.get(0), last_request_ts: r.get(1), capabilities_hash: r.get(2), display_name: r.get(3), description: r.get(4), language: r.get(5), manager_version: r.get(6), metadata_revision: revision as u64 };
let revision: i64 = r.get(4);
let version: i16 = r.get(5);
let stored_listing_hash: Option<String> = r.get(3);
let listing_hash = match stored_listing_hash {
Some(h) => h,
None => {
let l = Listing {
display_name: r.get(6),
description: r.get(7),
language: r.get(8),
region: r.get(9),
rates: serde_json::from_value::<Rates>(r.get(10)).unwrap_or_default(),
modules: serde_json::from_value::<Vec<ModuleEntry>>(r.get(11)).unwrap_or_default(),
account_provisioning: AccountProvisioning { automatic: r.get(12), existing_only: r.get(13) },
manager_version: r.get(14),
};
l.hash()
}
};
let view = HeartbeatView { published: r.get(0), last_request_ts: r.get(1), capabilities_hash: r.get(2), listing_hash, metadata_revision: revision as u64, advert_version: version as u8 };
let plan = plan_heartbeat(&view, hb, ts)?;
let players = (hb.player_count.map(|n| n as i32), hb.player_capacity.map(|n| n as i32));
let (players, bots, capacity) = (hb.population.players as i32, hb.population.bots as i32, hb.population.capacity.map(|n| n as i32));
tx.execute(
"UPDATE realms SET last_seen_at = to_timestamp($2::bigint), last_request_ts = $3, player_count = $4, player_capacity = $5, display_name = $6, description = $7, language = $8, manager_version = $9, capabilities_hash = $10, metadata_revision = $11, updated_at = CASE WHEN $12 THEN to_timestamp($2::bigint) ELSE updated_at END WHERE realm_id = $1::text::uuid",
&[&text, &now, &ts, &players.0, &players.1, &plan.display_name, &plan.description, &plan.language, &plan.manager_version, &plan.capabilities_hash, &(plan.metadata_revision as i64), &plan.metadata_changed],
"UPDATE realms SET last_seen_at = to_timestamp($2::bigint), last_request_ts = $3, players = $4, bots = $5, capacity = $6, listing_hash = $7, capabilities_hash = $8, metadata_revision = $9, updated_at = CASE WHEN $10 THEN to_timestamp($2::bigint) ELSE updated_at END WHERE realm_id = $1::text::uuid",
&[&text, &now, &ts, &players, &bots, &capacity, &plan.listing_hash, &plan.capabilities_hash, &(plan.metadata_revision as i64), &plan.metadata_changed],
)
.await
.map_err(backend)?;
if let Some(l) = &plan.listing {
let cols = listing_columns(l)?;
tx.execute(
"UPDATE realms SET display_name = $2, description = $3, language = $4, region = $5, rates = $6, modules = $7, account_automatic = $8, account_existing_only = $9, manager_version = $10, advert_version = 2 WHERE realm_id = $1::text::uuid",
&[&text, &l.display_name, &l.description, &l.language, &l.region, &cols.rates, &cols.modules, &l.account_provisioning.automatic, &l.account_provisioning.existing_only, &l.manager_version],
)
.await
.map_err(backend)?;
}
if let Some(caps) = &plan.capabilities {
let json = caps_json(caps)?;
tx.execute("UPDATE realms SET capabilities = $2, ruleset = $3 WHERE realm_id = $1::text::uuid", &[&text, &json, &caps.content.ruleset.as_str()]).await.map_err(backend)?;
let level_cap = caps.level_cap().map(|n| n as i32);
tx.execute("UPDATE realms SET capabilities = $2, ruleset = $3, level_cap = $4 WHERE realm_id = $1::text::uuid", &[&text, &json, &caps.content.ruleset.as_str(), &level_cap]).await.map_err(backend)?;
}
tx.commit().await.map_err(backend)?;
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, capabilities_hash: plan.capabilities_hash, resend_capabilities: plan.resend_capabilities })
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, listing_hash: plan.listing_hash, capabilities_hash: plan.capabilities_hash, resend_listing: plan.resend_listing, resend_capabilities: plan.resend_capabilities })
}
async fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> StoreResult<u64> {
+56 -53
View File
@@ -6,7 +6,7 @@ use std::future::Future;
use std::sync::Mutex;
use coa_registry_proto::caps::{AdvertisedCapabilities, Ruleset};
use coa_registry_proto::{HeartbeatRequest, RealmId, RegisterRequest};
use coa_registry_proto::{HeartbeatRequest, Listing, Population, RealmId, RegisterRequest};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum StoreError {
@@ -24,6 +24,9 @@ pub enum StoreError {
pub type StoreResult<T> = Result<T, StoreError>;
/// The version of advertisement a row holds: 1 is a Phase-10 record (identity, key and capabilities kept, nothing structured), 2 is a full v2 listing.
pub const ADVERT_VERSION: u8 = 2;
#[derive(Clone, Debug, PartialEq)]
pub struct RealmRow {
pub realm_id: RealmId,
@@ -32,17 +35,17 @@ pub struct RealmRow {
pub updated_at: i64,
pub last_seen_at: i64,
pub published: bool,
pub display_name: String,
pub description: String,
pub language: String,
pub listing: Listing,
pub listing_hash: String,
/// Derived from the capabilities.
pub ruleset: Ruleset,
pub manager_version: String,
pub level_cap: Option<u32>,
pub capabilities: AdvertisedCapabilities,
pub capabilities_hash: String,
pub population: Population,
pub metadata_revision: u64,
pub last_request_ts: i64,
pub player_count: Option<u32>,
pub player_capacity: Option<u32>,
pub advert_version: u8,
}
/// The light part of a row a heartbeat decides on (the capabilities JSON stays in the database unless it changes).
@@ -50,40 +53,29 @@ pub struct RealmRow {
pub struct HeartbeatView {
pub published: bool,
pub last_request_ts: i64,
pub listing_hash: String,
pub capabilities_hash: String,
pub display_name: String,
pub description: String,
pub language: String,
pub manager_version: String,
pub metadata_revision: u64,
pub advert_version: u8,
}
impl From<&RealmRow> for HeartbeatView {
fn from(r: &RealmRow) -> Self {
Self {
published: r.published,
last_request_ts: r.last_request_ts,
capabilities_hash: r.capabilities_hash.clone(),
display_name: r.display_name.clone(),
description: r.description.clone(),
language: r.language.clone(),
manager_version: r.manager_version.clone(),
metadata_revision: r.metadata_revision,
}
Self { published: r.published, last_request_ts: r.last_request_ts, listing_hash: r.listing_hash.clone(), capabilities_hash: r.capabilities_hash.clone(), metadata_revision: r.metadata_revision, advert_version: r.advert_version }
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct HeartbeatPlan {
pub display_name: String,
pub description: String,
pub language: String,
pub manager_version: String,
/// Set only when the listing is applied: the only case in which its columns are written.
pub listing: Option<Listing>,
pub listing_hash: String,
/// Set only when the hash changed: the only case in which the large JSON is written.
pub capabilities: Option<AdvertisedCapabilities>,
pub capabilities_hash: String,
pub metadata_revision: u64,
pub metadata_changed: bool,
pub resend_listing: bool,
pub resend_capabilities: bool,
}
@@ -95,17 +87,26 @@ pub fn plan_heartbeat(view: &HeartbeatView, hb: &HeartbeatRequest, ts: i64) -> S
return Err(StoreError::NotPublished);
}
let mut plan = HeartbeatPlan {
display_name: hb.display_name.clone().unwrap_or_else(|| view.display_name.clone()),
description: hb.description.clone().unwrap_or_else(|| view.description.clone()),
language: hb.language.clone().unwrap_or_else(|| view.language.clone()),
manager_version: hb.manager_version.clone().unwrap_or_else(|| view.manager_version.clone()),
listing: None,
listing_hash: view.listing_hash.clone(),
capabilities: None,
capabilities_hash: view.capabilities_hash.clone(),
metadata_revision: view.metadata_revision,
metadata_changed: false,
resend_listing: false,
resend_capabilities: false,
};
plan.metadata_changed = plan.display_name != view.display_name || plan.description != view.description || plan.language != view.language || plan.manager_version != view.manager_version;
// a record from before protocol 2 has no structured listing: it takes the first one it is given, whatever the hashes say
let legacy = view.advert_version < ADVERT_VERSION;
match &hb.listing {
Some(l) if legacy || hb.listing_hash != view.listing_hash => {
plan.listing = Some(l.clone());
plan.listing_hash = hb.listing_hash.clone();
plan.metadata_changed = true;
}
None if legacy || hb.listing_hash != view.listing_hash => plan.resend_listing = true,
_ => {}
}
match &hb.capabilities {
Some(c) if hb.capabilities_hash != view.capabilities_hash => {
plan.capabilities = Some(c.clone());
@@ -121,7 +122,7 @@ pub fn plan_heartbeat(view: &HeartbeatView, hb: &HeartbeatRequest, ts: i64) -> S
Ok(plan)
}
/// The new row for a registration: a first one, or the same key announcing itself again (a restart, a changed name, a republication).
/// The new row for a registration: a first one, or the same key announcing itself again (a restart, a changed name, a republication, a record upgraded from protocol 1).
pub fn plan_register(existing: Option<&RealmRow>, req: &RegisterRequest, key: [u8; 32], now: i64, ts: i64) -> StoreResult<(RealmRow, bool)> {
let mut row = RealmRow {
realm_id: req.realm_id,
@@ -130,17 +131,16 @@ pub fn plan_register(existing: Option<&RealmRow>, req: &RegisterRequest, key: [u
updated_at: now,
last_seen_at: now,
published: true,
display_name: req.display_name.clone(),
description: req.description.clone(),
language: req.language.clone(),
ruleset: req.ruleset,
manager_version: req.manager_version.clone(),
listing: req.listing.clone(),
listing_hash: req.listing_hash.clone(),
ruleset: req.capabilities.content.ruleset,
level_cap: req.capabilities.level_cap(),
capabilities: req.capabilities.clone(),
capabilities_hash: req.capabilities_hash.clone(),
population: req.population,
metadata_revision: 1,
last_request_ts: ts,
player_count: req.player_count,
player_capacity: req.player_capacity,
advert_version: ADVERT_VERSION,
};
let Some(old) = existing else { return Ok((row, true)) };
if old.public_key != key {
@@ -150,13 +150,7 @@ pub fn plan_register(existing: Option<&RealmRow>, req: &RegisterRequest, key: [u
return Err(StoreError::Stale);
}
row.created_at = old.created_at;
let changed = !old.published
|| old.display_name != row.display_name
|| old.description != row.description
|| old.language != row.language
|| old.ruleset != row.ruleset
|| old.manager_version != row.manager_version
|| old.capabilities_hash != row.capabilities_hash;
let changed = !old.published || old.advert_version < ADVERT_VERSION || old.listing_hash != row.listing_hash || old.capabilities_hash != row.capabilities_hash;
row.metadata_revision = old.metadata_revision + u64::from(changed);
row.updated_at = if changed { now } else { old.updated_at };
Ok((row, false))
@@ -177,7 +171,9 @@ pub trait Store: Send + Sync + 'static {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HeartbeatOutcome {
pub metadata_revision: u64,
pub listing_hash: String,
pub capabilities_hash: String,
pub resend_listing: bool,
pub resend_capabilities: bool,
}
@@ -196,6 +192,12 @@ impl MemoryStore {
self.rows.lock().unwrap().get(id).cloned()
}
/// Put a row in as it is (tests: a record left by an earlier protocol).
#[doc(hidden)]
pub fn put_for_test(&self, row: RealmRow) {
self.rows.lock().unwrap().insert(row.realm_id, row);
}
/// Forget everything (tests: a Registry that lost its data).
#[doc(hidden)]
pub fn forget_all(&self) {
@@ -249,12 +251,14 @@ impl Store for MemoryStore {
let mut rows = self.rows.lock().unwrap();
let row = rows.get_mut(id).ok_or(StoreError::Unknown)?;
let plan = plan_heartbeat(&HeartbeatView::from(&*row), hb, ts)?;
row.display_name = plan.display_name;
row.description = plan.description;
row.language = plan.language;
row.manager_version = plan.manager_version;
if let Some(c) = plan.capabilities {
if let Some(l) = plan.listing.clone() {
row.listing = l;
row.advert_version = ADVERT_VERSION;
}
row.listing_hash = plan.listing_hash.clone();
if let Some(c) = plan.capabilities.clone() {
row.ruleset = c.content.ruleset;
row.level_cap = c.level_cap();
row.capabilities = c;
}
row.capabilities_hash = plan.capabilities_hash.clone();
@@ -264,9 +268,8 @@ impl Store for MemoryStore {
row.metadata_revision = plan.metadata_revision;
row.last_seen_at = now;
row.last_request_ts = ts;
row.player_count = hb.player_count;
row.player_capacity = hb.player_capacity;
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, capabilities_hash: plan.capabilities_hash, resend_capabilities: plan.resend_capabilities })
row.population = hb.population;
Ok(HeartbeatOutcome { metadata_revision: plan.metadata_revision, listing_hash: plan.listing_hash, capabilities_hash: plan.capabilities_hash, resend_listing: plan.resend_listing, resend_capabilities: plan.resend_capabilities })
}
async fn unpublish(&self, id: &RealmId, now: i64, ts: i64) -> StoreResult<u64> {
+147 -57
View File
@@ -4,8 +4,9 @@ mod common;
use coa_registry::api::ApiConfig;
use coa_registry::limits::Rate;
use coa_registry::store::MemoryStore;
use coa_registry::store::{MemoryStore, RealmRow, ADVERT_VERSION};
use coa_registry_proto::sign::{sign_request, HEADER_SIGNATURE, HEADER_TIMESTAMP, HEADER_VERSION};
use coa_registry_proto::caps::Ruleset;
use coa_registry_proto::*;
use common::*;
use ed25519_dalek::SigningKey;
@@ -27,22 +28,28 @@ fn lifecycle(s: &TestServer) {
assert_eq!(r.status, 200, "{:?}", r.body);
assert_eq!((r.body["created"].as_bool(), r.body["metadata_revision"].as_u64(), r.body["published"].as_bool()), (Some(true), Some(1), Some(true)));
assert_eq!((r.body["heartbeat_interval_secs"].as_u64(), r.body["online_ttl_secs"].as_u64()), (Some(30), Some(120)));
assert_eq!(r.body["protocol_version"], 2);
let me = h.me();
assert_eq!(me.status, 200);
assert_eq!((me.body["online"].as_bool(), me.body["display_name"].as_str(), me.body["last_seen_at"].as_i64()), (Some(true), Some("Friends' realm"), Some(s.time())));
assert_eq!(me.status, 200, "{:?}", me.body);
assert_eq!((me.body["online"].as_bool(), me.body["listing"]["display_name"].as_str(), me.body["last_seen_at"].as_i64()), (Some(true), Some("Friends' realm"), Some(s.time())));
assert_eq!(me.body["capabilities"]["progression"]["max_player_level"], 60);
assert_eq!((me.body["level_cap"].as_u64(), me.body["ruleset"].as_str()), (Some(60), Some("coa")), "derived from the capabilities");
assert_eq!((me.body["population"]["players"].as_u64(), me.body["population"]["bots"].as_u64()), (Some(1), Some(4)), "players and bots are separate");
assert_eq!(me.body["listing"]["rates"]["xp_kill"], 2.0);
assert!(me.body["listing"]["rates"]["xp_explore"].is_null(), "an unknown rate stays null");
assert_eq!(me.body["listing"]["modules"][0]["id"], "playerbots");
s.advance(30);
h.ts = s.time();
let hb = h.heartbeat(60, false);
assert_eq!(hb.status, 200, "{:?}", hb.body);
assert_eq!((hb.body["metadata_revision"].as_u64(), hb.body["resend_capabilities"].as_bool()), (Some(1), Some(false)));
assert_eq!((hb.body["metadata_revision"].as_u64(), hb.body["resend_capabilities"].as_bool(), hb.body["resend_listing"].as_bool()), (Some(1), Some(false), Some(false)));
let me = h.me();
assert_eq!((me.body["last_seen_at"].as_i64(), me.body["player_count"].as_u64()), (Some(s.time()), Some(2)), "the heartbeat moved last_seen and the player count");
assert_eq!((me.body["last_seen_at"].as_i64(), me.body["population"]["players"].as_u64(), me.body["population"]["bots"].as_u64()), (Some(s.time()), Some(2), Some(4)), "the heartbeat moved last_seen and the counts");
assert_eq!(me.body["metadata_revision"], 1, "a heartbeat of unchanged metadata is not a metadata update");
// the same key announcing itself again (a Manager restart) keeps the identity; unchanged metadata keeps the revision
// the same key announcing itself again (a restart) keeps the identity; unchanged metadata keeps the revision
let again = h.register("Friends' realm", 60);
assert_eq!((again.status, again.body["created"].as_bool(), again.body["metadata_revision"].as_u64()), (200, Some(false), Some(1)));
let renamed = h.register("Friends' realm II", 60);
@@ -65,7 +72,7 @@ fn presence(s: &TestServer) {
assert_eq!(h.me().body["online"], true);
}
/// 6: new capabilities arrive with a heartbeat and move the metadata revision; a changed hash without them asks for them.
/// 6: new capabilities and a new listing arrive with a heartbeat and move the metadata revision; a changed hash without the part asks for it.
fn metadata_changes(s: &TestServer) {
let mut h = Host::new(s, 3);
assert_eq!(h.register("Caps", 60).status, 200);
@@ -77,16 +84,28 @@ fn metadata_changes(s: &TestServer) {
let hb = h.heartbeat(70, true);
assert_eq!((hb.status, hb.body["resend_capabilities"].as_bool(), hb.body["metadata_revision"].as_u64()), (200, Some(false), Some(2)));
let me = h.me();
assert_eq!((me.body["capabilities"]["progression"]["max_player_level"].as_u64(), me.body["metadata_revision"].as_u64()), (Some(70), Some(2)));
assert_eq!((me.body["capabilities"]["progression"]["max_player_level"].as_u64(), me.body["level_cap"].as_u64(), me.body["metadata_revision"].as_u64()), (Some(70), Some(70), Some(2)), "the level cap follows the capabilities");
let hb = h.heartbeat(70, true);
assert_eq!(hb.body["metadata_revision"], 2, "the same capabilities again change nothing");
// a heartbeat may also rename
// a changed listing: first only its hash (asks for it), then the listing
let mut body = h.heartbeat_body(70, false);
body.display_name = Some("Renamed".into());
let renamed = h.listing("Renamed");
body.listing_hash = renamed.hash();
let path = path_heartbeat(&h.realm);
let r = h.send("POST", &path, &serde_json::to_vec(&body).unwrap());
assert_eq!((r.status, r.body["resend_listing"].as_bool(), r.body["metadata_revision"].as_u64()), (200, Some(true), Some(2)));
h.name = "Renamed".into();
let body = h.heartbeat_with_listing(70, "Renamed");
let r = h.send("POST", &path, &serde_json::to_vec(&body).unwrap());
assert_eq!((r.status, r.body["resend_listing"].as_bool(), r.body["metadata_revision"].as_u64()), (200, Some(false), Some(3)));
assert_eq!(h.me().body["listing"]["display_name"], "Renamed");
// players and bots move without touching the revision
let mut body = h.heartbeat_body(70, false);
body.population = Population { players: 18, bots: 46, capacity: None };
let r = h.send("POST", &path, &serde_json::to_vec(&body).unwrap());
assert_eq!((r.status, r.body["metadata_revision"].as_u64()), (200, Some(3)));
assert_eq!(h.me().body["display_name"], "Renamed");
let me = h.me();
assert_eq!((me.body["population"]["players"].as_u64(), me.body["population"]["bots"].as_u64(), me.body["metadata_revision"].as_u64()), (Some(18), Some(46), Some(3)));
}
/// 7: an unrelated key can neither take a realm id over nor speak for it.
@@ -105,7 +124,7 @@ fn takeover(s: &TestServer) {
let r = thief.me();
assert_eq!(r.status, 401);
let me = owner.me();
assert_eq!((me.body["display_name"].as_str(), me.body["published"].as_bool()), (Some("Mine"), Some(true)), "the owner's record is untouched");
assert_eq!((me.body["listing"]["display_name"].as_str(), me.body["published"].as_bool()), (Some("Mine"), Some(true)), "the owner's record is untouched");
}
/// 8, 9, 10: tampering, time, and protocol version.
@@ -115,28 +134,24 @@ fn authentication(s: &TestServer) {
let path = path_heartbeat(&h.realm);
let body = serde_json::to_vec(&h.heartbeat_body(60, false)).unwrap();
// a body changed after it was signed
h.ts += 1;
let headers = sign_request(&h.key, "POST", &path, &h.realm, h.ts, &body);
let mut tampered = body.clone();
tampered.extend_from_slice(b" ");
let r = h.send_with("POST", &path, &tampered, &headers.pairs());
assert_eq!((r.status, r.code().as_str()), (401, "invalid_signature"));
// the method and the path are signed too
let r = h.send_with("POST", &path_unpublish(&h.realm), &serde_json::to_vec(&UnpublishRequest { protocol_version: 1 }).unwrap(), &headers.pairs());
let r = h.send_with("POST", &path_unpublish(&h.realm), &serde_json::to_vec(&UnpublishRequest { protocol_version: 2 }).unwrap(), &headers.pairs());
assert_eq!((r.status, r.code().as_str()), (401, "invalid_signature"), "a signature for one endpoint is not valid for another");
let r = h.send_with("POST", &path, &body, &headers.pairs());
assert_eq!(r.status, 200, "the untampered request is fine: {:?}", r.body);
let r = h.send_with("POST", &path, &body, &headers.pairs());
assert_eq!((r.status, r.code().as_str()), (401, "timestamp_not_monotonic"), "a captured request cannot be replayed");
// timestamps outside the window, either way
for skew in [-400, 400] {
h.ts = s.time() + skew;
let r = h.send("POST", &path, &body);
assert_eq!((r.status, r.code().as_str()), (401, "bad_timestamp"), "skew {skew}");
}
// a timestamp that is in the window but not later than the last applied one
h.ts = s.time() + 100;
assert_eq!(h.send("POST", &path, &body).status, 200);
h.ts = s.time() + 50;
@@ -145,17 +160,18 @@ fn authentication(s: &TestServer) {
h.ts = s.time() + 101;
assert_eq!(h.send("POST", &path, &body).status, 200, "later ones are accepted again");
// protocol version in the header and in the body
h.ts += 1;
let mut headers = sign_request(&h.key, "POST", &path, &h.realm, h.ts, &body).pairs();
headers[0] = (HEADER_VERSION, "2".into());
let r = h.send_with("POST", &path, &body, &headers);
// protocol version in the header and in the body (version 1 is refused like any other)
for wrong in ["1", "3"] {
h.ts += 1;
let mut headers = sign_request(&h.key, "POST", &path, &h.realm, h.ts, &body).pairs();
headers[0] = (HEADER_VERSION, wrong.into());
let r = h.send_with("POST", &path, &body, &headers);
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"), "header {wrong}");
}
let mut v1 = h.heartbeat_body(60, false);
v1.protocol_version = 1;
let r = h.send("POST", &path, &serde_json::to_vec(&v1).unwrap());
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"));
let mut v2 = h.heartbeat_body(60, false);
v2.protocol_version = 2;
let r = h.send("POST", &path, &serde_json::to_vec(&v2).unwrap());
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"));
// missing or garbled headers
let r = h.send_with("POST", &path, &body, &[]);
assert_eq!(r.status, 400);
let mut bad = sign_request(&h.key, "POST", &path, &h.realm, h.ts + 1, &body).pairs();
@@ -166,67 +182,91 @@ fn authentication(s: &TestServer) {
assert_eq!(h.send_with("POST", &path, &body, &bad).status, 400);
}
/// The one documented policy for protocol 1: it is refused, explicitly, on every endpoint, and nothing is stored or silently migrated.
fn old_protocol_is_refused(s: &TestServer) {
let mut h = Host::new(s, 11);
for (method, path) in [("POST", "/registry/v1/realms/register"), ("POST", &*format!("/registry/v1/realms/{}/heartbeat", h.realm)), ("POST", &*format!("/registry/v1/realms/{}/unpublish", h.realm)), ("GET", &*format!("/registry/v1/realms/{}", h.realm)), ("GET", "/registry/v1/healthz"), ("GET", "/registry/v1")] {
let r = h.send(method, path, if method == "GET" { b"" } else { br#"{"protocol_version":1}"# });
assert_eq!((r.status, r.code().as_str()), (400, "unsupported_protocol_version"), "{method} {path}: {:?}", r.body);
assert!(r.body["error"]["message"].as_str().unwrap().contains("protocol version 1 is no longer supported"));
}
let mut check = Host::new(s, 11);
check.realm = h.realm;
check.ts = h.ts + 10;
assert_eq!(check.me().status, 404, "a refused v1 request created nothing");
}
/// 11: hostile input is refused safely and stores nothing.
fn hostile_input(s: &TestServer) {
let mut h = Host::new(s, 7);
// oversized
let big = vec![b'x'; MAX_REQUEST_BYTES + 1];
let r = h.send("POST", PATH_REGISTER, &big);
assert_eq!((r.status, r.code().as_str()), (413, "request_too_large"));
// not JSON, not an object, deeply nested
for body in [b"not json".as_slice(), b"[]", b"null", &b"{\"a\":".repeat(1)] {
let r = h.send("POST", PATH_REGISTER, body);
assert_eq!(r.status, 400, "{:?}", String::from_utf8_lossy(body));
}
let nested = format!("{}1{}", "[".repeat(30_000), "]".repeat(30_000));
assert_eq!(h.send("POST", PATH_REGISTER, nested.as_bytes()).status, 400);
// metadata outside its limits, one at a time
let base = serde_json::to_value(h.register_body("Hostile", 60)).unwrap();
let cases: Vec<(&str, serde_json::Value)> = vec![
("display_name", json!("x".repeat(81))),
("display_name", json!("")),
("display_name", json!("evil\u{202E}name")),
("display_name", json!("new\nline")),
("description", json!("d".repeat(1025))),
("language", json!("<script>")),
("manager_version", json!("1.0 <b>")),
("player_count", json!(1_000_000)),
("capabilities_hash", json!("0".repeat(64))),
("public_key", json!("short")),
("ruleset", json!("wildcard")),
let cases: Vec<(Vec<&str>, serde_json::Value)> = vec![
(vec!["listing", "display_name"], json!("x".repeat(81))),
(vec!["listing", "display_name"], json!("")),
(vec!["listing", "display_name"], json!("evil\u{202E}name")),
(vec!["listing", "display_name"], json!("new\nline")),
(vec!["listing", "description"], json!("d".repeat(1025))),
(vec!["listing", "language"], json!("<script>")),
(vec!["listing", "region"], json!("<img src=x>")),
(vec!["listing", "manager_version"], json!("1.0 <b>")),
(vec!["listing", "rates", "xp_kill"], json!(-1.0)),
(vec!["listing", "rates", "loot"], json!(1.0e9)),
(vec!["listing", "modules"], json!([{"id": "<script>alert(1)</script>", "enabled": true}])),
(vec!["listing", "modules"], json!([{"id": "a", "enabled": true}, {"id": "a", "enabled": false}])),
(vec!["listing", "modules"], json!((0..65).map(|i| json!({"id": format!("m{i}"), "enabled": true})).collect::<Vec<_>>())),
(vec!["listing", "modules"], json!([{"id": "ok", "version": "v <1>", "enabled": true}])),
(vec!["listing", "account_provisioning"], json!({"automatic": false, "existing_only": false})),
(vec!["population", "players"], json!(1_000_000)),
(vec!["population", "bots"], json!(-5)),
(vec!["listing_hash"], json!("0".repeat(64))),
(vec!["capabilities_hash"], json!("0".repeat(64))),
(vec!["public_key"], json!("short")),
];
for (field, value) in cases {
for (path, value) in cases {
let mut v = base.clone();
v[field] = value;
let mut at = &mut v;
for key in &path[..path.len() - 1] {
at = &mut at[*key];
}
at[path[path.len() - 1]] = value;
let r = h.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap());
assert!(r.status == 400, "{field}: {} {:?}", r.status, r.body);
assert!(r.status == 400, "{path:?}: {} {:?}", r.status, r.body);
}
// what the protocol has no place for is not accepted, whatever it is
for extra in ["character", "snapshot", "password", "ra_password", "db_credentials", "canonical_revision"] {
for extra in ["character", "snapshot", "password", "ra_password", "db_credentials", "canonical_revision", "ruleset", "level_cap", "game_mode", "ping"] {
let mut v = base.clone();
v[extra] = json!("secret");
let r = h.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap());
assert_eq!((r.status, r.code().as_str()), (400, "malformed_request"), "{extra}");
}
let mut v = base.clone();
v["listing"]["rates"]["ping"] = json!(5.0);
assert_eq!(h.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap()).status, 400, "no unknown rate");
let mut v = base.clone();
v["capabilities"]["content"]["client_catalog"]["../../etc/passwd"] = json!({"sha256": "a".repeat(64), "records": 1});
assert_eq!(h.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap()).status, 400, "capabilities are checked field by field");
let mut v = base.clone();
v["capabilities"]["notes"] = json!("free text to store");
assert_eq!(h.send("POST", PATH_REGISTER, &serde_json::to_vec(&v).unwrap()).status, 400, "no free-form storage in the capabilities");
// ids and paths
let mut other = Host::new(s, 7);
other.ts = h.ts;
let r = h.send("GET", "/registry/v1/realms/not-a-uuid", b"");
let r = h.send("GET", "/registry/v2/realms/not-a-uuid/self", b"");
assert_eq!(r.status, 400);
let path = format!("/registry/v1/realms/{}", other.realm.to_string().to_uppercase());
let path = format!("/registry/v2/realms/{}/self", other.realm.to_string().to_uppercase());
assert_eq!(h.send("GET", &path, b"").status, 400, "upper case is not the canonical spelling");
assert_eq!(h.send("GET", &format!("{}?x=1", path_self(&h.realm)), b"").status, 400, "no query on a signed endpoint");
let r = h.send("GET", &path_self(&other.realm), b"");
assert_eq!(r.status, 400, "the realm header names another realm than the path");
let r = h.send("GET", "/registry/v1/realms/018f2d9e-5c3a-4b21-8c4d-0e5f6a7b8c9d", b"");
let r = h.send("GET", "/registry/v2/realms/018f2d9e-5c3a-4b21-8c4d-0e5f6a7b8c9d/self", b"");
assert_eq!(r.status, 400, "a version-4 UUID is not a realm id");
// nothing was stored by any of it
let mut clean = Host::new(s, 7);
clean.realm = h.realm;
clean.ts = h.ts + 100;
@@ -257,11 +297,11 @@ fn unpublishing(s: &TestServer) {
}
fn healthz(s: &TestServer) {
let r = reqwest::blocking::get(format!("{}/registry/v1/healthz", s.base)).unwrap();
let r = reqwest::blocking::get(format!("{}/registry/v2/healthz", s.base)).unwrap();
assert_eq!(r.status(), 200);
let v: serde_json::Value = r.json().unwrap();
assert_eq!((v["status"].as_str(), v["protocol_version"].as_u64()), (Some("ok"), Some(1)));
assert_eq!(reqwest::blocking::get(format!("{}/registry/v1/realms", s.base)).unwrap().status(), 404, "there is no public list");
assert_eq!((v["status"].as_str(), v["protocol_version"].as_u64()), (Some("ok"), Some(2)));
assert_eq!(reqwest::blocking::get(format!("{}/registry/v2/nothing", s.base)).unwrap().status(), 404);
assert_eq!(reqwest::blocking::get(format!("{}/admin", s.base)).unwrap().status(), 404, "and no admin surface");
}
@@ -272,6 +312,7 @@ fn all(s: &TestServer) {
metadata_changes(s);
takeover(s);
authentication(s);
old_protocol_is_refused(s);
hostile_input(s);
unpublishing(s);
}
@@ -281,6 +322,57 @@ fn the_protocol_on_the_memory_store() {
all(&memory());
}
/// A record left by protocol 1 keeps its identity, key and creation time when its Host republishes under protocol 2.
#[test]
fn a_protocol_1_record_is_upgraded_in_place() {
let store = std::sync::Arc::new(MemoryStore::new());
let s = spawn(store.clone(), lax());
let mut h = Host::new(&s, 60);
let caps = caps(60);
let created = START - 86_400;
let old = RealmRow {
realm_id: h.realm,
public_key: *h.key.verifying_key().as_bytes(),
created_at: created,
updated_at: created,
last_seen_at: created,
published: true,
listing: Listing { display_name: "Old realm".into(), description: "from protocol 1".into(), language: "en".into(), region: None, rates: Rates::default(), modules: vec![], account_provisioning: AccountProvisioning { automatic: false, existing_only: true }, manager_version: "0.6.6".into() },
listing_hash: "f".repeat(64),
ruleset: Ruleset::Coa,
level_cap: Some(60),
capabilities: caps.clone(),
capabilities_hash: caps.advert_hash(),
population: Population::default(),
metadata_revision: 5,
last_request_ts: s.time() - 1000,
advert_version: 1,
};
store.put_for_test(old);
// a heartbeat of the new protocol with only a hash cannot upgrade it: the listing is asked for
h.ts = s.time();
h.name = "Old realm".into();
let r = h.heartbeat(60, false);
assert_eq!((r.status, r.body["resend_listing"].as_bool()), (200, Some(true)), "{:?}", r.body);
assert_eq!(store.get_for_test(&h.realm).unwrap().advert_version, 1, "nothing was applied");
let body = h.heartbeat_with_listing(60, "Old realm");
let path = path_heartbeat(&h.realm);
let r = h.send("POST", &path, &serde_json::to_vec(&body).unwrap());
assert_eq!((r.status, r.body["resend_listing"].as_bool(), r.body["metadata_revision"].as_u64()), (200, Some(false), Some(6)), "{:?}", r.body);
let row = store.get_for_test(&h.realm).unwrap();
assert_eq!((row.advert_version, ADVERT_VERSION, row.created_at, row.public_key), (2, 2, created, *h.key.verifying_key().as_bytes()), "identity, key and creation time are kept");
assert_eq!(row.listing.rates.xp_kill, Some(2.0));
// and the other way: registering again as itself
let mut h2 = Host::new(&s, 61);
let old2 = RealmRow { realm_id: h2.realm, public_key: *h2.key.verifying_key().as_bytes(), advert_version: 1, last_request_ts: s.time() - 1000, ..store.get_for_test(&h.realm).unwrap() };
store.put_for_test(old2);
h2.ts = s.time();
let r = h2.register("Republished", 60);
assert_eq!((r.status, r.body["created"].as_bool(), r.body["metadata_revision"].as_u64()), (200, Some(false), Some(7)), "{:?}", r.body);
assert_eq!(store.get_for_test(&h2.realm).unwrap().created_at, created);
}
#[test]
fn a_flood_is_limited() {
let cfg = ApiConfig { register: Rate { burst: 3.0, refill: 0.0 }, heartbeat: Rate { burst: 2.0, refill: 0.0 }, general: Rate { burst: 1000.0, refill: 0.0 }, ..ApiConfig::default() };
@@ -305,7 +397,6 @@ fn a_flood_is_limited() {
assert_eq!(other.register("Other", 60).status, 200);
assert_eq!(other.heartbeat(60, false).status, 200, "another realm has its own allowance");
// forged requests cost their sender, and never the realm they pretend to be
let s = spawn(MemoryStore::new(), ApiConfig { general: Rate { burst: 12.0, refill: 0.0 }, heartbeat: Rate { burst: 2.0, refill: 0.0 }, ..ApiConfig::default() });
let mut victim = Host::new(&s, 40);
assert_eq!(victim.register("Victim", 60).status, 200);
@@ -318,7 +409,6 @@ fn a_flood_is_limited() {
}
assert_eq!(&statuses[..2], &[401, 401]);
assert_eq!(*statuses.last().unwrap(), 429, "the forger runs out of allowance: {statuses:?}");
// the victim's own per-realm allowance was never spent by the forgeries (its address allowance may be, which is the forger's address too here)
}
#[test]
+38 -15
View File
@@ -82,6 +82,8 @@ pub struct Host {
pub key: SigningKey,
pub realm: RealmId,
pub ts: i64,
/// The display name the next heartbeats advertise.
pub name: String,
http: reqwest::blocking::Client,
}
@@ -102,7 +104,7 @@ impl Reply {
impl Host {
pub fn new(server: &TestServer, seed: u8) -> Self {
Self { base: server.base.clone(), key: SigningKey::from_bytes(&[seed; 32]), realm: RealmId::new(), ts: server.time(), http: reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(10)).build().unwrap() }
Self { base: server.base.clone(), key: SigningKey::from_bytes(&[seed; 32]), realm: RealmId::new(), ts: server.time(), name: "Test realm".into(), http: reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(10)).build().unwrap() }
}
/// A client for a Registry that is not in this process (a real node): a random key, the real clock.
@@ -111,7 +113,7 @@ impl Host {
seed[..16].copy_from_slice(uuid_bytes().as_slice());
seed[16..].copy_from_slice(uuid_bytes().as_slice());
let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64;
Self { base: base.trim_end_matches('/').to_string(), key: SigningKey::from_bytes(&seed), realm: RealmId::new(), ts, http: reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(20)).build().unwrap() }
Self { base: base.trim_end_matches('/').to_string(), key: SigningKey::from_bytes(&seed), realm: RealmId::new(), ts, name: "Test realm".into(), http: reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(20)).build().unwrap() }
}
/// Bring the timestamp up to the real clock (after a pause); it never goes backwards.
@@ -120,27 +122,47 @@ impl Host {
self.ts = self.ts.max(now);
}
pub fn register_body(&self, name: &str, level: u32) -> RegisterRequest {
let capabilities = caps(level);
RegisterRequest {
protocol_version: 1,
realm_id: self.realm,
public_key: encode_public_key(&self.key.verifying_key()),
pub fn listing(&self, name: &str) -> Listing {
Listing {
display_name: name.into(),
description: "A test realm.".into(),
language: "en".into(),
ruleset: Ruleset::Coa,
region: Some("EU".into()),
rates: Rates { xp_kill: Some(2.0), xp_quest: Some(2.0), xp_explore: None, loot: Some(1.0), money: Some(1.5), reputation: None, honor: Some(1.0) },
modules: vec![ModuleEntry { id: "playerbots".into(), version: Some("1.4.2".into()), enabled: true }, ModuleEntry { id: "content-scaling".into(), version: None, enabled: false }],
account_provisioning: AccountProvisioning { automatic: true, existing_only: false },
manager_version: "0.6.6".into(),
capabilities_hash: capabilities.advert_hash(),
capabilities,
player_count: Some(1),
player_capacity: Some(50),
}
}
pub fn register_body(&self, name: &str, level: u32) -> RegisterRequest {
let capabilities = caps(level);
let listing = self.listing(name);
RegisterRequest {
protocol_version: 2,
realm_id: self.realm,
public_key: encode_public_key(&self.key.verifying_key()),
listing_hash: listing.hash(),
listing,
capabilities_hash: capabilities.advert_hash(),
capabilities,
population: Population { players: 1, bots: 4, capacity: Some(50) },
}
}
/// A heartbeat of the realm as `register` described it, with the capabilities of `level` (and their hash) and optionally the parts themselves.
pub fn heartbeat_body(&self, level: u32, with_caps: bool) -> HeartbeatRequest {
let capabilities = caps(level);
HeartbeatRequest { protocol_version: 1, capabilities_hash: capabilities.advert_hash(), capabilities: with_caps.then_some(capabilities), manager_version: None, player_count: Some(2), player_capacity: Some(50), display_name: None, description: None, language: None }
let listing = self.listing(&self.name);
HeartbeatRequest { protocol_version: 2, listing_hash: listing.hash(), listing: None, capabilities_hash: capabilities.advert_hash(), capabilities: with_caps.then_some(capabilities), population: Population { players: 2, bots: 4, capacity: Some(50) } }
}
pub fn heartbeat_with_listing(&self, level: u32, name: &str) -> HeartbeatRequest {
let mut hb = self.heartbeat_body(level, false);
let listing = self.listing(name);
hb.listing_hash = listing.hash();
hb.listing = Some(listing);
hb
}
/// A fully signed request; the timestamp advances by one for every call.
@@ -166,6 +188,7 @@ impl Host {
}
pub fn register(&mut self, name: &str, level: u32) -> Reply {
self.name = name.into();
let body = serde_json::to_vec(&self.register_body(name, level)).unwrap();
self.send("POST", PATH_REGISTER, &body)
}
@@ -177,7 +200,7 @@ impl Host {
}
pub fn unpublish(&mut self) -> Reply {
let body = serde_json::to_vec(&UnpublishRequest { protocol_version: 1 }).unwrap();
let body = serde_json::to_vec(&UnpublishRequest { protocol_version: 2 }).unwrap();
let path = path_unpublish(&self.realm);
self.send("POST", &path, &body)
}