diff --git a/crates/automation/README.md b/crates/automation/README.md index 91f0eff84..7c821d58f 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -7,7 +7,7 @@ Drive a running Craft app from tests, agents and the CLI, and record and play ac | `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. | | `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. | | `args` | `ControlOptions`: the `--control `, `--control-token`, `--control-token-file` values and their `_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). | -| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the `auth` handshake, bounded line reads, connection and request limits. | +| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | | `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index d6ae9ce11..96ac748c6 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -1,7 +1,9 @@ -//! Tokens, the `auth` handshake and the limits every transport applies. +//! Tokens, the authentication handshake and the limits every transport applies. //! -//! A connection's first line must be `{"id": 1, "method": "auth", "params": {"token": "<64 hex>"}}` -//! within [`AUTH_DEADLINE`]; until then nothing else is answered. A request line is at most +//! A connection authenticates within [`AUTH_DEADLINE`] ([`ServerHandshake`]): with the challenge +//! handshake, which never sends the token, or with the one-frame +//! `{"id": 1, "method": "auth", "params": {"token": "<64 hex>"}}`. Until then nothing else is +//! answered. A request line is at most //! [`MAX_REQUEST_BYTES`]; a transport serves at most [`MAX_CONNECTIONS`] at once; a connection //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. @@ -12,10 +14,15 @@ use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; +use hmac::{Hmac, Mac}; use serde_json::{Value, json}; +use sha2::Sha256; -/// The handshake method name. +/// The request that authenticates a connection: with the token itself, or with the client's +/// proof after [`CHALLENGE_METHOD`]. pub const AUTH_METHOD: &str = "auth"; +/// The first frame of challenge authentication: it carries a client nonce, never the token. +pub const CHALLENGE_METHOD: &str = "auth.challenge"; /// Longest request line, in bytes; a longer one gets an error reply and the connection closes. pub const MAX_REQUEST_BYTES: usize = 1 << 20; /// Connections served at once; the next one gets `connection limit reached` and is closed. @@ -95,21 +102,41 @@ pub fn discard_rest_of_line(reader: &mut impl BufRead) -> std::io::Result<()> { /// A failure is [`AutomationError::Io`] with `cannot generate control token: {e}` (PhotoCraft /// uses its app-level `Other` variant for it). pub fn generate_token() -> Result { + random_hex("control token") +} + +/// A fresh nonce for challenge authentication ([`CHALLENGE_METHOD`]), made as +/// [`generate_token`] makes a token. +pub fn generate_nonce() -> Result { + random_hex("authentication nonce") +} + +/// 32 bytes from the OS randomness source as lower-case hex. +fn random_hex(what: &str) -> Result { let mut bytes = [0u8; TOKEN_HEX_LEN / 2]; - getrandom::fill(&mut bytes).map_err(|e| AutomationError::Io(format!("cannot generate control token: {e}")))?; + getrandom::fill(&mut bytes).map_err(|e| AutomationError::Io(format!("cannot generate {what}: {e}")))?; + Ok(hex(&bytes)) +} + +fn hex(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut token = String::with_capacity(TOKEN_HEX_LEN); - for byte in bytes { - token.push(HEX[(byte >> 4) as usize] as char); - token.push(HEX[(byte & 0x0f) as usize] as char); + let mut out = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); } - Ok(token) + out +} + +/// Whether `s` has the shape of a token or a nonce: exactly [`TOKEN_HEX_LEN`] hex digits. +pub fn is_hex256(s: &str) -> bool { + s.len() == TOKEN_HEX_LEN && s.bytes().all(|b| b.is_ascii_hexdigit()) } /// Exactly [`TOKEN_HEX_LEN`] ASCII hex digits, upper or lower case; otherwise /// `BadRequest("control token must contain exactly 64 hexadecimal characters")`. pub fn validate_token(token: &str) -> Result<(), AutomationError> { - if token.len() != TOKEN_HEX_LEN || !token.bytes().all(|b| b.is_ascii_hexdigit()) { + if !is_hex256(token) { return Err(AutomationError::BadRequest("control token must contain exactly 64 hexadecimal characters".into())); } Ok(()) @@ -126,31 +153,114 @@ pub fn token_matches(expected: &str, supplied: &str) -> bool { expected.bytes().zip(supplied.bytes()).fold(0u8, |different, (a, b)| different | (a.to_ascii_lowercase() ^ b.to_ascii_lowercase())) == 0 } -/// The reply to a connection's first line: `(reply, authenticated)`. A match gets -/// `{"id", "ok": true, "result": {"authenticated": true}}`. A line that is not JSON gets -/// `{"id": null, "ok": false, "error": "authentication required"}`; one that is not an `auth` -/// request, or whose `params.token` does not match, gets the same with its `id`; then the -/// connection closes. -pub fn authentication_reply(line: &str, expected_token: &str) -> (Value, bool) { - let Ok(req) = serde_json::from_str::(line) else { - return (json!({"id": null, "ok": false, "error": "authentication required"}), false); +/// Which side of the challenge handshake a proof comes from. Each side's proof is keyed by the +/// token over both nonces under its own label, so one side's proof never passes for the other's. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProofRole { + /// The server's answer to `auth.challenge` (`serverProof`). + Server, + /// The client's `auth {proof}`. + Client, +} + +/// HMAC-SHA256 keyed by the lower-cased token over `