diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs index e1d00dd21..08abd7123 100644 --- a/crates/dg/src/auth/keys.rs +++ b/crates/dg/src/auth/keys.rs @@ -1,4 +1,4 @@ -//! `dg auth keys list | add | disable` (ux-dx-spec §2.4, §2.5, §9). +//! `dg auth keys list | add | disable | rotate` (ux-dx-spec §2.4, §2.5, §9). use std::path::PathBuf; @@ -24,7 +24,9 @@ pub enum KeysCommand { /// A limited key is what this computer then signs with (default: 0.25 DASH / 180 /// days, bound to dash-forge; `--replace ` disables the old one in the same update), or /// with --encryption the ENCRYPTION key private repositories need. Needs the master key once. - /// For a key to hand to CI use `dg auth export --new-key`. + /// For a key to hand to CI use `dg auth export --new-key`. With `--for-browser ` + /// the key is for a browser tab instead: dg prints it sealed to that tab, so the recovery + /// phrase never goes into a web page. Add(AddArgs), /// Disable a key on Platform. Needs the master key once. Disable { @@ -37,6 +39,25 @@ pub enum KeysCommand { #[arg(long)] force: bool, }, + /// Replace the encryption key after a lost device or a leak: add a new one from the recovery + /// phrase, move every private repository you maintain to it, then disable the old one. + /// + /// Repositories you don't maintain are listed, for a maintainer to move. Run it again to + /// continue after a failure. To replace a limited key, use `dg auth keys add --replace `. + Rotate { + /// Replace the ENCRYPTION key (the only key this command rotates). + #[arg(long, required = true)] + encryption: bool, + /// Keep the old key enabled (it still opens what was sealed for it). + #[arg(long)] + keep_old: bool, + /// The identity file with the master key and the recovery phrase (else you are asked for + /// the phrase). + #[arg(long, value_name = "FILE")] + master: Option, + #[command(flatten)] + storage: StorageArgs, + }, } impl KeysCommand { @@ -46,6 +67,7 @@ impl KeysCommand { KeysCommand::List => "could not list keys", KeysCommand::Add(_) => "key not added", KeysCommand::Disable { .. } => "key not disabled", + KeysCommand::Rotate { .. } => "encryption key not replaced", } } } @@ -54,13 +76,27 @@ impl KeysCommand { #[derive(Debug, clap::Args)] pub struct AddArgs { /// Add an ENCRYPTION key (for private repositories) instead of a limited key. - #[arg(long, conflicts_with_all = ["budget", "expires", "replace"])] + #[arg(long, conflicts_with_all = ["budget", "expires", "replace", "for_browser"])] pub encryption: bool, + /// Register a limited key for a browser tab and print it sealed to that tab: paste the + /// `dfkr1:` request the browser shows (Sign in → Use dg, or Renew). This computer keeps + /// signing with its own key. Default limits are the browser's: 0.05 DASH for 90 days. + #[arg(long, value_name = "REQUEST", conflicts_with = "keep_current")] + pub for_browser: Option, + /// With --for-browser: also hand over the identity's encryption key, so the browser opens + /// private repositories. + #[arg(long, requires = "for_browser")] + pub with_encryption_key: bool, + /// With --for-browser: the identity the browser asked a key for. dg refuses, before anything + /// is signed, to make the key for another identity. + #[arg(long, value_name = "IDENTITY_ID", requires = "for_browser")] + pub for_identity: Option, /// Bound to the `dash-forge` contract group (the only binding dg makes; kept for the /// spec's command line). #[arg(long, value_name = "GROUP", default_value = "dash-forge", value_parser = ["dash-forge"])] pub bound: String, - /// Disable this limited key in the same update (default: the one this computer signs with). + /// Disable this limited key in the same update (default: the one this computer signs with; + /// none with --for-browser). #[arg(long, value_name = "KEY_ID")] pub replace: Option, /// Keep the key this computer signs with now valid on Platform (it is no longer stored here). @@ -83,6 +119,12 @@ pub async fn run(ctx: &Ctx, cmd: &KeysCommand) -> Result<()> { KeysCommand::Disable { id, master, force } => { disable(ctx, *id, master.as_deref(), *force).await } + KeysCommand::Rotate { + encryption: _, + keep_old, + master, + storage, + } => super::rekey::rotate_encryption(ctx, master.as_deref(), storage, *keep_old).await, } } @@ -240,7 +282,283 @@ async fn add_encryption( Ok(()) } +/// The browser key defaults (`forge-web/lib/auth/limited-key.ts` `BROWSER_KEY_DEFAULTS`). +const BROWSER_KEY_BUDGET_DASH: f64 = 0.05; +const BROWSER_KEY_DAYS: u64 = 90; + +/// The flag that selects `network`, a network key (`testnet`, `mainnet`, `devnet-`). +fn network_flag(network: &str) -> String { + match network.strip_prefix("devnet-") { + Some(name) => format!("--devnet-name {name}"), + None => format!("--network {network}"), + } +} + +/// The browser's `dfkr1:` request, refused when it is not one or is for another network. +fn browser_request(ctx: &Ctx, text: &str) -> Result { + let request = forge_core::browser_key::parse_request(text).map_err(|e| { + UserError::new(codes::USAGE, "that is not a browser key request") + .cause(e.to_string()) + .fix("copy the whole command the browser shows, including the dfkr1:… request") + })?; + let network = ctx.network_label(); + if request.network != network { + return Err( + UserError::new(codes::USAGE, "the browser is on another network") + .cause(format!( + "the request is from a site on {}, and dg is on {network}", + request.network + )) + .fix(format!( + "run it again with {}", + network_flag(&request.network) + )) + .note("nothing was sent") + .into(), + ); + } + Ok(request) +} + +/// The encryption key `--with-encryption-key` hands over: the highest-id one `sources` (the +/// master source and the key dg signs with) open. +/// Checked before anything is paid for, so a key dg cannot hand over never leaves the browser +/// with a signing key and a promise. +fn handover_encryption_key( + ctx: &Ctx, + identity: &forge_core::platform::LoadedIdentity, + sources: &[&forge_core::keystore::BridgeIdentity], +) -> Result { + let storage = super::StorageArgs { + insecure_plaintext: false, + signing_only: false, + }; + let key = super::encryption_to_store(ctx, &storage, identity, sources) + .into_iter() + .max_by_key(|k| k.id) + .ok_or_else(|| { + UserError::new(codes::KEY_CANNOT_SIGN, "no encryption key to hand over") + .cause("this identity has no encryption key that the recovery words or the --master file open") + .fix("run it without --with-encryption-key, or add one first: `dg auth keys add --encryption`") + .note("nothing was sent") + })?; + Ok(forge_core::browser_key::EncryptionKey { + key_id: key.id, + private_key_hex: key.private_key_hex.expose().to_string(), + }) +} + +/// The longest a browser key may live (the web app's longest choice, TS-06). +const BROWSER_KEY_MAX_DAYS: u64 = 365; + +/// The master identity for `--for-browser`: `--master`, else the identity dg is signed in as, +/// else the recovery words (only when dg is not signed in at all: a key file that fails to +/// open is an error, not a reason to ask for the words). Refused when it is not `for_identity`. +async fn browser_master( + ctx: &Ctx, + client: &forge_core::platform::PlatformClient, + args: &AddArgs, +) -> Result<( + forge_core::keystore::BridgeIdentity, + Option, +)> { + let current = match ctx.identity_path { + Some(_) => Some(ctx.load_bridge()?), + None => None, + }; + let current_id = current.as_ref().map(|b| b.identity_id.clone()); + let master = match (¤t_id, &args.master) { + (None, None) => { + eprintln!("{}", super::MASTER_PROMPT); + let words = super::read_mnemonic()?; + super::identity_from_words(ctx, client, &words).await? + } + _ => master_identity( + ctx, + args.master.as_deref(), + current_id.as_deref().unwrap_or(""), + )?, + }; + if let Some(want) = &args.for_identity { + if *want != master.identity_id { + return Err( + UserError::new(codes::KEY_CANNOT_SIGN, "that is a different identity") + .cause(format!( + "the browser asked for a key of {want}, and dg would sign for {}", + master.identity_id + )) + .fix(format!("pass --master with the identity file of {want}")) + .note("nothing was sent") + .into(), + ); + } + } + Ok((master, current)) +} + +/// The key a reply carries, from the `dfk1:` text `register_limited_key` hands its `persist`. +fn handoff_payload( + network: &str, + dfk1: &forge_core::keystore::Secret, + replaced: Option, + encryption: Option<&forge_core::browser_key::EncryptionKey>, +) -> Result { + let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose())?; + let key = bridge.doc_op_key()?; + Ok(forge_core::browser_key::Payload { + v: 1, + network: network.to_string(), + identity_id: bridge.identity_id.clone(), + key_id: key.id, + wif: key.private_key_wif.expose().to_string(), + replaced_key_id: replaced, + encryption_key: encryption.map(|e| forge_core::browser_key::EncryptionKey { + key_id: e.key_id, + private_key_hex: e.private_key_hex.clone(), + }), + }) +} + +/// `dg auth keys add --for-browser ` (TS-06): register a limited key for a browser tab +/// and print it sealed to the tab's one-time key (`forge_core::browser_key`). Nothing is stored +/// here; this computer's own key is untouched unless `--replace` names it. +async fn add_for_browser(ctx: &Ctx, args: &AddArgs, request: &str) -> Result<()> { + let request = browser_request(ctx, request)?; + let network = ctx.network_label(); + let client = ctx.connect().await?; + let (master, current) = browser_master(ctx, &client, args).await?; + let identity = client.fetch_signer(&master).await?; + let encryption = if args.with_encryption_key { + let sources: Vec<_> = std::iter::once(&master).chain(current.as_ref()).collect(); + Some(handover_encryption_key(ctx, &identity, &sources)?) + } else { + None + }; + let spec = key_spec(ctx, &args.limits, BROWSER_KEY_BUDGET_DASH, BROWSER_KEY_DAYS)?; + if spec.expires_at_ms > super::expiry_ms(BROWSER_KEY_MAX_DAYS) { + return Err(crate::errors::usage(format!( + "a browser key lives at most {BROWSER_KEY_MAX_DAYS} days; pass --expires 365d or less" + ))); + } + let checked = super::check_group(ctx, &client, &spec.group, args.limits.strict_group()).await?; + super::explain_new_key(ctx, &master.identity_id, &spec, "for a browser", &checked); + explain_handover(ctx, args.replace, encryption.as_ref()); + ctx.confirm_or_cancel("Add the key?")?; + // The reply is sealed before anything is sent (as `register_limited_key` stores a key before + // it registers it), and again if the key lands under another id. + let seal = |dfk1: &forge_core::keystore::Secret| -> Result<(u32, String)> { + let payload = handoff_payload(&network, dfk1, args.replace, encryption.as_ref())?; + Ok(( + payload.key_id, + forge_core::browser_key::seal(&request, &payload)?, + )) + }; + let mut sealed: Option<(u32, String, forge_core::keystore::Secret)> = None; + let registered = super::register_limited_key( + ctx, + &client, + &master, + &spec, + args.replace, + &checked, + &mut |t| { + let (id, reply) = seal(t)?; + sealed = Some((id, reply, t.clone())); + Ok(()) + }, + ) + .await; + let (id, reply, unconfirmed) = match (registered, sealed) { + (Ok(id), Some((sealed_id, reply, _))) if id == sealed_id => (id, reply, None), + (Ok(id), _) => { + anyhow::bail!("internal error: key #{id} registered, but its reply was not sealed") + } + // The update errored but may have landed (a broadcast that timed out, a node behind): + // a key that is on chain is handed over, or nobody would hold it. + (Err(e), Some((_, _, dfk1))) => { + let Some(landed) = landed_key(ctx, &client, &network, &dfk1).await else { + return Err(e); + }; + let (id, reply) = seal(&landed)?; + (id, reply, Some(format!("{e:#}"))) + } + (Err(e), None) => return Err(e), + }; + ctx.emit( + json!({ + "status": "added", + "keyId": id, + "budgetCredits": spec.budget_credits, + "expiresAt": spec.expires_at_ms, + "replacedKeyId": args.replace, + "encryptionKeyId": encryption.as_ref().map(|e| e.key_id), + "reply": reply, + "warning": unconfirmed, + }), + || { + if let Some(why) = &unconfirmed { + eprintln!("note: the update reported an error ({why}), but key #{id} is on chain"); + } + eprintln!("✓ limited key #{id} added for the browser"); + if let Some(old) = args.replace { + eprintln!(" key #{old} disabled"); + } + eprintln!( + "Paste this line into the browser. It opens only in the tab that asked for it:" + ); + println!("{reply}"); + }, + ); + Ok(()) +} + +/// The key in `dfk1` under the id it is live with on chain (a `dfk1:` text again), if it landed. +async fn landed_key( + ctx: &Ctx, + client: &forge_core::platform::PlatformClient, + network: &str, + dfk1: &forge_core::keystore::Secret, +) -> Option { + let bridge = forge_core::keystore::BridgeIdentity::from_dfk1(dfk1.expose()).ok()?; + let wif = bridge.doc_op_key().ok()?.private_key_wif.clone(); + let identity = client.fetch_identity(&bridge.identity_id).await.ok()?; + let id = identity.key_id_for(wif.expose(), ctx.network())?; + Some(forge_core::keystore::dfk1( + network, + &bridge.identity_id, + id, + wif.expose(), + )) +} + +/// What else the update does (human mode): the key it disables, the encryption key it hands over. +fn explain_handover( + ctx: &Ctx, + replace: Option, + encryption: Option<&forge_core::browser_key::EncryptionKey>, +) { + if ctx.json { + return; + } + // Anyone can show a request: a look-alike page could ask for this command too. + eprintln!( + " run this only for a Forge page you opened yourself: the key can write to Forge as you" + ); + if let Some(old) = replace { + eprintln!(" key #{old} is disabled in the same update"); + } + if let Some(e) = encryption { + eprintln!( + " the browser also gets encryption key #{}: it opens your private repositories", + e.key_id + ); + } +} + async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { + if let Some(request) = &args.for_browser { + return add_for_browser(ctx, args, request).await; + } let current = ctx.load_bridge()?; let client = ctx.connect().await?; let master = master_identity(ctx, args.master.as_deref(), ¤t.identity_id)?; @@ -380,3 +698,14 @@ async fn disable(ctx: &Ctx, id: u32, master: Option<&std::path::Path>, force: bo ); Ok(()) } + +#[cfg(test)] +mod tests { + use super::network_flag; + + #[test] + fn the_network_flag_matches_the_browser_command() { + assert_eq!(network_flag("devnet-sakura"), "--devnet-name sakura"); + assert_eq!(network_flag("testnet"), "--network testnet"); + } +} diff --git a/crates/dg/src/auth/mod.rs b/crates/dg/src/auth/mod.rs index 031b78c89..4e6fc990a 100644 --- a/crates/dg/src/auth/mod.rs +++ b/crates/dg/src/auth/mod.rs @@ -14,6 +14,7 @@ pub mod group; mod keys; mod new; +mod rekey; pub mod store; use std::path::PathBuf; @@ -297,6 +298,8 @@ pub fn read_mnemonic() -> Result { .into(), ); } + // The same words before every phrase prompt, here and in the web app (TS-06). + eprintln!("{}", forge_core::browser_key::RECOVERY_PHRASE_WARNING); let words = rpassword::prompt_password("Recovery words (12, hidden as you type): ").map_err(|e| { // Ctrl-D or Ctrl-C: the user left, nothing was written (E803), not "no terminal". @@ -315,7 +318,7 @@ pub fn read_mnemonic() -> Result { /// What [`master_identity`] says before it asks for the recovery words: a user who signed in /// with an identity file has no words at hand, and `--master ` takes that file instead /// (L-34). -const MASTER_PROMPT: &str = +pub(crate) const MASTER_PROMPT: &str = "This needs your master key once. It is used for this one signature and not stored.\n\ Type your 12-word recovery phrase below, or press Ctrl-C and run the command again with \ --master (the file from the bridge, or a `dg auth new --backup-file`)."; @@ -360,7 +363,7 @@ pub fn master_identity( /// The identity's master identity loaded when only words are available and the id is unknown /// yet: derive, then find the identity by its master key on chain. -async fn identity_from_words( +pub(crate) async fn identity_from_words( ctx: &Ctx, client: &PlatformClient, words: &Secret, diff --git a/crates/dg/src/auth/rekey.rs b/crates/dg/src/auth/rekey.rs new file mode 100644 index 000000000..5f4215751 --- /dev/null +++ b/crates/dg/src/auth/rekey.rs @@ -0,0 +1,443 @@ +//! `dg auth keys rotate --encryption`: replace the identity's ENCRYPTION key +//! (`docs/security/private-repos.md` §5.2 "Rekey flow"), for a lost device or a leaked key. +//! +//! In order: add a new key at the next key id (derived from the recovery words, master-signed); +//! rotate every private repository this identity maintains so its new epoch is wrapped to the new +//! key (§5.5), and check that it was; name the repositories where it is only a member (a +//! maintainer's repair check moves them, §5.6); then disable every other enabled encryption key. +//! +//! Every run adds a fresh key and treats every enabled key as old: a lost device may have held +//! any of them, an earlier run's new key included. So a run that stopped half way is finished by +//! running it again, at the price of one more key add. + +use std::path::Path; + +use anyhow::{Context as _, Result}; +use serde_json::{json, Value}; + +use forge_core::keyring::{self, EncryptionKeys, PrivateSigner}; +use forge_core::keystore::BridgeIdentity; +use forge_core::platform::{identity_keys, LoadedIdentity}; +use forge_core::scope::RepoRef; +use forge_core::user_error::{codes, UserError}; + +use super::{master_identity, store, StorageArgs}; +use crate::context::Ctx; +use crate::fmt::{cost_json, cost_line}; + +/// What happened to one maintained repository. +enum Outcome { + /// Rotated, and its current epoch is wrapped to the new key. + Rotated(keyring::Rotation), + /// No longer a maintainer there: a maintainer must move it (like a member-only repository). + NotMaintainer, + /// Not moved to the new key (an error, or the current epoch still opens only with an old + /// key): the old keys stay enabled. + Failed(String), +} + +/// The rekey as it will run, worked out before anything is signed. +struct Plan { + id: String, + old_ids: Vec, + new_id: u32, + secret: identity_keys::EncryptionSecret, + members: keyring::PrivateMemberships, + keep_old: bool, +} + +/// What the run did, for the report. +struct Done<'a> { + plan: &'a Plan, + outcomes: Vec<(&'a RepoRef, Outcome)>, + disabled: Option>, + stored: Result, String>, +} + +impl Done<'_> { + fn failed(&self) -> bool { + self.outcomes + .iter() + .any(|(_, o)| matches!(o, Outcome::Failed(_))) + } + + /// The repositories a maintainer must move: member-only ones, and maintained ones where the + /// identity turned out not to be a maintainer any more. + fn ask_maintainer(&self) -> Vec<&RepoRef> { + self.plan + .members + .member_only + .iter() + .chain( + self.outcomes + .iter() + .filter(|(_, o)| matches!(o, Outcome::NotMaintainer)) + .map(|(r, _)| *r), + ) + .collect() + } +} + +pub(super) async fn rotate_encryption( + ctx: &Ctx, + master_file: Option<&Path>, + storage: &StorageArgs, + keep_old: bool, +) -> Result<()> { + let forge = ctx + .target + .v2 + .clone() + .context("Dash Forge is not deployed on this network")?; + let current = ctx.load_bridge()?; + let client = ctx.connect().await?; + let master = master_identity(ctx, master_file, ¤t.identity_id)?; + identity_keys::require_master_key(&master)?; + let identity = client.fetch_signer(&master).await?; + let plan = plan(ctx, &client, &forge, &master, &identity, keep_old).await?; + let price = ctx.usd_price(); + if !ctx.json { + print_plan(&plan, price); + } + ctx.confirm_or_cancel("Replace the key?")?; + let before = client.get_balance(&plan.id).await.unwrap_or(0); + + // 1. The new key. + let added = identity_keys::add_encryption_key(&client, &identity, &master, &plan.secret) + .await + .context("adding the new encryption key")?; + anyhow::ensure!( + added == plan.new_id, + "the new encryption key landed as #{added}, not #{}; run this again", + plan.new_id + ); + if !ctx.json { + println!("✓ added ENCRYPTION key #{added}"); + } + + // 2. Rotate every repository this identity maintains, signing with the key in use and + // holding every encryption key: an old one opens the current epoch, the new one is the + // highest enabled key, so the new epoch is wrapped to it (self first). + let signing = client.fetch_signer(¤t).await?; + let work = holding_every_encryption_key(¤t, &master, &signing, &forge.core, ctx); + let signer = PrivateSigner { + client: &client, + identity: &signing, + bridge: &work, + }; + let mut done = Done { + plan: &plan, + outcomes: Vec::new(), + disabled: None, + stored: Ok(None), + }; + for repo in &plan.members.maintained { + let outcome = rotate_one(&signer, repo, plan.new_id).await; + if !ctx.json { + print_outcome(repo, &outcome); + } + done.outcomes.push((repo, outcome)); + } + + // 3. The old keys: disabled once every maintained repository is on the new key. + if !done.failed() && !keep_old && !plan.old_ids.is_empty() { + let wif = &master + .master_key() + .context("no master key")? + .private_key_wif; + client + .update_identity_keys(&plan.id, wif, &[], &plan.old_ids) + .await + .context("disabling the old encryption key")?; + done.disabled = Some(plan.old_ids.clone()); + } + + // 4. The key this computer stores: its encryption keys now include the new one. Everything + // above is on chain already, so a failure here is reported, not raised. + done.stored = restore_login(ctx, storage, ¤t, &work).map_err(|e| format!("{e:#}")); + let spent = crate::common::spent_since(&client, &plan.id, before).await; + ctx.emit(report_json(&done, &cost_json(spent, price)), || { + print_done(&done, &cost_line(spent, price)); + }); + if done.failed() { + return Err( + UserError::new(codes::PARTIAL, "not every repository moved to the new key") + .cause("the old encryption keys stay enabled, so nothing is lost") + .fix("run `dg auth keys rotate --encryption` again: it adds a fresh key and moves every repository to it") + .into(), + ); + } + Ok(()) +} + +/// Which keys go and which comes, and the repositories it touches. +async fn plan( + ctx: &Ctx, + client: &forge_core::platform::PlatformClient, + forge: &forge_core::network::ForgeIds, + master: &BridgeIdentity, + identity: &LoadedIdentity, + keep_old: bool, +) -> Result { + let id = identity.id(); + let mut old_ids: Vec = identity + .public_keys() + .into_iter() + .filter(|k| k.is_usable_encryption_key(&forge.core)) + .map(|k| k.id) + .collect(); + old_ids.sort_unstable(); + if old_ids.is_empty() { + return Err(UserError::new( + codes::NO_ENCRYPTION_KEY, + "there is no encryption key to replace", + ) + .cause(format!("identity {id} has no enabled ENCRYPTION key")) + .fix("add one: `dg auth keys add --encryption`") + .into()); + } + if !identity_keys::recorded_keys_match(master, &identity.public_keys()) { + return Err(words_needed()); + } + let new_id = identity_keys::next_key_id(identity); + let secret = identity_keys::derive_encryption_secret(master, new_id, ctx.network()) + .ok_or_else(words_needed)?; + let members = keyring::private_memberships(client, forge, &id).await?; + Ok(Plan { + id, + old_ids, + new_id, + secret, + members, + keep_old, + }) +} + +fn words_needed() -> anyhow::Error { + UserError::new( + codes::KEY_CANNOT_SIGN, + "the new encryption key cannot be derived from what was given", + ) + .cause("a new key must come from the identity's recovery words, so that they alone recover it; the master key source given does not hold words that reproduce the identity's keys") + .fix("pass --master with the recovery words in it") + .fix("or sign in with a limited key (`dg auth login`), then run it again and type the words when asked") + .note("nothing was sent") + .into() +} + +/// `current` (the key this computer signs with) holding, in memory, every encryption key the +/// master source's words derive for the identity, old and new. What is stored afterwards is +/// decided by [`restore_login`]. +fn holding_every_encryption_key( + current: &BridgeIdentity, + master: &BridgeIdentity, + identity: &LoadedIdentity, + core: &str, + ctx: &Ctx, +) -> BridgeIdentity { + let on_chain = identity.public_keys(); + let mut keys = std::collections::BTreeMap::new(); + for source in [master, current] { + for k in EncryptionKeys::held(source, &on_chain, core, ctx.network()) + .to_identity_keys(ctx.network()) + { + keys.entry(k.id).or_insert(k); + } + } + let mut work = current.clone(); + work.identity_keys.retain(|k| k.purpose != "ENCRYPTION"); + work.identity_keys.extend(keys.into_values()); + work +} + +/// Rotate `repo`, then check, from a fresh read, that this identity's wrap for the current epoch +/// went to `new_id`: a resumed epoch can keep an earlier self-wrap to an old key, and another +/// maintainer's concurrent anchor may have been wrapped before the new key existed. +async fn rotate_one(signer: &PrivateSigner<'_>, repo: &RepoRef, new_id: u32) -> Outcome { + match keyring::rotate(signer, repo, &[]).await { + Ok(r) => match signer.keyring(repo).await { + Ok(kr) if kr.own_current_wrap_keys().contains(&new_id) => Outcome::Rotated(r), + Ok(kr) => Outcome::Failed(format!( + "its current key epoch {} is still wrapped to your old key, not #{new_id}", + kr.resolution().current_epoch.unwrap_or_default() + )), + Err(e) => Outcome::Failed(format!("rotated, but reading it back failed: {e}")), + }, + Err(forge_core::Error::NotPermitted { .. }) => Outcome::NotMaintainer, + Err(e) => Outcome::Failed(e.to_string()), + } +} + +/// Store the key in use again with the new encryption key beside it, in the same place, when it +/// is dg's own stored limited key (`dg auth login`) and kept encryption keys there. A full +/// identity is never re-stored (its words derive the new key by themselves), nor a key file of +/// the user's own, nor a plaintext one (encryption keys are never written in the clear). +fn restore_login( + ctx: &Ctx, + storage: &StorageArgs, + current: &BridgeIdentity, + work: &BridgeIdentity, +) -> Result> { + let Some(path) = ctx.identity_path.as_ref() else { + return Ok(None); + }; + let source = path.to_string_lossy(); + let kept_encryption = current + .identity_keys + .iter() + .any(|k| k.purpose == "ENCRYPTION"); + if storage.signing_only + || storage.insecure_plaintext + || !kept_encryption + || current.master_key().is_some() + { + return Ok(None); + } + let network = ctx.network_label(); + let Some(mut writer) = store::main_slot_storer(&network, ¤t.identity_id, &source)? else { + return Ok(None); + }; + let stored = writer + .store( + &network, + ¤t.identity_id, + &work.to_json_with_secrets(), + store::Slot::Main, + ) + .context("storing the new encryption key beside the key in use")?; + Ok(Some(stored)) +} + +fn names(repos: &[&RepoRef]) -> String { + repos + .iter() + .map(|r| r.display()) + .collect::>() + .join(", ") +} + +fn ids(ids: &[u32]) -> String { + ids.iter() + .map(|i| format!("#{i}")) + .collect::>() + .join(", ") +} + +fn print_plan(plan: &Plan, price: Option) { + let (id, new_id, members) = (&plan.id, plan.new_id, &plan.members); + let maintained: Vec<&RepoRef> = members.maintained.iter().collect(); + let member_only: Vec<&RepoRef> = members.member_only.iter().collect(); + let estimate = identity_keys::ADD_KEY_ESTIMATE_CREDITS + + maintained.len() as u64 * crate::keys::rotation_estimate(2).0; + println!( + "Replace the encryption key {} of {id} with a new key #{new_id}, derived from the recovery phrase:", + ids(&plan.old_ids) + ); + println!(" 1. add key #{new_id} (one identity update, signed by the master key)"); + if maintained.is_empty() { + println!(" 2. no private repository you maintain needs rotating"); + } else { + println!( + " 2. rotate the key of the {} private repo(s) you maintain, so new content is sealed for key #{new_id}: {}", + maintained.len(), + names(&maintained) + ); + } + if !member_only.is_empty() { + println!( + " {} repo(s) where you are not a maintainer keep using the old key until a maintainer moves them (their next visit does it): {}", + member_only.len(), + names(&member_only) + ); + } + if plan.keep_old { + println!(" 3. keep {} enabled (--keep-old)", ids(&plan.old_ids)); + } else { + println!( + " 3. disable {}: whoever holds it can no longer read what is sealed from now on (past content stays readable to them)", + ids(&plan.old_ids) + ); + } + println!( + " about {} (two members a repo assumed)", + cost_line(estimate, price) + ); +} + +fn print_outcome(repo: &RepoRef, o: &Outcome) { + match o { + Outcome::Rotated(r) => crate::keys::print_rotation(repo, r), + Outcome::NotMaintainer => println!( + "{}: you are no longer a maintainer; a maintainer must move it", + repo.display() + ), + Outcome::Failed(e) => eprintln!("{}: not moved to the new key: {e}", repo.display()), + } +} + +fn print_done(done: &Done<'_>, cost: &str) { + let plan = done.plan; + let new_id = plan.new_id; + if let Some(d) = &done.disabled { + println!( + "✓ disabled {}; private repos now use key #{new_id} · {cost}", + ids(d) + ); + } else if done.failed() { + println!( + " {} stay enabled until every repository moved · {cost}", + ids(&plan.old_ids) + ); + } else { + println!( + " {} stay enabled (--keep-old) · {cost}", + ids(&plan.old_ids) + ); + } + match &done.stored { + Ok(Some(s)) => println!( + " this computer now keeps key #{new_id} too, in {}", + s.describe() + ), + Ok(None) => {} + Err(e) => eprintln!( + "warning: key #{new_id} could not be stored on this computer ({e}); sign in again with `dg auth login` to keep it" + ), + } + let ask = done.ask_maintainer(); + if !ask.is_empty() { + println!( + " ask a maintainer of {} to move it to your new key (`dg repo keys repair `); until then new content there is sealed for the old key", + names(&ask) + ); + } + println!(" other browsers and computers: add the new key from the recovery phrase (web: Settings → Private repos)"); +} + +fn report_json(done: &Done<'_>, cost: &Value) -> Value { + let plan = done.plan; + let repos: Vec = done + .outcomes + .iter() + .map(|(repo, o)| { + let (status, detail) = match o { + Outcome::Rotated(r) => ("rotated", crate::keys::rotation_json(r)), + Outcome::NotMaintainer => ("not_maintainer", Value::Null), + Outcome::Failed(e) => ("failed", json!(e)), + }; + json!({ "repo": repo.display(), "repoId": repo.id(), "status": status, "detail": detail }) + }) + .collect(); + json!({ + "status": if done.disabled.is_some() { "replaced" } else { "added" }, + "identityId": plan.id, + "oldKeyIds": plan.old_ids, + "newKeyId": plan.new_id, + "repos": repos, + "askMaintainer": done.ask_maintainer().iter().map(|r| json!({ "repo": r.display(), "repoId": r.id() })).collect::>(), + "disabledKeyIds": done.disabled, + "storedAt": done.stored.as_ref().ok().and_then(Option::as_ref).map(store::Stored::describe), + "storeError": done.stored.as_ref().err(), + "cost": cost, + }) +} diff --git a/crates/dg/src/auth/store.rs b/crates/dg/src/auth/store.rs index d990d5b0f..75c00934d 100644 --- a/crates/dg/src/auth/store.rs +++ b/crates/dg/src/auth/store.rs @@ -245,6 +245,26 @@ fn passphrase_reason(why: &str) -> String { ) } +/// A storer that writes back to `source` when it is this identity's main slot (dg's own +/// keychain entry, or its passphrase-sealed key file), else `None` (a key file or inline key of +/// the user's own, or a plaintext one: those are left alone). The keychain entry is written to +/// the keychain again, the sealed file to a sealed file. +pub fn main_slot_storer(network: &str, identity_id: &str, source: &str) -> Result> { + let keychain_source = format!( + "{}{}/{}", + keystore::KEYCHAIN_PREFIX, + keychain::SERVICE, + account(network, identity_id, Slot::Main) + ); + if source == keychain_source { + return Ok(Some(Storer::new(false))); + } + let main = slot_file(network, identity_id, Slot::Main)?; + let sealed_here = std::path::Path::new(source) == main + && std::fs::read_to_string(&main).is_ok_and(|raw| sealed::is_sealed(&raw)); + Ok(sealed_here.then(|| Storer::sealed_only(false))) +} + /// Store a limited key in the main slot (one-off). pub fn store( network: &str, diff --git a/crates/forge-core/src/browser_key.rs b/crates/forge-core/src/browser_key.rs new file mode 100644 index 000000000..161b9acbb --- /dev/null +++ b/crates/forge-core/src/browser_key.rs @@ -0,0 +1,403 @@ +//! Handing a limited key from `dg` to a browser tab, so the recovery phrase never reaches a web +//! page (trust and safety TS-06; `docs/contracts/forge-v2.md` "Key handoff"). +//! +//! 1. The browser draws a one-time secp256k1 key pair and shows its public half as a +//! **request**: `dfkr1::`. +//! 2. `dg auth keys add --for-browser ` registers a limited key (signed by the master +//! key on the terminal) and prints a **reply** sealed to that public key: +//! `dfkh1::`. +//! 3. The browser opens the reply with its one-time private key, checks the key on chain and +//! keeps it in its vault. +//! +//! The AES key is `HKDF-SHA256(ikm = x(ECDH), salt = ephemeral public ‖ request public, +//! info = "dash-forge/key-handoff/1")`; the associated data is `"dfkh1:" ‖ network`, so a reply +//! for one network does not open on another. The plaintext is a JSON object +//! ([`Payload`]). The reply is useless to anyone without the browser's one-time private key, so +//! it may be printed and pasted; the key it carries is still a limited key, which is the point. +//! +//! The browser side is `forge-web/lib/auth/key-handoff.ts`; both run the +//! `key_handoff_*` conformance vectors. + +use aes_gcm::aead::{Aead as _, Payload as AeadPayload}; +use aes_gcm::{Aes256Gcm, KeyInit as _, Nonce}; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine as _; +use hkdf::Hkdf; +use secp256k1::{PublicKey, SecretKey}; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; +use zeroize::Zeroizing; + +use crate::error::{Error, Result}; + +/// The prefix of a browser's request. +pub const REQUEST_PREFIX: &str = "dfkr1:"; +/// The prefix of `dg`'s reply. +pub const REPLY_PREFIX: &str = "dfkh1:"; +/// The HKDF `info` of the reply key. +const INFO: &[u8] = b"dash-forge/key-handoff/1"; +/// The largest plaintext a reply carries (a key, an encryption key and their ids fit in 400 B). +const MAX_PAYLOAD: usize = 2048; + +/// The fixed warning shown before every recovery-phrase prompt, in `dg` and in the web app +/// (TS-06; vector `copy__recovery_phrase_warning`). +pub const RECOVERY_PHRASE_WARNING: &str = + "Your recovery phrase controls your identity. Forge asks \ +for it only after you start a key action yourself, never because a message, an email or a pop-up \ +says so. If you didn't start this, stop here."; + +/// A browser's request: the network it is on and its one-time public key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Request { + /// The network key (`sakura`, `testnet`, …). + pub network: String, + /// The browser's one-time public key. + pub public_key: PublicKey, +} + +fn bad_request(why: &str) -> Error { + Error::Config(format!( + "that is not a browser key request ({why}); copy the whole dfkr1:… line the browser shows" + )) +} + +fn valid_network(n: &str) -> bool { + !n.is_empty() && n.len() <= 32 && n.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') +} + +/// Parse a `dfkr1:` request. +pub fn parse_request(text: &str) -> Result { + let rest = text + .trim() + .strip_prefix(REQUEST_PREFIX) + .ok_or_else(|| bad_request("it does not start with dfkr1:"))?; + let (network, key) = rest + .split_once(':') + .ok_or_else(|| bad_request("it has no network"))?; + if !valid_network(network) { + return Err(bad_request("the network is not a network name")); + } + let bytes = URL_SAFE_NO_PAD + .decode(key) + .map_err(|_| bad_request("the key is not base64url"))?; + if bytes.len() != 33 { + return Err(bad_request("the key is not a compressed public key")); + } + let public_key = + PublicKey::from_slice(&bytes).map_err(|_| bad_request("the key is not on the curve"))?; + Ok(Request { + network: network.to_string(), + public_key, + }) +} + +/// The `dfkr1:` text of a request (the browser makes these; here for tests). +pub fn request_text(network: &str, public_key: &PublicKey) -> String { + format!( + "{REQUEST_PREFIX}{network}:{}", + URL_SAFE_NO_PAD.encode(public_key.serialize()) + ) +} + +/// The key the reply carries. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Payload { + /// Always 1. + pub v: u32, + /// The network key; equal to the request's. + pub network: String, + /// The identity the key belongs to. + pub identity_id: String, + /// The new limited key's id on the identity. + pub key_id: u32, + /// Its private key, WIF. + pub wif: String, + /// The limited key it replaced (disabled in the same update), if any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replaced_key_id: Option, + /// The identity's encryption key, when the user chose to hand it over too. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub encryption_key: Option, +} + +/// An `ENCRYPTION` key in a [`Payload`]. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EncryptionKey { + /// Its id on the identity. + pub key_id: u32, + /// The private key, 64 hex characters. + pub private_key_hex: String, +} + +impl Drop for Payload { + fn drop(&mut self) { + use zeroize::Zeroize as _; + self.wif.zeroize(); + } +} + +impl Drop for EncryptionKey { + fn drop(&mut self) { + use zeroize::Zeroize as _; + self.private_key_hex.zeroize(); + } +} + +impl std::fmt::Debug for EncryptionKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EncryptionKey") + .field("key_id", &self.key_id) + .finish_non_exhaustive() + } +} + +impl std::fmt::Debug for Payload { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Payload") + .field("network", &self.network) + .field("identity_id", &self.identity_id) + .field("key_id", &self.key_id) + .finish_non_exhaustive() + } +} + +/// The AES key for a reply between `ephemeral` (dg's) and `request` (the browser's) keys. +fn reply_key(shared_x: &[u8], ephemeral: &PublicKey, request: &PublicKey) -> Zeroizing<[u8; 32]> { + let mut salt = [0u8; 66]; + salt[..33].copy_from_slice(&ephemeral.serialize()); + salt[33..].copy_from_slice(&request.serialize()); + let hk = Hkdf::::new(Some(&salt), shared_x); + let mut key = Zeroizing::new([0u8; 32]); + hk.expand(INFO, key.as_mut()) + .expect("32 bytes is a valid HKDF-SHA256 length"); + key +} + +fn shared_x(point: &PublicKey, scalar: &SecretKey) -> Zeroizing<[u8; 32]> { + let full = Zeroizing::new(secp256k1::ecdh::shared_secret_point(point, scalar)); + let mut x = Zeroizing::new([0u8; 32]); + x.copy_from_slice(&full[..32]); + x +} + +fn aad(network: &str) -> Vec { + format!("{REPLY_PREFIX}{network}").into_bytes() +} + +/// Seal `payload` for `request` with a fresh ephemeral key and nonce. +pub fn seal(request: &Request, payload: &Payload) -> Result { + let mut eph = Zeroizing::new([0u8; 32]); + let mut nonce = [0u8; 12]; + loop { + getrandom::getrandom(eph.as_mut()) + .map_err(|e| Error::Config(format!("no randomness: {e}")))?; + if SecretKey::from_slice(eph.as_ref()).is_ok() { + break; + } + } + getrandom::getrandom(&mut nonce).map_err(|e| Error::Config(format!("no randomness: {e}")))?; + seal_with(request, payload, &eph, nonce) +} + +/// [`seal`] with a given ephemeral secret and nonce (conformance vectors). +pub fn seal_with( + request: &Request, + payload: &Payload, + ephemeral_secret: &[u8; 32], + nonce: [u8; 12], +) -> Result { + if payload.network != request.network { + return Err(Error::Config(format!( + "the key is for {}, but the browser is on {}", + payload.network, request.network + ))); + } + let plain = Zeroizing::new( + serde_json::to_vec(payload).map_err(|e| Error::Config(format!("payload: {e}")))?, + ); + seal_bytes(request, &plain, ephemeral_secret, nonce) +} + +/// Seal raw plaintext bytes (the vectors fix them byte for byte). +pub fn seal_bytes( + request: &Request, + plain: &[u8], + ephemeral_secret: &[u8; 32], + nonce: [u8; 12], +) -> Result { + if plain.len() > MAX_PAYLOAD { + return Err(Error::Config("the key handoff is too large".into())); + } + let secp = secp256k1::Secp256k1::new(); + let eph = SecretKey::from_slice(ephemeral_secret) + .map_err(|_| Error::Config("bad ephemeral key".into()))?; + let eph_pub = PublicKey::from_secret_key(&secp, &eph); + let x = shared_x(&request.public_key, &eph); + let key = reply_key(x.as_ref(), &eph_pub, &request.public_key); + let cipher = Aes256Gcm::new_from_slice(key.as_ref()).expect("32-byte key"); + let aad = aad(&request.network); + let ct = cipher + .encrypt( + Nonce::from_slice(&nonce), + AeadPayload { + msg: plain, + aad: &aad, + }, + ) + .map_err(|_| Error::Config("sealing the key handoff failed".into()))?; + let mut out = Vec::with_capacity(33 + 12 + ct.len()); + out.extend_from_slice(&eph_pub.serialize()); + out.extend_from_slice(&nonce); + out.extend_from_slice(&ct); + Ok(format!( + "{REPLY_PREFIX}{}:{}", + request.network, + URL_SAFE_NO_PAD.encode(out) + )) +} + +/// Why a reply does not open. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OpenError { + /// Not a `dfkh1:` reply, or cut short. + Malformed, + /// Made for another network. + Network, + /// Not sealed to this request's key, or altered. + Unreadable, +} + +/// Open a reply with the browser's one-time `secret` (the browser does this; here for tests and +/// for the vectors). Returns the plaintext bytes. +pub fn open( + reply: &str, + network: &str, + secret: &[u8; 32], +) -> std::result::Result>, OpenError> { + let rest = reply + .trim() + .strip_prefix(REPLY_PREFIX) + .ok_or(OpenError::Malformed)?; + let (net, body) = rest.split_once(':').ok_or(OpenError::Malformed)?; + if !valid_network(net) { + return Err(OpenError::Malformed); + } + if net != network { + return Err(OpenError::Network); + } + let bytes = URL_SAFE_NO_PAD + .decode(body) + .map_err(|_| OpenError::Malformed)?; + if bytes.len() < 33 + 12 + 16 { + return Err(OpenError::Malformed); + } + let eph_pub = PublicKey::from_slice(&bytes[..33]).map_err(|_| OpenError::Malformed)?; + let mine = SecretKey::from_slice(secret).map_err(|_| OpenError::Unreadable)?; + let secp = secp256k1::Secp256k1::new(); + let my_pub = PublicKey::from_secret_key(&secp, &mine); + let x = shared_x(&eph_pub, &mine); + let key = reply_key(x.as_ref(), &eph_pub, &my_pub); + let cipher = Aes256Gcm::new_from_slice(key.as_ref()).expect("32-byte key"); + let aad = aad(net); + cipher + .decrypt( + Nonce::from_slice(&bytes[33..45]), + AeadPayload { + msg: &bytes[45..], + aad: &aad, + }, + ) + .map(Zeroizing::new) + .map_err(|_| OpenError::Unreadable) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn browser() -> ([u8; 32], Request) { + let secret = [7u8; 32]; + let secp = secp256k1::Secp256k1::new(); + let pk = PublicKey::from_secret_key(&secp, &SecretKey::from_slice(&secret).unwrap()); + ( + secret, + Request { + network: "sakura".into(), + public_key: pk, + }, + ) + } + + fn payload(network: &str) -> Payload { + Payload { + v: 1, + network: network.into(), + identity_id: "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB".into(), + key_id: 7, + wif: "cTestWif".into(), + replaced_key_id: Some(5), + encryption_key: None, + } + } + + #[test] + fn a_request_round_trips_and_garbage_is_refused() { + let (_, req) = browser(); + let text = request_text("sakura", &req.public_key); + assert_eq!(parse_request(&text).unwrap(), req); + assert_eq!(parse_request(&format!(" {text}\n")).unwrap(), req); + for bad in [ + "", + "dfkr1:", + "dfkr1:sakura", + "dfkr1:sa kura:AAAA", + "dfkh1:sakura:AAAA", + "dfkr1:sakura:AAAA", + ] { + assert!(parse_request(bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_reply_opens_only_with_the_request_key_and_network() { + let (secret, req) = browser(); + let reply = seal(&req, &payload("sakura")).unwrap(); + let plain = open(&reply, "sakura", &secret).unwrap(); + let back: Payload = serde_json::from_slice(&plain).unwrap(); + assert_eq!(back.key_id, 7); + assert_eq!(back.replaced_key_id, Some(5)); + assert_eq!( + open(&reply, "testnet", &secret).unwrap_err(), + OpenError::Network + ); + assert_eq!( + open(&reply, "sakura", &[9u8; 32]).unwrap_err(), + OpenError::Unreadable + ); + // one flipped character of the ciphertext + let mut tampered = reply.clone(); + let last = tampered.pop().unwrap(); + tampered.push(if last == 'A' { 'B' } else { 'A' }); + assert!(open(&tampered, "sakura", &secret).is_err()); + // the network in the clear cannot be swapped: it is the associated data + let moved = reply.replacen("dfkh1:sakura:", "dfkh1:testnet:", 1); + assert_eq!( + open(&moved, "testnet", &secret).unwrap_err(), + OpenError::Unreadable + ); + } + + #[test] + fn a_key_for_another_network_is_never_sealed() { + let (_, req) = browser(); + assert!(seal(&req, &payload("testnet")).is_err()); + } + + #[test] + fn the_payload_never_debug_prints_its_keys() { + let p = payload("sakura"); + assert!(!format!("{p:?}").contains("cTestWif")); + } +} diff --git a/crates/forge-core/src/keyring.rs b/crates/forge-core/src/keyring.rs index 6a9229a79..aa2c53a69 100644 --- a/crates/forge-core/src/keyring.rs +++ b/crates/forge-core/src/keyring.rs @@ -511,6 +511,19 @@ impl Keyring { crate::members::best_role(&self.members, &platform::encode_identifier(self.reader)) } + /// The `ENCRYPTION` key ids the reader's own opened wraps for the current epoch went to + /// (§5.2 rekey: a wrap to the new key means this repository already moved to it). + pub fn own_current_wrap_keys(&self) -> Vec { + let Some(n) = self.resolution.current_epoch else { + return vec![]; + }; + self.wraps + .iter() + .filter(|w| w.member == self.reader && w.epoch == n && w.key.is_some()) + .map(|w| w.recipient_key_id) + .collect() + } + /// Epochs with a wrap to the reader that it could not open. pub fn unreadable_wraps(&self) -> &[u32] { &self.unreadable_wraps @@ -1560,6 +1573,65 @@ pub struct Rotation { pub burned: Option, } +/// The private repositories an identity is a current member of (§5.2 rekey), from the +/// `byMember` index of `maintainer` and `writer`. +#[derive(Debug, Default)] +pub struct PrivateMemberships { + /// Where it is a maintainer: it can rotate the key itself. + pub maintained: Vec, + /// Where it is only a writer, triage or reader: a maintainer must rotate (§5.6 repair). + pub member_only: Vec, +} + +/// [`PrivateMemberships`] of `identity` (base58) on `forge`'s contracts. A membership whose +/// repository is gone is skipped; public repositories have no keys and are left out. +pub async fn private_memberships( + client: &PlatformClient, + forge: &crate::network::ForgeIds, + identity: &str, +) -> Result { + let me = platform::decode_identifier(identity)?; + let core = client.fetch_contract(&forge.core).await?; + let mut by_type = Vec::new(); + for doc_type in ["maintainer", "writer"] { + let docs = client + .query_all_documents( + &core, + doc_type, + &[QueryFilter::eq("memberId", FieldValue::identifier(me))], + &[QueryOrder::asc("memberId")], + ) + .await?; + // Each membership document records its repository's visibility (`vis`): public ones + // have no keys and are not even resolved. + by_type.push( + docs.iter() + .filter(|d| d.field_str("vis").as_deref() == Some("private")) + .filter_map(|d| d.field_bytes32("repoId")) + .collect::>(), + ); + } + let (maintains, writes) = (&by_type[0], &by_type[1]); + let mut out = PrivateMemberships::default(); + for id in maintains.union(writes) { + let repo = match crate::resolve::resolve_id(client, &platform::encode_identifier(*id)).await + { + Ok(r) => r, + Err(Error::NotFound) => continue, + Err(e) => return Err(e), + }; + if repo.visibility != crate::rules::v2::Visibility::Private { + continue; + } + if maintains.contains(id) { + out.maintained.push(repo); + } else { + out.member_only.push(repo); + } + } + Ok(out) +} + /// The epoch a rotation chains from: the current epoch and its key. A burned current epoch /// still chains (§5.3); one the rotator cannot read cannot. fn chain_from(kr: &Keyring, repo: &RepoRef) -> Result<(u32, EpochKey)> { diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index 75f534d4b..485a29f68 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -38,6 +38,7 @@ //! (`test_support` validates with rs-dpp directly, and never ships). pub mod backends; +pub mod browser_key; pub mod budget; pub mod cache; pub mod ci; diff --git a/crates/forge-core/src/rules.rs b/crates/forge-core/src/rules.rs index e1ba75e49..7abfd2cf0 100644 --- a/crates/forge-core/src/rules.rs +++ b/crates/forge-core/src/rules.rs @@ -2550,23 +2550,7 @@ mod tests { "pubkey_entry" | "commit_signature" => run_signature_case(v), "repo_name" => run_repo_name_case(v), "webhook_url" => run_webhook_url_case(v), - "role_oracle" => { - let inp: RoleOracleInput = input(v); - let oracle = v2::RoleOracle::new(inp.memberships); - let got: Vec = inp - .queries - .iter() - .map(|q| { - serde_json::json!({ - "roleAt": oracle.role_at(&q.identity, q.at), - "memberAt": oracle.member_at(&q.identity, q.at), - "currentRole": oracle.current_role(&q.identity), - "approverAt": oracle.approver_at(&q.identity, q.at), - }) - }) - .collect(); - assert_eq!(serde_json::Value::from(got), v.expected, "vector `{ctx}`"); - } + "role_oracle" => run_role_oracle(v), "code_owners" | "code_owner_requests" => run_code_owners_case(v), "fold_review" | "policy" | "anchor" | "review_group" | "suggestion" | "linked_issues" => run_review_case(v), @@ -2575,10 +2559,127 @@ mod tests { } "long_body" => run_long_body(v), "ci_rerun" | "ci_rerun_write" => run_ci_rerun_case(v), + "key_handoff" | "key_handoff_open" | "copy" => run_key_handoff_case(v), other => panic!("vector `{ctx}`: unknown v2 case `{other}`"), } } + fn run_role_oracle(v: &Vector) { + let inp: RoleOracleInput = input(v); + let oracle = v2::RoleOracle::new(inp.memberships); + let got: Vec = inp + .queries + .iter() + .map(|q| { + serde_json::json!({ + "roleAt": oracle.role_at(&q.identity, q.at), + "memberAt": oracle.member_at(&q.identity, q.at), + "currentRole": oracle.current_role(&q.identity), + "approverAt": oracle.approver_at(&q.identity, q.at), + }) + }) + .collect(); + assert_eq!( + serde_json::Value::from(got), + v.expected, + "vector `{}`", + v.name + ); + } + + #[derive(Deserialize, Serialize)] + #[serde(deny_unknown_fields, rename_all = "camelCase")] + struct KeyHandoffInput { + network: String, + browser_secret: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + ephemeral_secret: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + nonce: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + plaintext: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + reply: Option, + } + + #[derive(Deserialize, Serialize)] + #[serde(deny_unknown_fields)] + struct CopyInput { + id: String, + } + + /// `key_handoff__*` (seal a reply for a request), `key_handoff_open__*` (open one) and + /// `copy__*` (fixed user-facing text): `crate::browser_key`. + fn run_key_handoff_case(v: &Vector) { + use crate::browser_key::{open, request_text, seal_bytes, OpenError, Request}; + let ctx = &v.name; + if v.case == "copy" { + let inp: CopyInput = input(v); + let text = match inp.id.as_str() { + "recoveryPhraseWarning" => crate::browser_key::RECOVERY_PHRASE_WARNING, + other => panic!("vector `{ctx}`: unknown copy `{other}`"), + }; + assert_eq!( + serde_json::json!({ "text": text }), + v.expected, + "vector `{ctx}`" + ); + return; + } + let inp: KeyHandoffInput = input(v); + let h32 = |s: &str| -> [u8; 32] { + hex::decode(s) + .unwrap_or_else(|e| panic!("vector `{ctx}`: {e}")) + .try_into() + .unwrap_or_else(|_| panic!("vector `{ctx}`: not 32 bytes")) + }; + let secret = h32(&inp.browser_secret); + let opened = |reply: &str| match open(reply, &inp.network, &secret) { + Ok(p) => serde_json::json!({ "plaintext": String::from_utf8(p.to_vec()).unwrap() }), + Err(e) => serde_json::json!({ "error": match e { + OpenError::Malformed => "malformed", + OpenError::Network => "network", + OpenError::Unreadable => "unreadable", + } }), + }; + if v.case == "key_handoff_open" { + let reply = inp.reply.as_deref().expect("reply"); + assert_eq!(opened(reply), v.expected, "vector `{ctx}`"); + return; + } + let secp = secp256k1::Secp256k1::new(); + let public_key = secp256k1::PublicKey::from_secret_key( + &secp, + &secp256k1::SecretKey::from_slice(&secret).unwrap(), + ); + let request = Request { + network: inp.network.clone(), + public_key, + }; + let plaintext = inp.plaintext.as_deref().expect("plaintext"); + let nonce: [u8; 12] = hex::decode(inp.nonce.as_deref().expect("nonce")) + .unwrap() + .try_into() + .unwrap(); + let reply = seal_bytes( + &request, + plaintext.as_bytes(), + &h32(inp.ephemeral_secret.as_deref().expect("ephemeralSecret")), + nonce, + ) + .unwrap(); + let got = serde_json::json!({ + "request": request_text(&inp.network, &public_key), + "reply": reply, + }); + assert_eq!(got, v.expected, "vector `{ctx}`"); + assert_eq!( + opened(&reply), + serde_json::json!({ "plaintext": plaintext }), + "vector `{ctx}`: round trip" + ); + } + #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct LongBodyInput { diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index d64c06b2f..07c7fdc49 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -499,6 +499,20 @@ The trailer is an HTML comment, which GitHub-flavoured renderers (forge-web's am **What it does not prove.** The file proves that someone who can push to the source named this repo. It says nothing about whether the mirror's content is current: the branch comparison does that, and only for the branch it compares. A source's maintainers can list several mirrors, and take one off the list. Only GitHub sources are checked; GitLab claims stay "says it mirrors". The check tells github.com the viewer's address, which is why it is a button. +### 6.5 Key handoff: a limited key from `dg` to a browser (client convention, TS-06) + +A browser can get its limited key from `dg` instead of from the recovery phrase, so the phrase never enters a web page. Nothing on chain changes: `dg` registers an ordinary limited key (§2, the `dash-forge` group, a budget and an expiry) with one master-key `IdentityUpdate` on the terminal, and hands its private key to the browser sealed. The rules, shared by forge-core (`browser_key`) and forge-web (`lib/auth/key-handoff.ts`) and pinned by the `key_handoff__*` and `key_handoff_open__*` vectors: + +| | Rule | +|---|---| +| **Request** (the browser shows it) | `dfkr1::`, from a one-time key pair drawn for this request and kept only in the tab's memory. `` is the network key (`testnet`, `mainnet`, `devnet-sakura`): 1 to 32 characters of `[A-Za-z0-9-]`. base64url is RFC 4648 §5 without padding, decoded strictly (no `=`, no stray bits). | +| **Reply** (`dg auth keys add --for-browser ` prints it) | `dfkh1::`: `E` dg's ephemeral compressed public key (33 bytes), `N` a random 12-byte nonce, `C` AES-256-GCM of the payload (tag included). Key: `HKDF-SHA256(ikm = x-coordinate of ECDH(ephemeral, request key), salt = E ‖ request public key, info = "dash-forge/key-handoff/1")`. Associated data: `"dfkh1:" ‖ network`, so a reply relabelled for another network does not open. | +| **Payload** | JSON `{"v":1,"network","identityId","keyId","wif"}` plus optional `"replacedKeyId"` (the key disabled in the same update) and `"encryptionKey":{"keyId","privateKeyHex"}` (with `--with-encryption-key`). Unknown fields, another version or another network: refused. At most 2,048 bytes. | +| **Opening** | Not a `dfkh1:` reply, or too short for a tag: *malformed*. Another network: *network*, before decrypting. A tag that fails (another tab's request, an altered reply): *unreadable*. | +| **Adopting** | The browser reads the key back from the chain before storing anything: live, AUTHENTICATION/HIGH, bound to the group, with a budget and an expiry, and controlled by the private key the payload carries. A renewal takes only a key for the signed-in identity, and a key this browser already holds for the identity must be the one the reply says was replaced (else it would stay live with nothing holding it); wallet keys, which `dg` cannot disable by id, renew with the identity file or phrase instead. The command names the identity when the tab knows it (`--for-identity`), and `dg` refuses another one before signing. `dg` refuses a browser key that lives longer than 365 days. The vault records that the key came from `dg`, and **Renew** then offers `dg` first. | + +The reply is useless without the tab's one-time private key, so it may be printed and pasted like any text; what it carries is still only a limited key. A request works once: the tab forgets its private key when the key is stored or the view closes. + ## 7. Measured size and cost From `tools/contract-validate` (rs-dpp v5.0.0-beta.1, `PlatformVersion` 14) on the RC2 build with every flag on. The signed-shape transitions carry a 65-byte recoverable signature and the contract group fields. diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index 912d43e1c..8e446bb82 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -68,8 +68,9 @@ Do this once: If you lose a laptop but still have the words or a backup of the file, nothing is lost. Your repositories, issues and history are on Platform, not on your laptop: 1. On the new machine run `dg auth login --mnemonic` (type the 12 words) or `dg auth login ` with your backup. It registers a new limited key and stores only that, with the encryption key beside it. -2. Disable the lost machine's key: `dg auth keys list` shows it, `dg auth keys disable ` disables it (or pass `--replace ` to the login above to do both in one update). A limited key can only spend its remaining budget, and only on Forge, until then. +2. Disable the lost machine's key: in the web app, **Settings → Devices & keys** lists every key and has **Disable** (your identity file or recovery phrase signs once); in the terminal, `dg auth keys list` shows it and `dg auth keys disable ` disables it (or pass `--replace ` to the login above to do both in one update). A limited key can only spend its remaining budget, and only on Forge, until then. 3. In a browser, **Sign in → Import an identity file or recovery phrase** registers a fresh limited key for that browser; the words alone are enough. +4. If you use private repositories, the lost machine also held your **encryption key**, which a disabled signing key does not protect. Replace it: `dg auth keys rotate --encryption` ([below](#replacing-it-after-a-lost-device)). Your **repository data** needs no backup of its own. Refs, issues and PRs are on Platform. Pack bytes are on Platform or in the storage you chose. Any clone also holds a full copy of the history, and [`dg reseed --from-local`](bring-your-own-storage.md#restoring-a-lost-copy) can restore a lost pack copy from it. @@ -105,7 +106,8 @@ Things to know: A web page is whoever served it. If the page, or a script it loads, is compromised, anything you paste into it is gone. - **Never paste your MASTER key, your 12 words, or your main identity file into a website.** That includes forge.dashhq.org. Nothing on Forge needs them. -- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Use my Dash wallet** instead (the wallet registers the key), or register a key for the browser from the terminal: `dg auth export --new-key --reveal-secrets --format dfk1 -o key.dfk1`, then under **Advanced** enter the identity id and the key's WIF (the last `:`-separated field of the `dfk1` value). It signs for that tab only. +- The web app's **Import** reads your identity file (or recovery phrase) once: its master key signs one update that registers a [limited key](#limited-keys) for this browser, and is not retained. If you would rather not load the master key into a web page at all, use **Sign in → Use dg on your computer**: the page shows a `dg auth keys add --for-browser …` command, `dg` registers the key with your master key on the terminal and prints a line that only that tab can open ([below](#a-browser-key-from-dg)). **Use my Dash wallet** also keeps the master key out of the page (the wallet registers the key). +- Forge asks for your recovery phrase only after you start a key action yourself. Every phrase prompt, in the web app and in `dg`, shows the same warning: *"Your recovery phrase controls your identity. Forge asks for it only after you start a key action yourself, never because a message, an email or a pop-up says so. If you didn't start this, stop here."* A page that asks for your words without it, or because a message told you to, is not Forge. - For CI, give a pipeline its own limited key: `dg auth export --new-key --budget 0.5 --expires 365d --format dfk1 --reveal-secrets -o runner.dfk1` makes one, and the file's one line is the `DASH_FORGE_KEY` secret. - Prefer a copy of the web app that you [serve yourself](verify-forge.md#run-your-own-copy-of-the-web-app) if you do not want to trust the one on forge.dashhq.org. @@ -120,7 +122,9 @@ Platform lets the MASTER key add new keys to an identity and disable old ones. A ```sh dg auth keys list # every key: purpose, level, budget left, expiry, this computer's dg auth keys add [--budget 0.25 --expires 180d] [--replace | --keep-current] # a new key for this computer; disables the one it replaces +dg auth keys add --for-browser [--replace ] [--with-encryption-key] # a key for a browser tab, printed sealed to it dg auth keys disable # disable one (limited keys; --force for others) +dg auth keys rotate --encryption [--keep-old] # replace the ENCRYPTION key and move your private repos to it dg auth logout [--disable] # forget the key here (and disable it on chain) ``` @@ -128,7 +132,7 @@ dg auth logout [--disable] # forget the key here (and disable it o When to rotate: -- a laptop or CI secret that held a key was lost or leaked: **disable that key**; +- a laptop or CI secret that held a key was lost or leaked: **disable that key**, and if it also held the encryption key (any `dg auth login` with private repos, a browser with private repos enabled), **replace the encryption key** too; - a limited key's budget is nearly spent or it is about to expire: `dg auth keys add` registers a fresh one and disables this computer's current key in the same update (`--replace ` names another key to disable, `--keep-current` keeps the current one live on chain, though this computer no longer stores it; `dg auth login … --replace ` does the same at sign-in). A browser's own key is managed in the web app: **Settings → This browser's key** can top it up, renew it or revoke it ([below](#limited-keys)). @@ -155,6 +159,21 @@ dg auth keys add --encryption **What it can read.** This key can read every private repo you're a member of, and every key you've handed out as a maintainer. Keep it as carefully as your signing keys. +### Replacing it after a lost device + +```sh +dg auth keys rotate --encryption [--master ] [--keep-old] +``` + +It runs the rekey of [private-repos.md §5.2](../security/private-repos.md#52-encryption-keys-derivation-custody-blast-radius-rekey), in this order, and prints the plan and its cost before anything is signed: + +1. Adds a new ENCRYPTION key, derived from the recovery phrase at the next key id, so the words alone recover it (one identity update, signed by the MASTER key). +2. Rotates the key of every private repository you **maintain**: a new key epoch, wrapped to every member, you first, to your new key. Each costs one wrap per member plus one anchor. +3. Names the private repositories where you are only a writer, triage or reader. You cannot rotate those. A maintainer's next visit (or `dg repo keys repair `) wraps the current key to your new one. Until then, new content there is sealed for the old key. +4. Disables the old key, unless `--keep-old` is given or a repository failed to rotate. A disabled key still opens what was sealed for it, so nothing you could read is lost. Whoever holds the old key keeps what was sealed before, but nothing sealed from now on. + +The key `dg` stores beside your limited key (`dg auth login`) gets the new key too. A repository counts as moved only when a fresh read shows your wrap for its current epoch on the new key. If one is not, every old key stays enabled and nothing is lost. Run the command again: each run adds a fresh key and treats every enabled encryption key as old, since a lost device may have held an earlier run's key too. Other computers and browsers need the new key: sign in again with the words, or in the web app add it from **Settings → Private repos**. + **In the web app** this will be **Settings → Keys → Enable private repos**, with the web release of private repositories. --- @@ -170,7 +189,7 @@ A limited key is an identity key with four restrictions: | Where | Budget | Expires | |---|---|---| -| Browser | 0.05 DASH | 90 days | +| Browser | 0.05 DASH | 90 days (30 days to 1 year) | | CLI (`dg auth new` / `login` / `keys add`) | 0.25 DASH | 180 days | | CI runner (`dg auth export --new-key`, Mirror Action) | 0.5 DASH | 365 days | @@ -196,11 +215,27 @@ dg auth name register