Integrate isolated rulesets, portable admission, and compatible relay authentication

This commit is contained in:
Дмитрий committed 2026-10-24 06:04:26 +05:00
commit d5f1e9cc83
112 files changed
+5892 -965

No files matched your search

+3 -2
View File
@@ -456,8 +456,9 @@ mod tests {
ruleset: Ruleset::Coa,
character_formats: ContentProfile::manager_formats(),
online_import_job_formats: jobs.to_vec(),
session_protocol: 2,
collection_protocol: 2,
session_protocol: crate::portable::session::protocol::SESSION_PROTOCOL_VERSION,
collection_protocol:
crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
features: features.iter().copied().collect(),
collection_kinds: ["coa:appearance".to_string(), "coa:vanity".to_string()]
.into_iter()
+5
View File
@@ -64,6 +64,11 @@ pub enum PortableError {
RealmRead(String),
#[error("the realm database is a {found} realm but a {expected} character was requested")]
WrongRealm { expected: String, found: String },
#[error("ruleset mismatch: character has {character:?}, realm expects {realm:?}")]
RulesetMismatch {
character: super::model::Ruleset,
realm: super::model::Ruleset,
},
#[error("character {character} is already on server {server_id}")]
AlreadyOnRealm {
@@ -0,0 +1,26 @@
-- 2. Upgrade character table to allow 'reborn' in CHECK (ruleset IN ('coa', 'wildcard', 'reborn'))
-- Foreign keys are off during migration runner, but legacy child tables remain valid because primary keys are untouched.
CREATE TABLE character_new (
character_id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
name TEXT NOT NULL,
race TEXT NOT NULL,
class TEXT NOT NULL,
gender INTEGER NOT NULL,
level INTEGER NOT NULL,
revision INTEGER NOT NULL CHECK (revision >= 1),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1))
) STRICT;
INSERT INTO character_new (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
SELECT character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived
FROM character;
DROP TABLE character;
ALTER TABLE character_new RENAME TO character;
CREATE INDEX character_profile ON character(profile_id);
CREATE INDEX character_profile_ruleset ON character(profile_id, ruleset);
+2 -2
View File
@@ -23,8 +23,8 @@ pub mod snapshot;
pub mod store;
pub mod versions;
#[cfg(test)]
pub(crate) mod fixtures;
#[cfg(any(test, feature = "testkit"))]
pub mod fixtures;
pub use collection::IdSet;
pub use error::{PortableError, Result};
+96 -1
View File
@@ -59,12 +59,13 @@ pub mod limits {
use limits::*;
/// A character belongs to exactly one ruleset for its whole life; CoA and Wildcard never mix.
/// A character belongs to exactly one ruleset for its whole life; rulesets never mix.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Ruleset {
Coa,
Wildcard,
Reborn,
}
impl Ruleset {
@@ -72,23 +73,99 @@ impl Ruleset {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn display_name(self) -> &'static str {
match self {
Ruleset::Coa => "Conquest of Azeroth",
Ruleset::Wildcard => "Wildcard",
Ruleset::Reborn => "Warcraft Reborn",
}
}
pub fn realm_id(self) -> u32 {
match self {
Ruleset::Coa => 1,
Ruleset::Wildcard => 2,
Ruleset::Reborn => 3,
}
}
pub fn schema(self, kind: &str) -> Result<&'static str> {
let mode: crate::realms::Mode = self.into();
mode.schema(kind)
.map_err(|e| PortableError::Invalid(e.to_string()))
}
pub fn collection_namespace(self) -> &'static str {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn parse(s: &str) -> Result<Self> {
match s {
"coa" => Ok(Ruleset::Coa),
"wildcard" => Ok(Ruleset::Wildcard),
"reborn" => Ok(Ruleset::Reborn),
other => Err(PortableError::Invalid(format!("unknown ruleset {other:?}"))),
}
}
}
impl std::str::FromStr for Ruleset {
type Err = PortableError;
fn from_str(s: &str) -> Result<Self> {
Self::parse(s)
}
}
impl std::fmt::Display for Ruleset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl From<crate::realms::Mode> for Ruleset {
fn from(m: crate::realms::Mode) -> Self {
match m {
crate::realms::Mode::Coa => Ruleset::Coa,
crate::realms::Mode::Wildcard => Ruleset::Wildcard,
crate::realms::Mode::Reborn => Ruleset::Reborn,
}
}
}
impl From<Ruleset> for crate::realms::Mode {
fn from(r: Ruleset) -> Self {
match r {
Ruleset::Coa => crate::realms::Mode::Coa,
Ruleset::Wildcard => crate::realms::Mode::Wildcard,
Ruleset::Reborn => crate::realms::Mode::Reborn,
}
}
}
impl From<coa_registry_proto::caps::Ruleset> for Ruleset {
fn from(r: coa_registry_proto::caps::Ruleset) -> Self {
match r {
coa_registry_proto::caps::Ruleset::Coa => Ruleset::Coa,
coa_registry_proto::caps::Ruleset::Wildcard => Ruleset::Wildcard,
coa_registry_proto::caps::Ruleset::Reborn => Ruleset::Reborn,
}
}
}
impl From<Ruleset> for coa_registry_proto::caps::Ruleset {
fn from(r: Ruleset) -> Self {
match r {
Ruleset::Coa => coa_registry_proto::caps::Ruleset::Coa,
Ruleset::Wildcard => coa_registry_proto::caps::Ruleset::Wildcard,
Ruleset::Reborn => coa_registry_proto::caps::Ruleset::Reborn,
}
}
}
/// Binary data as base64 text in the serialised form.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct Bytes(pub Vec<u8>);
@@ -806,3 +883,21 @@ impl PortableCharacter {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_mapping_never_falls_back_on_unknown_database_kind() {
for ruleset in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] {
assert!(ruleset.schema("auth").is_ok());
assert!(ruleset.schema("characters").is_ok());
assert!(ruleset.schema("world").is_ok());
assert!(ruleset.schema("characters_extra").is_err());
assert!(ruleset.schema("unknown").is_err());
assert!(ruleset.schema("").is_err());
assert!(ruleset.schema("acore_characters").is_err());
}
}
}
@@ -11,7 +11,6 @@ use crate::db::Db;
use super::super::collection::IdSet;
use super::super::error::{PortableError, Result};
use super::super::model::Ruleset;
use super::knowledge::{is_bank_vanity_item, RealmKnowledge};
use super::plan::FAIL;
use super::ruleset_of;
@@ -22,8 +21,12 @@ const CHUNK: usize = 2_000;
/// `(table, id column, columns written)` of a collection kind.
fn layout(kind: &str) -> Result<(&'static str, &'static str, bool)> {
match kind {
"coa:appearance" => Ok(("account_appearance_collection", "appearance_id", true)),
"coa:vanity" => Ok(("account_vanity_collection", "item_id", false)),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(("account_appearance_collection", "appearance_id", true))
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => {
Ok(("account_vanity_collection", "item_id", false))
}
other => Err(PortableError::Invalid(format!(
"collection kind {other:?} is not carried"
))),
@@ -34,11 +37,12 @@ fn realm_error(e: crate::Error) -> PortableError {
PortableError::RealmRead(e.to_string())
}
fn coa_only(db: &Db) -> Result<()> {
if ruleset_of(db)? != Ruleset::Coa {
return Err(PortableError::Invalid(
"collections are carried for CoA realms only (Wildcard transfer is disabled)".into(),
));
fn check_ruleset(db: &Db, kind: &str) -> Result<()> {
let r = ruleset_of(db)?;
if !crate::portable::session::protocol::carried_kind_for(kind, r) {
return Err(PortableError::Invalid(format!(
"collection kind {kind:?} does not belong to realm ruleset {r:?}"
)));
}
Ok(())
}
@@ -62,7 +66,7 @@ pub fn account_of(db: &Db, local_guid: u32) -> Result<Option<u32>> {
/// Count, maximum, sum and checksum of the account's rows of this kind: one cheap aggregate over the primary key.
pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
coa_only(db)?;
check_ruleset(db, kind)?;
let (table, column, _) = layout(kind)?;
let out = db
.query(&format!("SELECT COUNT(*), IFNULL(MAX(`{column}`), 0), IFNULL(SUM(`{column}`), 0), IFNULL(BIT_XOR(CRC32(`{column}`)), 0) FROM acore_characters.`{table}` WHERE `account_id` = {account}"))
@@ -82,7 +86,7 @@ pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result<String> {
/// The ids of the account in this realm, without the bank vanity items.
pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
coa_only(db)?;
check_ruleset(db, kind)?;
let (table, column, _) = layout(kind)?;
let out = db.query(&format!("SELECT `{column}` FROM acore_characters.`{table}` WHERE `account_id` = {account} ORDER BY `{column}`")).map_err(realm_error)?;
let mut ids = Vec::new();
@@ -91,7 +95,9 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
.trim()
.parse()
.map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?;
if kind == "coa:vanity" && is_bank_vanity_item(id) {
if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity")
&& is_bank_vanity_item(id)
{
continue;
}
ids.push(id);
@@ -117,21 +123,21 @@ pub fn apply_set(
canonical: &IdSet,
knowledge: &RealmKnowledge,
) -> Result<Applied> {
coa_only(db)?;
check_ruleset(db, kind)?;
let (table, column, has_source) = layout(kind)?;
let known = |id: u32| match kind {
"coa:appearance" => knowledge.knows_appearance(id),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
knowledge.knows_appearance(id)
}
_ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id),
};
let held = read_set(db, account, kind)?;
let mut applied = Applied::default();
let mut wanted = Vec::new();
for id in canonical
.ids()
.iter()
.copied()
.filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id)))
{
for id in canonical.ids().iter().copied().filter(|id| {
!((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity")
&& is_bank_vanity_item(*id))
}) {
if !known(id) {
applied.unknown += 1;
} else if held.contains(id) {
@@ -168,9 +168,11 @@ fn account_collections_are_read_cheaply_unioned_and_written_without_duplicates_o
let (mut store, _) = fresh_store();
let profile = store.default_profile().unwrap();
store
.merge_collection(profile, APPEARANCE, &wardrobe)
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &wardrobe)
.unwrap();
store
.merge_collection(profile, Ruleset::Coa, VANITY, &vanity)
.unwrap();
store.merge_collection(profile, VANITY, &vanity).unwrap();
let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap();
assert_eq!(
fingerprint(&r.a, 5001, APPEARANCE).unwrap(),
@@ -331,10 +333,20 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
reconcile_session(&r.b, &mut store, id, B, true, None).unwrap();
for kind in [APPEARANCE, VANITY] {
store
.merge_collection(profile, kind, &read_set(&r.b, ACCOUNT, kind).unwrap())
.merge_collection(
profile,
Ruleset::Coa,
kind,
&read_set(&r.b, ACCOUNT, kind).unwrap(),
)
.unwrap();
store
.merge_collection(profile, kind, &read_set(&r.a, 5001, kind).unwrap())
.merge_collection(
profile,
Ruleset::Coa,
kind,
&read_set(&r.a, 5001, kind).unwrap(),
)
.unwrap();
}
@@ -343,7 +355,10 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections(
let updated =
update_realm_character(&r.a, &mut store, id, "realm-a", &options(a_known.clone())).unwrap();
assert!(updated.updated, "{updated:?}");
let (_, canonical_wardrobe) = store.collection(profile, APPEARANCE).unwrap().unwrap();
let (_, canonical_wardrobe) = store
.collection(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap();
let applied = apply_set(&r.a, 5001, APPEARANCE, &canonical_wardrobe, &a_known).unwrap();
assert_eq!(applied.inserted, 1, "only 1300 is new to A");
assert_eq!(
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn ruleset_of(db: &Db) -> Result<Ruleset> {
match db.realm() {
Mode::Coa => Ok(Ruleset::Coa),
Mode::Wildcard => Ok(Ruleset::Wildcard),
Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())),
Mode::Reborn => Ok(Ruleset::Reborn),
}
}
@@ -14,7 +14,9 @@ use super::super::extension::{
};
use super::super::ids::CharacterId;
use super::super::model::PortableCharacter;
use super::super::session::protocol::{COLLECTION_KINDS, PROTOCOL_VERSION};
use super::super::session::protocol::{
collection_kinds, COLLECTION_PROTOCOL_VERSION, SESSION_PROTOCOL_VERSION,
};
use super::super::store::Store;
use super::import::ImportOptions;
use super::script::SchemaProbe;
@@ -97,13 +99,16 @@ pub fn assemble(
online_import_job_formats: core
.map(|c| c.portable.job_formats.clone())
.unwrap_or_default(),
session_protocol: PROTOCOL_VERSION,
collection_protocol: PROTOCOL_VERSION,
session_protocol: SESSION_PROTOCOL_VERSION,
collection_protocol: COLLECTION_PROTOCOL_VERSION,
features,
collection_kinds: if probe.has("account_appearance_collection")
&& probe.has("account_vanity_collection")
{
COLLECTION_KINDS.iter().map(|k| k.to_string()).collect()
collection_kinds(ruleset_of(db)?)
.iter()
.map(|k| k.to_string())
.collect()
} else {
Default::default()
},
+1 -1
View File
@@ -729,7 +729,7 @@ fn the_wildcard_ruleset_uses_its_own_namespace_and_quarantines_wildcard_state()
let wc_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Wildcard);
let coa_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Coa);
let reborn_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Reborn);
assert!(ruleset_of(&reborn_db).is_err());
assert_eq!(ruleset_of(&reborn_db).unwrap(), Ruleset::Reborn);
assert_eq!(
(ruleset_of(&wc_db).unwrap(), ruleset_of(&coa_db).unwrap()),
(Ruleset::Wildcard, Ruleset::Coa)
+11 -2
View File
@@ -112,6 +112,7 @@ pub struct RealmAccess {
pub job_dir: PathBuf,
pub data_dir: PathBuf,
pub game_server_users: Vec<String>,
pub mode: Option<crate::realms::Mode>,
source: Source,
}
@@ -198,6 +199,7 @@ impl RealmAccess {
job_dir: PathBuf::from(&d.job_dir),
data_dir: PathBuf::from(&d.data_dir),
game_server_users: d.game_server_users.clone(),
mode: None,
source: Source::Descriptor(Box::new(d)),
})
}
@@ -219,6 +221,7 @@ impl RealmAccess {
job_dir: root.join("Core").join("PortableImport"),
data_dir: root.join("Data"),
game_server_users: default_game_users(),
mode: None,
source: Source::Install {
root: root.to_path_buf(),
},
@@ -228,13 +231,19 @@ impl RealmAccess {
/// The database with full rights (imports and updates of a stopped realm, reading characters).
pub fn db(&self) -> Result<Db> {
match &self.source {
Source::Install { root } => Db::from_repack(root, Account::Admin),
Source::Install { root } => {
let mut d = Db::from_repack(root, Account::Admin)?;
if let Some(m) = self.mode {
d = d.for_realm(m);
}
Ok(d)
}
Source::Descriptor(d) => Ok(Db::with_tools(
PathBuf::from(&d.mysql_bin),
d.db_port,
leak(&d.db_user),
d.db_password.expose(),
Mode::Coa,
self.mode.unwrap_or(Mode::Coa),
)),
}
}
+92 -27
View File
@@ -136,6 +136,7 @@ struct Saved {
#[derive(Debug, Clone)]
pub struct ClaimBundle {
pub character_id: CharacterId,
pub ruleset: super::super::model::Ruleset,
pub payload: Vec<u8>,
pub content_hash: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>,
@@ -181,6 +182,16 @@ pub fn class_name(class: &str) -> String {
.and_then(|n| n.parse().ok())
.unwrap_or(0);
match id {
1 => "Warrior",
2 => "Paladin",
3 => "Hunter",
4 => "Rogue",
5 => "Priest",
6 => "Death Knight",
7 => "Shaman",
8 => "Mage",
9 => "Warlock",
11 => "Druid",
12 => "Barbarian",
13 => "Witch Doctor",
14 => "Felsworn",
@@ -363,11 +374,26 @@ impl PortableService {
pub fn reload_realms(&mut self) {
let (descriptors, broken) = access::load_descriptors(&self.dir.join("realms"));
self.broken_descriptors = broken;
let mut realms: Vec<RealmAccess> = self
.installs
.iter()
.map(|(id, root)| RealmAccess::from_install(id, root))
.collect();
let mut realms: Vec<RealmAccess> = Vec::new();
for (id, root) in &self.installs {
realms.push(RealmAccess::from_install(id, root));
if let Ok(state) = crate::realms::state(root) {
if state.wildcard_created {
let mut wc = RealmAccess::from_install(id, root);
wc.id = format!("srv-{id}:wildcard");
wc.name = format!("{} — Wildcard", wc.name);
wc.mode = Some(crate::realms::Mode::Wildcard);
realms.push(wc);
}
if state.reborn_created {
let mut rb = RealmAccess::from_install(id, root);
rb.id = format!("srv-{id}:reborn");
rb.name = format!("{} — Warcraft Reborn", rb.name);
rb.mode = Some(crate::realms::Mode::Reborn);
realms.push(rb);
}
}
}
for d in descriptors {
match RealmAccess::from_descriptor(d) {
Ok(a) if !realms.iter().any(|r| r.id == a.id) => realms.push(a),
@@ -414,10 +440,10 @@ impl PortableService {
}
fn access(&self, id: &str) -> Res<RealmAccess> {
self.realms
.iter()
.find(|r| r.id == id)
.cloned()
if let Some(r) = self.realms.iter().find(|r| r.id == id) {
return Ok(r.clone());
}
crate::realm_registry::advert::find_access(&self.dir.join("realms"), &self.installs, id)
.ok_or_else(|| fail("realm_missing", "That realm is not known to this Manager."))
}
@@ -728,6 +754,7 @@ impl PortableService {
characters.push(CharacterView {
id: c.character_id.to_string(),
name: c.name,
ruleset: c.ruleset,
class_name: class_name(&c.class),
race: c.race,
level: c.level,
@@ -1356,6 +1383,7 @@ impl PortableService {
.map_err(|e| fail("realm_offline", e.to_string()))?;
let list =
realm::inspect_characters(&db).map_err(|e| fail("realm_offline", e.to_string()))?;
let realm_ruleset = realm::ruleset_of(&db)?;
let mut out = Vec::new();
for c in list {
if self.host.find_by_local(realm_id, c.local_guid)?.is_some() {
@@ -1364,7 +1392,7 @@ impl PortableService {
out.push(LocalCharacterView {
token: c.local_guid,
name: c.name.clone(),
class_name: class_name(&format!("coa:class:{}", c.class)),
class_name: class_name(&format!("{}:class:{}", realm_ruleset.as_str(), c.class)),
level: c.level,
account: c.username.clone().unwrap_or_default(),
eligible: c.eligible(),
@@ -1438,18 +1466,18 @@ impl PortableService {
let model = self.host.load_current(character_id)?;
let encoded = super::super::snapshot::encode(&model)?;
let mut collections = BTreeMap::new();
if realm::ruleset_of(&db)? == super::super::model::Ruleset::Coa {
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
for kind in ["coa:appearance", "coa:vanity"] {
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
collections.insert(kind.to_string(), set.ids().to_vec());
}
let realm_ruleset = realm::ruleset_of(&db)?;
if let Some(account) = realm::collections::account_of(&db, local_guid)? {
for kind in super::super::session::protocol::collection_kinds(realm_ruleset) {
if let Ok(set) = realm::collections::read_set(&db, account, kind) {
collections.insert(kind.to_string(), set.ids().to_vec());
}
}
}
self.publish();
Ok(ClaimBundle {
character_id,
ruleset: model.ruleset,
payload: encoded.payload,
content_hash: encoded.content_hash,
collections,
@@ -1473,17 +1501,25 @@ impl PortableService {
"The character data does not belong to the character that was claimed.",
));
}
let ruleset = model.ruleset;
for kind in collections.keys() {
if !super::super::session::protocol::carried_kind_for(kind, ruleset) {
return Err(fail(
"incompatible",
format!("Foreign collection kind {kind:?} in {ruleset} claim"),
));
}
}
if self.owner.character(character_id).is_err() {
self.owner
.create_character_with_id(self.owner_profile, model, realm_id)?;
}
for (kind, ids) in collections {
if !matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
continue;
if super::super::session::protocol::carried_kind_for(kind, ruleset) {
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
self.owner
.merge_collection(self.owner_profile, ruleset, kind, &set)?;
}
let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?;
self.owner
.merge_collection(self.owner_profile, kind, &set)?;
}
self.publish();
self.state()
@@ -1499,13 +1535,17 @@ impl PortableService {
let model = self.owner.load_current(cid)?;
let encoded = super::super::snapshot::encode(&model)?;
let mut collections = BTreeMap::new();
for kind in ["coa:appearance", "coa:vanity"] {
if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, kind) {
for kind in super::super::session::protocol::collection_kinds(model.ruleset) {
if let Ok(Some((_, set))) =
self.owner
.collection(self.owner_profile, model.ruleset, kind)
{
collections.insert(kind.to_string(), set.ids().to_vec());
}
}
Ok(ClaimBundle {
character_id: cid,
ruleset: model.ruleset,
payload: encoded.payload,
content_hash: encoded.content_hash,
collections,
@@ -1591,6 +1631,21 @@ impl PortableService {
let opts = self.options(&access, &caps);
// Preflight compatibility check before ANY mutation
let db_ruleset = super::super::realm::ruleset_of(&db)?;
if model.ruleset != db_ruleset {
return Err(fail(
"incompatible",
"Character ruleset does not match realm database ruleset.",
));
}
let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset;
if model.ruleset != caps_ruleset {
return Err(fail(
"incompatible",
"Character ruleset does not match realm capability ruleset.",
));
}
let ops = [Operation::OnlineImport, Operation::RuntimeSession];
let report = self.report(&model, &caps, &opts, &ops, true);
if verdict_of(report.verdict()) == Verdict::Incompatible {
@@ -1606,10 +1661,19 @@ impl PortableService {
// Monotonic union of collections
for (kind, ids) in &params.collections {
if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
let _ = self.host.merge_collection(self.host_profile, kind, &set);
}
if !super::super::session::protocol::carried_kind_for(kind, model.ruleset) {
return Err(fail(
"incompatible",
format!(
"Foreign collection kind {kind:?} in {} remote transfer",
model.ruleset
),
));
}
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
let _ = self
.host
.merge_collection(self.host_profile, model.ruleset, kind, &set);
}
}
@@ -1625,6 +1689,7 @@ impl PortableService {
);
let offer = super::super::session::protocol::SessionOffer {
protocol_version: super::super::session::protocol::PROTOCOL_VERSION,
ruleset: model.ruleset,
session_id,
character_id: cid,
server_id: realm_id.to_string(),
@@ -53,6 +53,7 @@ pub struct CopyView {
pub struct CharacterView {
pub id: String,
pub name: String,
pub ruleset: super::super::model::Ruleset,
pub class_name: String,
pub race: String,
pub level: u8,
@@ -7,7 +7,7 @@ use super::*;
use crate::portable::collection::IdSet;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::ids::{CharacterId, SessionId};
use crate::portable::model::PortableCharacter;
use crate::portable::model::{PortableCharacter, Ruleset};
use crate::portable::realm::knowledge::RealmKnowledge;
use crate::portable::store::Store;
@@ -328,10 +328,10 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
// the Owner already holds a big wardrobe from other realms
let profile = owner.default_profile().unwrap();
owner
.merge_collection(profile, APPEARANCE, &ids(1..=500))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500))
.unwrap();
owner
.merge_collection(profile, VANITY, &ids(1000..=1010))
.merge_collection(profile, Ruleset::Coa, VANITY, &ids(1000..=1010))
.unwrap();
// this realm knows only part of it and holds only a few
realm.knowledge = knows(ids(1..=300), ids(1000..=1005));
@@ -344,7 +344,11 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() {
// the Owner unioned the realm's ids (700 included: the realm showed it) and kept everything else
let appearance_ack = acks.iter().find(|a| a.kind == APPEARANCE).unwrap();
assert_eq!(appearance_ack.outcome, CollectionOutcome::Applied);
let (_, canonical) = o.store().collection(profile, APPEARANCE).unwrap().unwrap();
let (_, canonical) = o
.store()
.collection(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap();
assert_eq!(canonical.len(), 501);
assert!(
canonical.contains(700) && canonical.contains(1) && canonical.contains(500),
@@ -371,12 +375,14 @@ fn an_account_with_unlocks_arrives_on_a_second_realm_from_the_owners_state_alone
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
owner
.merge_collection(profile, APPEARANCE, &ids(1..=40))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=40))
.unwrap();
owner
.merge_collection(profile, VANITY, &ids(50..=60))
.merge_collection(profile, Ruleset::Coa, VANITY, &ids(50..=60))
.unwrap();
let states = OwnerService::new(&mut owner)
.collection_states(Ruleset::Coa)
.unwrap();
let states = OwnerService::new(&mut owner).collection_states().unwrap();
assert_eq!(states.len(), 2);
let mut host = Store::open_in_memory().unwrap();
@@ -415,16 +421,17 @@ fn hostile_or_broken_collection_messages_change_nothing() {
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let mut o = OwnerService::new(&mut owner);
let good =
collection_to_json(&CollectionObserved::new(SERVER, APPEARANCE, &ids(1..=10)).unwrap())
.unwrap();
let good = collection_to_json(
&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap(),
)
.unwrap();
assert_eq!(
o.handle_collection(&good).unwrap().outcome,
CollectionOutcome::Applied
);
let state_of = |o: &OwnerService| {
o.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
};
@@ -487,13 +494,39 @@ fn hostile_or_broken_collection_messages_change_nothing() {
// a set that decodes to more ids than the cap allows is refused before it is built
let mut huge = vec![1u8];
huge.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
let message = serde_json::json!({"protocol_version": PROTOCOL_VERSION, "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
let message = serde_json::json!({"protocol_version": COLLECTION_PROTOCOL_VERSION, "ruleset": "coa", "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
assert!(matches!(
o.handle_collection(&serde_json::to_vec(&message).unwrap())
.unwrap()
.outcome,
CollectionOutcome::Rejected(_)
));
// attack test: prefix-confusion collection kinds are strictly rejected with zero state change
for evil_kind in [
"coax:appearance",
"coaevil:vanity",
"wildcard2:appearance",
"reborn-extra:vanity",
"coa:",
"unknown",
"coa:appearance:extra",
] {
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
v["kind"] = evil_kind.into();
let ack = o
.handle_collection(&serde_json::to_vec(&v).unwrap())
.unwrap();
assert!(
matches!(ack.outcome, CollectionOutcome::Rejected(_)),
"evil kind {evil_kind} must be rejected"
);
}
assert_eq!(
state_of(&o),
before,
"prefix confusion attacks must mutate nothing"
);
}
#[test]
@@ -555,7 +588,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
assert_eq!(realm.full_reads, reads);
let stored = o
.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap();
assert_eq!(stored.count, count as usize);
@@ -565,7 +598,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() {
let mut empty_realm = FakeRealm::new(GUID);
empty_realm.knowledge = realm.knowledge.clone();
let state = o
.collection_states()
.collection_states(Ruleset::Coa)
.unwrap()
.into_iter()
.find(|s| s.kind == APPEARANCE)
@@ -627,7 +660,7 @@ fn a_lost_acknowledgement_resends_the_same_set_and_the_owner_counts_it_once() {
.any(|p| p.kind == APPEARANCE));
assert_eq!(
o.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
.revision,
@@ -738,3 +771,102 @@ fn a_session_that_changes_nothing_on_a_format_1_store_makes_no_new_revision() {
"the same character in a newer format is not a change"
);
}
#[test]
fn wildcard_and_coa_collections_remain_strictly_isolated() {
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let coa_set = IdSet::from_ids([10, 20, 30]).unwrap();
let wc_set = IdSet::from_ids([10, 40, 50]).unwrap();
owner
.merge_collection(profile, Ruleset::Coa, "coa:appearance", &coa_set)
.unwrap();
owner
.merge_collection(profile, Ruleset::Wildcard, "wildcard:appearance", &wc_set)
.unwrap();
// Verify initial namespaces
let (_, s_coa) = owner
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa.ids(), &[10, 20, 30]);
let (_, s_wc) = owner
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc.ids(), &[10, 40, 50]);
let mut o = OwnerService::new(&mut owner);
// 1. Valid Wildcard observation updates Wildcard collection only
let wc_update = IdSet::from_ids([10, 40, 50, 60]).unwrap();
let msg_wc = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Wildcard,
server_id: "wc-realm".into(),
kind: "wildcard:appearance".into(),
set: CompactSet::seal("wildcard:appearance", &wc_update).unwrap(),
};
let ack = o.handle_collection(&to_json(&msg_wc).unwrap()).unwrap();
assert!(matches!(
ack.outcome,
CollectionOutcome::Applied | CollectionOutcome::Unchanged
));
// CoA remains exactly [10, 20, 30]
let (_, s_coa_after) = o
.store()
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa_after.ids(), &[10, 20, 30]);
// Wildcard updated to [10, 40, 50, 60]
let (_, s_wc_after) = o
.store()
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc_after.ids(), &[10, 40, 50, 60]);
// 2. Cross-ruleset injection attack: Wildcard message carrying coa:appearance is rejected
let rogue_wc = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Wildcard,
server_id: "wc-realm".into(),
kind: "coa:appearance".into(),
set: CompactSet::seal("coa:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
};
let ack_rogue = o.handle_collection(&to_json(&rogue_wc).unwrap()).unwrap();
assert!(matches!(ack_rogue.outcome, CollectionOutcome::Rejected(_)));
// 3. Cross-ruleset injection attack: CoA message carrying wildcard:appearance is rejected
let rogue_coa = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Coa,
server_id: "coa-realm".into(),
kind: "wildcard:appearance".into(),
set: CompactSet::seal("wildcard:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
};
let ack_rogue2 = o.handle_collection(&to_json(&rogue_coa).unwrap()).unwrap();
assert!(matches!(ack_rogue2.outcome, CollectionOutcome::Rejected(_)));
// Verify neither 999 touched CoA or Wildcard
let (_, s_coa_final) = o
.store()
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa_final.ids(), &[10, 20, 30]);
let (_, s_wc_final) = o
.store()
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc_final.ids(), &[10, 40, 50, 60]);
}
+8 -4
View File
@@ -467,16 +467,20 @@ impl RealmBridge for FakeRealm {
impl FakeRealm {
fn rows(&self, kind: &str) -> Result<&IdSet> {
match kind {
"coa:appearance" => Ok(&self.appearance_rows),
"coa:vanity" => Ok(&self.vanity_rows),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(&self.appearance_rows)
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&self.vanity_rows),
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
}
}
fn rows_mut(&mut self, kind: &str) -> Result<&mut IdSet> {
match kind {
"coa:appearance" => Ok(&mut self.appearance_rows),
"coa:vanity" => Ok(&mut self.vanity_rows),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(&mut self.appearance_rows)
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&mut self.vanity_rows),
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
}
}
+39 -5
View File
@@ -176,6 +176,26 @@ impl<'a> HostService<'a> {
found: model.character_id,
});
}
if offer.ruleset != model.ruleset {
return Err(PortableError::RulesetMismatch {
character: model.ruleset,
realm: offer.ruleset,
});
}
if let Some((_, rs)) = self.server_id.split_once(':') {
let host_ruleset = rs.parse::<crate::portable::Ruleset>().map_err(|_| {
PortableError::Invalid(format!(
"malformed or unknown ruleset suffix in server_id: {:?}",
self.server_id
))
})?;
if offer.ruleset != host_ruleset || model.ruleset != host_ruleset {
return Err(PortableError::RulesetMismatch {
character: model.ruleset,
realm: host_ruleset,
});
}
}
self.store
.host_install_copy(profile, &model, offer.canonical_revision, "owner")?;
self.store.host_prepare_session(offer, &model)
@@ -606,8 +626,16 @@ impl<'a> HostService<'a> {
let Some(account) = bridge.account_of(guid)? else {
continue;
};
for kind in COLLECTION_KINDS {
self.observe_collection(bridge, account, kind, now_secs, events)?;
let character = self.store.character(s.character_id)?;
for kind in collection_kinds(character.ruleset) {
self.observe_collection(
bridge,
account,
character.ruleset,
kind,
now_secs,
events,
)?;
}
}
Ok(())
@@ -619,6 +647,7 @@ impl<'a> HostService<'a> {
&mut self,
bridge: &mut dyn RealmBridge,
account: u32,
ruleset: crate::portable::model::Ruleset,
kind: &str,
now_secs: u64,
events: &mut Vec<HostEvent>,
@@ -644,7 +673,12 @@ impl<'a> HostService<'a> {
)?;
return Ok(());
}
let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, kind, &set)?)?;
let bytes = collection_to_json(&CollectionObserved::new(
&self.server_id,
ruleset,
kind,
&set,
)?)?;
self.store.host_collection_observe(
&self.server_id,
account,
@@ -674,7 +708,7 @@ impl<'a> HostService<'a> {
account: u32,
ack: &CollectionAck,
) -> Result<Option<Applied>> {
if !carried_kind(&ack.kind) {
if !carried_kind_for(&ack.kind, ack.ruleset) {
return Err(PortableError::Invalid(
"the acknowledgement is for a kind that is not carried".into(),
));
@@ -742,7 +776,7 @@ impl<'a> HostService<'a> {
account: u32,
state: &CollectionState,
) -> Result<Option<Applied>> {
if !carried_kind(&state.kind) {
if !carried_kind_for(&state.kind, state.ruleset) {
return Err(PortableError::Invalid(
"the collection kind is not carried".into(),
));
+31 -14
View File
@@ -49,10 +49,15 @@ impl<'a> OwnerService<'a> {
pub fn handle_collection(&mut self, bytes: &[u8]) -> Result<CollectionAck> {
let msg: CollectionObserved = collection_from_json(bytes)?;
let profile = self.store.default_profile()?;
let ruleset = msg.ruleset;
let rejected = |store: &Store, reason: &str| -> Result<CollectionAck> {
let info = store.collection_info(profile, &msg.kind).ok().flatten();
let info = store
.collection_info(profile, ruleset, &msg.kind)
.ok()
.flatten();
Ok(CollectionAck {
protocol_version: PROTOCOL_VERSION,
protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
ruleset,
kind: msg.kind.clone(),
outcome: CollectionOutcome::Rejected(reason.to_string()),
collection_revision: info.as_ref().map_or(0, |i| i.revision),
@@ -60,30 +65,39 @@ impl<'a> OwnerService<'a> {
canonical: None,
})
};
if !carried_kind(&msg.kind) {
return rejected(self.store, "this collection kind is not carried");
if !carried_kind_for(&msg.kind, ruleset) {
return rejected(
self.store,
"this collection kind is not carried for this ruleset",
);
}
let observed = match msg.set.open(&msg.kind) {
Ok(set) => set,
Err(e) => return rejected(self.store, &e.to_string()),
};
let merge = self.store.merge_collection(profile, &msg.kind, &observed)?;
let merge = self
.store
.merge_collection(profile, ruleset, &msg.kind, &observed)?;
let (info, canonical) = self
.store
.collection(profile, &msg.kind)?
.collection(profile, ruleset, &msg.kind)?
.map(|(i, s)| (Some(i), s))
.unwrap_or((None, IdSet::new()));
let canonical_state = match (
&info,
observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0,
) {
(Some(info), false) => {
Some(CollectionState::new(&msg.kind, info.revision, &canonical)?)
}
(Some(info), false) => Some(CollectionState::new(
ruleset,
&msg.kind,
info.revision,
&canonical,
)?),
_ => None,
};
Ok(CollectionAck {
protocol_version: PROTOCOL_VERSION,
protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
ruleset,
kind: msg.kind,
outcome: if merge.changed {
CollectionOutcome::Applied
@@ -97,12 +111,15 @@ impl<'a> OwnerService<'a> {
}
/// The canonical collections as messages (for a realm that has none of them yet, or a new one).
pub fn collection_states(&mut self) -> Result<Vec<CollectionState>> {
pub fn collection_states(
&mut self,
ruleset: crate::portable::model::Ruleset,
) -> Result<Vec<CollectionState>> {
let profile = self.store.default_profile()?;
let mut out = Vec::new();
for kind in COLLECTION_KINDS {
if let Some((info, set)) = self.store.collection(profile, kind)? {
out.push(CollectionState::new(kind, info.revision, &set)?);
for kind in collection_kinds(ruleset) {
if let Some((info, set)) = self.store.collection(profile, ruleset, kind)? {
out.push(CollectionState::new(ruleset, kind, info.revision, &set)?);
}
}
Ok(out)
@@ -128,7 +128,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re
} = rig(|_| {});
let profile = owner.default_profile().unwrap();
owner
.merge_collection(profile, APPEARANCE, &ids(1..=500))
.merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500))
.unwrap();
// the realm's client data knows 1..=300 of the canonical 500
realm.knowledge = RealmKnowledge::new(ids(1..=300), IdSet::new());
@@ -186,7 +186,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re
);
assert_eq!(
o.store()
.collection(profile, APPEARANCE)
.collection(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
.1
@@ -371,9 +371,10 @@ fn a_session_started_without_its_projection_or_with_a_wrong_one_is_not_opened()
);
// an older protocol is not understood at all
let old = String::from_utf8(genuine.clone())
.unwrap()
.replace("\"protocol_version\":2", "\"protocol_version\":1");
let old = String::from_utf8(genuine.clone()).unwrap().replace(
&format!("\"protocol_version\":{PROTOCOL_VERSION}"),
"\"protocol_version\":1",
);
assert!(o.handle_started(old.as_bytes()).is_err());
assert_eq!(
o.handle_started(&genuine).unwrap().outcome,
+185 -19
View File
@@ -13,14 +13,19 @@ use super::super::model::{limits::MAX_COMPRESSED_BYTES, PortableCharacter};
use super::super::projection::{ProgressionPin, ProjectionContext};
use super::super::snapshot;
/// Version 2 (Phase 8): `PortableSessionStarted` carries the progression the session runs under, every `PortableCheckpoint` and `OwnerAck` its pin.
/// A version 1 peer and a version 2 peer read each other's messages as unsupported, and the realm's capability profile (`session_protocol`)
/// says so before any character is armed.
pub const PROTOCOL_VERSION: u32 = 2;
/// Version 3: `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit `ruleset`.
/// Version 2 (Phase 8): `PortableSessionStarted` carried progression and pins.
pub const SESSION_PROTOCOL_VERSION: u32 = 3;
/// Protocol version for collection synchronization (`CollectionObserved`, `CollectionState`, `CollectionAck`).
pub const COLLECTION_PROTOCOL_VERSION: u32 = 2;
/// Backward-compatibility alias for session protocol version.
pub const PROTOCOL_VERSION: u32 = SESSION_PROTOCOL_VERSION;
/// A message carries at most one compressed snapshot (base64: 4/3) plus a little structure.
pub const MAX_MESSAGE_BYTES: usize = MAX_COMPRESSED_BYTES * 4 / 3 + 64 * 1024;
/// The most item/pet ids an acknowledgement lists.
pub const MAX_ACK_IDS: usize = 20_000;
/// The largest serialized collection message accepted.
pub const MAX_COLLECTION_MESSAGE_BYTES: usize = 1024 * 1024;
/// A sealed snapshot: the hash of the canonical JSON and the compressed bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -79,6 +84,7 @@ impl Envelope {
#[serde(deny_unknown_fields)]
pub struct SessionOffer {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -123,6 +129,7 @@ impl SessionProgression {
#[serde(deny_unknown_fields)]
pub struct PortableSessionStarted {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -139,6 +146,7 @@ pub struct PortableSessionStarted {
#[serde(deny_unknown_fields)]
pub struct PortableCheckpoint {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -188,6 +196,7 @@ pub struct NextSession {
#[serde(deny_unknown_fields)]
pub struct OwnerAck {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
/// 0 acknowledges `PortableSessionStarted`.
pub sequence: u64,
@@ -250,16 +259,17 @@ impl PortableSessionStarted {
if let Some(p) = &progression {
p.validate()?;
}
let b0 = Envelope::seal(b0)?;
let sealed_b0 = Envelope::seal(b0)?;
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset: b0.ruleset,
session_id,
character_id,
server_id: server_id.to_string(),
base_canonical_revision,
baseline_generation,
content_hash: b0.content_hash.clone(),
b0,
content_hash: sealed_b0.content_hash.clone(),
b0: sealed_b0,
progression,
})
}
@@ -279,6 +289,7 @@ impl PortableCheckpoint {
let realm_snapshot = Envelope::seal(b1)?;
Ok(Self {
protocol_version: PROTOCOL_VERSION,
ruleset: b1.ruleset,
session_id,
character_id,
server_id: server_id.to_string(),
@@ -300,15 +311,32 @@ impl PortableCheckpoint {
use super::super::collection::{valid_kind, IdSet, MAX_ENCODED_BYTES};
/// The collection kinds the v1 protocol carries.
pub const COLLECTION_KINDS: [&str; 2] = ["coa:appearance", "coa:vanity"];
/// A collection message carries at most one encoded set (base64: 4/3) plus a little structure.
pub const MAX_COLLECTION_MESSAGE_BYTES: usize = MAX_ENCODED_BYTES * 4 / 3 + 64 * 1024;
/// The collection kinds the protocol carries.
pub const COLLECTION_KINDS: [&str; 6] = [
"coa:appearance",
"coa:vanity",
"wildcard:appearance",
"wildcard:vanity",
"reborn:appearance",
"reborn:vanity",
];
pub fn collection_kinds(ruleset: super::super::model::Ruleset) -> &'static [&'static str] {
match ruleset {
super::super::model::Ruleset::Coa => &["coa:appearance", "coa:vanity"],
super::super::model::Ruleset::Wildcard => &["wildcard:appearance", "wildcard:vanity"],
super::super::model::Ruleset::Reborn => &["reborn:appearance", "reborn:vanity"],
}
}
pub fn carried_kind(kind: &str) -> bool {
valid_kind(kind) && COLLECTION_KINDS.contains(&kind)
}
pub fn carried_kind_for(kind: &str, ruleset: super::super::model::Ruleset) -> bool {
valid_kind(kind) && collection_kinds(ruleset).contains(&kind)
}
/// A compact id set as it travels: hash of the kind and content, number of ids, base64 of [`IdSet::encode`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -365,6 +393,7 @@ impl CompactSet {
#[serde(deny_unknown_fields)]
pub struct CollectionObserved {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub server_id: String,
pub kind: String,
pub set: CompactSet,
@@ -375,6 +404,7 @@ pub struct CollectionObserved {
#[serde(deny_unknown_fields)]
pub struct CollectionState {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub collection_revision: u64,
pub set: CompactSet,
@@ -400,6 +430,7 @@ pub enum CollectionOutcome {
#[serde(deny_unknown_fields)]
pub struct CollectionAck {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub outcome: CollectionOutcome,
pub collection_revision: u64,
@@ -430,24 +461,30 @@ pub fn collection_from_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
.get("protocol_version")
.and_then(|v| v.as_u64())
.ok_or_else(|| PortableError::Invalid("the message has no protocol version".into()))?;
if version != PROTOCOL_VERSION as u64 {
if version != COLLECTION_PROTOCOL_VERSION as u64 {
return Err(PortableError::UnsupportedFormat {
found: version.min(u32::MAX as u64) as u32,
supported: PROTOCOL_VERSION,
supported: COLLECTION_PROTOCOL_VERSION,
});
}
Ok(serde_json::from_value(value)?)
}
impl CollectionObserved {
pub fn new(server_id: &str, kind: &str, set: &IdSet) -> Result<Self> {
if !carried_kind(kind) {
pub fn new(
server_id: &str,
ruleset: super::super::model::Ruleset,
kind: &str,
set: &IdSet,
) -> Result<Self> {
if !carried_kind_for(kind, ruleset) {
return Err(PortableError::Invalid(format!(
"collection kind {kind:?} is not carried"
"collection kind {kind:?} is not carried for {ruleset:?}"
)));
}
Ok(Self {
protocol_version: PROTOCOL_VERSION,
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset,
server_id: server_id.to_string(),
kind: kind.to_string(),
set: CompactSet::seal(kind, set)?,
@@ -456,12 +493,141 @@ impl CollectionObserved {
}
impl CollectionState {
pub fn new(kind: &str, revision: u64, set: &IdSet) -> Result<Self> {
pub fn new(
ruleset: super::super::model::Ruleset,
kind: &str,
revision: u64,
set: &IdSet,
) -> Result<Self> {
Ok(Self {
protocol_version: PROTOCOL_VERSION,
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset,
kind: kind.to_string(),
collection_revision: revision,
set: CompactSet::seal(kind, set)?,
})
}
}
/// Legacy Session Protocol v2 representation (Phase 8), where absence of ruleset is defined to mean CoA.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LegacyV2SessionOffer {
pub protocol_version: u32,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
pub canonical_revision: u64,
pub snapshot: Envelope,
}
impl LegacyV2SessionOffer {
pub fn into_session_offer(self) -> SessionOffer {
SessionOffer {
protocol_version: SESSION_PROTOCOL_VERSION,
ruleset: super::super::model::Ruleset::Coa,
session_id: self.session_id,
character_id: self.character_id,
server_id: self.server_id,
canonical_revision: self.canonical_revision,
snapshot: self.snapshot,
}
}
}
#[cfg(test)]
mod protocol_tests {
use super::*;
use crate::portable::Ruleset;
#[test]
fn session_protocol_v3_requires_ruleset_and_rejects_missing_or_unknown() {
let envelope = Envelope {
content_hash: "00".repeat(32),
payload: "AA==".to_string(),
};
// 1. Valid v3 SessionOffer with explicit ruleset (CoA, Wildcard, Reborn)
for r in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] {
let offer = SessionOffer {
protocol_version: SESSION_PROTOCOL_VERSION,
ruleset: r,
session_id: SessionId::new(),
character_id: CharacterId::new(),
server_id: "realm-1".to_string(),
canonical_revision: 1,
snapshot: envelope.clone(),
};
let bytes = to_json(&offer).unwrap();
let parsed: SessionOffer = from_json(&bytes).unwrap();
assert_eq!(parsed.ruleset, r);
}
// 2. Missing ruleset in v3 JSON is rejected (never silently defaults to CoA)
let missing_ruleset_v3 = serde_json::json!({
"protocol_version": SESSION_PROTOCOL_VERSION,
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&missing_ruleset_v3).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(
err.is_err(),
"missing ruleset must be rejected in protocol v3"
);
// 3. Unknown ruleset in v3 JSON is rejected
let unknown_ruleset_v3 = serde_json::json!({
"protocol_version": SESSION_PROTOCOL_VERSION,
"ruleset": "cyberpunk",
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&unknown_ruleset_v3).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(err.is_err(), "unknown ruleset must be rejected");
// 4. Old v2 peer message (protocol_version 2) is rejected by current v3 parser
let legacy_v2_json = serde_json::json!({
"protocol_version": 2,
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&legacy_v2_json).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(
matches!(
err,
Err(PortableError::UnsupportedFormat {
found: 2,
supported: 3
})
),
"v2 peer must be rejected with UnsupportedFormat"
);
// 5. Explicit LegacyV2SessionOffer decode correctly interprets absence of ruleset as CoA
let v2_parsed: LegacyV2SessionOffer = serde_json::from_slice(&bytes).unwrap();
let upgraded = v2_parsed.into_session_offer();
assert_eq!(upgraded.ruleset, Ruleset::Coa);
assert_eq!(upgraded.protocol_version, SESSION_PROTOCOL_VERSION);
}
}
@@ -4,6 +4,7 @@ use super::bridge::*;
use super::fake::*;
use super::protocol::*;
use super::*;
use crate::portable::error::PortableError;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::ids::{CharacterId, PortableItemId, SessionId};
use crate::portable::model::*;
@@ -1051,3 +1052,611 @@ fn an_autosave_between_checkpoints_is_harmless() {
c0.progression.money + 10
);
}
fn setup_wildcard_in(mut owner: Store, mut host: Store, server_id: &str) -> Setup {
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
model.content_namespace = "wildcard".into();
let id = owner
.create_character(profile, model, "wildcard-origin")
.unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, server_id).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = normalizes;
{
let mut h = HostService::new(&mut host, server_id, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm
.import(
&mut host,
id,
server_id,
offer.canonical_revision,
offer.session_id,
)
.unwrap();
HostService::new(&mut host, server_id, HostConfig::default())
.bind(offer.session_id, GUID)
.unwrap();
}
Setup {
owner,
host,
realm,
id,
session: offer.session_id,
c0,
}
}
fn setup_reborn_in(mut owner: Store, mut host: Store, server_id: &str) -> Setup {
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Reborn;
model.content_namespace = "reborn".into();
let id = owner
.create_character(profile, model, "reborn-origin")
.unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, server_id).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = normalizes;
{
let mut h = HostService::new(&mut host, server_id, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm
.import(
&mut host,
id,
server_id,
offer.canonical_revision,
offer.session_id,
)
.unwrap();
HostService::new(&mut host, server_id, HostConfig::default())
.bind(offer.session_id, GUID)
.unwrap();
}
Setup {
owner,
host,
realm,
id,
session: offer.session_id,
c0,
}
}
#[test]
fn wildcard_session_offer_carrying_coa_snapshot_is_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let coa_model = geared_level_eighty();
let id = owner
.create_character(profile, coa_model, "realm-a")
.unwrap();
let mut offer = OwnerService::new(&mut owner)
.offer(id, "srv-1:wildcard")
.unwrap();
// Tamper offer: claim it is Wildcard while snapshot is CoA
offer.ruleset = Ruleset::Wildcard;
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res = h.accept_offer(host_profile, &offer);
assert!(matches!(
res,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Wildcard
})
));
// Zero mutation on host
assert!(host.character(id).is_err());
assert!(host.host_session(offer.session_id).unwrap().is_none());
}
#[test]
fn wildcard_portable_session_started_marked_coa_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
session,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let outbox = h.outbox().unwrap();
assert_eq!(outbox.len(), 1);
let mut started: PortableSessionStarted = from_json(&outbox[0].bytes).unwrap();
// Tamper: mark as CoA
started.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&started).unwrap();
let ack = o.handle_started(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Owner session remains offered, never open
let (state, _, _) = o.session(session).unwrap().unwrap();
assert_eq!(state, "offered");
}
#[test]
fn wildcard_checkpoint_marked_reborn_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
id,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
start(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 500);
h.tick(&mut realm, 100).unwrap();
h.tick(&mut realm, 101).unwrap();
let outbox = h.outbox().unwrap();
let checkpoint_msg = outbox.iter().find(|m| !m.started).unwrap();
let mut cp: PortableCheckpoint = from_json(&checkpoint_msg.bytes).unwrap();
// Tamper: mark as Reborn
cp.ruleset = Ruleset::Reborn;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let initial_snapshot = o.store().load_snapshot(id, initial_rev).unwrap();
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Zero canonical revision change or mutation
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
assert_eq!(
o.store().load_snapshot(id, initial_rev).unwrap(),
initial_snapshot
);
}
#[test]
fn wildcard_session_using_coa_server_id_is_rejected() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
let id = owner
.create_character(profile, model, "wildcard-origin")
.unwrap();
// Offer for srv-1:coa
let offer = OwnerService::new(&mut owner)
.offer(id, "srv-1:coa")
.unwrap();
// Host configured for Wildcard realm
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res = h.accept_offer(host_profile, &offer);
assert!(matches!(res, Err(PortableError::Invalid(_))));
}
#[test]
fn same_character_id_with_foreign_ruleset_is_rejected() {
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
let id = owner
.create_character(profile, model.clone(), "srv-1:wildcard")
.unwrap();
// Tampered snapshot with same ID but Ruleset::Coa
let mut tampered = model.clone();
tampered.character_id = id;
tampered.ruleset = Ruleset::Coa;
let res = owner.commit_snapshot(id, 1, tampered, "srv-1:wildcard", None);
assert!(matches!(res, Err(PortableError::RulesetChange { .. })));
}
#[test]
fn owner_ack_with_different_ruleset_is_rejected_by_host() {
let Setup {
mut owner,
mut host,
mut realm,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let outbox = h.outbox().unwrap();
let mut ack = o.handle_started(&outbox[0].bytes).unwrap();
// Tamper ack ruleset to CoA
ack.ruleset = Ruleset::Coa;
let res = h.receive_ack(&mut realm, &ack);
assert!(matches!(
res,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Coa
})
));
}
#[test]
fn final_checkpoint_relabelled_coa_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
id,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
start(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 1000);
realm.logout();
h.tick(&mut realm, 100).unwrap();
h.tick(&mut realm, 101).unwrap();
let outbox = h.outbox().unwrap();
let final_cp_msg = outbox.iter().find(|m| !m.started).unwrap();
let mut cp: PortableCheckpoint = from_json(&final_cp_msg.bytes).unwrap();
assert!(cp.final_checkpoint);
// Relabel as CoA
cp.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Revision must not advance and state must not be committed
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
}
#[test]
fn full_wildcard_session_lifecycle() {
let Setup {
mut owner,
mut host,
mut realm,
id,
session,
c0,
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
// 1. Start session
start(&mut h, &mut o, &mut realm);
assert_eq!(o.session(session).unwrap().unwrap().0, "open");
// 2. Play on Wildcard realm: earn gold and level up
realm.play(|m| {
m.progression.money += 50_000;
m.progression.xp += 1_000;
});
// 3. Online checkpoint
checkpoint(&mut h, &mut o, &mut realm, 100);
let rev2 = o.store().character(id).unwrap().revision;
assert_eq!(rev2, 2);
let curr2 = o.store().load_current(id).unwrap();
assert_eq!(curr2.ruleset, Ruleset::Wildcard);
assert_eq!(curr2.progression.money, c0.progression.money + 50_000);
// 4. More gameplay then logout
realm.play(|m| {
m.progression.money += 25_000;
});
realm.logout();
h.tick(&mut realm, 200).unwrap();
h.tick(&mut realm, 201).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
assert!(acks.iter().any(|a| a.outcome == AckOutcome::Applied));
// 5. Verify final canonical state
let rec = o.store().character(id).unwrap();
assert_eq!(rec.revision, 3);
assert_eq!(rec.ruleset, Ruleset::Wildcard);
let final_model = o.store().load_current(id).unwrap();
assert_eq!(final_model.ruleset, Ruleset::Wildcard);
assert_eq!(final_model.progression.money, c0.progression.money + 75_000);
}
#[test]
fn reborn_hostile_attacks_are_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let coa_model = geared_level_eighty();
let id_coa = owner
.create_character(profile, coa_model, "realm-coa")
.unwrap();
let mut wc_model = geared_level_eighty();
wc_model.ruleset = Ruleset::Wildcard;
let id_wc = owner
.create_character(profile, wc_model, "realm-wc")
.unwrap();
let mut reb_model = geared_level_eighty();
reb_model.ruleset = Ruleset::Reborn;
let id_reb = owner
.create_character(profile, reb_model, "realm-reb")
.unwrap();
// 1. Reborn offer carrying CoA snapshot
let mut offer_reb_with_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_reb_with_coa.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res1 = h_reborn.accept_offer(host_profile, &offer_reb_with_coa);
assert!(matches!(
res1,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_coa).is_err());
// 2. Reborn offer carrying Wildcard snapshot
let mut offer_reb_with_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_reb_with_wc.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res2 = h_reborn.accept_offer(host_profile, &offer_reb_with_wc);
assert!(matches!(
res2,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_wc).is_err());
// 3. CoA offer -> Reborn realm
let mut offer_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_coa.ruleset = Ruleset::Coa;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res3 = h_reborn.accept_offer(host_profile, &offer_coa);
assert!(matches!(
res3,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
// 4. Wildcard offer -> Reborn realm
let mut offer_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_wc.ruleset = Ruleset::Wildcard;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res4 = h_reborn.accept_offer(host_profile, &offer_wc);
assert!(matches!(
res4,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
// 5. Reborn offer -> CoA realm
let mut offer_reb = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
offer_reb.ruleset = Ruleset::Reborn;
{
let mut h_coa = HostService::new(&mut host, "srv-1:coa", HostConfig::default());
let res5 = h_coa.accept_offer(host_profile, &offer_reb);
assert!(matches!(
res5,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
// 6. Reborn offer -> Wildcard realm
let mut offer_reb_to_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
offer_reb_to_wc.ruleset = Ruleset::Reborn;
{
let mut h_wc = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res6 = h_wc.accept_offer(host_profile, &offer_reb_to_wc);
assert!(matches!(
res6,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Wildcard
})
));
}
// 7. Reborn session using foreign server ID srv-1:coa or srv-1:wildcard
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let offer_for_coa = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
let res7 = h_reborn.accept_offer(host_profile, &offer_for_coa);
assert!(res7.is_err());
let offer_for_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
let res8 = h_reborn.accept_offer(host_profile, &offer_for_wc);
assert!(res8.is_err());
}
// 8. Reborn collection containing foreign collections coa:appearance or wildcard:vanity
let coll_err1 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"coa:appearance",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
coll_err1.is_err(),
"Reborn merging coa:appearance must fail"
);
let coll_err2 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"wildcard:vanity",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
coll_err2.is_err(),
"Reborn merging wildcard:vanity must fail"
);
// 9. HostService with malformed server_id ruleset suffixes fails closed
for bad_server_id in ["srv-1:unknown", "srv-1:garbage", "srv-1:reborn:extra"] {
let mut h_bad = HostService::new(&mut host, bad_server_id, HostConfig::default());
let mut offer_bad = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:reborn")
.unwrap();
offer_bad.server_id = bad_server_id.to_string();
let res_bad = h_bad.accept_offer(host_profile, &offer_bad);
assert!(
res_bad.is_err(),
"accept_offer on malformed server id {bad_server_id} must fail closed"
);
}
}
#[test]
fn full_reborn_session_lifecycle() {
let Setup {
mut owner,
mut host,
mut realm,
id,
session,
c0,
} = setup_reborn_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:reborn",
);
let mut h = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
// 1. Start session
start(&mut h, &mut o, &mut realm);
assert_eq!(o.session(session).unwrap().unwrap().0, "open");
// 2. Play on Reborn realm: earn gold and level up
realm.play(|m| {
m.progression.money += 100_000;
m.progression.xp += 5_000;
});
// 3. Online checkpoint
checkpoint(&mut h, &mut o, &mut realm, 100);
let rev2 = o.store().character(id).unwrap().revision;
assert_eq!(rev2, 2);
let curr2 = o.store().load_current(id).unwrap();
assert_eq!(curr2.ruleset, Ruleset::Reborn);
assert_eq!(curr2.progression.money, c0.progression.money + 100_000);
// 4. Test Reborn checkpoint marked CoA / Wildcard rejected by owner
let outbox = h.outbox().unwrap();
if let Some(msg) = outbox.first() {
let mut cp: PortableCheckpoint = from_json(&msg.bytes).unwrap();
cp.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
}
// 5. Test OwnerAck marked CoA rejected by Reborn host
if let Some(msg) = outbox.first() {
if let Ok(mut ack) = o.handle_checkpoint(&msg.bytes) {
ack.ruleset = Ruleset::Coa;
let res_ack = h.receive_ack(&mut realm, &ack);
assert!(matches!(
res_ack,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
}
// 6. More gameplay then logout
realm.play(|m| {
m.progression.money += 50_000;
});
realm.logout();
h.tick(&mut realm, 200).unwrap();
h.tick(&mut realm, 201).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
assert!(acks.iter().any(|a| a.outcome == AckOutcome::Applied));
// 7. Verify final canonical state
let rec = o.store().character(id).unwrap();
assert_eq!(rec.revision, 3);
assert_eq!(rec.ruleset, Ruleset::Reborn);
let final_model = o.store().load_current(id).unwrap();
assert_eq!(final_model.ruleset, Ruleset::Reborn);
assert_eq!(
final_model.progression.money,
c0.progression.money + 150_000
);
}
+87 -10
View File
@@ -28,6 +28,7 @@ const MIGRATIONS: &[&str] = &[
include_str!("migrations/007_capabilities.sql"),
include_str!("migrations/008_projection.sql"),
include_str!("migrations/009_multiruleset.sql"),
include_str!("migrations/010_reborn_character_ruleset.sql"),
];
pub const DEFAULT_HISTORY_KEEP: u32 = 20;
@@ -174,12 +175,12 @@ impl Store {
}
fn init(conn: Connection) -> Result<Store> {
conn.pragma_update(None, "foreign_keys", true)?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
let _ = conn.pragma_update(None, "journal_mode", "WAL");
let _ = conn.pragma_update(None, "synchronous", "NORMAL");
let mut store = Store { conn };
store.migrate()?;
store.conn.pragma_update(None, "foreign_keys", true)?;
Ok(store)
}
@@ -206,11 +207,13 @@ impl Store {
});
}
for next in version..supported {
self.conn.pragma_update(None, "foreign_keys", false)?;
let tx = self.conn.transaction()?;
tx.execute_batch(MIGRATIONS[next as usize])?;
tx.pragma_update(None, "application_id", APPLICATION_ID)?;
tx.pragma_update(None, "user_version", next + 1)?;
tx.commit()?;
self.conn.pragma_update(None, "foreign_keys", true)?;
}
Ok(())
}
@@ -329,6 +332,23 @@ impl Store {
read_character(&self.conn, id)
}
pub fn get_character(
&self,
id: CharacterId,
expected_ruleset: Option<Ruleset>,
) -> Result<CharacterRecord> {
let rec = read_character(&self.conn, id)?;
if let Some(expected) = expected_ruleset {
if rec.ruleset != expected {
return Err(PortableError::RulesetMismatch {
character: rec.ruleset,
realm: expected,
});
}
}
Ok(rec)
}
pub fn list_characters(&self, profile: ProfileId) -> Result<Vec<CharacterRecord>> {
let mut stmt = self.conn.prepare(
"SELECT character_id FROM character WHERE profile_id = ?1 ORDER BY character_id",
@@ -341,6 +361,22 @@ impl Store {
.collect()
}
pub fn list_characters_by_ruleset(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CharacterRecord>> {
let mut stmt = self.conn.prepare(
"SELECT character_id FROM character WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY character_id",
)?;
let ids: Vec<String> = stmt
.query_map(params![profile.to_string(), ruleset.as_str()], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?;
ids.iter()
.map(|text| read_character(&self.conn, text.parse()?))
.collect()
}
/// Every character of every profile (an overview for tools; normally the UI lists one profile).
pub fn list_characters_all(&self) -> Result<Vec<CharacterRecord>> {
let mut stmt = self
@@ -658,13 +694,13 @@ impl Store {
}
// ---- collections ----------------------------------------------------------------------------------------
// These APIs exchange CoA collections only. Preserve other schema-9 partitions without reading or modifying them.
/// `stored = stored U incoming`. Nothing is ever removed. When the union equals what is stored, no revision is
/// created and the hash stays the same.
pub fn merge_collection(
&mut self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
incoming: &IdSet,
) -> Result<CollectionMerge> {
@@ -673,6 +709,13 @@ impl Store {
"invalid collection kind {kind:?}"
)));
}
if let Some((ns, _)) = kind.split_once(':') {
if matches!(ns, "coa" | "wildcard" | "reborn") && ns != ruleset.as_str() {
return Err(PortableError::Invalid(format!(
"collection kind namespace {ns:?} does not match ruleset {ruleset:?}"
)));
}
}
let tx = self.write_tx()?;
let profile_exists: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM profile WHERE profile_id = ?1)",
@@ -684,7 +727,7 @@ impl Store {
"profile {profile} does not exist"
)));
}
let stored = read_collection(&tx, profile, kind)?;
let stored = read_collection(&tx, profile, ruleset, kind)?;
let (current_set, revision) = match &stored {
Some((info, set)) => (set.clone(), info.revision),
None => (IdSet::new(), 0),
@@ -704,10 +747,10 @@ impl Store {
let at = now();
tx.execute(
"INSERT INTO collection(profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
VALUES (?1, 'coa', ?2, ?3, ?4, ?5, ?6, ?7, ?8)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(profile_id, ruleset, kind) DO UPDATE SET collection_revision = excluded.collection_revision, collection_hash = excluded.collection_hash,
format_version = excluded.format_version, item_count = excluded.item_count, updated_at = excluded.updated_at, payload = excluded.payload",
params![profile.to_string(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload],
params![profile.to_string(), ruleset.as_str(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload],
)?;
tx.commit()?;
Ok(CollectionMerge {
@@ -727,13 +770,14 @@ impl Store {
pub fn collection_info(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<CollectionInfo>> {
let row = self
.conn
.query_row(
"SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = 'coa' AND kind = ?2",
params![profile.to_string(), kind],
"SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3",
params![profile.to_string(), ruleset.as_str(), kind],
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?)),
)
.optional()?;
@@ -752,9 +796,41 @@ impl Store {
pub fn collection(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
read_collection(&self.conn, profile, kind)
read_collection(&self.conn, profile, ruleset, kind)
}
pub fn list_collections(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CollectionInfo>> {
let mut stmt = self.conn.prepare(
"SELECT kind, collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY kind",
)?;
let rows = stmt.query_map(params![profile.to_string(), ruleset.as_str()], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, Vec<u8>>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, String>(4)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (kind, revision, hash, count, updated_at) = row?;
out.push(CollectionInfo {
kind,
revision: revision as u64,
hash: hash_from_blob(hash)?,
count: count as usize,
updated_at,
});
}
Ok(out)
}
/// Rewrite the current revision exactly as format 1 stored it (the stores of Phases 1-5 hold such snapshots). Tests only.
@@ -778,12 +854,13 @@ impl Store {
fn read_collection(
conn: &Connection,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
let row = conn
.query_row(
"SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND ruleset = 'coa' AND kind = ?2",
params![profile.to_string(), kind],
"SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3",
params![profile.to_string(), ruleset.as_str(), kind],
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?, r.get::<_, Vec<u8>>(4)?)),
)
.optional()?;
@@ -579,6 +579,13 @@ impl Store {
Some(_) => {}
}
let at = now();
let record = read_character(&tx, s.character_id)?;
if ack.ruleset != record.ruleset {
return Err(PortableError::RulesetMismatch {
character: record.ruleset,
realm: ack.ruleset,
});
}
if ack.outcome.accepted() && ack.pin != s.pin {
return Err(PortableError::ProgressionChanged(
"the acknowledgement is under another progression profile than the session".into(),
+34 -4
View File
@@ -104,6 +104,7 @@ fn head_hash(conn: &Connection, id: CharacterId, revision: u64) -> Result<[u8; 3
}
fn ack(
ruleset: Ruleset,
session: SessionId,
sequence: u64,
outcome: AckOutcome,
@@ -112,6 +113,7 @@ fn ack(
) -> OwnerAck {
OwnerAck {
protocol_version: PROTOCOL_VERSION,
ruleset,
session_id: session,
sequence,
outcome,
@@ -136,9 +138,10 @@ fn owned_ids(
(items, pets)
}
fn offer_from_row(row: &OwnerRow) -> SessionOffer {
fn offer_from_row(row: &OwnerRow, ruleset: Ruleset) -> SessionOffer {
SessionOffer {
protocol_version: PROTOCOL_VERSION,
ruleset,
session_id: row.session_id,
character_id: row.character_id,
server_id: row.server_id.clone(),
@@ -163,6 +166,7 @@ fn open_offer(tx: &Transaction<'_>, id: CharacterId, server_id: &str) -> Result<
)?;
Ok(offer_from_row(
&read_owner_row(tx, session)?.expect("just inserted"),
record.ruleset,
))
}
@@ -186,7 +190,7 @@ impl Store {
return Err(PortableError::SessionOpen);
}
if row.c0_revision == record.revision {
return Ok(offer_from_row(&row));
return Ok(offer_from_row(&row, record.ruleset));
}
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![live, now()])?;
}
@@ -200,6 +204,7 @@ impl Store {
let tx = self.write_tx()?;
let Some(row) = read_owner_row(&tx, msg.session_id)? else {
return Ok(ack(
msg.ruleset,
msg.session_id,
0,
AckOutcome::Rejected("unknown session".into()),
@@ -207,9 +212,11 @@ impl Store {
[0; 32],
));
};
let record = read_character(&tx, row.character_id)?;
let current_hash = head_hash(&tx, row.character_id, row.head_revision)?;
let reject = |why: &str| {
ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Rejected(why.into()),
@@ -217,6 +224,9 @@ impl Store {
current_hash,
)
};
if msg.ruleset != record.ruleset {
return Ok(reject("the message ruleset does not match the character"));
}
if msg.character_id != row.character_id || msg.server_id != row.server_id {
return Ok(reject("the message does not belong to this session"));
}
@@ -237,6 +247,7 @@ impl Store {
&& row.progression == msg.progression
{
let mut a = ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Duplicate,
@@ -253,6 +264,7 @@ impl Store {
"offered" => {}
_ => {
return Ok(ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::StaleSession,
@@ -299,6 +311,7 @@ impl Store {
)?;
tx.commit()?;
let mut a = ack(
record.ruleset,
msg.session_id,
0,
AckOutcome::Applied,
@@ -315,6 +328,7 @@ impl Store {
let tx = self.write_tx()?;
let Some(row) = read_owner_row(&tx, msg.session_id)? else {
return Ok(ack(
msg.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Rejected("unknown session".into()),
@@ -324,10 +338,23 @@ impl Store {
};
let record = read_character(&tx, row.character_id)?;
let seen_hash = head_hash(&tx, row.character_id, record.revision)?;
let outcome =
|o: AckOutcome| ack(msg.session_id, msg.sequence, o, record.revision, seen_hash);
let outcome = |o: AckOutcome| {
ack(
record.ruleset,
msg.session_id,
msg.sequence,
o,
record.revision,
seen_hash,
)
};
let reject = |why: &str| outcome(AckOutcome::Rejected(why.into()));
if msg.ruleset != record.ruleset {
return Ok(reject(
"the checkpoint ruleset does not match the character",
));
}
if msg.character_id != row.character_id || msg.server_id != row.server_id {
return Ok(reject("the message does not belong to this session"));
}
@@ -354,6 +381,7 @@ impl Store {
}
let revision = revision as u64;
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Duplicate,
@@ -390,6 +418,7 @@ impl Store {
tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![msg.session_id.to_string(), now()])?;
tx.commit()?;
return Ok(ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::StaleSession,
@@ -457,6 +486,7 @@ impl Store {
};
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Applied,
+564 -20
View File
@@ -40,13 +40,13 @@ fn schema_nine_upgrade_preserves_characters_and_isolates_collections() {
drop(old);
let mut store = Store::open(dir.path()).unwrap();
assert_eq!(store.schema_version().unwrap(), 9);
assert_eq!(store.schema_version().unwrap(), 10);
assert_eq!(store.load_current(id).unwrap(), before);
assert_eq!(store.server_mappings(id).unwrap()[0].local_guid, 42);
assert_eq!(store.collection(profile, kind).unwrap().unwrap().1, set);
assert_eq!(store.collection(profile, Ruleset::Coa, kind).unwrap().unwrap().1, set);
assert_eq!(
store
.collection_info(profile, kind)
.collection_info(profile, Ruleset::Coa, kind)
.unwrap()
.unwrap()
.revision,
@@ -58,10 +58,10 @@ fn schema_nine_upgrade_preserves_characters_and_isolates_collections() {
[],
).unwrap();
store
.merge_collection(profile, kind, &IdSet::from_ids([30]).unwrap())
.merge_collection(profile, Ruleset::Coa, kind, &IdSet::from_ids([30]).unwrap())
.unwrap();
assert_eq!(
store.collection(profile, kind).unwrap().unwrap().1,
store.collection(profile, Ruleset::Coa, kind).unwrap().unwrap().1,
IdSet::from_ids([10, 20, 30]).unwrap()
);
let foreign: (i64, Vec<u8>) = store
@@ -88,7 +88,7 @@ fn schema_nine_existing_store_and_runtime_smoke() {
);
for role in ["owner", "host"] {
let store = Store::open(&root.join(role)).unwrap();
assert_eq!(store.schema_version().unwrap(), 9);
assert_eq!(store.schema_version().unwrap(), 10);
let records = store.list_characters_all().unwrap();
assert!(!records.is_empty());
for record in records {
@@ -1013,16 +1013,22 @@ fn schema_1_item_mappings_survive_the_migration_as_unverified() {
fn collection_union_never_removes_and_unchanged_means_no_revision() {
let (mut store, profile) = fresh();
let kind = "coa:wardrobe";
assert!(store.collection(profile, kind).unwrap().is_none());
let ruleset = Ruleset::Coa;
assert!(store.collection(profile, ruleset, kind).unwrap().is_none());
// nothing stored, nothing incoming: nothing is created
let empty = store
.merge_collection(profile, kind, &IdSet::new())
.merge_collection(profile, ruleset, kind, &IdSet::new())
.unwrap();
assert!(!empty.changed && empty.info.is_none());
let first = store
.merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.merge_collection(
profile,
ruleset,
kind,
&IdSet::from_ids([10, 20, 30]).unwrap(),
)
.unwrap();
assert!(first.changed);
assert_eq!(first.added, 3);
@@ -1031,7 +1037,7 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
// another realm returns a subset: nothing is lost, nothing changes
let subset = store
.merge_collection(profile, kind, &IdSet::from_ids([20]).unwrap())
.merge_collection(profile, ruleset, kind, &IdSet::from_ids([20]).unwrap())
.unwrap();
assert!(!subset.changed);
assert_eq!(
@@ -1040,13 +1046,23 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
"same revision, same hash"
);
let same = store
.merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap())
.merge_collection(
profile,
ruleset,
kind,
&IdSet::from_ids([10, 20, 30]).unwrap(),
)
.unwrap();
assert!(!same.changed);
// a realm with new unlocks (and without the old ones) only adds
let more = store
.merge_collection(profile, kind, &IdSet::from_ids([30, 40, 5]).unwrap())
.merge_collection(
profile,
ruleset,
kind,
&IdSet::from_ids([30, 40, 5]).unwrap(),
)
.unwrap();
assert!(more.changed);
assert_eq!(more.added, 2);
@@ -1054,22 +1070,25 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() {
assert_eq!((info2.revision, info2.count), (2, 5));
assert_ne!(info2.hash, info1.hash);
let (info, set) = store.collection(profile, kind).unwrap().unwrap();
let (info, set) = store.collection(profile, ruleset, kind).unwrap().unwrap();
assert_eq!(set.ids(), &[5, 10, 20, 30, 40]);
assert_eq!(info, info2);
assert_eq!(
store.collection_info(profile, kind).unwrap().unwrap(),
store
.collection_info(profile, ruleset, kind)
.unwrap()
.unwrap(),
info2
);
// kinds are separate collections
assert!(store
.collection_info(profile, "coa:vanity")
.collection_info(profile, ruleset, "coa:vanity")
.unwrap()
.is_none());
assert!(
store
.merge_collection(profile, "wardrobe", &IdSet::new())
.merge_collection(profile, ruleset, "wardrobe", &IdSet::new())
.is_err(),
"kinds must be namespaced"
);
@@ -1085,7 +1104,9 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
] {
let ids: Vec<u32> = (0..count).map(|n| n * 7 + (n % 5)).collect();
let set = IdSet::from_ids(ids).unwrap();
let merge = store.merge_collection(profile, kind, &set).unwrap();
let merge = store
.merge_collection(profile, Ruleset::Coa, kind, &set)
.unwrap();
assert_eq!(merge.added, count as usize);
let stored_bytes: i64 = store
.conn
@@ -1099,7 +1120,10 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
stored_bytes < count as i64 * 2 + 16,
"{kind}: {count} ids took {stored_bytes} bytes"
);
let (_, back) = store.collection(profile, kind).unwrap().unwrap();
let (_, back) = store
.collection(profile, Ruleset::Coa, kind)
.unwrap()
.unwrap();
assert_eq!(back, set);
}
}
@@ -1108,7 +1132,12 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
fn a_tampered_collection_is_detected() {
let (mut store, profile) = fresh();
store
.merge_collection(profile, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap())
.merge_collection(
profile,
Ruleset::Coa,
"coa:vanity",
&IdSet::from_ids([1, 2, 3]).unwrap(),
)
.unwrap();
let forged = IdSet::from_ids([1, 2, 3, 4]).unwrap().encode();
store
@@ -1116,7 +1145,7 @@ fn a_tampered_collection_is_detected() {
.execute("UPDATE collection SET payload = ?1", [forged])
.unwrap();
assert!(matches!(
store.collection(profile, "coa:vanity"),
store.collection(profile, Ruleset::Coa, "coa:vanity"),
Err(PortableError::CorruptSnapshot(_))
));
}
@@ -2034,3 +2063,518 @@ fn a_store_that_holds_format_1_snapshots_reads_them_and_compares_them_by_what_th
);
assert_eq!(owner.load_current(id).unwrap(), other);
}
#[test]
fn released_v0_7_x_database_upgrades_transactionally_through_migration_009_and_accepts_reborn() {
let dir = tempfile::tempdir().unwrap();
let file = Store::path_of(dir.path());
let profile = ProfileId::new();
let char_coa = CharacterId::new();
let char_wc = CharacterId::new();
let item_coa = PortableItemId::new();
let now = "2026-10-22T12:00:00Z";
// Build realistic pre-multiruleset v0.7.x database (migrations 0..8)
{
let conn = Connection::open(&file).unwrap();
conn.pragma_update(None, "foreign_keys", true).unwrap();
for m in &MIGRATIONS[..8] {
conn.execute_batch(m).unwrap();
}
conn.pragma_update(None, "application_id", APPLICATION_ID)
.unwrap();
conn.pragma_update(None, "user_version", 8).unwrap();
// 1. Profile
conn.execute(
"INSERT INTO profile (profile_id, created_at, format_version) VALUES (?1, ?2, 1)",
params![profile.to_string(), now],
)
.unwrap();
// 2. Characters (CoA and Wildcard allowed in pre-009 schema)
conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'coa', 'Varian', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
params![char_coa.to_string(), profile.to_string(), now],
).unwrap();
conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'wildcard', 'RogueMage', 'coa:race:1', 'coa:class:4', 1, 60, 2, ?3, ?3, 0)",
params![char_wc.to_string(), profile.to_string(), now],
).unwrap();
// Verify pre-009 CHECK constraint rejects 'reborn'
let err = conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'Paladin', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)",
params![CharacterId::new().to_string(), profile.to_string(), now],
);
assert!(err.is_err(), "pre-009 schema must reject reborn");
// 3. Snapshots and revisions
conn.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'realm-a', ?3, 4, X'01020304', 'genesis')",
params![char_coa.to_string(), now, [0x42u8; 32]],
).unwrap();
// 4. Mappings and server bindings
conn.execute(
"INSERT INTO character_server_mapping (character_id, server_id, local_guid, last_revision, state, updated_at)
VALUES (?1, 'realm-a', 101, 1, 'active', ?2)",
params![char_coa.to_string(), now],
).unwrap();
conn.execute(
"INSERT INTO item_mapping (character_id, server_id, portable_item_id, local_item_guid, entry, identity, state, created_revision, confirmed_revision, created_at, updated_at)
VALUES (?1, 'realm-a', ?2, 202, 'item_entry', 'ident', 'active', 1, 1, ?3, ?3)",
params![char_coa.to_string(), item_coa.to_string(), now],
).unwrap();
// 5. Baseline session (realm_baseline)
conn.execute(
"INSERT INTO realm_baseline (character_id, server_id, c0_revision, head_revision, state, c0_hash, c0_payload, b0_hash, b0_payload, created_at, updated_at)
VALUES (?1, 'realm-a', 1, 1, 'open', ?2, X'AA', ?2, X'BB', ?3, ?3)",
params![char_coa.to_string(), [0x42u8; 32], now],
).unwrap();
// 6. Pre-009 Collection (single profile_id, kind PK)
conn.execute(
"INSERT INTO collection (profile_id, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
VALUES (?1, 'coa:appearance', 1, ?2, 1, 0, ?3, X'00')",
params![profile.to_string(), [0x42u8; 32], now],
).unwrap();
}
// Upgrade through Store::open_file (applies migration 009)
let store = Store::open_file(&file).unwrap();
assert_eq!(store.schema_version().unwrap(), 10);
// Verify all original rows and fields survived byte-for-byte and constraint-wise
let coa_rec = store.character(char_coa).unwrap();
assert_eq!(coa_rec.ruleset, Ruleset::Coa);
assert_eq!(coa_rec.name, "Varian");
assert_eq!(coa_rec.revision, 1);
assert_eq!(coa_rec.level, 80);
assert_eq!(coa_rec.created_at, now);
let wc_rec = store.character(char_wc).unwrap();
assert_eq!(wc_rec.ruleset, Ruleset::Wildcard);
assert_eq!(wc_rec.name, "RogueMage");
assert_eq!(wc_rec.revision, 2);
// Verify child tables survived without cascading drop
let server_maps = store.server_mappings(char_coa).unwrap();
assert_eq!(server_maps.len(), 1);
assert_eq!(server_maps[0].local_guid, 101);
let item_maps = store.item_mappings(char_coa, "realm-a").unwrap();
assert_eq!(item_maps.len(), 1);
assert_eq!(item_maps[0].portable_item_id, item_coa);
assert_eq!(item_maps[0].local_item_guid, 202);
// Verify collection migrated to composite key (profile_id, ruleset, kind)
let coll_info = store
.collection_info(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_info.revision, 1);
// Verify insertion of Reborn character succeeds now on migrated DB
let char_rb = CharacterId::new();
let rb_rec = store.conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'Mograine', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)",
params![char_rb.to_string(), profile.to_string(), now],
);
assert!(
rb_rec.is_ok(),
"migrated database must accept reborn ruleset"
);
let loaded_rb = store.character(char_rb).unwrap();
assert_eq!(loaded_rb.ruleset, Ruleset::Reborn);
assert_eq!(loaded_rb.name, "Mograine");
// Verify invalid ruleset is still rejected by CHECK constraint
let err = store.conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'invalid_ruleset', 'Bad', 'coa:race:1', 'coa:class:1', 0, 1, 1, ?3, ?3, 0)",
params![CharacterId::new().to_string(), profile.to_string(), now],
);
assert!(
err.is_err(),
"migrated database must reject invalid ruleset"
);
}
#[test]
fn mapping_isolation_between_coa_and_wildcard_on_same_installation() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
let mut model_coa = fixtures::geared_level_eighty();
model_coa.ruleset = Ruleset::Coa;
let char_coa = store
.create_character(profile, model_coa, "srv-1:coa")
.unwrap();
let mut model_wc = fixtures::geared_level_eighty();
model_wc.ruleset = Ruleset::Wildcard;
let char_wc = store
.create_character(profile, model_wc, "srv-1:wildcard")
.unwrap();
// 1. Both share local_guid = 100 on their respective server_id
store
.bind_server(char_coa, "srv-1:coa", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_wc, "srv-1:wildcard", 100, 1, MappingState::Active)
.unwrap();
// 2. Both share local_item_guid = 500 on their respective server_id
let item_coa = PortableItemId::new();
let item_wc = PortableItemId::new();
store
.reconcile_item_mappings(
char_coa,
"srv-1:coa",
1,
&[obs(item_coa, 500, 10, "entry1")],
)
.unwrap();
store
.reconcile_item_mappings(
char_wc,
"srv-1:wildcard",
1,
&[obs(item_wc, 500, 20, "entry2")],
)
.unwrap();
// Verify lookup isolation
assert_eq!(
store.find_by_local("srv-1:coa", 100).unwrap(),
Some(char_coa)
);
assert_eq!(
store.find_by_local("srv-1:wildcard", 100).unwrap(),
Some(char_wc)
);
let maps_coa = store.item_mappings(char_coa, "srv-1:coa").unwrap();
assert_eq!(maps_coa.len(), 1);
assert_eq!(maps_coa[0].portable_item_id, item_coa);
assert_eq!(maps_coa[0].local_item_guid, 500);
let maps_wc = store.item_mappings(char_wc, "srv-1:wildcard").unwrap();
assert_eq!(maps_wc.len(), 1);
assert_eq!(maps_wc[0].portable_item_id, item_wc);
assert_eq!(maps_wc[0].local_item_guid, 500);
}
#[test]
fn three_space_isolation_fixture_proves_wildcard_activity_leaves_coa_and_reborn_untouched() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
// Character A: CoA
let mut model_a = fixtures::geared_level_eighty();
model_a.identity.name = "Hero".into();
model_a.ruleset = Ruleset::Coa;
let char_a = store
.create_character(profile, model_a, "srv-1:coa")
.unwrap();
// Character B: Wildcard
let mut model_b = fixtures::geared_level_eighty();
model_b.identity.name = "Hero".into();
model_b.ruleset = Ruleset::Wildcard;
let char_b = store
.create_character(profile, model_b, "srv-1:wildcard")
.unwrap();
// Character C: Reborn
let mut model_c = fixtures::geared_level_eighty();
model_c.identity.name = "Hero".into();
model_c.ruleset = Ruleset::Reborn;
let char_c = store
.create_character(profile, model_c, "srv-1:reborn")
.unwrap();
// Initial identical mappings (local_guid = 100, item_guid = 200)
store
.bind_server(char_a, "srv-1:coa", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_b, "srv-1:wildcard", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_c, "srv-1:reborn", 100, 1, MappingState::Active)
.unwrap();
let item_a = PortableItemId::new();
let item_b = PortableItemId::new();
let item_c = PortableItemId::new();
store
.reconcile_item_mappings(char_a, "srv-1:coa", 1, &[obs(item_a, 200, 10, "e1")])
.unwrap();
store
.reconcile_item_mappings(char_b, "srv-1:wildcard", 1, &[obs(item_b, 200, 10, "e2")])
.unwrap();
store
.reconcile_item_mappings(char_c, "srv-1:reborn", 1, &[obs(item_c, 200, 10, "e3")])
.unwrap();
// Initial collections
store
.merge_collection(
profile,
Ruleset::Coa,
"coa:appearance",
&IdSet::from_ids([1, 2, 3]).unwrap(),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Wildcard,
"wildcard:appearance",
&IdSet::from_ids([1, 2, 4]).unwrap(),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Reborn,
"reborn:appearance",
&IdSet::from_ids([1, 2, 5]).unwrap(),
)
.unwrap();
// Record baseline hashes and revisions
let hash_a_before = store.load_snapshot(char_a, 1).unwrap();
let hash_c_before = store.load_snapshot(char_c, 1).unwrap();
// ---- MUTATE WILDCARD B ONLY ----
let mut model_b_mut = store.load_current(char_b).unwrap();
model_b_mut.progression.money += 100_000;
model_b_mut.progression.level = 80;
store
.commit_snapshot(
char_b,
1,
model_b_mut,
"srv-1:wildcard",
Some("wildcard gameplay"),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Wildcard,
"wildcard:appearance",
&IdSet::from_ids([1, 2, 4, 999]).unwrap(),
)
.unwrap();
let new_item_b = PortableItemId::new();
store
.reconcile_item_mappings(
char_b,
"srv-1:wildcard",
2,
&[
obs(item_b, 200, 10, "e2"),
obs(new_item_b, 201, 10, "e2_new"),
],
)
.unwrap();
// ---- ASSERT WILDCARD B ADVANCED ----
let rec_b = store.character(char_b).unwrap();
assert_eq!(rec_b.revision, 2);
let (_, coll_b) = store
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_b.ids(), &[1, 2, 4, 999]);
assert_eq!(
store.item_mappings(char_b, "srv-1:wildcard").unwrap().len(),
2
);
// ---- ASSERT COA A IS 100% UNTOUCHED ----
let rec_a = store.character(char_a).unwrap();
assert_eq!(rec_a.revision, 1);
let hash_a_after = store.load_snapshot(char_a, 1).unwrap();
assert_eq!(hash_a_before, hash_a_after);
let (_, coll_a) = store
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_a.ids(), &[1, 2, 3]);
let items_a = store.item_mappings(char_a, "srv-1:coa").unwrap();
assert_eq!(items_a.len(), 1);
assert_eq!(items_a[0].portable_item_id, item_a);
assert_eq!(items_a[0].local_item_guid, 200);
// ---- ASSERT REBORN C IS 100% UNTOUCHED ----
let rec_c = store.character(char_c).unwrap();
assert_eq!(rec_c.revision, 1);
let hash_c_after = store.load_snapshot(char_c, 1).unwrap();
assert_eq!(hash_c_before, hash_c_after);
let (_, coll_c) = store
.collection(profile, Ruleset::Reborn, "reborn:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_c.ids(), &[1, 2, 5]);
let items_c = store.item_mappings(char_c, "srv-1:reborn").unwrap();
assert_eq!(items_c.len(), 1);
assert_eq!(items_c[0].portable_item_id, item_c);
assert_eq!(items_c[0].local_item_guid, 200);
// ---- MUTATE REBORN C ONLY ----
let mut model_c_mut = store.load_current(char_c).unwrap();
model_c_mut.progression.money += 300_000;
model_c_mut.progression.level = 80;
store
.commit_snapshot(
char_c,
1,
model_c_mut,
"srv-1:reborn",
Some("reborn gameplay progression"),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Reborn,
"reborn:appearance",
&IdSet::from_ids([1, 2, 5, 8888]).unwrap(),
)
.unwrap();
let new_item_c = PortableItemId::new();
store
.reconcile_item_mappings(
char_c,
"srv-1:reborn",
2,
&[
obs(item_c, 200, 10, "e3"),
obs(new_item_c, 202, 10, "e3_new"),
],
)
.unwrap();
// ---- ASSERT REBORN C ADVANCED TO REV 2 ----
let rec_c2 = store.character(char_c).unwrap();
assert_eq!(rec_c2.revision, 2);
let (_, coll_c2) = store
.collection(profile, Ruleset::Reborn, "reborn:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_c2.ids(), &[1, 2, 5, 8888]);
assert_eq!(
store.item_mappings(char_c, "srv-1:reborn").unwrap().len(),
2
);
// ---- ASSERT COA A REMAINS 100% UNTOUCHED (STILL REV 1) ----
let rec_a2 = store.character(char_a).unwrap();
assert_eq!(rec_a2.revision, 1);
assert_eq!(store.load_snapshot(char_a, 1).unwrap(), hash_a_before);
let (_, coll_a2) = store
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_a2.ids(), &[1, 2, 3]);
assert_eq!(store.item_mappings(char_a, "srv-1:coa").unwrap().len(), 1);
// ---- ASSERT WILDCARD B REMAINS 100% UNTOUCHED (STILL REV 2) ----
let rec_b2 = store.character(char_b).unwrap();
assert_eq!(rec_b2.revision, 2);
let (_, coll_b2) = store
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_b2.ids(), &[1, 2, 4, 999]);
assert_eq!(
store.item_mappings(char_b, "srv-1:wildcard").unwrap().len(),
2
);
}
#[test]
fn reborn_store_corruption_fails_closed() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
// 1. summary = reborn + snapshot = coa
let mut model_coa = fixtures::geared_level_eighty();
model_coa.ruleset = Ruleset::Coa;
let enc_coa = crate::portable::snapshot::encode(&model_coa).unwrap();
// Insert corrupt summary with reborn ruleset but pointing to coa snapshot
let id_1 = CharacterId::new();
let at = "2026-10-22T12:00:00Z";
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_1.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test')",
rusqlite::params![id_1.to_string(), at, enc_coa.content_hash.as_slice(), enc_coa.payload.len() as i64, enc_coa.payload],
)
.unwrap();
// Loading current snapshot must FAIL CLOSED with ruleset mismatch error
let res1 = store.load_current(id_1);
assert!(
res1.is_err(),
"Loading reborn summary with CoA snapshot must fail closed"
);
// 2. summary = reborn + snapshot = wildcard
let mut model_wc = fixtures::geared_level_eighty();
model_wc.ruleset = Ruleset::Wildcard;
let enc_wc = crate::portable::snapshot::encode(&model_wc).unwrap();
let id_2 = CharacterId::new();
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn2', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_2.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test 2')",
rusqlite::params![id_2.to_string(), at, enc_wc.content_hash.as_slice(), enc_wc.payload.len() as i64, enc_wc.payload],
)
.unwrap();
let res2 = store.load_current(id_2);
assert!(
res2.is_err(),
"Loading reborn summary with Wildcard snapshot must fail closed"
);
}