feat(storage): let domain data own admission keys
This commit is contained in:
1 parent
c225f34333
commit
dc8b9864cd
10 files changed
+166
-54
No files matched your search
@@ -34,12 +34,19 @@ pub struct DomainMetadata {
|
||||
|
||||
impl DomainMetadata {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
self.clone().into_authority(vec![]).map(|_| ())
|
||||
}
|
||||
|
||||
pub fn into_authority(
|
||||
self,
|
||||
ice_servers: Vec<serde_json::Value>,
|
||||
) -> Result<Authority, &'static str> {
|
||||
if self.version != 1 {
|
||||
return Err("unsupported_backup_version");
|
||||
}
|
||||
let mut authority =
|
||||
Authority::new(self.owner_key.clone(), self.invite_key.clone(), vec![])?;
|
||||
authority.import_state(self.state.clone())
|
||||
let mut authority = Authority::new(self.owner_key, self.invite_key, ice_servers)?;
|
||||
authority.import_state(self.state)?;
|
||||
Ok(authority)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,21 @@ impl Authority {
|
||||
state
|
||||
}
|
||||
|
||||
/// Private hosting data for the domain's storage owner, never a client event.
|
||||
pub fn export_backup(&self) -> backup::DomainMetadata {
|
||||
backup::DomainMetadata {
|
||||
version: 1,
|
||||
state: self.export_state(),
|
||||
owner_key: self.channel.identity.owner_key.clone(),
|
||||
invite_key: self.channel.identity.invite_key.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The local App/Server bootstrap uses the key owned by the opened domain.
|
||||
pub fn owner_admission_key(&self) -> &str {
|
||||
&self.channel.identity.owner_key
|
||||
}
|
||||
|
||||
/// Host history/activity never rewrites the domain checkpoint. Only public
|
||||
/// directory changes and completed domain admission belong in that store.
|
||||
pub fn changes_metadata(&self, request: &Request) -> bool {
|
||||
|
||||
@@ -35,17 +35,18 @@ first, and rebuild it after changing the shared Rust core. From the repository
|
||||
root, start Rust in one terminal:
|
||||
|
||||
```powershell
|
||||
$env:PIIK_CHANNEL_OWNER_KEY = "<private stable owner key>"
|
||||
$env:PIIK_CHANNEL_INVITE_KEY = "<different private invitation key>"
|
||||
$env:PIIK_CHANNEL_OWNER_KEY = "<private owner seed for a new domain>"
|
||||
$env:PIIK_CHANNEL_INVITE_KEY = "<different invitation seed for a new domain>"
|
||||
$env:PIIK_CHANNEL_WEB_DIR = (Resolve-Path build/channel-web).Path
|
||||
$env:PIIK_CHANNEL_WEB_ORIGIN = "http://127.0.0.1:8790"
|
||||
cargo +1.91.0 run --manifest-path prototype/channel-server/Cargo.toml
|
||||
```
|
||||
|
||||
The values above are placeholders. Supply independently generated keys through
|
||||
your local environment and keep them stable when reopening persistent data.
|
||||
Keep them out of committed files and saved logs. Server does not print key-bearing URLs or
|
||||
store the raw startup keys in SQLite.
|
||||
The values above are placeholders. Supply independently generated seeds through
|
||||
your local environment when creating a domain. Thereafter the domain database
|
||||
owns its admission keys; changing or removing these environment variables does
|
||||
not rotate them. Keep both the keys and hosting backups private and out of
|
||||
committed files and saved logs. Server does not print key-bearing URLs.
|
||||
|
||||
In another terminal, start the development interface:
|
||||
|
||||
@@ -308,11 +309,11 @@ stop, unwatch and leave take effect locally and are reconciled on reconnect.
|
||||
Saved data belongs to its domain or room runtime. Server defaults to
|
||||
`data/channel.sqlite` beside its executable. `PIIK_CHANNEL_DATA_DIR` chooses a
|
||||
different real directory; point it at an existing source-run directory to reuse
|
||||
that data. The domain checkpoint stores catalog summaries and
|
||||
identities; `rooms/living.sqlite`, `rooms/studio.sqlite` and `rooms/quiet.sqlite`
|
||||
that data. The domain checkpoint stores catalog summaries, identities and its
|
||||
owner/invitation admission keys; `rooms/living.sqlite`, `rooms/studio.sqlite` and `rooms/quiet.sqlite`
|
||||
each store that room's policy, grants and confirmed history. Existing room names
|
||||
and policy are restored rather than overwritten by startup defaults. The Native
|
||||
endpoint authenticates with the configured owner key and restored owner identity;
|
||||
endpoint authenticates with that domain's saved owner key and restored owner identity;
|
||||
it does not create a new user on every service start.
|
||||
Browser-owned room policy and history stay in that Browser's IndexedDB; the
|
||||
domain retains only its directory summary. Messages
|
||||
@@ -320,11 +321,12 @@ commit individually: their room order, send identity and attachment descriptions
|
||||
are saved in one transaction before confirmation or distribution. A retry returns
|
||||
the original confirmed message without rebroadcasting it, including after restart.
|
||||
Storage failure leaves the send unconfirmed and preserves existing records.
|
||||
User credentials/invitations are stored as digests and room passwords as password
|
||||
hashes. Sessions, captures and routes are not restored after a process restart.
|
||||
User credentials and room invitations are stored as digests, and room passwords
|
||||
as password hashes. The domain's bootstrap keys are private hosting data.
|
||||
Sessions, captures and routes are not restored after a process restart.
|
||||
|
||||
This unpublished prototype uses domain checkpoint version 4 and room SQLite
|
||||
schema version 3. Older experimental
|
||||
This unpublished prototype uses hosting metadata version 1 around domain
|
||||
authority version 4, and room SQLite schema version 3. Older experimental
|
||||
checkpoints are rejected rather than silently discarding their history. Keep any
|
||||
old experiment's database and choose a fresh `PIIK_CHANNEL_DATA_DIR` for this version.
|
||||
|
||||
|
||||
@@ -222,13 +222,14 @@ async fn run(
|
||||
}
|
||||
let permission = Arc::new(Permission::new(identity.namespace));
|
||||
app.registry.lock().await.local = Some((origin.clone(), permission.clone()));
|
||||
let owner_key = domain.owner_key();
|
||||
let (stop_domain, mut domain_stopped) = watch::channel(false);
|
||||
let mut service = tokio::spawn(domain.serve_with_https(http, https, routes, async move {
|
||||
let _ = domain_stopped.changed().await;
|
||||
}));
|
||||
progress.send_replace(Progress::Ready(format!(
|
||||
"{origin}/?piik-client-port={}#owner={}&piik-client=1",
|
||||
app.port, identity.owner
|
||||
app.port, owner_key
|
||||
)));
|
||||
let (result, finished_service) = tokio::select! {
|
||||
_ = stopped.changed() => (Ok(()), None),
|
||||
|
||||
@@ -14,6 +14,7 @@ const APPROVAL_SCOPE: i64 = 2;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub(super) struct LocalIdentity {
|
||||
// Seeds for first creation only. The opened Domain owns its active keys.
|
||||
pub owner: String,
|
||||
pub invite: String,
|
||||
pub namespace: Uuid,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use anyhow::Context;
|
||||
use axum::{
|
||||
extract::{
|
||||
ws::{Message, WebSocket, WebSocketUpgrade},
|
||||
@@ -10,6 +11,7 @@ use axum::{
|
||||
};
|
||||
use futures_util::{stream::FuturesUnordered, FutureExt, Sink, SinkExt, StreamExt};
|
||||
use piik_channel_core::{
|
||||
backup::DomainMetadata,
|
||||
storage,
|
||||
wire::{Event, Request},
|
||||
Authority, Effects,
|
||||
@@ -69,7 +71,7 @@ impl Hub {
|
||||
.any(|(target, event)| *target == connection && matches!(event, Event::Error { .. }));
|
||||
if metadata && !failed {
|
||||
let checkpoint =
|
||||
serde_json::to_value(self.authority.export_state()).expect("typed metadata");
|
||||
serde_json::to_value(self.authority.export_backup()).expect("typed metadata");
|
||||
if self.storage.lock().unwrap().save(&checkpoint).is_err() {
|
||||
if room_projection {
|
||||
self.apply(effects);
|
||||
@@ -287,8 +289,8 @@ fn now() -> u64 {
|
||||
impl Domain {
|
||||
pub fn open(
|
||||
directory: &Path,
|
||||
owner: &str,
|
||||
invite: &str,
|
||||
owner_seed: &str,
|
||||
invite_seed: &str,
|
||||
origin: String,
|
||||
invitation_origin: Option<String>,
|
||||
ice_servers: Vec<serde_json::Value>,
|
||||
@@ -305,15 +307,17 @@ impl Domain {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
let mut storage = storage::Storage::open(&directory.join("channel.sqlite"))
|
||||
.map_err(anyhow::Error::from_boxed)?;
|
||||
let mut authority =
|
||||
Authority::new(owner.into(), invite.into(), ice_servers).map_err(anyhow::Error::msg)?;
|
||||
if let Some(checkpoint) = storage.load().map_err(anyhow::Error::from_boxed)? {
|
||||
authority
|
||||
.import_state(serde_json::from_value(checkpoint)?)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
let authority = match storage.load().map_err(anyhow::Error::from_boxed)? {
|
||||
Some(checkpoint) => serde_json::from_value::<DomainMetadata>(checkpoint)
|
||||
.context("unsupported_domain_checkpoint: preserve the existing data and use a supported backup or a fresh directory")?
|
||||
.into_authority(ice_servers)
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
None => Authority::new(owner_seed.into(), invite_seed.into(), ice_servers)
|
||||
.map_err(anyhow::Error::msg)
|
||||
.context("A new domain requires distinct owner and invitation seed keys")?,
|
||||
};
|
||||
storage
|
||||
.save(&serde_json::to_value(authority.export_state())?)
|
||||
.save(&serde_json::to_value(authority.export_backup())?)
|
||||
.map_err(anyhow::Error::from_boxed)?;
|
||||
Ok(Domain {
|
||||
hub: Arc::new(Mutex::new(Hub {
|
||||
@@ -345,6 +349,16 @@ impl Domain {
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Private local bootstrap only; this value never enters client state.
|
||||
pub fn owner_key(&self) -> String {
|
||||
self.hub
|
||||
.lock()
|
||||
.unwrap()
|
||||
.authority
|
||||
.owner_admission_key()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
pub async fn serve(
|
||||
self,
|
||||
listener: tokio::net::TcpListener,
|
||||
|
||||
@@ -24,7 +24,6 @@ pub async fn serve_server(
|
||||
listener: tokio::net::TcpListener,
|
||||
domain: Domain,
|
||||
directory: PathBuf,
|
||||
owner: String,
|
||||
routes: axum::Router,
|
||||
udp: Arc<ServerUdp>,
|
||||
stop: impl Future<Output = ()>,
|
||||
@@ -34,7 +33,7 @@ pub async fn serve_server(
|
||||
url: format!("ws://{}/prototype/channel", listener.local_addr()?),
|
||||
origin: domain.origin().into(),
|
||||
name: domain.owner_name().unwrap_or_else(|| "Piik Server".into()),
|
||||
key: Some(owner),
|
||||
key: Some(domain.owner_key()),
|
||||
credential: None,
|
||||
server_udp: Some(udp),
|
||||
};
|
||||
|
||||
@@ -25,10 +25,9 @@ async fn main() -> anyhow::Result<std::process::ExitCode> {
|
||||
.parse::<IpAddr>()
|
||||
.context("PIIK_CHANNEL_BIND_ADDRESS must be an IP address")?;
|
||||
let invitation_origin = std::env::var("PIIK_CHANNEL_INVITATION_ORIGIN").ok();
|
||||
let owner = std::env::var("PIIK_CHANNEL_OWNER_KEY")
|
||||
.context("Set PIIK_CHANNEL_OWNER_KEY to a private stable startup key")?;
|
||||
let invite = std::env::var("PIIK_CHANNEL_INVITE_KEY")
|
||||
.context("Set PIIK_CHANNEL_INVITE_KEY to a separate stable invitation key")?;
|
||||
// Existing domain data owns its keys; environment values seed a new domain.
|
||||
let owner = std::env::var("PIIK_CHANNEL_OWNER_KEY").unwrap_or_default();
|
||||
let invite = std::env::var("PIIK_CHANNEL_INVITE_KEY").unwrap_or_default();
|
||||
let ice_servers = piik_channel_prototype::ice_servers_from_environment()?;
|
||||
let executable = std::env::current_exe().context("Locate the Server executable")?;
|
||||
let resources = executable.parent().context("Locate the Server directory")?;
|
||||
@@ -95,9 +94,9 @@ async fn main() -> anyhow::Result<std::process::ExitCode> {
|
||||
)?;
|
||||
println!("Piik Server: http://{bound}");
|
||||
println!(
|
||||
"Web interface: {origin}/__channel-preview (use your configured owner or invitation key)"
|
||||
"Web interface: {origin}/__channel-preview (use this domain's owner or invitation key)"
|
||||
);
|
||||
release::startup_notice();
|
||||
serve_server(listener, state, directory, owner, routes, udp, stop).await?;
|
||||
serve_server(listener, state, directory, routes, udp, stop).await?;
|
||||
Ok(std::process::ExitCode::SUCCESS)
|
||||
}
|
||||
@@ -62,6 +62,60 @@ impl Endpoint {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_keys_belong_to_its_data_and_old_checkpoints_remain_untouched() {
|
||||
let folder = std::env::temp_dir().join(format!("piik-domain-keys-{}", Uuid::new_v4()));
|
||||
let open = |owner, invite| {
|
||||
Domain::open(
|
||||
&folder,
|
||||
owner,
|
||||
invite,
|
||||
"http://localhost".into(),
|
||||
None,
|
||||
vec![],
|
||||
)
|
||||
};
|
||||
let domain = open("saved-owner", "saved-invite").unwrap();
|
||||
let identity = domain.identity();
|
||||
let old_checkpoint;
|
||||
{
|
||||
let mut hub = domain.hub.lock().unwrap();
|
||||
let owner = Endpoint::join(&mut hub, "saved-owner");
|
||||
assert_eq!(owner.user, identity.1);
|
||||
old_checkpoint = serde_json::to_value(hub.authority.export_state()).unwrap();
|
||||
}
|
||||
drop(domain);
|
||||
for (owner_seed, invite_seed) in [("different-owner", "different-invite"), ("", "")] {
|
||||
let reopened = open(owner_seed, invite_seed).unwrap();
|
||||
assert_eq!(reopened.identity(), identity);
|
||||
assert_eq!(reopened.owner_key(), "saved-owner");
|
||||
let mut hub = reopened.hub.lock().unwrap();
|
||||
let owner = Endpoint::join(&mut hub, "saved-owner");
|
||||
assert_eq!(owner.user, identity.1);
|
||||
let mut rejected = Endpoint::connect(&mut hub);
|
||||
rejected.request(
|
||||
&mut hub,
|
||||
json!({"type":"join", "name":"Wrong seed", "key":"different-owner"}),
|
||||
);
|
||||
assert!(rejected
|
||||
.drain()
|
||||
.iter()
|
||||
.any(|event| event["type"] == "error"));
|
||||
}
|
||||
let mut store = storage::Storage::open(&folder.join("channel.sqlite")).unwrap();
|
||||
store.save(&old_checkpoint).unwrap();
|
||||
drop(store);
|
||||
assert!(open("saved-owner", "saved-invite")
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("unsupported_domain_checkpoint"));
|
||||
let store = storage::Storage::open(&folder.join("channel.sqlite")).unwrap();
|
||||
assert_eq!(store.load().unwrap().unwrap(), old_checkpoint);
|
||||
drop(store);
|
||||
std::fs::remove_dir_all(folder).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_metadata_requires_owner_and_commits_before_broadcast_then_reopens() {
|
||||
let path = std::env::temp_dir().join(format!("piik-domain-metadata-{}.sqlite", Uuid::new_v4()));
|
||||
@@ -103,7 +157,7 @@ fn domain_metadata_requires_owner_and_commits_before_broadcast_then_reopens() {
|
||||
original
|
||||
);
|
||||
assert_eq!(
|
||||
hub.storage.lock().unwrap().load().unwrap().unwrap(),
|
||||
hub.storage.lock().unwrap().load().unwrap().unwrap()["state"],
|
||||
original
|
||||
);
|
||||
database
|
||||
@@ -121,9 +175,9 @@ fn domain_metadata_requires_owner_and_commits_before_broadcast_then_reopens() {
|
||||
serde_json::from_value(state["state"].clone()).unwrap();
|
||||
drop(hub);
|
||||
let store = storage::Storage::open(&path).unwrap();
|
||||
let mut restored = Authority::new("owner".into(), "invite".into(), vec![]).unwrap();
|
||||
restored
|
||||
.import_state(serde_json::from_value(store.load().unwrap().unwrap()).unwrap())
|
||||
let restored = serde_json::from_value::<DomainMetadata>(store.load().unwrap().unwrap())
|
||||
.unwrap()
|
||||
.into_authority(vec![])
|
||||
.unwrap();
|
||||
let saved = serde_json::to_value(restored.export_state()).unwrap();
|
||||
assert_eq!(saved["name"], "Friends");
|
||||
@@ -292,7 +346,8 @@ fn directory_save_failure_cannot_restore_a_room_hosts_revoked_flows() {
|
||||
"the real room store committed first"
|
||||
);
|
||||
assert_eq!(
|
||||
hub.storage.lock().unwrap().load().unwrap().unwrap()["hostedRooms"]["hosted"]["access"],
|
||||
hub.storage.lock().unwrap().load().unwrap().unwrap()["state"]["hostedRooms"]["hosted"]
|
||||
["access"],
|
||||
"public",
|
||||
"the directory checkpoint really failed"
|
||||
);
|
||||
@@ -649,17 +704,9 @@ async fn start_server(
|
||||
let (stop, stopped) = oneshot::channel();
|
||||
let folder = folder.to_owned();
|
||||
let udp = piik_channel_native::peer::server_udp::ServerUdp::bind(&[(address, None)]).unwrap();
|
||||
let task = tokio::spawn(serve(
|
||||
listener,
|
||||
state,
|
||||
folder,
|
||||
"owner".into(),
|
||||
Router::new(),
|
||||
udp,
|
||||
async {
|
||||
let _ = stopped.await;
|
||||
},
|
||||
));
|
||||
let task = tokio::spawn(serve(listener, state, folder, Router::new(), udp, async {
|
||||
let _ = stopped.await;
|
||||
}));
|
||||
(address, stop, task, hub)
|
||||
}
|
||||
|
||||
|
||||
@@ -831,6 +831,7 @@ async fn app_host_outlives_its_page_and_restores_rooms_only_after_real_admission
|
||||
#[tokio::test]
|
||||
async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change() {
|
||||
use piik_channel_core::conversation::SessionSigner;
|
||||
use piik_channel_core::{backup::DomainMetadata, storage::Storage};
|
||||
use piik_channel_prototype::{app, web};
|
||||
use rtc_stun::{
|
||||
fingerprint::FINGERPRINT,
|
||||
@@ -949,7 +950,21 @@ async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change()
|
||||
assert_eq!(target.scheme(), "http");
|
||||
assert_eq!(target.host_str(), Some("127.0.0.1"));
|
||||
let identity = saved_identity();
|
||||
let owner = identity["owner"].as_str().unwrap();
|
||||
let metadata: DomainMetadata = serde_json::from_value(
|
||||
Storage::open(&folder.join("domain/channel.sqlite"))
|
||||
.unwrap()
|
||||
.load()
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let owner = metadata.owner_key.as_str();
|
||||
if attempt == 1 {
|
||||
assert_ne!(
|
||||
identity["owner"], owner,
|
||||
"the original seed is no longer active"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
url::form_urlencoded::parse(target.fragment().unwrap().as_bytes())
|
||||
.any(|(key, value)| key == "owner" && value == owner)
|
||||
@@ -1012,7 +1027,7 @@ async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change()
|
||||
let (mut guest, _) = connect_async(upgrade).await.unwrap();
|
||||
guest
|
||||
.send(Message::Text(
|
||||
json!({"type":"join","name":"LAN guest", "key":identity["invite"],
|
||||
json!({"type":"join","name":"LAN guest", "key":metadata.invite_key,
|
||||
"signingKey":SessionSigner::from_seed([31;32]).signing_key()})
|
||||
.to_string()
|
||||
.into(),
|
||||
@@ -1115,6 +1130,18 @@ async fn app_launch_retries_owns_one_domain_and_restores_it_after_port_change()
|
||||
retired_listeners.push(TcpListener::bind(lan_address).await.unwrap());
|
||||
retired_listeners.push(TcpListener::bind(address).await.unwrap());
|
||||
retired_stun.push(UdpSocket::bind(stun_address).await.unwrap());
|
||||
if attempt == 0 {
|
||||
// Emulate replacement of the stopped Domain's hosting record. The
|
||||
// next launcher URL and real guest admission must use these keys,
|
||||
// while App namespace and original creation seeds remain unchanged.
|
||||
let mut restored = metadata;
|
||||
restored.owner_key = Uuid::new_v4().to_string();
|
||||
restored.invite_key = Uuid::new_v4().to_string();
|
||||
Storage::open(&folder.join("domain/channel.sqlite"))
|
||||
.unwrap()
|
||||
.save(&serde_json::to_value(restored).unwrap())
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
drop(retired_listeners);
|
||||
drop(retired_stun);
|
||||
|
||||
Reference in new issue
Block a user