Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 61b98ee9b0 | |||
| 2c2d56b856 | |||
| 95613f4ed0 | |||
| 2d04f32f57 | |||
| 1292c09d02 | |||
| a45d1054f0 | |||
| 4e8fb6a8f5 | |||
| aa5b692651 | |||
| 6f4075f7e3 | |||
| 54ce09ce61 | |||
| 045f1f5d00 | |||
| 82698bd9e5 | |||
| 68a1f1344d | |||
| ac69cf4638 | |||
| 65c87186d6 | |||
| 7f90f952f0 | |||
| 12a5ba31d8 | |||
| 8a10c695c5 | |||
| 6739423f4d | |||
| 8660b887c1 | |||
| 23a8878f32 | |||
| 37634f0d26 | |||
| 76a94b0d11 | |||
| 4e386e8113 |
@@ -15,6 +15,9 @@ crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor mate
|
||||
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 (origins, no fuzzy matching), native messaging frames
|
||||
crates/custos-native the browser extension's native messaging host: three ops, rebuilt, to custos.exe's pipe only
|
||||
extension/ the MV3 extension for Edge and Chrome (fixed id jchkapmceepdnlhagfppeckggaecdcmn)
|
||||
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,6 +26,7 @@ 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
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
Generated
+29
-10
@@ -327,9 +327,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-browser"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -341,7 +348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-kdbx"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"argon2",
|
||||
@@ -362,7 +369,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-keys"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"ed25519-dalek",
|
||||
@@ -373,13 +380,23 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-native"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"custos-browser",
|
||||
"serde_json",
|
||||
"windows-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
|
||||
[[package]]
|
||||
name = "custos-seal"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"hkdf",
|
||||
@@ -392,7 +409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -409,7 +426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-sign"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"blake2 0.10.6",
|
||||
"data-encoding",
|
||||
@@ -418,6 +435,8 @@ dependencies = [
|
||||
"rand 0.10.3",
|
||||
"rand_core 0.6.4",
|
||||
"rsa",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror",
|
||||
"x509-cert",
|
||||
@@ -426,7 +445,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -439,7 +458,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"bip39",
|
||||
@@ -463,7 +482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-seal",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.10.0"
|
||||
version = "0.16.1"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -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 Edge/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).
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[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]
|
||||
zeroize.workspace = true
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! 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.
|
||||
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON).
|
||||
//!
|
||||
//! ```
|
||||
//! 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 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) => 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.
|
||||
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('[') {
|
||||
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()
|
||||
}
|
||||
|
||||
#[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)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[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" }
|
||||
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"] }
|
||||
@@ -0,0 +1,240 @@
|
||||
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it
|
||||
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards
|
||||
//! three requests to the desktop Custos over its Domi pipe and returns the answers:
|
||||
//!
|
||||
//! - `browser_status`: is Custos running and unlocked;
|
||||
//! - `browser_match { origin }`: the logins for a page (title, username; never a password);
|
||||
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page.
|
||||
//!
|
||||
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the
|
||||
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from
|
||||
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses
|
||||
//! a pipe that is not served by custos.exe.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
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"];
|
||||
|
||||
/// The request Custos gets: only known fields, of the right types.
|
||||
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
|
||||
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
|
||||
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
|
||||
let mut out = json!({ "op": op, "app": "Custos for your browser" });
|
||||
if op != "browser_status" {
|
||||
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?;
|
||||
out["origin"] = origin.into();
|
||||
}
|
||||
if op == "browser_fill" {
|
||||
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
|
||||
out["id"] = id.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()
|
||||
}
|
||||
|
||||
fn answer(msg: &[u8], 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 req = match rebuild(msg) {
|
||||
Ok(r) => r,
|
||||
Err(code) => return Zeroizing::new(error(code, seq)),
|
||||
};
|
||||
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
|
||||
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 answer (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(|(_, v)| 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 (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, &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::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() {
|
||||
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap();
|
||||
assert_eq!(
|
||||
fill,
|
||||
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
|
||||
);
|
||||
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
|
||||
// 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"}"#,
|
||||
] {
|
||||
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
|
||||
}
|
||||
// Missing or wrong fields.
|
||||
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
|
||||
assert!(rebuild(b"not json").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
|
||||
let out = answer(br#"{"op":"browser_status","seq":3}"#, 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}"#, PIPE)).unwrap();
|
||||
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,9 @@ fn random<const N: usize>() -> Zeroizing<[u8; N]> {
|
||||
|
||||
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
|
||||
let mut k = Zeroizing::new([0u8; 32]);
|
||||
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
|
||||
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm)
|
||||
.expand(&info.concat(), k.as_mut())
|
||||
.expect("32 bytes is a valid HKDF length");
|
||||
k
|
||||
}
|
||||
|
||||
@@ -64,8 +66,8 @@ fn xnonce(n: &[u8]) -> XNonce {
|
||||
XNonce::try_from(n).expect("24-byte nonce")
|
||||
}
|
||||
|
||||
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
|
||||
/// wiped on drop.
|
||||
/// The one-time key pair of a device waiting for a secret. Its secret half is wiped on drop and leaves
|
||||
/// memory only through `secret_bytes`, for a caller that keeps a long-lived key (`from_secret`).
|
||||
pub struct Recipient {
|
||||
secret: StaticSecret,
|
||||
public: [u8; 32],
|
||||
@@ -78,6 +80,30 @@ impl Recipient {
|
||||
Recipient { secret, public }
|
||||
}
|
||||
|
||||
/// A long-lived key the caller kept (docs/SEAL.md, "A kept key"): the PC's Provisio sealing key, stored
|
||||
/// DPAPI-sealed and restored at start. Refuses a secret everyone knows: one that clamps to zero (a
|
||||
/// wiped or never-filled buffer), and, as `seal` does for a public key, one whose shared secrets would
|
||||
/// not be contributory.
|
||||
pub fn from_secret(secret: Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> {
|
||||
let secret = StaticSecret::from(*secret);
|
||||
let public = PublicKey::from(&secret).to_bytes();
|
||||
let zero = PublicKey::from(&StaticSecret::from([0u8; 32])).to_bytes();
|
||||
if public == zero {
|
||||
return Err(SealError::BadKey);
|
||||
}
|
||||
let probe = StaticSecret::from(*random::<32>());
|
||||
if !probe.diffie_hellman(&PublicKey::from(public)).was_contributory() {
|
||||
return Err(SealError::BadKey);
|
||||
}
|
||||
Ok(Recipient { secret, public })
|
||||
}
|
||||
|
||||
/// The secret half, for a caller that keeps this key (sealed with DPAPI or the like) instead of
|
||||
/// dropping it after one box. One-time keys never call this.
|
||||
pub fn secret_bytes(&self) -> Zeroizing<[u8; 32]> {
|
||||
Zeroizing::new(self.secret.to_bytes())
|
||||
}
|
||||
|
||||
/// What the device sends: 32 bytes.
|
||||
pub fn public(&self) -> [u8; 32] {
|
||||
self.public
|
||||
@@ -109,7 +135,7 @@ impl Recipient {
|
||||
|
||||
impl std::fmt::Debug for Recipient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
|
||||
write!(f, "Recipient {{ match_code: {}, secret: [redacted] }}", self.match_code())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,3 +72,47 @@ fn at_rest_seals_open_with_the_same_key_and_context_only() {
|
||||
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
|
||||
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_recipient_comes_back_from_its_secret() {
|
||||
// The PC keeps its Provisio sealing key (DPAPI-sealed) and restores it at the next start.
|
||||
let r = Recipient::generate();
|
||||
let kept = r.secret_bytes();
|
||||
let back = Recipient::from_secret(kept).unwrap();
|
||||
assert_eq!(back.public(), r.public());
|
||||
assert_eq!(back.match_code(), r.match_code());
|
||||
assert_eq!(back.secret_bytes().as_slice(), r.secret_bytes().as_slice());
|
||||
// A box sealed to the original opens with the restored key, for its purpose only.
|
||||
let ctx = b"provision-offer:vault:fabrica/gitea-read-token";
|
||||
let b = seal(&r.public(), ctx, b"gitea token").unwrap();
|
||||
assert_eq!(back.open(&b, ctx).unwrap().as_slice(), b"gitea token");
|
||||
assert_eq!(back.open(&b, b"provision-offer:vault:fabrica/other"), Err(SealError::Rejected));
|
||||
// Another kept key does not open it.
|
||||
let other = Recipient::from_secret(Recipient::generate().secret_bytes()).unwrap();
|
||||
assert_eq!(other.open(&b, ctx), Err(SealError::Rejected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_known_secret_is_refused() {
|
||||
// All zeros (a wiped or never-filled buffer) is a key everyone knows, and so is anything that clamps to it.
|
||||
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new([0u8; 32])).unwrap_err(), SealError::BadKey);
|
||||
let mut clamps_to_zero = [0u8; 32];
|
||||
clamps_to_zero[0] = 0b0000_0111;
|
||||
clamps_to_zero[31] = 0b1000_0000;
|
||||
assert_eq!(Recipient::from_secret(zeroize::Zeroizing::new(clamps_to_zero)).unwrap_err(), SealError::BadKey);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_recipient_prints_redacted() {
|
||||
let r = Recipient::generate();
|
||||
let secret = r.secret_bytes();
|
||||
let back = Recipient::from_secret(secret.clone()).unwrap();
|
||||
for shown in [format!("{r:?}"), format!("{back:?}"), format!("{back:#?}")] {
|
||||
assert!(shown.contains("[redacted]"), "{shown}");
|
||||
assert!(!shown.contains(&format!("{:?}", *secret)));
|
||||
assert!(!shown.contains(&format!("{:?}", &secret[..8])));
|
||||
let hex: String = secret.iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert!(!shown.contains(&hex[..16]));
|
||||
assert!(!shown.contains(&format!("{:?}", back.public())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ repository.workspace = true
|
||||
thiserror.workspace = true
|
||||
zeroize.workspace = true
|
||||
data-encoding.workspace = true
|
||||
# Deploy approvals: parsed, then written again in canonical form and compared.
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
|
||||
ed25519-dalek = "2"
|
||||
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! - 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).
|
||||
//!
|
||||
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
|
||||
|
||||
@@ -21,7 +23,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};
|
||||
@@ -36,6 +38,12 @@ use zeroize::Zeroizing;
|
||||
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;
|
||||
@@ -52,6 +60,10 @@ pub enum Error {
|
||||
BadKey,
|
||||
#[error("the certificate cannot be built or read")]
|
||||
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,
|
||||
}
|
||||
|
||||
/// An Ed25519 seed. Wiped on drop; never printed.
|
||||
@@ -288,8 +300,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))))
|
||||
}
|
||||
@@ -316,7 +328,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)?;
|
||||
@@ -329,7 +341,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 {
|
||||
@@ -344,6 +356,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);
|
||||
@@ -360,3 +425,180 @@ pub fn cert_pem(der: &[u8]) -> String {
|
||||
pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
// ---- deploy approvals ----
|
||||
|
||||
/// 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;
|
||||
|
||||
/// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Approval {
|
||||
pub run: String,
|
||||
pub repo: String,
|
||||
pub commit: String,
|
||||
pub pipeline: String,
|
||||
pub version: String,
|
||||
pub targets: Vec<String>,
|
||||
/// Unix seconds.
|
||||
pub expires: u64,
|
||||
}
|
||||
|
||||
/// The JSON as it is parsed: `v` first, the rest as [`Approval`].
|
||||
#[derive(serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ApprovalJson {
|
||||
v: u64,
|
||||
run: String,
|
||||
repo: String,
|
||||
commit: String,
|
||||
pipeline: String,
|
||||
version: String,
|
||||
targets: Vec<String>,
|
||||
expires: u64,
|
||||
}
|
||||
|
||||
impl Approval {
|
||||
/// The canonical text (docs/SIGNING.md): one line, no spaces, keys in the fixed order, `"` and `\` escaped,
|
||||
/// nothing else. Meaningful for an approval that passed [`approval_check`].
|
||||
pub fn canonical(&self) -> String {
|
||||
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('"');
|
||||
}
|
||||
let mut out = String::with_capacity(256);
|
||||
out.push_str("{\"v\":1,\"run\":");
|
||||
string(&mut out, &self.run);
|
||||
out.push_str(",\"repo\":");
|
||||
string(&mut out, &self.repo);
|
||||
out.push_str(",\"commit\":");
|
||||
string(&mut out, &self.commit);
|
||||
out.push_str(",\"pipeline\":");
|
||||
string(&mut out, &self.pipeline);
|
||||
out.push_str(",\"version\":");
|
||||
string(&mut out, &self.version);
|
||||
out.push_str(",\"targets\":[");
|
||||
for (i, t) in self.targets.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
string(&mut out, t);
|
||||
}
|
||||
out.push_str("],\"expires\":");
|
||||
out.push_str(&self.expires.to_string());
|
||||
out.push('}');
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A run id: `[A-Za-z0-9._-]{1,64}`.
|
||||
pub fn run_id_ok(run: &str) -> bool {
|
||||
(1..=64).contains(&run.len()) && run.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
|
||||
}
|
||||
|
||||
/// `[A-Za-z0-9._+-]{1,64}`: an approval's repo, pipeline and version.
|
||||
fn name_ok(s: &str) -> bool {
|
||||
(1..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"._+-".contains(&c))
|
||||
}
|
||||
|
||||
/// Characters a target may not hold: control characters, and the invisible ones that change how the rest of the
|
||||
/// line is shown on the card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen).
|
||||
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}')
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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"));
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// [`approval_check`] without the clock: the canonical form and every member's rule, not the expiry. For reading
|
||||
/// what a refused or expired request said; never enough to sign.
|
||||
pub fn approval_parse(text: &str) -> Result<Approval, Error> {
|
||||
let err = |why: &'static str| Err(Error::Approval(why));
|
||||
if text.len() > MAX_APPROVAL {
|
||||
return err("larger than 8 KiB");
|
||||
}
|
||||
let Ok(j) = serde_json::from_str::<ApprovalJson>(text) else {
|
||||
return err("not an approval in canonical form");
|
||||
};
|
||||
if j.v != 1 {
|
||||
return err("v is not 1");
|
||||
}
|
||||
let a = Approval {
|
||||
run: j.run,
|
||||
repo: j.repo,
|
||||
commit: j.commit,
|
||||
pipeline: j.pipeline,
|
||||
version: j.version,
|
||||
targets: j.targets,
|
||||
expires: j.expires,
|
||||
};
|
||||
if !run_id_ok(&a.run) {
|
||||
return err("the run is not a run id ([A-Za-z0-9._-], 1 to 64)");
|
||||
}
|
||||
if !name_ok(&a.repo) {
|
||||
return err("the repo is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||
}
|
||||
if a.commit.len() != 40 || !a.commit.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) {
|
||||
return err("the commit is not 40 lower-case hex digits");
|
||||
}
|
||||
if !name_ok(&a.pipeline) {
|
||||
return err("the pipeline is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||
}
|
||||
if !name_ok(&a.version) {
|
||||
return err("the version is not 1 to 64 of [A-Za-z0-9._+-]");
|
||||
}
|
||||
if !(1..=16).contains(&a.targets.len()) {
|
||||
return err("there must be 1 to 16 targets");
|
||||
}
|
||||
for t in &a.targets {
|
||||
if !(1..=80).contains(&t.chars().count()) {
|
||||
return err("a target is not 1 to 80 characters");
|
||||
}
|
||||
if t.chars().any(unprintable) {
|
||||
return err("a target has control or invisible characters");
|
||||
}
|
||||
}
|
||||
if a.canonical() != text {
|
||||
return err("not in canonical form (key order, spaces or escaping)");
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// Signs a deploy approval for `run` as prehashed minisign over the text's bytes, file name `approval-<run>.json`.
|
||||
/// The text is checked with [`approval_check`] at `timestamp` (Unix seconds) and must name `run`.
|
||||
pub fn approval(
|
||||
secret: &Ed25519Secret,
|
||||
key_id: &[u8; 8],
|
||||
text: &str,
|
||||
timestamp: u64,
|
||||
run: &str,
|
||||
) -> Result<String, Error> {
|
||||
let a = approval_check(text, timestamp)?;
|
||||
if a.run != run {
|
||||
return Err(Error::Approval("the approval's run is not the request's"));
|
||||
}
|
||||
minisign(secret, key_id, &blake2b512(text.as_bytes()), &format!("approval-{run}.json"), timestamp)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Deploy approvals (docs/SIGNING.md, "approval"): the canonical form is checked byte for byte, and the signature is
|
||||
//! a prehashed minisign over the text that minisign-verify (what Tauri and the hub's tools check with) accepts.
|
||||
|
||||
use custos_sign::*;
|
||||
|
||||
const NOW: u64 = 1_793_000_000;
|
||||
const COMMIT: &str = "3f2a9c1d0e4b5a6978877665544332211aabbccd";
|
||||
|
||||
/// The doc's example, with an expiry 10 minutes after NOW.
|
||||
fn canonical() -> String {
|
||||
format!(
|
||||
r#"{{"v":1,"run":"r-42","repo":"Arca","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
|
||||
NOW + 600
|
||||
)
|
||||
}
|
||||
|
||||
fn with(from: &str, to: &str) -> String {
|
||||
let t = canonical();
|
||||
assert!(t.contains(from), "{from:?}");
|
||||
t.replacen(from, to, 1)
|
||||
}
|
||||
|
||||
fn refused(text: &str, now: u64) -> String {
|
||||
match approval_check(text, now) {
|
||||
Ok(a) => panic!("accepted {text:?}: {a:?}"),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_canonical_approval_is_accepted_and_reads_back() {
|
||||
let a = approval_check(&canonical(), NOW).unwrap();
|
||||
assert_eq!(a.run, "r-42");
|
||||
assert_eq!(a.repo, "Arca");
|
||||
assert_eq!(a.commit, COMMIT);
|
||||
assert_eq!(a.pipeline, "release");
|
||||
assert_eq!(a.version, "0.7.0");
|
||||
assert_eq!(a.targets, ["deploy to nixos-vm", "publish to Aula"]);
|
||||
assert_eq!(a.expires, NOW + 600);
|
||||
assert_eq!(a.canonical(), canonical());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reordered_keys_spaces_and_other_shapes_are_refused() {
|
||||
let t = canonical();
|
||||
let reordered = with(r#""run":"r-42","repo":"Arca","#, r#""repo":"Arca","run":"r-42","#);
|
||||
let bad = [
|
||||
reordered,
|
||||
t.replace(',', ", "),
|
||||
t.replace(':', ": "),
|
||||
format!("{t}\n"),
|
||||
format!(" {t}"),
|
||||
t.replace("{\"v\"", "{\n\"v\""),
|
||||
with(r#""v":1,"#, r#""v":1,"x":1,"#),
|
||||
with(r#""v":1,"#, ""),
|
||||
with(r#""v":1,"#, r#""v":1,"v":1,"#),
|
||||
with(r#""v":1,"#, r#""v":2,"#),
|
||||
with(r#""v":1,"#, r#""v":1.0,"#),
|
||||
with(r#""v":1,"#, r#""v":"1","#),
|
||||
format!("[{t}]"),
|
||||
"not json".to_string(),
|
||||
String::new(),
|
||||
];
|
||||
for b in &bad {
|
||||
refused(b, NOW);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaping_must_be_minimal() {
|
||||
// A quote and a backslash in a target are escaped the one way JSON allows; the result is canonical.
|
||||
let q = with("publish to Aula", r#"say \"hi\" \\ there"#);
|
||||
assert_eq!(approval_check(&q, NOW).unwrap().targets[1], r#"say "hi" \ there"#);
|
||||
// Raw non-ASCII is canonical; the same text through \u escapes is not.
|
||||
let raw = with("publish to Aula", "publikovat na Aulu é");
|
||||
assert!(approval_check(&raw, NOW).is_ok());
|
||||
for b in [
|
||||
with("publish to Aula", r"publikovat na Aulu \u00e9"),
|
||||
with("publish to Aula", r"publish to \u0041ula"),
|
||||
with("publish to Aula", r"publish\/to Aula"),
|
||||
with("r-42", r"r\u002d42"),
|
||||
] {
|
||||
refused(&b, NOW);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_run_repo_pipeline_or_version_is_refused() {
|
||||
for run in ["", "r 42", "r/42", "r\\\\42", "ř-42", &"r".repeat(65)] {
|
||||
let e = refused(&with("\"run\":\"r-42\"", &format!("\"run\":\"{run}\"")), NOW);
|
||||
assert!(e.contains("run"), "{run:?}: {e}");
|
||||
}
|
||||
let ok_run = "a.B_c-9".to_string() + &"x".repeat(57);
|
||||
assert_eq!(ok_run.len(), 64);
|
||||
assert!(approval_check(&with("\"run\":\"r-42\"", &format!("\"run\":\"{ok_run}\"")), NOW).is_ok());
|
||||
for (member, value) in [("repo", "Arca"), ("pipeline", "release"), ("version", "0.7.0")] {
|
||||
let from = format!("\"{member}\":\"{value}\"");
|
||||
for bad in ["", "a b", "a/b", "a:b", &"a".repeat(65)] {
|
||||
let e = refused(&with(&from, &format!("\"{member}\":\"{bad}\"")), NOW);
|
||||
assert!(e.contains(member), "{member} {bad:?}: {e}");
|
||||
}
|
||||
let fine = format!("\"{member}\":\"A.b_c-1+x{}\"", "z".repeat(55));
|
||||
assert!(approval_check(&with(&from, &fine), NOW).is_ok(), "{fine}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_commit_is_refused() {
|
||||
for bad in [COMMIT.to_uppercase(), COMMIT[..39].to_string(), format!("{COMMIT}0"), COMMIT.replace('a', "g")] {
|
||||
let e = refused(&with(COMMIT, &bad), NOW);
|
||||
assert!(e.contains("commit"), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_have_limits() {
|
||||
let list = |ts: &[String]| ts.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
|
||||
let from = r#""targets":["deploy to nixos-vm","publish to Aula"]"#;
|
||||
let set = |ts: &[String]| with(from, &format!("\"targets\":[{}]", list(ts)));
|
||||
let n = |k: usize| (0..k).map(|i| format!("deploy to host-{i}")).collect::<Vec<_>>();
|
||||
|
||||
assert!(approval_check(&set(&n(1)), NOW).is_ok());
|
||||
assert!(approval_check(&set(&n(16)), NOW).is_ok());
|
||||
assert!(approval_check(&set(&["é".repeat(80)]), NOW).is_ok(), "80 characters, not bytes");
|
||||
for bad in [
|
||||
set(&[]),
|
||||
set(&n(17)),
|
||||
set(&[String::new()]),
|
||||
set(&["x".repeat(81)]),
|
||||
set(&["tab\\there".to_string()]),
|
||||
set(&["line\\nbreak".to_string()]),
|
||||
set(&["nul\\u0000".to_string()]),
|
||||
set(&["del\u{7f}".to_string()]),
|
||||
set(&["right-to-left \u{202e}evil".to_string()]),
|
||||
set(&["zero\u{200b}width".to_string()]),
|
||||
with(from, r#""targets":"deploy to nixos-vm""#),
|
||||
with(from, r#""targets":[1]"#),
|
||||
] {
|
||||
let e = refused(&bad, NOW);
|
||||
assert!(e.contains("target") || e.contains("form"), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expiry_is_after_now_and_within_an_hour() {
|
||||
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] {
|
||||
let e = refused(&at(exp), NOW);
|
||||
assert!(e.contains("expire"), "{exp}: {e}");
|
||||
}
|
||||
// The same text expires as time passes.
|
||||
assert!(refused(&canonical(), NOW + 600).contains("expire"));
|
||||
for bad in
|
||||
[format!("\"expires\":{}.0", NOW + 600), format!("\"expires\":-{}", NOW + 600), "\"expires\":\"1\"".into()]
|
||||
{
|
||||
refused(&with(&format!("\"expires\":{}", NOW + 600), &bad), NOW);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_text_is_refused_before_parsing() {
|
||||
let huge = with("publish to Aula", &"x".repeat(MAX_APPROVAL));
|
||||
assert!(refused(&huge, NOW).contains("larger"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_approval_signature_verifies_with_minisign() {
|
||||
let k = new_ed25519();
|
||||
let text = canonical();
|
||||
let sig = approval(&k.secret, &k.key_id, &text, NOW, "r-42").unwrap();
|
||||
let public = minisign_verify::PublicKey::decode(&minisign_public(&k.public, &k.key_id)).unwrap();
|
||||
let decoded = minisign_verify::Signature::decode(&sig).unwrap();
|
||||
public.verify(text.as_bytes(), &decoded, false).unwrap();
|
||||
assert!(public.verify(with("Arca", "Fabrica").as_bytes(), &decoded, false).is_err());
|
||||
assert_eq!(decoded.trusted_comment(), format!("timestamp:{NOW}\tfile:approval-r-42.json\thashed"));
|
||||
assert!(sig.ends_with('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approval_signs_only_a_valid_text_for_its_own_run() {
|
||||
let k = new_ed25519();
|
||||
let e = approval(&k.secret, &k.key_id, &canonical(), NOW, "r-43").unwrap_err();
|
||||
assert!(e.to_string().contains("run"), "{e}");
|
||||
assert!(approval(&k.secret, &k.key_id, &format!("{}\n", canonical()), NOW, "r-42").is_err());
|
||||
assert!(approval(&k.secret, &k.key_id, &canonical(), NOW + 600, "r-42").is_err(), "expired at signing time");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_reads_the_form_without_the_clock() {
|
||||
// For the audit of a refused or expired request: everything but the expiry is checked.
|
||||
let a = approval_parse(&canonical()).unwrap();
|
||||
assert_eq!(a, approval_check(&canonical(), NOW).unwrap());
|
||||
assert!(approval_check(&canonical(), NOW + 10_000).is_err());
|
||||
assert_eq!(approval_parse(&canonical()).unwrap().expires, NOW + 600);
|
||||
assert!(approval_parse(&canonical().replace(',', ", ")).is_err());
|
||||
assert!(approval_parse(&with("\"run\":\"r-42\"", "\"run\":\"r 42\"")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_ids_follow_the_rule() {
|
||||
for ok in ["r-42", "setup-1", "a.b_c", &"x".repeat(64)] {
|
||||
assert!(run_id_ok(ok), "{ok}");
|
||||
}
|
||||
for bad in ["", "a b", "a/b", "ř", &"x".repeat(65)] {
|
||||
assert!(!run_id_ok(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
+2
@@ -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).
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -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();
|
||||
|
||||
@@ -21,8 +21,10 @@ mod device;
|
||||
mod format;
|
||||
pub mod identity;
|
||||
mod item;
|
||||
pub mod provision;
|
||||
mod save;
|
||||
mod secret;
|
||||
pub mod security;
|
||||
pub mod signing;
|
||||
|
||||
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
||||
@@ -79,6 +81,12 @@ pub enum Error {
|
||||
UnknownKey,
|
||||
#[error("this vault already has {0} signing keys")]
|
||||
SigningExists(&'static str),
|
||||
/// Names the member that does not fit (docs/FORMAT.md), never its value.
|
||||
#[error("provision audit: {0}")]
|
||||
Provision(&'static str),
|
||||
/// Names the rule a security change breaks (docs/FORMAT.md, "The security member"), never a value.
|
||||
#[error("security: {0}")]
|
||||
Security(&'static str),
|
||||
#[error("signing keys: {0}")]
|
||||
Signing(String),
|
||||
#[error("{0}")]
|
||||
@@ -274,6 +282,10 @@ struct Body {
|
||||
identity: Option<identity::RootJson>,
|
||||
#[serde(default)]
|
||||
signing: Option<signing::StoreJson>,
|
||||
#[serde(default)]
|
||||
provision: Option<provision::ProvisionJson>,
|
||||
#[serde(default)]
|
||||
security: Option<security::State>,
|
||||
}
|
||||
|
||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||
@@ -287,6 +299,10 @@ struct BodyRef<'a> {
|
||||
identity: Option<identity::RootJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
signing: Option<signing::StoreJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
provision: Option<provision::ProvisionJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
security: Option<security::State>,
|
||||
}
|
||||
|
||||
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||
@@ -303,6 +319,10 @@ pub struct Vault {
|
||||
identity: Option<identity::Root>,
|
||||
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
|
||||
signing: signing::Store,
|
||||
/// The Provisio audit (docs/FORMAT.md), oldest first.
|
||||
provision: Vec<provision::ProvisionEntry>,
|
||||
/// The security level's Setup window, the checklist and their audit (docs/FORMAT.md).
|
||||
security: security::State,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Vault {
|
||||
@@ -403,6 +423,8 @@ impl Vault {
|
||||
kdf_new: kdf,
|
||||
identity: None,
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -420,6 +442,8 @@ impl Vault {
|
||||
kdf_new: kdf,
|
||||
identity: None,
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
};
|
||||
v.add_factor(a, label_a)?;
|
||||
v.add_factor(b, label_b)?;
|
||||
@@ -453,6 +477,8 @@ impl Vault {
|
||||
kdf_new: KdfParams::DEFAULT,
|
||||
identity: None,
|
||||
signing: signing::Store::default(),
|
||||
provision: Vec::new(),
|
||||
security: security::State::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -578,6 +604,7 @@ impl Vault {
|
||||
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
|
||||
None => signing::Store::default(),
|
||||
};
|
||||
let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?;
|
||||
Ok(Vault {
|
||||
key,
|
||||
version: header.version,
|
||||
@@ -587,6 +614,8 @@ impl Vault {
|
||||
kdf_new,
|
||||
identity,
|
||||
signing,
|
||||
provision: provision::from_json(body.provision),
|
||||
security,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -622,6 +651,8 @@ impl Vault {
|
||||
factors: self.factors.iter().map(FactorRec::json).collect(),
|
||||
identity: self.identity.as_ref().map(identity::Root::json),
|
||||
signing: self.signing.json(),
|
||||
provision: provision::json(&self.provision),
|
||||
security: self.security.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);
|
||||
@@ -659,6 +690,37 @@ impl Vault {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A machine-key vault: one device factor opens it alone (a Claude Code store, or Custos's hands-off vault
|
||||
/// before it is taken over).
|
||||
pub fn opens_with_machine_key(&self) -> bool {
|
||||
self.is_store()
|
||||
}
|
||||
|
||||
/// *Take over the vault* (Custos docs/12_hands_off.md, section 6): adds the master password as a factor paired
|
||||
/// with the device key, removes the PC-only access, and ticks the items that end unattended work. Returns the
|
||||
/// password factor's id. Only on a machine-key vault, once. The caller saves.
|
||||
pub fn take_over(&mut self, password: &SecretString, kdf: KdfParams, now: i64) -> Result<String, Error> {
|
||||
if !self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
let slots = self.slots.clone();
|
||||
let kdf_was = self.kdf_new;
|
||||
// Without its single slot the vault is an ordinary version-2 vault with one factor; the password pairs with it.
|
||||
self.slots.retain(|s| s.kind != format::SLOT_SINGLE);
|
||||
self.kdf_new = kdf;
|
||||
match self.add_factor(Unlock::Password(password), "Master password") {
|
||||
Ok(id) => {
|
||||
self.security_taken_over(now);
|
||||
Ok(id)
|
||||
}
|
||||
Err(e) => {
|
||||
self.slots = slots;
|
||||
self.kdf_new = kdf_was;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The Provisio audit (docs/FORMAT.md, "The provision audit"): the vault body member `provision`, beside
|
||||
//! signing's audit. One entry per outcome of a server's ask or offer. An entry holds no secret: every member is
|
||||
//! something the server sent in the clear through the mailbox, or the match code of a public key.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Vault};
|
||||
|
||||
/// The log keeps the newest this many entries.
|
||||
pub const AUDIT_LIMIT: usize = 5_000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Direction {
|
||||
/// The server asked Custos for a secret (or asked it to make one).
|
||||
Ask,
|
||||
/// The server offered a secret it made.
|
||||
Offer,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Store {
|
||||
/// A Domi-ref item in the vault.
|
||||
Vault,
|
||||
/// The local Claude Code store.
|
||||
Claude,
|
||||
/// The cloud Claude Code store.
|
||||
Cloud,
|
||||
/// Shown once on the card and stored nowhere: a display offer (core 0.12.0).
|
||||
Display,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Outcome {
|
||||
/// Ask: Mark approved; the item's value was sealed to the request.
|
||||
Approved,
|
||||
/// Ask with `--generate`: Custos made the item, stored it and sealed it to the request.
|
||||
Generated,
|
||||
/// Offer: Mark accepted; the value was stored.
|
||||
Accepted,
|
||||
/// Mark refused on the card.
|
||||
Refused,
|
||||
/// Outside the scope: refused before a card, or again when storing.
|
||||
OutOfScope,
|
||||
/// An offer's box did not match the offer (item, store, kind or code key), or did not open.
|
||||
Invalid,
|
||||
/// Nobody answered within five minutes.
|
||||
Expired,
|
||||
/// A display offer: Mark typed the code the phone shows, Custos checked it and sent it (core 0.12.0).
|
||||
Confirmed,
|
||||
}
|
||||
|
||||
/// One audit entry. Append-only: nothing edits or removes one.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProvisionEntry {
|
||||
/// Unix milliseconds.
|
||||
pub at: i64,
|
||||
pub direction: Direction,
|
||||
/// The name the factor service gave the server.
|
||||
pub host: String,
|
||||
pub item: String,
|
||||
pub store: Store,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub run: Option<String>,
|
||||
/// An offer's label (`--kind`), or an ask's `--generate` recipe.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kind: Option<String>,
|
||||
/// The match code both screens showed: six digits.
|
||||
pub code: String,
|
||||
pub outcome: Outcome,
|
||||
/// An accepted offer replaced an existing item.
|
||||
#[serde(default)]
|
||||
pub replaced: bool,
|
||||
}
|
||||
|
||||
/// The body member: `{"audit": [...]}`.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct ProvisionJson {
|
||||
#[serde(default)]
|
||||
audit: Vec<ProvisionEntry>,
|
||||
}
|
||||
|
||||
/// The log as the vault keeps it, oldest first.
|
||||
pub(crate) fn from_json(j: Option<ProvisionJson>) -> Vec<ProvisionEntry> {
|
||||
let mut audit = j.map(|j| j.audit).unwrap_or_default();
|
||||
trim(&mut audit);
|
||||
audit
|
||||
}
|
||||
|
||||
/// Absent while the log is empty, so a vault without entries is written exactly as before.
|
||||
pub(crate) fn json(audit: &[ProvisionEntry]) -> Option<ProvisionJson> {
|
||||
(!audit.is_empty()).then(|| ProvisionJson { audit: audit.to_vec() })
|
||||
}
|
||||
|
||||
fn trim(audit: &mut Vec<ProvisionEntry>) {
|
||||
if audit.len() > AUDIT_LIMIT {
|
||||
audit.drain(..audit.len() - AUDIT_LIMIT);
|
||||
}
|
||||
}
|
||||
|
||||
/// `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks an item.
|
||||
fn item_ok(item: &str) -> bool {
|
||||
let parts: Vec<&str> = item.split('/').collect();
|
||||
parts.len() <= 4
|
||||
&& parts.iter().all(|p| {
|
||||
let b = p.as_bytes();
|
||||
(1..=64).contains(&b.len())
|
||||
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
|
||||
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(c))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProvisionEntry {
|
||||
/// Whether every member fits docs/FORMAT.md. The error names the member, never its value.
|
||||
pub fn check(&self) -> Result<(), Error> {
|
||||
let host = self.host.as_bytes();
|
||||
if !(1..=253).contains(&host.len()) || !host.iter().all(|c| c.is_ascii_alphanumeric() || b".-".contains(c)) {
|
||||
return Err(Error::Provision("the host is not a host name"));
|
||||
}
|
||||
if !item_ok(&self.item) {
|
||||
return Err(Error::Provision("the item is not an item name"));
|
||||
}
|
||||
if let Some(run) = &self.run {
|
||||
let r = run.as_bytes();
|
||||
if !(1..=64).contains(&r.len()) || !r.iter().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(c)) {
|
||||
return Err(Error::Provision("the run is not a run id"));
|
||||
}
|
||||
}
|
||||
if let Some(kind) = &self.kind
|
||||
&& (kind.chars().count() > 200 || kind.chars().any(char::is_control))
|
||||
{
|
||||
return Err(Error::Provision("the kind is longer than 200 characters or has control characters"));
|
||||
}
|
||||
if self.code.len() != 6 || !self.code.bytes().all(|c| c.is_ascii_digit()) {
|
||||
return Err(Error::Provision("the match code is not six digits"));
|
||||
}
|
||||
// A display offer stores nothing; `confirmed` is its outcome and nobody else's.
|
||||
if self.store == Store::Display {
|
||||
if self.direction != Direction::Offer {
|
||||
return Err(Error::Provision("a display is an offer"));
|
||||
}
|
||||
if matches!(self.outcome, Outcome::Accepted | Outcome::Approved | Outcome::Generated) || self.replaced {
|
||||
return Err(Error::Provision("a display offer stores nothing"));
|
||||
}
|
||||
} else if self.outcome == Outcome::Confirmed {
|
||||
return Err(Error::Provision("only a display offer is confirmed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// Records one outcome, after `ProvisionEntry::check`. Beyond `AUDIT_LIMIT` entries the oldest goes. The
|
||||
/// caller saves.
|
||||
pub fn provision_record(&mut self, entry: ProvisionEntry) -> Result<(), Error> {
|
||||
entry.check()?;
|
||||
self.provision.push(entry);
|
||||
trim(&mut self.provision);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every outcome, oldest first (newest last).
|
||||
pub fn provision_audit(&self) -> &[ProvisionEntry] {
|
||||
&self.provision
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! An older reader still opens a vault with the member. It lives here because only the crate can decrypt the
|
||||
//! body and parse it the way core 0.10.0 did.
|
||||
use super::*;
|
||||
use crate::format::Header;
|
||||
use crate::{FactorJson, Item, ItemType, KdfParams, SecretString, crypto, identity, signing};
|
||||
|
||||
/// The body as core 0.10.0 parsed it (src/lib.rs `Body` at v0.10.0): no `provision`.
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct BodyV0_10 {
|
||||
format: u32,
|
||||
items: Vec<Item>,
|
||||
#[serde(default)]
|
||||
factors: Vec<FactorJson>,
|
||||
#[serde(default)]
|
||||
identity: Option<identity::RootJson>,
|
||||
#[serde(default)]
|
||||
signing: Option<signing::StoreJson>,
|
||||
}
|
||||
|
||||
fn body_json(v: &Vault) -> String {
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let (header, at) = Header::parse(&bytes).unwrap();
|
||||
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
|
||||
String::from_utf8(json.to_vec()).unwrap()
|
||||
}
|
||||
|
||||
fn entry() -> ProvisionEntry {
|
||||
ProvisionEntry {
|
||||
at: 1_793_750_000_000,
|
||||
direction: Direction::Offer,
|
||||
host: "nixos-vm".into(),
|
||||
item: "arca/gitea-read-token".into(),
|
||||
store: Store::Vault,
|
||||
run: None,
|
||||
kind: Some("Gitea token, read:repository".into()),
|
||||
code: "684361".into(),
|
||||
outcome: Outcome::Accepted,
|
||||
replaced: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_opens_a_vault_with_the_provision_audit() {
|
||||
let mut v =
|
||||
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
v.add(Item::new(ItemType::SecureNote, "kept", 1));
|
||||
// Without entries the body has no trace of the member, so it is byte-for-byte what 0.10.0 wrote.
|
||||
assert!(!body_json(&v).contains("provision"));
|
||||
|
||||
v.provision_record(entry()).unwrap();
|
||||
let json = body_json(&v);
|
||||
assert!(json.contains(r#""provision":{"audit":[{"#), "{json}");
|
||||
// Core 0.10.0's parser takes it and keeps everything it knows.
|
||||
let old: BodyV0_10 = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(old.format, 1);
|
||||
assert_eq!(old.items.len(), 1);
|
||||
assert_eq!(old.items[0].title, "kept");
|
||||
assert!(old.identity.is_none() && old.signing.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,883 @@
|
||||
//! The security level and the hardening checklist (docs/FORMAT.md, "The security member"): the vault body member
|
||||
//! `security`. The level is computed from the Setup window and the ticked items, never stored; every change is in an
|
||||
//! append-only audit. Nothing here is secret.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Vault};
|
||||
|
||||
/// The log keeps the newest this many entries.
|
||||
pub const AUDIT_LIMIT: usize = 5_000;
|
||||
/// How long Setup lasts from *Connect via SSH*, in milliseconds: 2 hours.
|
||||
pub const SETUP_WINDOW: i64 = 2 * 60 * 60 * 1000;
|
||||
|
||||
/// A checklist item.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Item {
|
||||
/// Move the Authelia TOTP to my phone.
|
||||
TotpOnPhone,
|
||||
/// Approve with Windows Hello.
|
||||
HelloApprovals,
|
||||
/// Narrow the server scope.
|
||||
NarrowScope,
|
||||
/// Rotate what setup made.
|
||||
RotateSetup,
|
||||
/// Turn off Connect via SSH.
|
||||
NoSsh,
|
||||
/// The phone approves this PC.
|
||||
PhoneApproves,
|
||||
/// Turn off auto-connect (Custos docs/12_hands_off.md).
|
||||
NoAutoConnect,
|
||||
/// Never accept unattended: a new connect opens no Setup window.
|
||||
NoUnattended,
|
||||
/// Sign only with a card.
|
||||
CardSigning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Level {
|
||||
/// From *Connect via SSH* until 2 hours later or *Finish setup*.
|
||||
Setup,
|
||||
/// After Setup, and every vault that never had one.
|
||||
Standard,
|
||||
/// Not in Setup, and at least one checklist item ticked.
|
||||
Hardened,
|
||||
}
|
||||
|
||||
/// How an undo was confirmed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Auth {
|
||||
Hello,
|
||||
Password,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Action {
|
||||
SetupStarted,
|
||||
SetupFinished,
|
||||
/// Written by the first change after the window ended on its own.
|
||||
SetupExpired,
|
||||
Ticked,
|
||||
Unticked,
|
||||
SshConnected,
|
||||
TotpMoved,
|
||||
/// Connected by itself at start (`detail`: where and as whom).
|
||||
AutoConnected,
|
||||
/// A setup run stored items without a card (`detail`: the run and the item names).
|
||||
UnattendedStored,
|
||||
/// One of those items was removed (`detail`: the run and the item).
|
||||
SetupItemRemoved,
|
||||
/// Signed without a card (`detail`: the key, the kind, the run and the file).
|
||||
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,
|
||||
}
|
||||
|
||||
/// What *Connect via SSH* needs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum SshRule {
|
||||
/// Offered, one click (Setup).
|
||||
Allowed,
|
||||
/// Offered after Windows Hello or the master password.
|
||||
NeedsAuth,
|
||||
/// Not offered (*Turn off Connect via SSH* is ticked).
|
||||
Off,
|
||||
}
|
||||
|
||||
/// A Setup window, Unix milliseconds: Setup holds for `started <= now < until`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Window {
|
||||
pub started: i64,
|
||||
pub until: i64,
|
||||
}
|
||||
|
||||
/// The server scope prefixes *Narrow the server scope* replaced, kept for its undo.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct KeptScope {
|
||||
#[serde(default)]
|
||||
pub ask: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub offer: Vec<String>,
|
||||
}
|
||||
|
||||
/// One audit entry. Append-only: nothing edits or removes one.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SecurityEntry {
|
||||
/// Unix milliseconds.
|
||||
pub at: i64,
|
||||
pub action: Action,
|
||||
/// The checklist item, for `ticked` and `unticked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub item: Option<Item>,
|
||||
/// How an undo was confirmed, for `unticked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auth: Option<Auth>,
|
||||
/// What a note says (`auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`): names,
|
||||
/// never a value. At most 500 characters, no control characters.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything *Settings → Security* shows.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SecurityView {
|
||||
pub level: Level,
|
||||
/// The last Setup window, if there was one.
|
||||
pub setup: Option<Window>,
|
||||
/// When that window ended (Finish setup, or `until` once its expiry was noticed).
|
||||
pub finished: Option<i64>,
|
||||
/// Milliseconds of Setup left, while in Setup.
|
||||
pub setup_remaining: Option<i64>,
|
||||
pub ticked: BTreeSet<Item>,
|
||||
pub kept_scope: Option<KeptScope>,
|
||||
/// Oldest first.
|
||||
pub audit: Vec<SecurityEntry>,
|
||||
}
|
||||
|
||||
/// The member as the vault keeps it, and as it is written.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct State {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
setup: Option<Window>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
finished: Option<i64>,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
ticked: BTreeSet<Item>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
kept_scope: Option<KeptScope>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
audit: Vec<SecurityEntry>,
|
||||
}
|
||||
|
||||
/// At most this many prefixes on each side of a kept scope.
|
||||
const KEPT_MAX: usize = 64;
|
||||
|
||||
/// A kept scope prefix: 1 to 200 characters, no control characters. The error names the rule, never the value.
|
||||
fn kept_ok(list: &[String]) -> Result<(), Error> {
|
||||
if list.len() > KEPT_MAX {
|
||||
return Err(Error::Security("a kept scope has at most 64 prefixes on each side"));
|
||||
}
|
||||
if list.iter().any(|p| !(1..=200).contains(&p.chars().count()) || p.chars().any(char::is_control)) {
|
||||
return Err(Error::Security("a kept scope prefix is 1 to 200 characters without control characters"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A note's detail: 1 to 500 characters, no control characters. The error names the rule, never the text.
|
||||
fn detail_ok(d: &str) -> Result<(), Error> {
|
||||
if !(1..=500).contains(&d.chars().count()) || d.chars().any(char::is_control) {
|
||||
return Err(Error::Security("a note is 1 to 500 characters without control characters"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trim(audit: &mut Vec<SecurityEntry>) {
|
||||
if audit.len() > AUDIT_LIMIT {
|
||||
audit.drain(..audit.len() - AUDIT_LIMIT);
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The member as read, checked; `None` when it breaks a rule (the vault then does not open).
|
||||
pub(crate) fn from_json(j: Option<State>) -> Option<State> {
|
||||
let mut st = j.unwrap_or_default();
|
||||
if let Some(w) = st.setup
|
||||
&& w.until <= w.started
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if st.finished.is_some() && st.setup.is_none() {
|
||||
return None;
|
||||
}
|
||||
if let Some(k) = &st.kept_scope
|
||||
&& (kept_ok(&k.ask).is_err() || kept_ok(&k.offer).is_err())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
trim(&mut st.audit);
|
||||
Some(st)
|
||||
}
|
||||
|
||||
/// Absent while nothing was ever set, so a vault without it is written exactly as before.
|
||||
pub(crate) fn json(&self) -> Option<State> {
|
||||
(*self != State::default()).then(|| self.clone())
|
||||
}
|
||||
|
||||
/// Setup holds for `started <= now < until` of a window that has not finished.
|
||||
fn in_setup(&self, now: i64) -> bool {
|
||||
self.finished.is_none() && self.setup.is_some_and(|w| w.started <= now && now < w.until)
|
||||
}
|
||||
|
||||
fn level(&self, now: i64) -> Level {
|
||||
if self.in_setup(now) {
|
||||
Level::Setup
|
||||
} else if self.ticked.is_empty() {
|
||||
Level::Standard
|
||||
} else {
|
||||
Level::Hardened
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, at: i64, action: Action, item: Option<Item>, auth: Option<Auth>) {
|
||||
self.audit.push(SecurityEntry { at, action, item, auth, detail: None });
|
||||
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);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if let Some(w) = self.setup
|
||||
&& self.finished.is_none()
|
||||
&& now >= w.until
|
||||
{
|
||||
self.finished = Some(w.until);
|
||||
self.push(now, Action::SetupExpired, None, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// *Accept all* on a run card: only in Setup, for a setup run (its id starts with `setup-`) that holds Provisio
|
||||
/// lines only.
|
||||
pub fn accept_all_allowed(level: Level, run_id: &str, only_provision: bool) -> bool {
|
||||
level == Level::Setup && run_id.starts_with("setup-") && only_provision
|
||||
}
|
||||
|
||||
/// Whether a line that replaces a stored item starts ticked: only where *Accept all* applies (a setup run in
|
||||
/// Setup); otherwise Mark ticks it himself.
|
||||
pub fn replacing_line_preticked(level: Level, setup_run: bool) -> bool {
|
||||
level == Level::Setup && setup_run
|
||||
}
|
||||
|
||||
/// What *Connect via SSH* needs: off when *Turn off Connect via SSH* is ticked, one click in Setup, Windows Hello or
|
||||
/// the master password otherwise.
|
||||
pub fn ssh_needs_auth(level: Level, ticked: &BTreeSet<Item>) -> SshRule {
|
||||
if ticked.contains(&Item::NoSsh) {
|
||||
SshRule::Off
|
||||
} else if level == Level::Setup {
|
||||
SshRule::Allowed
|
||||
} else {
|
||||
SshRule::NeedsAuth
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a server may offer a TOTP seed into the vault: not once it was moved to the phone.
|
||||
pub fn totp_offer_allowed(ticked: &BTreeSet<Item>) -> bool {
|
||||
!ticked.contains(&Item::TotpOnPhone)
|
||||
}
|
||||
|
||||
/// The Provisio namespaces a setup run may fill without a card (Custos docs/12_hands_off.md, section 3).
|
||||
pub const UNATTENDED_NAMESPACES: [&str; 5] = ["arca/", "custos/", "fabrica/", "aula/", "gitea/"];
|
||||
|
||||
/// A setup run's id: `setup-` and 1 to 58 of `[A-Za-z0-9._-]`.
|
||||
pub fn is_setup_run(run: &str) -> bool {
|
||||
run.strip_prefix("setup-").is_some_and(|rest| {
|
||||
(1..=58).contains(&rest.len()) && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether Custos may connect to the factor service by itself (at start, with no device token).
|
||||
pub fn auto_connect_allowed(level: Level, ticked: &BTreeSet<Item>) -> bool {
|
||||
level != Level::Hardened && !ticked.contains(&Item::NoAutoConnect) && !ticked.contains(&Item::NoSsh)
|
||||
}
|
||||
|
||||
/// Whether a new connection opens the Setup window.
|
||||
pub fn setup_on_connect(ticked: &BTreeSet<Item>) -> bool {
|
||||
!ticked.contains(&Item::NoUnattended) && !ticked.contains(&Item::NoSsh)
|
||||
}
|
||||
|
||||
/// Ask or offer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Verb {
|
||||
Ask,
|
||||
Offer,
|
||||
}
|
||||
|
||||
/// Where a Provisio line goes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Store {
|
||||
Vault,
|
||||
Claude,
|
||||
Display,
|
||||
}
|
||||
|
||||
/// A Provisio line as the unattended rule sees it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ProvisionAsk<'a> {
|
||||
pub verb: Verb,
|
||||
/// `--generate`: Custos makes the value.
|
||||
pub generate: bool,
|
||||
/// The item exists already (an ask would read it, an offer would replace it).
|
||||
pub exists: bool,
|
||||
pub store: Store,
|
||||
pub item: &'a str,
|
||||
/// An offer of kind `totp`.
|
||||
pub totp: bool,
|
||||
}
|
||||
|
||||
/// Whether a Provisio line is answered without a card: a setup run, in Setup, new items in the allowed namespaces.
|
||||
pub fn unattended_provision(level: Level, ticked: &BTreeSet<Item>, run: &str, req: &ProvisionAsk) -> bool {
|
||||
if level != Level::Setup || !is_setup_run(run) || ticked.contains(&Item::NoUnattended) || req.exists {
|
||||
return false;
|
||||
}
|
||||
if req.totp && !totp_offer_allowed(ticked) {
|
||||
return false;
|
||||
}
|
||||
match (req.store, req.verb) {
|
||||
// The Claude Code store takes the names the server offers; it is never read this way.
|
||||
(Store::Claude, Verb::Offer) => true,
|
||||
(Store::Vault, Verb::Ask) if !req.generate => false,
|
||||
(Store::Vault, _) => UNATTENDED_NAMESPACES
|
||||
.iter()
|
||||
.any(|ns| req.item.strip_prefix(ns).is_some_and(|rest| !rest.is_empty() && !rest.contains(".."))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a run's signature is made without a card: a machine-key vault (not taken over), the release kinds.
|
||||
pub fn unattended_sign(
|
||||
level: Level,
|
||||
ticked: &BTreeSet<Item>,
|
||||
machine_key_vault: bool,
|
||||
kind: &str,
|
||||
has_run: bool,
|
||||
) -> bool {
|
||||
machine_key_vault
|
||||
&& has_run
|
||||
&& level != Level::Hardened
|
||||
&& !ticked.contains(&Item::CardSigning)
|
||||
&& matches!(kind, "minisign" | "manifest" | "authenticode" | "approval")
|
||||
}
|
||||
|
||||
/// Whether *Sign & release*, *Accept*, *Accept all* and approvals ask for Windows Hello first.
|
||||
pub fn hello_for_approvals(ticked: &BTreeSet<Item>) -> bool {
|
||||
ticked.contains(&Item::HelloApprovals)
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// The level at `now` (Unix milliseconds).
|
||||
pub fn security_level(&self, now: i64) -> Level {
|
||||
self.security.level(now)
|
||||
}
|
||||
|
||||
/// The level, the Setup window and what is left of it, the ticked items, the kept scope and the audit.
|
||||
pub fn security_view(&self, now: i64) -> SecurityView {
|
||||
let st = &self.security;
|
||||
SecurityView {
|
||||
level: st.level(now),
|
||||
setup: st.setup,
|
||||
finished: st.finished,
|
||||
setup_remaining: st.setup.filter(|_| st.in_setup(now)).map(|w| w.until - now),
|
||||
ticked: st.ticked.clone(),
|
||||
kept_scope: st.kept_scope.clone(),
|
||||
audit: st.audit.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts Setup (*Connect via SSH*): a window of 2 hours from `now`, audited `setup-started`. While in Setup it
|
||||
/// changes nothing and returns the window that holds. The caller saves.
|
||||
pub fn security_start_setup(&mut self, now: i64) -> Window {
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
if st.in_setup(now)
|
||||
&& let Some(w) = st.setup
|
||||
{
|
||||
return w;
|
||||
}
|
||||
let w = Window { started: now, until: now.saturating_add(SETUP_WINDOW) };
|
||||
st.setup = Some(w);
|
||||
st.finished = None;
|
||||
st.push(now, Action::SetupStarted, None, None);
|
||||
w
|
||||
}
|
||||
|
||||
/// *Finish setup*: ends the window at `now`, audited `setup-finished`. False when not in Setup. The caller saves.
|
||||
pub fn security_finish_setup(&mut self, now: i64) -> bool {
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
if !st.in_setup(now) {
|
||||
return false;
|
||||
}
|
||||
st.finished = Some(now);
|
||||
st.push(now, Action::SetupFinished, None, None);
|
||||
true
|
||||
}
|
||||
|
||||
/// Ticks a checklist item, audited `ticked`. False (and no entry) when it was ticked already. The caller saves.
|
||||
pub fn security_tick(&mut self, item: Item, now: i64) -> bool {
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
if !st.ticked.insert(item) {
|
||||
return false;
|
||||
}
|
||||
st.push(now, Action::Ticked, Some(item), None);
|
||||
true
|
||||
}
|
||||
|
||||
/// Unticks a checklist item after Windows Hello or the master password, audited `unticked` with how. False (and
|
||||
/// no entry) when it was not ticked. The caller saves.
|
||||
pub fn security_untick(&mut self, item: Item, auth: Auth, now: i64) -> bool {
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
if !st.ticked.remove(&item) {
|
||||
return false;
|
||||
}
|
||||
st.push(now, Action::Unticked, Some(item), Some(auth));
|
||||
true
|
||||
}
|
||||
|
||||
/// Keeps the scope prefixes *Narrow the server scope* replaces. Refused when a scope is kept already (its undo
|
||||
/// has not taken it back), so the first prefixes are never lost. The caller saves.
|
||||
pub fn security_keep_scope(&mut self, ask: &[String], offer: &[String]) -> Result<(), Error> {
|
||||
if self.security.kept_scope.is_some() {
|
||||
return Err(Error::Security("a scope is kept already; take it back first"));
|
||||
}
|
||||
kept_ok(ask)?;
|
||||
kept_ok(offer)?;
|
||||
self.security.kept_scope = Some(KeptScope { ask: ask.to_vec(), offer: offer.to_vec() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes the kept prefixes back, for the undo. The caller saves.
|
||||
pub fn security_take_kept_scope(&mut self) -> Option<KeptScope> {
|
||||
self.security.kept_scope.take()
|
||||
}
|
||||
|
||||
/// Records a note with its detail: `auto-connected`, `unattended-stored`, `setup-item-removed` or
|
||||
/// `unattended-signed`. The caller saves.
|
||||
pub fn security_note(&mut self, action: Action, detail: &str, now: i64) -> Result<(), Error> {
|
||||
if !matches!(
|
||||
action,
|
||||
Action::AutoConnected | Action::UnattendedStored | Action::SetupItemRemoved | Action::UnattendedSigned
|
||||
) {
|
||||
return Err(Error::Security(
|
||||
"only auto-connected, unattended-stored, setup-item-removed and unattended-signed are notes",
|
||||
));
|
||||
}
|
||||
detail_ok(detail)?;
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
st.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail.to_owned()) });
|
||||
trim(&mut st.audit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The take-over's half in this member: ticks the items that end unattended work and writes `taken-over`.
|
||||
pub(crate) fn security_taken_over(&mut self, now: i64) {
|
||||
self.security.notice_expiry(now);
|
||||
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
|
||||
self.security_tick(item, now);
|
||||
}
|
||||
self.security.push(now, Action::TakenOver, None, None);
|
||||
}
|
||||
|
||||
/// Records `ssh-connected` or `totp-moved`; the other actions are written by the calls above. The caller saves.
|
||||
pub fn security_record(&mut self, action: Action, item: Option<Item>, now: i64) -> Result<(), Error> {
|
||||
if !matches!(action, Action::SshConnected | Action::TotpMoved) {
|
||||
return Err(Error::Security("only ssh-connected and totp-moved are recorded directly"));
|
||||
}
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
st.push(now, action, item, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! An older reader still opens a vault with the member, and unknown values make the vault refuse to open. They
|
||||
//! live here because only the crate can decrypt the body, change it and seal it again.
|
||||
use super::*;
|
||||
use crate::format::Header;
|
||||
use crate::{FactorJson, Item as VaultItem, ItemType, KdfParams, SecretString, crypto, identity, provision};
|
||||
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
|
||||
fn vault() -> Vault {
|
||||
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap()
|
||||
}
|
||||
|
||||
fn body_json(v: &Vault) -> String {
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let (header, at) = Header::parse(&bytes).unwrap();
|
||||
let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap();
|
||||
String::from_utf8(json.to_vec()).unwrap()
|
||||
}
|
||||
|
||||
/// The vault's file with its body replaced by `json`, sealed with the vault's key as `to_bytes` does.
|
||||
fn with_body(v: &Vault, json: &str) -> Vec<u8> {
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let (header, at) = Header::parse(&bytes).unwrap();
|
||||
let mut out = bytes[..at].to_vec();
|
||||
out.extend_from_slice(&crypto::seal(&v.key, &header.body_nonce, json.as_bytes(), &bytes[..at]));
|
||||
out
|
||||
}
|
||||
|
||||
// ---- the body as core 0.11.0 parsed it (src/lib.rs, src/signing.rs, src/provision.rs at v0.11.0) ----
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct BodyV0_11 {
|
||||
format: u32,
|
||||
items: Vec<VaultItem>,
|
||||
#[serde(default)]
|
||||
factors: Vec<FactorJson>,
|
||||
#[serde(default)]
|
||||
identity: Option<identity::RootJson>,
|
||||
#[serde(default)]
|
||||
signing: Option<SigningV0_11>,
|
||||
#[serde(default)]
|
||||
provision: Option<ProvisionV0_11>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct SigningV0_11 {
|
||||
#[serde(default)]
|
||||
keys: Vec<KeyV0_11>,
|
||||
#[serde(default)]
|
||||
audit: Vec<SignEntryV0_11>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[allow(dead_code)]
|
||||
struct KeyV0_11 {
|
||||
id: String,
|
||||
kind: OldKeyKind,
|
||||
role: OldRole,
|
||||
name: String,
|
||||
created: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum OldKeyKind {
|
||||
Ed25519,
|
||||
RootCa,
|
||||
CodeSigning,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum OldRole {
|
||||
Release,
|
||||
Test,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct SignEntryV0_11 {
|
||||
at: i64,
|
||||
key: String,
|
||||
kind: OldSignKind,
|
||||
outcome: OldSignOutcome,
|
||||
via: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum OldSignKind {
|
||||
Minisign,
|
||||
Manifest,
|
||||
Authenticode,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum OldSignOutcome {
|
||||
Approved,
|
||||
Auto,
|
||||
Refused,
|
||||
Expired,
|
||||
OutOfScope,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct ProvisionV0_11 {
|
||||
#[serde(default)]
|
||||
audit: Vec<ProvisionEntryV0_11>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
struct ProvisionEntryV0_11 {
|
||||
store: OldStore,
|
||||
outcome: OldProvisionOutcome,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum OldStore {
|
||||
Vault,
|
||||
Claude,
|
||||
Cloud,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
enum OldProvisionOutcome {
|
||||
Approved,
|
||||
Generated,
|
||||
Accepted,
|
||||
Refused,
|
||||
OutOfScope,
|
||||
Invalid,
|
||||
Expired,
|
||||
}
|
||||
|
||||
fn display_entry(outcome: provision::Outcome) -> provision::ProvisionEntry {
|
||||
provision::ProvisionEntry {
|
||||
at: NOW,
|
||||
direction: provision::Direction::Offer,
|
||||
host: "nixos-vm".into(),
|
||||
item: "arca/authelia-mark".into(),
|
||||
store: provision::Store::Display,
|
||||
run: None,
|
||||
kind: Some("totp".into()),
|
||||
code: "684361".into(),
|
||||
outcome,
|
||||
replaced: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_opens_a_vault_with_the_security_member() {
|
||||
let mut v = vault();
|
||||
v.add(VaultItem::new(ItemType::SecureNote, "kept", 1));
|
||||
// Never set: the body has no trace of the member, so it is byte-for-byte what 0.11.0 wrote.
|
||||
assert!(!body_json(&v).contains("security"));
|
||||
|
||||
v.security_start_setup(NOW);
|
||||
v.security_tick(Item::HelloApprovals, NOW + 1);
|
||||
v.security_untick(Item::HelloApprovals, Auth::Hello, NOW + 2);
|
||||
v.security_tick(Item::NoSsh, NOW + 3);
|
||||
v.security_keep_scope(&["arca/".to_string()], &[]).unwrap();
|
||||
v.security_record(Action::SshConnected, None, NOW + 4).unwrap();
|
||||
let json = body_json(&v);
|
||||
assert!(json.contains(r#""security":{"setup":{"started":"#), "{json}");
|
||||
assert!(json.contains(r#""ticked":["no-ssh"]"#) && json.contains(r#""keptScope":{"ask":["arca/"]"#), "{json}");
|
||||
// Core 0.11.0's parser takes it and keeps everything it knows.
|
||||
let old: BodyV0_11 = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(old.items.len(), 1);
|
||||
assert_eq!(old.items[0].title, "kept");
|
||||
// And this core reads it back the same.
|
||||
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.security_view(NOW + 5), v.security_view(NOW + 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_opens_a_vault_with_the_approval_key_and_runs_but_not_approval_entries() {
|
||||
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
|
||||
let mut v = vault();
|
||||
v.signing_create(Role::Release, &["*".to_string()], &["*".to_string()], NOW).unwrap();
|
||||
let mut r = Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![1; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some("r-42".into()),
|
||||
context: Context { file: "a.exe".into(), version: "0.7.0".into(), ..Default::default() },
|
||||
via: Via::Local,
|
||||
};
|
||||
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||
v.provision_record(provision::ProvisionEntry {
|
||||
store: provision::Store::Vault,
|
||||
outcome: provision::Outcome::Accepted,
|
||||
..display_entry(provision::Outcome::Accepted)
|
||||
})
|
||||
.unwrap();
|
||||
let json = body_json(&v);
|
||||
assert!(json.contains(r#""id":"domi-approve""#) && json.contains(r#""run":"r-42""#), "{json}");
|
||||
assert!(serde_json::from_str::<BodyV0_11>(&json).is_ok(), "the new key and members are ignored");
|
||||
|
||||
// An approval entry is a kind 0.11.0 does not know: it refuses the vault (docs/FORMAT.md).
|
||||
r.key = "domi-approve".into();
|
||||
r.kind = SignKind::Approval;
|
||||
r.digest = vec![];
|
||||
v.signing_refuse(&r, crate::signing::Outcome::Refused, None, NOW + 1);
|
||||
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_refuses_display_and_confirmed() {
|
||||
for (store, outcome) in [
|
||||
(provision::Store::Display, provision::Outcome::Refused),
|
||||
(provision::Store::Display, provision::Outcome::Confirmed),
|
||||
] {
|
||||
let mut v = vault();
|
||||
v.provision_record(provision::ProvisionEntry { store, ..display_entry(outcome) }).unwrap();
|
||||
assert!(serde_json::from_str::<BodyV0_11>(&body_json(&v)).is_err(), "{store:?} {outcome:?}");
|
||||
// This core reads it.
|
||||
assert!(Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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_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();
|
||||
v.security_start_setup(NOW);
|
||||
v.security_tick(Item::NoSsh, NOW + 1);
|
||||
v.security_untick(Item::NoSsh, Auth::Password, NOW + 2);
|
||||
v.security_tick(Item::RotateSetup, NOW + 3);
|
||||
v.security_keep_scope(&["arca/".to_string()], &["fabrica/".to_string()]).unwrap();
|
||||
let json = body_json(&v);
|
||||
// The file as written opens.
|
||||
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
|
||||
let until = format!(r#""until":{}"#, NOW + SETUP_WINDOW);
|
||||
let cases = [
|
||||
(r#""ticked":["rotate-setup"]"#, r#""ticked":["rotate-later"]"#.to_string()),
|
||||
(r#""action":"ticked""#, r#""action":"tocked""#.to_string()),
|
||||
(r#""auth":"password""#, r#""auth":"pin""#.to_string()),
|
||||
(r#""item":"no-ssh""#, r#""item":"no-telnet""#.to_string()),
|
||||
(until.as_str(), format!(r#""until":{NOW}"#)),
|
||||
(r#""ask":["arca/"]"#, r#""ask":["arca/\n"]"#.to_string()),
|
||||
(r#""ask":["arca/"]"#, r#""ask":[""]"#.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:?}");
|
||||
}
|
||||
// `finished` without a window.
|
||||
let mut no_window = json.clone();
|
||||
let start = no_window.find(r#""setup":{"#).unwrap();
|
||||
let end = start + no_window[start..].find('}').unwrap() + 2;
|
||||
no_window.replace_range(start..end, r#""finished":5,"#);
|
||||
let r = Vault::open(&with_body(&v, &no_window), &SecretString::from("pw"));
|
||||
assert!(matches!(r, Err(Error::Corrupted)), "{no_window}");
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,9 @@ impl Refusal {
|
||||
}
|
||||
}
|
||||
|
||||
/// The key that signs deploy approvals, and nothing else (docs/SIGNING.md, "approval").
|
||||
pub const APPROVE_KEY: &str = "domi-approve";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
@@ -46,6 +49,8 @@ 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,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -54,6 +59,11 @@ pub enum SignKind {
|
||||
Minisign,
|
||||
Manifest,
|
||||
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,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -77,6 +87,9 @@ pub struct Context {
|
||||
pub file: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
/// The version being built (core 0.12.0); absent when empty, so older readers see the entry they knew.
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// A signing request, from the Domi pipe or the factor service's mailbox.
|
||||
@@ -84,10 +97,15 @@ 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>,
|
||||
/// The deploy approval's canonical JSON, for `SignKind::Approval` (core 0.12.0).
|
||||
pub approval: Option<String>,
|
||||
/// The build's run id, `[A-Za-z0-9._-]{1,64}` (core 0.12.0). Required for an approval, and equal to its `run`.
|
||||
pub run: Option<String>,
|
||||
pub context: Context,
|
||||
pub via: Via,
|
||||
}
|
||||
@@ -98,12 +116,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,
|
||||
@@ -128,12 +150,44 @@ pub struct AuditEntry {
|
||||
/// Why, for refusals the vault decided.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reason: Option<String>,
|
||||
/// 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 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;
|
||||
|
||||
/// 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,
|
||||
}
|
||||
@@ -155,7 +209,7 @@ 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>,
|
||||
}
|
||||
@@ -191,6 +245,7 @@ impl fmt::Debug for Key {
|
||||
pub(crate) struct Store {
|
||||
keys: Vec<Key>,
|
||||
audit: Vec<AuditEntry>,
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -222,6 +277,9 @@ 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>,
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
@@ -249,7 +307,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()
|
||||
}
|
||||
|
||||
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
|
||||
@@ -260,7 +318,7 @@ 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()?)
|
||||
}
|
||||
};
|
||||
@@ -282,6 +340,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,
|
||||
@@ -297,7 +359,10 @@ 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;
|
||||
}
|
||||
Some(Store { keys, audit: j.audit, standing: j.standing })
|
||||
}
|
||||
|
||||
pub(crate) fn json(&self) -> Option<StoreJson> {
|
||||
@@ -325,7 +390,7 @@ 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() })
|
||||
}
|
||||
|
||||
fn get(&self, id: &str) -> Option<&Key> {
|
||||
@@ -333,6 +398,92 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
|
||||
fn seconds(now_ms: i64) -> u64 {
|
||||
(now_ms.max(0) / 1000) as u64
|
||||
}
|
||||
|
||||
/// A new `domi-approve`: Ed25519, a release key with the given scope.
|
||||
fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
|
||||
let ed = custos_sign::new_ed25519();
|
||||
Key {
|
||||
id: APPROVE_KEY.into(),
|
||||
kind: KeyKind::Ed25519,
|
||||
role: Role::Release,
|
||||
name: "Domi deploy approval".into(),
|
||||
secret: Secret::Ed25519(ed.secret),
|
||||
public: Some(ed.public),
|
||||
key_id: Some(ed.key_id),
|
||||
cert: None,
|
||||
issuer: None,
|
||||
created: now,
|
||||
pipelines: pipelines.to_vec(),
|
||||
repos: repos.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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",
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
fn in_scope(list: &[String], what: &str) -> bool {
|
||||
list.iter().any(|x| x == "*" || x == what)
|
||||
}
|
||||
@@ -360,7 +511,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",
|
||||
@@ -419,7 +571,77 @@ impl Vault {
|
||||
true,
|
||||
);
|
||||
self.signing.keys.extend([ed_key, root_key, leaf_key]);
|
||||
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
|
||||
let mut ids = vec![ed_id.to_string(), root_id.into(), leaf_id.into()];
|
||||
if role == Role::Release {
|
||||
self.signing.keys.push(approve_key(&pipelines, &repos, now));
|
||||
ids.push(APPROVE_KEY.into());
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Adds `domi-approve` to a vault whose release keys an older core made, with `domi-release`'s scope (else the
|
||||
/// first release key's). Refused without release keys, or when the key is there already. The caller saves.
|
||||
pub fn signing_add_approve(&mut self, now: i64) -> Result<String, Error> {
|
||||
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 && !matches!(k.kind, KeyKind::RootCa | KeyKind::Android));
|
||||
let model = self
|
||||
.signing
|
||||
.get("domi-release")
|
||||
.filter(|k| k.role == Role::Release)
|
||||
.or_else(|| release.clone().next())
|
||||
.ok_or_else(|| Error::Signing("there are no release keys to add an approval key to".into()))?;
|
||||
let key = approve_key(&model.pipelines, &model.repos, now);
|
||||
self.signing.keys.push(key);
|
||||
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.
|
||||
@@ -472,19 +694,45 @@ impl Vault {
|
||||
|
||||
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
|
||||
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
|
||||
/// An approval's expiry is checked against the system clock; [`Vault::signing_check_at`] takes the time.
|
||||
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
|
||||
self.signing_check_at(req, crate::now_ms())
|
||||
}
|
||||
|
||||
/// [`Vault::signing_check`] at `now` (Unix milliseconds): an approval must not have expired then, and must
|
||||
/// expire at most an hour later.
|
||||
pub fn signing_check_at(&self, req: &Request, now: i64) -> Result<KeyView, Refusal> {
|
||||
self.check(req, now).map(|(view, _)| view)
|
||||
}
|
||||
|
||||
/// The check, and the approval it read (for an approval request).
|
||||
fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option<custos_sign::Approval>), Refusal> {
|
||||
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
|
||||
let fits = matches!(
|
||||
(k.kind, req.kind),
|
||||
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest)
|
||||
| (KeyKind::CodeSigning, SignKind::Authenticode)
|
||||
);
|
||||
let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release;
|
||||
let fits = match (k.kind, req.kind) {
|
||||
(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 {
|
||||
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
|
||||
}
|
||||
if !fits {
|
||||
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
|
||||
return Err(Refusal::Invalid(if k.id == APPROVE_KEY || req.kind == SignKind::Approval {
|
||||
format!("`{APPROVE_KEY}` signs deploy approvals only, and only it signs them (asked: `{}`)", k.id)
|
||||
} else {
|
||||
format!("`{}` cannot make {:?} signatures", k.id, req.kind)
|
||||
}));
|
||||
}
|
||||
if req.run.as_deref().is_some_and(|r| !custos_sign::run_id_ok(r)) {
|
||||
return Err(Refusal::Invalid("the run is not a run id ([A-Za-z0-9._-], 1 to 64)".into()));
|
||||
}
|
||||
if req.kind != SignKind::Approval && req.approval.is_some() {
|
||||
return Err(Refusal::Invalid("approval text comes only with an approval request".into()));
|
||||
}
|
||||
let mut approval = None;
|
||||
match req.kind {
|
||||
SignKind::Minisign if req.digest.len() != 64 => {
|
||||
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
|
||||
@@ -492,35 +740,67 @@ 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()))?;
|
||||
}
|
||||
SignKind::Approval => {
|
||||
let text = req.approval.as_deref().ok_or_else(|| Refusal::Invalid("no approval text".into()))?;
|
||||
let a = custos_sign::approval_check(text, seconds(now)).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
||||
if req.run.as_deref() != Some(a.run.as_str()) {
|
||||
return Err(Refusal::Invalid("the approval's run is not the request's run".into()));
|
||||
}
|
||||
let c = &req.context;
|
||||
for (member, ours, theirs) in [
|
||||
("repo", &c.repo, &a.repo),
|
||||
("pipeline", &c.pipeline, &a.pipeline),
|
||||
("commit", &c.commit, &a.commit),
|
||||
("version", &c.version, &a.version),
|
||||
] {
|
||||
if !ours.is_empty() && ours != theirs {
|
||||
return Err(Refusal::Invalid(format!("the request's {member} is not the approval's")));
|
||||
}
|
||||
}
|
||||
approval = Some(a);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let file = &req.context.file;
|
||||
if req.kind != SignKind::Manifest
|
||||
if !matches!(req.kind, SignKind::Manifest | SignKind::Approval)
|
||||
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
|
||||
{
|
||||
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
|
||||
}
|
||||
if !in_scope(&k.pipelines, &req.context.pipeline) {
|
||||
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
|
||||
// An approval is scoped by what it approves.
|
||||
let (pipeline, repo) = match &approval {
|
||||
Some(a) => (a.pipeline.as_str(), a.repo.as_str()),
|
||||
None => (req.context.pipeline.as_str(), req.context.repo.as_str()),
|
||||
};
|
||||
if !in_scope(&k.pipelines, pipeline) {
|
||||
return Err(Refusal::OutOfScope(format!("pipeline `{pipeline}` may not use `{}`", k.id)));
|
||||
}
|
||||
if !in_scope(&k.repos, &req.context.repo) {
|
||||
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
|
||||
if !in_scope(&k.repos, repo) {
|
||||
return Err(Refusal::OutOfScope(format!("repo `{repo}` may not use `{}`", k.id)));
|
||||
}
|
||||
if k.role == Role::Test && req.context.trigger == "tag" {
|
||||
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
|
||||
}
|
||||
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
|
||||
let view = self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists");
|
||||
Ok((view, approval))
|
||||
}
|
||||
|
||||
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
|
||||
/// A refusal is recorded too. The caller saves.
|
||||
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
|
||||
let view = match self.signing_check(req) {
|
||||
Ok(v) => v,
|
||||
let view = match self.check(req, now) {
|
||||
Ok((v, _)) => v,
|
||||
Err(r) => {
|
||||
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
@@ -531,8 +811,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);
|
||||
if approval == Approval::Standing && rule.is_none() {
|
||||
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 = (now.max(0) / 1000) as u64;
|
||||
let seconds = seconds(now);
|
||||
let bytes = match (&k.secret, req.kind) {
|
||||
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
|
||||
s,
|
||||
@@ -549,7 +835,16 @@ impl Vault {
|
||||
seconds,
|
||||
)
|
||||
.map(String::into_bytes),
|
||||
(Secret::Ed25519(s), SignKind::Approval) => custos_sign::approval(
|
||||
s,
|
||||
&k.key_id.expect("ed25519 keys have an id"),
|
||||
req.approval.as_deref().unwrap_or_default(),
|
||||
seconds,
|
||||
req.run.as_deref().unwrap_or_default(),
|
||||
)
|
||||
.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 {
|
||||
@@ -561,15 +856,25 @@ 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);
|
||||
}
|
||||
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);
|
||||
@@ -584,8 +889,31 @@ impl Vault {
|
||||
now: i64,
|
||||
) {
|
||||
let mut context = req.context.clone();
|
||||
if req.kind == SignKind::Manifest {
|
||||
context.file = "SHA256SUMS".into();
|
||||
let run = req.run.clone().filter(|r| custos_sign::run_id_ok(r));
|
||||
match req.kind {
|
||||
SignKind::Manifest => context.file = "SHA256SUMS".into(),
|
||||
SignKind::Approval => {
|
||||
context.file = match &run {
|
||||
Some(r) => format!("approval-{r}.json"),
|
||||
None => "approval.json".into(),
|
||||
};
|
||||
// What the approval says, where the request left the context empty: read without the clock, so a
|
||||
// refused or expired request is filled in too. A text that does not read leaves the context as is.
|
||||
let read = custos_sign::approval_parse(req.approval.as_deref().unwrap_or_default()).ok();
|
||||
if let Some(a) = read {
|
||||
for (ours, theirs) in [
|
||||
(&mut context.repo, a.repo),
|
||||
(&mut context.pipeline, a.pipeline),
|
||||
(&mut context.commit, a.commit),
|
||||
(&mut context.version, a.version),
|
||||
] {
|
||||
if ours.is_empty() {
|
||||
*ours = theirs;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.signing.audit.push(AuditEntry {
|
||||
at: now,
|
||||
@@ -596,9 +924,135 @@ impl Vault {
|
||||
context,
|
||||
signature,
|
||||
reason,
|
||||
run,
|
||||
});
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// Every request any key was named in, oldest first.
|
||||
pub fn signing_audit(&self) -> &[AuditEntry] {
|
||||
&self.signing.audit
|
||||
@@ -622,6 +1076,8 @@ mod tests {
|
||||
kind,
|
||||
digest: vec![5; digest],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: None,
|
||||
context: Context {
|
||||
repo: "Arca".into(),
|
||||
pipeline: "release".into(),
|
||||
@@ -633,12 +1089,66 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vault_with_release_keys_from_an_older_core_gets_its_approval_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(&["release"]), &s(&["Arca"]), 1).unwrap();
|
||||
// What core 0.11.0 made: the release set without `domi-approve`.
|
||||
v.signing.keys.retain(|k| k.id != "domi-approve");
|
||||
assert_eq!(v.signing.keys.len(), 3);
|
||||
assert_eq!(v.signing_add_approve(7).unwrap(), "domi-approve");
|
||||
let views = v.signing_keys();
|
||||
let a = views.iter().find(|k| k.id == "domi-approve").unwrap();
|
||||
assert_eq!((a.kind, a.role, a.created), (KeyKind::Ed25519, Role::Release, 7));
|
||||
assert_eq!((a.pipelines.clone(), a.repos.clone()), (s(&["release"]), s(&["Arca"])));
|
||||
assert!(a.minisign_public.is_some());
|
||||
assert!(matches!(v.signing_add_approve(8), Err(Error::SigningExists("approval"))));
|
||||
// It survives a save and a reopen.
|
||||
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
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
|
||||
@@ -648,7 +1158,7 @@ mod tests {
|
||||
Secret::Rsa(s) => s.expose().to_vec(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(secrets.len(), 6);
|
||||
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.
|
||||
@@ -665,15 +1175,44 @@ mod tests {
|
||||
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
|
||||
reqs.push(req("domi-root", SignKind::Authenticode, 32));
|
||||
reqs.push(req("domi-test", SignKind::Minisign, 64));
|
||||
let mut approve = req("domi-approve", SignKind::Approval, 0);
|
||||
approve.run = Some("r-1".into());
|
||||
approve.approval = Some(format!(
|
||||
r#"{{"v":1,"run":"r-1","repo":"Arca","commit":"{}","pipeline":"release","version":"1.0.0","targets":["deploy"],"expires":600}}"#,
|
||||
"a".repeat(40)
|
||||
));
|
||||
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));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Hands off (Custos docs/12_hands_off.md): a machine-key vault that Custos opens itself, the rules for auto-connect,
|
||||
//! the unattended setup run and unattended signing, and *Take over the vault*.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use custos_vault::security::{
|
||||
Action, Item, Level, ProvisionAsk, Store, Verb, auto_connect_allowed, is_setup_run, setup_on_connect,
|
||||
unattended_provision, unattended_sign,
|
||||
};
|
||||
use custos_vault::{Error, FactorKind, 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];
|
||||
|
||||
fn none() -> BTreeSet<Item> {
|
||||
BTreeSet::new()
|
||||
}
|
||||
fn ticked(items: &[Item]) -> BTreeSet<Item> {
|
||||
items.iter().copied().collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- take over
|
||||
|
||||
#[test]
|
||||
fn a_machine_key_vault_is_taken_over_with_a_master_password() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
assert!(v.opens_with_machine_key());
|
||||
// The hands-off vault holds the release set (with the approval key) from its first start.
|
||||
v.signing_create(custos_vault::signing::Role::Release, &[], &[], NOW).unwrap();
|
||||
|
||||
let id = v.take_over(&SecretString::from("a long password"), FAST, NOW).expect("taken over");
|
||||
assert!(!v.opens_with_machine_key());
|
||||
assert!(v.factors().iter().any(|f| f.id == id && f.kind == FactorKind::Password));
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
|
||||
// This PC alone no longer opens it; the password and this PC do, and the keys are still there.
|
||||
assert!(Vault::open_machine_store(&bytes, &PC).is_err(), "the PC-only access is gone");
|
||||
let pw = SecretString::from("a long password");
|
||||
let w = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &PC))
|
||||
.expect("two factors");
|
||||
assert!(w.same_key_as(&v));
|
||||
assert_eq!(w.signing_keys().len(), v.signing_keys().len());
|
||||
assert!(!w.signing_keys().is_empty());
|
||||
|
||||
// Unattended work is turned off, and it is audited.
|
||||
let view = w.security_view(NOW);
|
||||
assert!(view.ticked.contains(&Item::NoAutoConnect));
|
||||
assert!(view.ticked.contains(&Item::NoUnattended));
|
||||
assert!(view.ticked.contains(&Item::CardSigning));
|
||||
assert_eq!(view.level, Level::Hardened);
|
||||
assert!(view.audit.iter().any(|e| e.action == Action::TakenOver));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_machine_key_vault_is_taken_over_and_only_once() {
|
||||
let mut user = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
assert!(!user.opens_with_machine_key());
|
||||
assert!(user.take_over(&SecretString::from("a long password"), FAST, NOW).is_err());
|
||||
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
|
||||
assert!(v.take_over(&SecretString::from("another long one"), FAST, NOW).is_err(), "once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_take_over_a_phone_can_be_added_as_for_any_vault() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
assert!(v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").is_err(), "not before");
|
||||
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
|
||||
v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").expect("after");
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
assert!(
|
||||
Vault::open_with(
|
||||
&bytes,
|
||||
Unlock::Material(FactorKind::Device, &PC),
|
||||
Unlock::Material(FactorKind::Approval, &[3; 32])
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_carry_their_detail_and_refuse_other_actions() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
v.security_note(Action::AutoConnected, "Connected to 192.168.100.217 as MARK-PC", NOW).unwrap();
|
||||
v.security_note(Action::UnattendedStored, "setup-1: arca/authelia-mark, arca/totp-mark", NOW).unwrap();
|
||||
v.security_note(Action::SetupItemRemoved, "setup-1: arca/totp-mark", NOW).unwrap();
|
||||
v.security_note(Action::UnattendedSigned, "domi-release minisign run r42 Arca_0.3.0_x64-setup.exe", NOW).unwrap();
|
||||
assert!(v.security_note(Action::Ticked, "x", NOW).is_err());
|
||||
assert!(v.security_note(Action::AutoConnected, "line\nbreak", NOW).is_err(), "no control characters");
|
||||
assert!(v.security_note(Action::AutoConnected, &"x".repeat(501), NOW).is_err(), "at most 500 characters");
|
||||
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let w = Vault::open_machine_store(&bytes, &PC).unwrap();
|
||||
let audit = w.security_view(NOW).audit;
|
||||
assert_eq!(audit.len(), 4);
|
||||
assert_eq!(audit[0].detail.as_deref(), Some("Connected to 192.168.100.217 as MARK-PC"));
|
||||
assert_eq!(audit[3].action, Action::UnattendedSigned);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- auto-connect and the Setup window
|
||||
|
||||
#[test]
|
||||
fn auto_connect_runs_in_setup_and_standard_and_stops_when_hardened() {
|
||||
assert!(auto_connect_allowed(Level::Setup, &none()));
|
||||
assert!(auto_connect_allowed(Level::Standard, &none()));
|
||||
assert!(!auto_connect_allowed(Level::Hardened, &ticked(&[Item::HelloApprovals])));
|
||||
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoAutoConnect])), "the item holds in Setup too");
|
||||
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoSsh])), "no SSH implies no auto-connect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_connect_opens_setup_unless_unattended_is_off() {
|
||||
assert!(setup_on_connect(&none()));
|
||||
assert!(!setup_on_connect(&ticked(&[Item::NoUnattended])));
|
||||
assert!(!setup_on_connect(&ticked(&[Item::NoSsh])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_runs_are_named_setup_dash_something_short() {
|
||||
assert!(is_setup_run("setup-1"));
|
||||
assert!(is_setup_run("setup-2026-11-05.first_run"));
|
||||
assert!(is_setup_run(&format!("setup-{}", "a".repeat(58))));
|
||||
assert!(!is_setup_run(&format!("setup-{}", "a".repeat(59))));
|
||||
assert!(!is_setup_run("setup-"));
|
||||
assert!(!is_setup_run("setup-a b"));
|
||||
assert!(!is_setup_run("setup-a/b"));
|
||||
assert!(!is_setup_run("Setup-1"));
|
||||
assert!(!is_setup_run("r42"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the unattended setup run
|
||||
|
||||
fn ask(item: &str) -> ProvisionAsk<'_> {
|
||||
ProvisionAsk { verb: Verb::Ask, generate: true, exists: false, store: Store::Vault, item, totp: false }
|
||||
}
|
||||
fn offer(item: &str) -> ProvisionAsk<'_> {
|
||||
ProvisionAsk { verb: Verb::Offer, generate: false, exists: false, store: Store::Vault, item, totp: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_run_in_setup_takes_new_items_in_the_allowed_namespaces() {
|
||||
for item in ["arca/authelia-mark", "custos/x", "fabrica/hub-token", "aula/admin", "gitea/read-token"] {
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &ask(item)), "{item}");
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &offer(item)), "{item}");
|
||||
}
|
||||
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &totp));
|
||||
let claude = ProvisionAsk { store: Store::Claude, ..offer("fabrica-hub-token") };
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &claude), "the Claude store's names");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_else_waits_for_a_card() {
|
||||
let s = |l, t: &BTreeSet<Item>, run, r: &ProvisionAsk| unattended_provision(l, t, run, r);
|
||||
let n = none();
|
||||
// Existing items, asks without --generate, replacing offers.
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..ask("arca/x") }), "an existing item");
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { generate: false, ..ask("arca/x") }), "no --generate");
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..offer("arca/x") }), "a replacing offer");
|
||||
// Namespaces.
|
||||
for item in ["mark/bank", "domi/root", "arcax/y", "arca", "../arca/x", "ARCA/x"] {
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ask(item)), "{item}");
|
||||
}
|
||||
// Display offers, and asks from the Claude store.
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Display, ..offer("arca/totp-mark") }));
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Claude, ..ask("fabrica-hub-token") }));
|
||||
// The run and the level.
|
||||
assert!(!s(Level::Setup, &n, "r42", &ask("arca/x")), "not a setup run");
|
||||
assert!(!s(Level::Standard, &n, "setup-1", &ask("arca/x")), "after the window");
|
||||
assert!(!s(Level::Hardened, &ticked(&[Item::NarrowScope]), "setup-1", &ask("arca/x")));
|
||||
// Items that turn it off.
|
||||
assert!(!s(Level::Setup, &ticked(&[Item::NoUnattended]), "setup-1", &ask("arca/x")));
|
||||
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
|
||||
assert!(!s(Level::Setup, &ticked(&[Item::TotpOnPhone]), "setup-1", &totp), "the TOTP lives on the phone");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- unattended signing
|
||||
|
||||
#[test]
|
||||
fn a_machine_key_vault_signs_run_requests_of_the_release_kinds_without_a_card() {
|
||||
for kind in ["minisign", "manifest", "authenticode", "approval"] {
|
||||
assert!(unattended_sign(Level::Standard, &none(), true, kind, true), "{kind}");
|
||||
assert!(unattended_sign(Level::Setup, &none(), true, kind, true), "{kind} in Setup");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_waits_for_a_card_otherwise() {
|
||||
assert!(!unattended_sign(Level::Standard, &none(), false, "minisign", true), "taken over");
|
||||
assert!(!unattended_sign(Level::Standard, &none(), true, "minisign", false), "no run");
|
||||
assert!(!unattended_sign(Level::Standard, &none(), true, "ssh", true), "another kind");
|
||||
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::CardSigning]), true, "minisign", true));
|
||||
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::HelloApprovals]), true, "minisign", true), "hardened");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_items_round_trip_and_can_be_undone() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
|
||||
assert!(v.security_tick(item, NOW));
|
||||
}
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let mut w = Vault::open(&bytes, &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(w.security_view(NOW).ticked, ticked(&[Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning]));
|
||||
assert!(w.security_untick(Item::CardSigning, custos_vault::security::Auth::Hello, NOW));
|
||||
assert!(!w.security_view(NOW).ticked.contains(&Item::CardSigning));
|
||||
let _ = Error::Corrupted;
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Mandatory tests for the Provisio audit (docs/FORMAT.md, "The provision audit"): it survives a reopen, takes
|
||||
//! only entries that fit, is append-only and bounded, and has no member that could hold a secret. That an older
|
||||
//! reader still opens such a vault is a unit test in src/provision.rs, which can see the decrypted body.
|
||||
|
||||
use custos_vault::provision::{AUDIT_LIMIT, Direction, Outcome, ProvisionEntry, Store};
|
||||
use custos_vault::{Error, 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;
|
||||
|
||||
/// One way to spoil an entry.
|
||||
type Change = Box<dyn Fn(&mut ProvisionEntry)>;
|
||||
|
||||
fn entry(i: i64, outcome: Outcome) -> ProvisionEntry {
|
||||
ProvisionEntry {
|
||||
at: NOW + i,
|
||||
direction: Direction::Offer,
|
||||
host: "nixos-vm".into(),
|
||||
item: "fabrica/gitea-read-token".into(),
|
||||
store: Store::Vault,
|
||||
run: Some("deploy-7".into()),
|
||||
kind: Some("Gitea token, read:repository".into()),
|
||||
code: "684361".into(),
|
||||
outcome,
|
||||
replaced: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_provision_audit_records_every_outcome_and_survives_a_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
assert!(v.provision_audit().is_empty());
|
||||
let all = [
|
||||
Outcome::Approved,
|
||||
Outcome::Generated,
|
||||
Outcome::Accepted,
|
||||
Outcome::Refused,
|
||||
Outcome::OutOfScope,
|
||||
Outcome::Invalid,
|
||||
Outcome::Expired,
|
||||
];
|
||||
for (i, o) in all.iter().enumerate() {
|
||||
let mut e = entry(i as i64, *o);
|
||||
if i % 2 == 0 {
|
||||
e.direction = Direction::Ask;
|
||||
e.store = Store::Vault;
|
||||
e.kind = None;
|
||||
e.run = None;
|
||||
} else {
|
||||
e.store = if i % 3 == 0 { Store::Claude } else { Store::Cloud };
|
||||
e.item = "fabrica-hub-token".into();
|
||||
}
|
||||
e.replaced = *o == Outcome::Accepted;
|
||||
v.provision_record(e).unwrap();
|
||||
}
|
||||
v.save(&path).unwrap();
|
||||
|
||||
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
let audit: &[ProvisionEntry] = back.provision_audit();
|
||||
assert_eq!(audit, v.provision_audit());
|
||||
assert_eq!(audit.iter().map(|e| e.outcome).collect::<Vec<_>>(), all);
|
||||
// Newest last.
|
||||
assert!(audit.windows(2).all(|w| w[0].at < w[1].at));
|
||||
assert_eq!(audit[0].direction, Direction::Ask);
|
||||
assert_eq!(audit[1].store, Store::Cloud);
|
||||
assert_eq!(audit[3].store, Store::Claude);
|
||||
assert!(audit[2].replaced && !audit[1].replaced);
|
||||
// The signing audit is a separate log and stays empty.
|
||||
assert!(back.signing_audit().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_that_do_not_fit_are_refused_and_not_stored() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.provision_record(entry(0, Outcome::Approved)).unwrap();
|
||||
let secretish = "ghp_s3cr3tV4lu3ThatMustNeverBeInAnError";
|
||||
let bad: Vec<Change> = vec![
|
||||
Box::new(|e| e.code = "68436".into()),
|
||||
Box::new(|e| e.code = "68436a".into()),
|
||||
Box::new(|e| e.code = "6843611".into()),
|
||||
Box::new(|e| e.item = "Arca/x".into()),
|
||||
Box::new(|e| e.item = "../x".into()),
|
||||
Box::new(|e| e.item = "a/b/c/d/e".into()),
|
||||
Box::new(|e| e.item = String::new()),
|
||||
Box::new(|e| e.item = format!("arca/{}", "x".repeat(65))),
|
||||
Box::new(|e| e.run = Some(String::new())),
|
||||
Box::new(|e| e.run = Some("run 1".into())),
|
||||
Box::new(|e| e.run = Some("r".repeat(65))),
|
||||
Box::new(|e| e.host = String::new()),
|
||||
Box::new(|e| e.host = "nixos vm".into()),
|
||||
Box::new(|e| e.host = "h".repeat(254)),
|
||||
Box::new(|e| e.kind = Some("x".repeat(201))),
|
||||
Box::new(move |e| e.kind = Some(format!("token\n{secretish}"))),
|
||||
];
|
||||
for (i, change) in bad.iter().enumerate() {
|
||||
let mut e = entry(1, Outcome::Accepted);
|
||||
change(&mut e);
|
||||
let err = v.provision_record(e).unwrap_err();
|
||||
assert!(matches!(err, Error::Provision(_)), "case {i}: {err:?}");
|
||||
assert!(!format!("{err}{err:?}").contains(secretish), "case {i}: an error repeats a value");
|
||||
}
|
||||
assert_eq!(v.provision_audit(), [entry(0, Outcome::Approved)]);
|
||||
// The limits themselves fit.
|
||||
let mut e = entry(2, Outcome::Accepted);
|
||||
e.item = format!("a{0}/b{0}/c{0}/d{0}", "x".repeat(63));
|
||||
e.run = Some("R".repeat(64));
|
||||
e.host = "h".repeat(253);
|
||||
e.kind = Some("k".repeat(200));
|
||||
v.provision_record(e).unwrap();
|
||||
assert_eq!(v.provision_audit().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_audit_is_append_only_and_keeps_the_newest_entries() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.provision_record(entry(0, Outcome::Refused)).unwrap();
|
||||
let before = v.provision_audit().to_vec();
|
||||
v.provision_record(entry(1, Outcome::Accepted)).unwrap();
|
||||
// Recording appends; what was there is unchanged.
|
||||
assert_eq!(&v.provision_audit()[..1], before.as_slice());
|
||||
assert_eq!(v.provision_audit()[1], entry(1, Outcome::Accepted));
|
||||
|
||||
assert_eq!(AUDIT_LIMIT, 5_000);
|
||||
for i in 2..(AUDIT_LIMIT as i64 + 3) {
|
||||
v.provision_record(entry(i, Outcome::Expired)).unwrap();
|
||||
}
|
||||
let audit = v.provision_audit();
|
||||
assert_eq!(audit.len(), AUDIT_LIMIT);
|
||||
// The three oldest went; the newest is last.
|
||||
assert_eq!(audit[0].at, NOW + 3);
|
||||
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_has_no_member_that_could_hold_a_secret() {
|
||||
// Every member, with every option set: the JSON has exactly these names and nothing like a value.
|
||||
let mut e = entry(0, Outcome::Accepted);
|
||||
e.replaced = true;
|
||||
let json: serde_json::Value = serde_json::to_value(&e).unwrap();
|
||||
let mut names: Vec<&str> = json.as_object().unwrap().keys().map(String::as_str).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["at", "code", "direction", "host", "item", "kind", "outcome", "replaced", "run", "store"]);
|
||||
for v in json.as_object().unwrap().values() {
|
||||
assert!(!v.is_object() && !v.is_array(), "no nested member to hide a value in");
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::to_string(&e).unwrap(),
|
||||
r#"{"at":1793750000000,"direction":"offer","host":"nixos-vm","item":"fabrica/gitea-read-token","store":"vault","run":"deploy-7","kind":"Gitea token, read:repository","code":"684361","outcome":"accepted","replaced":true}"#
|
||||
);
|
||||
// The options are left out when absent; the outcomes are spelled as docs/FORMAT.md says.
|
||||
let mut e = entry(0, Outcome::OutOfScope);
|
||||
e.run = None;
|
||||
e.kind = None;
|
||||
let s = serde_json::to_string(&e).unwrap();
|
||||
assert!(!s.contains("\"run\"") && !s.contains("\"kind\"") && s.contains("\"out-of-scope\""), "{s}");
|
||||
}
|
||||
|
||||
// ---- display offers (core 0.12.0) ----
|
||||
|
||||
fn display(i: i64, outcome: Outcome) -> ProvisionEntry {
|
||||
ProvisionEntry {
|
||||
item: "arca/authelia-mark".into(),
|
||||
store: Store::Display,
|
||||
kind: Some("totp".into()),
|
||||
run: None,
|
||||
..entry(i, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_display_offer_is_recorded_as_confirmed_and_survives_a_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
for (i, o) in [Outcome::Confirmed, Outcome::Refused, Outcome::Expired, Outcome::Invalid, Outcome::OutOfScope]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
v.provision_record(display(i as i64, o)).unwrap();
|
||||
}
|
||||
let s = serde_json::to_string(&v.provision_audit()[0]).unwrap();
|
||||
assert!(s.contains(r#""store":"display""#) && s.contains(r#""outcome":"confirmed""#), "{s}");
|
||||
v.save(&path).unwrap();
|
||||
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.provision_audit(), v.provision_audit());
|
||||
assert_eq!(back.provision_audit()[0].outcome, Outcome::Confirmed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_and_confirmed_go_only_together_and_store_nothing() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
let bad: Vec<ProvisionEntry> = vec![
|
||||
// Nothing is stored, so nothing is accepted, approved, generated or replaced.
|
||||
display(0, Outcome::Accepted),
|
||||
display(0, Outcome::Approved),
|
||||
display(0, Outcome::Generated),
|
||||
ProvisionEntry { replaced: true, ..display(0, Outcome::Confirmed) },
|
||||
// A display is an offer.
|
||||
ProvisionEntry { direction: Direction::Ask, ..display(0, Outcome::Confirmed) },
|
||||
// Confirmed is a display offer's outcome only.
|
||||
entry(0, Outcome::Confirmed),
|
||||
ProvisionEntry { store: Store::Claude, ..entry(0, Outcome::Confirmed) },
|
||||
];
|
||||
for (i, e) in bad.into_iter().enumerate() {
|
||||
assert!(matches!(v.provision_record(e), Err(Error::Provision(_))), "case {i}");
|
||||
}
|
||||
assert!(v.provision_audit().is_empty());
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
//! The security member (docs/FORMAT.md, "The security member"): the level rules, the checklist and its audit, the
|
||||
//! kept scope, and the rules the app asks before a card. That an older reader still opens such a vault, and that
|
||||
//! unknown values are refused, are unit tests in src/security.rs, which can see the decrypted body.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use custos_vault::security::{
|
||||
AUDIT_LIMIT, Action, Auth, Item, KeptScope, Level, SETUP_WINDOW, SshRule, Window, accept_all_allowed,
|
||||
hello_for_approvals, replacing_line_preticked, ssh_needs_auth, totp_offer_allowed,
|
||||
};
|
||||
use custos_vault::{Error, 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 HOUR: i64 = 3_600_000;
|
||||
|
||||
fn vault() -> Vault {
|
||||
Vault::create(&SecretString::from("pw"), FAST).unwrap()
|
||||
}
|
||||
|
||||
fn actions(v: &Vault) -> Vec<Action> {
|
||||
v.security_view(NOW).audit.iter().map(|e| e.action).collect()
|
||||
}
|
||||
|
||||
fn s(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vault_that_never_had_setup_is_standard() {
|
||||
let v = vault();
|
||||
assert_eq!(v.security_level(NOW), Level::Standard);
|
||||
let view = v.security_view(NOW);
|
||||
assert_eq!(view.level, Level::Standard);
|
||||
assert!(view.setup.is_none() && view.setup_remaining.is_none());
|
||||
assert!(view.ticked.is_empty() && view.audit.is_empty() && view.kept_scope.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_lasts_two_hours_from_its_start() {
|
||||
assert_eq!(SETUP_WINDOW, 2 * HOUR);
|
||||
let mut v = vault();
|
||||
let w = v.security_start_setup(NOW);
|
||||
assert_eq!(w, Window { started: NOW, until: NOW + 2 * HOUR });
|
||||
assert_eq!(v.security_level(NOW), Level::Setup);
|
||||
assert_eq!(v.security_level(NOW + 2 * HOUR - 1), Level::Setup, "the last millisecond is still Setup");
|
||||
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard, "`until` itself is not");
|
||||
assert_eq!(v.security_level(NOW - 1), Level::Standard, "a clock set back before the start is not Setup");
|
||||
assert_eq!(v.security_view(NOW + HOUR).setup_remaining, Some(HOUR));
|
||||
assert_eq!(v.security_view(NOW + 2 * HOUR).setup_remaining, None);
|
||||
assert_eq!(actions(&v), [Action::SetupStarted]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_setup_again_while_in_setup_extends_nothing() {
|
||||
let mut v = vault();
|
||||
let w = v.security_start_setup(NOW);
|
||||
assert_eq!(v.security_start_setup(NOW + HOUR), w);
|
||||
assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard);
|
||||
assert_eq!(actions(&v), [Action::SetupStarted], "no second entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finish_setup_ends_it_early_and_is_audited() {
|
||||
let mut v = vault();
|
||||
assert!(!v.security_finish_setup(NOW), "nothing to finish");
|
||||
v.security_start_setup(NOW);
|
||||
assert!(v.security_finish_setup(NOW + 10));
|
||||
assert_eq!(v.security_level(NOW + 10), Level::Standard);
|
||||
assert_eq!(v.security_view(NOW + 10).finished, Some(NOW + 10));
|
||||
assert!(!v.security_finish_setup(NOW + 20), "once");
|
||||
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished]);
|
||||
// A later Connect via SSH starts a new window.
|
||||
let w = v.security_start_setup(NOW + HOUR);
|
||||
assert_eq!(w, Window { started: NOW + HOUR, until: NOW + 3 * HOUR });
|
||||
assert_eq!(v.security_level(NOW + HOUR), Level::Setup);
|
||||
assert_eq!(v.security_view(NOW + HOUR).finished, None);
|
||||
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished, Action::SetupStarted]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expiry_is_audited_once_by_the_first_change_that_notices_it() {
|
||||
let mut v = vault();
|
||||
v.security_start_setup(NOW);
|
||||
// Reading notices nothing.
|
||||
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Standard);
|
||||
assert_eq!(actions(&v), [Action::SetupStarted]);
|
||||
v.security_tick(Item::NoSsh, NOW + 3 * HOUR);
|
||||
v.security_record(Action::SshConnected, None, NOW + 3 * HOUR + 1).unwrap();
|
||||
assert!(!v.security_finish_setup(NOW + 3 * HOUR + 2));
|
||||
assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupExpired, Action::Ticked, Action::SshConnected]);
|
||||
let view = v.security_view(NOW + 3 * HOUR);
|
||||
assert_eq!(view.finished, Some(NOW + 2 * HOUR), "ended at `until`");
|
||||
assert_eq!(view.audit[1].at, NOW + 3 * HOUR, "written when noticed");
|
||||
// Starting again after expiry opens a new window.
|
||||
let w = v.security_start_setup(NOW + 4 * HOUR);
|
||||
assert_eq!(w.started, NOW + 4 * HOUR);
|
||||
assert_eq!(*actions(&v).last().unwrap(), Action::SetupStarted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticking_hardens_and_undoing_needs_hello_or_the_password_and_is_audited() {
|
||||
let mut v = vault();
|
||||
assert!(v.security_tick(Item::HelloApprovals, NOW));
|
||||
assert!(!v.security_tick(Item::HelloApprovals, NOW + 1), "ticked already: no entry");
|
||||
assert_eq!(v.security_level(NOW), Level::Hardened);
|
||||
assert!(v.security_tick(Item::NoSsh, NOW + 2));
|
||||
assert!(v.security_untick(Item::NoSsh, Auth::Hello, NOW + 3));
|
||||
assert!(!v.security_untick(Item::NoSsh, Auth::Password, NOW + 4), "not ticked: no entry");
|
||||
assert_eq!(v.security_level(NOW + 5), Level::Hardened);
|
||||
assert!(v.security_untick(Item::HelloApprovals, Auth::Password, NOW + 5));
|
||||
assert_eq!(v.security_level(NOW + 6), Level::Standard);
|
||||
|
||||
let audit = v.security_view(NOW + 6).audit;
|
||||
let got: Vec<_> = audit.iter().map(|e| (e.at, e.action, e.item, e.auth)).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(NOW, Action::Ticked, Some(Item::HelloApprovals), None),
|
||||
(NOW + 2, Action::Ticked, Some(Item::NoSsh), None),
|
||||
(NOW + 3, Action::Unticked, Some(Item::NoSsh), Some(Auth::Hello)),
|
||||
(NOW + 5, Action::Unticked, Some(Item::HelloApprovals), Some(Auth::Password)),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticked_items_hold_during_setup() {
|
||||
let mut v = vault();
|
||||
v.security_tick(Item::NoSsh, NOW);
|
||||
v.security_tick(Item::TotpOnPhone, NOW);
|
||||
v.security_start_setup(NOW + 1);
|
||||
assert_eq!(v.security_level(NOW + 1), Level::Setup);
|
||||
let ticked = v.security_view(NOW + 1).ticked;
|
||||
assert_eq!(ticked, BTreeSet::from([Item::TotpOnPhone, Item::NoSsh]));
|
||||
assert_eq!(ssh_needs_auth(Level::Setup, &ticked), SshRule::Off, "Setup never undoes hardening");
|
||||
assert!(!totp_offer_allowed(&ticked));
|
||||
// After Setup the ticks are still there: Hardened.
|
||||
assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Hardened);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_state_survives_a_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = vault();
|
||||
v.security_start_setup(NOW);
|
||||
v.security_tick(Item::NarrowScope, NOW + 1);
|
||||
v.security_keep_scope(&s(&["arca/"]), &s(&["arca/", "fabrica/"])).unwrap();
|
||||
v.security_record(Action::TotpMoved, Some(Item::TotpOnPhone), NOW + 2).unwrap();
|
||||
v.save(&path).unwrap();
|
||||
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.security_view(NOW + 3), v.security_view(NOW + 3));
|
||||
assert_eq!(back.security_level(NOW + 3), Level::Setup);
|
||||
let view = back.security_view(NOW + 3);
|
||||
assert_eq!(view.kept_scope, Some(KeptScope { ask: s(&["arca/"]), offer: s(&["arca/", "fabrica/"]) }));
|
||||
assert_eq!(view.audit.last().unwrap().item, Some(Item::TotpOnPhone));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kept_scope_is_kept_once_and_taken_back() {
|
||||
let mut v = vault();
|
||||
assert!(v.security_take_kept_scope().is_none());
|
||||
v.security_keep_scope(&s(&["arca/"]), &s(&["fabrica/"])).unwrap();
|
||||
// A second keep would lose the first prefixes: refused.
|
||||
assert!(matches!(v.security_keep_scope(&s(&["x/"]), &[]), Err(Error::Security(_))));
|
||||
let kept = v.security_take_kept_scope().unwrap();
|
||||
assert_eq!(kept, KeptScope { ask: s(&["arca/"]), offer: s(&["fabrica/"]) });
|
||||
assert!(v.security_take_kept_scope().is_none());
|
||||
// The rules for a prefix.
|
||||
for bad in [s(&[""]), s(&["a\nb"]), vec!["x".repeat(201)], (0..65).map(|i| format!("p{i}/")).collect()] {
|
||||
assert!(matches!(v.security_keep_scope(&bad, &[]), Err(Error::Security(_))), "{bad:?}");
|
||||
assert!(matches!(v.security_keep_scope(&[], &bad), Err(Error::Security(_))), "{bad:?}");
|
||||
}
|
||||
v.security_keep_scope(&[], &[]).unwrap();
|
||||
assert_eq!(v.security_take_kept_scope(), Some(KeptScope { ask: vec![], offer: vec![] }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_ssh_connected_and_totp_moved_are_recorded_directly() {
|
||||
let mut v = vault();
|
||||
v.security_record(Action::SshConnected, None, NOW).unwrap();
|
||||
v.security_record(Action::TotpMoved, None, NOW + 1).unwrap();
|
||||
for a in [Action::SetupStarted, Action::SetupFinished, Action::SetupExpired, Action::Ticked, Action::Unticked] {
|
||||
assert!(matches!(v.security_record(a, Some(Item::NoSsh), NOW + 2), Err(Error::Security(_))), "{a:?}");
|
||||
}
|
||||
assert_eq!(actions(&v), [Action::SshConnected, Action::TotpMoved]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_audit_keeps_the_newest_5000() {
|
||||
assert_eq!(AUDIT_LIMIT, 5_000);
|
||||
let mut v = vault();
|
||||
for i in 0..(AUDIT_LIMIT as i64 + 2) {
|
||||
v.security_record(Action::SshConnected, None, NOW + i).unwrap();
|
||||
}
|
||||
let audit = v.security_view(NOW).audit;
|
||||
assert_eq!(audit.len(), AUDIT_LIMIT);
|
||||
assert_eq!(audit[0].at, NOW + 2);
|
||||
assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rules_before_a_card() {
|
||||
let none = BTreeSet::new();
|
||||
// Accept all: only in Setup, only for a setup run with Provisio lines only.
|
||||
assert!(accept_all_allowed(Level::Setup, "setup-1", true));
|
||||
assert!(!accept_all_allowed(Level::Setup, "setup-1", false), "a signing or approval line");
|
||||
assert!(!accept_all_allowed(Level::Setup, "r-42", true), "not a setup run");
|
||||
assert!(!accept_all_allowed(Level::Setup, "Setup-1", true), "the prefix is exact");
|
||||
assert!(!accept_all_allowed(Level::Standard, "setup-1", true));
|
||||
assert!(!accept_all_allowed(Level::Hardened, "setup-1", true));
|
||||
// A line that replaces a stored item is pre-ticked only where Accept all applies.
|
||||
assert!(replacing_line_preticked(Level::Setup, true));
|
||||
assert!(!replacing_line_preticked(Level::Setup, false));
|
||||
assert!(!replacing_line_preticked(Level::Standard, true));
|
||||
assert!(!replacing_line_preticked(Level::Hardened, true));
|
||||
// Connect via SSH.
|
||||
assert_eq!(ssh_needs_auth(Level::Setup, &none), SshRule::Allowed);
|
||||
assert_eq!(ssh_needs_auth(Level::Standard, &none), SshRule::NeedsAuth);
|
||||
let hello = BTreeSet::from([Item::HelloApprovals]);
|
||||
assert_eq!(ssh_needs_auth(Level::Hardened, &hello), SshRule::NeedsAuth);
|
||||
let off = BTreeSet::from([Item::NoSsh]);
|
||||
for l in [Level::Setup, Level::Standard, Level::Hardened] {
|
||||
assert_eq!(ssh_needs_auth(l, &off), SshRule::Off);
|
||||
}
|
||||
// TOTP offers and Hello for approvals.
|
||||
assert!(totp_offer_allowed(&none) && totp_offer_allowed(&hello));
|
||||
assert!(!totp_offer_allowed(&BTreeSet::from([Item::TotpOnPhone])));
|
||||
assert!(hello_for_approvals(&hello) && !hello_for_approvals(&none) && !hello_for_approvals(&off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_are_spelled_as_docs_format_says() {
|
||||
let all = [
|
||||
Item::TotpOnPhone,
|
||||
Item::HelloApprovals,
|
||||
Item::NarrowScope,
|
||||
Item::RotateSetup,
|
||||
Item::NoSsh,
|
||||
Item::PhoneApproves,
|
||||
];
|
||||
assert_eq!(
|
||||
serde_json::to_string(&all).unwrap(),
|
||||
r#"["totp-on-phone","hello-approvals","narrow-scope","rotate-setup","no-ssh","phone-approves"]"#
|
||||
);
|
||||
let actions = [
|
||||
Action::SetupStarted,
|
||||
Action::SetupFinished,
|
||||
Action::SetupExpired,
|
||||
Action::Ticked,
|
||||
Action::Unticked,
|
||||
Action::SshConnected,
|
||||
Action::TotpMoved,
|
||||
];
|
||||
assert_eq!(
|
||||
serde_json::to_string(&actions).unwrap(),
|
||||
r#"["setup-started","setup-finished","setup-expired","ticked","unticked","ssh-connected","totp-moved"]"#
|
||||
);
|
||||
assert_eq!(serde_json::to_string(&[Auth::Hello, Auth::Password]).unwrap(), r#"["hello","password"]"#);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&[Level::Setup, Level::Standard, Level::Hardened]).unwrap(),
|
||||
r#"["setup","standard","hardened"]"#
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_string(&[SshRule::Allowed, SshRule::NeedsAuth, SshRule::Off]).unwrap(),
|
||||
r#"["allowed","needs-auth","off"]"#
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,7 @@ fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
|
||||
file: "Arca_0.2.0_x64-setup.exe".into(),
|
||||
size: 25_145_977,
|
||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +39,8 @@ fn minisign_req(key: &str, c: Context) -> Request {
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![7; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: None,
|
||||
context: c,
|
||||
via: Via::Local,
|
||||
}
|
||||
@@ -49,6 +52,8 @@ fn authenticode_req(key: &str, c: Context) -> Request {
|
||||
kind: SignKind::Authenticode,
|
||||
digest: vec![9; 32],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: None,
|
||||
context: c,
|
||||
via: Via::Remote,
|
||||
}
|
||||
@@ -61,13 +66,21 @@ fn the_release_and_test_sets_are_made_once_each() {
|
||||
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"]
|
||||
[
|
||||
"domi-release",
|
||||
"domi-root",
|
||||
"domi-code-signing",
|
||||
"domi-approve",
|
||||
"domi-test",
|
||||
"domi-test-root",
|
||||
"domi-test-code-signing"
|
||||
]
|
||||
);
|
||||
assert_eq!(keys[1].kind, KeyKind::RootCa);
|
||||
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
|
||||
assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root"));
|
||||
assert!(!keys[0].auto_approve && !keys[2].auto_approve);
|
||||
assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve);
|
||||
assert_eq!(keys[6].issuer.as_deref(), Some("domi-test-root"));
|
||||
assert!(!keys[0].auto_approve && !keys[2].auto_approve && !keys[3].auto_approve);
|
||||
assert!(keys[4].auto_approve && keys[6].auto_approve && !keys[5].auto_approve);
|
||||
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
||||
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
|
||||
// The root's certificate is exported; a key without one is not.
|
||||
@@ -205,3 +218,177 @@ fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
|
||||
let mut reopened = reopened;
|
||||
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
|
||||
}
|
||||
|
||||
// ---- deploy approvals (core 0.12.0) ----
|
||||
|
||||
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
|
||||
|
||||
fn approval_text(run: &str, repo: &str, expires_in: i64) -> String {
|
||||
format!(
|
||||
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":{}}}"#,
|
||||
NOW / 1000 + expires_in
|
||||
)
|
||||
}
|
||||
|
||||
fn approval_req(run: &str) -> Request {
|
||||
Request {
|
||||
key: "domi-approve".into(),
|
||||
kind: SignKind::Approval,
|
||||
digest: vec![],
|
||||
manifest: None,
|
||||
approval: Some(approval_text(run, "Arca", 600)),
|
||||
run: Some(run.into()),
|
||||
context: Context {
|
||||
repo: "Arca".into(),
|
||||
pipeline: "release".into(),
|
||||
trigger: "tag".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via: Via::Remote,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domi_approve_is_made_with_the_release_keys() {
|
||||
let v = vault_with_keys();
|
||||
let keys = v.signing_keys();
|
||||
let a = keys.iter().find(|k| k.id == "domi-approve").expect("made with the release set");
|
||||
assert_eq!(a.kind, KeyKind::Ed25519);
|
||||
assert_eq!(a.role, Role::Release);
|
||||
assert_eq!(a.name, "Domi deploy approval");
|
||||
assert!(!a.auto_approve, "it always asks");
|
||||
let rel = keys.iter().find(|k| k.id == "domi-release").unwrap();
|
||||
assert_eq!((&a.pipelines, &a.repos), (&rel.pipelines, &rel.repos), "the release keys' scope");
|
||||
assert!(a.minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
||||
assert_ne!(a.key_id, rel.key_id);
|
||||
// The test set has no approval key.
|
||||
assert!(!keys.iter().any(|k| k.role == Role::Test && k.id.contains("approve")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_approval_is_signed_by_domi_approve_and_verifies_with_minisign() {
|
||||
let mut v = vault_with_keys();
|
||||
let req = approval_req("r-42");
|
||||
v.signing_check_at(&req, NOW).unwrap();
|
||||
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
|
||||
let text = String::from_utf8(signed.bytes.clone()).unwrap();
|
||||
let pubkey = v.signing_keys().into_iter().find(|k| k.id == "domi-approve").unwrap().minisign_public.unwrap();
|
||||
let public = minisign_verify::PublicKey::decode(&pubkey).unwrap();
|
||||
let sig = minisign_verify::Signature::decode(&text).unwrap();
|
||||
public.verify(req.approval.as_deref().unwrap().as_bytes(), &sig, false).unwrap();
|
||||
assert_eq!(sig.trusted_comment(), format!("timestamp:{}\tfile:approval-r-42.json\thashed", NOW / 1000));
|
||||
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
|
||||
|
||||
let e = v.signing_audit().last().unwrap();
|
||||
assert_eq!((e.key.as_str(), e.kind, e.outcome), ("domi-approve", SignKind::Approval, Outcome::Approved));
|
||||
assert_eq!(e.run.as_deref(), Some("r-42"));
|
||||
assert_eq!(e.context.file, "approval-r-42.json");
|
||||
assert_eq!((e.context.commit.as_str(), e.context.version.as_str()), (COMMIT, "0.7.0"), "filled from the JSON");
|
||||
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domi_approve_signs_only_approvals_and_approvals_only_with_domi_approve() {
|
||||
let mut v = vault_with_keys();
|
||||
let by_release = Request { key: "domi-release".into(), ..approval_req("r-42") };
|
||||
let by_test = Request { key: "domi-test".into(), ..approval_req("r-42") };
|
||||
let mut digest = minisign_req("domi-approve", ctx("release", "Arca", "tag"));
|
||||
digest.run = Some("r-42".into());
|
||||
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
|
||||
let manifest = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums), ..digest.clone() };
|
||||
let authenticode = Request { kind: SignKind::Authenticode, digest: vec![1; 32], ..digest.clone() };
|
||||
for r in [&by_release, &by_test, &digest, &manifest, &authenticode] {
|
||||
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||
}
|
||||
let code_signing = Request { key: "domi-code-signing".into(), ..approval_req("r-42") };
|
||||
assert!(matches!(v.signing_check_at(&code_signing, NOW), Err(Refusal::Invalid(_))));
|
||||
// A release key: never without Mark.
|
||||
assert!(matches!(v.signing_sign(&approval_req("r-42"), Approval::Auto, NOW), Err(Refusal::NeedsApproval(_))));
|
||||
assert!(v.signing_audit().iter().all(|e| e.signature.is_none()), "nothing was signed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_approval_needs_its_run_a_canonical_unexpired_text_and_a_matching_context() {
|
||||
let mut v = vault_with_keys();
|
||||
let invalid = |v: &mut Vault, r: &Request| {
|
||||
assert!(matches!(v.signing_check_at(r, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||
};
|
||||
invalid(&mut v, &Request { run: None, ..approval_req("r-42") });
|
||||
invalid(&mut v, &Request { run: Some("r-43".into()), ..approval_req("r-42") });
|
||||
invalid(&mut v, &Request { approval: None, ..approval_req("r-42") });
|
||||
let mut spaced = approval_req("r-42");
|
||||
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));
|
||||
invalid(&mut v, &late);
|
||||
let mut past = approval_req("r-42");
|
||||
past.approval = Some(approval_text("r-42", "Arca", 0));
|
||||
invalid(&mut v, &past);
|
||||
let zeros = "0".repeat(40);
|
||||
for (member, value) in
|
||||
[("repo", "Fabrica"), ("pipeline", "nightly"), ("commit", zeros.as_str()), ("version", "0.8.0")]
|
||||
{
|
||||
let mut r = approval_req("r-42");
|
||||
match member {
|
||||
"repo" => r.context.repo = value.into(),
|
||||
"pipeline" => r.context.pipeline = value.into(),
|
||||
"commit" => r.context.commit = value.into(),
|
||||
_ => r.context.version = value.into(),
|
||||
}
|
||||
invalid(&mut v, &r);
|
||||
}
|
||||
// The expiry is checked against the time given: valid now, expired ten minutes later.
|
||||
let ok = approval_req("r-42");
|
||||
assert!(v.signing_check_at(&ok, NOW).is_ok());
|
||||
assert!(matches!(v.signing_check_at(&ok, NOW + 600_000), Err(Refusal::Invalid(_))));
|
||||
assert!(matches!(v.signing_sign(&ok, Approval::Mark, NOW + 600_000), Err(Refusal::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_approval_for_a_repo_off_the_list_is_out_of_scope() {
|
||||
let mut v = vault_with_keys();
|
||||
let mut r = approval_req("r-42");
|
||||
r.approval = Some(approval_text("r-42", "Custos", 600));
|
||||
r.context.repo = "Custos".into();
|
||||
assert!(matches!(v.signing_check_at(&r, NOW), Err(Refusal::OutOfScope(_))));
|
||||
// The JSON's repo is what counts, even when the context leaves it empty.
|
||||
r.context.repo = String::new();
|
||||
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::OutOfScope);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_request_may_name_its_run_and_the_audit_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = vault_with_keys();
|
||||
let mut r = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
r.run = Some("r-42".into());
|
||||
r.context.version = "0.7.0".into();
|
||||
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||
v.signing_refuse(&r, Outcome::Refused, None, NOW + 1);
|
||||
let mut bad = r.clone();
|
||||
bad.run = Some("r 42".into());
|
||||
assert!(matches!(v.signing_check_at(&bad, NOW), Err(Refusal::Invalid(_))));
|
||||
let mut stray = r.clone();
|
||||
stray.approval = Some(approval_text("r-42", "Arca", 600));
|
||||
assert!(matches!(v.signing_check_at(&stray, NOW), Err(Refusal::Invalid(_))), "approval text on a digest request");
|
||||
v.save(&path).unwrap();
|
||||
let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
let a = back.signing_audit();
|
||||
assert_eq!(a[0].run.as_deref(), Some("r-42"));
|
||||
assert_eq!(a[0].context.version, "0.7.0");
|
||||
assert_eq!(a[1].run.as_deref(), Some("r-42"));
|
||||
assert_eq!(back.signing_audit(), v.signing_audit());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_approval_key_is_added_only_to_release_keys_and_only_once() {
|
||||
let mut empty = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
assert!(matches!(empty.signing_add_approve(NOW), Err(Error::Signing(_))), "no release keys");
|
||||
let mut v = vault_with_keys();
|
||||
assert!(matches!(v.signing_add_approve(NOW), Err(Error::SigningExists("approval"))));
|
||||
}
|
||||
|
||||
@@ -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 ¬es {
|
||||
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(_))));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
# Custos in the browser
|
||||
|
||||
Version 1 of the browser extension: Chromium (Edge and Chrome) on Windows, logins only. 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)─► service worker ─(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 click asks for the logins of *its own frame*, and fills the one the person picks. | Fill without a click; read anything from Custos before the list is opened; trust what the page says about its own address. |
|
||||
| `extension/popup.*` | The toolbar popup: the logins for the active tab; 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 `browser_status`, `browser_match` or `browser_fill`, with the origin taken from **`sender.url`** (the frame's real URL, as the browser reports it). | Accept messages from pages or other extensions (`sender.id` must be its own). |
|
||||
| `crates/custos-native` | The native messaging host. Reads frames from stdin, **rebuilds** each request from its known fields (op, origin ≤ 2 KiB, id ≤ 128 bytes, seq), forwards it to the Custos pipe and returns the answer. | 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 answers are zeroized). |
|
||||
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match` (which login fits which page) and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
|
||||
|
||||
## 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 or a bare name (`cz`) matches only that exact host.
|
||||
|
||||
URLs with userinfo (`https://bank.cz@evil.net`) 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 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.
|
||||
|
||||
| Extension → host | Host → Custos | Answer |
|
||||
|:--|:--|:--|
|
||||
| `{"op":"browser_status"}` | `{"op":"browser_status","app":"Custos for your browser"}` | `{"ok":true}` |
|
||||
| `{"op":"browser_match","origin":"https://github.com"}` | + `origin` | `{"ok":true,"logins":[{"id","title","username"}]}`: never a password |
|
||||
| `{"op":"browser_fill","id":"…","origin":"…"}` | + `origin`, `id` | `{"ok":true,"username","password","totp"}` only if that login matches `origin`, else `"error":"no_match"` |
|
||||
|
||||
Errors the extension turns into a sentence: `not_connected` (no host registered), `not_running`,
|
||||
`not_custos` (the pipe's server is not `custos.exe`: nothing was sent), `locked`, `denied`, `not_found`,
|
||||
`no_match`, `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 the origin again with `custos-browser` and checks the login against it on **every**
|
||||
`browser_fill`, whatever the extension asked for before.
|
||||
- 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 id
|
||||
|
||||
The extension's `manifest.json` carries a public `key`, which fixes its id to
|
||||
**`jchkapmceepdnlhagfppeckggaecdcmn`** however it is loaded (unpacked or packed). The desktop's *Connect*
|
||||
writes the host manifest with `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]`
|
||||
and registers it under `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` and
|
||||
`HKCU\Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos`, so only this extension can start
|
||||
the host. The private key that matches the public key is not in this repository; it is only needed to pack a
|
||||
`.crx` with the same id.
|
||||
|
||||
## 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.
|
||||
- Another **extension** cannot message this one (`sender.id`), and cannot start the host (`allowed_origins`).
|
||||
- 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 and no state beyond the open native port.
|
||||
|
||||
## Not yet
|
||||
|
||||
Passkeys (WebAuthn through the extension), Firefox, saving new logins from the browser, filling cards.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
cargo test -p custos-browser -p custos-native
|
||||
```
|
||||
|
||||
`custos-browser` covers origin parsing, look-alikes, ports and schemes, bare names and IPs, best-of-several and
|
||||
the frames; `custos-native` that only the three ops pass, rebuilt from known fields. The desktop repo has the
|
||||
pipe tests and an end-to-end run in Edge.
|
||||
@@ -10,6 +10,13 @@ on, Custos writes it as v2 only.
|
||||
A **machine store** (the Claude Code store) is the one exception: a separate file whose vault key is
|
||||
wrapped by one device key alone, so a program can open it unattended. It never holds the user's secrets.
|
||||
|
||||
**Taking over a machine-key vault** (core 0.13.0, Custos's hands-off vault): `Vault::take_over(password)` adds the
|
||||
master password as a factor paired with the device key and removes the single slot, in one step. From then on it is
|
||||
an ordinary version-2 vault: two factors open it, the device key alone does not, and factors are added as for any
|
||||
vault (a phone, a TOTP backup). Only a machine-key vault is taken over, and only once; `opens_with_machine_key()`
|
||||
says which it is. The take-over also ticks `no-auto-connect`, `no-unattended` and `card-signing` and writes
|
||||
`taken-over` (FORMAT.md, "The security member").
|
||||
|
||||
## Keys
|
||||
|
||||
```
|
||||
|
||||
+106
@@ -129,6 +129,112 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
||||
An older Custos drops `folder` and `attachments` when it saves.
|
||||
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
|
||||
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
|
||||
- `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.
|
||||
- `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
|
||||
"The security member" below.
|
||||
|
||||
**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. 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.
|
||||
|
||||
### The provision audit (core 0.11.0)
|
||||
|
||||
```json
|
||||
"provision": {
|
||||
"audit": [
|
||||
{ "at": 1793750100000, "direction": "offer", "host": "nixos-vm", "item": "fabrica/gitea-read-token",
|
||||
"store": "vault", "run": "deploy-7", "kind": "Gitea token, read:repository", "code": "684361",
|
||||
"outcome": "accepted", "replaced": true }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Member | |
|
||||
| :-- | :-- |
|
||||
| `at` | Unix milliseconds |
|
||||
| `direction` | `ask` (the server asked for a secret) or `offer` (the server offered one) |
|
||||
| `host` | the name the factor service gave, 1–253 characters `[A-Za-z0-9.-]` |
|
||||
| `item` | `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks it |
|
||||
| `store` | `vault`, `claude`, `cloud` or (core 0.12.0) `display`: shown once on the card, stored nowhere |
|
||||
| `run` | optional, `[A-Za-z0-9._-]{1,64}` |
|
||||
| `kind` | optional, at most 200 characters, no control characters (an offer's label; an ask's `--generate` recipe) |
|
||||
| `code` | the match code: six ASCII digits |
|
||||
| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid`, `expired` or (core 0.12.0) `confirmed` |
|
||||
| `replaced` | `true` when an accepted offer replaced an existing item |
|
||||
|
||||
A **display offer** (core 0.12.0; a TOTP seed moved to a phone) is an `offer` with store `display`. Its outcome is
|
||||
`confirmed` (Mark typed the phone's current code, Custos checked it and sent it to the server), `refused`, `expired`,
|
||||
`invalid` or `out-of-scope`; never `accepted`, `approved` or `generated`, and never `replaced`, because nothing is
|
||||
stored. `confirmed` belongs to display offers only. A code Custos's own check refuses stays on the card and is not
|
||||
an outcome; a code the server then refuses (its exit 10) is not seen by Custos, so there is no `confirmed-wrong`.
|
||||
|
||||
- **No value, ever.** There is no member that holds a secret: every member is something the server sent in the
|
||||
clear through the mailbox (host, item, store, run, kind) or derives from a public key (`code`). A recorded
|
||||
entry is checked against the table above; an entry that does not fit is refused, not stored.
|
||||
- **Append-only.** The API records an entry and lists them (oldest first); nothing edits or removes one, except
|
||||
that the log keeps the newest 5 000 entries and drops the oldest beyond that.
|
||||
- Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or
|
||||
`store` this core does not know does not open (`Corrupted`), as for `signing`.
|
||||
|
||||
### The security member (core 0.12.0; hands-off values 0.13.0)
|
||||
|
||||
```json
|
||||
"security": {
|
||||
"setup": { "started": 1793750000000, "until": 1793757200000 },
|
||||
"finished": 1793751000000,
|
||||
"ticked": ["hello-approvals", "no-ssh"],
|
||||
"keptScope": { "ask": ["arca/"], "offer": ["arca/", "fabrica/"] },
|
||||
"audit": [
|
||||
{ "at": 1793750000000, "action": "setup-started" },
|
||||
{ "at": 1793751000000, "action": "setup-finished" },
|
||||
{ "at": 1793752000000, "action": "ticked", "item": "no-ssh" },
|
||||
{ "at": 1793753000000, "action": "unticked", "item": "no-ssh", "auth": "hello" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Member | |
|
||||
| :-- | :-- |
|
||||
| `setup` | optional: the last Setup window, Unix milliseconds; `until` is 2 hours after `started` |
|
||||
| `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`, or (core 0.16.0) `standing-granted`, `standing-revoked`; `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:
|
||||
|
||||
- **Setup** while there is a `setup` window, it has not `finished`, and `started` ≤ now < `until`;
|
||||
- otherwise **Hardened** when at least one item is ticked;
|
||||
- otherwise **Standard** (also every vault without the member).
|
||||
|
||||
Ticked items hold during Setup too: Setup never undoes hardening. Starting Setup while in Setup changes nothing;
|
||||
after a window ended a new one starts at now. Its expiry is written (`setup-expired`, and `finished` = `until`) by
|
||||
the first change after it, not by reading.
|
||||
|
||||
- **Append-only** like `provision`: the API adds entries and lists them; the log keeps the newest 5 000.
|
||||
- Absent while nothing was ever set, so a vault without it is written exactly as before.
|
||||
- The values new in core 0.13.0 make a vault unreadable for a core before 0.13.0 once one is written, as the
|
||||
0.12.0 values did before.
|
||||
- **Hands-off rules** (core 0.13.0, `security`): `is_setup_run` (`setup-` and 1–58 of `[A-Za-z0-9._-]`),
|
||||
`auto_connect_allowed` (not Hardened, neither `no-auto-connect` nor `no-ssh`), `setup_on_connect` (neither
|
||||
`no-unattended` nor `no-ssh`), `unattended_provision` (in Setup, a setup run, `no-unattended` not ticked, never an
|
||||
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`; 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`).
|
||||
|
||||
### Item types and their fields (v1)
|
||||
|
||||
|
||||
+23
-2
@@ -20,8 +20,29 @@ aad "CSL1" ‖ E ‖ context
|
||||
A box opens only with the context it was sealed for, so a box for one request does not work as another.
|
||||
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
|
||||
- **Plaintext limit:** 32 KiB.
|
||||
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
|
||||
and is wiped on drop. Nothing writes it to disk.
|
||||
- **The recipient's secret half** lives in memory as `x25519_dalek::StaticSecret` with `zeroize`, and is
|
||||
wiped on drop. One-time keys (`Recipient::generate`) are the default and nothing writes them to disk.
|
||||
|
||||
### A kept key (core 0.11.0)
|
||||
|
||||
The recipient's secret may now be kept by the caller, for one purpose: the PC's Provisio sealing key
|
||||
(docs/10_provisio.md in the app), the key the server seals **offers** to. Custos makes it once with
|
||||
`Recipient::generate`, keeps `Recipient::secret_bytes()` DPAPI-sealed in `<data>actors\provision.key`, and
|
||||
restores it with `Recipient::from_secret` at every start. Everything else (approvals, pairing, a Provisio *ask*)
|
||||
still uses a fresh one-time key per request.
|
||||
|
||||
```
|
||||
Recipient::from_secret(Zeroizing<[u8; 32]>) -> Result<Recipient, SealError> // BadKey for a known key
|
||||
Recipient::secret_bytes(&self) -> Zeroizing<[u8; 32]> // only for a key that is kept
|
||||
```
|
||||
|
||||
- `from_secret` refuses (`BadKey`) a secret that X25519 clamps to zero (all zeros: a wiped or never-filled
|
||||
buffer) and, as for public keys, one whose shared secrets would not be contributory.
|
||||
- A kept key opens every box ever sealed to it, so the **context** carries the binding: an offer is sealed for
|
||||
`provision-offer:<store>:<item>`, and the PC checks the plaintext's item, store, kind and code key against the
|
||||
offer before it shows a card. The mailbox refuses an offer whose ephemeral key it has seen (replay).
|
||||
- `secret_bytes` hands out the secret in a `Zeroizing` buffer. It goes to the caller's sealed storage and
|
||||
nowhere else: never a log, a message or a file in the clear. `Debug` of a `Recipient` prints `[redacted]`.
|
||||
|
||||
## The match code
|
||||
|
||||
|
||||
+162
-10
@@ -1,4 +1,4 @@
|
||||
# Signing keys (core 0.9.0)
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.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
|
||||
@@ -18,12 +18,16 @@ In the vault body, next to `identity` (FORMAT.md), as the optional member `signi
|
||||
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
|
||||
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
|
||||
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
|
||||
"pipelines": ["release"], "repos": ["Arca"] }
|
||||
"pipelines": ["release"], "repos": ["Arca"] },
|
||||
{ "id": "domi-approve", "kind": "ed25519", "role": "release", "name": "Domi deploy approval",
|
||||
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
|
||||
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] }
|
||||
],
|
||||
"audit": [
|
||||
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
|
||||
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
|
||||
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>" }
|
||||
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>",
|
||||
"run": "r-42", "version": "0.1.0" }
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -39,15 +43,29 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul
|
||||
|
||||
| `kind` | Key | Signs | Created |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest` | random |
|
||||
| `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 |
|
||||
| `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` and `domi-code-signing`.
|
||||
`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
|
||||
release keys' scope. A vault whose release keys were made by an older core gets it with `signing_add_approve`
|
||||
(*Create approval key*).
|
||||
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
|
||||
`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).
|
||||
@@ -59,6 +77,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
|
||||
|
||||
@@ -69,6 +90,12 @@ A request names a key, a kind and what to sign. Custos never receives the file.
|
||||
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
|
||||
| `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
|
||||
request of another kind is `invalid` too.
|
||||
|
||||
### minisign
|
||||
|
||||
@@ -96,6 +123,40 @@ the whole minisign text. That wrapping is the build's job.
|
||||
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
|
||||
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
|
||||
|
||||
### approval (core 0.12.0)
|
||||
|
||||
A deploy approval says "this run of this commit may deploy to these targets until then". Fabrica's hub checks it with
|
||||
`domi-approve`'s public key before it runs a deploy step. What is signed is one line of JSON, no spaces, the keys in
|
||||
exactly this order:
|
||||
|
||||
```
|
||||
{"v":1,"run":"r-42","repo":"Arca","commit":"<40 hex>","pipeline":"release","version":"0.7.0","targets":["deploy to nixos-vm","publish to Aula"],"expires":1793000000}
|
||||
```
|
||||
|
||||
| Key | |
|
||||
| :-- | :-- |
|
||||
| `v` | `1` |
|
||||
| `run` | `[A-Za-z0-9._-]{1,64}`, equal to the request's `run` |
|
||||
| `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) |
|
||||
|
||||
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
|
||||
parses the text, writes it again in this form and refuses anything that is not byte-identical (`invalid`): another
|
||||
key order, a space, an escape, a duplicate or unknown key, a number written as `1.0`.
|
||||
|
||||
The signature is a prehashed minisign signature over those bytes, made exactly as for `minisign` with the file name
|
||||
`approval-<run>.json`, so the trusted comment is `timestamp:<now>\tfile:approval-<run>.json\thashed`
|
||||
(the `hashed` that minisign itself writes for a prehashed signature). `minisign -V -P <domi-approve public key> -m
|
||||
approval.json` verifies it.
|
||||
|
||||
`domi-approve` signs only `approval`, and `approval` is signed only by `domi-approve`; it is a release key, so it
|
||||
always asks. The scope is checked against the JSON's `repo` and `pipeline`; a request whose context names another
|
||||
`repo`, `pipeline`, `commit` or `version` than its JSON is `invalid` (an empty context member is filled from the JSON
|
||||
in the audit). The audit entry's `file` is `approval-<run>.json`.
|
||||
|
||||
### authenticode
|
||||
|
||||
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
|
||||
@@ -112,6 +173,73 @@ 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.
|
||||
|
||||
## 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 audit log
|
||||
|
||||
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
|
||||
@@ -120,27 +248,51 @@ 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 |
|
||||
| `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 not in canonical form, a kind the key cannot do) |
|
||||
| `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) |
|
||||
|
||||
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
|
||||
`remote` (the factor service's mailbox). The entry is part of the vault, so it survives a reopen and travels with it.
|
||||
`remote` (the factor service's mailbox). `run` (core 0.12.0) is the request's run, absent without one; `version`
|
||||
(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 (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.
|
||||
|
||||
## The API (custos-vault)
|
||||
|
||||
```
|
||||
Vault::signing_create(role, pipelines, repos, now) -> ids // release or test set
|
||||
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
|
||||
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
|
||||
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, 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
|
||||
```
|
||||
|
||||
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the
|
||||
// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`,
|
||||
// the tab's URL), never what a page says about itself; Custos decides which logins belong to it.
|
||||
|
||||
const HOST = 'cz.marek_novak.custos';
|
||||
|
||||
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */
|
||||
let port = null;
|
||||
let seq = 0;
|
||||
const waiting = new Map();
|
||||
|
||||
function connect() {
|
||||
if (port) return port;
|
||||
port = chrome.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(() => {
|
||||
// Not registered, or the host exited: every open request fails the same way.
|
||||
const why = chrome.runtime.lastError?.message ?? '';
|
||||
const error = /not found|forbidden/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, seq: n });
|
||||
} catch {
|
||||
waiting.delete(n);
|
||||
resolve({ ok: false, error: 'not_connected' });
|
||||
}
|
||||
// Custos may wait up to a minute for an unlock or an approval.
|
||||
setTimeout(() => {
|
||||
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
|
||||
}, 75_000);
|
||||
});
|
||||
}
|
||||
|
||||
/** `https://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;
|
||||
}
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||
// Only this extension's own pages and content scripts reach here; pages cannot send to it.
|
||||
if (sender.id !== chrome.runtime.id) return false;
|
||||
(async () => {
|
||||
switch (msg?.kind) {
|
||||
case 'status':
|
||||
return reply(await ask({ op: 'browser_status' }));
|
||||
case 'match': {
|
||||
// From a content script: the logins for the frame it runs in.
|
||||
const origin = originOf(sender.url);
|
||||
if (!origin) return reply({ ok: false, error: 'no_match' });
|
||||
return reply({ ...(await ask({ op: 'browser_match', origin })), origin });
|
||||
}
|
||||
case 'fill': {
|
||||
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
|
||||
const origin = originOf(sender.url);
|
||||
if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' });
|
||||
return reply(await ask({ op: 'browser_fill', id: msg.id, origin }));
|
||||
}
|
||||
case 'match-tab': {
|
||||
// From the popup: the logins for the active tab's page.
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
const origin = tab && originOf(tab.url);
|
||||
if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null });
|
||||
return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id });
|
||||
}
|
||||
default:
|
||||
return reply({ ok: false, error: 'bad_request' });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
// 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 and the
|
||||
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens.
|
||||
(() => {
|
||||
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.',
|
||||
locked: 'Custos is locked. Unlock it, then try again.',
|
||||
denied: 'Custos did not allow this browser to use your logins.',
|
||||
not_found: 'That login is no longer in Custos.',
|
||||
no_match: 'That login does not belong to this site.',
|
||||
no_answer: 'Custos did not answer.',
|
||||
};
|
||||
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||
function put(el, value) {
|
||||
if (!el || 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 }));
|
||||
}
|
||||
|
||||
async function fill(id, near) {
|
||||
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
|
||||
if (!r?.ok) return say(r?.error);
|
||||
const f = fieldsAround(near);
|
||||
put(f.user, r.username);
|
||||
put(f.pass, r.password);
|
||||
if (f.otp) put(f.otp, r.totp);
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- the button and the list ----
|
||||
|
||||
const host = document.createElement('custos-fill');
|
||||
const root = host.attachShadow({ mode: 'closed' });
|
||||
root.innerHTML = `
|
||||
<style>
|
||||
:host { all: initial; }
|
||||
.chip, .menu { 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 { 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); }
|
||||
.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; }
|
||||
[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>`;
|
||||
const chip = root.querySelector('.chip');
|
||||
const menu = root.querySelector('.menu');
|
||||
let field = null;
|
||||
|
||||
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(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
|
||||
menu.hidden = false;
|
||||
}
|
||||
|
||||
async function open() {
|
||||
const target = field;
|
||||
note('Asking Custos…');
|
||||
const r = await chrome.runtime.sendMessage({ 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 head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
|
||||
const items = r.logins.map((l) => {
|
||||
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' });
|
||||
b.setAttribute('role', 'menuitem');
|
||||
b.append(
|
||||
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||
);
|
||||
b.addEventListener('click', async () => {
|
||||
const why = await fill(l.id, target);
|
||||
if (why) note(why);
|
||||
else hide();
|
||||
});
|
||||
return b;
|
||||
});
|
||||
menu.replaceChildren(head, ...items);
|
||||
items[0]?.focus();
|
||||
}
|
||||
|
||||
chip.addEventListener('click', () => (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 el = e.target;
|
||||
if (!(el instanceof HTMLInputElement) || !visible(el)) return;
|
||||
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return;
|
||||
if (!host.isConnected) document.documentElement.append(host);
|
||||
field = el;
|
||||
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);
|
||||
|
||||
// The popup's choice, in the top frame: fill the page's login form.
|
||||
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||
if (sender.id !== chrome.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;
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"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.",
|
||||
"version": "0.15.0",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
|
||||
"minimum_chrome_version": "116",
|
||||
"permissions": [
|
||||
"nativeMessaging",
|
||||
"activeTab"
|
||||
],
|
||||
"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'"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
: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;
|
||||
}
|
||||
footer {
|
||||
padding: 8px 14px 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<!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>
|
||||
<p id="note" class="note">Asking Custos…</p>
|
||||
<ul id="logins" class="logins" aria-label="Logins for this site"></ul>
|
||||
</main>
|
||||
<footer>Only logins saved for this site are offered here.</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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).
|
||||
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.',
|
||||
locked: 'Custos is locked. Unlock it, then try again.',
|
||||
denied: 'Custos did not allow this browser to use your logins.',
|
||||
not_found: 'That login is no longer in Custos.',
|
||||
no_match: 'Custos fills only web pages (https, or this computer).',
|
||||
no_answer: 'Custos did not answer.',
|
||||
};
|
||||
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||
const note = document.getElementById('note');
|
||||
const list = document.getElementById('logins');
|
||||
|
||||
async function show() {
|
||||
const r = await chrome.runtime.sendMessage({ kind: 'match-tab' });
|
||||
if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host;
|
||||
if (!r?.ok) {
|
||||
note.textContent = say(r?.error);
|
||||
return;
|
||||
}
|
||||
if (!r.logins.length) {
|
||||
note.textContent = 'Custos has no login for this site.';
|
||||
return;
|
||||
}
|
||||
note.hidden = true;
|
||||
for (const l of r.logins) {
|
||||
const li = document.createElement('li');
|
||||
const b = Object.assign(document.createElement('button'), { type: 'button' });
|
||||
b.append(
|
||||
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||
);
|
||||
b.addEventListener('click', async () => {
|
||||
const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null);
|
||||
if (done?.ok) window.close();
|
||||
else {
|
||||
note.hidden = false;
|
||||
note.textContent = done?.error ?? 'This page has no login form Custos can fill.';
|
||||
}
|
||||
});
|
||||
li.append(b);
|
||||
list.append(li);
|
||||
}
|
||||
list.querySelector('button')?.focus();
|
||||
}
|
||||
|
||||
void show();
|
||||
Reference in New Issue
Block a user