diff --git a/crates/dg/src/auth/keys.rs b/crates/dg/src/auth/keys.rs index 6d1323eb7..cf3e0b139 100644 --- a/crates/dg/src/auth/keys.rs +++ b/crates/dg/src/auth/keys.rs @@ -167,10 +167,9 @@ async fn list(ctx: &Ctx) -> Result<()> { /// id, so the words alone recover it. One identity update signed by the master key. /// /// Only a master identity that carries its words can do this: the private half must be -/// recoverable, and `dg` keeps nothing but limited keys (an ENCRYPTION key is not one). Readers -/// (`git clone`, `dg`) need the key's private half in the identity they sign with: sign in with -/// the full identity for private repositories (`dg auth login --full-key`), or keep the words' -/// file, which now derives it. +/// recoverable. Readers (`git clone`, `dg`) need the key's private half in the key source they +/// sign with: `dg auth login` again stores it beside a limited key (QW2-004), and the words' +/// file now derives it. async fn add_encryption( ctx: &Ctx, client: &forge_core::platform::PlatformClient, @@ -214,7 +213,10 @@ async fn add_encryption( "purpose": "ENCRYPTION", "derived": true, }), - || println!("✓ added ENCRYPTION key #{added}; the recovery words re-derive it"), + || { + println!("✓ added ENCRYPTION key #{added}; the recovery words re-derive it"); + println!(" to use it from this computer: `dg auth login ` (or --mnemonic) stores it beside a limited key"); + }, ); Ok(()) } @@ -259,16 +261,17 @@ async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { ctx.confirm_or_cancel("Add the key?")?; // The key this computer signs with now is replaced by default: otherwise it would stay live // on chain with nothing holding it. `--replace` names another one; `--keep-current` keeps it. + let identity = client.fetch_signer(&master).await?; let replace = match args.replace { Some(id) => Some(id), None if args.keep_current => None, - None => { - let identity = client.fetch_signer(&master).await?; - identity - .signing_key_id(¤t, ctx.network()) - .filter(|id| identity.is_limited_key(*id)) - } + None => identity + .signing_key_id(¤t, ctx.network()) + .filter(|id| identity.is_limited_key(*id)), }; + // The encryption keys the key in use holds are kept too, whatever the master source holds. + let encryption = + super::encryption_to_store(ctx, &args.storage, &identity, &[&master, ¤t]); let (id, stored) = super::register_and_store( ctx, &client, @@ -277,8 +280,10 @@ async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { replace, &checked, args.storage.insecure_plaintext, + &encryption, ) .await?; + let kept: Vec = encryption.iter().map(|k| k.id).collect(); super::store::set_default(ctx, &master.identity_id, &stored.source())?; ctx.emit( super::group::with_group_fields( @@ -288,12 +293,14 @@ async fn add(ctx: &Ctx, args: &AddArgs) -> Result<()> { "budgetCredits": spec.budget_credits, "expiresAt": spec.expires_at_ms, "storedAt": stored.describe(), + "encryptionKeyIds": kept, "replacedKeyId": replace, }), Some(&checked), ), || { println!("✓ limited key #{id} added; this computer now signs with it"); + super::print_kept_encryption(&kept); println!(" stored in {}", stored.describe()); if let Some(old) = replace { println!(" key #{old} disabled"); diff --git a/crates/dg/src/auth/mod.rs b/crates/dg/src/auth/mod.rs index 2f1bea42b..3af21d285 100644 --- a/crates/dg/src/auth/mod.rs +++ b/crates/dg/src/auth/mod.rs @@ -8,7 +8,7 @@ //! - `new` — recovery words → deposit QR → asset lock → identity with its canonical keys and a //! limited key in one IdentityCreate ([`new`]). //! - `login` — import an identity file or the recovery words once, register a limited key, -//! store only that key. +//! store only that key (with the identity's encryption key beside it, QW2-004). //! - `status`, `balance`, `keys list|add|disable`, `name register`, `export`, `logout`. pub mod group; @@ -118,6 +118,10 @@ pub struct StorageArgs { /// passphrase. Every later use warns. #[arg(long)] pub insecure_plaintext: bool, + /// Store the limited signing key only, not your identity's encryption key beside it + /// (private repositories then need DASH_FORGE_KEY= for each command). + #[arg(long)] + pub signing_only: bool, } /// `dg auth login` arguments. @@ -429,6 +433,10 @@ pub async fn register_limited_key( /// outcome is unclear (the update errored, but it may have landed), the chain is asked: a key /// that landed is promoted; otherwise both copies stay and the error says where each is. /// Returns the new key's id and where it is stored. +/// +/// `encryption` ([`encryption_to_store`]) is stored beside the new key, so private +/// repositories work with it. +#[allow(clippy::too_many_arguments)] pub async fn register_and_store( ctx: &Ctx, client: &PlatformClient, @@ -437,6 +445,7 @@ pub async fn register_and_store( replace: Option, checked: &group::GroupCheck, insecure_plaintext: bool, + encryption: &[keystore::IdentityKey], ) -> Result<(u32, store::Stored)> { let network = ctx.network_label(); let id_ = master.identity_id.clone(); @@ -445,13 +454,24 @@ pub async fn register_and_store( || "none".to_string(), |p| store::describe_source(&p.to_string_lossy()).0, ); + // The slots take the new key's `dfk1:` text and store it with the encryption keys. let slots = KeySlots { stage: |t: &Secret| { - storer - .borrow_mut() - .store(&network, &id_, t, store::Slot::Pending) + storer.borrow_mut().store( + &network, + &id_, + &with_encryption_keys(t, encryption)?, + store::Slot::Pending, + ) + }, + promote: |t: &Secret| { + store::promote( + &mut storer.borrow_mut(), + &network, + &id_, + &with_encryption_keys(t, encryption)?, + ) }, - promote: |t: &Secret| store::promote(&mut storer.borrow_mut(), &network, &id_, t), }; let mut staged = None; let result = register_limited_key(ctx, client, master, spec, replace, checked, &mut |t| { @@ -478,6 +498,149 @@ pub async fn register_and_store( settle(&slots, result, staged, landed, &in_use) } +/// The identity's `ENCRYPTION` keys to store beside a new limited key (QW2-004): those the +/// `sources` hold (the master identity, which may derive them from its recovery words, and the +/// key in use, so a replacement never drops one) that match the identity's keys on chain. A +/// private repository then opens with the limited key, as with the web app's "Enable private +/// repos", instead of needing the master key on disk. None with `--signing-only`, nor with +/// `--insecure-plaintext` (it would be written in the clear), nor on a network with no +/// forge-v2 contracts. +pub fn encryption_to_store( + ctx: &Ctx, + storage: &StorageArgs, + identity: &LoadedIdentity, + sources: &[&BridgeIdentity], +) -> Vec { + let Some(v2) = ctx.target.v2.as_ref() else { + return vec![]; + }; + if storage.signing_only || storage.insecure_plaintext { + return vec![]; + } + let on_chain = identity.public_keys(); + let mut keys = std::collections::BTreeMap::new(); + for source in sources.iter().filter(|b| b.identity_id == identity.id()) { + let held = + forge_core::keyring::EncryptionKeys::held(source, &on_chain, &v2.core, ctx.network()); + for k in held.to_identity_keys(ctx.network()) { + keys.entry(k.id).or_insert(k); + } + } + keys.into_values().collect() +} + +/// What is stored for the limited key `dfk1`: the `dfk1:` text alone, or with `encryption` +/// keys, a bridge-format identity holding exactly that key and those (no mnemonic, no master +/// key, nothing else). +pub fn with_encryption_keys(dfk1: &Secret, encryption: &[keystore::IdentityKey]) -> Result { + if encryption.is_empty() { + return Ok(dfk1.clone()); + } + let mut bridge = BridgeIdentity::from_dfk1(dfk1.expose())?; + bridge.identity_keys.extend(encryption.iter().cloned()); + Ok(bridge.to_json_with_secrets()) +} + +/// The login / new / keys add line for the encryption keys stored beside a limited key. +pub fn print_kept_encryption(ids: &[u32]) { + if ids.is_empty() { + println!(" signing key only: private repositories need DASH_FORGE_KEY="); + } else { + println!( + " with encryption key {}: private repositories you are a member of open with it", + key_id_list(ids) + ); + } +} + +/// `#4`, or `#4, #7`. +pub fn key_id_list(ids: &[u32]) -> String { + ids.iter() + .map(|i| format!("#{i}")) + .collect::>() + .join(", ") +} + +/// Whether private repositories open with a key source: the `ENCRYPTION` keys it holds that +/// are enabled on the identity, and whether the identity has any enabled one at all. +pub(crate) struct PrivateAccess { + held: Vec, + on_identity: bool, +} + +/// [`PrivateAccess`] of `bridge`, from the identity on chain; from the file alone (taken at +/// its word) when the chain was not read. +pub(crate) fn private_access( + ctx: &Ctx, + bridge: &BridgeIdentity, + identity: Option<&LoadedIdentity>, +) -> PrivateAccess { + match (identity, ctx.target.v2.as_ref()) { + (Some(identity), Some(v2)) => { + let on_chain = identity.public_keys(); + PrivateAccess { + held: forge_core::keyring::EncryptionKeys::held( + bridge, + &on_chain, + &v2.core, + ctx.network(), + ) + .enabled_ids(), + on_identity: on_chain + .iter() + .any(|k| k.purpose == "ENCRYPTION" && !k.disabled), + } + } + _ => PrivateAccess { + held: encryption_key_ids(bridge), + on_identity: true, + }, + } +} + +/// `dg auth status`'s `Private:` line (and doctor's): whether private repositories open with +/// the key source, and the step that makes them when they do not. `None` when the key was not +/// opened, or for a CI runner key, which never needs one. `key_id` is the key in use, which a +/// new sign-in replaces rather than leaves live with nothing holding it. +pub(crate) fn private_line( + access: Option<&PrivateAccess>, + runner_key: bool, + key_id: Option, +) -> Option { + let access = access?; + if !access.held.is_empty() { + return Some(format!( + "encryption key {} stored (opens private repositories you are a member of)", + key_id_list(&access.held) + )); + } + if runner_key { + return None; + } + if !access.on_identity { + return Some( + "your identity has no encryption key; `dg auth keys add --encryption` adds one \ + (from the recovery words)" + .into(), + ); + } + let replace = key_id.map_or(String::new(), |id| format!(" --replace {id}")); + Some(format!( + "no encryption key stored; `dg auth login {replace}` stores it beside a \ + new limited key" + )) +} + +/// The `ENCRYPTION` key ids a key source holds. +pub fn encryption_key_ids(bridge: &BridgeIdentity) -> Vec { + bridge + .identity_keys + .iter() + .filter(|k| k.purpose == "ENCRYPTION") + .map(|k| k.id) + .collect() +} + /// Where a new key is kept while it is being registered. struct KeySlots { /// Write the key to the staging slot. @@ -687,7 +850,7 @@ async fn login_source( } /// Import an identity once: register a limited key signed by its master key and store only -/// that key (or, with `--full-key`, the whole identity). +/// that key and the identity's encryption keys (or, with `--full-key`, the whole identity). #[allow(clippy::too_many_lines)] async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { let client = ctx.connect().await?; @@ -713,6 +876,14 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { "--full-key keeps the master key: it goes to a passphrase-sealed file, never unencrypted (drop --insecure-plaintext)", )); } + // The encryption keys stored with the signing key: for a limited key, those the file holds + // or its words derive; a full identity keeps all of its own. + let kept_encryption = encryption_to_store(ctx, &args.storage, &on_chain, &[&master]); + let kept_ids: Vec = if full_key { + encryption_key_ids(&master) + } else { + kept_encryption.iter().map(|k| k.id).collect() + }; let (stored, key_id, spec) = if full_key || master.master_key().is_none() { // --full-key, no forge-v2 here, or a file holding one limited key (an export of this // or another computer's key): store it as it is. A master key never goes into the @@ -720,12 +891,14 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { let lone_key = master.master_key().is_none(); let text = if lone_key { let k = master.doc_op_key()?; - keystore::dfk1( + let dfk1 = keystore::dfk1( &master.network, &master.identity_id, k.id, k.private_key_wif.expose(), - ) + ); + // an export of a limited key and its encryption key keeps both + with_encryption_keys(&dfk1, &kept_encryption)? } else { master.to_json_with_secrets() }; @@ -755,6 +928,7 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { args.replace, &checked, insecure, + &kept_encryption, ) .await?; (stored, Some(id), Some((spec, checked))) @@ -769,6 +943,7 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { "network": network, "keyId": key_id, "fullKey": full_key, + "encryptionKeyIds": kept_ids, "budgetCredits": spec.as_ref().map(|(s, _)| s.budget_credits), "expiresAt": spec.as_ref().map(|(s, _)| s.expires_at_ms), "storage": stored.kind(), @@ -792,6 +967,9 @@ async fn login(ctx: &Ctx, args: &LoginArgs) -> Result<()> { ), _ => println!(" the key in the file is stored as it is (no new key registered)"), } + if !full_key { + print_kept_encryption(&kept_ids); + } println!(" stored in {}", stored.describe()); println!(" balance {} DASH", dash_amount(credits_to_dash(balance))); if key_id.is_some() { @@ -841,15 +1019,31 @@ pub fn explain_new_key( // --------------------------------------------------------------------------------------- /// Which key a source signs with, and what the chain says about it. -struct KeyReport { - key_id: Option, +pub(crate) struct KeyReport { + pub key_id: Option, limited: bool, + /// The one document type the key is bound to (a CI runner key: `checkRun`). + pub doc_type: Option, total: Option, remaining: Option, expires_at: Option, } -async fn key_report( +impl KeyReport { + /// Why the key signs nothing any more, when it does not: its budget is spent, or it has + /// expired (at `now_ms`). + pub(crate) fn spent_or_expired(&self, now_ms: u64) -> Option<&'static str> { + if self.remaining == Some(0) { + Some("its budget is spent") + } else if self.expires_at.is_some_and(|at| at <= now_ms) { + Some("it has expired") + } else { + None + } + } +} + +pub(crate) async fn key_report( client: &PlatformClient, identity: &LoadedIdentity, bridge: &BridgeIdentity, @@ -868,6 +1062,9 @@ async fn key_report( KeyReport { key_id, limited: key_id.is_some_and(|id| identity.is_limited_key(id)), + doc_type: key_id + .and_then(|id| identity.key_doc_type(id)) + .map(|(_, doc_type)| doc_type), total: limits.and_then(|l| l.total_budget), remaining, expires_at: limits.and_then(|l| l.expires_at), @@ -905,26 +1102,19 @@ async fn status(ctx: &Ctx) -> Result<()> { Some(b) => b.identity_id.clone(), None => ctx.identity_id_hint().unwrap_or_default(), }; - let chain = match ctx.connect().await { - Ok(client) => match client.fetch_identity(&identity_id).await { - Ok(identity) => { - let report = match &bridge { - Some(b) => Some(key_report(&client, &identity, b, ctx).await), - None => None, - }; - let names = client.dpns_names_of(&identity_id).await.unwrap_or_default(); - Some((identity.balance(), report, names)) - } - Err(_) => None, - }, - Err(_) => None, - }; + let chain = status_from_chain(ctx, bridge.as_ref(), &identity_id).await; let reached = chain.is_some(); - let (balance, report, names) = match chain { - Some((b, r, n)) => (Some(b), r, n), - None => (None, None, vec![]), + let (balance, report, names, access) = match chain { + Some((b, r, n, a)) => (Some(b), r, n, a), + None => ( + None, + None, + vec![], + bridge.as_ref().map(|b| private_access(ctx, b, None)), + ), }; let master = bridge.as_ref().map(|b| b.master_key().is_some()); + let runner_key = report.as_ref().is_some_and(|r| r.doc_type.is_some()); ctx.emit( json!({ "network": network, @@ -933,6 +1123,8 @@ async fn status(ctx: &Ctx) -> Result<()> { "names": names, "keyId": report.as_ref().and_then(|r| r.key_id), "limited": report.as_ref().map(|r| r.limited), + "boundDocumentType": report.as_ref().and_then(|r| r.doc_type.clone()), + "encryptionKeyIds": access.as_ref().map(|a| a.held.clone()), "budgetCredits": report.as_ref().and_then(|r| r.total), "budgetRemainingCredits": report.as_ref().and_then(|r| r.remaining), "expiresAt": report.as_ref().and_then(|r| r.expires_at), @@ -954,12 +1146,16 @@ async fn status(ctx: &Ctx) -> Result<()> { "Key: {}", key_line(report.as_ref(), unopened.as_deref(), reached) ); + let key_id = report.as_ref().and_then(|r| r.key_id); + if let Some(line) = private_line(access.as_ref(), runner_key, key_id) { + println!("Private: {line}"); + } if let Some(b) = balance { println!("Balance: {} DASH", dash_amount(credits_to_dash(b))); } println!("Stored: {where_}"); if master == Some(true) { - println!(" (holds the master key: `dg auth login ` would store only a limited key)"); + println!(" (holds the master key: `dg auth login ` would store only a limited key and the encryption key)"); if kind == "keychain" { println!(" warning: an older dg put this master key in the keychain, where any program running as you can read it; `dg auth login --full-key ` moves it to a sealed file"); } @@ -969,21 +1165,57 @@ async fn status(ctx: &Ctx) -> Result<()> { Ok(()) } +/// What `dg auth status` reads from Platform: the balance, the key's limits, the DPNS names +/// and whether private repositories open. `None` when Platform or the identity was not reached. +async fn status_from_chain( + ctx: &Ctx, + bridge: Option<&BridgeIdentity>, + identity_id: &str, +) -> Option<(u64, Option, Vec, Option)> { + let client = ctx.connect().await.ok()?; + let identity = client.fetch_identity(identity_id).await.ok()?; + let report = match bridge { + Some(b) => Some(key_report(&client, &identity, b, ctx).await), + None => None, + }; + let names = client.dpns_names_of(identity_id).await.unwrap_or_default(); + let access = bridge.map(|b| private_access(ctx, b, Some(&identity))); + Some((identity.balance(), report, names, access)) +} + /// The status's `Key:` line: the key's limits, or why they were not checked (the key was not /// opened, or Platform was not `reached`). -fn key_line(report: Option<&KeyReport>, unopened: Option<&str>, reached: bool) -> String { +pub(crate) fn key_line( + report: Option<&KeyReport>, + unopened: Option<&str>, + reached: bool, +) -> String { match (report, unopened) { (Some(r), _) => { let id = r.key_id.map_or("?".to_string(), |i| format!("#{i}")); - if r.limited { + let limits = || { format!( - "{id} limited — {} of {} DASH left, expires {}", + "{} of {} DASH left, expires {}", r.remaining .map_or("?".into(), |c| dash_amount(credits_to_dash(c))), r.total .map_or("?".into(), |c| dash_amount(credits_to_dash(c))), r.expires_at.map_or("never".into(), expiry_text) ) + }; + if r.limited { + format!("{id} limited — {}", limits()) + } else if let Some(doc_type) = &r.doc_type { + // QW2-005: a CI runner key signs one document type, and nothing else. + format!( + "{id} bound to {doc_type} documents only{} — {}", + if doc_type == "checkRun" { + " (a CI runner key)" + } else { + "" + }, + limits() + ) } else { format!("{id} unlimited (not a Forge limited key)") } @@ -1463,6 +1695,96 @@ mod tests { assert_eq!(main.borrow().as_deref(), Some("dfk1:new")); } + /// QW2-004: a limited key is stored with the encryption keys as a bridge identity holding + /// exactly those (no master key, no words); without any, as the plain `dfk1:` key. + #[test] + fn a_limited_key_is_stored_with_its_encryption_keys() { + const ID: &str = "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB"; + let dfk1 = keystore::dfk1("devnet-bonsia", ID, 5, "FAKE-wif"); + assert_eq!( + with_encryption_keys(&dfk1, &[]).unwrap().expose(), + dfk1.expose() + ); + let enc = keystore::IdentityKey { + id: 4, + name: "enc".into(), + key_type: "ECDSA_SECP256K1".into(), + purpose: "ENCRYPTION".into(), + security_level: "MEDIUM".into(), + private_key_wif: Secret::new("FAKE-enc-wif"), + private_key_hex: Secret::new("07".repeat(32)), + public_key_hex: "02ab".into(), + derivation_path: String::new(), + }; + let text = with_encryption_keys(&dfk1, std::slice::from_ref(&enc)).unwrap(); + let b = BridgeIdentity::from_source_text(text.expose()).unwrap(); + assert_eq!(b.identity_id, ID); + assert_eq!(b.network, "devnet-bonsia"); + assert!(b.master_key().is_none()); + assert!(b.mnemonic.expose().is_empty()); + assert_eq!(b.doc_op_key().unwrap().id, 5); + assert_eq!(encryption_key_ids(&b), [4]); + assert_eq!(b.identity_keys.len(), 2); + } + + /// QW2-005: a key bound to one document type (a CI runner key) says so, not "unlimited". + #[test] + fn a_runner_key_is_described_as_bound_to_its_document_type() { + let report = |limited, doc_type: Option<&str>| KeyReport { + key_id: Some(6), + limited, + doc_type: doc_type.map(str::to_string), + total: Some(50_000_000_000), + remaining: Some(49_000_000_000), + expires_at: None, + }; + let line = key_line(Some(&report(false, Some("checkRun"))), None, true); + assert!( + line.starts_with( + "#6 bound to checkRun documents only (a CI runner key) — 0.49 of 0.5 DASH left" + ), + "{line}" + ); + assert!(!line.contains("unlimited"), "{line}"); + assert!(key_line(Some(&report(true, None)), None, true).starts_with("#6 limited — ")); + // doctor fails a key that signs nothing any more + let mut r = report(true, None); + assert_eq!(r.spent_or_expired(1_000), None); + r.expires_at = Some(1_000); + assert_eq!(r.spent_or_expired(1_000), Some("it has expired")); + r.remaining = Some(0); + assert_eq!(r.spent_or_expired(0), Some("its budget is spent")); + assert_eq!( + key_line(Some(&report(false, None)), None, true), + "#6 unlimited (not a Forge limited key)" + ); + } + + #[test] + fn the_private_line_says_whether_private_repositories_open() { + let access = |held: &[u32], on_identity| PrivateAccess { + held: held.to_vec(), + on_identity, + }; + assert_eq!(private_line(None, false, Some(5)), None); + // a CI runner key never needs one + assert_eq!(private_line(Some(&access(&[], true)), true, Some(6)), None); + // the step names the key in use, which the new sign-in replaces + assert_eq!( + private_line(Some(&access(&[], true)), false, Some(15)).unwrap(), + "no encryption key stored; `dg auth login --replace 15` stores it \ + beside a new limited key" + ); + // an identity with none: signing in again would not help + assert!(private_line(Some(&access(&[], false)), false, Some(15)) + .unwrap() + .contains("dg auth keys add --encryption")); + assert_eq!( + private_line(Some(&access(&[4, 7], true)), false, Some(16)).unwrap(), + "encryption key #4, #7 stored (opens private repositories you are a member of)" + ); + } + #[test] fn durations() { assert_eq!(parse_days("180d").unwrap(), 180); diff --git a/crates/dg/src/auth/new.rs b/crates/dg/src/auth/new.rs index 22bc00c98..08ed9bf67 100644 --- a/crates/dg/src/auth/new.rs +++ b/crates/dg/src/auth/new.rs @@ -721,8 +721,32 @@ async fn fund_and_lock( Ok((lock, proof)) } +/// The new identity's `ENCRYPTION` key entries (key 4, registered in the same IdentityCreate) +/// to store beside its limited key: none with `--signing-only` or `--insecure-plaintext`, as +/// [`super::encryption_to_store`] decides for an identity that exists. +fn encryption_to_keep( + args: &NewArgs, + keys: &NewIdentityKeys, + identity_id: &str, +) -> Vec { + if args.storage.signing_only || args.storage.insecure_plaintext { + return vec![]; + } + keys.to_bridge(identity_id) + .identity_keys + .into_iter() + .filter(|k| k.purpose == "ENCRYPTION") + .map(|mut k| { + // what the stored key needs, not how to derive it again + k.derivation_path.clear(); + k + }) + .collect() +} + /// Store this computer's limited key, then register the identity with it (or, when an earlier /// run already created the identity, register a fresh limited key with the words' master key). +/// Returns the key's id, where it is stored and the encryption keys stored beside it. #[allow(clippy::too_many_arguments)] async fn register( ctx: &Ctx, @@ -733,7 +757,7 @@ async fn register( identity_id: &str, spec: &LimitedKeySpec, checked: &GroupCheck, -) -> Result<(u32, store::Stored)> { +) -> Result<(u32, store::Stored, Vec)> { let network = ctx.network_label(); let insecure = args.storage.insecure_plaintext; if client.identity_exists(identity_id).await? { @@ -756,13 +780,26 @@ async fn register( store::Stored::Keychain { source: stored_source, }, + super::encryption_key_ids(&b), )); } } let replace = identity .is_limited_key(FIRST_LIMITED_KEY_ID) .then_some(FIRST_LIMITED_KEY_ID); - return register_and_store(ctx, client, &master, spec, replace, checked, insecure).await; + let encryption = super::encryption_to_store(ctx, &args.storage, &identity, &[&master]); + let (id, stored) = register_and_store( + ctx, + client, + &master, + spec, + replace, + checked, + insecure, + &encryption, + ) + .await?; + return Ok((id, stored, encryption.iter().map(|k| k.id).collect())); } let limited = FreshKey::generate(ctx.network()); let dfk1 = forge_core::keystore::dfk1( @@ -771,8 +808,12 @@ async fn register( FIRST_LIMITED_KEY_ID, limited.wif().expose(), ); + // With the identity's encryption key (key 4, registered in the same IdentityCreate), so + // private repositories work with this computer's key (QW2-004), unless --signing-only. + let encryption = encryption_to_keep(args, keys, identity_id); + let text = super::with_encryption_keys(&dfk1, &encryption)?; // Stored before the identity exists: an interruption never leaves a key nobody holds. - let stored = store::store(&network, identity_id, &dfk1, insecure)?; + let stored = store::store(&network, identity_id, &text, insecure)?; say(ctx, " registering the identity…"); client .create_identity(keys, proof, &limited, spec) @@ -787,7 +828,11 @@ async fn register( spec, ) .await?; - Ok((FIRST_LIMITED_KEY_ID, stored)) + Ok(( + FIRST_LIMITED_KEY_ID, + stored, + encryption.iter().map(|k| k.id).collect(), + )) } pub async fn run(ctx: &Ctx, args: &NewArgs) -> Result<()> { @@ -820,7 +865,7 @@ pub async fn run(ctx: &Ctx, args: &NewArgs) -> Result<()> { j.identity_id = Some(identity_id.clone()); save_journal(&j)?; - let (key_id, stored) = register( + let (key_id, stored, encryption) = register( ctx, &client, args, @@ -862,6 +907,7 @@ pub async fn run(ctx: &Ctx, args: &NewArgs) -> Result<()> { "expiresAt": spec.expires_at_ms, "storage": stored.kind(), "storedAt": stored.describe(), + "encryptionKeyIds": encryption, "assetLockTxid": lock.txid, "proof": match proof { LockProof::Instant { .. } => "instant", LockProof::Chain { .. } => "chain" }, "balanceCredits": balance, @@ -879,6 +925,7 @@ pub async fn run(ctx: &Ctx, args: &NewArgs) -> Result<()> { dash_amount(credits_to_dash(spec.budget_credits)), expiry_text(spec.expires_at_ms) ); + super::print_kept_encryption(&encryption); println!(" stored in {}", stored.describe()); println!(" balance {} DASH", dash_amount(credits_to_dash(balance))); println!(" next: cd my-project && dg init"); diff --git a/crates/dg/src/ci.rs b/crates/dg/src/ci.rs index ab0fb6fba..a942f7c9f 100644 --- a/crates/dg/src/ci.rs +++ b/crates/dg/src/ci.rs @@ -247,7 +247,12 @@ fn key_holder(ctx: &Ctx, args: &RunnerNewArgs, me: &str) -> Result Vec { if forge_core::keystore::is_file_source(&path) { out.push(file_mode_check(&path)); } - out.push(if bridge.doc_op_key().is_ok() { - Check::ok("keys", "HIGH/CRITICAL auth key for writes") - } else { - Check::fail( + if bridge.doc_op_key().is_err() { + out.push(Check::fail( "keys", "no HIGH or CRITICAL AUTHENTICATION key: nothing can be signed", "export the identity again from the bridge (it includes the auth keys)", - ) - }); - out.push(match ctx.connect().await { - Err(_) => Check::warn( + )); + } + let client = ctx.connect().await; + let identity = match &client { + Ok(c) => Some(c.fetch_identity(&bridge.identity_id).await), + Err(_) => None, + }; + if bridge.doc_op_key().is_ok() { + out.push(match (&client, &identity) { + (Ok(c), Some(Ok(identity))) => { + let report = crate::auth::key_report(c, identity, &bridge, ctx).await; + let access = crate::auth::private_access(ctx, &bridge, Some(identity)); + keys_check(&report, &access, crate::auth::now_ms()) + } + // Not on chain, or not reachable: the balance row says which; what the key file + // holds is all that can be said. + _ => Check::ok( + "keys", + "HIGH/CRITICAL auth key for writes (its limits on chain not checked)", + ), + }); + } + out.push(match (client, identity) { + (Err(_), _) | (_, None) => Check::warn( "balance", "not checked: Platform unreachable (see network)", "run `dg doctor` again when the network row passes", ), - Ok(client) => match client.get_balance(&bridge.identity_id).await { + (Ok(_), Some(fetched)) => match fetched.map(|i| i.balance()) { Ok(credits) => balance_check(credits), Err(forge_core::Error::NotFound) => Check::fail( "balance", @@ -544,6 +562,37 @@ async fn check_identity(ctx: &Ctx) -> Vec { out } +/// The `keys` row: what the key in use can sign, as the chain says (QW2-005: a CI runner key +/// bound to `checkRun` passed as "HIGH/CRITICAL auth key for writes"), whether it still can +/// (budget, expiry, `now_ms`), and whether private repositories open with it (an `ENCRYPTION` +/// key held beside it). +fn keys_check( + report: &crate::auth::KeyReport, + access: &crate::auth::PrivateAccess, + now_ms: u64, +) -> Check { + let Some(key_id) = report.key_id else { + return Check::fail( + "keys", + "the key in use is not a live key of this identity (disabled, or never registered)", + "sign in again: `dg auth login ` or `dg auth login --mnemonic`", + ); + }; + let line = crate::auth::key_line(Some(report), None, true); + if let Some(why) = report.spent_or_expired(now_ms) { + let fix = if report.doc_type.is_some() { + "`dg ci runner new` registers a fresh runner key".to_string() + } else { + format!("`dg auth keys add --replace {key_id}` registers a fresh limited key") + }; + return Check::fail("keys", format!("{line}: {why}, so it signs nothing"), fix); + } + let also = crate::auth::private_line(Some(access), report.doc_type.is_some(), Some(key_id)) + .map(|l| format!("; {l}")) + .unwrap_or_default(); + Check::ok("keys", format!("{line}{also}")) +} + fn balance_check(credits: u64) -> Check { let dash = credits_to_dash(credits); let detail = format!("{} DASH", dash_amount(dash)); diff --git a/crates/dg/src/webhook.rs b/crates/dg/src/webhook.rs index 7ed67b1c8..0ae0420b6 100644 --- a/crates/dg/src/webhook.rs +++ b/crates/dg/src/webhook.rs @@ -20,7 +20,7 @@ use forge_core::webhooks::{ WebhookService, }; -use crate::common::{resolve, RepoRef}; +use crate::common::{resolve, Reader, RepoRef}; use crate::context::Ctx; use crate::fmt::{cost_json, cost_line, dash_usd_price}; use crate::secret_out::{self, Stream, Surroundings}; @@ -275,12 +275,13 @@ fn refuse_unless_shown(here: Surroundings) -> Result<()> { .into()) } +/// A read: no key is opened for a public repository (QW-034: a sealed key with no terminal +/// stopped it with E303, while every other list reads on). async fn list(ctx: &Ctx, repo: &str) -> Result<()> { - let repo_ref = RepoRef::parse(repo)?; - let (client, _bridge, identity) = ctx.connect_with_identity().await?; - let handle = resolve(&client, &identity, &repo_ref).await?; + let r = Reader::open(ctx, repo).await?; + let handle = &r.repo; let hooks = newest_per_hook( - WebhookReader::new(&client) + WebhookReader::new(&r.client) .for_repo(handle.id()) .await .context("listing webhooks")?, diff --git a/crates/forge-core/src/keyring.rs b/crates/forge-core/src/keyring.rs index bf7c5ca14..47520bcca 100644 --- a/crates/forge-core/src/keyring.rs +++ b/crates/forge-core/src/keyring.rs @@ -127,6 +127,33 @@ impl EncryptionKeys { .map(|(id, (k, _))| (*id, k)) } + /// The keys held, as identity-file entries (`ENCRYPTION` / `MEDIUM`, the private key as hex + /// and as a WIF for `network`, no derivation path): what `dg auth login` keeps beside a + /// limited signing key, so private repositories open with no master key on disk, as in the + /// web app (QW2-004). Disabled ones are kept too: they still open history. + pub fn to_identity_keys( + &self, + network: &platform::Network, + ) -> Vec { + use platform::identity_keys::{encryption_key_entry, EncryptionSecret}; + self.keys + .iter() + .filter_map(|(id, (k, _))| { + let secret = EncryptionSecret::new(*k.secret_bytes()).ok()?; + Some(encryption_key_entry(&secret, *id, network, "")) + }) + .collect() + } + + /// The ids of the keys held that are enabled on chain. + pub fn enabled_ids(&self) -> Vec { + self.keys + .iter() + .filter(|(_, (_, enabled))| *enabled) + .map(|(id, _)| *id) + .collect() + } + /// The private key with `id`, enabled or not. fn get(&self, id: u32) -> Option<&PrivateKey> { self.keys.get(&id).map(|(k, _)| k) @@ -168,7 +195,7 @@ pub fn no_encryption_key_held_because(action: &str, why: &str) -> Error { codes::NO_ENCRYPTION_KEY, format!("{action}: the key stored on this computer holds no encryption key"), ) - .cause(format!("{why}; the key source in use holds none that matches an enabled one on your identity (a limited key from `dg auth login` or `dg auth new` is a signing key only)")) + .cause(format!("{why}; the key source in use holds none that matches an enabled one on your identity (a limited key stored by an older dg, or with --signing-only, is a signing key only)")) .fix(format!( "if your identity has an ENCRYPTION key (`dg auth keys list`), store a source that holds it: {}", crate::user_error::FIX_FULL_KEY_LOGIN @@ -2328,7 +2355,9 @@ mod tests { u.message ); assert!( - u.fix.iter().any(|f| f.contains("--mnemonic --full-key")), + u.fix + .iter() + .any(|f| f.contains("dg auth login --mnemonic --replace")), "{:?}", u.fix ); @@ -3075,6 +3104,52 @@ mod tests { assert_eq!(short_branch("refs/tags/v1"), "refs/tags/v1"); } + /// QW2-004: the encryption keys a source holds, as the entries a limited-key login stores + /// beside its signing key: only those matching the identity's keys on chain, and they are + /// held again when read back. + #[test] + fn held_encryption_keys_become_identity_file_entries() { + use crate::platform::identity_keys::{encryption_key_entry, EncryptionSecret}; + let net = platform::Network::from_key("testnet"); + let entry = |seed: u8, id| { + encryption_key_entry(&EncryptionSecret::new([seed; 32]).unwrap(), id, &net, "m/x") + }; + let mut bridge = BridgeIdentity::from_dfk1( + "dfk1:testnet:8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB:5:FAKE-wif", + ) + .unwrap(); + // key 4 is on chain; key 9 is not (a stale file): only 4 is kept + bridge.identity_keys.extend([entry(7, 4), entry(8, 9)]); + let on_chain = |e: &crate::keystore::IdentityKey| IdentityKeyInfo { + id: e.id, + purpose: "ENCRYPTION".into(), + security_level: "MEDIUM".into(), + key_type: "ECDSA_SECP256K1".into(), + public_key: hex::decode(&e.public_key_hex).unwrap(), + disabled: false, + bound_to: None, + }; + let chain = [on_chain(&entry(7, 4))]; + let kept = EncryptionKeys::held(&bridge, &chain, "CORE", &net).to_identity_keys(&net); + assert_eq!(kept.len(), 1); + assert_eq!(kept[0].id, 4); + assert_eq!(kept[0].purpose, "ENCRYPTION"); + assert_eq!(kept[0].public_key_hex, entry(7, 4).public_key_hex); + assert_eq!(kept[0].derivation_path, ""); + // stored beside the signing key, they open again + let mut stored = BridgeIdentity::from_dfk1( + "dfk1:testnet:8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB:5:FAKE-wif", + ) + .unwrap(); + stored.identity_keys.extend(kept); + let back = + BridgeIdentity::from_source_text(stored.to_json_with_secrets().expose()).unwrap(); + let again = EncryptionKeys::held(&back, &chain, "CORE", &net); + assert_eq!(again.sender().map(|(id, _)| id), Some(4)); + assert!(back.master_key().is_none()); + assert_eq!(back.doc_op_key().unwrap().id, 5); + } + #[test] fn recipient_is_the_highest_enabled_encryption_key() { let k = |id, disabled, purpose: &str| IdentityKeyInfo { diff --git a/crates/forge-core/src/keystore.rs b/crates/forge-core/src/keystore.rs index dfe0c2520..e9388a9c3 100644 --- a/crates/forge-core/src/keystore.rs +++ b/crates/forge-core/src/keystore.rs @@ -649,6 +649,31 @@ pub fn create_private_file(path: &Path, bytes: &[u8]) -> Result<()> { f.sync_all().map_err(io) } +/// E303 for the sealed key file `shown` that did not open with the passphrase given (from the +/// variable `via`, or typed), naming the file (QW2-022: it was an E204 that named neither of +/// two sealed files). A malformed file keeps `err`'s own message. +fn wrong_passphrase(shown: &str, via: Option<&str>, err: Error) -> Error { + match &err { + Error::Config(msg) if msg.contains("wrong passphrase") => {} + Error::Config(msg) => return Error::Config(format!("{shown}: {msg}")), + _ => return err, + } + let given = via.map_or_else(|| "the passphrase typed".to_string(), str::to_string); + crate::user_error::UserError::new( + crate::user_error::codes::IDENTITY_UNREADABLE, + format!("wrong passphrase for {shown}"), + ) + .cause(format!( + "{given} does not open this sealed file (or the file was modified)" + )) + .fix("each sealed file keeps its own passphrase: in a terminal each is asked for") + .fix( + "in scripts, DASH_FORGE_PASSPHRASE opens your key and DASH_FORGE_RUNNER_PASSPHRASE \ + the --runner file of `dg ci runner new`", + ) + .into() +} + /// Security levels acceptable for signing a document create/delete, in preference /// order. Document ops accept HIGH (spike S0.7); CRITICAL also works and is the /// fallback when a HIGH key is absent. @@ -680,6 +705,18 @@ impl BridgeIdentity { /// passphrase once). [`Self::from_source_text`] parses it; `dg` also hands it to /// `git-remote-dash` ([`crate::key_handoff`]) so the helper never asks again. pub fn unlock_source(path: impl AsRef) -> Result { + Self::unlock_source_with(path, &[crate::sealed::PASSPHRASE_ENV]) + } + + /// [`Self::load_from_file`], a sealed file's passphrase read from the first of + /// `passphrase_envs` that is set (else asked for): a second sealed file in one command + /// keeps its own passphrase (QW2-022, `dg ci runner new --runner`). + pub fn load_from_file_with(path: impl AsRef, passphrase_envs: &[&str]) -> Result { + Self::from_source_text(Self::unlock_source_with(path, passphrase_envs)?.expose()) + } + + /// [`Self::unlock_source`] with [`Self::load_from_file_with`]'s passphrase variables. + pub fn unlock_source_with(path: impl AsRef, passphrase_envs: &[&str]) -> Result { let path = path.as_ref(); if let Some(inline) = path.to_str().filter(|s| s.starts_with(DFK1_PREFIX)) { // Refused here, with the format's own message, rather than later. @@ -713,8 +750,10 @@ impl BridgeIdentity { .map_err(|e| Error::Io(format!("reading identity file {shown}: {e}")))?, ); if crate::sealed::is_sealed(&raw) { - let pass = crate::sealed::passphrase(&shown, false)?; - let plain = crate::sealed::open(&raw, pass.expose())?; + let pass = crate::sealed::passphrase_from(passphrase_envs, &shown, false)?; + let via = crate::sealed::passphrase_env_in_use(passphrase_envs); + let plain = crate::sealed::open(&raw, pass.expose()) + .map_err(|e| wrong_passphrase(&shown, via, e))?; let text = std::str::from_utf8(&plain) .map_err(|_| Error::Io("the sealed identity file does not hold text".into()))?; return Ok(Secret::new(text)); @@ -953,6 +992,41 @@ mod tests { } }"#; + /// QW2-022: a sealed file that does not open is E303 naming the file and where the + /// passphrase came from (it was an E204 naming neither), and the first variable given wins. + #[test] + fn a_wrong_passphrase_names_the_file_and_the_variable() { + const ENV: &str = "DASH_FORGE_TEST_QW2_022_PASSPHRASE"; + const OTHER: &str = "DASH_FORGE_TEST_QW2_022_UNSET"; + let t = tempfile::tempdir().unwrap(); + let p = t.path().join("runner.json"); + std::fs::write( + &p, + crate::sealed::seal(FIXTURE.as_bytes(), "correct horse battery").unwrap(), + ) + .unwrap(); + std::env::set_var(ENV, "not the passphrase"); + let err = BridgeIdentity::unlock_source_with(&p, &[OTHER, ENV]).unwrap_err(); + std::env::set_var(ENV, "correct horse battery"); + let opened = BridgeIdentity::load_from_file_with(&p, &[OTHER, ENV]); + std::env::remove_var(ENV); + let crate::Error::User(u) = err else { + panic!("expected a phrased error, got {err}") + }; + assert_eq!(u.code, "E303"); + assert!(u.message.contains("runner.json"), "{}", u.message); + assert!( + u.cause.as_deref().unwrap_or("").contains(ENV), + "{:?}", + u.cause + ); + assert!(u + .fix + .iter() + .any(|f| f.contains("DASH_FORGE_RUNNER_PASSPHRASE"))); + assert_eq!(opened.unwrap().network, "testnet"); + } + #[test] fn parses_bridge_fixture() { let id = BridgeIdentity::from_json(FIXTURE).expect("fixture should parse"); diff --git a/crates/forge-core/src/sealed.rs b/crates/forge-core/src/sealed.rs index 7cbaff279..f4d75c534 100644 --- a/crates/forge-core/src/sealed.rs +++ b/crates/forge-core/src/sealed.rs @@ -33,6 +33,10 @@ use crate::keystore::Secret; /// Environment variable a passphrase is read from before prompting. pub const PASSPHRASE_ENV: &str = "DASH_FORGE_PASSPHRASE"; +/// The passphrase of `dg ci runner new --runner ` when that file is sealed with another +/// passphrase than your own key (QW2-022); [`PASSPHRASE_ENV`] when unset. +pub const RUNNER_PASSPHRASE_ENV: &str = "DASH_FORGE_RUNNER_PASSPHRASE"; + /// Set by a program that must never read from the terminal (the importer, `dg --json`): a /// sealed file then needs [`PASSPHRASE_ENV`], and no prompt appears. `GIT_TERMINAL_PROMPT=0` /// has the same effect, so the helper does not ask when git was told not to. @@ -218,22 +222,39 @@ pub fn open(raw: &str, passphrase: &str) -> Result>> { /// The passphrase for `what`: [`PASSPHRASE_ENV`] when set, else a hidden prompt on the /// terminal. `confirm` asks twice (for a new file) and enforces [`MIN_PASSPHRASE_LEN`]. pub fn passphrase(what: &str, confirm: bool) -> Result { - if let Some(p) = std::env::var_os(PASSPHRASE_ENV).filter(|v| !v.is_empty()) { - let p = p + passphrase_from(&[PASSPHRASE_ENV], what, confirm) +} + +/// The first of `envs` that is set (not empty): where [`passphrase_from`] takes the +/// passphrase from, `None` when it asks for it. +pub fn passphrase_env_in_use<'a>(envs: &[&'a str]) -> Option<&'a str> { + envs.iter() + .copied() + .find(|e| std::env::var_os(e).is_some_and(|v| !v.is_empty())) +} + +/// [`passphrase`], reading the first of `envs` that is set before prompting (a second sealed +/// file in one command, with its own passphrase: `DASH_FORGE_RUNNER_PASSPHRASE`, then +/// [`PASSPHRASE_ENV`]). Messages name the first. +pub fn passphrase_from(envs: &[&str], what: &str, confirm: bool) -> Result { + let first = envs.first().copied().unwrap_or(PASSPHRASE_ENV); + if let Some(env) = passphrase_env_in_use(envs) { + let p = std::env::var_os(env) + .unwrap_or_default() .into_string() - .map_err(|_| Error::Config(format!("{PASSPHRASE_ENV} is not UTF-8")))?; + .map_err(|_| Error::Config(format!("{env} is not UTF-8")))?; return Ok(Secret::new(p)); } if !prompts_allowed() { return Err(Error::Config(format!( - "{what} needs a passphrase and this command does not prompt; set {PASSPHRASE_ENV}" + "{what} needs a passphrase and this command does not prompt; set {first}" ))); } let prompt = |label: &str| { rpassword::prompt_password(label).map_err(|e| { Error::Config(format!( "{what} needs a passphrase and there is no terminal to ask on ({e}); set \ - {PASSPHRASE_ENV}" + {first}" )) }) }; diff --git a/crates/forge-core/src/user_error.rs b/crates/forge-core/src/user_error.rs index 7342e9aaa..df5f33fec 100644 --- a/crates/forge-core/src/user_error.rs +++ b/crates/forge-core/src/user_error.rs @@ -765,10 +765,11 @@ fn not_permitted(ctx: &ErrorContext<'_>, action: &str, reason: &str, needs: &str } } -/// How a member stores a key source that can open private repositories: the limited key -/// `dg auth login` and `dg auth new` store is a signing key only, so the full identity is kept -/// instead, from its file or from the recovery words (QW-040). -pub const FIX_FULL_KEY_LOGIN: &str = "`dg auth login --full-key `, or `dg auth login --mnemonic --full-key` with your 12 recovery words"; +/// How a member stores a key source that can open private repositories: `dg auth login` +/// keeps the identity's encryption key beside the limited signing key (QW2-004), from its file +/// or from the recovery words (QW-040). A key stored by an older `dg`, or with +/// `--signing-only`, is a signing key only: signing in again fixes it. +pub const FIX_FULL_KEY_LOGIN: &str = "`dg auth login --replace ` (the key `dg auth status` shows), or `dg auth login --mnemonic --replace ` with your 12 recovery words: it stores a new limited key with your encryption key beside it (never the master key) and disables the old one"; /// The E601 way in: the owner's add, and before it, for someone not a member yet, their own /// consent (`member_consent`: a `member` document naming the add is refused without it, E604; @@ -2783,8 +2784,13 @@ mod tests { u.fix ); let u = private_needs_identity("alice/secret"); - assert!(u.fix[0].contains("--full-key"), "{:?}", u.fix); - assert!(u.fix[0].contains("--mnemonic --full-key"), "{:?}", u.fix); + // QW2-004: a limited key with the encryption key, not the master key + assert!( + u.fix[0].contains("dg auth login --mnemonic --replace"), + "{:?}", + u.fix + ); + assert!(!u.fix[0].contains("--full-key"), "{:?}", u.fix); } #[test] diff --git a/crates/git-remote-dash/src/helper.rs b/crates/git-remote-dash/src/helper.rs index 4d3e7b4e9..d6decedc0 100644 --- a/crates/git-remote-dash/src/helper.rs +++ b/crates/git-remote-dash/src/helper.rs @@ -2904,7 +2904,7 @@ async fn load_signer( format!("{why}; DASH_FORGE_KEY is not set and no default identity is recorded") }; if repo.visibility == forge_core::rules::v2::Visibility::Private { - // A limited key (what `dg auth login ` stores) cannot open it: E306 next. + // Only a key source with the encryption key opens it (`dg auth login`). return Err(UserError::new(codes::NO_IDENTITY, "no identity configured") .cause(why) .fix(format!( diff --git a/docs/errors.md b/docs/errors.md index 8b7112063..d7e01f0a0 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -131,7 +131,7 @@ Fix: none within the private repository in this release. The label definitions ( Fix: `dg auth new` creates an identity and stores a limited key for this computer; `dg auth login ` (or `dg auth login --mnemonic`) signs in with an existing one. For a single command pass `--identity `, or set `DASH_FORGE_KEY` to a file, a `keychain:dash-forge//` entry, or a `dfk1:` key (this is also how `git-remote-dash` finds the key; without it the helper uses the default `dg auth` recorded, then `~/.config/dash-forge/identities/.identity.json`). -A private repository needs more than a signing key: its content is encrypted to each member's `ENCRYPTION` key, which the limited key `dg auth login ` and `dg auth new` store does not hold (that would be [E306](#e306) next). For one, sign in with `dg auth login --full-key `, or `dg auth login --mnemonic --full-key` with the 12 recovery words. +A private repository needs more than a signing key: its content is encrypted to each member's `ENCRYPTION` key. `dg auth login `, `dg auth login --mnemonic` and `dg auth new` store it beside the limited signing key (never the master key), unless `--signing-only`; a key stored by an older `dg` lacks it (that would be [E306](#e306) next): sign in again with `--replace `. ## E302 @@ -143,7 +143,7 @@ Fix: pass the identity file with `--master `, or type the recovery words w **Identity unreadable.** The identity file or stored key is missing, unreadable, not a bridge-format identity export or `dfk1:` key, or a sealed key file could not be opened (wrong passphrase). -Fix: `dg auth status` shows which key source is in use. Sign in again with `dg auth login ` or `dg auth login --mnemonic`. For a sealed file, set `DASH_FORGE_PASSPHRASE` or type the passphrase when asked. +Fix: `dg auth status` shows which key source is in use. Sign in again with `dg auth login ` or `dg auth login --mnemonic`. For a sealed file, set `DASH_FORGE_PASSPHRASE` or type the passphrase when asked. A wrong passphrase names the file and where the passphrase came from. Each sealed file keeps its own passphrase: `dg ci runner new --runner ` reads the runner file's from `DASH_FORGE_RUNNER_PASSPHRASE` (else `DASH_FORGE_PASSPHRASE`), so a script can open your key and the runner's when they differ. Reads do not open the key: `dg auth status`, `dg auth balance`, and `dg storage status` / `dg cost audit` of a public repository work with a sealed key and no terminal (the status says the key itself was not checked). @@ -174,10 +174,10 @@ Fix: register a fresh one with your master key (used once): `dg auth login ` has no encryption key" (`dg collab add` to a private repository): the member you named has no enabled `ENCRYPTION` key on their identity. -Fix: for the first, store a key source that holds it: `dg auth login --full-key ` (a passphrase-sealed file), or `dg auth login --mnemonic --full-key` with the 12 recovery words if you have no identity file (a `dg auth new` identity). For one command, point `DASH_FORGE_KEY` at the identity file. If the identity has no ENCRYPTION key at all, `dg auth keys add --encryption` adds one, derived from the recovery words (one identity update signed by the master key). A member you are adding does this themselves, or uses Settings → Keys → Enable private repos in the web app. See [identity and keys](guides/identity-and-keys.md#encryption-key-private-repositories). +Fix: for the first, sign in again, replacing the key in use (`dg auth status` shows its id, and its `Private:` line prints the command): `dg auth login --replace `, or `dg auth login --mnemonic --replace ` with the 12 recovery words if you have no identity file (a `dg auth new` identity). It registers a new limited key, stores your encryption key beside it and disables the old key; the master key is used once and not stored. For one command, point `DASH_FORGE_KEY` at the identity file. If the identity has no ENCRYPTION key at all, `dg auth keys add --encryption` adds one, derived from the recovery words (one identity update signed by the master key). A member you are adding does this themselves, or uses Settings → Keys → Enable private repos in the web app. See [identity and keys](guides/identity-and-keys.md#encryption-key-private-repositories). ## E307 diff --git a/docs/guides/ci.md b/docs/guides/ci.md index 81dafe09a..896c55432 100644 --- a/docs/guides/ci.md +++ b/docs/guides/ci.md @@ -36,6 +36,10 @@ The key is written to `runner.dfk1` (0600, unencrypted) *before* it is registere `dg auth export --format dfk1 --reveal-secrets -o -` prints this computer's limited key on stdout, for piping straight into a secret store (`| gh secret set DASH_FORGE_KEY`). That key can sign any Forge document within its budget; it is not a runner key, so use `dg ci runner new` for check runs. It is refused with `--json` and when a CI variable is set. Never run it where stdout is a log. +In a terminal, a passphrase-sealed key and a sealed `runner.json` are each asked for. In a script, `DASH_FORGE_PASSPHRASE` opens your key and `DASH_FORGE_RUNNER_PASSPHRASE` opens `runner.json` (it falls back to `DASH_FORGE_PASSPHRASE`); a wrong one is [`E303`](../errors.md#e303) naming the file. + +`dg auth status` and `dg doctor` with the runner key describe it as bound to `checkRun` documents only (a CI runner key), with its budget and expiry. + Other commands: | Command | Does | diff --git a/docs/guides/collaborating.md b/docs/guides/collaborating.md index f54deea57..54fda1526 100644 --- a/docs/guides/collaborating.md +++ b/docs/guides/collaborating.md @@ -119,7 +119,7 @@ Leave the description empty if the project's purpose is itself sensitive. **Repairs.** A maintainer's `dg` and `git push` check the key on every visit: if a non-member still holds the current key (two maintainers removed members at the same time), or a member has no wrap to their current encryption key (they replaced it, or an add was interrupted), `dg repo keys repair` fixes it. The key is re-read before every write, so nothing is ever written under a key that was rotated away. -**Cloning.** `git clone dash:///` works as for a public repository when your key source holds your encryption key: the identity file (`DASH_FORGE_KEY`) or `dg auth login --full-key`, not the limited key a plain `dg auth login` stores ([identity and keys](identity-and-keys.md#encryption-key-private-repositories)). A non-member gets [`E307`](../errors.md#e307); an identity without an encryption key gets [`E306`](../errors.md#e306). +**Cloning.** `git clone dash:///` works as for a public repository when your key source holds your encryption key: what `dg auth login` and `dg auth new` store (the limited key with your encryption key beside it), or the identity file (`DASH_FORGE_KEY`); not a key stored with `--signing-only` or by an older `dg` ([identity and keys](identity-and-keys.md#encryption-key-private-repositories)). A non-member gets [`E307`](../errors.md#e307); an identity without an encryption key gets [`E306`](../errors.md#e306). **No recovery.** If every member loses their encryption key (every copy of every identity file and mnemonic), the contents cannot be decrypted by anyone. diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index 3dce62551..812d86e5b 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -60,11 +60,11 @@ Do this once: 1. Write the 12 words on paper, in order. Keep two copies in separate places. 2. Keep the words offline. Do not put them in a password manager that syncs, in a note-taking app, or in a screenshot. -3. Treat the identity file (`dash-identity-.json`) like the words. It contains them, plus every private key. Keep it offline once you have signed in: `dg auth login` stores only a limited key. If you keep it on disk, keep it `chmod 600`; `dg doctor` warns when an identity file it uses is readable by other users, and `dg doctor --fix` tightens it. +3. Treat the identity file (`dash-identity-.json`) like the words. It contains them, plus every private key. Keep it offline once you have signed in: `dg auth login` stores only a limited key and the encryption key. If you keep it on disk, keep it `chmod 600`; `dg doctor` warns when an identity file it uses is readable by other users, and `dg doctor --fix` tightens it. 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. +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. 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. @@ -90,7 +90,7 @@ A key *source* (`--identity`, `DASH_FORGE_KEY`, the recorded default) is any of: Things to know: -- On macOS `dg` reads and writes the keychain through Apple's `/usr/bin/security`, so `dg`, `git-remote-dash` and upgraded copies of either read the entry without an access dialog. Any program running as you can ask `security` for it without a prompt: the keychain protects entries at rest and from other users. What `dg` keeps there is limited identity keys (a budget, an expiry, Forge contracts only) and the storage credentials `dg storage add` is given, so scope those to the one bucket. A full identity (`dg auth login --full-key`: master key and recovery words) never goes there; it is always a passphrase-sealed file. The GitHub CLI stores its token the same way. +- On macOS `dg` reads and writes the keychain through Apple's `/usr/bin/security`, so `dg`, `git-remote-dash` and upgraded copies of either read the entry without an access dialog. Any program running as you can ask `security` for it without a prompt: the keychain protects entries at rest and from other users. What `dg` keeps there is limited identity keys (a budget, an expiry, Forge contracts only), with your identity's encryption key beside them (it reads your private repositories; `--signing-only` leaves it out), and the storage credentials `dg storage add` is given, so scope those to the one bucket. A full identity (`dg auth login --full-key`: master key and recovery words) never goes there; it is always a passphrase-sealed file. The GitHub CLI stores its token the same way. - Over SSH there is no keychain dialog to answer; use a sealed key file there (`DASH_FORGE_NO_KEYCHAIN=1 dg auth login …`). - `--insecure-plaintext` stores the key unencrypted (0600) where there is no keychain and no way to type a passphrase. Every later use warns. - In the web app, the key never leaves that browser, but any script running on the page can use it while it is unlocked ([details](#the-browser-vault-and-its-limits)). Lock or sign out on shared machines. @@ -138,7 +138,7 @@ If the **MASTER** key or the 12 words leak, rotating does not help: whoever has A private repository encrypts its content under a repository key, and each member gets that key wrapped (encrypted) to their identity's **ENCRYPTION** key. Without one, nobody can add you to a private repository and you cannot create one. Identities from `dg auth new`, the bridge and the web app carry key 4 for this. -**Using it from the CLI.** Reading or writing a private repository needs the ENCRYPTION key's private half, and the limited key `dg auth login` stores is a signing key only. For private repositories, point `DASH_FORGE_KEY` at your identity file, or sign in with `dg auth login --full-key ` (kept in a passphrase-sealed file, never the keychain). Without it, private-repo commands stop with [`E306`](../errors.md#e306). +**Using it from the CLI.** Reading or writing a private repository needs the ENCRYPTION key's private half. `dg auth login` (from the identity file or the recovery words) and `dg auth new` store it beside the limited signing key, where the limited key is kept (the keychain, or a passphrase-sealed file), as the web app's "Enable private repos" does: private repositories work with no master key on disk. `dg auth status` shows it (`Private:`). `--signing-only` (or `--insecure-plaintext`, which would write it in the clear) stores the signing key alone; a key stored by an older `dg` is one too, and signing in again with `--replace ` adds it (`dg auth status` prints the command). `dg auth keys add` keeps the encryption keys the key it replaces holds. Without it, private-repo commands stop with [`E306`](../errors.md#e306); `DASH_FORGE_KEY=` works for one command. **An identity without one** can add it: @@ -185,7 +185,7 @@ From the terminal: ```sh dg auth new [--amount 0.05] [--name alice] # 12 words → deposit QR → identity + a limited key in the keychain -dg auth login | --mnemonic # import once; registers a limited key and stores only that +dg auth login | --mnemonic # import once; registers a limited key and stores it with the encryption key dg auth status # identity, name, key, budget left, expiry, balance, where it is stored dg auth export --new-key --format dfk1 --reveal-secrets -o runner.dfk1 # a key for CI dg auth name register