Compare commits

...

26 Commits

Author SHA1 Message Date
mnovak 04a6031c5d [browser] Firefox: one extension source for Firefox, Edge and Chrome; frames, public suffixes, the caller check, 2FA codes and saving logins; v0.20.0
- custos-browser: fill_allowed (a frame gets a login only when its page would too), public suffixes match
  exactly only (psl), ports digits only, caller (which extension started the host); spoof tests.
- custos-native: answers not_allowed to anything but the Custos extension, browser_totp and browser_save,
  the frame's and the page's origins, a random session per connection (its match code on Custos's cards).
- extension/: manifest.firefox.json (gecko id custos@marek-novak.cz) and manifest.chromium.json, one set of
  scripts; the popup shows 2FA codes, the save offer and the connection's code; tools/extension.mjs builds
  each browser and reproducible zips; tools/extension-test.mjs runs the background against a fake browser.
2026-11-22 21:57:35 +01:00
mnovak a3b3a32745 [repo] Merge: fix/android-grant-compat (a key the Android grant makes is standing-granted; v0.19.1, PR #26) 2026-11-21 09:07:02 +01:00
mnovak 0eee7632ae [vault] Signing: a key the Android grant makes is standing-granted, a value older cores read; v0.19.1
0.19.0 wrote a new security action, android-key-made, which every older core refuses. The phone app and the
web vault open the same vault with their own pinned core, so a vault in which the grant made a key would stop
opening there. The key's creation is now standing-granted with 'Android grant made <id> for <repo> pipeline
release'; the grant itself is a member older cores ignore.
2026-11-21 09:06:35 +01:00
mnovak 6588461438 [repo] Merge: feature/android-grant (the Android grant: every Domi app's release APK and its key on first use; v0.19.0, PR #25) 2026-11-21 08:58:25 +01:00
mnovak e533a38883 [vault] Signing: the Android grant, one answer for every Domi app's release APK and its key on first use; v0.19.0
signing.android: patterns owner/name or owner/*, the certificate's O and C, uses, last used and the keys it
made. A request fits when it is an apk from this PC's pipe with a run, pipeline release, a covered repository,
and that repository's own app key (<name>-android, scoped to exactly it and release, role release), while
card-signing is not ticked; a key's first signature fits. android_grant_make_key makes that key for a covered
repository (android-key-made in the security audit). Granting and revoking write standing-granted and
standing-revoked. A vault whose grant made a key needs core 0.19.0; older cores drop the grant itself.
2026-11-21 08:57:48 +01:00
mnovak 47146a6ea2 [repo] Merge: fix/team-review (deployment ticket on target.request, unknown author under others, refuse after sign; v0.18.1, PR #24) 2026-11-17 12:45:27 +01:00
mnovak 98d56f4673 [team] Review fixes: a deployment ticket and a MAC on target.request, an unknown author is unsatisfiable under others, a signed request cannot be refused afterwards; TEAM.md limits; v0.18.1 2026-11-17 12:44:54 +01:00
mnovak f95c768bfa [repo] Merge: feature/team-vault (team vaults, policies, sign.request, proofs, cosign and Tauri envelopes; v0.18.0, PR #23) 2026-11-17 12:21:44 +01:00
mnovak 3bb05bf6f1 [team] Team vaults: rustfmt on the files this change touches 2026-11-17 12:15:18 +01:00
mnovak e3ede760bd [team] Team vaults: member keys, member slots (kind 6), policies per environment, the canonical sign.request, approval statements, policy proofs; cosign and Tauri updater envelopes; v0.18.0 2026-11-17 11:38:41 +01:00
mnovak 9b40c834dd [repo] Merge: feature/approval-25h (a deploy approval may expire up to 25 hours ahead; v0.17.1, PR #22) 2026-11-14 17:51:37 +01:00
mnovak f84ac575bd [sign] Approval: a deploy approval may expire up to 25 hours ahead (was an hour), so a release's day-long card can still be signed; v0.17.1 2026-11-14 17:12:20 +01:00
mnovak ff14c8902f [repo] Merge: feature/recovery-key (the recovery key: one per two-factor vault, taken only by Vault::recover; v0.17.0, PR #21) 2026-11-12 23:09:31 +01:00
mnovak 2b4a78644b [vault] The recovery key is printed as 8 groups of 8 2026-11-12 23:09:02 +01:00
mnovak 8d5d08afcb [vault] The recovery key: one per two-factor vault, returned once, taken only by Vault::recover, which replaces every factor and the key (slot kind 5, three audit actions); v0.17.0 2026-11-12 13:24:00 +01:00
mnovak 61b98ee9b0 [repo] Merge: fix/standing-count (a standing approval's use count saturates; v0.16.1, PR #20) 2026-11-11 16:19:54 +01:00
mnovak 2c2d56b856 [vault] Standing approvals: a rule's use count saturates instead of overflowing (a stored count at its end made the next standing signature panic in debug builds); v0.16.1 2026-11-11 16:19:35 +01:00
mnovak 95613f4ed0 [repo] Merge: feature/standing-approval (standing approvals: always allow for one repository, key, kind, pipeline and origin; the outcome standing; v0.16.0, PR #19) 2026-11-11 16:13:04 +01:00
mnovak 2d04f32f57 [vault] Standing approvals: a rule Mark grants from a card (repository, key, kind, pipeline, origin; an approval's targets), signed without asking as outcome standing, counted, revocable, paused by card-signing; never a key's first signature or a mailbox release signature; v0.16.0 2026-11-11 16:02:14 +01:00
mnovak 1292c09d02 [repo] Merge: feature/browser-ext-v2 (autofill for Edge and Chrome: custos-browser, custos-native, the MV3 extension, docs/BROWSER.md; v0.15.0, PR #18) 2026-11-10 21:50:00 +01:00
mnovak a45d1054f0 [browser] Docs: docs/BROWSER.md (the pieces, which login goes where, the messages, registration, threat model); v0.15.0 2026-11-09 08:55:55 +01:00
mnovak 4e8fb6a8f5 [browser] Autofill for Edge and Chrome: custos-browser (which login fits which page, native messaging frames), custos-native (the host), the MV3 extension 2026-11-09 08:54:08 +01:00
mnovak aa5b692651 [repo] Merge: fix/android-sets (an Android key never counts as the release or test set; v0.14.1, PR #17) 2026-11-08 00:56:35 +01:00
mnovak 6f4075f7e3 [vault] Android: an Android key never counts as the release or test set (signing_create, signing_add_approve); v0.14.1 2026-11-08 00:56:18 +01:00
mnovak 54ce09ce61 [repo] Merge: feature/apk-signing (the android key kind and the apk sign kind for Postea's APKs; v0.14.0, PR #16) 2026-11-08 00:33:11 +01:00
mnovak 045f1f5d00 [vault] Android: the android key kind (RSA-4096, self-signed, 100 years) and the apk sign kind (1-4 SHA-512 digests, PKCS#1 v1.5), never unattended; v0.14.0 2026-11-08 00:27:47 +01:00
61 changed files with 9296 additions and 73 deletions
+11
View File
@@ -12,9 +12,15 @@ crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing
crates/custos-team team vaults' pure parts: member keys, policy evaluation, sign.request, approval statements, proofs
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli
crates/custos-browser which login belongs on which page and frame (origins, public suffixes, no fuzzy matching),
which extension started the host, native messaging frames
crates/custos-native the browser extension's native messaging host: five browser_* ops, rebuilt, to custos.exe's pipe only
extension/ the MV3 extension, one source for Firefox (custos@marek-novak.cz) and Edge/Chrome (fixed id
jchkapmceepdnlhagfppeckggaecdcmn); tools/extension.mjs builds each, tools/extension-test.mjs
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
docs/FACTORS.md version 2: any two factors open the vault; the machine store
docs/KEYS.md secret keys, API keys and key pairs
@@ -23,12 +29,17 @@ docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
docs/THREAT_MODEL.md what is and is not protected
docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs
docs/KDBX.md KeePass files: reading, writing, limits, the item mapping and what does not survive
docs/BROWSER.md the browser extension: pieces, matching rule, messages, registration, threat model
docs/SIGNING.md release signing keys, kinds, standing approvals, the audit log
docs/TEAM.md team vaults (member slots, kind 6), policies, sign.request, proofs, cosign and Tauri envelopes
```
## Commands
```
cargo test --workspace # all mandatory tests
cargo test --workspace --release # same, faster Argon2
node tools/extension-test.mjs # the extension's background against a fake browser
node tools/extension.mjs --zip # target/extension/{firefox,chromium}/ and their zips
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
Generated
+65 -10
View File
@@ -327,9 +327,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "custos-browser"
version = "0.20.0"
dependencies = [
"psl",
"zeroize",
]
[[package]]
name = "custos-gen"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -341,7 +349,7 @@ dependencies = [
[[package]]
name = "custos-kdbx"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"aes",
"argon2",
@@ -362,7 +370,7 @@ dependencies = [
[[package]]
name = "custos-keys"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"custos-vault",
"ed25519-dalek",
@@ -373,13 +381,24 @@ dependencies = [
"thiserror",
]
[[package]]
name = "custos-native"
version = "0.20.0"
dependencies = [
"custos-browser",
"rand 0.10.3",
"serde_json",
"windows-sys",
"zeroize",
]
[[package]]
name = "custos-qr"
version = "0.13.0"
version = "0.20.0"
[[package]]
name = "custos-seal"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"chacha20poly1305",
"hkdf",
@@ -392,7 +411,7 @@ dependencies = [
[[package]]
name = "custos-share"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"argon2",
"chacha20poly1305",
@@ -409,12 +428,13 @@ dependencies = [
[[package]]
name = "custos-sign"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"blake2 0.10.6",
"data-encoding",
"ed25519-dalek",
"minisign-verify",
"p256",
"rand 0.10.3",
"rand_core 0.6.4",
"rsa",
@@ -426,9 +446,27 @@ dependencies = [
"zeroize",
]
[[package]]
name = "custos-team"
version = "0.20.0"
dependencies = [
"custos-seal",
"custos-sign",
"data-encoding",
"ed25519-dalek",
"hmac 0.13.0",
"minisign-verify",
"rand 0.10.3",
"serde",
"serde_json",
"sha2 0.11.1",
"thiserror",
"zeroize",
]
[[package]]
name = "custos-totp"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -441,12 +479,14 @@ dependencies = [
[[package]]
name = "custos-vault"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"custos-seal",
"custos-sign",
"custos-team",
"data-encoding",
"ed25519-dalek",
"hkdf",
@@ -465,7 +505,7 @@ dependencies = [
[[package]]
name = "custos-wasm"
version = "0.13.0"
version = "0.20.0"
dependencies = [
"custos-qr",
"custos-seal",
@@ -987,6 +1027,21 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "psl"
version = "2.1.261"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3058f918351d1ee290ff4e70243e419b33269dcb83bc8cd46c5afa8a97a90012"
dependencies = [
"psl-types",
]
[[package]]
name = "psl-types"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
[[package]]
name = "qrcode"
version = "0.14.1"
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.13.0"
version = "0.20.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
+1
View File
@@ -12,6 +12,7 @@ password and secret manager: everything that touches plaintext or keys.
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) |
| `custos-browser`, `custos-native`, `extension/` | The Firefox, Edge and Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "custos-browser"
description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
# Mozilla's Public Suffix List, compiled in: a login for `github.io` or `co.uk` never goes to their subdomains.
psl = "2"
zeroize.workspace = true
+66
View File
@@ -0,0 +1,66 @@
//! Which extension started the native host. Browsers start `custos-native.exe` only for the extensions its
//! host manifest names (`allowed_origins` for Chromium, `allowed_extensions` for Firefox), and they say which
//! one it was in the host's arguments:
//!
//! - **Chromium** (Edge, Chrome): the first argument is the caller's origin, `chrome-extension://<id>/`
//! (then `--parent-window=<n>` on Windows);
//! - **Firefox**: the first argument is the host manifest's path, the second the add-on's id.
//!
//! The host checks them again ([`caller`]) and answers every request from anything else with `not_allowed`,
//! without reaching Custos: a second line behind the browser's own check, for a manifest someone else wrote.
/// The Chromium extension's id, fixed by the public key in its manifest (`extension/manifest.chromium.json`).
pub const CHROMIUM_ID: &str = "jchkapmceepdnlhagfppeckggaecdcmn";
/// The Firefox add-on's id (`browser_specific_settings.gecko.id` in `extension/manifest.firefox.json`).
pub const FIREFOX_ID: &str = "custos@marek-novak.cz";
/// The kind of browser the Custos extension runs in, as its host's arguments say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Browser {
Chromium,
Firefox,
}
/// The caller of the host, from its arguments without the program name; `None` unless it is the Custos
/// extension.
pub fn caller<S: AsRef<str>>(args: &[S]) -> Option<Browser> {
let first = args.first()?.as_ref();
if first == format!("chrome-extension://{CHROMIUM_ID}/") {
return Some(Browser::Chromium);
}
// Firefox: <manifest path> <add-on id>. The path is the browser's business; the id must be exactly ours.
if first.to_ascii_lowercase().ends_with(".json") && args.get(1).map(AsRef::as_ref) == Some(FIREFOX_ID) {
return Some(Browser::Firefox);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_custos_extension_may_use_the_host() {
let edge = ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/", "--parent-window=0"];
assert_eq!(caller(&edge), Some(Browser::Chromium));
let firefox = [r"F:\Apps\Custos\cz.marek_novak.custos.firefox.json", "custos@marek-novak.cz"];
assert_eq!(caller(&firefox), Some(Browser::Firefox));
// Any other extension, a look-alike id, or no arguments at all (started by hand): refused.
let refused: [&[&str]; 11] = [
&["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmnx/"],
&["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn"],
&["CHROME-EXTENSION://JCHKAPMCEEPDNLHAGFPPECKGGAECDCMN/"],
&["moz-extension://jchkapmceepdnlhagfppeckggaecdcmn/"],
&[r"C:\x\manifest.json", "evil@example.com"],
&[r"C:\x\manifest.json", "custos@marek-novak.cz.evil"],
&[r"C:\x\manifest.json", "Custos@marek-novak.cz"],
&["custos@marek-novak.cz"],
&[r"C:\x\manifest.txt", "custos@marek-novak.cz"],
&[],
];
for other in refused {
assert_eq!(caller(other), None, "{other:?}");
}
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine
//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the
//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB.
//!
//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped.
use std::io::{self, Read, Write};
use zeroize::Zeroizing;
/// The largest message the extension may send to the host.
pub const MAX_TO_HOST: usize = 64 * 1024;
/// The largest message Chrome accepts from a host.
pub const MAX_TO_BROWSER: usize = 1024 * 1024;
/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected).
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
let mut len = [0u8; 4];
match r.read_exact(&mut len) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let n = u32::from_le_bytes(len) as usize;
if n > MAX_TO_HOST {
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
}
let mut buf = Zeroizing::new(vec![0u8; n]);
r.read_exact(&mut buf)?;
Ok(Some(buf))
}
/// Writes one frame and flushes it (Chrome reads frame by frame).
pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
if msg.len() > MAX_TO_BROWSER {
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
}
w.write_all(&(msg.len() as u32).to_le_bytes())?;
w.write_all(msg)?;
w.flush()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_round_trip_and_oversized_ones_are_refused() {
let mut out = Vec::new();
write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap();
write_frame(&mut out, b"{}").unwrap();
assert_eq!(&out[..4], &23u32.to_le_bytes());
let mut r = &out[..];
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#);
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}");
assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away");
// A length over the limit is refused before anything is allocated.
let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes();
assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData);
// A frame cut short is an error, not a short message.
let mut cut = 10u32.to_le_bytes().to_vec();
cut.extend_from_slice(b"{}");
assert!(read_frame(&mut &cut[..]).is_err());
assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err());
}
}
+392
View File
@@ -0,0 +1,392 @@
//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in
//! this public repository; the rules that decide which login goes into which page live here too, so the
//! desktop app and anyone reviewing the extension apply the same ones.
//!
//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims).
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
//! (`paypa1.com`, `paypal.com.evil.net`) never match.
//! - [`fill_allowed`]: the same for a login field in a frame: the frame's origin, and the top page's too when
//! the frame is not the top page, so a login never goes into a site embedded by another one.
//! - [`caller`]: which extension started the native host (the browser's arguments), refused unless it is Custos's.
//! - [`framing`]: native messaging frames (a 4-byte little-endian length, then JSON), the same in every browser.
//!
//! ```
//! use custos_browser::{login_matches, Origin};
//! let page = Origin::parse("https://accounts.github.com/login?return=/")?;
//! assert!(login_matches("https://github.com", &page).is_some());
//! assert!(login_matches("https://github.com.evil.net", &page).is_none());
//! # Ok::<(), custos_browser::OriginError>(())
//! ```
pub mod caller;
pub mod framing;
use std::fmt;
/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origin {
pub scheme: Scheme,
pub host: String,
pub port: u16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scheme {
Https,
Http,
}
impl Scheme {
fn default_port(self) -> u16 {
match self {
Scheme::Https => 443,
Scheme::Http => 80,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum OriginError {
/// Not an `http(s)://host…` URL.
NotWeb,
/// A host that is empty, too long or has characters a host cannot have.
BadHost,
BadPort,
}
impl fmt::Display for OriginError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
OriginError::NotWeb => "not a web address",
OriginError::BadHost => "not a valid host",
OriginError::BadPort => "not a valid port",
})
}
}
impl std::error::Error for OriginError {}
/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com).
fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u16>), OriginError> {
let url = url.trim();
let (scheme, rest) = match url.split_once("://") {
Some((s, rest)) => match s.to_ascii_lowercase().as_str() {
"https" => (Scheme::Https, rest),
"http" => (Scheme::Http, rest),
_ => return Err(OriginError::NotWeb),
},
None => (default.ok_or(OriginError::NotWeb)?, url),
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
if authority.contains('@') {
return Err(OriginError::BadHost);
}
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?;
(format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':'))
} else {
match authority.rsplit_once(':') {
Some((h, p)) => (h.to_ascii_lowercase(), Some(p)),
None => (authority.to_ascii_lowercase(), None),
}
};
let host = host.trim_end_matches('.').to_string();
let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':');
if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") {
return Err(OriginError::BadHost);
}
let port = match port {
None | Some("") => None,
Some(p) if !p.bytes().all(|b| b.is_ascii_digit()) => return Err(OriginError::BadPort),
Some(p) => Some(
p.parse::<u16>()
.map_err(|_| OriginError::BadPort)
.and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?,
),
};
Ok((scheme, host, port))
}
impl Origin {
/// A page URL as the browser reports it (`sender.url`, the tab's URL).
pub fn parse(url: &str) -> Result<Origin, OriginError> {
let (scheme, host, port) = split(url, None)?;
Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host })
}
fn is_loopback(&self) -> bool {
self.host == "localhost"
|| self.host.ends_with(".localhost")
|| self.host == "127.0.0.1"
|| self.host == "[::1]"
}
fn is_ip(&self) -> bool {
self.host.starts_with('[')
|| self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
}
/// May a login be filled into this page at all? Only over https, or plain http on this machine.
pub fn fillable(&self) -> bool {
self.scheme == Scheme::Https || self.is_loopback()
}
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let scheme = match self.scheme {
Scheme::Https => "https",
Scheme::Http => "http",
};
if self.port == self.scheme.default_port() {
write!(f, "{scheme}://{}", self.host)
} else {
write!(f, "{scheme}://{}:{}", self.host, self.port)
}
}
}
/// How well a login's URL fits a page, best first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Match {
/// The page is on the login's host itself (`www.` counts as the host).
Exact,
/// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`).
Subdomain,
}
/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there.
///
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
/// an IP address matches only that exact host, and so does a login for a public suffix (`co.uk`, `github.io`,
/// Mozilla's Public Suffix List): its subdomains belong to different people.
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
if !page.fillable() {
return None;
}
let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?;
if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port {
return None;
}
let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string());
let (item, at) = (strip(&host), strip(&page.host));
if item == at {
return Some(Match::Exact);
}
if page.is_ip() || !item.contains('.') || item.starts_with('[') || psl::domain_str(&item).is_none() {
return None;
}
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
}
/// The best match among a login's URLs.
pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) -> Option<Match> {
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
}
/// May the login with `urls` be filled into a field of the frame at `frame`, on the tab whose top page is `top`?
///
/// The frame must match (it is where the password goes). A frame that is not the top page (another origin) must
/// match **and** the top page must match too: `evil.net` embedding `github.com/login` in an iframe gets nothing,
/// and neither does a `github.com` page that embeds an advertiser's frame. The answer is the frame's match.
pub fn fill_allowed<'a>(
urls: impl IntoIterator<Item = &'a str> + Clone,
frame: &Origin,
top: &Origin,
) -> Option<Match> {
let m = best_match(urls.clone(), frame)?;
if frame != top && best_match(urls, top).is_none() {
return None;
}
Some(m)
}
#[cfg(test)]
mod tests {
use super::*;
fn page(u: &str) -> Origin {
Origin::parse(u).unwrap()
}
#[test]
fn origins_parse_as_the_browser_reports_them() {
assert_eq!(
page("https://GitHub.com./login?x=1#y"),
Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 }
);
assert_eq!(page("http://localhost:5173/").port, 5173);
assert_eq!(page("https://[::1]:8443/").host, "[::1]");
assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz");
assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080");
for bad in [
"ftp://x.cz",
"file:///C:/a.html",
"chrome-extension://abc/",
"javascript:alert(1)",
"about:blank",
"https://",
"https://a..b.cz/",
"https://bank.cz:99999/",
"https://bank.cz:0/",
"https://bad host.cz/",
] {
assert!(Origin::parse(bad).is_err(), "{bad}");
}
// Userinfo is refused outright: it is how look-alike links hide their real host.
assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost));
}
#[test]
fn a_login_matches_its_host_and_its_subdomains_only() {
let gh = page("https://github.com/login");
assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact));
assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https");
assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact));
assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact));
assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain));
// A login for a subdomain does not go to its parent or its siblings.
assert_eq!(login_matches("https://gist.github.com", &gh), None);
assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None);
// Look-alikes never match.
for evil in [
"https://github.com.evil.net/",
"https://evilgithub.com/",
"https://github.co/",
"https://githuh.com/",
"https://xn--gthub-cta.com/",
] {
assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}");
}
}
#[test]
fn scheme_port_and_plain_http_are_strict() {
// Never over plain http on the internet, even for a login saved with http.
assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None);
// On this machine plain http is fine, with the port the login names.
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact));
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None);
assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None);
// An https login does not go to the http page of the same host, nor the other way round.
assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None);
assert_eq!(
login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")),
Some(Match::Exact)
);
assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None);
}
#[test]
fn bare_names_and_addresses_match_exactly_only() {
assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact));
assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None);
assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None);
assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact));
assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None);
assert_eq!(login_matches("", &page("https://bank.cz/")), None);
}
#[test]
fn the_best_of_several_urls_wins() {
let p = page("https://www.github.com/");
assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact));
assert_eq!(best_match(["https://gitlab.com"], &p), None);
assert_eq!(
best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")),
Some(Match::Subdomain)
);
}
/// Hostile pages, one trick each: none of them gets the `github.com` login.
#[test]
fn spoofed_addresses_never_get_a_login() {
let gh = "https://github.com";
// Look-alike hosts: punycode twins (Cyrillic and Greek letters), extra labels, hyphens, typos.
for evil in [
"https://xn--gthub-n4a.com/",
"https://xn--80ak6aa92e.com/",
"https://xn--github-xyz.com/",
"https://github.com.evil.net/",
"https://www.github.com.evil.net/",
"https://github.com-login.evil.net/",
"https://wwwgithub.com/",
"https://github.co.evil.net/",
"https://evil.net/github.com",
"https://evil.net/?next=https://github.com",
"https://evil.net/#@github.com",
] {
assert_eq!(login_matches(gh, &page(evil)), None, "{evil}");
}
// Addresses that hide their host: userinfo, encoded dots, backslashes, unicode, odd ports. Refused outright.
for bad in [
"https://github.com@evil.net/",
"https://github.com:443@evil.net/",
r"https://evil.net\@github.com/",
"https://github%2ecom/",
"https://github.com%2eevil.net/",
r"https://github.com\.evil.net/",
"https://g\u{0456}thub.com/",
"https://github.com:+443/",
"https://github.com:-1/",
"https://github.com: 443/",
] {
assert!(Origin::parse(bad).is_err(), "{bad}");
}
// A stored URL that hides its host never matches either.
assert_eq!(login_matches("https://evil.net@github.com", &page("https://github.com/")), None);
assert_eq!(
login_matches("https://bücher.de", &page("https://xn--bcher-kva.de/")),
None,
"only what the browser reports"
);
// Plain http, even of the right host, and https logins on http pages: never.
assert_eq!(login_matches(gh, &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("http://github.com/")), None);
assert_eq!(login_matches("http://github.com", &page("https://github.com/")), None);
// The case and a trailing dot are the same host; that is not a trick.
assert_eq!(login_matches(gh, &page("https://GITHUB.com./")), Some(Match::Exact));
}
#[test]
fn a_public_suffix_has_no_subdomains_to_fill() {
// Anyone can own a subdomain of these: a login saved for the suffix itself fits only the suffix.
for (login, other) in [
("https://github.io", "https://attacker.github.io/"),
("https://co.uk", "https://bank.co.uk/"),
("https://blogspot.com", "https://evil.blogspot.com/"),
("https://herokuapp.com", "https://evil.herokuapp.com/"),
] {
assert_eq!(login_matches(login, &page(other)), None, "{login} on {other}");
assert_eq!(login_matches(login, &page(&format!("{login}/"))), Some(Match::Exact), "{login}");
}
// A site on such a suffix keeps its own subdomains.
assert_eq!(
login_matches("https://mark.github.io", &page("https://docs.mark.github.io/")),
Some(Match::Subdomain)
);
assert_eq!(login_matches("https://mark.github.io", &page("https://eve.github.io/")), None);
assert_eq!(login_matches("https://bank.co.uk", &page("https://login.bank.co.uk/")), Some(Match::Subdomain));
}
#[test]
fn a_frame_gets_a_login_only_when_its_page_would_too() {
let gh = ["https://github.com"];
let (login, top_gh, evil) =
(page("https://github.com/login"), page("https://github.com/"), page("https://evil.net/"));
// The top page itself.
assert_eq!(fill_allowed(gh, &login, &login), Some(Match::Exact));
// A frame of the same site, on a page of the same site.
assert_eq!(fill_allowed(gh, &page("https://gist.github.com/"), &top_gh), Some(Match::Subdomain));
// github.com framed by evil.net: the frame's own origin matches, the page does not. Nothing.
assert_eq!(fill_allowed(gh, &login, &evil), None);
// An evil frame on github.com: its own origin does not match. Nothing.
assert_eq!(fill_allowed(gh, &evil, &top_gh), None);
// A plain-http top page around an https frame of the site: nothing either.
assert_eq!(fill_allowed(gh, &login, &page("http://github.com/")), None);
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-native"
description = "Custos's native messaging host: the browser extension's way to the desktop Custos"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-browser = { path = "../custos-browser" }
rand.workspace = true
serde_json.workspace = true
zeroize.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
+372
View File
@@ -0,0 +1,372 @@
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Firefox, Edge or Chrome
//! starts it when the extension connects, and talks to it over stdin/stdout in native messaging frames. It
//! forwards five requests to the desktop Custos over its Domi pipe and returns the answers:
//!
//! - `browser_status`: is Custos running, and this connection's match code;
//! - `browser_match { origin, top }`: the logins for a frame (title, username, has 2FA; never a password);
//! - `browser_fill { id, origin, top }`: one login's username, password and 2FA code, when it matches;
//! - `browser_totp { id, origin, top }`: only the 2FA code, for the popup;
//! - `browser_save { origin, top, username, password, title }`: offer a new login (or a changed password);
//! Custos shows a card and stores it only on *Save*.
//!
//! The host adds nothing and decides nothing: Custos checks the origins against the login and asks the user
//! once whether this host may use web logins. It forwards only those requests, rebuilt from their known fields,
//! so the extension cannot reach Custos's other Domi requests through it. It answers nothing to an extension
//! that is not Custos's (`custos_browser::caller`), and it refuses a pipe that is not served by custos.exe.
//!
//! Every request carries this connection's `session`: 32 random bytes made when the host starts. Custos shows
//! their match code on its card and in the audit; the extension shows the same code in its popup.
use std::io::{self, Write};
use custos_browser::caller::{Browser, caller};
use custos_browser::framing::{read_frame, write_frame};
use serde_json::{Value, json};
use zeroize::Zeroizing;
const PIPE: &str = r"\\.\pipe\custos-domi";
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill", "browser_totp", "browser_save"];
/// The connection: who started the host, and its session.
struct Conn {
browser: Browser,
session: String,
}
impl Conn {
fn new(browser: Browser) -> Conn {
use rand::Rng;
let mut raw = Zeroizing::new([0u8; 32]);
rand::rand_core::UnwrapErr(rand::rngs::SysRng).fill_bytes(raw.as_mut());
Conn { browser, session: raw.iter().map(|b| format!("{b:02x}")).collect() }
}
/// The browser's name as Custos shows it: Firefox is what the arguments say; for Chromium the extension
/// names it (Edge or Chrome), a label only.
fn browser_name(&self, hint: Option<&str>) -> &'static str {
match (self.browser, hint) {
(Browser::Firefox, _) => "firefox",
(Browser::Chromium, Some("edge")) => "edge",
(Browser::Chromium, Some("chrome")) => "chrome",
(Browser::Chromium, _) => "chromium",
}
}
}
/// A string field of at most `max` bytes, or `bad_request`.
fn field<'a>(v: &'a Value, name: &str, max: usize) -> Result<&'a str, &'static str> {
v.get(name).and_then(Value::as_str).filter(|s| s.len() <= max).ok_or("bad_request")
}
/// The request Custos gets: only known fields, of the right types.
fn rebuild(msg: &[u8], conn: &Conn) -> Result<Value, &'static str> {
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
let out = build(&v, conn);
// The parsed message can hold a password: wiped before it is dropped.
zeroize_json(v);
out
}
fn build(v: &Value, conn: &Conn) -> Result<Value, &'static str> {
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
let hint = v.get("browser").and_then(Value::as_str);
let mut out = json!({
"op": op,
"app": "Custos for your browser",
"browser": conn.browser_name(hint),
"session": conn.session,
});
if op != "browser_status" {
out["origin"] = field(v, "origin", 2048)?.into();
out["top"] = field(v, "top", 2048)?.into();
}
if matches!(op, "browser_fill" | "browser_totp") {
out["id"] = field(v, "id", 128)?.into();
}
if op == "browser_save" {
out["username"] = field(v, "username", 1024)?.into();
out["password"] =
field(v, "password", 4096).and_then(|p| if p.is_empty() { Err("bad_request") } else { Ok(p) })?.into();
if let Some(t) = v.get("title") {
out["title"] = t.as_str().filter(|t| t.len() <= 200).ok_or("bad_request")?.into();
}
}
// The extension's own request number comes back with the answer, so it can pair them.
if let Some(n) = v.get("seq").and_then(Value::as_u64) {
out["seq"] = n.into();
}
Ok(out)
}
fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
}
/// One answer. `conn` is `None` when the host was started by anything but the Custos extension: then every
/// request gets `not_allowed` and nothing reaches Custos.
fn answer(msg: &[u8], conn: Option<&Conn>, pipe: &str) -> Zeroizing<Vec<u8>> {
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
let Some(conn) = conn else {
return Zeroizing::new(error("not_allowed", seq));
};
let req = match rebuild(msg, conn) {
Ok(r) => r,
Err(code) => return Zeroizing::new(error(code, seq)),
};
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
zeroize_json(req);
match pipe::call(pipe, &bytes) {
Ok(resp) => {
// Custos does not know the extension's request number: put it back.
let Ok(mut v) = serde_json::from_slice::<Value>(&resp) else {
return Zeroizing::new(error("bad_answer", seq));
};
if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) {
obj.insert("seq".into(), n.into());
}
let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default());
zeroize_json(v);
out
}
Err(code) => Zeroizing::new(error(code, seq)),
}
}
/// Wipes the strings of a parsed message (it can hold a password) before dropping it.
fn zeroize_json(v: Value) {
use zeroize::Zeroize;
match v {
Value::String(mut s) => s.zeroize(),
Value::Array(a) => a.into_iter().for_each(zeroize_json),
Value::Object(o) => o.into_iter().for_each(|(mut k, v)| {
k.zeroize();
zeroize_json(v)
}),
_ => {}
}
}
fn main() {
// Tests point the host at another Custos.
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
let args: Vec<String> = std::env::args().skip(1).collect();
let conn = caller(&args).map(Conn::new);
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
loop {
let msg = match read_frame(&mut stdin) {
Ok(Some(m)) => m,
// The extension disconnected, or sent something that is not a frame: done.
Ok(None) | Err(_) => return,
};
let out = answer(&msg, conn.as_ref(), &pipe);
let mut w = stdout.lock();
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
return;
}
}
}
#[cfg(windows)]
mod pipe {
use std::time::Duration;
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile};
use windows_sys::Win32::System::Pipes::{
GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW,
};
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
};
use zeroize::Zeroizing;
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn server_exe(h: HANDLE) -> Option<String> {
unsafe {
let mut pid = 0u32;
if GetNamedPipeServerProcessId(h, &mut pid) == 0 {
return None;
}
let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if p.is_null() {
return None;
}
let p = Handle(p);
let mut buf = vec![0u16; 1024];
let mut len = buf.len() as u32;
let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len);
(ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
}
}
/// One request, one answer. The error is a code the extension shows as a sentence.
pub fn call(name: &str, request: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
let w = wide(name);
unsafe {
let mut h = INVALID_HANDLE_VALUE;
// Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running.
for _ in 0..50 {
h = CreateFileW(
w.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
0,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
);
if h != INVALID_HANDLE_VALUE {
break;
}
match GetLastError() {
ERROR_PIPE_BUSY => {
WaitNamedPipeW(w.as_ptr(), 200);
}
ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)),
_ => break,
}
}
if h == INVALID_HANDLE_VALUE {
return Err("not_running");
}
let h = Handle(h);
// Anything else serving this pipe could collect passwords: only custos.exe gets the request.
if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") {
return Err("not_custos");
}
let mode = PIPE_READMODE_MESSAGE;
SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null());
let mut n = 0u32;
if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
return Err("not_running");
}
let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]);
if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
return Err("no_answer");
}
buf.truncate(n as usize);
Ok(buf)
}
}
}
#[cfg(not(windows))]
mod pipe {
pub fn call(_: &str, _: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, &'static str> {
Err("not_running")
}
}
#[cfg(test)]
mod tests {
use super::*;
fn conn(b: Browser) -> Conn {
Conn::new(b)
}
#[test]
fn only_the_browser_requests_pass_rebuilt_from_known_fields() {
let c = conn(Browser::Chromium);
let fill = rebuild(
br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","top":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca","browser":"edge","session":"mine"}"#,
&c,
)
.unwrap();
assert_eq!(
fill,
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "top": "https://github.com", "seq": 7,
"app": "Custos for your browser", "browser": "edge", "session": c.session })
);
assert_eq!(c.session.len(), 64, "the host's own session, never the extension's");
assert_ne!(c.session, conn(Browser::Chromium).session, "a new one for every connection");
assert_eq!(rebuild(br#"{"op":"browser_status"}"#, &c).unwrap()["op"], "browser_status");
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz","top":"https://a.cz"}"#, &c).is_ok());
let totp =
rebuild(br#"{"op":"browser_totp","id":"x","origin":"https://a.cz","top":"https://a.cz"}"#, &c).unwrap();
assert_eq!(totp["id"], "x");
let save = rebuild(
br#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"mark","password":"pw","title":"A","extra":1}"#,
&c,
)
.unwrap();
assert_eq!(
(save["username"].as_str(), save["password"].as_str(), save["title"].as_str()),
(Some("mark"), Some("pw"), Some("A"))
);
assert!(save.get("extra").is_none());
// The browser's name: Firefox from the arguments, whatever the extension says; Chromium names itself.
let f = conn(Browser::Firefox);
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"chrome"}"#, &f).unwrap()["browser"], "firefox");
assert_eq!(rebuild(br#"{"op":"browser_status","browser":"lynx"}"#, &c).unwrap()["browser"], "chromium");
// Custos's other Domi requests never pass through the browser's host.
for other in [
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
r#"{"op":"list","namespace":"arca"}"#,
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
r#"{"op":"subkey"}"#,
r#"{"op":"sign"}"#,
r#"{"op":"browser_anything","origin":"https://a.cz","top":"https://a.cz"}"#,
] {
assert_eq!(rebuild(other.as_bytes(), &c), Err("bad_request"), "{other}");
}
// Missing or wrong fields, or too long.
for bad in [
r#"{"op":"browser_fill","origin":"https://a.cz","top":"https://a.cz"}"#,
r#"{"op":"browser_fill","id":"x","origin":"https://a.cz"}"#,
r#"{"op":"browser_match","origin":5,"top":"https://a.cz"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m"}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":""}"#,
r#"{"op":"browser_save","origin":"https://a.cz","top":"https://a.cz","username":"m","password":"p","title":7}"#,
"not json",
] {
assert!(rebuild(bad.as_bytes(), &c).is_err(), "{bad}");
}
let long = format!(
r#"{{"op":"browser_fill","id":"{}","origin":"https://a.cz","top":"https://a.cz"}}"#,
"x".repeat(129)
);
assert!(rebuild(long.as_bytes(), &c).is_err());
}
#[test]
fn an_extension_that_is_not_custos_gets_nothing() {
// Started by another extension (or by hand): `not_allowed` for every request, and the pipe is never
// opened (this pipe does not exist; reaching for it would answer `not_running`).
let args = ["chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/"];
let conn = caller(&args).map(Conn::new);
assert!(conn.is_none());
for msg in [
&br#"{"op":"browser_status","seq":1}"#[..],
br#"{"op":"browser_match","origin":"https://github.com","top":"https://github.com","seq":2}"#,
br#"{"op":"browser_fill","id":"x","origin":"https://github.com","top":"https://github.com","seq":3}"#,
] {
let v: Value =
serde_json::from_slice(&answer(msg, conn.as_ref(), r"\\.\pipe\custos-test-nobody-here")).unwrap();
assert_eq!(v["error"], "not_allowed");
}
}
#[test]
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
let c = conn(Browser::Firefox);
let out = answer(br#"{"op":"browser_status","seq":3}"#, Some(&c), r"\\.\pipe\custos-test-nobody-here");
let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, Some(&c), PIPE)).unwrap();
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
}
}
+2
View File
@@ -22,6 +22,8 @@ x509-cert = { version = "0.2.5", features = ["builder"] }
# rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`).
rand_core = "0.6"
rand.workspace = true
# cosign container image signatures (core 0.18.0): ECDSA P-256 with SHA-256, RFC 6979 nonces.
p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] }
[dev-dependencies]
minisign-verify = "0.3"
+112
View File
@@ -0,0 +1,112 @@
//! Tauri's updater envelope and cosign container image signatures (core 0.18.0, docs/TEAM.md, "Signature
//! envelopes").
use std::fmt;
use data_encoding::BASE64;
use zeroize::Zeroizing;
use crate::{Error, OsRng06};
// ---- Tauri's updater ----
/// The content of Tauri's `<file>.sig`: the base64 of the whole minisign signature file. Tauri's `pubkey` is,
/// likewise, the base64 of `minisign.pub`.
pub fn tauri_updater(minisig: &str) -> String {
BASE64.encode(minisig.as_bytes())
}
/// The minisign text inside a Tauri `.sig`, or `None` when it is not base64 of UTF-8.
pub fn tauri_updater_open(sig: &str) -> Option<String> {
String::from_utf8(BASE64.decode(sig.trim().as_bytes()).ok()?).ok()
}
// ---- cosign ----
/// An ECDSA P-256 secret scalar. Wiped on drop; never printed.
pub struct P256Secret(Zeroizing<[u8; 32]>);
impl P256Secret {
/// Refuses bytes that are not a valid scalar (zero, or not below the group order).
pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, Error> {
let bytes = Zeroizing::new(bytes);
p256::ecdsa::SigningKey::from_bytes(&(*bytes).into()).map_err(|_| Error::BadKey)?;
Ok(P256Secret(bytes))
}
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
fn key(&self) -> Result<p256::ecdsa::SigningKey, Error> {
p256::ecdsa::SigningKey::from_bytes(&(*self.0).into()).map_err(|_| Error::BadKey)
}
/// The public key as `cosign.pub` holds it: a PEM `PUBLIC KEY` (SubjectPublicKeyInfo).
pub fn public_pem(&self) -> Result<String, Error> {
use p256::pkcs8::EncodePublicKey;
self.key()?.verifying_key().to_public_key_pem(p256::pkcs8::LineEnding::LF).map_err(|_| Error::BadKey)
}
}
impl fmt::Debug for P256Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// A new random P-256 key, from the OS CSPRNG.
pub fn new_p256() -> P256Secret {
let key = p256::ecdsa::SigningKey::random(&mut OsRng06);
let mut bytes = Zeroizing::new([0u8; 32]);
bytes.copy_from_slice(&key.to_bytes());
P256Secret(bytes)
}
/// An image reference as cosign's payload names it: the repository, without a tag or digest, 1–255 of
/// `[a-z0-9._/:-]`, starting and ending with a letter or digit, no `//`.
pub fn image_ok(image: &str) -> Result<(), Error> {
let b = image.as_bytes();
if !(1..=255).contains(&b.len()) {
return Err(Error::Image("not 1 to 255 characters"));
}
if !b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._/:-".contains(c)) {
return Err(Error::Image("only a-z 0-9 . _ / : - (a repository, without @digest)"));
}
if !b[0].is_ascii_alphanumeric() || !b[b.len() - 1].is_ascii_alphanumeric() || image.contains("//") {
return Err(Error::Image("not a repository name"));
}
Ok(())
}
/// cosign's simple-signing payload for `image` at the manifest whose SHA-256 is `digest`, exactly as docs/TEAM.md
/// writes it: these keys in this order, no spaces, `"optional":null`.
pub fn cosign_payload(image: &str, digest: &[u8]) -> Result<String, Error> {
let digest: &[u8; 32] = digest.try_into().map_err(|_| Error::DigestLength(32))?;
image_ok(image)?;
let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
Ok(format!(
"{{\"critical\":{{\"identity\":{{\"docker-reference\":\"{image}\"}},\"image\":{{\"docker-manifest-digest\":\"sha256:{hex}\"}},\"type\":\"cosign container image signature\"}},\"optional\":null}}"
))
}
/// The ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload`, as `cosign sign` makes it and `cosign verify
/// --key` and `openssl dgst -sha256 -verify` check it. Nonces are RFC 6979's.
pub fn cosign(secret: &P256Secret, payload: &str) -> Result<Vec<u8>, Error> {
use p256::ecdsa::signature::Signer;
let sig: p256::ecdsa::Signature = secret.key()?.sign(payload.as_bytes());
Ok(sig.to_der().as_bytes().to_vec())
}
/// Checks a cosign signature (DER, as [`cosign`] makes it) over `payload` with a `cosign.pub` PEM.
pub fn cosign_verify(public_pem: &str, payload: &[u8], der: &[u8]) -> bool {
use p256::ecdsa::signature::Verifier;
use p256::pkcs8::DecodePublicKey;
let Ok(key) = p256::ecdsa::VerifyingKey::from_public_key_pem(public_pem) else {
return false;
};
let Ok(sig) = p256::ecdsa::Signature::from_der(der) else {
return false;
};
key.verify(payload, &sig).is_ok()
}
+86 -11
View File
@@ -4,7 +4,12 @@
//! - minisign (prehashed `ED`, what minisign and Tauri's updater verify) over a BLAKE2b-512 digest;
//! - a canonical `SHA256SUMS` manifest, checked here and signed as minisign;
//! - Authenticode: RSA PKCS#1 v1.5 over the 32-byte digest `signtool sign /dg` writes;
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3).
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3);
//! - Android APKs: an RSA-4096 key with a self-signed certificate, signing the SHA-512 digests of the APK
//! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side);
//! - Tauri's updater: the base64 of a minisign signature file (core 0.18.0);
//! - cosign container image signatures (core 0.18.0): ECDSA P-256 over cosign's simple-signing payload, written
//! here from the image and its manifest digest, never taken from the request.
//!
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
@@ -21,7 +26,7 @@ use rsa::RsaPrivateKey;
use rsa::pkcs1v15;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
use rsa::signature::hazmat::PrehashSigner;
use sha2_010::Sha256;
use sha2_010::{Sha256, Sha512};
use x509_cert::Certificate;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::der::{Decode, Encode};
@@ -32,10 +37,21 @@ use x509_cert::spki::SubjectPublicKeyInfoOwned;
use x509_cert::time::Validity;
use zeroize::Zeroizing;
mod cosign;
pub use cosign::{
P256Secret, cosign, cosign_payload, cosign_verify, image_ok, new_p256, tauri_updater, tauri_updater_open,
};
/// Authenticode's code-signing purpose (RFC 5280 id-kp-codeSigning).
const CODE_SIGNING: x509_cert::der::oid::ObjectIdentifier =
x509_cert::der::oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3");
const RSA_BITS: usize = 3072;
/// An Android app's signing key: RSA-4096. apksig signs with SHA512withRSA for any RSA key over 3072 bits.
pub const ANDROID_RSA_BITS: usize = 4096;
/// An Android app's certificate is valid this long: the key can never change for the app's whole life.
pub const ANDROID_YEARS: u64 = 100;
/// One `apk` request carries 1 to this many SHA-512 digests (v2 and v3 are two).
pub const MAX_APK_DIGESTS: usize = 4;
const DAY: u64 = 24 * 60 * 60;
/// The largest manifest Custos signs (docs/SIGNING.md).
pub const MAX_MANIFEST: usize = 32 * 1024;
@@ -54,6 +70,10 @@ pub enum Error {
Certificate,
#[error("the approval cannot be signed: {0}")]
Approval(&'static str),
#[error("an APK request is 1 to 4 SHA-512 digests of 64 bytes each")]
ApkDigests,
#[error("the image reference is not usable: {0}")]
Image(&'static str),
}
/// An Ed25519 seed. Wiped on drop; never printed.
@@ -290,8 +310,8 @@ pub struct NewCert {
pub cert_der: Vec<u8>,
}
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng06, RSA_BITS).map_err(|_| Error::BadKey)?;
fn new_rsa(bits: usize) -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng06, bits).map_err(|_| Error::BadKey)?;
let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec();
Ok((key, RsaSecret(Zeroizing::new(der))))
}
@@ -318,7 +338,7 @@ fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
/// A self-signed root CA, valid for `years` years from now.
pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
let (key, secret) = new_rsa()?;
let (key, secret) = new_rsa(RSA_BITS)?;
let spki = spki(&key)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
@@ -331,7 +351,7 @@ pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
/// A code-signing leaf issued by `issuer`, valid for `years` years from now.
pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &[u8]) -> Result<NewCert, Error> {
let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?;
let (key, secret) = new_rsa()?;
let (key, secret) = new_rsa(RSA_BITS)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(issuer.key()?);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
let profile = Profile::Leaf {
@@ -346,6 +366,59 @@ pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
// ---- Android APKs ----
/// One attribute value of an Android certificate's subject: 1 to 64 bytes, no characters RFC 4514 would have to
/// escape, no control characters, no space at either end.
fn subject_part(s: &str) -> Result<&str, Error> {
let bad = s.is_empty()
|| s.len() > 64
|| s.trim() != s
|| s.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#'])
|| s.chars().any(char::is_control);
if bad { Err(Error::Certificate) } else { Ok(s) }
}
/// A new Android app signing key: RSA-4096 and a self-signed X.509 v3 certificate `CN=<cn>, O=<o>, C=<c>` valid
/// [`ANDROID_YEARS`] years from now, an end-entity certificate (not a CA, key usage digitalSignature +
/// nonRepudiation, no extended key usage). `c` is a two-letter country code. Slow: one RSA-4096 key.
pub fn new_android(cn: &str, o: &str, c: &str) -> Result<NewCert, Error> {
let (cn, o) = (subject_part(cn)?, subject_part(o)?);
if c.len() != 2 || !c.bytes().all(|b| b.is_ascii_uppercase()) {
return Err(Error::Certificate);
}
// RFC 4514 order: the string names the most specific part first, the certificate encodes C, O, CN.
let subject = Name::from_str(&format!("CN={cn},O={o},C={c}")).map_err(|_| Error::Certificate)?;
let (key, secret) = new_rsa(ANDROID_RSA_BITS)?;
let spki = spki(&key)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
let validity =
Validity::from_now(Duration::from_secs(ANDROID_YEARS * 365 * DAY)).map_err(|_| Error::Certificate)?;
// A leaf issued by itself: self-signed, but without the CA extensions of a root.
let profile =
Profile::Leaf { issuer: subject.clone(), enable_key_agreement: false, enable_key_encipherment: false };
let builder = CertificateBuilder::new(profile, serial()?, validity, subject, spki, &signer)
.map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
/// RSA PKCS#1 v1.5 with the SHA-512 DigestInfo over each 64-byte digest in `digests` (1 to [`MAX_APK_DIGESTS`],
/// concatenated): the signatures, concatenated in the same order, for APK Signature Scheme v2 and v3
/// (`RSA_PKCS1_V1_5_WITH_SHA512`, what apksig picks for an RSA key over 3072 bits).
pub fn apk(secret: &RsaSecret, digests: &[u8]) -> Result<Vec<u8>, Error> {
if digests.is_empty() || digests.len() % 64 != 0 || digests.len() > 64 * MAX_APK_DIGESTS {
return Err(Error::ApkDigests);
}
let key = pkcs1v15::SigningKey::<Sha512>::new(secret.key()?);
let mut out = Vec::new();
for digest in digests.chunks(64) {
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
out.extend_from_slice(&Box::<[u8]>::from(sig));
}
Ok(out)
}
/// A certificate as PEM, for tools that want text.
pub fn cert_pem(der: &[u8]) -> String {
let b64 = BASE64.encode(der);
@@ -367,8 +440,9 @@ pub fn sha256_hex(bytes: &[u8]) -> String {
/// The largest approval text Custos reads (docs/SIGNING.md).
pub const MAX_APPROVAL: usize = 8 * 1024;
/// An approval expires at most this many seconds after it is checked.
pub const APPROVAL_MAX_AHEAD: u64 = 3600;
/// An approval expires at most this many seconds after it is checked: 25 hours (a release's approval lives a day,
/// and its card may wait for Mark that long; an hour before core 0.17.1).
pub const APPROVAL_MAX_AHEAD: u64 = 25 * 3600;
/// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
@@ -457,15 +531,16 @@ fn unprintable(c: char) -> bool {
}
/// Checks that `text` is a deploy approval in canonical form that has not expired at `now_secs` and expires at most
/// an hour later (docs/SIGNING.md). It is parsed, written again in canonical form and compared byte for byte, so
/// any other spelling of the same values (key order, spaces, escapes, a trailing newline) is refused.
/// 25 hours later ([`APPROVAL_MAX_AHEAD`], docs/SIGNING.md). It is parsed, written again in canonical form and
/// compared byte for byte, so any other spelling of the same values (key order, spaces, escapes, a trailing newline)
/// is refused.
pub fn approval_check(text: &str, now_secs: u64) -> Result<Approval, Error> {
let a = approval_parse(text)?;
if a.expires <= now_secs {
return Err(Error::Approval("it has expired"));
}
if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) {
return Err(Error::Approval("it expires more than an hour from now"));
return Err(Error::Approval("it expires more than 25 hours from now"));
}
Ok(a)
}
+6 -2
View File
@@ -142,11 +142,15 @@ fn targets_have_limits() {
}
#[test]
fn the_expiry_is_after_now_and_within_an_hour() {
fn the_expiry_is_after_now_and_within_25_hours() {
let at = |exp: u64| with(&format!("\"expires\":{}", NOW + 600), &format!("\"expires\":{exp}"));
assert!(approval_check(&at(NOW + 1), NOW).is_ok());
assert!(approval_check(&at(NOW + 3600), NOW).is_ok());
for exp in [NOW, NOW - 1, 0, NOW + 3601, u64::MAX] {
// A release's approval lives a day, and its card may wait for Mark that long (core 0.17.1).
assert_eq!(APPROVAL_MAX_AHEAD, 25 * 3600);
assert!(approval_check(&at(NOW + 24 * 3600), NOW).is_ok());
assert!(approval_check(&at(NOW + 25 * 3600), NOW).is_ok());
for exp in [NOW, NOW - 1, 0, NOW + 25 * 3600 + 1, u64::MAX] {
let e = refused(&at(exp), NOW);
assert!(e.contains("expire"), "{exp}: {e}");
}
+91
View File
@@ -0,0 +1,91 @@
//! cosign and the Tauri updater envelope (docs/TEAM.md, "Signature envelopes"; core 0.18.0).
use custos_sign::*;
#[test]
fn the_cosign_payload_is_written_exactly_as_the_doc_says() {
let p = cosign_payload("gitea.example/team/arca", &[0xab; 32]).unwrap();
assert_eq!(
p,
"{\"critical\":{\"identity\":{\"docker-reference\":\"gitea.example/team/arca\"},\"image\":{\"docker-manifest-digest\":\"sha256:abababababababababababababababababababababababababababababababab\"},\"type\":\"cosign container image signature\"},\"optional\":null}"
);
let v: serde_json::Value = serde_json::from_str(&p).unwrap();
assert_eq!(v["critical"]["type"], "cosign container image signature");
assert!(v["optional"].is_null());
}
#[test]
fn image_references_are_checked() {
for bad in ["", "Arca", "a b", "x@sha256:00", "/a", "a/", "a//b", "a\"b", "a\nb"] {
assert!(cosign_payload(bad, &[0; 32]).is_err(), "{bad:?}");
}
for good in ["arca", "registry.example:5000/team/app", "ghcr.io/mnovak/custos-share"] {
assert!(cosign_payload(good, &[0; 32]).is_ok(), "{good}");
}
assert_eq!(cosign_payload("arca", &[0; 31]), Err(Error::DigestLength(32)));
}
#[test]
fn a_cosign_signature_verifies_and_only_over_its_payload() {
let key = new_p256();
let pem = key.public_pem().unwrap();
assert!(pem.starts_with("-----BEGIN PUBLIC KEY-----\n"));
let payload = cosign_payload("arca", &[7; 32]).unwrap();
let sig = cosign(&key, &payload).unwrap();
assert!(cosign_verify(&pem, payload.as_bytes(), &sig));
// RFC 6979: the same key and payload give the same signature.
assert_eq!(sig, cosign(&key, &payload).unwrap());
let other = cosign_payload("arca", &[8; 32]).unwrap();
assert!(!cosign_verify(&pem, other.as_bytes(), &sig));
assert!(!cosign_verify(&new_p256().public_pem().unwrap(), payload.as_bytes(), &sig));
let again = P256Secret::from_bytes(*key.expose()).unwrap();
assert_eq!(again.public_pem().unwrap(), pem);
assert_eq!(format!("{key:?}"), "[redacted]");
assert!(P256Secret::from_bytes([0; 32]).is_err());
assert!(P256Secret::from_bytes([0xff; 32]).is_err());
}
/// The cosign signature against openssl, a standard tool (`openssl dgst -sha256 -verify`, what a cosign
/// signature is underneath). Skipped with a note when openssl is not on PATH.
#[test]
fn openssl_verifies_a_cosign_signature() {
if std::process::Command::new("openssl").arg("version").output().is_err() {
eprintln!("openssl not found: skipped");
return;
}
let dir = std::env::temp_dir().join(format!("custos-cosign-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let key = new_p256();
let payload = cosign_payload("registry.example/team/arca", &[3; 32]).unwrap();
let sig = cosign(&key, &payload).unwrap();
std::fs::write(dir.join("cosign.pub"), key.public_pem().unwrap()).unwrap();
std::fs::write(dir.join("payload.json"), &payload).unwrap();
std::fs::write(dir.join("other.json"), payload.replace("arca", "arcb")).unwrap();
std::fs::write(dir.join("sig.der"), &sig).unwrap();
let verify = |file: &str| {
std::process::Command::new("openssl")
.args(["dgst", "-sha256", "-verify", "cosign.pub", "-signature", "sig.der", file])
.current_dir(&dir)
.output()
.unwrap()
};
let ok = verify("payload.json");
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stdout));
assert!(String::from_utf8_lossy(&ok.stdout).contains("Verified OK"));
assert!(!verify("other.json").status.success());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_tauri_envelope_is_base64_of_the_minisign_file_and_tauris_verifier_reads_it() {
let k = new_ed25519();
let file = b"Arca_0.7.0_x64-setup.exe contents";
let minisig = minisign(&k.secret, &k.key_id, &blake2b512(file), "Arca_0.7.0_x64-setup.exe", 1_794_000_000).unwrap();
let sig = tauri_updater(&minisig);
let pubkey = tauri_updater(&minisign_public(&k.public, &k.key_id));
// What tauri-plugin-updater does: base64-decode both, then minisign-verify.
let pk = minisign_verify::PublicKey::decode(&tauri_updater_open(&pubkey).unwrap()).unwrap();
let s = minisign_verify::Signature::decode(&tauri_updater_open(&sig).unwrap()).unwrap();
pk.verify(file, &s, true).unwrap();
assert!(pk.verify(b"another file", &s, true).is_err());
assert_eq!(tauri_updater_open("not base64!"), None);
}
+2
View File
@@ -4,3 +4,5 @@ Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign not
`payload.bin.minisig`: `minisign -S -m payload.bin -t "timestamp:1700000000<TAB>file:payload.bin<TAB>hashed"`.
- `rsa3072.pk8.der`: `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072`, then `openssl pkcs8 -topk8 -nocrypt`;
`digest.openssl.sig`: `openssl pkeyutl -sign -in digest.bin -pkeyopt digest:sha256` (PKCS#1 v1.5).
- `digest512.bin` (64 random bytes) and `digest512.openssl.sig`: `openssl pkeyutl -sign -inkey rsa3072.pk8.der -keyform DER
-in digest512.bin -pkeyopt digest:sha512` (PKCS#1 v1.5 with the SHA-512 DigestInfo: the `apk` kind).
Binary file not shown.
Binary file not shown.
+76 -1
View File
@@ -1,6 +1,7 @@
//! Mandatory test 1 (docs/SIGNING.md): known answers for every signature kind, from tools that are not this crate.
//! The fixtures are throwaway test keys: `minisign.key` was made by minisign 0.12 (`-G -W`, unencrypted) and
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der` and `digest.openssl.sig` by `openssl pkeyutl`.
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der`, `digest.openssl.sig` and `digest512.openssl.sig` by
//! `openssl pkeyutl`.
//! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode.
use std::fs;
@@ -108,6 +109,80 @@ fn authenticode_signature_equals_openssls() {
assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32));
}
#[test]
fn apk_signatures_equal_openssls_sha512_pkcs1() {
// The PKCS#1 v1.5 SHA-512 DigestInfo does not depend on the key size: the 3072-bit fixture checks it.
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
let digest = fixture("digest512.bin");
let expected = fixture("digest512.openssl.sig");
assert_eq!(apk(&key, &digest).unwrap(), expected);
// Two digests (v2 and v3): two signatures, in order.
let mut two = digest.clone();
two.extend(custos_sign::sha256_hex(&digest).as_bytes()); // any other 64 bytes
let both = apk(&key, &two).unwrap();
assert_eq!(both.len(), 2 * 384);
assert_eq!(&both[..384], expected.as_slice());
assert_eq!(both[384..].to_vec(), apk(&key, &two[64..]).unwrap());
for bad in [0usize, 32, 63, 65, 64 * 5] {
assert_eq!(apk(&key, &vec![1u8; bad]).unwrap_err(), Error::ApkDigests, "{bad}");
}
}
#[test]
fn an_android_key_is_rsa_4096_with_a_self_signed_end_entity_certificate_for_100_years() {
use rsa::RsaPublicKey;
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::Verifier;
use rsa::signature::hazmat::PrehashVerifier;
use rsa::traits::PublicKeyParts;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage, KeyUsage};
let made = new_android("Postea", "Marek Novak", "CZ").unwrap();
let c = Certificate::from_der(&made.cert_der).unwrap();
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject, "self-signed");
let v = &c.tbs_certificate.validity;
let days = (v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / 86_400;
assert_eq!(days, 100 * 365);
let (_, bc) = c.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(!bc.ca, "not a CA");
assert!(c.tbs_certificate.get::<KeyUsage>().unwrap().is_some());
assert!(c.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().is_none(), "no extended key usage");
let spki = c.tbs_certificate.subject_public_key_info.to_der().unwrap();
assert_eq!(RsaPublicKey::from_public_key_der(&spki).unwrap().n().bits(), 4096);
// Signed by its own key, and that key makes the APK signatures.
let sha256 = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(&spki).unwrap();
sha256
.verify(&c.tbs_certificate.to_der().unwrap(), &Signature::try_from(c.signature.raw_bytes()).unwrap())
.unwrap();
let digests = [3u8; 128];
let sigs = apk(&made.secret, &digests).unwrap();
assert_eq!(sigs.len(), 2 * 512);
let sha512 = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
for (d, s) in digests.chunks(64).zip(sigs.chunks(512)) {
sha512.verify_prehash(d, &Signature::try_from(s).unwrap()).unwrap();
}
// An Android key is not an Authenticode key, but the function cannot tell: the vault keeps them apart.
assert_eq!(format!("{:?}", made.secret), "[redacted]");
for (cn, o, c) in [
("", "O", "CZ"),
("A,B", "O", "CZ"),
(" Postea", "O", "CZ"),
("Postea", "O=x", "CZ"),
("Postea", "O", "cz"),
("Postea", "O", "CZE"),
(
"Postea", "O
", "CZ",
),
] {
assert!(matches!(new_android(cn, o, c), Err(Error::Certificate)), "{cn:?} {o:?} {c:?}");
}
}
#[test]
fn digests_and_file_names_are_checked() {
let (secret, key_id) = minisign_key();
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "custos-team"
description = "Custos Domi: team vaults' pure parts (member keys, policy evaluation, the canonical sign.request, approval statements, policy proofs)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-seal = { path = "../custos-seal" }
custos-sign = { path = "../custos-sign" }
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
sha2.workspace = true
hmac.workspace = true
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
zeroize.workspace = true
thiserror.workspace = true
rand.workspace = true
[dev-dependencies]
minisign-verify = "0.3"
+54
View File
@@ -0,0 +1,54 @@
//! The canonical JSON every signed text here uses (as deploy approvals, SIGNING.md): fixed key order, no spaces,
//! `"` and `\` escaped and nothing else, no newline. Callers only write strings that passed [`text_ok`].
/// Appends `s` as a JSON string with minimal escaping.
pub fn string(out: &mut String, s: &str) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c => out.push(c),
}
}
out.push('"');
}
/// Appends `["a","b"]`.
pub fn strings(out: &mut String, list: &[String]) {
out.push('[');
for (i, s) in list.iter().enumerate() {
if i > 0 {
out.push(',');
}
string(out, s);
}
out.push(']');
}
/// Characters a shown text may not hold: control characters, and the invisible ones that change how a line looks
/// on a card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
pub fn unprintable(c: char) -> bool {
c.is_control()
|| matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}')
|| matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}')
}
/// 1..=`max` characters, none of them [`unprintable`].
pub fn text_ok(s: &str, max: usize) -> bool {
(1..=max).contains(&s.chars().count()) && !s.chars().any(unprintable)
}
/// `min..=max` bytes, every one ASCII alphanumeric or in `extra`.
pub fn ascii_ok(s: &str, min: usize, max: usize, extra: &[u8]) -> bool {
(min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || extra.contains(&c))
}
/// An environment name: `[a-z][a-z0-9-]{0,31}`.
pub fn env_ok(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 32
&& b[0].is_ascii_lowercase()
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
}
+34
View File
@@ -0,0 +1,34 @@
//! The one interface an external signer is reached through (docs/TEAM.md, Authenticode). A hardware token or a
//! cloud signing service holds the private key; Custos approves, then hands the adapter the digest and the
//! credential that lets it ask. Adapters are the app's (I/O); this crate only names the shape.
use std::fmt;
/// The credential an adapter uses, borrowed from the team vault for one call. Prints `[redacted]` for `secret`.
pub struct SignerCredential<'a> {
pub id: &'a str,
pub name: &'a str,
/// Which adapter: `command` in this phase.
pub adapter: &'a str,
pub endpoint: &'a str,
pub account: &'a str,
pub secret: &'a str,
}
impl fmt::Debug for SignerCredential<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SignerCredential")
.field("id", &self.id)
.field("adapter", &self.adapter)
.field("endpoint", &self.endpoint)
.field("secret", &"[redacted]")
.finish_non_exhaustive()
}
}
/// Signs a 32-byte SHA-256 digest (signtool's `.dig`) with a key Custos never holds: returns the raw signature
/// (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo, as `signtool sign /di` wants it). An error names what failed,
/// never the credential.
pub trait ExternalSigner {
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String>;
}
+100
View File
@@ -0,0 +1,100 @@
//! Custos Domi · teams (docs/TEAM.md, core 0.18.0): the pure parts of team vaults and team signing.
//!
//! - [`member`]: a person's member key (X25519 to receive the team key, Ed25519 to sign approvals), the member id,
//! the join code, and sealing the team key to a member;
//! - [`policy`]: one rule per environment, its canonical text, and [`policy::evaluate`];
//! - [`request`]: the canonical `sign.request` and `target.request`, their hash and match code;
//! - [`statement`]: a member's signed approval of one request;
//! - [`proof`]: the team identity's policy proof, and checking it;
//! - [`reply`]: what goes back to Fabrica, sealed; [`target`]: a released target credential;
//! - [`external`]: the interface an external signer (a hardware token, a cloud signing service) is reached through.
//!
//! No I/O, no clock: every check takes `now` from the caller. Secrets print as `[redacted]`.
pub mod canon;
pub mod external;
pub mod member;
pub mod policy;
pub mod proof;
pub mod reply;
pub mod request;
pub mod statement;
pub mod target;
pub use member::{MemberKey, MemberPublic, TeamIdentity};
pub use policy::{EnvRule, Evaluation, KeyRole, Policy, RosterMember, Verdict, evaluate};
pub use proof::{Proof, Verified, verify_proof};
pub use request::{Format, SignRequest, TargetRequest};
pub use statement::Statement;
/// How far ahead a request may expire: 25 hours, as deploy approvals (SIGNING.md).
pub const MAX_AHEAD_SECS: u64 = 25 * 3600;
/// How long a signed request's hash is remembered against replay: longer than any request lives.
pub const SEEN_SECS: u64 = 48 * 3600;
/// The most members a team has (member slots in one file).
pub const MAX_MEMBERS: usize = 32;
/// Why something is refused. None of them carries a key, a credential or a signature.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TeamError {
#[error("not in canonical form: {0}")]
NotCanonical(&'static str),
#[error("{0}")]
Invalid(&'static str),
#[error("the request has expired")]
Expired,
#[error("the match code is not this request's: someone else's request may be waiting, refuse it")]
WrongMatch,
#[error("this request was already answered: a replay is refused")]
Replayed,
#[error("the request is for another team")]
WrongTeam,
#[error("not a member of this team")]
NotAMember,
#[error("a signature does not verify")]
BadSignature,
#[error("the policy has no rule for this environment")]
UnknownEnv,
#[error("the policy cannot be met: {0}")]
Unsatisfiable(&'static str),
#[error("the policy needs {0} more approval(s)")]
NeedMore(u8),
#[error("this member may not approve this request: {0}")]
NotEligible(&'static str),
#[error("the key cannot be read")]
BadKey,
}
pub(crate) fn hex(b: &[u8]) -> String {
data_encoding::HEXLOWER.encode(b)
}
pub(crate) fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
let v = data_encoding::HEXLOWER.decode(s.as_bytes()).ok()?;
v.try_into().ok()
}
pub(crate) fn b64(b: &[u8]) -> String {
data_encoding::BASE64.encode(b)
}
pub(crate) fn unb64(s: &str) -> Option<Vec<u8>> {
data_encoding::BASE64.decode(s.as_bytes()).ok()
}
pub(crate) fn sha256(b: &[u8]) -> [u8; 32] {
use sha2::Digest;
sha2::Sha256::digest(b).into()
}
/// 32 lower-case hex digits: a team, member or request id.
pub fn id_ok(s: &str) -> bool {
s.len() == 32 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
/// A random 16-byte id, hex.
pub fn new_id() -> String {
let mut b = [0u8; 16];
rand::Rng::fill_bytes(&mut rand::rand_core::UnwrapErr(rand::rngs::SysRng), &mut b);
hex(&b)
}
+179
View File
@@ -0,0 +1,179 @@
//! A person's member key, the team identity, and sealing the team key to a member (docs/TEAM.md, "The member key",
//! "The team vault file").
use std::fmt;
use custos_seal::Recipient;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use zeroize::Zeroizing;
use crate::{TeamError, hex, sha256};
/// The size of a sealed team key: custos-seal's box around 32 bytes.
pub const SEALED_KEY_LEN: usize = 4 + 32 + 24 + 32 + 16;
/// The public half of a member key, as the roster and the service keep it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemberPublic {
pub ed25519: [u8; 32],
pub x25519: [u8; 32],
}
impl MemberPublic {
/// The member id: the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 ‖ x25519)`, 32 hex.
pub fn id(&self) -> String {
hex(&self.id_bytes())
}
pub fn id_bytes(&self) -> [u8; 16] {
let mut m = Vec::with_capacity(16 + 64);
m.extend_from_slice(b"custos member v1");
m.extend_from_slice(&self.ed25519);
m.extend_from_slice(&self.x25519);
sha256(&m)[..16].try_into().expect("16 bytes")
}
/// The code a joining member's screen shows and the approving member compares: `match_code(x25519)`.
pub fn join_code(&self) -> String {
custos_seal::match_code(&self.x25519)
}
/// Both keys must be usable: an Ed25519 point and a contributory X25519 key.
pub fn check(&self) -> Result<(), TeamError> {
VerifyingKey::from_bytes(&self.ed25519).map_err(|_| TeamError::BadKey)?;
custos_seal::seal(&self.x25519, b"check", b"").map_err(|_| TeamError::BadKey)?;
Ok(())
}
/// Checks an Ed25519 signature by this member over `msg`.
pub fn verify(&self, msg: &[u8], sig: &[u8; 64]) -> bool {
verify(&self.ed25519, msg, sig)
}
}
pub(crate) fn verify(public: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> bool {
let Ok(key) = VerifyingKey::from_bytes(public) else {
return false;
};
key.verify_strict(msg, &Signature::from_bytes(sig)).is_ok()
}
/// The context a team key is sealed under for one member slot.
pub fn key_context(team: &str, epoch: u32, member: &str) -> Vec<u8> {
format!("custos team key v1:{team}:{epoch}:{member}").into_bytes()
}
/// Seals the 32-byte team key to a member for one team and epoch: the member slot's box ([`SEALED_KEY_LEN`] bytes).
pub fn seal_team_key(team_key: &[u8; 32], to: &MemberPublic, team: &str, epoch: u32) -> Result<Vec<u8>, TeamError> {
custos_seal::seal(&to.x25519, &key_context(team, epoch, &to.id()), team_key).map_err(|_| TeamError::BadKey)
}
/// A person's member key. Lives in their own vault; wiped on drop; prints `[redacted]`.
pub struct MemberKey {
x: Recipient,
ed: SigningKey,
}
impl MemberKey {
/// A new member key from the OS CSPRNG.
pub fn generate() -> MemberKey {
let ed = custos_seal::random_bytes();
MemberKey { x: Recipient::generate(), ed: SigningKey::from_bytes(&ed) }
}
/// The key as the member's vault keeps it.
pub fn from_secrets(x25519: Zeroizing<[u8; 32]>, ed25519: Zeroizing<[u8; 32]>) -> Result<MemberKey, TeamError> {
let x = Recipient::from_secret(x25519).map_err(|_| TeamError::BadKey)?;
Ok(MemberKey { x, ed: SigningKey::from_bytes(&ed25519) })
}
/// The X25519 secret, for the member's own vault only.
pub fn x25519_secret(&self) -> Zeroizing<[u8; 32]> {
self.x.secret_bytes()
}
/// The Ed25519 seed, for the member's own vault only.
pub fn ed25519_secret(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.ed.to_bytes())
}
pub fn public(&self) -> MemberPublic {
MemberPublic { ed25519: self.ed.verifying_key().to_bytes(), x25519: self.x.public() }
}
pub fn id(&self) -> String {
self.public().id()
}
/// Opens this member's slot of a team vault: the team key.
pub fn open_team_key(&self, sealed: &[u8], team: &str, epoch: u32) -> Result<Zeroizing<[u8; 32]>, TeamError> {
let k = self.x.open(sealed, &key_context(team, epoch, &self.id())).map_err(|_| TeamError::NotAMember)?;
let k: [u8; 32] = k.as_slice().try_into().map_err(|_| TeamError::NotAMember)?;
Ok(Zeroizing::new(k))
}
/// Signs `msg` with the member's Ed25519 key (approval statements only; the domain is the caller's prefix).
pub(crate) fn sign(&self, msg: &[u8]) -> [u8; 64] {
self.ed.sign(msg).to_bytes()
}
/// Opens a box sealed to this member's X25519 key (for a joiner: nothing else is ever sealed to it).
pub fn recipient(&self) -> &Recipient {
&self.x
}
}
impl fmt::Debug for MemberKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// The team identity: an Ed25519 key in the team body that signs the policy and the proofs, and never rotates.
pub struct TeamIdentity(SigningKey);
/// Domain prefixes, so a signature of one kind never passes for another.
pub const POLICY_DOMAIN: &[u8] = b"custos team policy v1\0";
pub const PROOF_DOMAIN: &[u8] = b"custos team proof v1\0";
impl TeamIdentity {
pub fn generate() -> TeamIdentity {
TeamIdentity(SigningKey::from_bytes(&custos_seal::random_bytes()))
}
pub fn from_secret(secret: &[u8; 32]) -> TeamIdentity {
TeamIdentity(SigningKey::from_bytes(secret))
}
pub fn secret(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.0.to_bytes())
}
pub fn public(&self) -> [u8; 32] {
self.0.verifying_key().to_bytes()
}
pub fn sign_policy(&self, text: &str) -> [u8; 64] {
self.0.sign(&[POLICY_DOMAIN, text.as_bytes()].concat()).to_bytes()
}
pub fn sign_proof(&self, text: &str) -> [u8; 64] {
self.0.sign(&[PROOF_DOMAIN, text.as_bytes()].concat()).to_bytes()
}
}
impl fmt::Debug for TeamIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// Checks the team identity's signature on a policy text.
pub fn verify_policy_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
verify(identity, &[POLICY_DOMAIN, text.as_bytes()].concat(), sig)
}
/// Checks the team identity's signature on a proof text.
pub fn verify_proof_sig(identity: &[u8; 32], text: &str, sig: &[u8; 64]) -> bool {
verify(identity, &[PROOF_DOMAIN, text.as_bytes()].concat(), sig)
}
+290
View File
@@ -0,0 +1,290 @@
//! The approval policy: one rule per environment, its canonical text, and its evaluation (docs/TEAM.md, "Policy").
use serde::{Deserialize, Serialize};
use crate::{TeamError, canon, id_ok};
/// One environment's rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvRule {
pub env: String,
/// How many members must approve: 0 ..= 10. At 0 a test-role key signs without a card.
pub approvals: u8,
/// The approvers must not include the release's author, when the team has 2 or more members.
pub others: bool,
/// Member ids allowed to approve; empty = every member.
pub approvers: Vec<String>,
}
/// A team's policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Policy {
pub team: String,
pub rev: u32,
pub envs: Vec<EnvRule>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PolicyJson {
v: u32,
team: String,
rev: u32,
envs: Vec<EnvRule>,
}
pub const MAX_APPROVALS: u8 = 10;
pub const MAX_ENVS: usize = 8;
impl Policy {
/// The default (docs/TEAM.md): preview 0, staging 1, production 1 by someone other than the author.
pub fn default_for(team: &str) -> Policy {
let rule = |env: &str, approvals, others| EnvRule { env: env.into(), approvals, others, approvers: vec![] };
Policy {
team: team.into(),
rev: 1,
envs: vec![rule("preview", 0, false), rule("staging", 1, false), rule("production", 1, true)],
}
}
pub fn rule(&self, env: &str) -> Option<&EnvRule> {
self.envs.iter().find(|r| r.env == env)
}
/// The canonical text the team identity signs.
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"rev\":");
o.push_str(&self.rev.to_string());
o.push_str(",\"envs\":[");
for (i, r) in self.envs.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"env\":");
canon::string(&mut o, &r.env);
o.push_str(",\"approvals\":");
o.push_str(&r.approvals.to_string());
o.push_str(",\"others\":");
o.push_str(if r.others { "true" } else { "false" });
o.push_str(",\"approvers\":");
canon::strings(&mut o, &r.approvers);
o.push('}');
}
o.push_str("]}");
o
}
/// Every rule as docs/TEAM.md allows it.
pub fn check(&self) -> Result<(), TeamError> {
let bad = |why| Err(TeamError::Invalid(why));
if !id_ok(&self.team) {
return bad("the policy's team is not an id");
}
if self.rev == 0 {
return bad("the policy's rev starts at 1");
}
if self.envs.is_empty() || self.envs.len() > MAX_ENVS {
return bad("a policy has 1 to 8 environments");
}
for (i, r) in self.envs.iter().enumerate() {
if !canon::env_ok(&r.env) {
return bad("an environment is not [a-z][a-z0-9-]{0,31}");
}
if self.envs[..i].iter().any(|o| o.env == r.env) {
return bad("an environment is named twice");
}
if r.approvals > MAX_APPROVALS {
return bad("at most 10 approvals");
}
if r.approvers.len() > crate::MAX_MEMBERS || !r.approvers.iter().all(|a| id_ok(a)) {
return bad("approvers are member ids");
}
if r.approvers.iter().enumerate().any(|(j, a)| r.approvers[..j].contains(a)) {
return bad("an approver is named twice");
}
}
Ok(())
}
/// Reads a canonical policy text; anything else is refused, not normalised.
pub fn parse(text: &str) -> Result<Policy, TeamError> {
if text.len() > 16 * 1024 {
return Err(TeamError::NotCanonical("a policy is at most 16 KiB"));
}
let j: PolicyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a policy"))?;
if j.v != 1 {
return Err(TeamError::NotCanonical("v is not 1"));
}
let p = Policy { team: j.team, rev: j.rev, envs: j.envs };
p.check()?;
if p.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(p)
}
/// Replaces (or adds) one environment's rule and raises `rev`.
pub fn set_rule(&mut self, rule: EnvRule) -> Result<(), TeamError> {
let mut next = self.clone();
match next.envs.iter_mut().find(|r| r.env == rule.env) {
Some(r) => *r = rule,
None => next.envs.push(rule),
}
next.rev = self.rev.checked_add(1).ok_or(TeamError::Invalid("rev overflow"))?;
next.check()?;
*self = next;
Ok(())
}
}
/// A member as the policy sees it: who they are and the names Fabrica knows them by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RosterMember {
pub id: String,
pub name: String,
pub handles: Vec<String>,
pub ed25519: [u8; 32],
}
impl RosterMember {
/// The member's id, or one of their handles (ASCII case-insensitive), names `author`.
pub fn is(&self, author: &str) -> bool {
!author.is_empty() && (self.id == author || self.handles.iter().any(|h| h.eq_ignore_ascii_case(author)))
}
}
/// Which kind of key a verdict allows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KeyRole {
/// The environment asks for 1+ approvals and they are there: the release keys.
Release,
/// The environment asks for 0: a test-role key, no card.
Test,
}
impl KeyRole {
pub fn word(self) -> &'static str {
match self {
KeyRole::Release => "release",
KeyRole::Test => "test",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Allowed(KeyRole),
/// This many more eligible approvals are needed.
Need(u8),
/// No set of approvals can ever meet the rule.
Unsatisfiable(&'static str),
UnknownEnv,
}
/// The verdict and how it was reached.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Evaluation {
pub verdict: Verdict,
/// Members who may approve this request.
pub eligible: Vec<String>,
/// The approvals that counted, distinct, in the order given.
pub counted: Vec<String>,
/// Approvals that did not count: not on the roster, not eligible (the author, not an approver), a repeat.
pub ignored: Vec<String>,
}
impl Evaluation {
pub fn into_result(self) -> Result<KeyRole, TeamError> {
match self.verdict {
Verdict::Allowed(r) => Ok(r),
Verdict::Need(n) => Err(TeamError::NeedMore(n)),
Verdict::Unsatisfiable(w) => Err(TeamError::Unsatisfiable(w)),
Verdict::UnknownEnv => Err(TeamError::UnknownEnv),
}
}
}
/// Who may approve a request for `env` by `author`.
pub fn eligible(policy: &Policy, roster: &[RosterMember], env: &str, author: &str) -> Option<Vec<String>> {
let rule = policy.rule(env)?;
let others = rule.others && roster.len() >= 2;
Some(
roster
.iter()
.filter(|m| rule.approvers.is_empty() || rule.approvers.contains(&m.id))
.filter(|m| !(others && m.is(author)))
.map(|m| m.id.clone())
.collect(),
)
}
/// Evaluates the policy for one request (docs/TEAM.md, "Evaluation"). `approvers` are member ids whose approval
/// statements were already checked.
pub fn evaluate(policy: &Policy, roster: &[RosterMember], env: &str, author: &str, approvers: &[String]) -> Evaluation {
let Some(rule) = policy.rule(env) else {
return Evaluation {
verdict: Verdict::UnknownEnv,
eligible: vec![],
counted: vec![],
ignored: approvers.to_vec(),
};
};
let eligible = eligible(policy, roster, env, author).unwrap_or_default();
let mut counted: Vec<String> = Vec::new();
let mut ignored = Vec::new();
for a in approvers {
if eligible.contains(a) && !counted.contains(a) {
counted.push(a.clone());
} else {
ignored.push(a.clone());
}
}
// `others` needs to know who the author is (core 0.18.1): an empty author, or one no member is, would let the
// author approve their own release under a name the rule cannot see.
let unknown_author = rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author));
let verdict = if rule.approvals == 0 {
Verdict::Allowed(KeyRole::Test)
} else if unknown_author {
Verdict::Unsatisfiable("the release's author is not a member the team knows, so the rule cannot exclude them")
} else if counted.len() >= rule.approvals as usize {
Verdict::Allowed(KeyRole::Release)
} else if eligible.len() < rule.approvals as usize {
Verdict::Unsatisfiable(if rule.others && roster.len() >= 2 && eligible.is_empty() {
"only the author may approve, and the rule needs someone else"
} else {
"the rule needs more approvals than there are members who may give them"
})
} else {
Verdict::Need(rule.approvals - counted.len() as u8)
};
Evaluation { verdict, eligible, counted, ignored }
}
/// Why `member` may not approve this request, or `Ok`.
pub fn may_approve(
policy: &Policy,
roster: &[RosterMember],
env: &str,
author: &str,
member: &str,
) -> Result<(), TeamError> {
let rule = policy.rule(env).ok_or(TeamError::UnknownEnv)?;
let Some(me) = roster.iter().find(|m| m.id == member) else {
return Err(TeamError::NotAMember);
};
if !rule.approvers.is_empty() && !rule.approvers.contains(&me.id) {
return Err(TeamError::NotEligible("not on this environment's approver list"));
}
if rule.others && roster.len() >= 2 && me.is(author) {
return Err(TeamError::NotEligible("the release's author may not approve it here"));
}
if rule.approvals > 0 && rule.others && roster.len() >= 2 && !roster.iter().any(|m| m.is(author)) {
return Err(TeamError::NotEligible("the release's author is not a member the team knows"));
}
Ok(())
}
+227
View File
@@ -0,0 +1,227 @@
//! The policy proof (docs/TEAM.md, "The policy proof"): signed by the team identity, it says which request was
//! signed under which policy, with whose approvals, by whom, and over which envelope. Anyone who pinned the team
//! identity checks it with [`verify_proof`], which accepts only what the signing Custos itself would have signed.
use serde::{Deserialize, Serialize};
use crate::member::{TeamIdentity, verify_policy_sig, verify_proof_sig};
use crate::policy::{KeyRole, Policy, RosterMember, evaluate};
use crate::request::SignRequest;
use crate::statement::{Statement, verified_members};
use crate::{TeamError, b64, canon, hex, sha256, unb64, unhex};
/// The proof as it travels: its canonical text and the team identity's signature over it (base64).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Proof {
pub text: String,
pub sig: String,
}
/// A roster member as a proof lists them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RosterJson {
id: String,
name: String,
handles: Vec<String>,
ed25519: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BodyJson {
v: u32,
team: String,
request: String,
env: String,
author: String,
policy: String,
policy_sig: String,
roster: Vec<RosterJson>,
approvals: Vec<Statement>,
signer: String,
role: KeyRole,
signature: String,
at: u64,
}
/// What a proof says, as the team's Custos builds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProofBody {
pub team: String,
/// The request hash (hex).
pub request: String,
pub env: String,
pub author: String,
pub policy: String,
pub policy_sig: [u8; 64],
pub roster: Vec<RosterMember>,
pub approvals: Vec<Statement>,
pub signer: String,
pub role: KeyRole,
/// SHA-256 (hex) of the envelope that was returned.
pub signature: String,
pub at: u64,
}
impl ProofBody {
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(1024);
o.push_str("{\"v\":1,\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"request\":");
canon::string(&mut o, &self.request);
o.push_str(",\"env\":");
canon::string(&mut o, &self.env);
o.push_str(",\"author\":");
canon::string(&mut o, &self.author);
o.push_str(",\"policy\":");
canon::string(&mut o, &self.policy);
o.push_str(",\"policy_sig\":");
canon::string(&mut o, &b64(&self.policy_sig));
o.push_str(",\"roster\":[");
for (i, m) in self.roster.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"id\":");
canon::string(&mut o, &m.id);
o.push_str(",\"name\":");
canon::string(&mut o, &m.name);
o.push_str(",\"handles\":");
canon::strings(&mut o, &m.handles);
o.push_str(",\"ed25519\":");
canon::string(&mut o, &hex(&m.ed25519));
o.push('}');
}
o.push_str("],\"approvals\":[");
for (i, s) in self.approvals.iter().enumerate() {
if i > 0 {
o.push(',');
}
o.push_str("{\"member\":");
canon::string(&mut o, &s.member);
o.push_str(",\"code\":");
canon::string(&mut o, &s.code);
o.push_str(",\"at\":");
o.push_str(&s.at.to_string());
o.push_str(",\"sig\":");
canon::string(&mut o, &s.sig);
o.push('}');
}
o.push_str("],\"signer\":");
canon::string(&mut o, &self.signer);
o.push_str(",\"role\":");
canon::string(&mut o, self.role.word());
o.push_str(",\"signature\":");
canon::string(&mut o, &self.signature);
o.push_str(",\"at\":");
o.push_str(&self.at.to_string());
o.push('}');
o
}
/// Signed by the team identity.
pub fn sign(&self, identity: &TeamIdentity) -> Proof {
let text = self.canonical();
let sig = identity.sign_proof(&text);
Proof { text, sig: b64(&sig) }
}
pub fn parse(text: &str) -> Result<ProofBody, TeamError> {
if text.len() > 64 * 1024 {
return Err(TeamError::NotCanonical("a proof is at most 64 KiB"));
}
let j: BodyJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a proof"))?;
if j.v != 1 {
return Err(TeamError::NotCanonical("v is not 1"));
}
let mut roster = Vec::new();
for m in j.roster {
let ed25519 = unhex::<32>(&m.ed25519).ok_or(TeamError::Invalid("a roster key is not 64 hex"))?;
roster.push(RosterMember { id: m.id, name: m.name, handles: m.handles, ed25519 });
}
let body = ProofBody {
team: j.team,
request: j.request,
env: j.env,
author: j.author,
policy: j.policy,
policy_sig: unb64(&j.policy_sig)
.and_then(|s| s.try_into().ok())
.ok_or(TeamError::Invalid("policy_sig is not base64 of 64 bytes"))?,
roster,
approvals: j.approvals,
signer: j.signer,
role: j.role,
signature: j.signature,
at: j.at,
};
if body.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(body)
}
}
/// What a proof established.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verified {
pub role: KeyRole,
pub env: String,
pub signer: String,
/// The approvals that counted under the policy.
pub approvers: Vec<String>,
pub policy_rev: u32,
}
/// Checks a proof against the pinned team identity, the request it was made for and the envelope that came back
/// with it: both signatures, every approval (signature, roster, the request's own match code), the request and
/// envelope hashes, and the policy evaluated again. The clock is not consulted: a proof stays checkable after its
/// request expired.
pub fn verify_proof(
proof: &Proof,
identity: &[u8; 32],
request_text: &str,
envelope: &[u8],
) -> Result<Verified, TeamError> {
let sig: [u8; 64] = unb64(&proof.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
if !verify_proof_sig(identity, &proof.text, &sig) {
return Err(TeamError::BadSignature);
}
let body = ProofBody::parse(&proof.text)?;
let req = SignRequest::parse(request_text)?;
if body.request != req.hash_hex() {
return Err(TeamError::Invalid("the proof is for another request"));
}
if body.team != req.team || body.env != req.env || body.author != req.author {
return Err(TeamError::Invalid("the proof does not match the request's team, env or author"));
}
if body.signature != hex(&sha256(envelope)) {
return Err(TeamError::Invalid("the proof is for another signature"));
}
if !verify_policy_sig(identity, &body.policy, &body.policy_sig) {
return Err(TeamError::BadSignature);
}
let policy = Policy::parse(&body.policy)?;
if policy.team != body.team {
return Err(TeamError::WrongTeam);
}
if !body.roster.iter().any(|m| m.id == body.signer) {
return Err(TeamError::NotAMember);
}
for s in &body.approvals {
s.verify(&req, &body.roster)?;
}
let approvers = verified_members(&body.approvals, &req, &body.roster);
let eval = evaluate(&policy, &body.roster, &req.env, &req.author, &approvers);
let role = eval.clone().into_result()?;
if role != body.role {
return Err(TeamError::Invalid("the proof's key role is not what the policy gives"));
}
if role == KeyRole::Release && !eval.counted.contains(&body.signer) {
return Err(TeamError::Invalid("the signer's own approval is not among those that counted"));
}
Ok(Verified { role, env: body.env, signer: body.signer, approvers: eval.counted, policy_rev: policy.rev })
}
+50
View File
@@ -0,0 +1,50 @@
//! What goes back to Fabrica, sealed to the request's `pub` (docs/TEAM.md, "The reply").
use serde::{Deserialize, Serialize};
use crate::proof::Proof;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplyKey {
pub id: String,
/// `minisign.pub` text, `cosign.pub` PEM, or a certificate PEM.
pub public: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplySigner {
pub member: String,
pub name: String,
}
/// `sign.reply` v1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignReply {
pub v: u32,
pub op: String,
/// The request hash (hex).
pub request: String,
pub format: String,
/// The envelope (docs/TEAM.md, "Signature envelopes").
pub signature: String,
/// cosign only: the payload that was signed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload: Option<String>,
pub key: ReplyKey,
pub signer: ReplySigner,
pub proof: Proof,
/// The deployment ticket (core 0.18.1): 32 random bytes, base64, for the `mac` of this deployment's
/// `target.request`s. Secret: it travels only inside the sealed reply; never log it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ticket: Option<String>,
}
impl SignReply {
/// The bytes the proof's `signature` hashes: the envelope as text.
pub fn envelope(&self) -> &[u8] {
self.signature.as_bytes()
}
}
+384
View File
@@ -0,0 +1,384 @@
//! The canonical `sign.request` and `target.request` (docs/TEAM.md, "The signing request"). Parsed, written again
//! in canonical form and compared byte for byte: any other spelling is refused, not normalised.
use serde::Deserialize;
use crate::{MAX_AHEAD_SECS, TeamError, b64, canon, hex, id_ok, sha256, unb64};
/// The largest request text read.
pub const MAX_REQUEST: usize = 4 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Minisign,
TauriUpdater,
Apk,
Cosign,
Authenticode,
}
impl Format {
pub fn word(self) -> &'static str {
match self {
Format::Minisign => "minisign",
Format::TauriUpdater => "tauri-updater",
Format::Apk => "apk",
Format::Cosign => "cosign",
Format::Authenticode => "authenticode",
}
}
pub fn from_word(w: &str) -> Option<Format> {
Some(match w {
"minisign" => Format::Minisign,
"tauri-updater" => Format::TauriUpdater,
"apk" => Format::Apk,
"cosign" => Format::Cosign,
"authenticode" => Format::Authenticode,
_ => return None,
})
}
/// Whether `digest` has this format's length (docs/TEAM.md, `artifact_digest`).
pub fn digest_ok(self, digest: &[u8]) -> bool {
match self {
Format::Minisign | Format::TauriUpdater => digest.len() == 64,
Format::Apk => !digest.is_empty() && digest.len() % 64 == 0 && digest.len() <= 64 * 4,
Format::Cosign | Format::Authenticode => digest.len() == 32,
}
}
}
/// What the build claims about the file; shown on the card.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Artifact {
pub name: String,
pub size: u64,
pub sha256: String,
}
/// A checked `sign.request`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignRequest {
pub team: String,
pub id: String,
pub project: String,
pub release: String,
pub env: String,
pub author: String,
pub format: Format,
pub artifact: Artifact,
pub artifact_digest: Vec<u8>,
pub image: String,
pub public: [u8; 32],
pub expires: u64,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SignJson {
v: u32,
op: String,
team: String,
id: String,
project: String,
release: String,
env: String,
author: String,
format: String,
artifact: Artifact,
artifact_digest: String,
image: String,
#[serde(rename = "pub")]
public: String,
expires: u64,
}
fn lower_hex(s: &str, len: usize) -> bool {
s.len() == len && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
pub(crate) fn pub_key(s: &str) -> Result<[u8; 32], TeamError> {
let k: [u8; 32] =
unb64(s).and_then(|v| v.try_into().ok()).ok_or(TeamError::Invalid("pub is not base64 of 32 bytes"))?;
if k == [0; 32] {
return Err(TeamError::Invalid("pub is all zeros"));
}
Ok(k)
}
fn name_ok(name: &str) -> bool {
canon::text_ok(name, 200) && !name.contains(['/', '\\'])
}
impl SignRequest {
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(640);
o.push_str("{\"v\":1,\"op\":\"sign.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"project\":");
canon::string(&mut o, &self.project);
o.push_str(",\"release\":");
canon::string(&mut o, &self.release);
o.push_str(",\"env\":");
canon::string(&mut o, &self.env);
o.push_str(",\"author\":");
canon::string(&mut o, &self.author);
o.push_str(",\"format\":");
canon::string(&mut o, self.format.word());
o.push_str(",\"artifact\":{\"name\":");
canon::string(&mut o, &self.artifact.name);
o.push_str(",\"size\":");
o.push_str(&self.artifact.size.to_string());
o.push_str(",\"sha256\":");
canon::string(&mut o, &self.artifact.sha256);
o.push_str("},\"artifact_digest\":");
canon::string(&mut o, &b64(&self.artifact_digest));
o.push_str(",\"image\":");
canon::string(&mut o, &self.image);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o.push('}');
o
}
/// Every field as docs/TEAM.md allows it, without the clock.
pub fn check_fields(&self) -> Result<(), TeamError> {
let bad = |w| Err(TeamError::Invalid(w));
if !id_ok(&self.team) || !id_ok(&self.id) {
return bad("team and id are 32 lower-case hex digits");
}
if !canon::ascii_ok(&self.project, 1, 128, b"._/-") {
return bad("project is 1 to 128 of [A-Za-z0-9._/-]");
}
if !canon::ascii_ok(&self.release, 1, 64, b"._+-") {
return bad("release is 1 to 64 of [A-Za-z0-9._+-]");
}
if !canon::env_ok(&self.env) {
return bad("env is [a-z][a-z0-9-]{0,31}");
}
if !canon::ascii_ok(&self.author, 0, 64, b"._@-") {
return bad("author is 0 to 64 of [A-Za-z0-9._@-]");
}
if !name_ok(&self.artifact.name) {
return bad("the artifact's name is 1 to 200 characters, no path, no control characters");
}
if !lower_hex(&self.artifact.sha256, 64) {
return bad("the artifact's sha256 is 64 lower-case hex digits");
}
if !self.format.digest_ok(&self.artifact_digest) {
return bad("artifact_digest has the wrong length for its format");
}
match self.format {
Format::Cosign => {
custos_sign::image_ok(&self.image).map_err(|_| TeamError::Invalid("image is not a repository"))?
}
_ if !self.image.is_empty() => return bad("image is for cosign only"),
_ => {}
}
Ok(())
}
/// Reads a canonical request, without the clock: for showing what an expired request said. Never enough to sign.
pub fn parse(text: &str) -> Result<SignRequest, TeamError> {
if text.len() > MAX_REQUEST {
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
}
let j: SignJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a sign.request"))?;
if j.v != 1 || j.op != "sign.request" {
return Err(TeamError::NotCanonical("not a sign.request v1"));
}
let format = Format::from_word(&j.format).ok_or(TeamError::Invalid("an unknown format"))?;
let digest = unb64(&j.artifact_digest).ok_or(TeamError::Invalid("artifact_digest is not base64"))?;
let r = SignRequest {
team: j.team,
id: j.id,
project: j.project,
release: j.release,
env: j.env,
author: j.author,
format,
artifact: j.artifact,
artifact_digest: digest,
image: j.image,
public: pub_key(&j.public)?,
expires: j.expires,
};
r.check_fields()?;
if r.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
Ok(r)
}
/// [`SignRequest::parse`] and the clock: not expired at `now` (Unix seconds), at most 25 hours ahead.
pub fn check(text: &str, now: u64) -> Result<SignRequest, TeamError> {
let r = SignRequest::parse(text)?;
if r.expires <= now {
return Err(TeamError::Expired);
}
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
}
Ok(r)
}
/// SHA-256 of the canonical text.
pub fn hash(&self) -> [u8; 32] {
sha256(self.canonical().as_bytes())
}
pub fn hash_hex(&self) -> String {
hex(&self.hash())
}
/// The match code Fabrica shows and every card shows: `match_code(pub)`.
pub fn match_code(&self) -> String {
custos_seal::match_code(&self.public)
}
/// The context the reply is sealed under.
pub fn reply_context(&self) -> Vec<u8> {
format!("team-sign:{}", self.id).into_bytes()
}
}
/// Fabrica asks for a target credential for one deployment (docs/TEAM.md, "Target credentials").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetRequest {
pub team: String,
pub id: String,
pub target: String,
/// The hash of the `sign.request` whose signature this deployment deploys.
pub deployment: String,
pub public: [u8; 32],
pub expires: u64,
/// HMAC-SHA256 with the deployment's ticket (core 0.18.1): only the Fabrica that opened the signing reply has the
/// ticket, so only it can ask for the deployment's credentials.
pub mac: [u8; 32],
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TargetJson {
v: u32,
op: String,
team: String,
id: String,
target: String,
deployment: String,
#[serde(rename = "pub")]
public: String,
expires: u64,
mac: String,
}
/// The domain of a target request's MAC.
pub const TARGET_MAC_DOMAIN: &[u8] = b"custos team target v1\0";
impl TargetRequest {
/// The text the MAC covers: the canonical request without `mac`.
fn unsigned(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"target\":");
canon::string(&mut o, &self.target);
o.push_str(",\"deployment\":");
canon::string(&mut o, &self.deployment);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o
}
fn mac_over(&self, ticket: &[u8; 32]) -> hmac::Hmac<sha2::Sha256> {
use hmac::KeyInit;
let mut m = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(ticket).expect("any key length");
hmac::Mac::update(&mut m, TARGET_MAC_DOMAIN);
hmac::Mac::update(&mut m, self.unsigned().as_bytes());
m
}
/// Sets `mac` with the deployment's ticket (from the sealed `sign.reply`).
pub fn sign_with(mut self, ticket: &[u8; 32]) -> TargetRequest {
self.mac = hmac::Mac::finalize(self.mac_over(ticket)).into_bytes().into();
self
}
/// Whether `mac` was made with this ticket (constant time).
pub fn mac_ok(&self, ticket: &[u8; 32]) -> bool {
hmac::Mac::verify_slice(self.mac_over(ticket), &self.mac).is_ok()
}
pub fn canonical(&self) -> String {
let mut o = String::with_capacity(256);
o.push_str("{\"v\":1,\"op\":\"target.request\",\"team\":");
canon::string(&mut o, &self.team);
o.push_str(",\"id\":");
canon::string(&mut o, &self.id);
o.push_str(",\"target\":");
canon::string(&mut o, &self.target);
o.push_str(",\"deployment\":");
canon::string(&mut o, &self.deployment);
o.push_str(",\"pub\":");
canon::string(&mut o, &b64(&self.public));
o.push_str(",\"expires\":");
o.push_str(&self.expires.to_string());
o.push_str(",\"mac\":");
canon::string(&mut o, &b64(&self.mac));
o.push('}');
o
}
/// Reads and checks a canonical target request at `now`; it lives at most 25 hours.
pub fn check(text: &str, now: u64) -> Result<TargetRequest, TeamError> {
if text.len() > MAX_REQUEST {
return Err(TeamError::NotCanonical("a request is at most 4 KiB"));
}
let j: TargetJson = serde_json::from_str(text).map_err(|_| TeamError::NotCanonical("not a target.request"))?;
if j.v != 1 || j.op != "target.request" {
return Err(TeamError::NotCanonical("not a target.request v1"));
}
let r = TargetRequest {
team: j.team,
id: j.id,
target: j.target,
deployment: j.deployment,
public: pub_key(&j.public)?,
expires: j.expires,
mac: unb64(&j.mac)
.and_then(|m| m.try_into().ok())
.ok_or(TeamError::Invalid("mac is not base64 of 32 bytes"))?,
};
if !id_ok(&r.team) || !id_ok(&r.id) || !lower_hex(&r.target, 16) || !lower_hex(&r.deployment, 64) {
return Err(TeamError::Invalid("team, id, target and deployment are hex ids"));
}
if r.canonical() != text {
return Err(TeamError::NotCanonical("key order, spaces or escaping"));
}
if r.expires <= now {
return Err(TeamError::Expired);
}
if r.expires > now.saturating_add(MAX_AHEAD_SECS) {
return Err(TeamError::Invalid("it expires more than 25 hours from now"));
}
Ok(r)
}
pub fn match_code(&self) -> String {
custos_seal::match_code(&self.public)
}
pub fn reply_context(&self) -> Vec<u8> {
format!("team-target:{}", self.id).into_bytes()
}
}
+75
View File
@@ -0,0 +1,75 @@
//! A member's approval of one request (docs/TEAM.md, "Approval statements").
use serde::{Deserialize, Serialize};
use crate::member::MemberKey;
use crate::policy::RosterMember;
use crate::request::SignRequest;
use crate::{TeamError, b64, unb64, unhex};
pub const APPROVAL_DOMAIN: &[u8] = b"custos team approval v1\0";
/// `{"member", "code", "at", "sig"}`: who approved which request (by its hash, outside), with which code, when.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Statement {
pub member: String,
pub code: String,
pub at: u64,
/// Base64 of the 64-byte Ed25519 signature.
pub sig: String,
}
/// What a statement signs.
pub fn message(request_hash: &[u8; 32], code: &str, member: &[u8; 16], at: u64) -> Vec<u8> {
let mut m = Vec::with_capacity(APPROVAL_DOMAIN.len() + 32 + 6 + 16 + 8);
m.extend_from_slice(APPROVAL_DOMAIN);
m.extend_from_slice(request_hash);
m.extend_from_slice(code.as_bytes());
m.extend_from_slice(member);
m.extend_from_slice(&at.to_be_bytes());
m
}
fn code_ok(code: &str) -> bool {
code.len() == 6 && code.bytes().all(|c| c.is_ascii_digit())
}
/// A member approves `req`. `shown_code` is the code the card showed: when it is not the request's own match code,
/// the request changed after the card was drawn, or it is someone else's, and nothing is signed (`WrongMatch`).
pub fn approve(key: &MemberKey, req: &SignRequest, shown_code: &str, now: u64) -> Result<Statement, TeamError> {
if shown_code != req.match_code() {
return Err(TeamError::WrongMatch);
}
let id = key.public().id_bytes();
let sig = key.sign(&message(&req.hash(), shown_code, &id, now));
Ok(Statement { member: key.id(), code: shown_code.into(), at: now, sig: b64(&sig) })
}
impl Statement {
/// Checks this statement for `req` against the roster: the member is on it, the code is the request's own,
/// the signature is the member's.
pub fn verify(&self, req: &SignRequest, roster: &[RosterMember]) -> Result<(), TeamError> {
if !code_ok(&self.code) || self.code != req.match_code() {
return Err(TeamError::WrongMatch);
}
let m = roster.iter().find(|m| m.id == self.member).ok_or(TeamError::NotAMember)?;
let id: [u8; 16] = unhex(&self.member).ok_or(TeamError::NotAMember)?;
let sig: [u8; 64] = unb64(&self.sig).and_then(|s| s.try_into().ok()).ok_or(TeamError::BadSignature)?;
if !crate::member::verify(&m.ed25519, &message(&req.hash(), &self.code, &id, self.at), &sig) {
return Err(TeamError::BadSignature);
}
Ok(())
}
}
/// The member ids of the statements that verify for `req`, each once, in order; the others are dropped.
pub fn verified_members(statements: &[Statement], req: &SignRequest, roster: &[RosterMember]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for s in statements {
if s.verify(req, roster).is_ok() && !out.contains(&s.member) {
out.push(s.member.clone());
}
}
out
}
+66
View File
@@ -0,0 +1,66 @@
//! Target credentials (docs/TEAM.md, "Target credentials"): what they are, and the plaintext a released one is
//! sealed as.
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TargetKind {
/// An OpenSSH private key.
SshKey,
/// A WinRM user and password.
Winrm,
/// An OpenSSH user and password.
Openssh,
/// A Docker registry token.
Registry,
/// A kubeconfig.
Kubeconfig,
}
impl TargetKind {
pub fn word(self) -> &'static str {
match self {
TargetKind::SshKey => "ssh-key",
TargetKind::Winrm => "winrm",
TargetKind::Openssh => "openssh",
TargetKind::Registry => "registry",
TargetKind::Kubeconfig => "kubeconfig",
}
}
}
/// The largest target credential.
pub const MAX_SECRET: usize = 64 * 1024;
/// A released credential, as sealed to the Fabrica server's one-time key (`team-target:<request id>`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetRelease {
pub v: u32,
pub op: String,
pub team: String,
pub target: String,
pub kind: TargetKind,
pub name: String,
pub host: String,
pub user: String,
pub secret: String,
/// The deployment's request hash.
pub deployment: String,
pub project: String,
pub env: String,
}
impl fmt::Debug for TargetRelease {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TargetRelease")
.field("target", &self.target)
.field("kind", &self.kind)
.field("deployment", &self.deployment)
.field("secret", &"[redacted]")
.finish_non_exhaustive()
}
}
+213
View File
@@ -0,0 +1,213 @@
//! Mandatory: policy evaluation, every combination of team size, environment and the author/approver rule
//! (docs/TEAM.md, "Evaluation").
use custos_team::policy::{EnvRule, may_approve};
use custos_team::*;
const TEAM: &str = "0123456789abcdef0123456789abcdef";
fn roster(n: usize) -> Vec<RosterMember> {
(0..n)
.map(|i| RosterMember {
id: format!("{i:032x}"),
name: format!("Member {i}"),
// Member 0 is the author; Fabrica names them by handle, in another case.
handles: if i == 0 { vec!["MNovak".into()] } else { vec![format!("dev{i}")] },
ed25519: [i as u8; 32],
})
.collect()
}
fn id(i: usize) -> String {
format!("{i:032x}")
}
const OUTSIDER: &str = "ffffffffffffffffffffffffffffffff";
/// The approver sets every size is tried with.
fn approver_sets(n: usize) -> Vec<(&'static str, Vec<String>)> {
let mut v = vec![("nobody", vec![]), ("the author", vec![id(0)]), ("an outsider", vec![OUTSIDER.into()])];
if n >= 2 {
v.push(("one other", vec![id(1)]));
v.push(("the author and one other", vec![id(0), id(1)]));
v.push(("one other twice", vec![id(1), id(1)]));
}
if n >= 3 {
v.push(("two others", vec![id(1), id(2)]));
}
v
}
/// The rule in the doc's own words, for the default policy.
fn expected(n: usize, env: &str, author_is_member: bool, set: &[String]) -> Verdict {
let members: Vec<&String> = set.iter().filter(|a| a.as_str() != OUTSIDER).collect();
let mut distinct: Vec<&String> = Vec::new();
for m in members {
if !distinct.contains(&m) {
distinct.push(m);
}
}
match env {
"preview" => Verdict::Allowed(KeyRole::Test),
"staging" => {
if distinct.is_empty() {
Verdict::Need(1)
} else {
Verdict::Allowed(KeyRole::Release)
}
}
"production" => {
// "1 by someone other than the release author when the team has 2+ members"
// ... and the rule must know the author: someone no member is (or nobody named) cannot be excluded.
if n >= 2 && !author_is_member {
return Verdict::Unsatisfiable(
"the release's author is not a member the team knows, so the rule cannot exclude them",
);
}
let author_excluded = n >= 2 && author_is_member;
let counted = distinct.iter().filter(|m| !(author_excluded && m.as_str() == id(0))).count();
if counted >= 1 { Verdict::Allowed(KeyRole::Release) } else { Verdict::Need(1) }
}
_ => Verdict::UnknownEnv,
}
}
#[test]
fn every_size_environment_author_and_approver_under_the_default_policy() {
let policy = Policy::default_for(TEAM);
let mut cases = 0;
for n in [1usize, 2, 3, 4, 10] {
let r = roster(n);
for env in ["preview", "staging", "production", "qa"] {
// The author by handle (any case), by member id, someone outside the team, or nobody named.
for (author, is_member) in
[("mnovak", true), ("MNOVAK", true), (id(0).as_str(), true), ("stranger", false), ("", false)]
{
for (what, set) in approver_sets(n) {
let got = evaluate(&policy, &r, env, author, &set);
let want = expected(n, env, is_member, &set);
assert_eq!(got.verdict, want, "size {n}, {env}, author {author:?}, approved by {what}");
cases += 1;
}
}
}
}
assert!(cases > 400, "{cases}");
}
#[test]
fn a_team_of_one_approves_its_own_production_release_and_a_second_member_ends_that() {
let p = Policy::default_for(TEAM);
let solo = roster(1);
assert_eq!(evaluate(&p, &solo, "production", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release));
assert!(may_approve(&p, &solo, "production", "mnovak", &id(0)).is_ok());
let two = roster(2);
let e = evaluate(&p, &two, "production", "mnovak", &[id(0)]);
assert_eq!(e.verdict, Verdict::Need(1));
assert_eq!(e.ignored, vec![id(0)]);
assert_eq!(e.eligible, vec![id(1)]);
assert_eq!(
may_approve(&p, &two, "production", "mnovak", &id(0)),
Err(TeamError::NotEligible("the release's author may not approve it here"))
);
assert!(may_approve(&p, &two, "production", "mnovak", &id(1)).is_ok());
assert_eq!(may_approve(&p, &two, "production", "mnovak", OUTSIDER), Err(TeamError::NotAMember));
assert_eq!(may_approve(&p, &two, "qa", "mnovak", &id(1)), Err(TeamError::UnknownEnv));
}
#[test]
fn several_approvals_others_and_approver_lists() {
let mut p = Policy::default_for(TEAM);
p.set_rule(EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] }).unwrap();
assert_eq!(p.rev, 2);
// Two members, the author excluded: one left for two approvals, which can never be met.
assert!(matches!(evaluate(&p, &roster(2), "production", "mnovak", &[]).verdict, Verdict::Unsatisfiable(_)));
// A team of one: `others` does not apply, but two approvals from one person cannot be.
assert!(matches!(evaluate(&p, &roster(1), "production", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_)));
let three = roster(3);
assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(1)]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &three, "production", "mnovak", &[id(0), id(1)]).verdict, Verdict::Need(1));
assert_eq!(
evaluate(&p, &three, "production", "mnovak", &[id(1), id(2)]).verdict,
Verdict::Allowed(KeyRole::Release)
);
// Someone no member is, or nobody named: the rule cannot exclude the author, so it refuses (core 0.18.1).
for author in ["stranger", ""] {
assert!(matches!(
evaluate(&p, &three, "production", author, &[id(0), id(1)]).verdict,
Verdict::Unsatisfiable(_)
));
assert!(matches!(may_approve(&p, &three, "production", author, &id(1)), Err(TeamError::NotEligible(_))));
}
// Only member 1 may approve staging.
p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: false, approvers: vec![id(1)] }).unwrap();
let four = roster(4);
assert_eq!(evaluate(&p, &four, "staging", "", &[id(2)]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &four, "staging", "", &[id(2), id(1)]).verdict, Verdict::Allowed(KeyRole::Release));
assert!(matches!(may_approve(&p, &four, "staging", "", &id(2)), Err(TeamError::NotEligible(_))));
// The only listed approver is the author, and the rule wants someone else.
p.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap();
assert!(matches!(evaluate(&p, &four, "staging", "mnovak", &[id(0)]).verdict, Verdict::Unsatisfiable(_)));
// ... but in a team of one the author is the only member and approves.
let solo_policy = {
let mut q = Policy::default_for(TEAM);
q.set_rule(EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![id(0)] }).unwrap();
q
};
assert_eq!(
evaluate(&solo_policy, &roster(1), "staging", "mnovak", &[id(0)]).verdict,
Verdict::Allowed(KeyRole::Release)
);
// A preview made strict.
p.set_rule(EnvRule { env: "preview".into(), approvals: 1, others: false, approvers: vec![] }).unwrap();
assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[]).verdict, Verdict::Need(1));
assert_eq!(evaluate(&p, &four, "preview", "mnovak", &[id(0)]).verdict, Verdict::Allowed(KeyRole::Release));
}
#[test]
fn the_policy_text_is_canonical_and_its_rules_are_checked() {
let p = Policy::default_for(TEAM);
let text = p.canonical();
assert_eq!(
text,
"{\"v\":1,\"team\":\"0123456789abcdef0123456789abcdef\",\"rev\":1,\"envs\":[{\"env\":\"preview\",\"approvals\":0,\"others\":false,\"approvers\":[]},{\"env\":\"staging\",\"approvals\":1,\"others\":false,\"approvers\":[]},{\"env\":\"production\",\"approvals\":1,\"others\":true,\"approvers\":[]}]}"
);
assert_eq!(Policy::parse(&text).unwrap(), p);
for bad in [
text.replace("{\"v\":1,", "{ \"v\":1,"),
text.replace("\"rev\":1", "\"rev\":0"),
text.replace("\"approvals\":0", "\"approvals\":11"),
text.replace("\"staging\"", "\"preview\""),
text.replace("\"staging\"", "\"Staging\""),
text.replace("\"approvers\":[]}]", "\"approvers\":[\"nope\"]}]"),
text.replace("{\"v\":1,", "{\"v\":2,"),
text.clone() + "\n",
text.replace(
"\"others\":false,\"approvers\":[]},{\"env\":\"staging\"",
"\"others\":false,\"approvers\":[],\"x\":1},{\"env\":\"staging\"",
),
] {
assert!(Policy::parse(&bad).is_err(), "{bad}");
}
let mut q = p.clone();
assert!(q.set_rule(EnvRule { env: "prod uction".into(), approvals: 1, others: true, approvers: vec![] }).is_err());
assert_eq!(q, p, "a refused change leaves the policy as it was");
}
#[test]
fn the_identity_signs_the_policy_and_nothing_else_passes_for_it() {
let identity = TeamIdentity::generate();
let text = Policy::default_for(TEAM).canonical();
let sig = identity.sign_policy(&text);
assert!(custos_team::member::verify_policy_sig(&identity.public(), &text, &sig));
assert!(!custos_team::member::verify_policy_sig(
&identity.public(),
&text.replace("\"approvals\":1,\"others\":true", "\"approvals\":0,\"others\":true"),
&sig
));
// A proof signature is not a policy signature.
let proof_sig = identity.sign_proof(&text);
assert!(!custos_team::member::verify_policy_sig(&identity.public(), &text, &proof_sig));
assert_eq!(format!("{identity:?}"), "[redacted]");
}
+190
View File
@@ -0,0 +1,190 @@
//! The canonical sign.request, match codes, approval statements and the policy proof (docs/TEAM.md).
use custos_team::policy::Policy;
use custos_team::proof::ProofBody;
use custos_team::statement::{approve, verified_members};
use custos_team::*;
const NOW: u64 = 1_794_000_000;
pub fn request(team: &str, env: &str, author: &str, public: [u8; 32]) -> SignRequest {
SignRequest {
team: team.into(),
id: "aa".repeat(16),
project: "mnovak/Arca".into(),
release: "0.7.0".into(),
env: env.into(),
author: author.into(),
format: Format::Minisign,
artifact: custos_team::request::Artifact {
name: "Arca_0.7.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4".repeat(32),
},
artifact_digest: vec![9; 64],
image: String::new(),
public,
expires: NOW + 3600,
}
}
#[test]
fn a_request_is_read_only_in_canonical_form() {
let fabrica = custos_seal::Recipient::generate();
let r = request(&"01".repeat(16), "production", "mnovak", fabrica.public());
let text = r.canonical();
assert!(text.starts_with("{\"v\":1,\"op\":\"sign.request\",\"team\":\"0101"));
assert_eq!(SignRequest::check(&text, NOW).unwrap(), r);
assert_eq!(r.match_code(), fabrica.match_code());
for bad in [
text.replace(",\"id\"", ", \"id\""),
text.replace("\"op\":\"sign.request\"", "\"op\":\"sign.reply\""),
text.replace("\"format\":\"minisign\"", "\"format\":\"gpg\""),
text.replace("mnovak/Arca", "mnovak/Arca\\u0041"),
text.replace("Arca_0.7.0_x64-setup.exe", "../Arca.exe"),
text.replace("\"env\":\"production\"", "\"env\":\"Production\""),
format!("{text}\n"),
text.replace("\"image\":\"\"", "\"image\":\"arca\""),
] {
assert!(SignRequest::check(&bad, NOW).is_err(), "{bad}");
}
assert_eq!(SignRequest::check(&text, r.expires), Err(TeamError::Expired));
let mut far = r.clone();
far.expires = NOW + 25 * 3600 + 1;
assert!(SignRequest::check(&far.canonical(), NOW).is_err());
// Digest lengths per format.
let mut apk = r.clone();
apk.format = Format::Apk;
apk.artifact_digest = vec![1; 128];
assert!(SignRequest::check(&apk.canonical(), NOW).is_ok());
apk.artifact_digest = vec![1; 64 * 5];
assert!(SignRequest::check(&apk.canonical(), NOW).is_err());
let mut cosign = r.clone();
cosign.format = Format::Cosign;
cosign.artifact_digest = vec![1; 32];
assert!(SignRequest::check(&cosign.canonical(), NOW).is_err(), "cosign needs an image");
cosign.image = "registry.example/team/arca".into();
assert!(SignRequest::check(&cosign.canonical(), NOW).is_ok());
}
fn roster_of(keys: &[&MemberKey]) -> Vec<RosterMember> {
keys.iter()
.enumerate()
.map(|(i, k)| RosterMember {
id: k.id(),
name: format!("M{i}"),
handles: if i == 0 { vec!["mnovak".into()] } else { vec![] },
ed25519: k.public().ed25519,
})
.collect()
}
#[test]
fn a_wrong_match_code_is_refused_and_never_counts() {
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let roster = roster_of(&[&a, &b]);
let fabrica = custos_seal::Recipient::generate();
let req = request(&"01".repeat(16), "production", "mnovak", fabrica.public());
// B's card showed another code: B approves nothing.
let wrong = if req.match_code() == "000000" { "000001" } else { "000000" };
assert_eq!(approve(&b, &req, wrong, NOW), Err(TeamError::WrongMatch));
// A request whose pub was swapped after B's card was drawn: the code B saw is the old request's.
let shown = req.match_code();
let mut swapped = req.clone();
swapped.public = custos_seal::Recipient::generate().public();
assert_eq!(approve(&b, &swapped, &shown, NOW), Err(TeamError::WrongMatch));
// A statement made for one request does not count for the swapped one.
let s = approve(&b, &req, &shown, NOW).unwrap();
s.verify(&req, &roster).unwrap();
assert_eq!(s.verify(&swapped, &roster), Err(TeamError::WrongMatch));
assert!(verified_members(&[s.clone()], &swapped, &roster).is_empty());
// A forged code inside a statement fails its signature or its code.
let mut forged = s.clone();
forged.code = wrong.into();
assert_eq!(forged.verify(&req, &roster), Err(TeamError::WrongMatch));
let mut other_member = s.clone();
other_member.member = a.id();
assert_eq!(other_member.verify(&req, &roster), Err(TeamError::BadSignature));
// Not on the roster.
let c = MemberKey::generate();
let sc = approve(&c, &req, &shown, NOW).unwrap();
assert_eq!(sc.verify(&req, &roster), Err(TeamError::NotAMember));
assert_eq!(verified_members(&[s.clone(), s.clone(), sc], &req, &roster), vec![b.id()]);
}
#[test]
fn member_keys_seal_the_team_key_to_one_member_team_and_epoch() {
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let team = "02".repeat(16);
let key = [7u8; 32];
let sealed = custos_team::member::seal_team_key(&key, &a.public(), &team, 3).unwrap();
assert_eq!(sealed.len(), custos_team::member::SEALED_KEY_LEN);
assert_eq!(*a.open_team_key(&sealed, &team, 3).unwrap(), key);
assert_eq!(a.open_team_key(&sealed, &team, 4), Err(TeamError::NotAMember));
assert_eq!(a.open_team_key(&sealed, &"03".repeat(16), 3), Err(TeamError::NotAMember));
assert_eq!(b.open_team_key(&sealed, &team, 3), Err(TeamError::NotAMember));
// The key round-trips through its secrets; ids and codes are stable.
let again = MemberKey::from_secrets(a.x25519_secret(), a.ed25519_secret()).unwrap();
assert_eq!(again.public(), a.public());
assert_eq!(a.public().join_code(), custos_seal::match_code(&a.public().x25519));
assert_eq!(a.id().len(), 32);
assert_ne!(a.id(), b.id());
assert_eq!(format!("{a:?}"), "[redacted]");
a.public().check().unwrap();
}
#[test]
fn a_proof_verifies_only_for_its_request_signature_policy_and_identity() {
let identity = TeamIdentity::generate();
let team = "04".repeat(16);
let (a, b) = (MemberKey::generate(), MemberKey::generate());
let roster = roster_of(&[&a, &b]);
let policy = Policy::default_for(&team);
let policy_text = policy.canonical();
let fabrica = custos_seal::Recipient::generate();
let req = request(&team, "production", "mnovak", fabrica.public());
let req_text = req.canonical();
let s = approve(&b, &req, &req.match_code(), NOW).unwrap();
let envelope = b"untrusted comment: ...".to_vec();
let body = |approvals: Vec<Statement>, signer: String, role: KeyRole| ProofBody {
team: team.clone(),
request: req.hash_hex(),
env: req.env.clone(),
author: req.author.clone(),
policy: policy_text.clone(),
policy_sig: identity.sign_policy(&policy_text),
roster: roster.clone(),
approvals,
signer,
role,
signature: custos_sign::sha256_hex(&envelope),
at: NOW,
};
let good = body(vec![s.clone()], b.id(), KeyRole::Release).sign(&identity);
assert_eq!(ProofBody::parse(&good.text).unwrap(), body(vec![s.clone()], b.id(), KeyRole::Release));
let v = verify_proof(&good, &identity.public(), &req_text, &envelope).unwrap();
assert_eq!((v.role, v.signer.as_str(), v.approvers.clone()), (KeyRole::Release, b.id().as_str(), vec![b.id()]));
// Another identity, another envelope, another request.
assert_eq!(
verify_proof(&good, &TeamIdentity::generate().public(), &req_text, &envelope),
Err(TeamError::BadSignature)
);
assert!(verify_proof(&good, &identity.public(), &req_text, b"another signature").is_err());
let mut other = req.clone();
other.release = "0.7.1".into();
assert!(verify_proof(&good, &identity.public(), &other.canonical(), &envelope).is_err());
// The author's own approval does not make a production proof.
let sa = approve(&a, &req, &req.match_code(), NOW).unwrap();
let selfish = body(vec![sa], a.id(), KeyRole::Release).sign(&identity);
assert_eq!(verify_proof(&selfish, &identity.public(), &req_text, &envelope), Err(TeamError::NeedMore(1)));
// A proof claiming the test role for production, or signed by someone who did not approve.
let wrong_role = body(vec![s.clone()], b.id(), KeyRole::Test).sign(&identity);
assert!(verify_proof(&wrong_role, &identity.public(), &req_text, &envelope).is_err());
let not_approver = body(vec![s.clone()], a.id(), KeyRole::Release).sign(&identity);
assert!(verify_proof(&not_approver, &identity.public(), &req_text, &envelope).is_err());
// An edited text breaks the identity's signature.
let mut edited = good.clone();
edited.text = edited.text.replace("\"production\"", "\"staging\"");
assert_eq!(verify_proof(&edited, &identity.public(), &req_text, &envelope), Err(TeamError::BadSignature));
}
+3
View File
@@ -22,9 +22,12 @@ bip39 = { version = "2", default-features = false, features = ["std", "zeroize"]
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
# Signing keys for releases (docs/SIGNING.md).
custos-sign = { path = "../custos-sign" }
# Team vaults (docs/TEAM.md, core 0.18.0).
custos-team = { path = "../custos-team" }
[dev-dependencies]
tempfile = "3"
custos-seal = { path = "../custos-seal" }
minisign-verify = "0.3"
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
+124
View File
@@ -15,6 +15,15 @@ pub const SLOT_PASSWORD: u8 = 1;
pub const SLOT_FACTOR: u8 = 2;
pub const SLOT_PAIR: u8 = 3;
pub const SLOT_SINGLE: u8 = 4;
/// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key").
pub const SLOT_RECOVERY: u8 = 5;
pub const RECOVERY_ID_LEN: usize = 4;
/// A team vault's member slot (core 0.18.0; docs/TEAM.md): the team key sealed to one member.
pub const SLOT_MEMBER: u8 = 6;
/// team id (16) ‖ member id (16) ‖ epoch (4) ‖ sealed team key (108).
pub const MEMBER_SLOT_LEN: usize = 16 + 16 + 4 + 108;
/// A team has at most this many members.
pub const MAX_MEMBER_SLOTS: usize = 32;
const KDF_ARGON2ID: u8 = 1;
pub const SALT_LEN: usize = 32;
pub const ID_LEN: usize = 16;
@@ -244,6 +253,80 @@ impl SingleSlot {
}
}
/// The recovery slot (kind 5): the vault key, wrapped by the recovery key alone. At most one, never in a machine
/// store. `id` says which printed key it is and is not secret.
pub struct RecoverySlot {
pub id: [u8; RECOVERY_ID_LEN],
pub salt: [u8; SALT_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl RecoverySlot {
fn head(&self) -> Vec<u8> {
let mut h = Vec::with_capacity(RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN);
h.extend_from_slice(&self.id);
h.extend_from_slice(&self.salt);
h.extend_from_slice(&self.nonce);
h
}
pub fn aad(&self) -> Vec<u8> {
v2_aad(SLOT_RECOVERY, &self.head())
}
pub fn raw(&self) -> RawSlot {
let mut p = self.head();
p.extend_from_slice(&self.wrapped);
RawSlot { kind: SLOT_RECOVERY, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
const HEAD: usize = RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN;
if payload.len() != HEAD + WRAPPED_LEN {
return Err(Error::Malformed);
}
Ok(RecoverySlot {
id: payload[..RECOVERY_ID_LEN].try_into().unwrap(),
salt: payload[RECOVERY_ID_LEN..RECOVERY_ID_LEN + SALT_LEN].try_into().unwrap(),
nonce: payload[RECOVERY_ID_LEN + SALT_LEN..HEAD].try_into().unwrap(),
wrapped: payload[HEAD..].to_vec(),
})
}
}
/// A team vault's member slot (kind 6): the box carries its own binding (its context names team, epoch and member).
#[derive(Clone)]
pub struct MemberSlot {
pub team: [u8; ID_LEN],
pub member: [u8; ID_LEN],
pub epoch: u32,
pub sealed: Vec<u8>,
}
impl MemberSlot {
pub fn raw(&self) -> RawSlot {
let mut p = Vec::with_capacity(MEMBER_SLOT_LEN);
p.extend_from_slice(&self.team);
p.extend_from_slice(&self.member);
p.extend_from_slice(&self.epoch.to_le_bytes());
p.extend_from_slice(&self.sealed);
RawSlot { kind: SLOT_MEMBER, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != MEMBER_SLOT_LEN {
return Err(Error::Malformed);
}
Ok(MemberSlot {
team: payload[..16].try_into().unwrap(),
member: payload[16..32].try_into().unwrap(),
epoch: u32::from_le_bytes(payload[32..36].try_into().unwrap()),
sealed: payload[36..].to_vec(),
})
}
}
pub struct Header {
pub version: u16,
pub slots: Vec<RawSlot>,
@@ -303,6 +386,9 @@ impl Header {
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
fn check_v2(&self) -> Result<(), Error> {
if self.slots.iter().any(|s| s.kind == SLOT_MEMBER) {
return self.check_team();
}
let mut ids = Vec::new();
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
ids.push(FactorSlot::parse(&s.payload)?.id);
@@ -317,6 +403,7 @@ impl Header {
return Err(Error::Malformed);
}
let mut singles = 0;
let mut recoveries = 0;
for s in &self.slots {
match s.kind {
SLOT_FACTOR => {}
@@ -333,6 +420,10 @@ impl Header {
}
singles += 1;
}
SLOT_RECOVERY => {
RecoverySlot::parse(&s.payload)?;
recoveries += 1;
}
// A v1 password slot, or an unknown kind, has no place in a v2 header.
_ => return Err(Error::Malformed),
}
@@ -341,9 +432,38 @@ impl Header {
if singles > 0 && (singles != 1 || ids.len() != 1) {
return Err(Error::Malformed);
}
// One recovery key at most, and none for a vault that opens by itself.
if recoveries > 1 || (recoveries == 1 && singles > 0) {
return Err(Error::Malformed);
}
Ok(())
}
/// A team vault (docs/TEAM.md): 1 ..= 32 member slots and nothing else, one team id and epoch, distinct members.
fn check_team(&self) -> Result<(), Error> {
if self.slots.len() > MAX_MEMBER_SLOTS || self.slots.iter().any(|s| s.kind != SLOT_MEMBER) {
return Err(Error::Malformed);
}
let slots = self.slots.iter().map(|s| MemberSlot::parse(&s.payload)).collect::<Result<Vec<_>, _>>()?;
let first = &slots[0];
let mut members: Vec<[u8; ID_LEN]> = Vec::with_capacity(slots.len());
for s in &slots {
if s.team != first.team || s.epoch != first.epoch || members.contains(&s.member) {
return Err(Error::Malformed);
}
members.push(s.member);
}
Ok(())
}
pub fn is_team(&self) -> bool {
self.slots.iter().any(|s| s.kind == SLOT_MEMBER)
}
pub fn member_slots(&self) -> Vec<MemberSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_MEMBER).filter_map(|s| MemberSlot::parse(&s.payload).ok()).collect()
}
pub fn factor_slots(&self) -> Vec<FactorSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
}
@@ -356,6 +476,10 @@ impl Header {
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
}
pub fn recovery_slot(&self) -> Option<RecoverySlot> {
self.slots.iter().find(|s| s.kind == SLOT_RECOVERY).and_then(|s| RecoverySlot::parse(&s.payload).ok())
}
pub fn is_machine_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == SLOT_SINGLE)
}
+181
View File
@@ -22,14 +22,21 @@ mod format;
pub mod identity;
mod item;
pub mod provision;
mod recovery;
mod save;
mod secret;
pub mod security;
pub mod signing;
pub mod team;
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use recovery::RecoveryKey;
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::{SecretBytes, SecretString};
pub use team::{
KnownTeam, NewSigner, NewTarget, Removal, RemovedMember, SignerView, TargetView, TeamAction, TeamAuditEntry,
TeamMember, TeamView,
};
use crypto::KEY_LEN;
use format::{
@@ -63,6 +70,12 @@ pub enum Error {
FactorRejected,
#[error("these two factors are kept on the same device; use one of them with another factor")]
SameDevice,
#[error("this is not a recovery key as Custos prints it: check each group of characters")]
RecoveryKeyMistyped,
#[error("this recovery key does not open this vault: it is another vault's, or an older one that was replaced")]
WrongRecoveryKey,
#[error("this vault has no recovery key")]
NoRecoveryKey,
#[error("a vault has at most 8 factors and one master password")]
TooManyFactors,
#[error("this vault has no Domi identity yet")]
@@ -89,6 +102,15 @@ pub enum Error {
Security(&'static str),
#[error("signing keys: {0}")]
Signing(String),
/// A team vault operation was refused (docs/TEAM.md); names why, never a value.
#[error("team: {0}")]
Team(String),
#[error("this is not a team vault")]
NotATeam,
#[error("this member key does not open this team vault: not a member, or removed")]
NotAMember,
#[error("this team vault is older than the one this member has seen, or another team's under the same id")]
TeamRollback,
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -271,6 +293,7 @@ const BODY_FORMAT_2: u32 = 2;
const INFO_FACTOR: &[u8] = b"custos factor v2";
const INFO_PAIR: &[u8] = b"custos pair v2";
const INFO_SINGLE: &[u8] = b"custos single v2";
const INFO_RECOVERY: &[u8] = b"custos recovery v2";
#[derive(Deserialize)]
struct Body {
@@ -286,6 +309,14 @@ struct Body {
provision: Option<provision::ProvisionJson>,
#[serde(default)]
security: Option<security::State>,
/// `"team"` for a team vault (core 0.18.0, docs/TEAM.md).
#[serde(default)]
kind: Option<String>,
#[serde(default)]
team: Option<team::TeamJson>,
/// A person's member key (core 0.18.0).
#[serde(default)]
member: Option<team::MemberJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -303,6 +334,12 @@ struct BodyRef<'a> {
provision: Option<provision::ProvisionJson>,
#[serde(skip_serializing_if = "Option::is_none")]
security: Option<security::State>,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
team: Option<team::TeamJson>,
#[serde(skip_serializing_if = "Option::is_none")]
member: Option<team::MemberJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
@@ -323,6 +360,10 @@ pub struct Vault {
provision: Vec<provision::ProvisionEntry>,
/// The security level's Setup window, the checklist and their audit (docs/FORMAT.md).
security: security::State,
/// A team vault's own state (docs/TEAM.md); `None` for every other vault.
team: Option<team::TeamState>,
/// A person's member key and the teams it has opened (docs/TEAM.md); never in a team vault.
member: Option<team::MemberState>,
}
impl fmt::Debug for Vault {
@@ -410,6 +451,24 @@ fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
}
impl Vault {
/// An empty version-2 vault with `key` and no slots yet: a team vault writes its member slots itself.
pub(crate) fn empty_v2(key: Zeroizing<[u8; KEY_LEN]>) -> Vault {
Vault {
key,
version: VERSION_2,
slots: Vec::new(),
items: Vec::new(),
factors: Vec::new(),
kdf_new: KdfParams::DEFAULT,
identity: None,
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
}
}
/// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
let key = crypto::random_key();
@@ -425,6 +484,8 @@ impl Vault {
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
})
}
@@ -444,6 +505,8 @@ impl Vault {
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
@@ -479,6 +542,8 @@ impl Vault {
signing: signing::Store::default(),
provision: Vec::new(),
security: security::State::default(),
team: None,
member: None,
})
}
@@ -605,6 +670,17 @@ impl Vault {
None => signing::Store::default(),
};
let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?;
// A team vault (member slots) has a team body and nothing of a person's; every other vault has none.
let team = match (header.is_team(), body.kind.as_deref(), body.team) {
(true, Some("team"), Some(j)) => Some(team::TeamState::from_json(j).ok_or(Error::Corrupted)?),
(false, None, None) => None,
_ => return Err(Error::Corrupted),
};
let member = match body.member {
Some(_) if team.is_some() => return Err(Error::Corrupted),
Some(j) => Some(team::MemberState::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
Ok(Vault {
key,
version: header.version,
@@ -616,6 +692,8 @@ impl Vault {
signing,
provision: provision::from_json(body.provision),
security,
team,
member,
})
}
@@ -653,6 +731,9 @@ impl Vault {
signing: self.signing.json(),
provision: provision::json(&self.provision),
security: self.security.json(),
kind: self.team.is_some().then_some("team"),
team: self.team.as_ref().map(team::TeamState::json),
member: self.member.as_ref().map(team::MemberState::json),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
@@ -721,6 +802,106 @@ impl Vault {
}
}
// ---- the recovery key (docs/FACTORS.md, "The recovery key") ----
/// Which recovery key a vault file has (its id, 8 hex characters), from the header alone.
pub fn recovery_id_of(bytes: &[u8]) -> Result<Option<String>, Error> {
Ok(Header::parse(bytes)?.0.recovery_slot().map(|s| recovery::id_hex(&s.id)))
}
/// Which recovery key this vault has.
pub fn recovery_id(&self) -> Option<String> {
self.slots
.iter()
.find(|s| s.kind == format::SLOT_RECOVERY)
.and_then(|s| format::RecoverySlot::parse(&s.payload).ok())
.map(|s| recovery::id_hex(&s.id))
}
fn recovery_put(&mut self) -> RecoveryKey {
let mut id = [0u8; recovery::ID_LEN];
crypto::fill_random(&mut id);
let material = crypto::random_key();
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = format::RecoverySlot { id, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
slot.wrapped = crypto::seal(&kek, &slot.nonce, self.key.as_ref(), &slot.aad());
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
self.slots.push(slot.raw());
recovery::encode(&id, &material)
}
/// Makes the vault's recovery key and returns it, once: it is in no file and no log, so what the caller does
/// not show or print is lost. A key the vault already had stops working. Only a two-factor vault has one
/// (not version 1, not a machine-key vault). The caller saves.
pub fn recovery_create(&mut self, now: i64) -> Result<RecoveryKey, Error> {
if self.version != VERSION_2 {
return Err(Error::NeedTwoFactors);
}
if self.is_store() {
return Err(Error::FactorRejected);
}
let key = self.recovery_put();
self.security.recovery_note(security::Action::RecoveryCreated, key.id(), now);
Ok(key)
}
/// Removes the recovery key: from the next save on, only the factors open the vault. The caller saves.
pub fn recovery_remove(&mut self, now: i64) -> Result<(), Error> {
let id = self.recovery_id().ok_or(Error::NoRecoveryKey)?;
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
self.security.recovery_note(security::Action::RecoveryRemoved, &id, now);
Ok(())
}
/// Opens a vault with its recovery key and, before handing it back, replaces what opened it until now: every
/// factor is dropped, `new_password` and `second` (anything but a password) become its two factors, and the
/// used recovery key is replaced by the new one returned here. The items and everything else stay. Nothing is
/// written: the caller saves, and until it does the file is as it was.
///
/// This is the only call that takes a recovery key, so the key is never an everyday unlock.
pub fn recover(
bytes: &[u8],
key: &SecretString,
new_password: &SecretString,
kdf: KdfParams,
second: Unlock,
label: &str,
now: i64,
) -> Result<(Vault, RecoveryKey), Error> {
// What was typed is checked first: a typing mistake is not a wrong key.
let (id, material) = recovery::decode(key)?;
if second.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
second.check()?;
if new_password.expose().is_empty() {
return Err(Error::WrongPassword);
}
kdf.check()?;
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 {
return Err(Error::NoRecoveryKey);
}
let slot = header.recovery_slot().ok_or(Error::NoRecoveryKey)?;
if slot.id != id {
return Err(Error::WrongRecoveryKey);
}
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
let k = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::WrongRecoveryKey)?;
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
// Whoever held the old factors holds nothing of this vault from the next save on.
v.slots.clear();
v.factors.clear();
v.kdf_new = kdf;
v.add_factor(Unlock::Password(new_password), "Master password")?;
v.add_factor(second, label)?;
let new_key = v.recovery_put();
v.security.recovery_note(security::Action::Recovered, &recovery::id_hex(&id), now);
Ok((v, new_key))
}
fn is_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
}
+150
View File
@@ -0,0 +1,150 @@
//! The recovery key (docs/FACTORS.md, "The recovery key"): one long random key per vault that opens it alone, for
//! the day the factors are gone. It is printed once and kept on paper. It is never an everyday unlock:
//! [`crate::Vault::recover`] is the only call that takes it, and it replaces every factor before it returns.
use crate::Error;
use crate::secret::SecretString;
use data_encoding::BASE32_NOPAD;
use sha2::{Digest, Sha256};
use std::fmt;
use zeroize::Zeroizing;
pub(crate) const ID_LEN: usize = 4;
pub(crate) const MATERIAL_LEN: usize = 32;
const CHECK_LEN: usize = 4;
const CHECK_CONTEXT: &[u8] = b"custos recovery key v1";
/// 40 bytes as base32: 64 characters, written as 8 groups of 8.
const TEXT_LEN: usize = 64;
const GROUP: usize = 8;
/// A recovery key as it is printed. `Debug` never shows it.
pub struct RecoveryKey {
id: String,
text: Zeroizing<String>,
}
impl RecoveryKey {
/// Which key this is (8 hex characters): not secret, shown in Settings and printed next to the key.
pub fn id(&self) -> &str {
&self.id
}
/// The key: 8 groups of 8 characters, `A-Z` and `2-7`.
pub fn expose(&self) -> &str {
&self.text
}
}
impl fmt::Debug for RecoveryKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RecoveryKey({}, [redacted])", self.id)
}
}
pub(crate) fn id_hex(id: &[u8; ID_LEN]) -> String {
id.iter().map(|b| format!("{b:02x}")).collect()
}
fn check(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> [u8; CHECK_LEN] {
let mut h = Sha256::new();
h.update(CHECK_CONTEXT);
h.update(id);
h.update(material);
let d = h.finalize();
[d[0], d[1], d[2], d[3]]
}
pub(crate) fn encode(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> RecoveryKey {
let mut raw = Zeroizing::new([0u8; ID_LEN + MATERIAL_LEN + CHECK_LEN]);
raw[..ID_LEN].copy_from_slice(id);
raw[ID_LEN..ID_LEN + MATERIAL_LEN].copy_from_slice(material);
raw[ID_LEN + MATERIAL_LEN..].copy_from_slice(&check(id, material));
let flat = Zeroizing::new(BASE32_NOPAD.encode(raw.as_ref()));
let mut text = Zeroizing::new(String::with_capacity(TEXT_LEN + TEXT_LEN / GROUP));
for (i, c) in flat.chars().enumerate() {
if i > 0 && i % GROUP == 0 {
text.push('-');
}
text.push(c);
}
RecoveryKey { id: id_hex(id), text }
}
/// The id and the material of a typed key. Case, spaces and hyphens do not matter; a key that is too short, too
/// long, has another character or fails its check is `RecoveryKeyMistyped`, before any vault is touched.
pub(crate) fn decode(text: &SecretString) -> Result<([u8; ID_LEN], Zeroizing<[u8; MATERIAL_LEN]>), Error> {
let mut flat = Zeroizing::new(String::with_capacity(TEXT_LEN));
for c in text.expose().chars() {
match c {
' ' | '-' | '\t' | '\r' | '\n' => {}
c if c.is_ascii_alphanumeric() && flat.len() < TEXT_LEN + 1 => flat.push(c.to_ascii_uppercase()),
_ => return Err(Error::RecoveryKeyMistyped),
}
}
if flat.len() != TEXT_LEN {
return Err(Error::RecoveryKeyMistyped);
}
let raw = Zeroizing::new(BASE32_NOPAD.decode(flat.as_bytes()).map_err(|_| Error::RecoveryKeyMistyped)?);
if raw.len() != ID_LEN + MATERIAL_LEN + CHECK_LEN {
return Err(Error::RecoveryKeyMistyped);
}
let id: [u8; ID_LEN] = raw[..ID_LEN].try_into().expect("checked");
let mut material = Zeroizing::new([0u8; MATERIAL_LEN]);
material.copy_from_slice(&raw[ID_LEN..ID_LEN + MATERIAL_LEN]);
if raw[ID_LEN + MATERIAL_LEN..] != check(&id, &material) {
return Err(Error::RecoveryKeyMistyped);
}
Ok((id, material))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_printed_key_reads_back_however_it_is_typed() {
let key = encode(&[0xa1, 0xb2, 0xc3, 0xd4], &[9; 32]);
assert_eq!(key.id(), "a1b2c3d4");
let text = key.expose().to_owned();
assert_eq!(text.len(), 64 + 7);
assert!(
text.split('-')
.all(|g| g.len() == 8 && g.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
);
for typed in
[text.clone(), text.to_lowercase(), text.replace('-', " "), text.replace('-', ""), format!(" {text}\r\n")]
{
let (id, material) = decode(&SecretString::from(typed.as_str())).unwrap();
assert_eq!((id, *material), ([0xa1, 0xb2, 0xc3, 0xd4], [9; 32]));
}
assert_eq!(format!("{key:?}"), "RecoveryKey(a1b2c3d4, [redacted])");
}
#[test]
fn a_mistyped_key_is_told_apart_before_any_vault_is_touched() {
let text = encode(&[1, 2, 3, 4], &[9; 32]).expose().to_owned();
let mistyped = |s: String| matches!(decode(&SecretString::from(s.as_str())), Err(Error::RecoveryKeyMistyped));
// One character changed, anywhere: the check catches it.
for at in [0usize, 7, 40, 70] {
let mut chars: Vec<char> = text.chars().collect();
if chars[at] == '-' {
continue;
}
chars[at] = if chars[at] == 'A' { 'B' } else { 'A' };
assert!(mistyped(chars.into_iter().collect()), "position {at}");
}
// Two groups swapped, a group missing, one too many, a character that is never in a key.
let groups: Vec<&str> = text.split('-').collect();
let mut swapped = groups.clone();
swapped.swap(2, 6);
if swapped != groups {
assert!(mistyped(swapped.join("-")));
}
assert!(mistyped(groups[1..].join("-")));
assert!(mistyped(format!("{text}-AAAAAAAA")));
assert!(mistyped(text.replacen(|c: char| c != '-', "1", 1)));
assert!(mistyped(text.replacen('-', "_", 1)));
assert!(mistyped(String::new()));
assert!(mistyped("A".repeat(100_000)));
}
}
+160
View File
@@ -77,6 +77,19 @@ pub enum Action {
UnattendedSigned,
/// *Take over the vault*: a master password added, the PC-only access removed.
TakenOver,
/// A standing approval was granted on a card (core 0.16.0; `detail`: the rule's repository, key, kind, pipeline
/// and origin). Written by [`Vault::standing_grant`] only.
StandingGranted,
/// A standing approval was revoked (`detail`: the same). Written by [`Vault::standing_revoke`] only.
StandingRevoked,
/// A recovery key was made (core 0.17.0; `detail`: the key's id, never the key). Written by
/// [`Vault::recovery_create`] only.
RecoveryCreated,
/// The recovery key was removed (`detail`: its id). Written by [`Vault::recovery_remove`] only.
RecoveryRemoved,
/// The vault was opened with its recovery key: every factor and the key were replaced (`detail`: the used
/// key's id). Written by [`Vault::recover`] only.
Recovered,
}
/// What *Connect via SSH* needs.
@@ -232,6 +245,28 @@ impl State {
trim(&mut self.audit);
}
/// Whether a checklist item is ticked.
pub(crate) fn is_ticked(&self, item: Item) -> bool {
self.ticked.contains(&item)
}
/// `standing-granted` or `standing-revoked`, with the rule as its detail (cut to what a note may hold).
pub(crate) fn standing_note(&mut self, action: Action, detail: &str, now: i64) {
debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked));
let detail: String = detail.chars().filter(|c| !c.is_control()).take(500).collect();
self.notice_expiry(now);
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail) });
trim(&mut self.audit);
}
/// `recovery-created`, `recovery-removed` or `recovered`, with the key's id as its detail.
pub(crate) fn recovery_note(&mut self, action: Action, id: &str, now: i64) {
debug_assert!(matches!(action, Action::RecoveryCreated | Action::RecoveryRemoved | Action::Recovered));
self.notice_expiry(now);
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(id.to_owned()) });
trim(&mut self.audit);
}
/// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and
/// `finished` = `until`.
fn notice_expiry(&mut self, now: i64) {
@@ -724,6 +759,131 @@ mod tests {
}
}
/// A vault whose release key has signed once and has one standing approval, used once (core 0.16.0).
fn vault_with_a_standing_approval() -> Vault {
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
let mut v = vault();
v.signing_create(Role::Release, &["release".to_string()], &["Arca".to_string()], NOW).unwrap();
let r = Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-42".into()),
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
};
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
v.standing_grant(&r, NOW + 1).unwrap();
v.signing_sign(&r, Approval::Standing, NOW + 2).unwrap();
v
}
#[test]
fn an_older_reader_refuses_a_vault_in_which_a_standing_approval_was_granted() {
let v = vault_with_a_standing_approval();
let json = body_json(&v);
assert!(json.contains(r#""standing":[{"id":""#) && json.contains(r#""outcome":"standing""#), "{json}");
assert!(json.contains(r#""action":"standing-granted""#), "{json}");
// Core 0.11.0 does not know the outcome or the action: it refuses the file rather than misread it.
assert!(serde_json::from_str::<BodyV0_11>(&json).is_err());
// The rules alone it would ignore: with the outcome it knows, its signing parser takes the member.
let plain = json.replace(r#""outcome":"standing""#, r#""outcome":"approved""#);
let body: serde_json::Value = serde_json::from_str(&plain).unwrap();
let old: SigningV0_11 = serde_json::from_value(body["signing"].clone()).unwrap();
assert_eq!(old.audit.len(), 2);
// This core reads it back the same.
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.standing_rules(), v.standing_rules());
assert_eq!(back.standing_rules()[0].uses, 1);
}
#[test]
fn a_rule_whose_count_is_at_its_end_still_signs() {
use crate::signing::{Approval, Context, Request, SignKind, Via};
let v = vault_with_a_standing_approval();
let json = body_json(&v).replace(r#""uses":1"#, r#""uses":18446744073709551615"#);
let mut full = Vault::open(&with_body(&v, &json), &SecretString::from("pw")).unwrap();
let r = Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![1; 64],
manifest: None,
approval: None,
run: Some("r-43".into()),
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
};
full.signing_sign(&r, Approval::Standing, NOW + 9).expect("signed, not a panic");
assert_eq!(full.standing_rules()[0].uses, u64::MAX);
}
#[test]
fn a_broken_android_grant_makes_the_vault_refuse_to_open() {
let mut v = vault();
v.android_grant_set(&["mnovak/*".to_string()], "Marek Novak", "CZ", NOW).unwrap();
let json = body_json(&v);
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let from = r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ""#;
assert!(json.contains(from), "{json}");
for to in [
r#""repos":["*/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":[],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*","mnovak/*"],"o":"Marek Novak","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"","c":"CZ""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"Czech""#,
r#""repos":["mnovak/*"],"o":"Marek Novak","c":"CZ","made":["Not An Id"]"#,
] {
let bad = json.replacen(from, to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
}
#[test]
fn a_broken_standing_approval_makes_the_vault_refuse_to_open() {
let v = vault_with_a_standing_approval();
let json = body_json(&v);
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
let id = v.standing_rules()[0].id.clone();
let shape = r#""kind":"minisign","pipeline":"release","via":"local""#;
let cases = [
// A rule edited to name another repository, pipeline, kind or origin no longer has its id.
(
r#""repo":"Arca","key":"domi-release","keyCreated""#.to_string(),
r#""repo":"Fabrica","key":"domi-release","keyCreated""#.to_string(),
),
(shape.to_string(), r#""kind":"minisign","pipeline":"deploy","via":"local""#.to_string()),
(shape.to_string(), r#""kind":"apk","pipeline":"release","via":"local""#.to_string()),
(shape.to_string(), r#""kind":"minisign","pipeline":"release","via":"remote""#.to_string()),
(shape.to_string(), r#""kind":"sigstore","pipeline":"release","via":"local""#.to_string()),
(format!(r#""id":"{id}""#), r#""id":"0000000000000000""#.to_string()),
// Targets belong to approvals only.
(
r#""via":"local","granted""#.to_string(),
r#""via":"local","targets":["deploy to nixos-vm"],"granted""#.to_string(),
),
];
for (from, to) in cases {
assert!(json.contains(&from), "{from} in {json}");
let bad = json.replacen(&from, &to, 1);
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
}
}
#[test]
fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() {
let mut v = vault();
+662 -32
View File
@@ -49,6 +49,10 @@ pub enum KeyKind {
Ed25519,
RootCa,
CodeSigning,
/// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only.
Android,
/// A team's cosign key (core 0.18.0, docs/TEAM.md): ECDSA P-256; signs `cosign` only, in a team vault only.
EcdsaP256,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -59,6 +63,15 @@ pub enum SignKind {
Authenticode,
/// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0).
Approval,
/// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only
/// (core 0.14.0).
Apk,
/// Tauri's updater: minisign over a BLAKE2b-512 digest, wrapped in base64 (core 0.18.0, team vaults only).
#[serde(rename = "tauri-updater")]
TauriUpdater,
/// A cosign container image signature: ECDSA P-256 over the simple-signing payload (core 0.18.0, team vaults
/// only).
Cosign,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -92,7 +105,8 @@ pub struct Context {
pub struct Request {
pub key: String,
pub kind: SignKind,
/// BLAKE2b-512 of the file (minisign) or signtool's 32-byte digest (authenticode). Empty for a manifest.
/// BLAKE2b-512 of the file (minisign), signtool's 32-byte digest (authenticode), or 1 to 4 SHA-512 digests of
/// an APK's signed data, concatenated (apk). Empty for a manifest or an approval.
pub digest: Vec<u8>,
/// The `SHA256SUMS` text, for a manifest.
pub manifest: Option<String>,
@@ -110,12 +124,16 @@ pub enum Approval {
Mark,
/// Nobody was asked: allowed for test keys only.
Auto,
/// Nobody was asked: a standing approval Mark granted fits the request (core 0.16.0). Refused when none does.
Standing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
Approved,
/// Signed without asking: a standing approval fitted (core 0.16.0).
Standing,
Auto,
Refused,
Expired,
@@ -143,12 +161,82 @@ pub struct AuditEntry {
/// The request's run id (core 0.12.0), when it had a well-formed one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
/// A team vault's entry (core 0.18.0, docs/TEAM.md): the member whose Custos signed or refused.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by: Option<String>,
/// The environment the request was for.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub env: Option<String>,
/// The request hash (hex).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request: Option<String>,
/// The members whose approvals counted.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub approvers: Vec<String>,
}
/// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used.
/// Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StandingRule {
/// 16 hex characters: the SHA-256 of repo, key, kind, pipeline and via, joined by newlines, cut short.
pub id: String,
pub repo: String,
pub key: String,
/// The key's `created`: a key made later under the same id does not inherit the rule.
pub key_created: i64,
pub kind: SignKind,
pub pipeline: String,
pub via: Via,
/// For an approval: the deploy targets the rule was granted for.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<String>,
/// Unix milliseconds.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
}
/// At most this many standing approvals in a vault.
pub const STANDING_MAX: usize = 256;
/// The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): Mark's one answer for every Domi app's
/// release APK. It signs an app key's APKs from this PC's pipe, its first signature included, and makes the key when
/// the app's first release asks. Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AndroidGrant {
/// `owner/name` or `owner/*`, 1 to [`ANDROID_PATTERNS_MAX`].
pub repos: Vec<String>,
/// The organisation and country in the certificates of the keys it makes.
pub o: String,
pub c: String,
/// Unix milliseconds: when Mark granted it, or last changed it.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
/// The ids of the keys it made, oldest first.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub made: Vec<String>,
}
/// The one pipeline the Android grant covers.
pub const ANDROID_PIPELINE: &str = "release";
/// At most this many repository patterns in the Android grant.
pub const ANDROID_PATTERNS_MAX: usize = 64;
/// At most this many keys the Android grant remembers making.
const ANDROID_MADE_MAX: usize = 256;
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
/// The `.minisig` text (minisign, manifest) or the raw RSA signature (authenticode).
/// The `.minisig` text (minisign, manifest, approval), the raw RSA signature (authenticode) or the raw RSA
/// signatures, concatenated in the order of the digests (apk).
pub bytes: Vec<u8>,
pub sha256: String,
}
@@ -170,29 +258,32 @@ pub struct KeyView {
pub key_id: Option<String>,
/// The `minisign.pub` text, for Ed25519 keys.
pub minisign_public: Option<String>,
/// The certificate (DER), for root and code-signing keys.
/// The certificate (DER), for root, code-signing and Android keys.
pub cert: Option<Vec<u8>>,
pub issuer: Option<String>,
/// The `cosign.pub` PEM, for ECDSA P-256 keys (core 0.18.0).
pub public_pem: Option<String>,
}
enum Secret {
pub(crate) enum Secret {
Ed25519(Ed25519Secret),
Rsa(RsaSecret),
P256(custos_sign::P256Secret),
}
struct Key {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: Secret,
public: Option<[u8; 32]>,
key_id: Option<[u8; 8]>,
cert: Option<Vec<u8>>,
issuer: Option<String>,
created: i64,
pipelines: Vec<String>,
repos: Vec<String>,
pub(crate) struct Key {
pub(crate) id: String,
pub(crate) kind: KeyKind,
pub(crate) role: Role,
pub(crate) name: String,
pub(crate) secret: Secret,
pub(crate) public: Option<[u8; 32]>,
pub(crate) key_id: Option<[u8; 8]>,
pub(crate) cert: Option<Vec<u8>>,
pub(crate) issuer: Option<String>,
pub(crate) created: i64,
pub(crate) pipelines: Vec<String>,
pub(crate) repos: Vec<String>,
}
impl fmt::Debug for Key {
@@ -204,8 +295,10 @@ impl fmt::Debug for Key {
/// The keys and the log, in the vault.
#[derive(Debug, Default)]
pub(crate) struct Store {
keys: Vec<Key>,
audit: Vec<AuditEntry>,
pub(crate) keys: Vec<Key>,
pub(crate) audit: Vec<AuditEntry>,
standing: Vec<StandingRule>,
android: Option<AndroidGrant>,
}
#[derive(Serialize, Deserialize)]
@@ -237,6 +330,12 @@ pub(crate) struct StoreJson {
keys: Vec<KeyJson>,
#[serde(default)]
audit: Vec<AuditEntry>,
/// Standing approvals (core 0.16.0); absent while there are none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
standing: Vec<StandingRule>,
/// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it.
#[serde(default, skip_serializing_if = "Option::is_none")]
android: Option<AndroidGrant>,
}
fn b64(bytes: &[u8]) -> String {
@@ -264,7 +363,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty()
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
@@ -275,9 +374,13 @@ impl Store {
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
}
KeyKind::RootCa | KeyKind::CodeSigning => {
KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => {
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
}
KeyKind::EcdsaP256 => {
let scalar: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::P256(custos_sign::P256Secret::from_bytes(scalar).ok()?)
}
};
let public = match &k.public {
Some(p) => Some(unb64(p)?.try_into().ok()?),
@@ -297,6 +400,10 @@ impl Store {
Some(c) => Some(unb64(c)?),
None => None,
};
// An Android key is nothing without its certificate: the app is identified by it forever.
if k.kind == KeyKind::Android && cert.is_none() {
return None;
}
keys.push(Key {
id: k.id,
kind: k.kind,
@@ -312,7 +419,13 @@ impl Store {
repos: k.repos,
});
}
Some(Store { keys, audit: j.audit })
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
return None;
}
if j.android.as_ref().is_some_and(|g| !grant_ok(g)) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
@@ -330,6 +443,7 @@ impl Store {
secret: SecretBytes::new(match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
Secret::P256(s) => s.expose().to_vec(),
}),
public: k.public.map(|p| b64(&p)),
key_id: k.key_id.map(|i| hex(&i)),
@@ -340,16 +454,21 @@ impl Store {
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone() })
Some(StoreJson {
keys,
audit: self.audit.clone(),
standing: self.standing.clone(),
android: self.android.clone(),
})
}
fn get(&self, id: &str) -> Option<&Key> {
pub(crate) fn get(&self, id: &str) -> Option<&Key> {
self.keys.iter().find(|k| k.id == id)
}
}
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
fn seconds(now_ms: i64) -> u64 {
pub(crate) fn seconds(now_ms: i64) -> u64 {
(now_ms.max(0) / 1000) as u64
}
@@ -372,6 +491,128 @@ fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
}
}
/// What [`Vault::signing_create_android`] makes: the key's id and name, the certificate's subject, its role and
/// who may ask. The key is RSA-4096 and the certificate is valid [`custos_sign::ANDROID_YEARS`] years.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AndroidKey {
/// `[a-z0-9-]{1,64}`, e.g. `postea-android`; not the id of a key the vault has.
pub id: String,
pub name: String,
/// The certificate's subject: common name, organisation, two-letter country code.
pub cn: String,
pub o: String,
pub c: String,
pub role: Role,
pub pipelines: Vec<String>,
pub repos: Vec<String>,
}
/// A name in a rule: 1 to 100 characters, no control characters (as a key's scope lists hold them).
fn name_ok(x: &str) -> bool {
(1..=100).contains(&x.chars().count()) && !x.chars().any(char::is_control)
}
fn kind_word(kind: SignKind) -> &'static str {
match kind {
SignKind::Minisign => "minisign",
SignKind::Manifest => "manifest",
SignKind::Authenticode => "authenticode",
SignKind::Approval => "approval",
SignKind::Apk => "apk",
SignKind::TauriUpdater => "tauri-updater",
SignKind::Cosign => "cosign",
}
}
fn via_word(via: Via) -> &'static str {
match via {
Via::Local => "local",
Via::Remote => "remote",
}
}
/// A rule's id: one per repository, key, kind, pipeline and origin.
fn rule_id(repo: &str, key: &str, kind: SignKind, pipeline: &str, via: Via) -> String {
let joined = [repo, key, kind_word(kind), pipeline, via_word(via)].join("\n");
custos_sign::sha256_hex(joined.as_bytes())[..16].to_string()
}
/// A stored rule is what [`Vault::standing_grant`] could have written; anything else makes the vault refuse to open.
fn rule_ok(r: &StandingRule) -> bool {
r.id == rule_id(&r.repo, &r.key, r.kind, &r.pipeline, r.via)
&& name_ok(&r.repo)
&& name_ok(&r.pipeline)
&& (1..=64).contains(&r.key.len())
&& (r.via == Via::Local || r.kind == SignKind::Approval)
&& (r.kind == SignKind::Approval) == !r.targets.is_empty()
&& r.targets.len() <= 64
&& r.targets.iter().all(|t| (1..=80).contains(&t.chars().count()) && !t.chars().any(char::is_control))
}
/// What a rule says, for the security audit: names only.
fn rule_words(r: &StandingRule) -> String {
let targets = if r.targets.is_empty() { String::new() } else { format!(" ({} targets)", r.targets.len()) };
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
}
/// `owner/name`, each 1 to 64 of `A-Z a-z 0-9 . _ -`: the owner and the name, or `None`.
fn repo_parts(repo: &str) -> Option<(&str, &str)> {
let part =
|x: &str| (1..=64).contains(&x.len()) && x.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
let (owner, name) = repo.split_once('/')?;
(part(owner) && part(name)).then_some((owner, name))
}
/// The app key of a repository (core 0.19.0): `mnovak/Culina` is `culina-android` (the name in lower case, `.` and
/// `_` as `-`); `None` for anything that is not `owner/name` or an id longer than 64.
pub fn android_key_id(repo: &str) -> Option<String> {
let (_, name) = repo_parts(repo)?;
let id: String = name.chars().map(|c| if c == '.' || c == '_' { '-' } else { c.to_ascii_lowercase() }).collect();
let id = format!("{id}-android");
(id.len() <= 64).then_some(id)
}
/// A pattern of the Android grant: `owner/name`, or `owner/*` for every repository of that owner.
fn grant_pattern_ok(p: &str) -> bool {
match p.strip_suffix("/*") {
Some(owner) => repo_parts(&format!("{owner}/x")).is_some(),
None => repo_parts(p).is_some(),
}
}
fn grant_covers(g: &AndroidGrant, repo: &str) -> bool {
let Some((owner, _)) = repo_parts(repo) else { return false };
g.repos.iter().any(|p| p == repo || p.strip_suffix("/*") == Some(owner))
}
/// The certificate's O (1 to 64, no control characters) and C (two ASCII capitals) for the keys the grant makes.
fn grant_subject_ok(o: &str, c: &str) -> bool {
(1..=64).contains(&o.chars().count())
&& !o.chars().any(char::is_control)
&& o.trim() == o
&& c.len() == 2
&& c.bytes().all(|b| b.is_ascii_uppercase())
}
/// A stored grant is what [`Vault::android_grant_set`] could have written; anything else makes the vault refuse to
/// open.
fn grant_ok(g: &AndroidGrant) -> bool {
let id_ok = |id: &String| {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
};
(1..=ANDROID_PATTERNS_MAX).contains(&g.repos.len())
&& g.repos.iter().all(|p| grant_pattern_ok(p))
&& g.repos.iter().enumerate().all(|(i, p)| !g.repos[..i].contains(p))
&& grant_subject_ok(&g.o, &g.c)
&& g.made.len() <= ANDROID_MADE_MAX
&& g.made.iter().all(id_ok)
}
/// What the grant says, for the security audit: names only.
fn grant_words(g: &AndroidGrant) -> String {
format!("Android releases: {} pipeline {ANDROID_PIPELINE}, keys made on first use", g.repos.join(", "))
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
@@ -399,7 +640,8 @@ impl Vault {
repos: &[String],
now: i64,
) -> Result<Vec<String>, Error> {
if self.signing.keys.iter().any(|k| k.role == role) {
// An Android key (core 0.14.0) is a key of its own, not part of a set: it never counts as the set.
if self.signing.keys.iter().any(|k| k.role == role && k.kind != KeyKind::Android) {
return Err(Error::SigningExists(match role {
Role::Release => "release",
Role::Test => "test",
@@ -472,7 +714,11 @@ impl Vault {
if self.signing.get(APPROVE_KEY).is_some() {
return Err(Error::SigningExists("approval"));
}
let release = self.signing.keys.iter().filter(|k| k.role == Role::Release && k.kind != KeyKind::RootCa);
let release = self
.signing
.keys
.iter()
.filter(|k| k.role == Role::Release && !matches!(k.kind, KeyKind::RootCa | KeyKind::Android));
let model = self
.signing
.get("domi-release")
@@ -484,6 +730,49 @@ impl Vault {
Ok(APPROVE_KEY.into())
}
/// Creates an Android app signing key (core 0.14.0): RSA-4096 and a self-signed certificate. A release key
/// always asks; a test key signs without asking, never for a `tag`. The caller saves. Slow: one RSA-4096 key.
pub fn signing_create_android(&mut self, spec: &AndroidKey, now: i64) -> Result<String, Error> {
let id = spec.id.as_str();
if id.is_empty()
|| id.len() > 64
|| !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into()));
}
if self.signing.get(id).is_some() {
return Err(Error::Signing(format!("there is a key `{id}` already")));
}
let name = spec.name.trim();
if name.is_empty() || name.len() > 100 || name.chars().any(char::is_control) {
return Err(Error::Signing("the key's name is not usable".into()));
}
let (pipelines, repos) = (clean_list(&spec.pipelines)?, clean_list(&spec.repos)?);
let made = custos_sign::new_android(&spec.cn, &spec.o, &spec.c).map_err(|e| match e {
custos_sign::Error::Certificate => Error::Signing(
"the certificate's name is not usable (1-64 characters without , + = \" \\ < > ; # and no space at \
either end, and a two-letter country code)"
.into(),
),
e => Error::Signing(e.to_string()),
})?;
self.signing.keys.push(Key {
id: id.into(),
kind: KeyKind::Android,
role: spec.role,
name: name.into(),
secret: Secret::Rsa(made.secret),
public: None,
key_id: None,
cert: Some(made.cert_der),
issuer: None,
created: now,
pipelines,
repos,
});
Ok(id.into())
}
/// Every signing key, public parts only.
pub fn signing_keys(&self) -> Vec<KeyView> {
self.signing
@@ -505,6 +794,10 @@ impl Vault {
},
cert: k.cert.clone(),
issuer: k.issuer.clone(),
public_pem: match &k.secret {
Secret::P256(s) => s.public_pem().ok(),
_ => None,
},
})
.collect()
}
@@ -540,7 +833,7 @@ impl Vault {
}
/// [`Vault::signing_check`] at `now` (Unix milliseconds): an approval must not have expired then, and must
/// expire at most an hour later.
/// expire at most 25 hours later (`custos_sign::APPROVAL_MAX_AHEAD`).
pub fn signing_check_at(&self, req: &Request, now: i64) -> Result<KeyView, Refusal> {
self.check(req, now).map(|(view, _)| view)
}
@@ -553,6 +846,7 @@ impl Vault {
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY,
(KeyKind::Ed25519, SignKind::Approval) => approver,
(KeyKind::CodeSigning, SignKind::Authenticode) => true,
(KeyKind::Android, SignKind::Apk) => true,
_ => false,
};
if k.kind == KeyKind::RootCa {
@@ -579,6 +873,13 @@ impl Vault {
SignKind::Authenticode if req.digest.len() != 32 => {
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
}
SignKind::Apk
if req.digest.is_empty()
|| req.digest.len() % 64 != 0
|| req.digest.len() > 64 * custos_sign::MAX_APK_DIGESTS =>
{
return Err(Refusal::Invalid("an APK request is 1 to 4 SHA-512 digests: 64 bytes each".into()));
}
SignKind::Manifest => {
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
@@ -643,6 +944,14 @@ impl Vault {
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let rule = self.standing_rule_for(req, now).map(|r| r.id);
// A standing approval first; the Android grant only where none fits (core 0.19.0).
let by_grant = approval == Approval::Standing && rule.is_none() && self.android_grant_fits(req, now);
if approval == Approval::Standing && rule.is_none() && !by_grant {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let k = self.signing.get(&req.key).expect("checked");
let seconds = seconds(now);
let bytes = match (&k.secret, req.kind) {
@@ -670,6 +979,7 @@ impl Vault {
)
.map(String::into_bytes),
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
(Secret::Rsa(s), SignKind::Apk) => custos_sign::apk(s, &req.digest),
_ => unreachable!("signing_check matched the key to the kind"),
};
let bytes = match bytes {
@@ -681,15 +991,29 @@ impl Vault {
}
};
let sha256 = custos_sign::sha256_hex(&bytes);
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
let outcome = match approval {
Approval::Auto => Outcome::Auto,
Approval::Mark => Outcome::Approved,
Approval::Standing => Outcome::Standing,
};
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
if let (Approval::Standing, Some(id)) = (approval, rule)
&& let Some(r) = self.signing.standing.iter_mut().find(|r| r.id == id)
{
r.uses = r.uses.saturating_add(1);
r.last_used = Some(now);
}
if by_grant && let Some(g) = self.signing.android.as_mut() {
g.uses = g.uses.saturating_add(1);
g.last_used = Some(now);
}
Ok(Signed { bytes, sha256 })
}
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
let outcome = match outcome {
Outcome::Approved | Outcome::Auto => Outcome::Refused,
Outcome::Approved | Outcome::Auto | Outcome::Standing => Outcome::Refused,
o => o,
};
self.signing_record(req, outcome, reason, None, now);
@@ -740,9 +1064,263 @@ impl Vault {
signature,
reason,
run,
by: None,
env: None,
request: None,
approvers: Vec::new(),
});
}
/// What a rule for `req` would name, when `req` could be signed and may be covered by one at all: the key's
/// `created`, the repository and pipeline as the scope check reads them, and an approval's targets.
fn standing_shape(&self, req: &Request, now: i64) -> Result<(i64, String, String, Vec<String>), Error> {
let no = |why: &str| Error::Signing(why.into());
let (view, approval) = self.check(req, now).map_err(|r| Error::Signing(r.to_string()))?;
if req.run.is_none() {
return Err(no("a standing approval is for requests that name a run"));
}
if req.via == Via::Remote && req.kind != SignKind::Approval {
return Err(no("a release signature the server runner asks for always needs a card"));
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(no("Sign only with a card is ticked"));
}
let (repo, pipeline, targets) = match approval {
Some(a) => (a.repo, a.pipeline, a.targets),
None => (req.context.repo.clone(), req.context.pipeline.clone(), Vec::new()),
};
if !name_ok(&repo) || !name_ok(&pipeline) {
return Err(no("the repository or pipeline is not a usable name"));
}
Ok((view.created, repo, pipeline, targets))
}
/// Whether `req`, which Mark is approving on a card, may start a standing approval (docs/SIGNING.md, "Standing
/// approvals"); the error says why not, in words for the card.
pub fn standing_can_grant(&self, req: &Request, now: i64) -> Result<(), Error> {
self.standing_shape(req, now)?;
let k = self.signing.get(&req.key).expect("checked");
if k.role != Role::Release {
return Err(Error::Signing("a test key signs without asking: it needs no standing approval".into()));
}
// A key's first signature is never the one that starts a rule.
let signed = |e: &AuditEntry| {
e.key == k.id && e.at >= k.created && matches!(e.outcome, Outcome::Approved | Outcome::Standing)
};
if !self.signing.audit.iter().any(signed) {
return Err(Error::Signing(format!(
"`{}` has never signed: its first signature needs a card of its own",
k.id
)));
}
Ok(())
}
/// Stores the standing approval for `req` (or adds an approval's targets to the one there is) and writes
/// `standing-granted` to the security audit. Call it before signing the request Mark approved. The caller saves.
pub fn standing_grant(&mut self, req: &Request, now: i64) -> Result<StandingRule, Error> {
self.standing_can_grant(req, now)?;
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now)?;
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
let at = self.signing.standing.iter().position(|r| r.id == id);
// The same combination again keeps its rule (and its count) unless the key under that id is another one.
let mut rule = match at.map(|i| self.signing.standing[i].clone()).filter(|r| r.key_created == key_created) {
Some(r) => r,
None => StandingRule {
id,
repo,
key: req.key.clone(),
key_created,
kind: req.kind,
pipeline,
via: req.via,
targets: Vec::new(),
granted: now,
last_used: None,
uses: 0,
},
};
// Any target Mark sees on this card joins the ones he allowed before.
for t in targets {
if !rule.targets.contains(&t) {
rule.targets.push(t);
}
}
// Never stored in a form this core would refuse to read back; what was there stays as it was.
if !rule_ok(&rule) {
return Err(Error::Signing("this request cannot be written as a standing approval".into()));
}
match at {
Some(i) => self.signing.standing[i] = rule.clone(),
None if self.signing.standing.len() >= STANDING_MAX => {
return Err(Error::Signing("there are 256 standing approvals already: revoke one first".into()));
}
None => self.signing.standing.push(rule.clone()),
}
self.security.standing_note(crate::security::Action::StandingGranted, &rule_words(&rule), now);
Ok(rule)
}
/// The standing approval `req` fits, if one does: the request passes [`Vault::signing_check_at`], names a run,
/// and equals the rule in repository, pipeline, key, kind and origin (an approval: its targets are the rule's).
pub fn standing_rule_for(&self, req: &Request, now: i64) -> Option<StandingRule> {
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now).ok()?;
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
self.signing
.standing
.iter()
.find(|r| {
r.id == id
&& r.repo == repo
&& r.key == req.key
&& r.key_created == key_created
&& r.kind == req.kind
&& r.pipeline == pipeline
&& r.via == req.via
&& targets.iter().all(|t| r.targets.contains(t))
})
.cloned()
}
/// The standing approvals, oldest first.
pub fn standing_rules(&self) -> Vec<StandingRule> {
self.signing.standing.clone()
}
/// Removes a standing approval, audited `standing-revoked`. False when there is none with this id. The caller
/// saves.
pub fn standing_revoke(&mut self, id: &str, now: i64) -> bool {
let Some(i) = self.signing.standing.iter().position(|r| r.id == id) else { return false };
let rule = self.signing.standing.remove(i);
self.security.standing_note(crate::security::Action::StandingRevoked, &rule_words(&rule), now);
true
}
/// The Android grant, if Mark gave it (core 0.19.0, docs/SIGNING.md "The Android grant").
pub fn android_grant(&self) -> Option<AndroidGrant> {
self.signing.android.clone()
}
/// Stores the Android grant, or replaces its patterns and subject (its counts and the keys it made stay), and
/// writes `standing-granted`. Refused while *Sign only with a card* is ticked. Call it only from Mark's own
/// click. The caller saves.
pub fn android_grant_set(&mut self, repos: &[String], o: &str, c: &str, now: i64) -> Result<AndroidGrant, Error> {
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(Error::Signing("Sign only with a card is ticked".into()));
}
let mut patterns: Vec<String> = Vec::new();
for p in repos.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
if !grant_pattern_ok(p) {
return Err(Error::Signing(format!(
"`{p}` is not a repository (owner/name) or every repository of an owner (owner/*)"
)));
}
if !patterns.iter().any(|x| x == p) {
patterns.push(p.to_string());
}
}
if patterns.is_empty() || patterns.len() > ANDROID_PATTERNS_MAX {
return Err(Error::Signing(format!("the grant names 1 to {ANDROID_PATTERNS_MAX} repositories")));
}
if !grant_subject_ok(o, c) {
return Err(Error::Signing(
"the certificates need an organisation (1-64 characters) and a two-letter country code".into(),
));
}
let old = self.signing.android.clone();
let grant = AndroidGrant {
repos: patterns,
o: o.into(),
c: c.into(),
granted: now,
last_used: old.as_ref().and_then(|g| g.last_used),
uses: old.as_ref().map_or(0, |g| g.uses),
made: old.map(|g| g.made).unwrap_or_default(),
};
self.security.standing_note(crate::security::Action::StandingGranted, &grant_words(&grant), now);
self.signing.android = Some(grant.clone());
Ok(grant)
}
/// Removes the Android grant (`standing-revoked`); the keys it made stay. False when there is none. The caller
/// saves.
pub fn android_grant_revoke(&mut self, now: i64) -> bool {
let Some(g) = self.signing.android.take() else { return false };
self.security.standing_note(crate::security::Action::StandingRevoked, &grant_words(&g), now);
true
}
/// Whether `req` is signed by the Android grant: an `apk` from this PC's pipe with a run, in the key's scope, for
/// a repository the grant covers and pipeline `release`, by that repository's own app key (scoped to exactly it
/// and `release`, role release), while *Sign only with a card* is not ticked. A key's first signature fits.
pub fn android_grant_fits(&self, req: &Request, now: i64) -> bool {
let Some(g) = &self.signing.android else { return false };
let Ok((view, _)) = self.check(req, now) else { return false };
req.kind == SignKind::Apk
&& req.via == Via::Local
&& req.run.is_some()
&& !self.security.is_ticked(crate::security::Item::CardSigning)
&& view.kind == KeyKind::Android
&& view.role == Role::Release
&& req.context.pipeline == ANDROID_PIPELINE
&& grant_covers(g, &req.context.repo)
&& android_key_id(&req.context.repo).as_deref() == Some(req.key.as_str())
&& view.repos == [req.context.repo.clone()]
&& view.pipelines == [ANDROID_PIPELINE.to_string()]
}
/// Makes `repo`'s app key under the Android grant, when its first release asks (`custos-sign apk`): the grant
/// covers `repo`, `pipeline` is `release`, `via` is local, *Sign only with a card* is not ticked, and there is
/// no key under that id. RSA-4096, `CN=<Name>`, the grant's O and C, scoped to exactly `repo` and `release`.
/// Writes `standing-granted` with `Android grant made <id> for <repo> pipeline release`: a value every core since
/// 0.16.0 reads, so the phone and the web vault still open the vault (core 0.19.1). The caller saves. Slow: one
/// RSA-4096 key.
pub fn android_grant_make_key(&mut self, repo: &str, pipeline: &str, via: Via, now: i64) -> Result<String, Error> {
let no = |why: String| Err(Error::Signing(why));
let Some(g) = self.signing.android.clone() else { return no("there is no Android grant".into()) };
let (Some((_, name)), Some(id)) = (repo_parts(repo), android_key_id(repo)) else {
return no(format!("`{repo}` is not a repository (owner/name)"));
};
if via != Via::Local {
return no("the server runner never makes a key".into());
}
if pipeline != ANDROID_PIPELINE {
return no(format!("the Android grant makes keys for the pipeline `{ANDROID_PIPELINE}` only"));
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
return no("Sign only with a card is ticked".into());
}
if !grant_covers(&g, repo) {
return no(format!("the Android grant does not cover `{repo}`"));
}
if self.signing.get(&id).is_some() {
return no(format!("there is a key `{id}` already"));
}
let mut cn = name.to_string();
if let Some(first) = cn.get_mut(0..1) {
first.make_ascii_uppercase();
}
let spec = AndroidKey {
id: id.clone(),
name: format!("{cn} Android"),
cn,
o: g.o.clone(),
c: g.c.clone(),
role: Role::Release,
pipelines: vec![ANDROID_PIPELINE.into()],
repos: vec![repo.into()],
};
self.signing_create_android(&spec, now)?;
if let Some(g) = self.signing.android.as_mut()
&& g.made.len() < ANDROID_MADE_MAX
{
g.made.push(id.clone());
}
let words = format!("Android grant made {id} for {repo} pipeline {ANDROID_PIPELINE}");
self.security.standing_note(crate::security::Action::StandingGranted, &words, now);
Ok(id)
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
@@ -799,12 +1377,46 @@ mod tests {
assert_eq!(back.signing_keys(), views);
}
#[test]
fn a_key_made_again_under_the_same_id_does_not_inherit_the_rule() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
let r = Request { run: Some("r-1".into()), ..req("domi-release", SignKind::Minisign, 64) };
v.signing_sign(&r, Approval::Mark, 2).unwrap();
v.standing_grant(&r, 3).unwrap();
assert!(v.standing_rule_for(&r, 4).is_some());
// The same id, made at another time (no API does this; a rule must not depend on that).
v.signing.keys.iter_mut().find(|k| k.id == "domi-release").unwrap().created = 10;
assert!(v.standing_rule_for(&r, 11).is_none(), "the rule names the key it was granted for");
assert!(matches!(v.signing_sign(&r, Approval::Standing, 11), Err(Refusal::NeedsApproval(_))));
// The old key's signatures do not count as the new key's first one either.
assert!(v.standing_grant(&r, 12).is_err());
v.signing_sign(&r, Approval::Mark, 13).unwrap();
let again = v.standing_grant(&r, 14).unwrap();
assert_eq!((again.key_created, again.granted, again.uses), (10, 14, 0));
assert_eq!(v.standing_rules().len(), 1);
}
#[test]
fn no_api_path_returns_a_private_key() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["*"]), &s(&["*"]), 1).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
for (id, role) in [("postea-android", Role::Release), ("domi-test-android", Role::Test)] {
let spec = AndroidKey {
id: id.into(),
name: id.into(),
cn: "Postea".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role,
pipelines: s(&["*"]),
repos: s(&["*"]),
};
v.signing_create_android(&spec, 1).unwrap();
}
let secrets: Vec<Vec<u8>> = v
.signing
.keys
@@ -812,9 +1424,10 @@ mod tests {
.map(|k| match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
Secret::P256(s) => s.expose().to_vec(),
})
.collect();
assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set");
assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys");
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
@@ -839,19 +1452,36 @@ mod tests {
));
reqs.push(approve);
reqs.push(req("domi-approve", SignKind::Minisign, 64));
reqs.push(req("postea-android", SignKind::Apk, 128));
reqs.push(req("domi-test-android", SignKind::Apk, 64));
reqs.push(req("postea-android", SignKind::Authenticode, 32));
reqs.push(req("domi-code-signing", SignKind::Apk, 64));
for r in &reqs {
out += &format!("{:?}", v.signing_check(r));
for approval in [Approval::Mark, Approval::Auto] {
for approval in [Approval::Mark, Approval::Auto, Approval::Standing] {
match v.signing_sign(r, approval, 2) {
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
Err(e) => out += &format!("{e:?}{e}"),
}
// A standing approval for the same request with a run, once the key has signed (core 0.16.0).
let with_run = Request { run: r.run.clone().or(Some("r-1".into())), ..r.clone() };
out += &format!("{:?}{:?}", v.standing_can_grant(&with_run, 2), v.standing_grant(&with_run, 2));
out += &format!("{:?}", v.standing_rule_for(&with_run, 2));
}
}
assert!(v.standing_rules().len() >= 3, "rules were granted: {:?}", v.standing_rules());
out += &serde_json::to_string(&v.standing_rules()).unwrap();
out += &format!("{:?}{:?}", v.standing_rules(), v.security_view(3).audit);
assert!(
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
"an approval was signed too"
);
assert!(
v.signing_audit()
.iter()
.any(|e| e.kind == SignKind::Apk && e.key == "postea-android" && e.outcome == Outcome::Approved),
"and an APK"
);
out += &serde_json::to_string(v.signing_audit()).unwrap();
out += &format!("{:?}", v.signing_audit());
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
File diff suppressed because it is too large Load Diff
+265
View File
@@ -0,0 +1,265 @@
//! Android APK signing keys (core 0.14.0, docs/SIGNING.md "apk"): the key and its certificate, the `apk` kind and
//! nothing else, scope, the test-key rules, malformed requests, the audit through a reopen, and never unattended.
//! That no API path returns an Android key's private half is part of the unit test in src/signing.rs.
use std::collections::BTreeSet;
use std::sync::OnceLock;
use custos_vault::security::{self, Level};
use custos_vault::signing::{AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const REPO: &str = "mnovak/Postea";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn spec(id: &str, role: Role, pipelines: &[&str], repos: &[&str]) -> AndroidKey {
AndroidKey {
id: id.into(),
name: if role == Role::Release { "Postea Android".into() } else { "Domi test Android".into() },
cn: if role == Role::Release { "Postea".into() } else { "Domi Test Android".into() },
o: if role == Role::Release { "Marek Novak".into() } else { "Domi".into() },
c: "CZ".into(),
role,
pipelines: s(pipelines),
repos: s(repos),
}
}
/// A vault with the release and test sets, `postea-android` (release, `mnovak/Postea`) and `domi-test-android`
/// (test, any). Two RSA-4096 keys are made once and the vault reopened from its bytes for each test.
fn vault() -> Vault {
static BYTES: OnceLock<Vec<u8>> = OnceLock::new();
let bytes = BYTES.get_or_init(|| {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
v.to_bytes().unwrap()
});
Vault::open(bytes, &SecretString::from("pw")).unwrap()
}
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
Context {
repo: repo.into(),
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: trigger.into(),
file: "Postea-1.0.0.apk".into(),
size: 9_876_543,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.0.0".into(),
}
}
fn apk_req(key: &str, digests: usize, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: (0..digests * 64).map(|i| (i % 251) as u8).collect(),
manifest: None,
approval: None,
run: Some("r-7".into()),
context: c,
via: Via::Local,
}
}
fn release() -> Context {
ctx("release", REPO, "tag")
}
#[test]
fn an_android_key_has_its_certificate_and_no_secret_in_its_view() {
let v = vault();
let keys = v.signing_keys();
let k = keys.iter().find(|k| k.id == "postea-android").unwrap();
assert_eq!((k.kind, k.role, k.auto_approve), (KeyKind::Android, Role::Release, false));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&[REPO])));
assert_eq!((k.issuer.clone(), k.key_id.clone(), k.minisign_public.clone()), (None, None, None));
let cert = v.signing_export_cert("postea-android").unwrap();
assert_eq!(k.cert.as_deref(), Some(cert.as_slice()));
let c = x509_cert::Certificate::from_der(&cert).unwrap();
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject);
let t = keys.iter().find(|k| k.id == "domi-test-android").unwrap();
assert_eq!((t.kind, t.role, t.auto_approve), (KeyKind::Android, Role::Test, true));
// Both serialise as the closed value `android`.
assert!(serde_json::to_string(k).unwrap().contains(r#""kind":"android""#));
}
#[test]
fn ids_and_names_are_checked_and_an_id_is_made_once() {
let mut v = vault();
let again = v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(again, Err(Error::Signing(m)) if m.contains("already")));
let taken = v.signing_create_android(&spec("domi-release", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(taken, Err(Error::Signing(_))), "an id of another kind");
for bad in ["", "Postea", "postea android", "postea/android", &"x".repeat(65)] {
let r = v.signing_create_android(&spec(bad, Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(r, Err(Error::Signing(_))), "{bad:?}");
}
let mut odd = spec("odd-android", Role::Release, &["release"], &[REPO]);
odd.c = "Czechia".into();
assert!(matches!(v.signing_create_android(&odd, NOW), Err(Error::Signing(m)) if m.contains("country")));
assert_eq!(v.signing_keys().len(), 9, "nothing was added");
}
#[test]
fn an_apk_request_signs_every_digest_with_sha512_pkcs1_and_the_certificates_key() {
let mut v = vault();
let req = apk_req("postea-android", 2, release());
assert!(v.signing_check(&req).is_ok());
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
assert_eq!(signed.bytes.len(), 2 * 512, "two RSA-4096 signatures");
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("postea-android").unwrap()).unwrap();
let spki = cert.tbs_certificate.subject_public_key_info.to_der().unwrap();
let key = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
for (d, sig) in req.digest.chunks(64).zip(signed.bytes.chunks(512)) {
key.verify_prehash(d, &Signature::try_from(sig).unwrap()).unwrap();
}
// One request, one audit entry, whatever the number of digests.
let a = v.signing_audit().last().unwrap();
assert_eq!((a.key.as_str(), a.kind, a.outcome), ("postea-android", SignKind::Apk, Outcome::Approved));
assert_eq!((a.context.file.as_str(), a.run.as_deref()), ("Postea-1.0.0.apk", Some("r-7")));
}
#[test]
fn an_android_key_signs_only_apks_and_only_android_keys_sign_apks() {
let mut v = vault();
let mut exe = apk_req("postea-android", 0, release());
exe.kind = SignKind::Authenticode;
exe.digest = vec![9; 32];
let mut minisign = exe.clone();
minisign.kind = SignKind::Minisign;
minisign.digest = vec![9; 64];
let leaf = Request {
key: "domi-code-signing".into(),
context: ctx("release", "Arca", "tag"),
..apk_req("", 1, release())
};
let ed =
Request { key: "domi-release".into(), context: ctx("release", "Arca", "tag"), ..apk_req("", 1, release()) };
let root = Request { key: "domi-root".into(), ..apk_req("", 1, release()) };
let test_leaf = Request { key: "domi-test-code-signing".into(), ..apk_req("", 1, ctx("ci", REPO, "push")) };
for r in [&exe, &minisign, &leaf, &ed, &root, &test_leaf] {
assert!(matches!(v.signing_check(r), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
}
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn another_repo_or_pipeline_is_out_of_scope_even_when_approved() {
let mut v = vault();
for c in [ctx("release", "mnovak/Arca", "tag"), ctx("release", "Postea", "tag"), ctx("nightly", REPO, "tag")] {
let r = apk_req("postea-android", 2, c);
assert!(matches!(v.signing_check(&r), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
assert_eq!(v.signing_audit().iter().filter(|e| e.outcome == Outcome::OutOfScope).count(), 3);
}
#[test]
fn the_release_key_always_needs_mark_and_the_test_twin_signs_alone_but_never_a_tag() {
let mut v = vault();
let r = v.signing_sign(&apk_req("postea-android", 2, release()), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
let t = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "manual")), Approval::Auto, NOW).unwrap();
assert_eq!(t.bytes.len(), 1024);
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Auto);
let tag = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
}
#[test]
fn malformed_apk_requests_are_refused() {
let mut v = vault();
let mut cases = Vec::new();
for n in [0usize, 1, 32, 63, 65, 64 * 5] {
let mut r = apk_req("postea-android", 0, release());
r.digest = vec![1; n];
if n != 1 {
cases.push(r);
}
}
let mut no_file = apk_req("postea-android", 2, release());
no_file.context.file = String::new();
let mut path = apk_req("postea-android", 2, release());
path.context.file = "out\\Postea.apk".into();
let mut stray = apk_req("postea-android", 2, release());
stray.approval = Some("{}".into());
let mut bad_run = apk_req("postea-android", 2, release());
bad_run.run = Some("r 7".into());
cases.extend([no_file, path, stray, bad_run]);
for r in &cases {
assert!(
matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))),
"{} bytes {:?}",
r.digest.len(),
r.context.file
);
}
assert_eq!(v.signing_audit().len(), cases.len());
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn refused_and_expired_apk_requests_are_recorded_and_everything_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault();
let req = apk_req("postea-android", 2, release());
v.signing_refuse(&req, Outcome::Refused, Some("Mark refused this signature".into()), NOW);
v.signing_refuse(&req, Outcome::Expired, None, NOW + 1);
let signed = v.signing_sign(&req, Approval::Mark, NOW + 2).unwrap();
v.save(&path).unwrap();
let mut back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
assert_eq!(back.signing_audit(), v.signing_audit());
let outcomes: Vec<Outcome> = back.signing_audit().iter().map(|e| e.outcome).collect();
assert_eq!(outcomes, [Outcome::Refused, Outcome::Expired, Outcome::Approved]);
assert_eq!(back.signing_audit()[2].signature.as_deref(), Some(signed.sha256.as_str()));
assert_eq!(back.signing_keys(), v.signing_keys());
// The same key: a reopened vault makes the same (deterministic PKCS#1 v1.5) signatures.
assert_eq!(back.signing_sign(&req, Approval::Mark, NOW + 3).unwrap().bytes, signed.bytes);
}
#[test]
fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() {
// `unattended_sign` is a closed list of kinds: `apk` is not on it, so an APK always shows the card.
for level in [Level::Setup, Level::Standard] {
assert!(!security::unattended_sign(level, &BTreeSet::new(), true, "apk", true));
assert!(security::unattended_sign(level, &BTreeSet::new(), true, "authenticode", true));
}
}
#[test]
fn an_android_key_made_first_does_not_count_as_the_release_or_test_set() {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
// No release set yet: there is nothing to add an approval key to, and the Android key is no model for one.
assert!(matches!(v.signing_add_approve(NOW), Err(Error::Signing(_))));
let ids = v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
assert_eq!(ids, ["domi-release", "domi-root", "domi-code-signing", "domi-approve"]);
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
let keys = v.signing_keys();
let approve = keys.iter().find(|k| k.id == "domi-approve").unwrap();
assert_eq!(approve.repos, s(&["Arca"]), "the release set's scope, not Postea's");
assert_eq!(keys.len(), 9);
}
+266
View File
@@ -0,0 +1,266 @@
//! The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): one answer for every Domi app's release
//! APK. It signs a request for a repository's own app key (`<name>-android`, scoped to exactly that repository and
//! `release`) from this PC's pipe, its first signature included, and makes that key when the app's first release
//! asks. Everything else still needs a card.
use custos_vault::security::{Action, Auth, Item};
use custos_vault::signing::{
AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via, android_key_id,
};
use custos_vault::{KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["mnovak/Culina"]), NOW).unwrap();
v
}
fn granted(repos: &[&str]) -> Vault {
let mut v = vault();
v.android_grant_set(&s(repos), "Marek Novak", "CZ", NOW).unwrap();
v
}
fn apk(key: &str, repo: &str, pipeline: &str, run: Option<&str>) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: vec![5; 64],
manifest: None,
approval: None,
run: run.map(Into::into),
context: Context {
repo: repo.into(),
commit: COMMIT.into(),
pipeline: pipeline.into(),
step: "sign-apk".into(),
trigger: "tag".into(),
file: "Culina-1.2.0.apk".into(),
size: 9_400_000,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.2.0".into(),
},
via: Via::Local,
}
}
fn culina(run: &str) -> Request {
apk("culina-android", "mnovak/Culina", "release", Some(run))
}
fn notes(v: &Vault, action: Action) -> Vec<String> {
v.security_view(NOW + 1_000)
.audit
.into_iter()
.filter(|e| e.action == action)
.map(|e| e.detail.unwrap_or_default())
.collect()
}
#[test]
fn an_app_key_is_named_by_its_repository() {
assert_eq!(android_key_id("mnovak/Culina").as_deref(), Some("culina-android"));
assert_eq!(android_key_id("mnovak/domi-office").as_deref(), Some("domi-office-android"));
assert_eq!(android_key_id("mnovak/Domi.Office_2").as_deref(), Some("domi-office-2-android"));
for bad in ["Culina", "mnovak/", "/Culina", "mnovak/*", "a/b/c", "mnovak/Cu lina", "mnovak/Čulina", ""] {
assert_eq!(android_key_id(bad), None, "{bad}");
}
assert_eq!(android_key_id(&format!("mnovak/{}", "x".repeat(57))), None, "the id would be longer than 64");
}
#[test]
fn the_grant_makes_an_apps_key_and_signs_its_first_apk_without_a_card() {
let mut v = granted(&["mnovak/*"]);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 1), "no key yet");
let id = v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 1).unwrap();
assert_eq!(id, "culina-android");
let k = v.signing_keys().into_iter().find(|k| k.id == id).unwrap();
assert_eq!((k.kind, k.role, k.name.as_str()), (KeyKind::Android, Role::Release, "Culina Android"));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&["mnovak/Culina"])));
let cert = String::from_utf8_lossy(k.cert.as_ref().unwrap()).into_owned();
assert!(cert.contains("Culina") && cert.contains("Marek Novak"), "the certificate names the app and Mark");
// Its first signature: no card, recorded as `standing`, counted on the grant.
assert!(v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(v.standing_rule_for(&culina("r-1"), NOW + 2).is_none(), "the grant is not a per-key rule");
let signed = v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2);
assert!(signed.is_ok(), "{signed:?}");
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
assert_eq!(v.signing_audit().last().unwrap().context.file, "Culina-1.2.0.apk");
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 3).unwrap();
let g = v.android_grant().unwrap();
assert_eq!((g.uses, g.last_used, g.made.clone()), (2, Some(NOW + 3), s(&["culina-android"])));
// Granting, then the key it made: both `standing-granted`, a value cores since 0.16.0 read (core 0.19.1).
let granted_note = notes(&v, Action::StandingGranted);
assert_eq!(granted_note.len(), 2, "{granted_note:?}");
assert!(granted_note[0].contains("Android releases") && granted_note[0].contains("mnovak/*"), "{granted_note:?}");
assert_eq!(granted_note[1], "Android grant made culina-android for mnovak/Culina pipeline release");
// The public note call cannot write it.
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
}
#[test]
fn the_grant_never_makes_a_key_it_does_not_cover() {
let mut v = granted(&["mnovak/Culina", "mnovak/Liber"]);
for (repo, pipeline, via, why) in [
("mnovak/Postea", "release", Via::Local, "a repository no pattern matches"),
("someone/Culina", "release", Via::Local, "another owner"),
("mnovak/Culina", "ci", Via::Local, "another pipeline"),
("mnovak/Culina", "release", Via::Remote, "the server runner"),
("Culina", "release", Via::Local, "not owner/name"),
] {
assert!(v.android_grant_make_key(repo, pipeline, via, NOW + 1).is_err(), "{why}");
}
assert!(v.signing_keys().iter().all(|k| k.kind != KeyKind::Android), "nothing was made");
v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 2).unwrap();
assert!(v.android_grant_make_key("mnovak/Liber", "release", Via::Local, NOW + 3).is_err(), "made once");
v.security_tick(Item::CardSigning, NOW + 4);
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 5).is_err(), "paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 6);
assert!(v.android_grant_revoke(NOW + 7));
assert!(v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW + 8).is_err(), "no grant");
assert_eq!(v.android_grant().map(|g| g.made), None);
}
#[test]
fn only_the_repositorys_own_app_key_in_its_own_scope_from_this_pc_with_a_run_fits() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
// A key of the right name with a wider scope, and one for the wrong repository, made by hand.
let wide = AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["*"]),
};
v.signing_create_android(&wide, NOW).unwrap();
v.signing_create_android(
&AndroidKey { id: "other-android".into(), repos: s(&["mnovak/Rosea"]), ..wide.clone() },
NOW,
)
.unwrap();
v.signing_create_android(&AndroidKey { id: "domi-test-android".into(), role: Role::Test, ..wide.clone() }, NOW)
.unwrap();
let mut remote = culina("r-1");
remote.via = Via::Remote;
let mut minisign = culina("r-1");
minisign.kind = SignKind::Minisign;
minisign.key = "domi-release".into();
minisign.digest = vec![7; 64];
for (req, why) in [
(remote, "the server runner"),
(apk("culina-android", "mnovak/Culina", "release", None), "no run"),
(apk("liber-android", "mnovak/Liber", "release", Some("r-1")), "a key with a wider scope"),
(apk("other-android", "mnovak/Rosea", "release", Some("r-1")), "not the repository's app key"),
(apk("domi-test-android", "mnovak/Liber", "release", Some("r-1")), "a test key"),
(minisign, "another kind"),
] {
assert!(!v.android_grant_fits(&req, NOW + 1), "{why}");
assert!(v.signing_sign(&req, Approval::Standing, NOW + 1).is_err(), "{why}: never signed without a card");
assert_ne!(v.signing_audit().last().unwrap().outcome, Outcome::Standing, "{why}");
}
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn an_explicit_list_covers_only_its_repositories_and_bad_patterns_are_refused() {
let mut v = granted(&["mnovak/Culina"]);
v.signing_create_android(
&AndroidKey {
id: "liber-android".into(),
name: "Liber Android".into(),
cn: "Liber".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["mnovak/Liber"]),
},
NOW,
)
.unwrap();
let liber = apk("liber-android", "mnovak/Liber", "release", Some("r-1"));
assert!(!v.android_grant_fits(&liber, NOW + 1), "not in the list");
// Editing the list keeps the counts and covers the new repository; a key made by hand in that shape is covered.
v.android_grant_set(&s(&["mnovak/Culina", "mnovak/Liber", "mnovak/Liber"]), "Marek Novak", "CZ", NOW + 2).unwrap();
assert_eq!(v.android_grant().unwrap().repos, s(&["mnovak/Culina", "mnovak/Liber"]));
assert!(v.android_grant_fits(&liber, NOW + 3));
for bad in [&[][..], &["mnovak"], &["*/*"], &["*"], &["mnovak/*/x"], &["mn ovak/*"], &["mnovak/Cu*"]] {
assert!(v.android_grant_set(&s(bad), "Marek Novak", "CZ", NOW + 4).is_err(), "{bad:?}");
}
let many: Vec<String> = (0..65).map(|i| format!("mnovak/app{i}")).collect();
assert!(v.android_grant_set(&many, "Marek Novak", "CZ", NOW + 4).is_err(), "at most 64");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "Czech", NOW + 4).is_err(), "a two-letter country");
assert!(v.android_grant_set(&s(&["mnovak/*"]), "", "CZ", NOW + 4).is_err(), "an organisation");
assert_eq!(
v.android_grant().unwrap().repos,
s(&["mnovak/Culina", "mnovak/Liber"]),
"a refused edit changes nothing"
);
}
#[test]
fn sign_only_with_a_card_pauses_the_grant_and_revoking_ends_it() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.security_tick(Item::CardSigning, NOW + 1);
assert!(!v.android_grant_fits(&culina("r-1"), NOW + 2));
assert!(matches!(v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 2), Err(Refusal::NeedsApproval(_))));
assert!(v.android_grant_set(&s(&["mnovak/*"]), "Marek Novak", "CZ", NOW + 2).is_err(), "no grant while ticked");
assert!(v.android_grant().is_some(), "kept, paused");
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 3);
assert!(v.android_grant_fits(&culina("r-1"), NOW + 4));
assert!(v.android_grant_revoke(NOW + 5));
assert!(!v.android_grant_revoke(NOW + 6), "once");
assert!(!v.android_grant_fits(&culina("r-2"), NOW + 7));
assert!(matches!(v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 7), Err(Refusal::NeedsApproval(_))));
// Mark still signs it on a card, and the key stays.
assert!(v.signing_sign(&culina("r-2"), Approval::Mark, NOW + 8).is_ok());
let revoked = notes(&v, Action::StandingRevoked);
assert_eq!(revoked.len(), 1);
assert!(revoked[0].contains("Android releases"), "{revoked:?}");
}
#[test]
fn a_standing_rule_for_the_same_request_is_used_first() {
let mut v = granted(&["mnovak/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Mark, NOW + 1).unwrap();
v.standing_grant(&culina("r-2"), NOW + 2).unwrap();
v.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).unwrap();
assert_eq!(v.standing_rules()[0].uses, 1);
assert_eq!(v.android_grant().unwrap().uses, 0);
}
#[test]
fn the_grant_and_its_counts_survive_a_reopen() {
let mut v = granted(&["mnovak/*", "domi/*"]);
v.android_grant_make_key("mnovak/Culina", "release", Via::Local, NOW).unwrap();
v.signing_sign(&culina("r-1"), Approval::Standing, NOW + 1).unwrap();
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.android_grant(), v.android_grant());
assert!(back.signing_sign(&culina("r-2"), Approval::Standing, NOW + 2).is_ok());
assert_eq!(back.android_grant().unwrap().uses, 2);
assert!(back.android_grant_revoke(NOW + 3));
let again = Vault::open(&back.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(again.android_grant(), None);
}
+31 -7
View File
@@ -86,7 +86,9 @@ fn a_factor_is_added_and_removed_without_the_others() {
// Only the new factor's material is needed: its pairs come from the factor keys in the body.
let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let mut v =
open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE))
.unwrap();
let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]);
// A lost device: drop its factor; the other two still open, the device no longer helps.
@@ -108,7 +110,8 @@ fn a_forgotten_password_is_replaced_with_two_other_factors() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
let mut v =
open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
v.change_password(&pw("New9-Password4"), FAST).unwrap();
let bytes2 = v.to_bytes().unwrap();
let dev = || Unlock::Material(FactorKind::Device, &DEVICE);
@@ -168,7 +171,14 @@ fn a_machine_store_opens_with_its_device_key_alone() {
let user = two_factor_vault().to_bytes().unwrap();
assert!(!Vault::is_machine_store(&user).unwrap());
assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors)));
assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err());
assert!(
Vault::open_with(
&bytes,
Unlock::Material(FactorKind::Device, &STORE),
Unlock::Material(FactorKind::Device, &STORE)
)
.is_err()
);
}
#[test]
@@ -178,10 +188,20 @@ fn limits_are_enforced() {
v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap();
}
assert_eq!(v.factors().len(), 8);
assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors)));
assert!(matches!(
v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"),
Err(Error::TooManyFactors)
));
// Every pair still opens with 8 factors (8 factor slots + 28 pair slots).
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok());
assert!(
open(
&bytes,
Unlock::Material(FactorKind::Device, &[100; 32]),
Unlock::Material(FactorKind::Device, &[105; 32])
)
.is_ok()
);
}
#[test]
@@ -190,7 +210,10 @@ fn no_factor_material_in_debug_output() {
let u = Unlock::Material(FactorKind::Device, &secret);
let p = pw("Orbit7-Fable3");
let printed = format!("{u:?} {:?}", Unlock::Password(&p));
assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}");
assert!(
!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"),
"{printed}"
);
let v = two_factor_vault();
let printed = format!("{v:?} {:?}", v.factors());
for f in v.factors() {
@@ -207,7 +230,8 @@ fn the_key_pair_item_type_round_trips() {
k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5);
v.add(k);
let bytes = v.to_bytes().unwrap();
let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let back =
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
}
+227
View File
@@ -0,0 +1,227 @@
//! The recovery key (docs/FACTORS.md, "The recovery key"): made on request, printed once, and taken by
//! `Vault::recover` only, which replaces every factor and the key itself before it hands the vault back.
use custos_vault::security::Action;
use custos_vault::{Error, FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const PC: [u8; 32] = [7; 32];
const NEW_PC: [u8; 32] = [8; 32];
const PHONE: [u8; 32] = [9; 32];
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
fn device(m: &[u8; 32]) -> Unlock<'_> {
Unlock::Material(FactorKind::Device, m)
}
/// A two-factor vault (password, this PC, a phone's approval) with one item.
fn vault() -> Vault {
let old = pw("the old master password");
let mut v = Vault::create_with(Unlock::Password(&old), "Master password", device(&PC), "MARK-PC", FAST).unwrap();
v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let mut item = Item::new(ItemType::WebLogin, "Gitea", NOW);
item.set("password", "item-secret-value", NOW);
v.add(item);
v
}
fn actions(v: &Vault) -> Vec<Action> {
v.security_view(NOW + 60_000).audit.iter().map(|e| e.action).collect()
}
fn recover(bytes: &[u8], key: &str, new_password: &str) -> Result<(Vault, custos_vault::RecoveryKey), Error> {
Vault::recover(bytes, &pw(key), &pw(new_password), FAST, device(&NEW_PC), "MARK-PC", NOW + 5000)
}
#[test]
fn a_vault_without_a_recovery_key_is_as_before_and_making_one_changes_only_the_header() {
let v = vault();
let before = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&before).unwrap(), None);
assert_eq!(v.recovery_id(), None);
assert!(matches!(recover(&before, &"A".repeat(64), "a new master password"), Err(Error::RecoveryKeyMistyped)));
let mut v = v;
let key = v.recovery_create(NOW).unwrap();
assert_eq!(v.recovery_id().as_deref(), Some(key.id()));
let after = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&after).unwrap().as_deref(), Some(key.id()));
// The factors still open it, exactly as before, and the item is there.
let old = pw("the old master password");
let w = Vault::open_with(&after, Unlock::Password(&old), device(&PC)).unwrap();
assert_eq!((w.items().len(), w.factors().len()), (1, 3));
assert_eq!(actions(&w), [Action::RecoveryCreated]);
assert_eq!(w.security_view(NOW).audit[0].detail.as_deref(), Some(key.id()));
// The key is in neither the file nor the audit.
let flat = key.expose().replace('-', "");
let text = String::from_utf8_lossy(&after).into_owned();
assert!(!text.contains(&flat) && !text.contains(key.expose()));
}
#[test]
fn recovering_forces_a_new_password_new_factors_and_a_new_key() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let (r, new_key) = recover(&bytes, key.expose(), "a new master password").expect("recovered");
// Everything in the vault is still there.
assert_eq!(r.items().len(), 1);
assert_eq!(r.item(&r.items()[0].id).unwrap().field("password").unwrap().value.expose(), "item-secret-value");
// Exactly the two new factors; the old password, the old PC key and the phone are gone.
let kinds: Vec<FactorKind> = r.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device]);
assert_ne!(new_key.id(), key.id());
assert_ne!(new_key.expose(), key.expose());
assert_eq!(r.recovery_id().as_deref(), Some(new_key.id()));
assert_eq!(actions(&r), [Action::RecoveryCreated, Action::Recovered]);
let last = r.security_view(NOW + 5000).audit[1].clone();
assert_eq!((last.at, last.detail.as_deref()), (NOW + 5000, Some(key.id())));
let saved = r.to_bytes().unwrap();
let (old, new) = (pw("the old master password"), pw("a new master password"));
assert!(Vault::open_with(&saved, Unlock::Password(&new), device(&NEW_PC)).is_ok());
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&old), device(&NEW_PC)), Err(Error::WrongPassword)));
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&new), device(&PC)), Err(Error::FactorRejected)));
assert!(Vault::open_with(&saved, device(&PC), Unlock::Material(FactorKind::Approval, &PHONE)).is_err());
// The used key is spent; the new one works, once more.
assert!(matches!(recover(&saved, key.expose(), "yet another password"), Err(Error::WrongRecoveryKey)));
assert!(recover(&saved, new_key.expose(), "yet another password").is_ok());
}
#[test]
fn a_recovery_key_is_never_an_everyday_unlock() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let text = pw(key.expose());
let (_, material) = (key.id(), key.expose().replace('-', ""));
// It is not a password and not a factor: no ordinary way of opening takes it, alone or with a real factor.
assert!(Vault::open(&bytes, &text).is_err());
let old = pw("the old master password");
assert!(matches!(Vault::open_with(&bytes, Unlock::Password(&text), device(&PC)), Err(Error::WrongPassword)));
for kind in [FactorKind::Device, FactorKind::Totp, FactorKind::Approval, FactorKind::Passkey] {
let as_material = Unlock::Material(kind, &material.as_bytes()[..32]);
assert!(Vault::open_with(&bytes, Unlock::Password(&old), as_material).is_err(), "{kind:?}");
}
assert!(Vault::open_machine_store(&bytes, &PC).is_err());
assert_eq!(Vault::is_machine_store(&bytes).unwrap(), false);
// It does not count as a factor: two are still needed and it is not listed.
assert_eq!(Vault::factor_ids(&bytes).unwrap().len(), 3);
// Recovering needs a real second factor and a password worth the name.
let two_passwords =
Vault::recover(&bytes, &text, &pw("a new master password"), FAST, Unlock::Password(&old), "x", NOW);
assert!(matches!(two_passwords, Err(Error::NeedTwoFactors)));
let short = Vault::recover(&bytes, &text, &pw(""), FAST, device(&NEW_PC), "x", NOW);
assert!(matches!(short, Err(Error::WrongPassword) | Err(Error::FactorRejected)));
// A refused recovery changed nothing: the key still works.
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
}
#[test]
fn a_wrong_an_old_or_another_vaults_key_opens_nothing() {
let mut v = vault();
let first = v.recovery_create(NOW).unwrap();
// A second key replaces the first: one key per vault.
let second = v.recovery_create(NOW + 1000).unwrap();
assert_ne!(first.id(), second.id());
let bytes = v.to_bytes().unwrap();
assert!(matches!(recover(&bytes, first.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
let mut other = vault();
let others = other.recovery_create(NOW).unwrap();
assert!(matches!(recover(&bytes, others.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
// The right key with its last character changed: the check says so before the vault is tried.
let forged: String = {
let mut flat: Vec<char> = second.expose().chars().collect();
let last = flat.len() - 1;
flat[last] = if flat[last] == 'A' { 'B' } else { 'A' };
flat.into_iter().collect()
};
assert!(matches!(recover(&bytes, &forged, "a new master password"), Err(Error::RecoveryKeyMistyped)));
assert!(recover(&bytes, second.expose(), "a new master password").is_ok());
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryCreated]);
}
#[test]
fn removing_the_key_closes_that_door_and_is_audited() {
let mut v = vault();
assert!(matches!(v.recovery_remove(NOW), Err(Error::NoRecoveryKey)));
let key = v.recovery_create(NOW).unwrap();
v.recovery_remove(NOW + 1000).unwrap();
assert_eq!(v.recovery_id(), None);
let bytes = v.to_bytes().unwrap();
assert_eq!(Vault::recovery_id_of(&bytes).unwrap(), None);
assert!(matches!(recover(&bytes, key.expose(), "a new master password"), Err(Error::NoRecoveryKey)));
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryRemoved]);
// The file is an ordinary two-factor vault again: byte for byte the slots an older reader knows.
let old = pw("the old master password");
assert!(Vault::open_with(&bytes, Unlock::Password(&old), device(&PC)).is_ok());
}
#[test]
fn only_a_two_factor_vault_gets_a_recovery_key() {
// Version 1: one password. A recovery key would be its second way in without a second factor to replace.
let mut v1 = Vault::create(&pw("a version one password"), FAST).unwrap();
assert!(matches!(v1.recovery_create(NOW), Err(Error::NeedTwoFactors)));
// A machine store opens itself; it has nothing to recover and must stay exactly one factor and its slot.
let mut store = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
assert!(matches!(store.recovery_create(NOW), Err(Error::FactorRejected)));
assert!(Vault::open_machine_store(&store.to_bytes().unwrap(), &PC).is_ok());
}
#[test]
fn a_header_with_a_broken_or_a_second_recovery_slot_is_malformed() {
let mut v = vault();
v.recovery_create(NOW).unwrap();
let bytes = v.to_bytes().unwrap();
let plain = vault().to_bytes().unwrap();
// The slot count is the byte after magic (6) and version (2); slots follow as kind, length (u16 LE), payload.
let count = bytes[8] as usize;
assert_eq!(count, plain[8] as usize + 1);
let mut at = 9;
let mut found = None;
for _ in 0..count {
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
if bytes[at] == 5 {
found = Some((at, len));
}
at += 3 + len;
}
let (at, len) = found.expect("a recovery slot, kind 5");
assert_eq!(len, 4 + 32 + 24 + 48);
// A kind this reader does not know.
let mut unknown = bytes.clone();
unknown[at] = 6;
assert!(matches!(Vault::factor_ids(&unknown), Err(Error::Malformed)));
// The slot twice.
let mut twice = bytes[..at + 3 + len].to_vec();
twice.extend_from_slice(&bytes[at..at + 3 + len]);
twice.extend_from_slice(&bytes[at + 3 + len..]);
twice[8] += 1;
assert!(matches!(Vault::factor_ids(&twice), Err(Error::Malformed)));
// A changed byte in the slot: the header is the body's AAD, so the vault does not open at all.
let mut flipped = bytes.clone();
flipped[at + 3 + 10] ^= 1;
let old = pw("the old master password");
assert!(matches!(Vault::open_with(&flipped, Unlock::Password(&old), device(&PC)), Err(Error::Corrupted)));
}
#[test]
fn the_key_and_the_audit_survive_a_reopen_and_ordinary_changes() {
let mut v = vault();
let key = v.recovery_create(NOW).unwrap();
let old = pw("the old master password");
let mut w = Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&old), device(&PC)).unwrap();
// Changing the password, adding and removing a factor: none of them touches the recovery key.
w.change_password(&pw("a changed master password"), FAST).unwrap();
let id = w.add_factor(Unlock::Material(FactorKind::Totp, &[5; 32]), "TOTP").unwrap();
w.remove_factor(&id).unwrap();
assert_eq!(w.recovery_id().as_deref(), Some(key.id()));
let bytes = w.to_bytes().unwrap();
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
}
+5 -1
View File
@@ -322,8 +322,12 @@ fn an_approval_needs_its_run_a_canonical_unexpired_text_and_a_matching_context()
spaced.approval = Some(spaced.approval.unwrap().replace(',', ", "));
invalid(&mut v, &spaced);
let mut late = approval_req("r-42");
late.approval = Some(approval_text("r-42", "Arca", 3601));
late.approval = Some(approval_text("r-42", "Arca", 25 * 3600 + 1));
invalid(&mut v, &late);
// A day ahead is fine (core 0.17.1): a release's approval lives that long.
let mut day = approval_req("r-42");
day.approval = Some(approval_text("r-42", "Arca", 24 * 3600));
assert!(v.signing_check_at(&day, NOW).is_ok());
let mut past = approval_req("r-42");
past.approval = Some(approval_text("r-42", "Arca", 0));
invalid(&mut v, &past);
+386
View File
@@ -0,0 +1,386 @@
//! Standing approvals (core 0.16.0, docs/SIGNING.md "Standing approvals"): a rule Mark grants from a request he is
//! approving, for one repository, key, kind, pipeline and origin. A later request that fits is signed without
//! asking and recorded as `standing`; everything else still needs him.
use custos_vault::security::{Action, Auth, Item};
use custos_vault::signing::{AndroidKey, Approval, Context, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
/// The release set for the pipelines `release` and `deploy` of Arca, Aula and Fabrica, and the test set.
fn vault() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release", "deploy"]), &s(&["Arca", "Aula", "Fabrica"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v
}
fn ctx(pipeline: &str, repo: &str) -> Context {
Context {
repo: repo.into(),
commit: COMMIT.into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: "tag".into(),
file: "Arca_0.7.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "0.7.0".into(),
}
}
fn minisign(repo: &str, pipeline: &str, run: &str) -> Request {
Request {
key: "domi-release".into(),
kind: SignKind::Minisign,
digest: vec![7; 64],
manifest: None,
approval: None,
run: Some(run.into()),
context: ctx(pipeline, repo),
via: Via::Local,
}
}
fn authenticode(repo: &str, run: &str) -> Request {
Request {
key: "domi-code-signing".into(),
kind: SignKind::Authenticode,
digest: vec![9; 32],
..minisign(repo, "release", run)
}
}
fn approval(repo: &str, run: &str, targets: &[&str], via: Via) -> Request {
let targets = targets.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
let text = format!(
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"deploy","version":"0.7.0","targets":[{targets}],"expires":{}}}"#,
NOW / 1000 + 600
);
Request {
key: "domi-approve".into(),
kind: SignKind::Approval,
digest: vec![],
manifest: None,
approval: Some(text),
run: Some(run.into()),
context: Context {
repo: repo.into(),
pipeline: "deploy".into(),
trigger: "manual".into(),
..Default::default()
},
via,
}
}
/// Mark approves `req` on a card (the key's signature that must come before any rule).
fn mark_signs(v: &mut Vault, req: &Request) {
v.signing_sign(req, Approval::Mark, NOW).expect("signed with Mark's click");
}
/// Mark approves `req` with *Always allow*: the rule first, then the signature.
fn always(v: &mut Vault, req: &Request) -> String {
let rule = v.standing_grant(req, NOW + 1).expect("granted");
v.signing_sign(req, Approval::Mark, NOW + 1).unwrap();
rule.id
}
fn outcomes(v: &Vault) -> Vec<Outcome> {
v.signing_audit().iter().map(|e| e.outcome).collect()
}
#[test]
fn a_granted_rule_signs_the_next_matching_request_and_records_it() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
assert!(v.standing_rules().is_empty());
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-2"), NOW).is_none(), "nothing fits before a grant");
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
let rules = v.standing_rules();
assert_eq!(rules.len(), 1);
let r = &rules[0];
assert_eq!(
(r.id.as_str(), r.repo.as_str(), r.key.as_str(), r.pipeline.as_str()),
(id.as_str(), "Arca", "domi-release", "release")
);
assert_eq!((r.kind, r.via, r.granted, r.uses, r.last_used), (SignKind::Minisign, Via::Local, NOW + 1, 0, None));
// The next run: it fits, and signing with the rule records everything an approved entry holds.
let next = minisign("Arca", "release", "r-3");
assert_eq!(v.standing_rule_for(&next, NOW + 5).map(|r| r.id), Some(id.clone()));
let signed = v.signing_sign(&next, Approval::Standing, NOW + 5).expect("signed by the rule");
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Approved, Outcome::Standing]);
let e = v.signing_audit().last().unwrap().clone();
assert_eq!(e.context, ctx("release", "Arca"));
assert_eq!(
(e.key.as_str(), e.kind, e.via, e.run.as_deref(), e.at),
("domi-release", SignKind::Minisign, Via::Local, Some("r-3"), NOW + 5)
);
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
let r = &v.standing_rules()[0];
assert_eq!((r.uses, r.last_used), (1, Some(NOW + 5)));
// Granting the same thing again makes no second rule and keeps the count.
assert_eq!(v.standing_grant(&minisign("Arca", "release", "r-4"), NOW + 9).unwrap().id, id);
assert_eq!(v.standing_rules().len(), 1);
assert_eq!(v.standing_rules()[0].uses, 1);
}
#[test]
fn another_repository_key_kind_pipeline_or_origin_does_not_fit() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
mark_signs(&mut v, &authenticode("Arca", "r-1"));
always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-3"), NOW).is_some());
let sums = format!("{} Arca_0.7.0_x64-setup.exe\n", "c".repeat(64));
let cases: [(&str, Request); 5] = [
("another repository", minisign("Fabrica", "release", "r-3")),
("another pipeline", minisign("Arca", "deploy", "r-3")),
("another key and kind", authenticode("Arca", "r-3")),
(
"another kind of the same key",
Request {
kind: SignKind::Manifest,
digest: vec![],
manifest: Some(sums),
..minisign("Arca", "release", "r-3")
},
),
("the server runner", Request { via: Via::Remote, ..minisign("Arca", "release", "r-3") }),
];
for (what, req) in cases {
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}: the key itself would sign it");
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
let r = v.signing_sign(&req, Approval::Standing, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{what}: {r:?}");
}
assert_eq!(v.standing_rules()[0].uses, 0);
}
#[test]
fn a_request_out_of_the_keys_scope_never_fits_and_narrowing_the_scope_stops_the_rule() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
// Out of scope today: no rule can be made for it.
assert!(v.standing_grant(&minisign("Postea", "release", "r-2"), NOW).is_err());
assert!(v.standing_grant(&minisign("Arca", "nightly", "r-2"), NOW).is_err());
assert!(v.standing_rules().is_empty());
always(&mut v, &minisign("Arca", "release", "r-2"));
// Mark narrows the key: Arca may no longer use it. The rule is still listed and no longer fits.
v.signing_set_scope("domi-release", &s(&["release"]), &s(&["Fabrica"])).unwrap();
let req = minisign("Arca", "release", "r-3");
assert!(v.standing_rule_for(&req, NOW).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW), Err(Refusal::OutOfScope(_))));
assert_eq!(v.standing_rules().len(), 1);
}
#[test]
fn a_request_without_a_run_never_fits() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let no_run = Request { run: None, ..minisign("Arca", "release", "x") };
assert!(v.standing_grant(&no_run, NOW).is_err(), "and cannot start a rule");
always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(v.standing_rule_for(&no_run, NOW).is_none());
assert!(matches!(v.signing_sign(&no_run, Approval::Standing, NOW), Err(Refusal::NeedsApproval(_))));
}
#[test]
fn a_keys_first_signature_cannot_start_a_rule() {
let mut v = vault();
let first = minisign("Arca", "release", "r-1");
assert!(v.standing_can_grant(&first, NOW).is_err());
assert!(v.standing_grant(&first, NOW).is_err(), "the key has never signed");
assert!(v.standing_rules().is_empty());
// A refused or expired card is not a signature either.
v.signing_refuse(&first, Outcome::Refused, None, NOW);
assert!(v.standing_grant(&first, NOW).is_err());
// Mark signs once on the card; from then on the key can have a rule.
mark_signs(&mut v, &first);
assert!(v.standing_can_grant(&minisign("Arca", "release", "r-2"), NOW).is_ok());
// Another key of the same vault has still never signed.
assert!(v.standing_grant(&authenticode("Arca", "r-2"), NOW).is_err());
}
#[test]
fn a_test_key_and_a_server_runners_release_signature_cannot_start_a_rule() {
let mut v = vault();
let test = Request {
key: "domi-test".into(),
context: Context { trigger: "push".into(), ..ctx("ci", "Arca") },
..minisign("Arca", "ci", "r-1")
};
v.signing_sign(&test, Approval::Auto, NOW).unwrap();
assert!(v.standing_grant(&test, NOW).is_err(), "a test key signs without asking anyway");
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let remote = Request { via: Via::Remote, ..minisign("Arca", "release", "r-2") };
assert!(v.standing_can_grant(&remote, NOW).is_err());
assert!(v.standing_grant(&remote, NOW).is_err(), "a release signature asked through the mailbox");
assert!(v.standing_rules().is_empty());
}
#[test]
fn an_approval_rule_holds_only_for_the_targets_it_was_granted_for() {
let mut v = vault();
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
let id = always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
let r = &v.standing_rules()[0];
assert_eq!((r.repo.as_str(), r.pipeline.as_str(), r.via), ("Aula", "deploy", Via::Remote));
assert_eq!(r.targets, s(&["deploy to nixos-vm"]));
assert!(v.standing_rule_for(&approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Remote), NOW).is_some());
// A target Mark has not seen, alone or next to the known one; another repository; the same from this PC.
for (what, req) in [
("a new target", approval("Aula", "r-3", &["publish to Aula"], Via::Remote)),
(
"a new target next to the old",
approval("Aula", "r-3", &["deploy to nixos-vm", "publish to Aula"], Via::Remote),
),
("another repository", approval("Arca", "r-3", &["deploy to nixos-vm"], Via::Remote)),
("this PC's pipe", approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Local)),
] {
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}");
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
}
// Granting again on a card that shows the new target adds it to the same rule.
let wider = approval("Aula", "r-4", &["deploy to nixos-vm", "publish to Aula"], Via::Remote);
assert_eq!(always(&mut v, &wider), id);
assert_eq!(v.standing_rules().len(), 1);
assert_eq!(v.standing_rules()[0].targets, s(&["deploy to nixos-vm", "publish to Aula"]));
let signed =
v.signing_sign(&approval("Aula", "r-5", &["publish to Aula"], Via::Remote), Approval::Standing, NOW + 9);
assert!(signed.is_ok(), "{signed:?}");
assert_eq!(v.signing_audit().last().unwrap().context.file, "approval-r-5.json");
}
#[test]
fn sign_only_with_a_card_pauses_every_rule() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
always(&mut v, &minisign("Arca", "release", "r-2"));
let req = minisign("Arca", "release", "r-3");
v.security_tick(Item::CardSigning, NOW + 2);
assert!(v.standing_rule_for(&req, NOW + 3).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 3), Err(Refusal::NeedsApproval(_))));
assert!(v.standing_can_grant(&req, NOW + 3).is_err(), "and no new rule while it is ticked");
assert_eq!(v.standing_rules().len(), 1, "the rule is kept, paused");
// Other checklist items do not pause it.
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 4);
v.security_tick(Item::NoAutoConnect, NOW + 4);
assert!(v.standing_rule_for(&req, NOW + 5).is_some());
}
#[test]
fn a_revoked_rule_no_longer_fits_and_both_are_in_the_security_audit() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
assert!(!v.standing_revoke("0000000000000000", NOW + 2), "no such rule");
assert!(v.standing_revoke(&id, NOW + 3));
assert!(!v.standing_revoke(&id, NOW + 4), "once");
assert!(v.standing_rules().is_empty());
let req = minisign("Arca", "release", "r-3");
assert!(v.standing_rule_for(&req, NOW + 5).is_none());
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 5), Err(Refusal::NeedsApproval(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
let notes: Vec<(Action, String)> = v
.security_view(NOW + 6)
.audit
.into_iter()
.filter(|e| matches!(e.action, Action::StandingGranted | Action::StandingRevoked))
.map(|e| (e.action, e.detail.unwrap_or_default()))
.collect();
assert_eq!(notes.len(), 2, "{notes:?}");
assert_eq!(notes[0].0, Action::StandingGranted);
assert_eq!(notes[1].0, Action::StandingRevoked);
for (_, d) in &notes {
assert!(
d.contains("Arca") && d.contains("domi-release") && d.contains("minisign") && d.contains("release"),
"{d}"
);
}
// The public note call cannot write them.
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
}
#[test]
fn rules_and_the_standing_outcome_survive_a_reopen() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
always(&mut v, &minisign("Arca", "release", "r-2"));
always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
v.signing_sign(&minisign("Arca", "release", "r-3"), Approval::Standing, NOW + 5).unwrap();
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.standing_rules(), v.standing_rules());
assert_eq!(back.standing_rules().len(), 2);
assert_eq!(back.signing_audit(), v.signing_audit());
// After the restart the rule still answers, and still only what it was granted for.
assert!(back.signing_sign(&minisign("Arca", "release", "r-4"), Approval::Standing, NOW + 9).is_ok());
assert!(back.standing_rule_for(&minisign("Fabrica", "release", "r-4"), NOW + 9).is_none());
assert_eq!(back.standing_rules().iter().find(|r| r.repo == "Arca").unwrap().uses, 2);
}
#[test]
fn signing_with_standing_and_no_rule_is_refused_and_recorded() {
let mut v = vault();
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
let req = minisign("Arca", "release", "r-2");
let r = v.signing_sign(&req, Approval::Standing, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{r:?}");
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Refused]);
assert!(v.signing_audit()[1].signature.is_none());
}
#[test]
fn an_android_keys_rule_signs_its_apks_and_nothing_else() {
let spec = AndroidKey {
id: "postea-android".into(),
name: "Postea Android".into(),
cn: "Postea".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role: Role::Release,
pipelines: s(&["release"]),
repos: s(&["mnovak/Postea"]),
};
let apk = |run: &str| Request {
key: "postea-android".into(),
kind: SignKind::Apk,
digest: vec![3; 128],
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Postea") },
..minisign("mnovak/Postea", "release", run)
};
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create_android(&spec, NOW).unwrap();
// The first signature (the card says so) cannot be the one that starts the rule.
assert!(v.standing_grant(&apk("r-1"), NOW).is_err());
mark_signs(&mut v, &apk("r-1"));
always(&mut v, &apk("r-2"));
let signed = v.signing_sign(&apk("r-3"), Approval::Standing, NOW + 2).expect("an APK fits its rule");
assert_eq!(signed.bytes.len(), 2 * 512, "v2 and v3, RSA-4096");
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
// Postea's rule says nothing about another repository: that is out of the key's scope, as before.
let other = Request {
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Other") },
..apk("r-4")
};
assert!(matches!(v.signing_sign(&other, Approval::Standing, NOW + 3), Err(Refusal::OutOfScope(_))));
}
+485
View File
@@ -0,0 +1,485 @@
//! Team vaults (docs/TEAM.md, core 0.18.0): opening, adding and removing members, the policy, signing every
//! format, replays, target credentials.
use custos_team::external::{ExternalSigner, SignerCredential};
use custos_team::policy::{EnvRule, KeyRole};
use custos_team::request::{Artifact, Format, SignRequest, TargetRequest};
use custos_team::target::{TargetKind, TargetRelease};
use custos_team::{MemberKey, TeamError, verify_proof};
use custos_vault::{Error, NewSigner, NewTarget, SecretString, Vault};
const NOW: i64 = 1_794_000_000_000;
const NOW_S: u64 = 1_794_000_000;
struct Team {
vault: Vault,
a: MemberKey,
b: MemberKey,
}
/// Mark founds a team, makes its keys and adds Petra (comparing her join code).
fn team() -> Team {
let a = MemberKey::generate();
let b = MemberKey::generate();
let mut vault = Vault::create_team("Domi", &a, "Mark", &["mnovak".into()], NOW).unwrap();
vault.team_create_keys(&a.id(), NOW).unwrap();
let code = b.public().join_code();
vault.team_add_member(&b.public(), "Petra", &["petra".into()], &a.id(), &code, NOW).unwrap();
Team { vault, a, b }
}
fn request(vault: &Vault, env: &str, author: &str, format: Format, fabrica: &custos_seal::Recipient) -> String {
let (digest, image) = match format {
Format::Minisign | Format::TauriUpdater => (custos_sign::blake2b512(b"the installer").to_vec(), ""),
Format::Apk => (vec![5u8; 128], ""),
Format::Cosign => (vec![6u8; 32], "registry.example/domi/arca"),
Format::Authenticode => (vec![7u8; 32], ""),
};
SignRequest {
team: vault.team_view().unwrap().id,
id: custos_team::new_id(),
project: "mnovak/Arca".into(),
release: "0.7.0".into(),
env: env.into(),
author: author.into(),
format,
artifact: Artifact {
name: "Arca_0.7.0_x64-setup.exe".into(),
size: 13,
sha256: custos_sign::sha256_hex(b"the installer"),
},
artifact_digest: digest.to_vec(),
image: image.into(),
public: fabrica.public(),
expires: NOW_S + 3600,
}
.canonical()
}
#[test]
fn members_open_the_team_vault_and_outsiders_do_not() {
let t = team();
let bytes = t.vault.to_bytes().unwrap();
let (id, epoch, members) = Vault::team_peek(&bytes).unwrap();
assert_eq!((id.as_str(), epoch, members.len()), (t.vault.team_view().unwrap().id.as_str(), 1, 2));
for k in [&t.a, &t.b] {
let v = Vault::open_team(&bytes, k).unwrap();
assert!(v.is_team());
assert_eq!(v.team_view().unwrap().members.len(), 2);
assert_eq!(v.signing_keys().len(), 4);
}
assert!(matches!(Vault::open_team(&bytes, &MemberKey::generate()), Err(Error::NotAMember)));
// A team vault is not a two-factor vault, and a personal vault is not a team vault.
assert!(Vault::factor_kinds(&bytes).unwrap().is_empty());
let mut personal =
Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 })
.unwrap();
assert!(matches!(Vault::open_team(&personal.to_bytes().unwrap(), &t.a), Err(Error::NotATeam)));
// A changed header byte (a member slot moved to another epoch) does not open.
let mut moved = bytes.clone();
moved[9 + 3 + 32] ^= 1;
assert!(Vault::open_team(&moved, &t.a).is_err());
// The member key lives in the member's own vault and survives a save.
personal.member_key_create(NOW).unwrap();
let again = Vault::open(&personal.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(again.member_key().unwrap().id(), personal.member_key().unwrap().id());
}
#[test]
fn a_wrong_join_code_adds_nobody() {
let mut t = team();
let c = MemberKey::generate();
let wrong = if c.public().join_code() == "111111" { "222222" } else { "111111" };
let e = t.vault.team_add_member(&c.public(), "Eve", &[], &t.a.id(), wrong, NOW).unwrap_err();
assert!(e.to_string().contains("match code"), "{e}");
assert_eq!(t.vault.team_view().unwrap().members.len(), 2);
// An outsider cannot add anyone either.
let code = c.public().join_code();
assert!(t.vault.team_add_member(&c.public(), "Eve", &[], &c.id(), &code, NOW).is_err());
}
/// Mandatory: removing a member rotates the team key; the old member cannot unwrap anything created after.
#[test]
fn a_removed_member_cannot_open_anything_written_after() {
let mut t = team();
let before = t.vault.to_bytes().unwrap();
assert!(Vault::open_team(&before, &t.b).is_ok());
t.vault
.team_add_target(
NewTarget {
kind: TargetKind::SshKey,
name: "web-1".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: "web-1.example".into(),
user: "deploy".into(),
secret: SecretString::from("-----BEGIN OPENSSH PRIVATE KEY-----\nold\n"),
},
&t.a.id(),
NOW,
)
.unwrap();
let removal = t.vault.team_remove_member(&t.b.id(), &t.a.id(), NOW + 1).unwrap();
assert_eq!(removal.epoch, 2);
assert_eq!(removal.rotate, vec!["target web-1".to_string()]);
// Something created after the removal.
t.vault
.team_add_target(
NewTarget {
kind: TargetKind::Registry,
name: "registry".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: String::new(),
user: String::new(),
secret: SecretString::from("new-registry-token-after-removal"),
},
&t.a.id(),
NOW + 2,
)
.unwrap();
let after = t.vault.to_bytes().unwrap();
// B has no slot, and B's old slot (from the earlier file) does not open the new body.
assert!(matches!(Vault::open_team(&after, &t.b), Err(Error::NotAMember)));
let (_, epoch, members) = Vault::team_peek(&after).unwrap();
assert_eq!((epoch, members), (2, vec![t.a.id()]));
let mut spliced = Vec::new();
let (hb, _) = header_len(&before);
let (ha, _) = header_len(&after);
spliced.extend_from_slice(&before[..hb]);
spliced.extend_from_slice(&after[ha..]);
assert!(Vault::open_team(&spliced, &t.b).is_err(), "the old key does not open the new body");
// The new token is in no byte of the file B can read.
assert!(!contains(&after, b"new-registry-token"));
// A still opens it, at epoch 2, and B is listed as removed.
let v = Vault::open_team(&after, &t.a).unwrap();
let view = v.team_view().unwrap();
assert_eq!((view.epoch, view.members.len(), view.removed[0].name.as_str()), (2, 1, "Petra"));
// The last member cannot be removed.
let mut v = v;
assert!(v.team_remove_member(&t.a.id(), &t.a.id(), NOW).is_err());
}
fn header_len(bytes: &[u8]) -> (usize, ()) {
let count = bytes[8] as usize;
let mut at = 9;
for _ in 0..count {
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
at += 3 + len;
}
(at + 24, ())
}
fn contains(hay: &[u8], needle: &[u8]) -> bool {
hay.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn a_member_refuses_an_older_copy_or_another_identity() {
let mut t = team();
let mut own =
Vault::create(&SecretString::from("pw"), custos_vault::KdfParams { m_cost_kib: 8, t_cost: 1, p_cost: 1 })
.unwrap();
// Mark's own vault holds his member key; the team was made with the same key.
let c = MemberKey::generate();
let code = c.public().join_code();
t.vault.team_add_member(&c.public(), "Third", &[], &t.a.id(), &code, NOW).unwrap();
own.member_key_create(NOW).unwrap();
let old = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
t.vault.team_remove_member(&c.id(), &t.a.id(), NOW).unwrap();
let new = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
own.member_note_team(&new).unwrap();
assert!(matches!(own.member_note_team(&old), Err(Error::TeamRollback)));
let impostor = Vault::create_team("Domi", &t.a, "Mark", &[], NOW).unwrap();
own.member_note_team(&impostor).unwrap(); // another id: a team of its own
assert_eq!(own.member_teams().len(), 2);
}
#[test]
fn the_policy_is_set_per_environment_signed_and_kept() {
let mut t = team();
let p = t
.vault
.team_set_rule(
EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec![t.b.id()] },
&t.a.id(),
NOW,
)
.unwrap();
assert_eq!(p.rev, 2);
assert!(
t.vault
.team_set_rule(
EnvRule { env: "staging".into(), approvals: 1, others: true, approvers: vec!["ab".repeat(16)] },
&t.a.id(),
NOW
)
.is_err()
);
let v = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.b).unwrap();
let (text, sig) = v.team_policy_signed().unwrap();
assert!(custos_team::member::verify_policy_sig(&v.team_identity().unwrap(), &text, &sig));
assert_eq!(v.team_policy().unwrap().rule("staging").unwrap().approvers, vec![t.b.id()]);
assert!(
v.team_audit().unwrap().iter().any(|e| e.detail.as_deref() == Some("staging: 1 approval(s), not the author"))
);
}
/// Mandatory: a signing request with a wrong or replayed match code is refused.
#[test]
fn wrong_and_replayed_match_codes_are_refused() {
let mut t = team();
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let code = fabrica.match_code();
let wrong = if code == "000000" { "000001" } else { "000000" };
// Petra's card showed another code: nothing is signed, nothing recorded as seen.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(wrong), None, NOW).unwrap_err(), TeamError::WrongMatch);
assert_eq!(t.vault.team_approve(&text, &t.b, wrong, NOW).unwrap_err(), TeamError::WrongMatch);
// The author may not approve production in a team of two.
assert!(matches!(t.vault.team_sign(&text, &[], &t.a, Some(&code), None, NOW), Err(TeamError::NotEligible(_))));
// Petra with the right code signs.
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap();
// A refusal after the signature is refused too: nothing contradicts what was signed (core 0.18.1).
assert!(t.vault.team_refuse(&text, &t.a.id(), "late", NOW).unwrap_err().to_string().contains("replay"));
// The same request again (a replay): refused, by this vault, whoever asks.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::Replayed);
assert_eq!(t.vault.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
// ... also after a save and reopen, and in Mark's copy once he has the saved file.
let reopened = Vault::open_team(&t.vault.to_bytes().unwrap(), &t.a).unwrap();
assert_eq!(reopened.team_check_request(&text, NOW).unwrap_err(), TeamError::Replayed);
// Petra's approval statement from this request does not count for another one.
let other = request(&t.vault, "production", "mnovak", Format::Minisign, &custos_seal::Recipient::generate());
let statements: Vec<_> = custos_team::proof::ProofBody::parse(&reply.proof.text).unwrap().approvals;
let req = SignRequest::parse(&other).unwrap();
let eval = t.vault.team_evaluate(&req, &statements).unwrap();
assert!(eval.counted.is_empty());
// An expired request.
let late = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
assert_eq!(
t.vault.team_sign(&late, &[], &t.a, Some(&code), None, NOW + 3_601_000).unwrap_err(),
TeamError::Expired
);
}
#[test]
fn two_approvals_collect_statements_and_the_last_approver_signs() {
let mut t = team();
let c = MemberKey::generate();
let code = c.public().join_code();
t.vault.team_add_member(&c.public(), "Jan", &[], &t.a.id(), &code, NOW).unwrap();
t.vault
.team_set_rule(
EnvRule { env: "production".into(), approvals: 2, others: true, approvers: vec![] },
&t.a.id(),
NOW,
)
.unwrap();
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let code = fabrica.match_code();
// Petra alone is not enough: she approves (a statement), she does not sign.
assert_eq!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).unwrap_err(), TeamError::NeedMore(1));
let petra = t.vault.team_approve(&text, &t.b, &code, NOW).unwrap();
// Mark's statement (the author) does not count; Jan's does, and Jan signs.
let reply = t.vault.team_sign(&text, &[petra.clone()], &c, Some(&code), None, NOW).unwrap();
let v = verify_proof(&reply.proof, &t.vault.team_identity().unwrap(), &text, reply.envelope()).unwrap();
assert_eq!(v.approvers.len(), 2);
assert_eq!(v.signer, c.id());
let audit = t.vault.signing_audit().last().unwrap().clone();
assert_eq!(audit.by.as_deref(), Some(c.id().as_str()));
assert_eq!(audit.approvers.len(), 2);
assert_eq!(audit.env.as_deref(), Some("production"));
}
struct FakeHsm(custos_sign::RsaSecret);
impl ExternalSigner for FakeHsm {
fn sign_digest(&self, signer: &SignerCredential<'_>, digest: &[u8; 32]) -> Result<Vec<u8>, String> {
if signer.secret != "hsm-pin" {
return Err("wrong credential".into());
}
custos_sign::authenticode(&self.0, digest).map_err(|e| e.to_string())
}
}
/// Every format signs and the proof checks; the signatures verify (minisign-verify is minisign's and Tauri's own
/// verifier; cosign with p256 here and openssl in custos-sign's tests).
#[test]
fn every_format_signs_with_the_right_key_and_verifies() {
let mut t = team();
let identity = t.vault.team_identity().unwrap();
t.vault
.team_create_android(
&custos_vault::signing::AndroidKey {
id: "arca-android".into(),
name: "Arca Android".into(),
cn: "Arca".into(),
o: "Domi".into(),
c: "CZ".into(),
role: custos_vault::signing::Role::Release,
pipelines: vec!["*".into()],
repos: vec!["mnovak/Arca".into()],
},
&t.a.id(),
NOW,
)
.unwrap();
let hsm = custos_sign::new_root("Fake HSM", 1).unwrap();
t.vault
.team_add_signer(
NewSigner {
name: "Fake cloud signer".into(),
adapter: "command".into(),
endpoint: "https://signer.example".into(),
account: "domi".into(),
secret: SecretString::from("hsm-pin"),
certificate: hsm.cert_der.clone(),
},
&t.a.id(),
NOW,
)
.unwrap();
let ext = FakeHsm(hsm.secret);
for format in [Format::Minisign, Format::TauriUpdater, Format::Cosign, Format::Apk, Format::Authenticode] {
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "production", "mnovak", format, &fabrica);
let reply = t.vault.team_sign(&text, &[], &t.b, Some(&fabrica.match_code()), Some(&ext), NOW).unwrap();
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
assert_eq!(v.role, KeyRole::Release, "{format:?}");
assert_eq!(reply.signer.name, "Petra");
match format {
Format::Minisign | Format::TauriUpdater => {
assert_eq!(reply.key.id, "team-release");
let minisig = if format == Format::TauriUpdater {
custos_sign::tauri_updater_open(&reply.signature).unwrap()
} else {
reply.signature.clone()
};
let pk = minisign_verify::PublicKey::decode(&reply.key.public).unwrap();
pk.verify(b"the installer", &minisign_verify::Signature::decode(&minisig).unwrap(), true).unwrap();
}
Format::Cosign => {
assert_eq!(reply.key.id, "team-cosign");
let payload = reply.payload.as_deref().unwrap();
assert!(payload.contains("\"docker-reference\":\"registry.example/domi/arca\""));
let der = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
assert!(custos_sign::cosign_verify(&reply.key.public, payload.as_bytes(), &der));
}
Format::Apk => {
assert_eq!(reply.key.id, "arca-android");
let sig = data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap();
assert_eq!(sig.len(), 2 * 512);
assert!(reply.key.public.starts_with("-----BEGIN CERTIFICATE-----"));
}
Format::Authenticode => {
assert!(reply.key.id.starts_with("signer:"));
assert_eq!(data_encoding::BASE64.decode(reply.signature.as_bytes()).unwrap().len(), 384);
}
}
}
// Preview: 0 approvals, the test key, no code needed; a release key never signs it.
let fabrica = custos_seal::Recipient::generate();
let text = request(&t.vault, "preview", "mnovak", Format::Minisign, &fabrica);
let reply = t.vault.team_sign(&text, &[], &t.a, None, None, NOW).unwrap();
assert_eq!(reply.key.id, "team-preview");
let v = verify_proof(&reply.proof, &identity, &text, reply.envelope()).unwrap();
assert_eq!(v.role, KeyRole::Test);
// Authenticode is never signed without an approval, and not without the adapter.
let text = request(&t.vault, "preview", "mnovak", Format::Authenticode, &fabrica);
assert!(t.vault.team_sign(&text, &[], &t.a, None, Some(&ext), NOW).is_err());
let text = request(&t.vault, "production", "mnovak", Format::Authenticode, &custos_seal::Recipient::generate());
let code = SignRequest::parse(&text).unwrap().match_code();
assert!(t.vault.team_sign(&text, &[], &t.b, Some(&code), None, NOW).is_err());
}
#[test]
fn a_target_credential_is_released_once_for_a_signed_deployment_of_its_project_and_environment() {
let mut t = team();
let target = t
.vault
.team_add_target(
NewTarget {
kind: TargetKind::Kubeconfig,
name: "prod cluster".into(),
project: "mnovak/Arca".into(),
env: "production".into(),
host: "k8s.example".into(),
user: "fabrica".into(),
secret: SecretString::from("apiVersion: v1\nkind: Config\n"),
},
&t.a.id(),
NOW,
)
.unwrap();
assert!(!format!("{:?}", t.vault.team_targets().unwrap()).contains("apiVersion"));
let team_id = t.vault.team_view().unwrap().id;
let fabrica = custos_seal::Recipient::generate();
let ticket_of = |r: &custos_team::reply::SignReply| -> [u8; 32] {
data_encoding::BASE64.decode(r.ticket.as_deref().unwrap().as_bytes()).unwrap().try_into().unwrap()
};
let ask = |deployment: &str, ticket: &[u8; 32]| {
TargetRequest {
team: team_id.clone(),
id: custos_team::new_id(),
target: target.clone(),
deployment: deployment.into(),
public: fabrica.public(),
expires: NOW_S + 600,
mac: [0; 32],
}
.sign_with(ticket)
.canonical()
};
// No signed deployment yet.
let unsigned = "ab".repeat(32);
assert!(t.vault.team_target_release(&ask(&unsigned, &[1; 32]), &t.b.id(), NOW).is_err());
// A staging deployment is not a production one.
let staging = request(&t.vault, "staging", "mnovak", Format::Minisign, &fabrica);
let r = t.vault.team_sign(&staging, &[], &t.a, Some(&fabrica.match_code()), None, NOW).unwrap();
assert!(t.vault.team_target_release(&ask(&r.request, &ticket_of(&r)), &t.b.id(), NOW).is_err());
let prod = request(&t.vault, "production", "mnovak", Format::Minisign, &fabrica);
let r = t.vault.team_sign(&prod, &[], &t.b, Some(&fabrica.match_code()), None, NOW).unwrap();
// Someone who knows the deployment's hash (the service, another connection) but not its ticket gets nothing.
let e = t.vault.team_target_release(&ask(&r.request, &[7; 32]), &t.b.id(), NOW).unwrap_err();
assert!(e.to_string().contains("ticket"), "{e}");
let ask = |deployment: &str| ask(deployment, &ticket_of(&r));
let (json, req) = t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap();
let released: TargetRelease = serde_json::from_str(&json).unwrap();
assert_eq!((released.secret.as_str(), released.env.as_str()), ("apiVersion: v1\nkind: Config\n", "production"));
assert!(!format!("{released:?}").contains("apiVersion"));
assert_eq!(req.reply_context(), format!("team-target:{}", req.id).into_bytes());
// Once per deployment.
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW).unwrap_err().to_string().contains("replay"));
// Too late: a deployment signed more than 25 hours ago.
assert!(t.vault.team_target_release(&ask(&r.request), &t.b.id(), NOW + 26 * 3_600_000).is_err());
assert!(t.vault.team_audit().unwrap().iter().any(|e| e.action == custos_vault::TeamAction::TargetReleased));
}
#[test]
fn nothing_secret_prints_or_reaches_a_view() {
let mut t = team();
t.vault
.team_add_signer(
NewSigner {
name: "HSM".into(),
adapter: "command".into(),
endpoint: String::new(),
account: String::new(),
secret: SecretString::from("very-secret-pin-123"),
certificate: vec![],
},
&t.a.id(),
NOW,
)
.unwrap();
let shown = format!(
"{:?} {:?} {:?} {:?}",
t.vault,
t.vault.team_view(),
t.vault.team_signers().unwrap(),
serde_json::to_string(&t.vault.team_view()).unwrap()
);
assert!(!shown.contains("very-secret-pin-123"));
assert!(!contains(&t.vault.to_bytes().unwrap(), b"very-secret-pin-123"));
}
+130
View File
@@ -0,0 +1,130 @@
# Custos in the browser
Version 2 of the browser extension (core 0.20.0): Firefox, Edge and Chrome on Windows, from one source; logins
and their 2FA codes, and saving a new login. Passkeys come later.
The extension, its native host and the rule that decides which login belongs on which page are all in this
public repository, so anyone can read what the browser side does. The desktop app (the private `Custos`
repo) holds the vault and answers the host; its side is `docs/13_browser.md` there.
```
page ─(content script)─► background ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
extension/content.js extension/background.js crates/custos-native the desktop app
```
## The pieces
| Piece | What it does | What it never does |
|:--|:--|:--|
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on a (trusted) click asks for the logins of *its own frame*, and fills the one the person picks: username and password, or only the 2FA code on a page that asks only for that. When a form is sent with a password the person typed (not one Custos filled), offers to save it. | Fill without a click; read anything from Custos before the list is opened; put a secret anywhere but its field; trust what the page says about its own address. |
| `extension/popup.*` | The toolbar popup: the logins for the active tab, a 2FA code on request, a login offered for saving, and this connection's match code. A click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
| `extension/background.js` | Owns the one connection to the native host; turns each request into a `browser_*` op, with the frame's origin from **`sender.url`** and its page's from **`sender.tab.url`** (as the browser reports them). Holds a login offered for saving in memory, for its tab, at most 3 minutes. | Accept messages from pages or other extensions (`sender.id` must be its own); ask for a frame whose real origin is not its URL's (`sender.origin`, e.g. a sandboxed frame); write anything to `storage`. |
| `crates/custos-native` | The native messaging host. Checks who started it (`custos_browser::caller`); reads frames from stdin, **rebuilds** each request from its known fields, adds its connection's `session`, forwards it to the Custos pipe and returns the answer. | Answer an extension that is not Custos's (`not_allowed`, nothing reaches Custos); forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed messages are zeroized). |
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match`, `fill_allowed` (which login fits which frame of which page), `caller`, and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
| `tools/extension.mjs` | Builds `target/extension/firefox/` and `…/chromium/` from the one source with each browser's manifest (`extension/manifest.<browser>.json`) and the workspace version; `--zip` writes reproducible packages for AMO and the stores. | Differ per browser: the scripts are the same files. |
## Which login goes where (`custos-browser`)
A page's origin is `scheme://host[:port]`, host lowercased, trailing dot removed. A login's stored `url`
fields (an item may have several) match a page when:
1. the page is **fillable**: `https`, or plain `http` only on this machine (`localhost`, `*.localhost`,
`127.0.0.1`, `[::1]`). Plain http on the internet is never filled, even for a login saved with `http://`;
2. the schemes are equal (a stored URL without a scheme means `https`);
3. the ports are equal (the stored URL's port, or the scheme's default when it names none);
4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it
(**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent
or to a sibling. A login for an IP address, a bare name (`cz`) or a **public suffix** (`co.uk`, `github.io`,
`herokuapp.com`: Mozilla's Public Suffix List, the `psl` crate) matches only that exact host, because the
subdomains of a public suffix belong to different people;
5. **in a frame** (`fill_allowed`): the frame matches, and when the frame is not the top page, the top page
matches too. `evil.net` framing `github.com/login` gets nothing, and neither does an ad frame on
`github.com`.
URLs with userinfo (`https://bank.cz@evil.net`), a port that is not only digits (`:+443`) or a host that is not
ASCII (the browser reports punycode, and that is what is compared) are refused outright. Look-alikes (`github.com.evil.net`,
`githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered
before subdomain matches, then by title; at most 50 logins per page.
## The messages
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON (the same in Firefox and Chromium). The
host accepts at most 64 KiB per message (the desktop pipe's limit). Every request may carry `seq` (a number); the
answer carries it back. The host adds `app`, `browser` (`firefox` from its arguments; `edge`, `chrome` or
`chromium` as the extension says, a label) and `session` (64 hex digits, random per connection) to each.
| Extension → host | Answer |
|:--|:--|
| `{"op":"browser_status"}` | `{"ok":true,"code":"123456"}`: the session's match code |
| `{"op":"browser_match","origin","top"}` | `{"ok":true,"logins":[{"id","title","username","totp"}]}` (`totp`: it has a 2FA code); never a secret |
| `{"op":"browser_fill","id","origin","top"}` | `{"ok":true,"username","password","totp"}` only if that login may go into that frame of that page, else `no_match` |
| `{"op":"browser_totp","id","origin","top"}` | `{"ok":true,"totp","remaining"}` (seconds left) under the same rule; `no_totp` without one |
| `{"op":"browser_save","origin","top","username","password"[,"title"]}` | after Custos's card: `{"ok":true,"saved":"new"/"updated"/"unchanged"}`, or `refused` |
Limits: `origin`, `top` ≤ 2 KiB, `id` ≤ 128 bytes, `username` ≤ 1 KiB, `password` 1 byte to 4 KiB, `title`
≤ 200 bytes. Errors the extension turns into a sentence: `not_connected` (no host registered), `not_allowed`
(not the Custos extension), `not_running`, `not_custos` (the pipe's server is not `custos.exe`: nothing was sent),
`locked`, `denied`, `refused`, `not_found`, `no_match`, `no_totp`, `no_answer`, `bad_request`.
## What Custos checks (the desktop's side, summarised)
- The host is a Domi client like any other: Custos identifies it by its executable and asks the person once
whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the
`web-logins` namespace and the browser ops reach nothing else.
- Custos parses both origins again with `custos-browser` and checks the login with `fill_allowed` on **every**
`browser_fill` and `browser_totp`, whatever the extension asked for before.
- The grant card shows the session's match code, the one the popup shows. Every fill, code and save goes in the
vault's audit with that code.
- `browser_save` always shows a card (*Save* / *Don't save*): a new *Web login* for the origin, or, when a login
of that site has the same username, its new password. An identical login is `unchanged`, without a card.
- Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then
answers `locked`.
## Registration and the extension ids
| Browser | Extension id | Host manifest | Registry (HKCU, per user) |
|:--|:--|:--|:--|
| Firefox | `custos@marek-novak.cz` (`browser_specific_settings.gecko.id`) | `"allowed_extensions": ["custos@marek-novak.cz"]` | `Software\Mozilla\NativeMessagingHosts\cz.marek_novak.custos` |
| Edge | `jchkapmceepdnlhagfppeckggaecdcmn` (the `key` in `manifest.chromium.json`) | `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]` | `Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` |
| Chrome | the same | the same | `Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos` |
The desktop writes both host manifests and registers them. The Chromium `key` fixes the id however the extension
is loaded; the private key that matches it is not in this repository (it is held in Custos) and is needed only to
pack a `.crx`, or for the first upload to the Chrome Web Store, to keep the id. Release Firefox installs only
add-ons signed by Mozilla: the Firefox zip is signed through AMO as an *unlisted* (self-distributed) add-on.
## Threat model, briefly
- A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list
are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI.
A page *can* read what was filled into its own fields: that is what filling is.
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins, and those
only if the page around it matches them too. A good site framed by a malicious page gets nothing.
- Another **extension** cannot message this one (`sender.id`), cannot start the host (`allowed_origins`,
`allowed_extensions`), and if a stray manifest let it, the host answers it only `not_allowed` (`caller`).
- A page can make the extension *offer* to save a login for **its own** origin, with values of its choosing; it
is saved only on Custos's card, which names the site.
- A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe
server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can
replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.)
- The extension holds no secret at rest. Its only state is the open native port and, for a login offered for
saving, that login in the background's memory for at most 3 minutes (JavaScript strings cannot be wiped;
they are dropped).
## Not yet
Passkeys (WebAuthn through the extension), filling cards, other operating systems.
## Tests
```
cargo test -p custos-browser -p custos-native
node tools/extension-test.mjs
```
`custos-browser` covers origin parsing, look-alikes (punycode twins, extra labels, userinfo, encoded dots,
backslashes, odd ports), public suffixes, frames and their pages, ports and schemes, bare names and IPs,
best-of-several, the callers and the frames. `custos-native` covers that only the five ops pass, rebuilt from
known fields, and that another extension gets `not_allowed` without reaching Custos. `tools/extension-test.mjs`
runs the background script against a fake browser: origins from the browser and never from the message, frames,
sandboxed and blank frames, other extensions, a locked Custos, and a login offered for saving that never comes back
out. The desktop repo has the pipe tests and the end-to-end runs in each browser.
+52
View File
@@ -79,6 +79,10 @@ is the whole header, as in v1.
### Limits a reader enforces
- 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed.
- At most one recovery slot (kind 5, core 0.17.0), of exactly 108 bytes, and none in a machine store.
- A **team vault** (core 0.18.0, docs/TEAM.md) has 1 ..= 32 member slots (kind 6, 144 bytes) and no other slot;
a file that mixes member slots with any other kind is malformed. It is opened with `Vault::open_team` and a
member key, never with factors.
- A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed.
- Argon2 limits as in v1, checked before any work.
- Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work.
@@ -96,6 +100,54 @@ slot, then the body.
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
| A machine store: its one device factor unwraps, then the single slot | — |
## The recovery key (core 0.17.0)
A two-factor vault can have **one recovery key**: 32 random bytes that open the vault alone, for the day the
factors are gone (a forgotten password and a dead PC, a lost phone and a reinstalled Windows). It is the one
deliberate exception to "never one secret", and it is hedged accordingly:
- **It is made on request and returned once** (`Vault::recovery_create`). It is in no file and no log. The app
shows or prints it and keeps nothing. Making a new one replaces the old one.
- **It is never an everyday unlock.** `Vault::recover` is the only call that takes it. Before it returns the vault
it drops **every** factor, makes the new master password and one new second factor the vault's two factors, and
replaces the recovery key (the new one is returned, once). Whoever held the old password, an old PC key or a
phone holds nothing of the vault from the next save on. No `open` or `open_with` accepts a recovery key, as a
password or as material.
- **It is audited** in the security member: `recovery-created`, `recovery-removed`, `recovered`, each with the
key's id (never the key).
- A version-1 vault and a machine-key vault have none (`NeedTwoFactors`, `FactorRejected`).
- `recover` writes nothing. Until the caller saves, the file is as it was and the old factors still open it.
- The vault key stays the same across a recovery: a **copy of the file from before** still opens with the old
factors and the old recovery key. A recovery takes back the vault, not its old copies.
**As printed:** `id (4 bytes) ‖ key (32 bytes) ‖ check (4 bytes)` in base32 without padding, 64 characters in 8
groups of 8 (`A–Z`, `2–7`). The check is the first 4 bytes of `SHA-256("custos recovery key v1" ‖ id ‖ key)`.
A reader ignores case, spaces and hyphens; any other character, another length or a failed check is
`RecoveryKeyMistyped`, told apart from `WrongRecoveryKey` (a well-formed key that is not this vault's current one)
before the vault is touched. The **id** (8 hex characters) is not secret: it is in the header, shown in Settings
and printed next to the key, so the paper can be matched to the vault.
```
kind 5, recovery slot (at most one; never together with a single slot)
4 id
32 salt
24 wrap nonce
48 wrapped vault key KEK = HKDF-SHA256(key, salt, info "custos recovery v2")
AAD = magic ‖ version ‖ kind ‖ id ‖ salt ‖ nonce
```
It is not a factor: it has no factor slot, no pair slots and no entry in the body's `factors`, it does not count
toward the two factors or the limit of 8, and `factor_ids` does not list it. `Vault::recovery_id_of(bytes)` reads
its id from the header.
**Older readers.** A reader before core 0.17.0 knows slot kinds 2 to 4 and treats kind 5 as malformed: a vault
with a recovery key does not open in an older Custos ("the vault file is malformed"), and is not rewritten by
one. Removing the key (`recovery_remove`) makes the file readable by older readers again, apart from the three
audit actions, which they refuse like any unknown action (docs/FORMAT.md, "The security member").
**What it costs.** The paper is a complete way in. It is 256 bits, so it is not guessed; it is stolen, copied or
photographed. Keep it away from the PC and from the other vault's paper. Losing it loses nothing: make a new one.
## Which factors a file has
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
+15 -3
View File
@@ -132,6 +132,10 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
- `provision` (optional, core 0.11.0): the Provisio audit, every outcome of a server's *ask* or *offer* (the app's
docs/10_provisio.md). An older Custos ignores it when it reads and drops it when it saves, so every Custos that
saves the vault must be 0.11.0 or later. See "The provision audit" below.
- `kind`, `team` (core 0.18.0): a team vault's body is `"kind": "team"` with the `team` member (docs/TEAM.md); no
other vault has either, and a team vault has no `factors`, `identity` or `member`.
- `member` (optional, core 0.18.0): a person's member key and the teams it opened (docs/TEAM.md). An older Custos
drops it when it saves, so every Custos that saves a member's vault must be 0.18.0 or later.
- `security` (optional, core 0.12.0): the security level, the hardening checklist and their audit (the app's
docs/11_runs_and_levels.md). An older Custos ignores it when it reads and drops it when it saves (the level falls
back to Standard, the checklist to unticked), so every Custos that saves the vault must be 0.12.0 or later. See
@@ -140,7 +144,15 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
**Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each
member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are
written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or
outcome `confirmed`. A vault without them still opens in core 0.11.0.
outcome `confirmed`. A vault without them still opens in core 0.11.0. Core 0.14.0 adds two more: a `signing` key
of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault that holds either does not open in a
core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions
`standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing
approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a
member older cores ignore and drop. Core 0.19.0 adds the member `signing.android` (the Android grant, docs/SIGNING.md "The Android
grant"), which older cores ignore and drop (the grant is lost, never widened). It adds no closed-list value:
a key the grant makes is `standing-granted` in the security audit (core 0.19.1), so a vault with the grant still
opens in every core since 0.16.0, as the phone app and the web vault may be.
### The provision audit (core 0.11.0)
@@ -204,7 +216,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed |
| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` |
| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo |
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes) names what happened, never a value: 1–500 characters, no control characters |
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked` (also for the Android grant and the keys it makes), or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
The **level** is computed, never stored:
@@ -226,7 +238,7 @@ the first change after it, not by reading.
existing item: an `ask --generate` or an `offer` into `arca/`, `custos/`, `fabrica/`, `aula/`, `gitea/`, an offer
into the Claude Code store, a TOTP offer unless `totp-on-phone`; never `display`) and `unattended_sign` (a
machine-key vault, a request with a run, not Hardened, `card-signing` not ticked, the kinds `minisign`,
`manifest`, `authenticode`, `approval`). The app enforces them; the server never decides.
`manifest`, `authenticode`, `approval`; never `apk`, core 0.14.0). The app enforces them; the server never decides.
- Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not
know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the
rules above does not open (`Corrupted`).
+171 -5
View File
@@ -1,4 +1,4 @@
# Signing keys (core 0.9.0; deploy approvals 0.12.0)
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0; teams 0.18.0; the Android grant 0.19.0)
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
@@ -46,6 +46,8 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random |
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
| `ecdsa-p256` (core 0.18.0) | ECDSA P-256; `secret` is the 32-byte scalar; a team vault's cosign key (docs/TEAM.md) | only `cosign`, only through `team_sign` | random |
| `android` (core 0.14.0) | RSA-4096; `secret` PKCS#8 DER; `cert` a self-signed X.509 v3 certificate, valid 100 years, no EKU, under no root | only `apk` | random |
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and
(since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the
@@ -55,6 +57,16 @@ release keys' scope. A vault whose release keys were made by an older core gets
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
never trusted by Mark's PCs.
*Create Android key* (`signing_create_android`, core 0.14.0) makes one Android app signing key at a time, with the
id, name, certificate subject (`CN`, `O`, a two-letter `C`), role and scope the app gives it; an id is used once.
An Android key is a key of its own, not part of a set: it never counts as the release or test set (core 0.14.1).
The app makes `postea-android` (`CN=Postea, O=Marek Novak, C=CZ`, release, pipeline `release`, repo
`mnovak/Postea`) and its test twin `domi-test-android` (`CN=Domi Test Android, O=Domi, C=CZ`, test). An Android
key's certificate *is* the app's identity: Android accepts an update only when it is signed by the same certificate,
for the app's whole life. Its loss ends the app's updates for good, and there is no phrase to recover it from (the
vault has none), so **the vault must have two backups off the PC before the first real signature**. Its public
half is the certificate (`signing_export_cert`).
`pipelines` and `repos` list who may ask (pipeline names, repository folder names; `*` means any). A request from
a pipeline or repo not on its key's lists is refused **even when approved**. Release keys always need approval.
Test keys are approved automatically, but only for requests whose `trigger` is not `tag` (a manual run, a push).
@@ -66,6 +78,9 @@ Certificates:
`extKeyUsage` codeSigning, subject and authority key identifiers; both signed with sha256WithRSAEncryption.
The root's certificate (public part only) is exported as DER (`.cer`) to install as Trusted Root and Trusted
Publisher.
- android: subject and issuer `CN=<cn>, O=<o>, C=<c>` (encoded C, O, CN; `C` a PrintableString), validity 100 × 365
days, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation, subject and authority key
identifiers (both of its own key), no `extKeyUsage`; sha256WithRSAEncryption by its own key.
## Signature kinds
@@ -77,6 +92,7 @@ A request names a key, a kind and what to sign. Custos never receives the file.
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
| `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it |
| `apk` (core 0.14.0) | `digest`: 1 to 4 SHA-512 digests of APK Signature Scheme signed data, concatenated (64·n bytes) | the n RSA PKCS#1 v1.5 signatures (512 bytes each), concatenated in the same order |
Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every
request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a
@@ -125,7 +141,7 @@ exactly this order:
| `repo`, `pipeline`, `version` | 1–64 of `[A-Za-z0-9._+-]` |
| `commit` | 40 lower-case hex digits |
| `targets` | 1–16 strings of 1–80 characters (Unicode scalar values); no control characters, and none of the invisible ones that change how a line looks on the card (U+00AD, U+061C, U+180E, U+200B–U+200F, U+2028–U+202E, U+2060–U+2069, U+FEFF) |
| `expires` | Unix seconds, later than now and at most 3 600 s after now (checked before the card and again when signing) |
| `expires` | Unix seconds, later than now and at most 90 000 s (25 hours) after now (checked before the card and again when signing). Before core 0.17.1 the limit was 3 600 s; a release's approval now lives a day, so its card can wait for Mark that long |
Strings use JSON's minimal escaping: a quote is written `\"`, a backslash `\\`, every other character as
itself (no `\u` escapes, no `\/`; control characters cannot occur). There is no newline at the end. Custos
@@ -158,6 +174,134 @@ Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the
with "terminated in a root certificate which is not trusted", and a wrong signature gives "No signature found".
`signtool verify /pa` on a machine that trusts the root is the last check, done where the root is installed.
### apk (core 0.14.0)
An APK is signed by Google's apksig (`apksigner.jar` from the Android SDK build-tools) on the build's side; Custos
signs only what apksig's signer would sign. APK Signature Scheme v2 and v3 each sign one *signed data* block (the
APK's content digests, the certificate, attributes; v3 adds the SDK range), so a v2+v3 APK needs two signatures.
apksig picks `RSA_PKCS1_V1_5_WITH_SHA512` (`SHA512withRSA`) for every RSA key over 3072 bits and has no way to
choose otherwise, so the kind takes **SHA-512** digests and signs each with the SHA-512 DigestInfo:
- `digest` is 64·n bytes, n from 1 to 4: the SHA-512 of each signed data block, in the order the build wants the
signatures back. Anything else is `invalid`. The context's `file` (the APK's name) is required, as for minisign.
- The answer is the n signatures concatenated, 512 bytes each for RSA-4096. One request, one card line, one audit
entry (its `signature` is the SHA-256 of all of them), so a release run raises **one** card for its APK.
- `apk` is signed only by an `android` key, and an `android` key signs nothing else: an Authenticode key cannot sign
an APK and an Android key cannot sign an exe (`invalid`).
- `apk` is not one of the kinds the hands-off vault may sign without a card (FORMAT.md, `unattended_sign`): an
Android key cannot be revoked or replaced, so its signatures always ask.
The client (`custos-sign apk`, in the app's repository) runs apksig twice: once with a stand-in signer that records
the digests and answers with placeholder signatures (the signed data does not depend on the signatures), then, with
Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did
not record. It verifies the result with apksig's verifier before it writes the APK.
### Team kinds (core 0.18.0)
`tauri-updater` (the base64 of a `minisign` file) and `cosign` (ECDSA P-256 over cosign's simple-signing payload)
exist only in team vaults and are signed only by `Vault::team_sign` (docs/TEAM.md); `signing_sign` refuses them
(`invalid`). A team audit entry carries `by`, `env`, `request` and `approvers`; its context's `repo` is the project,
`pipeline` the environment, `version` the release, `trigger` `team`. A core before 0.18.0 refuses a vault holding
any of these values (`Corrupted`); only team vaults do.
## Standing approvals (core 0.16.0)
A release key always asks. A **standing approval** is Mark's answer kept: "always allow this, for this repository".
It is a rule in `signing.standing`, made only from a request Mark is approving on a card, and a later request that
fits it is signed without a card.
```json
"standing": [
{ "id": "5b0c1e0f6a2d4c11", "repo": "mnovak/Postea", "key": "postea-android", "keyCreated": 1793750000000,
"kind": "apk", "pipeline": "release", "via": "local", "granted": 1794000000000, "lastUsed": 1794100000000, "uses": 3 },
{ "id": "9d3e…", "repo": "Aula", "key": "domi-approve", "keyCreated": 1793750000000, "kind": "approval",
"pipeline": "deploy", "via": "remote", "targets": ["deploy to nixos-vm"], "granted": 1794000000000, "uses": 0 }
]
```
**What a rule is.** Five things, all compared exactly (no `*`, no prefix): the repository and the pipeline as the
scope check reads them (an approval's own `repo` and `pipeline`), the key (its id and its `created` time, so a key
made later under the same id never inherits a rule), the kind, and `via` (the Domi pipe or the factor service's
mailbox). A rule for an `approval` also keeps the targets it was granted for. `id` is the first 16 hex characters
of the SHA-256 of `repo`, `key`, `kind`, `pipeline` and `via` joined by newlines, so one rule exists per
combination. The trigger and the step are not part of a rule; they are in every audit entry.
**A request fits a rule** (`standing_rule_for`) when all of these hold:
- `signing_check` passes: a rule never widens a key's scope, and narrowing the scope afterwards stops the rule;
- the request names a run;
- repository, pipeline, key (id and `created`), kind and `via` equal the rule's;
- for an approval, every target of the request is one of the rule's targets;
- `via` is `local`, or the kind is `approval`: a release signature asked through the mailbox never fits a rule;
- the checklist item `card-signing` (*Sign only with a card*) is not ticked.
**A rule is made** (`standing_grant`) only when the request would itself fit the rule being made, the key is a
release key (a test key needs none), and **the key has signed before** (an `approved` or `standing` audit entry):
a key's first signature is never the one that starts a rule. Granting again for an approval adds its targets to
the rule. At most 256 rules. `standing_revoke` removes one. Granting and revoking are written to the security audit
(`standing-granted`, `standing-revoked`, with the rule's fields as the detail).
**Signing with a rule** is `signing_sign(req, Approval::Standing, now)`: it checks the request, finds the rule
(refusing with `NeedsApproval` when none fits), signs, records the outcome `standing` with everything an `approved`
entry holds, and counts the use on the rule (`uses`, `lastUsed`).
Never covered by a rule, by construction: another repository, key, kind, pipeline or origin; a request out of the
key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for;
a release signature the server runner asks for; creating a key.
## The Android grant (core 0.19.0)
A standing approval is one repository's one key, and never a key's first signature. Mark has a dozen Domi apps, each
with its own Android key (`<app>-android`), each new: that is a card to make the key's first signature and another to
store the rule, per app. **The Android grant** is one answer for all of them: "sign my apps' release APKs, and make
each app's key when its first release asks". One grant per vault, in `signing.android`:
```json
"android": { "repos": ["mnovak/*"], "o": "Marek Novak", "c": "CZ", "granted": 1794000000000,
"lastUsed": 1794100000000, "uses": 3, "made": ["culina-android"] }
```
- `repos`: 1 to 64 patterns, each `owner/name` or `owner/*` (every repository of that owner, never another
owner's); owner and name are 1 to 64 of `A-Z a-z 0-9 . _ -`.
- `o`, `c`: the certificate subject's organisation and country for the keys it makes.
- `uses`, `lastUsed`: as on a standing approval. `made`: the ids of the keys it made, oldest first (at most 256).
**An app's key** is named by its repository: `android_key_id("mnovak/Culina")` is `culina-android` (the name in
lower case, `.` and `_` as `-`). The grant only ever deals in that key, and only when its scope is exactly that
repository and the pipeline `release`, with the role `release`: a key with a wider scope (or `*`) is never the
grant's, and a key the grant did not make but that has this shape (`postea-android`) is covered too.
**A request fits the grant** (`android_grant_fits`) when all of these hold:
- `signing_check` passes (scope as always: the grant never widens a key's scope);
- the kind is `apk` and `via` is `local`: an APK the server runner asks for never fits;
- the request names a run;
- the pipeline is `release` and the repository matches one of the patterns;
- the key is that repository's app key, as above;
- `card-signing` (*Sign only with a card*) is not ticked.
A key's first signature fits too: that is the point of the grant. `signing_sign(req, Approval::Standing, now)` signs
a request that fits a standing approval or the grant (a standing approval first), records the outcome `standing`,
and counts the use on whichever fitted.
**Making a key** (`android_grant_make_key(repo, pipeline, via, now)`): the grant covers the repository, the
pipeline is `release`, `via` is `local`, `card-signing` is not ticked, and the vault has no key under that id. It
makes the RSA-4096 key with the certificate `CN=<Name>` (the repository's name, first letter upper case), `O` and `C`
from the grant, named `<Name> Android`, scoped to exactly that repository and `release`, adds the id to `made`, and
writes `standing-granted` to the security audit (`Android grant made <id> for <repo> pipeline release`). Core 0.19.0
wrote a new action, `android-key-made`, which older cores refuse; 0.19.1 keeps to the values every core since 0.16.0
reads, because the phone app and the web vault open the same vault. It is a key like any other: not exportable,
removed only as any key is.
**Granting** (`android_grant_set(repos, o, c, now)`) stores or replaces the grant (the counts and `made` stay) and
writes `standing-granted` with `Android releases: <patterns> pipeline release, keys made on first use`. It is
refused while `card-signing` is ticked. `android_grant_revoke` removes it (`standing-revoked`). Neither asks
anyone: the app calls them only from Mark's own click.
Never covered by the grant: another kind, the server runner, a pipeline other than `release`, a repository no pattern
matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card*
is ticked.
## The audit log
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
@@ -166,9 +310,10 @@ one entry, whatever happened:
| `outcome` | |
| :-- | :-- |
| `approved` | Mark approved; signed |
| `standing` | (core 0.16.0) a standing approval fitted; signed without asking |
| `auto` | a test key; signed without asking |
| `refused` | Mark refused |
| `expired` | nobody answered within 5 minutes |
| `expired` | nobody answered before the card's wait ran out (the app's wait: 24 hours since Custos 0.17.0, 5 minutes before), or the requester withdrew it |
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
| `invalid` | the request was malformed (wrong digest length, a manifest or approval not in canonical form, an expired approval, a kind the key cannot do) |
@@ -177,7 +322,16 @@ one entry, whatever happened:
(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen
and travels with it.
**Compatibility.** Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
**Compatibility (core 0.16.0).** A core before 0.16.0 ignores `standing` when it reads and drops it when it saves
(the rules are gone and every request asks again). The audit outcome `standing` and the security actions
`standing-granted` and `standing-revoked` are values it does not know: once a rule was granted, every Custos that
opens the vault must be on core 0.16.0 or later (an older one refuses it as `Corrupted`).
**Compatibility.** A key of kind `android` and an audit entry of kind `apk` (core 0.14.0) are values a core
before 0.14.0 does not know: once the vault holds an Android key, every Custos that opens it must be on core 0.14.0
or later (an older one refuses the vault as `Corrupted`; the web vault, which never reads `signing`, is unaffected).
Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
`approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a
vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later.
@@ -186,15 +340,27 @@ vault has recorded an approval request, every Custos that opens it must be on co
```
Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set
Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0
Vault::signing_create_android(&AndroidKey, now) -> id // one Android key (core 0.14.0)
Vault::signing_keys() -> [SigningKeyView] // public parts only
Vault::signing_set_scope(id, pipelines, repos)
Vault::signing_export_cert(id) -> DER // a certificate, never a key
Vault::signing_minisign_public(id) -> minisign.pub text
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms)
Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry)
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
Vault::signing_sign(&request, Approval::{Mark, Auto, Standing}, now) -> Signed // checks again, signs, records
Vault::signing_refuse(&request, outcome, now) // records refused / expired
Vault::signing_audit() -> [AuditEntry]
Vault::standing_can_grant(&request, now) -> Ok | why not // may the card offer "always"? (0.16.0)
Vault::standing_grant(&request, now) -> StandingRule // before signing the approved request
Vault::standing_rule_for(&request, now) -> Option<StandingRule>
Vault::standing_rules() -> [StandingRule]
Vault::standing_revoke(id, now) -> bool
android_key_id(repo) -> Option<String> (core 0.19.0)
Vault::android_grant() -> Option<AndroidGrant>
Vault::android_grant_set(repos, o, c, now) -> Result<AndroidGrant, Error>
Vault::android_grant_revoke(now) -> bool
Vault::android_grant_fits(req, now) -> bool
Vault::android_grant_make_key(repo, pipeline, via, now) -> Result<String, Error>
```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+310
View File
@@ -0,0 +1,310 @@
# Team vaults, policies and team signing (core 0.18.0; review fixes 0.18.1)
A **team vault** is a `.custos` file that a small team (1 to 32 people) shares: the team's release-signing keys,
its target credentials, its external-signer credentials and its approval policy. Each member opens it with the
**member key** kept in their own vault, so any member's Custos can open it and no server ever can. The pure parts
live here: the member key, the member slot, the team body, policy evaluation, the `sign.request` canonical form,
approval statements, the policy proof and the signature envelopes. Transport, prompts and storage are the app's
(Custos `docs/27_team_vault.md`).
```
member's own vault (two factors) ──► member key (X25519 + Ed25519)
│ opens its member slot
team vault ── member slots: team key sealed to each member's X25519 key
└─ body (XChaCha20-Poly1305 under the team key): roster, policy, signing keys, targets, signers, audit
```
## The member key
Every person who is in a team has one member key, made at random the first time they create or join a team, and
kept in their own vault (body member `member`, below). It never leaves that vault.
| Part | |
| :-- | :-- |
| `x25519` | 32-byte X25519 secret: the team key is sealed to its public half (custos-seal) |
| `ed25519` | 32-byte Ed25519 seed: signs the member's approvals |
| member id | the first 16 bytes of `SHA-256("custos member v1" ‖ ed25519 public ‖ x25519 public)`, 32 hex |
The **join code** a joining member's screen shows is `custos_seal::match_code(x25519 public)` (SEAL.md): the member
who approves the join compares it with the code on their own card.
In the member's own vault:
```json
"member": {
"x25519": "<64 hex>", "ed25519": "<64 hex>", "created": 1794000000000,
"teams": [ { "id": "<32 hex>", "name": "Domi", "epoch": 3, "identity": "<64 hex: the team identity's public key>" } ]
}
```
`teams` is what this member has seen: a team vault whose identity differs, or whose epoch is lower than the one
recorded, is refused (`TeamRollback`): an old copy of the file, or a fork made with an old team key, does not open
as current. An older Custos drops `member` when it saves: every Custos that saves a member's vault must be 0.18.0
or later (the member would have to be invited again).
## The team vault file
Version 2 (FACTORS.md) with one new slot kind and no factor slots:
```
kind 6, member slot (144 bytes)
16 team id
16 member id
4 epoch u32
108 sealed team key custos-seal box of the 32-byte team key, to the member's X25519 key,
context "custos team key v1:<team id hex>:<epoch>:<member id hex>"
```
- A team vault has 1 ..= 32 member slots and **only** member slots; a file that mixes member slots with factor,
pair, single or recovery slots is malformed. All member slots carry the same team id and epoch.
- The slot is authenticated by its box: the context binds team, epoch and member, so a slot moved to another
member, team or epoch does not open. The body AAD is the whole header, as for every vault.
- **Opening** (`Vault::open_team(bytes, &member_key)`): the slot with this member's id, its box opened, the body
decrypted with the team key. The body must be `"kind": "team"` with the same team id and epoch, and the member
must be on its roster; else `NotAMember` (no slot, a removed member) or `Corrupted`.
- A core before 0.18.0 skips kind 6, finds no factor slot and refuses the file: it never misreads a team vault.
### Rotation: removing a member
`team_remove_member` makes a **new random team key**, raises the epoch and writes member slots for the remaining
members only. The body (every key, credential and policy) is encrypted under the new key at the next save, so the
removed member cannot open anything written after. What they could read before stays read: Custos never hands out
a signing key, but the target and signer credentials they could reveal should be rotated at their source (the
app's card says which).
The **team identity** (an Ed25519 key in the body) does not rotate: it is what Fabrica and every target pin, and a
removed member never held it outside Custos. Rotating it is a new team.
## The team body
```json
{ "format": 2, "kind": "team", "items": [],
"team": {
"id": "<32 hex>", "name": "Domi", "created": 1794000000000, "epoch": 1,
"identity": { "secret": "<64 hex>", "public": "<64 hex>" },
"members": [ { "id": "<32 hex>", "name": "Mark", "handles": ["mnovak"], "ed25519": "<64 hex>",
"x25519": "<64 hex>", "added": 1794000000000, "by": "<member id or empty for the founder>",
"code": "684361" } ],
"removed": [ { "id": "<32 hex>", "name": "Old", "at": 1794100000000, "by": "<member id>", "epoch": 2 } ],
"policy": { "text": "<canonical policy JSON>", "sig": "<base64: the identity's signature>" },
"targets": [ { "id": "<16 hex>", "kind": "ssh-key", "name": "web-1", "project": "mnovak/Arca", "env": "production",
"host": "web-1.example", "user": "deploy", "secret": "<the credential>", "created": 1794000000000,
"by": "<member id>" } ],
"signers": [ { "id": "<16 hex>", "name": "Cloud signing", "adapter": "command", "endpoint": "…",
"account": "…", "secret": "<the credential>", "certificate": "<base64 DER or empty>",
"created": 1794000000000, "by": "<member id>" } ],
"seen": [ { "request": "<64 hex>", "at": 1794000000 } ],
"audit": [ { "at": 1794000000000, "action": "member-added", "by": "<member id>", "detail": "Petra" } ] },
"signing": { "keys": [ … ], "audit": [ … ] } }
```
- `handles`: the names Fabrica knows the member by (git host user names), 0 ..= 8 of `[A-Za-z0-9._-]{1,64}`. The
policy's author rule matches a request's `author` against them (ASCII case-insensitive) and against the member id.
- `targets` and `signers` are **not items**: an item can be revealed, copied, shared and exported, and these are
reached only through `team_target_*` and `team_signer_*`. `secret` is never in a view, a `Debug` or an error.
- `seen`: every request a member of this vault signed or refused as replayed, kept 48 hours (longer than any
request lives, 25 hours). A request whose hash is in it is refused (`Replayed`).
- `audit` (team actions; signatures are in `signing.audit`): `team-created`, `member-added`, `member-removed`,
`policy-set`, `target-added`, `target-removed`, `target-released`, `signer-added`, `signer-removed`,
`keys-created`. `detail` names, never holds a value. Append-only, newest 5 000.
- `signing` is the store of SIGNING.md, with the team's keys (below) and its audit; a team audit entry carries
`by` (the signing member's id), `env`, `release`, `request` (the request hash) and `approvers`.
### Team keys
`team_create_keys` makes the team's set, once:
| id | kind | role | Signs |
| :-- | :-- | :-- | :-- |
| `team-release` | `ed25519` | release | `minisign`, `tauri-updater` when the policy asks for 1+ approvals |
| `team-preview` | `ed25519` | test | the same, when the environment's policy asks for **0** approvals |
| `team-cosign` | `ecdsa-p256` (new kind) | release | `cosign` when the policy asks for 1+ approvals |
| `team-cosign-preview` | `ecdsa-p256` | test | `cosign` at 0 approvals |
An Android key (`android`, SIGNING.md) is made per app with `team_create_android`; at 0 approvals an `apk` request
needs a test Android key, else it is `NoKey`. Authenticode is never signed with a key in the vault: a request goes
to an external signer (`signers`) after the policy is met.
**Why 0 approvals uses a different key.** A preview signature is made without anyone looking. It must not be
mistakable for a release: it is made by a test-role key that production targets do not trust, exactly as today's
test keys (SIGNING.md). A signature by `team-release` always means the policy's people approved it.
## Policy
One rule per environment, signed by the team identity:
```
{"v":1,"team":"<32 hex>","rev":2,"envs":[{"env":"preview","approvals":0,"others":false,"approvers":[]},{"env":"staging","approvals":1,"others":false,"approvers":[]},{"env":"production","approvals":1,"others":true,"approvers":[]}]}
```
| Key | |
| :-- | :-- |
| `rev` | starts at 1, +1 on every change |
| `envs` | 1 ..= 8 rules, `env` unique, `[a-z][a-z0-9-]{0,31}`, sorted as written by `Policy::canonical` (the order given) |
| `approvals` | 0 ..= 10: how many members must approve |
| `others` | the approvers must not include the release's author, **when the team has 2 or more members** |
| `approvers` | member ids allowed to approve; empty = every member |
Canonical form as for deploy approvals (SIGNING.md): this key order, no spaces, minimal escaping, no newline;
anything else is refused, not normalised. Signature: Ed25519 by the team identity over
`"custos team policy v1\0" ‖ text`.
**Defaults** (`Policy::default_for(team)`): preview 0, staging 1, production 1 with `others`. A team of one approves
its own production releases (the `others` rule needs two members); when a second member joins, it applies.
### Evaluation
`evaluate(policy, roster, env, author, approvers) -> Verdict`, pure:
1. No rule for `env`: `UnknownEnv`.
2. `approvals == 0`: `Allowed { key_role: Test }`.
3. Eligible = roster members in `approvers` (or all); minus the author when `others` and the roster has ≥ 2 members.
The author is the member whose id equals `author` or whose handles contain it. Under `others` with 2+ members,
an author no member is (or an empty one) is `Unsatisfiable` (core 0.18.1): the rule cannot exclude someone it
cannot recognise, so it refuses instead of letting anyone approve.
4. Counted = distinct eligible members among `approvers` given. Members not on the roster, ineligible members and
duplicates are not counted (and listed in `ignored`).
5. Counted ≥ `approvals`: `Allowed { key_role: Release }`. Eligible < `approvals`: `Unsatisfiable` (no set of
approvals can ever meet it: say so instead of waiting a day). Else `Need { more }`.
## The signing request (`sign.request`, v1)
Fabrica asks for a signature with one line of canonical JSON (the app relays it; the core checks it):
```
{"v":1,"op":"sign.request","team":"<32 hex>","id":"<32 hex>","project":"mnovak/Arca","release":"0.7.0","env":"production","author":"mnovak","format":"minisign","artifact":{"name":"Arca_0.7.0_x64-setup.exe","size":25145977,"sha256":"<64 hex>"},"artifact_digest":"<base64>","image":"","pub":"<base64, 32 bytes>","expires":1794003600}
```
| Key | |
| :-- | :-- |
| `team` | the team id |
| `id` | 16 random bytes, hex: the request's own nonce |
| `project` | 1–128 of `[A-Za-z0-9._/-]` |
| `release` | 1–64 of `[A-Za-z0-9._+-]` (the version) |
| `env` | as in the policy |
| `author` | the release's author as Fabrica knows them, 0–64 of `[A-Za-z0-9._@-]` (empty: unknown) |
| `format` | `minisign`, `tauri-updater`, `apk`, `cosign`, `authenticode` |
| `artifact` | `name` (1–200 characters, no `/`, `\` or control characters), `size`, `sha256` (64 lower-case hex) |
| `artifact_digest` | base64; minisign and tauri-updater: BLAKE2b-512 of the file (64 bytes); apk: 1–4 SHA-512 digests of APK Signature Scheme signed data (64·n); cosign: the image manifest's SHA-256 (32); authenticode: signtool's 32-byte `.dig` |
| `image` | cosign only, else empty: the image reference without tag or digest, 1–255 of `[a-z0-9._/:-]` |
| `pub` | Fabrica's one-time X25519 key: the reply is sealed to it, and its match code is the request's code |
| `expires` | Unix seconds, later than now, at most 25 hours ahead |
The **request hash** is `SHA-256(text)`, hex. The **match code** is `match_code(pub)`: Fabrica shows it beside the
release, every member's card shows it.
### Approval statements
A member who approves signs, with their member key:
```
Ed25519( "custos team approval v1\0" ‖ request hash (32) ‖ match code (6 ASCII digits) ‖ member id (16) ‖ at (u64 BE, Unix seconds) )
```
`approve(request, shown_code, member_key, now)` refuses (`WrongMatch`) when the code the card showed is not the
request's match code: a request whose `pub` was swapped after the card was drawn is not approved. A statement whose
code is not the request's never counts.
### Signing
`Vault::team_sign(request_text, statements, signer, shown_code, now)` in the vault of the member whose Custos signs:
1. parses the request (canonical, fields as above, `team` = this team, not expired), refuses a hash in `seen`
(`Replayed`);
2. checks every statement's signature against the roster, and that its code is the request's;
3. evaluates the policy with the signer's own approval added (a signer approves by signing, and their shown code
must match: `WrongMatch` otherwise);
4. picks the key: by format and the verdict's role (`team-release` / `team-preview`, `team-cosign` /
`team-cosign-preview`, the Android key of that role whose `repos` holds the request's `project`, or for
authenticode the team's first external signer, never at 0 approvals);
5. signs, records the request in `seen` and an audit entry with `by`, `env`, `release`, `request`, `approvers`;
6. returns the reply.
A refusal by the policy, the code or the clock changes nothing. A member who refuses on the card records an audit
entry `refused` and the request's hash in `seen` (`team_refuse`).
### The reply (`sign.reply`, v1)
Sealed to the request's `pub` with the context `team-sign:<request id>`:
```json
{ "v": 1, "op": "sign.reply", "request": "<request hash>", "format": "minisign",
"signature": "<the envelope, below>", "payload": "<cosign: the signed payload, else absent>",
"key": { "id": "team-release", "public": "<minisign.pub text | cosign.pub PEM | certificate PEM>" },
"signer": { "member": "<member id>", "name": "Petra" },
"proof": { … } }
```
### The policy proof
What makes a signature checkable as *approved by the team's rules*, by anyone who pinned the team identity:
```
{"v":1,"team":"<id>","request":"<request hash>","env":"production","author":"mnovak","policy":"<policy text>","policy_sig":"<b64>","roster":[{"id":"<id>","name":"Mark","handles":["mnovak"],"ed25519":"<hex>"}],"approvals":[{"member":"<id>","code":"684361","at":1794000000,"sig":"<b64>"}],"signer":"<id>","role":"release","signature":"<sha256 hex of the envelope>","at":1794000100}
```
plus `"sig"`: Ed25519 by the team identity over `"custos team proof v1\0" ‖ that text`, carried next to it as
`{"text": …, "sig": …}`. `role` is `release` or `test` (0 approvals: no approvals listed). For `release`, the
signer's own approval is one of those that count: the signature is made in an approving member's Custos. `verify_proof(proof, team_identity_public, request_text, envelope, now)` checks both
signatures, every approval against the roster and the request's code, the request hash and the envelope hash, and
evaluates the policy again: it accepts only what `team_sign` itself would have signed.
## Signature envelopes
| `format` | `signature` in the reply | Check it with |
| :-- | :-- | :-- |
| `minisign` | the `.minisig` text (prehashed, SIGNING.md) | `minisign -V -P <pub> -m <file>`, minisign-verify |
| `tauri-updater` | base64 of that `.minisig` text: the content of Tauri's `<file>.sig` | Tauri's updater (minisign-verify) with `pubkey` = base64 of `minisign.pub` |
| `apk` | base64 of the n RSA PKCS#1 v1.5 SHA-512 signatures (512 bytes each) | apksig pass 2 then `apksigner verify` (the app's `custos-sign apk`) |
| `cosign` | base64 of the ECDSA P-256 SHA-256 signature (ASN.1 DER) over `payload` | `cosign verify --key cosign.pub --insecure-ignore-tlog=true <image>@<digest>` once attached; `openssl dgst -sha256 -verify cosign.pub -signature sig.der payload.json` |
| `authenticode` | base64 of what the external signer returned for the `.dig` (RSA PKCS#1 v1.5 over the SHA-256 DigestInfo) | `signtool sign /di`, then `signtool verify /pa`, `osslsigncode verify` |
**cosign.** The payload is cosign's *simple signing* JSON, written by Custos (never taken from the request), with the
keys in this order and no spaces:
```
{"critical":{"identity":{"docker-reference":"<image>"},"image":{"docker-manifest-digest":"sha256:<64 hex>"},"type":"cosign container image signature"},"optional":null}
```
No transparency log is involved: Fabrica attaches it with
`cosign attach signature --payload payload.json --signature <base64> <image>@sha256:<digest>`, and a target checks it
with the team's `cosign.pub` (PEM, SubjectPublicKeyInfo) and `--insecure-ignore-tlog=true`, or by fetching the
`sha256-<digest>.sig` manifest and checking the layer's `dev.cosignproject.cosign/signature` annotation over the
layer's bytes, which are this payload.
## Target credentials
A target credential is handed to the Fabrica server for one deployment: `team_target_release(target id, request,
deployment, now)` returns the plaintext to seal, only when the target's `project` and `env` equal the deployment's,
**and the request's `mac` was made with that deployment's ticket** (core 0.18.1), and records `target-released`
with the deployment's request hash.
**The ticket.** `team_sign` makes 32 random bytes per signed request, keeps them in the team body (`tickets`, 25
hours) and puts them in the reply (`"ticket"`, base64), which only the requester can open. A `target.request` ends
with `"mac":"<base64>"`: HMAC-SHA256(ticket, `"custos team target v1\0"` ‖ the canonical request up to and including
`"expires":N`, without the closing brace). Knowing a deployment's hash (the service stores every request text; a
proof names it) is not enough: without the ticket nobody else, not the service and not another connection, can ask
for its credentials or use up its one release. One release per (target, deployment): a second
call is `Replayed`. The app seals it to the server's one-time key (`team-target:<id>`); the service hands the box
out once, to the caller that asked (Custos `docs/27_team_vault.md`).
`kind`: `ssh-key` (an OpenSSH private key), `winrm` (user and password), `openssh` (user and password),
`registry` (a Docker registry token), `kubeconfig` (the kubeconfig text). `secret` ≤ 64 KiB.
## Limits (known, not fixed in 0.18.x)
- **Every member holds the team's secrets in their Custos**: the team identity, the release keys and the credentials
are in the body every member decrypts. Custos never hands them out, but a member running a modified build of the
public core can copy them before they are removed, and then sign directly, write proofs, or build a fork at a higher
epoch for the remaining members, which `member_note_team` would accept as current. Removing a member you no longer
trust means a new team (new identity, new keys), not only a new epoch.
- **Any member can change the policy.** `team_set_rule` is one member's action (audited as `policy-set`, signed by the
identity). A member who loosens production and then signs their own release passes `verify_proof`. Policy changes
that need the current policy's approvals are future work; until then, review the team audit.
## Crates
`custos-team` (pure): member keys, wrapping, policy, request, statements, proof, envelopes, on `ed25519-dalek`,
`x25519-dalek` through `custos-seal`, `sha2`, `p256` (cosign verification only). `custos-sign` gains `cosign`
(ECDSA P-256 with `p256`, RFC 6979 deterministic nonces) and `tauri_updater`. `custos-vault` holds the file format,
the body and `team_sign`.
+4
View File
@@ -69,6 +69,10 @@ just as plainly, what it does not.
password, the TOTP code or a PC.
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
screens; a request you did not start is someone else's.
- **Losing the vault loses its signing keys.** They never leave it, so no backup holds them but a backup of the
vault itself, and there is no phrase to rebuild them from. Most can be replaced with new keys; an Android app's
key (docs/SIGNING.md, `android`) cannot: Android accepts updates only from the same certificate, so its loss ends
that app's updates for good. Keep two copies of the vault off the PC before the first real signature.
## Design rules that follow from this
+211
View File
@@ -0,0 +1,211 @@
// Custos's background script (docs/BROWSER.md): an event page in Firefox, a service worker in Edge and Chrome.
// It owns the connection to the native host and answers the content scripts and the popup. The origins it sends
// to Custos are always the browser's (`sender.url` of the frame, `sender.tab.url` of its page), never what a page
// says about itself; Custos decides which logins belong there.
//
// It keeps no secret at rest: nothing goes to `storage`, and a login offered for saving waits in memory only, for
// its tab, until it is saved, dismissed or three minutes old.
const api = globalThis.browser ?? globalThis.chrome;
const HOST = 'cz.marek_novak.custos';
const SAVE_KEPT_MS = 3 * 60_000;
/** Which browser this is, for Custos's card (a label only: the host knows Firefox from its arguments). */
function browserHint() {
const brands = (globalThis.navigator?.userAgentData?.brands ?? []).map((b) => b.brand);
if (brands.includes('Microsoft Edge')) return 'edge';
if (brands.includes('Google Chrome')) return 'chrome';
return null;
}
/** The native host, connected on first use; the browser keeps the background alive while it is open. */
let port = null;
let seq = 0;
const waiting = new Map();
function connect() {
if (port) return port;
port = api.runtime.connectNative(HOST);
port.onMessage.addListener((msg) => {
const w = waiting.get(msg?.seq);
if (!w) return;
waiting.delete(msg.seq);
w(msg);
});
port.onDisconnect.addListener((p) => {
// Not registered, or the host exited: every open request fails the same way.
const why = `${p?.error?.message ?? api.runtime.lastError?.message ?? ''}`;
const error = /not found|forbidden|no such native application|not allowed/i.test(why) ? 'not_connected' : 'not_running';
for (const w of waiting.values()) w({ ok: false, error });
waiting.clear();
port = null;
});
return port;
}
function ask(request) {
return new Promise((resolve) => {
const n = ++seq;
waiting.set(n, resolve);
try {
connect().postMessage({ ...request, browser: browserHint(), seq: n });
} catch {
waiting.delete(n);
resolve({ ok: false, error: 'not_connected' });
}
// Custos may wait up to a minute for an unlock or an answer on its card.
setTimeout(() => {
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
}, 75_000);
});
}
/** `scheme://host[:port]` of a page or frame URL; null for anything Custos never fills. */
function originOf(url) {
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
return u.origin;
} catch {
return null;
}
}
/**
* The frame's origin and its page's, from what the browser says about the sender. Null when either is unknown,
* or when the frame's real origin is not its URL's (a sandboxed frame has an opaque origin: it gets nothing).
*/
function placeOf(sender) {
const origin = originOf(sender.url);
if (!origin) return null;
if (typeof sender.origin === 'string' && sender.origin !== origin) return null;
const top = sender.frameId === 0 ? origin : originOf(sender.tab?.url);
if (!top) return null;
return { origin, top };
}
// ---- logins offered for saving: in memory, per tab ----
const offers = new Map();
function offerFor(tabId) {
const o = offers.get(tabId);
if (o && Date.now() - o.at > SAVE_KEPT_MS) offers.delete(tabId);
return offers.get(tabId) ?? null;
}
function showBadge(tabId) {
const on = !!offerFor(tabId);
Promise.resolve(api.action.setBadgeText({ tabId, text: on ? '1' : '' })).catch(() => {});
if (on) Promise.resolve(api.action.setBadgeBackgroundColor({ tabId, color: '#c9a96e' })).catch(() => {});
}
api.tabs.onRemoved.addListener((tabId) => offers.delete(tabId));
/** What the popup and the page may see of an offer: never its password. */
const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username } : null);
async function save(tabId) {
const o = offerFor(tabId);
if (!o) return { ok: false, error: 'gone' };
offers.delete(tabId);
showBadge(tabId);
const r = await ask({ op: 'browser_save', origin: o.origin, top: o.top, username: o.username, password: o.password, title: o.title });
o.password = '';
return r;
}
async function activeTab() {
const [tab] = await api.tabs.query({ active: true, currentWindow: true });
return tab ?? null;
}
// ---- messages from the content scripts and the popup ----
async function handle(msg, sender) {
switch (msg?.kind) {
case 'status':
return ask({ op: 'browser_status' });
case 'match': {
// From a content script: the logins for the frame it runs in, on its page.
const at = placeOf(sender);
if (!at) return { ok: false, error: 'no_match' };
return { ...(await ask({ op: 'browser_match', ...at })), origin: at.origin };
}
case 'fill':
case 'totp': {
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
const at = placeOf(sender);
if (!at || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return ask({ op: msg.kind === 'fill' ? 'browser_fill' : 'browser_totp', id: msg.id, ...at });
}
case 'offer-save': {
// A login form was sent with a password Custos did not fill: keep it for this tab until the person decides.
const at = placeOf(sender);
const tabId = sender.tab?.id;
if (!at || tabId == null || typeof msg.password !== 'string' || !msg.password || msg.password.length > 4096) {
return { ok: false, error: 'bad_request' };
}
const username = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : '';
const title = new URL(at.origin).host;
offers.set(tabId, { ...at, username, password: msg.password, title, at: Date.now() });
showBadge(tabId);
// The open connection keeps a service worker (Edge, Chrome) alive, and the offer with it.
void ask({ op: 'browser_status' });
return { ok: true, offer: offerView(offers.get(tabId)) };
}
case 'pending-save': {
// The top page of the tab that sent the form, on the same site, asks whether to show the offer.
const at = placeOf(sender);
const o = sender.tab?.id != null ? offerFor(sender.tab.id) : null;
if (!at || !o || sender.frameId !== 0 || at.top !== o.top) return { ok: true, offer: null };
return { ok: true, offer: offerView(o) };
}
case 'save':
// From the page's own offer: its tab's offer only.
if (sender.tab?.id == null || sender.frameId !== 0) return { ok: false, error: 'bad_request' };
return save(sender.tab.id);
case 'dismiss-save':
if (sender.tab?.id != null) {
offers.delete(sender.tab.id);
showBadge(sender.tab.id);
}
return { ok: true };
case 'match-tab': {
// From the popup: the logins for the active tab's page, and any login offered for saving there.
const tab = await activeTab();
const origin = tab && originOf(tab.url);
const offer = tab ? offerView(offerFor(tab.id)) : null;
if (!origin) return { ok: false, error: 'no_match', tab: tab?.id ?? null, offer };
return { ...(await ask({ op: 'browser_match', origin, top: origin })), origin, tab: tab.id, offer };
}
case 'totp-tab': {
// From the popup: one login's 2FA code for the active tab's page.
const tab = await activeTab();
const origin = tab && originOf(tab.url);
if (!origin || typeof msg.id !== 'string') return { ok: false, error: 'no_match' };
return ask({ op: 'browser_totp', id: msg.id, origin, top: origin });
}
case 'save-tab': {
const tab = await activeTab();
return tab ? save(tab.id) : { ok: false, error: 'gone' };
}
case 'dismiss-tab': {
const tab = await activeTab();
if (tab) {
offers.delete(tab.id);
showBadge(tab.id);
}
return { ok: true };
}
default:
return { ok: false, error: 'bad_request' };
}
}
api.runtime.onMessage.addListener((msg, sender, reply) => {
// Only this extension's own pages and content scripts reach here; pages and other extensions cannot.
if (sender.id !== api.runtime.id) return false;
handle(msg, sender).then(reply, () => reply({ ok: false, error: 'bad_request' }));
return true;
});
+262
View File
@@ -0,0 +1,262 @@
// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button, the list and
// the save offer live in a closed shadow root, out of the page's reach; logins are asked for only when the list
// opens, and a secret goes only into the field it is for.
(() => {
const api = globalThis.browser ?? globalThis.chrome;
const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.',
no_match: 'That login does not belong to this site.',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const visible = (el) => {
const r = el.getBoundingClientRect();
const s = getComputedStyle(el);
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly;
};
const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type);
const isOtp = (el) =>
el instanceof HTMLInputElement &&
(el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`));
const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`);
/** The username field of a password field: the one the page marks, else the last text field before it. */
function usernameFor(pw) {
const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible);
const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete));
if (marked) return marked;
for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i];
return null;
}
/** The fields a login fills, around `near` (the focused field) or on the whole page. */
function fieldsAround(near) {
const all = [...document.querySelectorAll('input')].filter(visible);
const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null;
const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all;
const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null;
const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null);
return { user, pass, otp };
}
// Fields Custos filled and the person has not typed in since: a form sent with them is not offered for saving.
const filledByCustos = new WeakSet();
document.addEventListener('input', (e) => e.isTrusted && filledByCustos.delete(e.target), true);
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
function put(el, value) {
if (!el || !el.isConnected || typeof value !== 'string' || !value) return;
el.focus();
setValue.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
filledByCustos.add(el);
}
/** Fills login `id` around `near`. Only what the page has fields for is asked for: a 2FA page gets the code only. */
async function fill(id, near) {
const f = fieldsAround(near);
if (!f.pass && !f.user && f.otp) {
const r = await send({ kind: 'totp', id });
if (!r?.ok) return say(r?.error);
put(f.otp, r.totp);
return null;
}
const r = await send({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
put(f.user, r.username);
put(f.pass, r.password);
if (f.otp) put(f.otp, r.totp);
return null;
}
// ---- the button, the list and the save offer ----
const host = document.createElement('custos-fill');
const root = host.attachShadow({ mode: 'closed' });
root.innerHTML = `
<style>
:host { all: initial; }
.chip, .menu, .offer { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
.menu, .offer { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
.offer { top: 12px; right: 12px; padding: 10px 12px; }
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
color: inherit; text-align: left; cursor: pointer; font: inherit; }
button.login:hover, button.login:focus-visible { background: #262b33; outline: none; }
.title { font-weight: 600; }
.user { color: #9aa3b1; font-size: 12px; }
.note { padding: 6px 8px; color: #c9d1dc; }
.row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; }
.row button { padding: 5px 12px; border: 1px solid #3a404b; border-radius: 7px; background: #1d2128; color: inherit;
font: inherit; cursor: pointer; }
.row button.primary { border-color: #c9a96e; }
[hidden] { display: none !important; }
</style>
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5l5 2v4c0 3.2-2.1 5.8-5 7-2.9-1.2-5-3.8-5-7v-4z"
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>
<div class="offer" role="dialog" aria-label="Save in Custos" hidden></div>`;
const chip = root.querySelector('.chip');
const menu = root.querySelector('.menu');
const offerBox = root.querySelector('.offer');
let field = null;
const attach = () => host.isConnected || document.documentElement.append(host);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
function place() {
if (!field || !field.isConnected) return hide();
const r = field.getBoundingClientRect();
chip.style.left = `${Math.max(0, r.right - 28)}px`;
chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`;
menu.style.left = `${Math.max(4, r.left)}px`;
menu.style.top = `${r.bottom + 4}px`;
}
function hide() {
chip.hidden = true;
menu.hidden = true;
field = null;
}
function note(text) {
menu.replaceChildren(el('div', { className: 'note', textContent: text }));
menu.hidden = false;
}
async function open() {
const target = field;
note('Asking Custos…');
const r = await send({ kind: 'match' });
if (field !== target) return;
if (!r?.ok) return note(say(r?.error));
if (!r.logins.length) return note('Custos has no login for this site.');
const items = r.logins.map((l) => {
const b = el('button', { className: 'login', type: 'button' });
b.setAttribute('role', 'menuitem');
b.append(
el('span', { className: 'title', textContent: l.title }),
el('span', { className: 'user', textContent: (l.username || '—') + (l.totp ? ' · 2FA' : '') }),
);
b.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
const why = await fill(l.id, target);
if (why) note(why);
else hide();
});
return b;
});
menu.replaceChildren(el('div', { className: 'head', textContent: 'Custos' }), ...items);
items[0]?.focus();
}
chip.addEventListener('click', (e) => e.isTrusted && (menu.hidden ? void open() : (menu.hidden = true)));
// A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it.
host.addEventListener('mousedown', (e) => e.preventDefault());
document.addEventListener(
'focusin',
(e) => {
const t = e.target;
if (!(t instanceof HTMLInputElement) || !visible(t)) return;
if (t.type !== 'password' && !isOtp(t) && !(isText(t) && fieldsAround(t).pass) && !isUserName(t)) return;
attach();
field = t;
menu.hidden = true;
chip.hidden = false;
place();
},
true,
);
document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true);
document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true);
window.addEventListener('scroll', place, true);
window.addEventListener('resize', place);
// ---- saving a login the person typed ----
function showOffer(offer) {
if (!offer || window.top !== window) return;
attach();
const yes = el('button', { type: 'button', className: 'primary', textContent: 'Save in Custos' });
const no = el('button', { type: 'button', textContent: 'Not now' });
yes.addEventListener('click', async (e) => {
if (!e.isTrusted) return;
offerBox.replaceChildren(el('div', { className: 'note', textContent: 'Answer in Custos…' }));
const r = await send({ kind: 'save' });
const done = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
offerBox.replaceChildren(el('div', { className: 'note', textContent: done }));
setTimeout(() => (offerBox.hidden = true), 2500);
});
no.addEventListener('click', (e) => {
if (!e.isTrusted) return;
void send({ kind: 'dismiss-save' });
offerBox.hidden = true;
});
offerBox.replaceChildren(
el('div', { className: 'head', textContent: 'Custos' }),
el('div', { className: 'note', textContent: `Save the login${offer.username ? ` of ${offer.username}` : ''} for ${offer.host}?` }),
Object.assign(el('div', { className: 'row' }), {}),
);
offerBox.lastChild.append(no, yes);
offerBox.hidden = false;
}
/** A form is being sent: if it has a password the person typed (not one Custos filled), offer to save it. */
function sent(form) {
const scope = form ? [...form.querySelectorAll('input')] : [...document.querySelectorAll('input')];
const pass = scope.find((i) => i.type === 'password' && visible(i) && i.value);
if (!pass || filledByCustos.has(pass)) return;
const user = usernameFor(pass);
// Read once, handed to the background in memory, and not kept here.
void send({ kind: 'offer-save', username: user?.value ?? '', password: pass.value }).then((r) => r?.ok && showOffer(r.offer));
}
document.addEventListener('submit', (e) => e.isTrusted && sent(e.target instanceof HTMLFormElement ? e.target : null), true);
// Pages that sign in by script never send a form: a click on their button, or Enter in the password, counts.
document.addEventListener(
'click',
(e) => {
if (!e.isTrusted) return;
const b = e.target instanceof Element ? e.target.closest('button, input[type=submit]') : null;
if (!b || b.form?.querySelector('input[type=password]') == null || (b.type && b.type !== 'submit')) return;
sent(b.form);
},
true,
);
document.addEventListener(
'keydown',
(e) => e.isTrusted && e.key === 'Enter' && e.target instanceof HTMLInputElement && e.target.type === 'password' && !e.target.form && sent(null),
true,
);
// After the sign-in page went away: the next page of the same site shows the offer.
if (window.top === window) void send({ kind: 'pending-save' }).then((r) => r?.ok && showOffer(r.offer));
// ---- the popup's choice, in the top frame: fill the page's login form, or only its 2FA field ----
api.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== api.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false;
fill(msg.id, null).then((why) => reply({ ok: !why, error: why }));
return true;
});
})();
+43
View File
@@ -0,0 +1,43 @@
{
"manifest_version": 3,
"name": "Custos",
"short_name": "Custos",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to, and offers to save new ones.",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
"minimum_chrome_version": "116",
"permissions": [
"nativeMessaging",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "Custos",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"js": [
"content.js"
],
"all_frames": true,
"run_at": "document_idle"
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
}
}
+54
View File
@@ -0,0 +1,54 @@
{
"manifest_version": 3,
"name": "Custos",
"short_name": "Custos",
"description": "Fills your logins from the Custos on this computer, only into the site they belong to, and offers to save new ones.",
"browser_specific_settings": {
"gecko": {
"id": "custos@marek-novak.cz",
"strict_min_version": "140.0",
"data_collection_permissions": {
"required": [
"none"
]
}
}
},
"permissions": [
"nativeMessaging",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"background": {
"scripts": [
"background.js"
]
},
"action": {
"default_title": "Custos",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"https://*/*",
"http://localhost/*",
"http://127.0.0.1/*",
"http://*.localhost/*"
],
"js": [
"content.js"
],
"all_frames": true,
"run_at": "document_idle"
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
}
}
+130
View File
@@ -0,0 +1,130 @@
:root {
color-scheme: dark;
--bg: #101216;
--panel: #15181d;
--hover: #262b33;
--line: #2b3038;
--fg: #e8ebf0;
--muted: #9aa3b1;
--accent: #c9d1dc;
}
body {
width: 320px;
margin: 0;
background: var(--bg);
color: var(--fg);
font: 13px/1.45 "Segoe UI", system-ui, sans-serif;
}
header {
display: flex;
align-items: baseline;
gap: 10px;
padding: 12px 14px 10px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
.wordmark {
color: var(--accent);
font-size: 12px;
letter-spacing: 0.3em;
}
.site {
overflow: hidden;
color: var(--muted);
white-space: nowrap;
text-overflow: ellipsis;
}
main {
padding: 8px;
}
.note {
margin: 6px 6px 10px;
}
.logins {
margin: 0;
padding: 0;
list-style: none;
}
.logins button {
display: grid;
width: 100%;
padding: 8px 10px;
border: 0;
border-radius: 8px;
background: none;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.logins button:hover,
.logins button:focus-visible {
background: var(--hover);
outline: none;
}
.title {
font-weight: 600;
}
.user {
color: var(--muted);
font-size: 12px;
}
.logins li {
display: flex;
align-items: center;
gap: 6px;
}
.logins button.login {
flex: 1;
min-width: 0;
}
.logins button.code {
display: block;
width: auto;
flex: none;
padding: 4px 8px;
border: 1px solid var(--line);
color: var(--accent);
font-variant-numeric: tabular-nums;
letter-spacing: 0.08em;
}
.offer {
margin: 4px 4px 10px;
padding: 10px;
border: 1px solid #c9a96e;
border-radius: 8px;
}
.offer p {
margin: 0 0 8px;
}
.buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.buttons button {
padding: 5px 12px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel);
color: inherit;
font: inherit;
cursor: pointer;
}
.buttons button.primary {
border-color: #c9a96e;
}
footer {
display: grid;
gap: 2px;
padding: 8px 14px 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 12px;
}
.code-line {
font-variant-numeric: tabular-nums;
}
[hidden] {
display: none !important;
}
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custos</title>
<link rel="stylesheet" href="popup.css">
<script src="popup.js" defer></script>
</head>
<body>
<header>
<span class="wordmark">CUSTOS</span>
<span id="site" class="site"></span>
</header>
<main>
<section id="offer" class="offer" hidden>
<p id="offer-text"></p>
<div id="offer-buttons" class="buttons">
<button id="offer-dismiss" type="button">Not now</button>
<button id="offer-save" type="button" class="primary">Save in Custos</button>
</div>
</section>
<p id="note" class="note">Asking Custos…</p>
<ul id="logins" class="logins" aria-label="Logins for this site"></ul>
</main>
<footer>
<span>Only logins saved for this site are offered here.</span>
<span id="code" class="code-line"></span>
</footer>
</body>
</html>
+98
View File
@@ -0,0 +1,98 @@
// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form
// (the top frame's content script asks for the secrets itself, so they go only where they belong). A login with
// 2FA can show its current code here. A login the page just sent can be saved in Custos. The footer shows this
// connection's match code, the one Custos shows on its card.
const api = globalThis.browser ?? globalThis.chrome;
const SENTENCES = {
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
not_running: 'Custos is not running. Start it, then try again.',
not_custos: 'Something other than Custos answered. Nothing was sent.',
not_allowed: 'This copy of the extension is not the one Custos knows.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
refused: 'Not saved.',
not_found: 'That login is no longer in Custos.',
no_match: 'Custos fills only web pages (https, or this computer).',
no_totp: 'That login has no 2FA code in Custos.',
no_answer: 'Custos did not answer.',
gone: 'That offer has expired.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' }));
const $ = (id) => document.getElementById(id);
const el = (tag, props) => Object.assign(document.createElement(tag), props);
const note = $('note');
const list = $('logins');
function tell(text) {
note.hidden = false;
note.textContent = text;
}
/** The 2FA code, shown until it changes; then the next one is asked for. */
async function showCode(id, out) {
const r = await send({ kind: 'totp-tab', id });
if (!r?.ok) {
out.textContent = say(r?.error);
return;
}
out.textContent = `${r.totp.slice(0, 3)} ${r.totp.slice(3)}`;
out.title = `Changes in ${r.remaining} s`;
setTimeout(() => out.isConnected && showCode(id, out), Math.max(1, r.remaining) * 1000);
}
function offer(o) {
if (!o) return;
const box = $('offer');
box.hidden = false;
$('offer-text').textContent = `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host}?`;
$('offer-save').addEventListener('click', async () => {
$('offer-text').textContent = 'Answer in Custos…';
const r = await send({ kind: 'save-tab' });
$('offer-text').textContent = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error);
$('offer-buttons').hidden = true;
});
$('offer-dismiss').addEventListener('click', async () => {
await send({ kind: 'dismiss-tab' });
box.hidden = true;
});
}
async function show() {
const r = await send({ kind: 'match-tab' });
if (r?.origin) $('site').textContent = new URL(r.origin).host;
offer(r?.offer);
if (!r?.ok) return tell(say(r?.error));
if (!r.logins.length) return tell('Custos has no login for this site.');
note.hidden = true;
for (const l of r.logins) {
const li = el('li', {});
const b = el('button', { type: 'button', className: 'login' });
b.append(el('span', { className: 'title', textContent: l.title }), el('span', { className: 'user', textContent: l.username || '—' }));
b.addEventListener('click', async () => {
const done = await Promise.resolve(api.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 })).catch(() => null);
if (done?.ok) window.close();
else tell(done?.error ?? 'This page has no login form Custos can fill.');
});
li.append(b);
if (l.totp) {
const code = el('button', { type: 'button', className: 'code', textContent: '2FA code' });
code.addEventListener('click', () => {
code.disabled = true;
code.textContent = '…';
void showCode(l.id, code);
});
li.append(code);
}
list.append(li);
}
list.querySelector('button')?.focus();
}
async function connection() {
const r = await send({ kind: 'status' });
if (r?.ok && typeof r.code === 'string') $('code').textContent = `Connection ${r.code.slice(0, 3)} ${r.code.slice(3)}`;
}
void show();
void connection();
+141
View File
@@ -0,0 +1,141 @@
// Tests of the extension's background script against a fake browser (docs/BROWSER.md, "Tests"):
//
// node tools/extension-test.mjs
//
// The background is the extension's one gate to Custos: what it sends to the host must come from the browser's
// own view of the sender, never from the message; other extensions and odd frames get nothing; a login offered for
// saving never comes back out of it.
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf8');
const ID = 'custos-test-id';
/** A fresh background with a fake API. `host(req)` answers the native host's requests. */
function background(host) {
const sent = [];
let listener = null;
const port = {
onMessage: { addListener: (f) => (port.deliver = f) },
onDisconnect: { addListener: () => {} },
postMessage: (m) => {
sent.push(m);
queueMicrotask(() => port.deliver({ ...host(m), seq: m.seq }));
},
};
const tabs = [{ id: 1, url: 'https://github.com/login', active: true }];
const api = {
runtime: { id: ID, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } },
tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } },
action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} },
};
vm.runInNewContext(code, { chrome: api, URL, setTimeout, Promise, queueMicrotask, console });
const call = (msg, sender) =>
new Promise((resolve) => {
// Answers are made in the background's realm: compared as plain JSON.
const kept = listener(msg, { id: ID, ...sender }, (v) => resolve(JSON.parse(JSON.stringify(v))));
if (kept !== true) resolve('ignored');
});
return { call, sent, tabs };
}
const tab = (url) => ({ id: 1, url });
const top = (url) => ({ url, frameId: 0, tab: tab(url) });
const frame = (url, pageUrl) => ({ url, frameId: 7, tab: tab(pageUrl) });
const tests = [];
const test = (name, f) => tests.push([name, f]);
test('another extension, or a page, is not answered at all', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
for (const id of ['someone-else', undefined, '']) {
assert.equal(await b.call({ kind: 'match' }, { ...top('https://github.com/'), id }), 'ignored');
assert.equal(await b.call({ kind: 'fill', id: 'a' }, { ...top('https://github.com/'), id }), 'ignored');
}
assert.equal(b.sent.length, 0);
});
test('the origins come from the browser, never from the message', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match', origin: 'https://bank.cz', top: 'https://bank.cz' }, top('https://github.com/login?x=1'));
assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_match', 'https://github.com', 'https://github.com']]);
});
test('a frame asks with its own origin and its page’s', async () => {
const b = background(() => ({ ok: true, logins: [] }));
await b.call({ kind: 'match' }, frame('https://evil.net/ad', 'https://github.com/'));
await b.call({ kind: 'fill', id: 'x' }, frame('https://github.com/login', 'https://evil.net/'));
assert.deepEqual(
b.sent.map((m) => [m.op, m.origin, m.top]),
[
['browser_match', 'https://evil.net', 'https://github.com'],
['browser_fill', 'https://github.com', 'https://evil.net'],
],
);
});
test('sandboxed, blank, script and file frames get nothing, and nothing is asked', async () => {
const b = background(() => ({ ok: true, logins: [{ id: 'a' }] }));
const odd = [
{ ...frame('https://github.com/login', 'https://evil.net/'), origin: 'null' },
{ ...top('https://github.com/'), origin: 'https://evil.net' },
frame('about:blank', 'https://github.com/'),
top('javascript:alert(1)'),
top('file:///C:/x.html'),
top('data:text/html,<input type=password>'),
{ url: 'https://github.com/', frameId: 3 },
];
for (const s of odd) {
assert.deepEqual(await b.call({ kind: 'match' }, s), { ok: false, error: 'no_match' }, JSON.stringify(s));
assert.deepEqual(await b.call({ kind: 'fill', id: 'a' }, s), { ok: false, error: 'no_match' });
}
assert.equal(b.sent.length, 0);
});
test('a locked Custos answers nothing but locked', async () => {
const b = background(() => ({ ok: false, error: 'locked' }));
const r = await b.call({ kind: 'fill', id: 'a' }, top('https://github.com/'));
assert.deepEqual(r, { ok: false, error: 'locked', seq: 1 });
});
test('a login offered for saving never comes back out, and goes only to Custos', async () => {
const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' }));
const at = top('https://github.com/login');
const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at);
assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark' } });
// Another page of the site in the same tab sees the offer, without the password; a frame or another site does not.
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark' } });
assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null });
assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null });
const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` });
assert.ok(!JSON.stringify(popup).includes('hunter2'), 'the popup never sees the password');
// A frame cannot save; the top page can, once.
assert.deepEqual(await b.call({ kind: 'save' }, frame('https://github.com/x', 'https://github.com/')), { ok: false, error: 'bad_request' });
const saved = await b.call({ kind: 'save' }, top('https://github.com/home'));
assert.equal(saved.saved, 'new');
const req = b.sent.find((m) => m.op === 'browser_save');
assert.deepEqual([req.origin, req.top, req.username, req.password], ['https://github.com', 'https://github.com', 'mark', 'hunter2-secret']);
assert.deepEqual(await b.call({ kind: 'save' }, top('https://github.com/home')), { ok: false, error: 'gone' });
});
test('an offer needs a password, from a web page', async () => {
const b = background(() => ({ ok: true }));
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: '' }, top('https://github.com/'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'p' }, top('about:blank'))).ok, false);
assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false);
});
let failed = 0;
for (const [name, f] of tests) {
try {
await f();
console.log(`ok ${name}`);
} catch (e) {
failed++;
console.log(`FAIL ${name}\n${e.stack}`);
}
}
console.log(`${tests.length - failed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
+87
View File
@@ -0,0 +1,87 @@
// Builds the browser extension for each browser from the one source in extension/ (docs/BROWSER.md):
//
// node tools/extension.mjs [--out <dir>] [--zip]
//
// writes <out>/firefox/ and <out>/chromium/ (default out: target/extension), each with its manifest.json (the
// browser's manifest.<browser>.json, with the workspace version) and the shared scripts and popup. With --zip
// also custos-<browser>-<version>.zip next to them, reproducible (fixed order and times): the Firefox one is what
// AMO signs, the Chromium one what the Edge and Chrome stores take.
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
const root = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const arg = (name) => {
const i = process.argv.indexOf(name);
return i > 0 ? process.argv[i + 1] : null;
};
const out = path.resolve(arg('--out') ?? path.join(root, 'target', 'extension'));
const zip = process.argv.includes('--zip');
const cargo = fs.readFileSync(path.join(root, 'Cargo.toml'), 'utf8');
const version = /\[workspace\.package\][^[]*?version = "([^"]+)"/s.exec(cargo)?.[1];
if (!version) throw new Error('no workspace version in Cargo.toml');
const SHARED = ['background.js', 'content.js', 'popup.html', 'popup.js', 'popup.css'];
const BROWSERS = ['firefox', 'chromium'];
/** A zip of `files` ([name, bytes]), deflated, with a fixed time: the same input gives the same bytes. */
function zipOf(files) {
const parts = [];
const central = [];
let offset = 0;
const time = 0, date = (2026 - 1980) << 9 | 1 << 5 | 1; // 2026-01-01 00:00
for (const [name, data] of files) {
const n = Buffer.from(name, 'utf8');
const packed = zlib.deflateRawSync(data, { level: 9 });
const crc = zlib.crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(8, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(n.length, 26);
parts.push(local, n, packed);
const c = Buffer.alloc(46);
c.writeUInt32LE(0x02014b50, 0);
c.writeUInt16LE(20, 4);
c.writeUInt16LE(20, 6);
c.writeUInt16LE(0x0800, 8);
c.writeUInt16LE(8, 10);
c.writeUInt16LE(time, 12);
c.writeUInt16LE(date, 14);
c.writeUInt32LE(crc, 16);
c.writeUInt32LE(packed.length, 20);
c.writeUInt32LE(data.length, 24);
c.writeUInt16LE(n.length, 28);
c.writeUInt32LE(offset, 42);
central.push(c, n);
offset += 30 + n.length + packed.length;
}
const dir = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(dir.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, dir, end]);
}
for (const browser of BROWSERS) {
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'extension', `manifest.${browser}.json`), 'utf8'));
const withVersion = { manifest_version: manifest.manifest_version, name: manifest.name, version, ...manifest };
const files = [['manifest.json', Buffer.from(JSON.stringify(withVersion, null, 2) + '\n')]];
for (const f of SHARED) files.push([f, fs.readFileSync(path.join(root, 'extension', f))]);
const dir = path.join(out, browser);
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
for (const [name, data] of files) fs.writeFileSync(path.join(dir, name), data);
if (zip) fs.writeFileSync(path.join(out, `custos-${browser}-${version}.zip`), zipOf(files));
console.log(`${browser}: ${dir}${zip ? ` (+ custos-${browser}-${version}.zip)` : ''}`);
}