mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 07:35:02 +00:00
merge-fwe: FW16 E2: challenge handshake (ServerHandshake) in craft-automation's control channel, one-frame auth kept
This commit is contained in:
@@ -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 <PORT>`, `--control-token`, `--control-token-file` values and their `<APP>_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. |
|
||||
|
||||
@@ -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<String, AutomationError> {
|
||||
random_hex("control token")
|
||||
}
|
||||
|
||||
/// A fresh nonce for challenge authentication ([`CHALLENGE_METHOD`]), made as
|
||||
/// [`generate_token`] makes a token.
|
||||
pub fn generate_nonce() -> Result<String, AutomationError> {
|
||||
random_hex("authentication nonce")
|
||||
}
|
||||
|
||||
/// 32 bytes from the OS randomness source as lower-case hex.
|
||||
fn random_hex(what: &str) -> Result<String, AutomationError> {
|
||||
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::<Value>(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 `<label>\n<client nonce>\n<server nonce>`
|
||||
/// (nonces lower-cased), as 64 lower-case hex characters. The labels are
|
||||
/// `photocraft-control-v1 server` and `photocraft-control-v1 client`.
|
||||
pub fn handshake_proof(token: &str, role: ProofRole, client_nonce: &str, server_nonce: &str) -> Result<String, AutomationError> {
|
||||
// The wire label of protocol version 1, which PhotoCraft's clients and scripts already speak:
|
||||
// changing these bytes is a protocol version change.
|
||||
let label: &[u8] = match role {
|
||||
ProofRole::Server => b"photocraft-control-v1 server",
|
||||
ProofRole::Client => b"photocraft-control-v1 client",
|
||||
};
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let supplied = req.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or("");
|
||||
let ok = req.get("method").and_then(Value::as_str) == Some(AUTH_METHOD) && token_matches(expected_token, supplied);
|
||||
if ok {
|
||||
(json!({"id": id, "ok": true, "result": {"authenticated": true}}), true)
|
||||
} else {
|
||||
(json!({"id": id, "ok": false, "error": "authentication required"}), false)
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(token.to_ascii_lowercase().as_bytes())
|
||||
.map_err(|e| AutomationError::Io(format!("cannot key the authentication proof: {e}")))?;
|
||||
for part in [label, b"\n", client_nonce.to_ascii_lowercase().as_bytes(), b"\n", server_nonce.to_ascii_lowercase().as_bytes()] {
|
||||
mac.update(part);
|
||||
}
|
||||
Ok(hex(&mac.finalize().into_bytes()))
|
||||
}
|
||||
|
||||
/// Whether `supplied` is `role`'s proof for these nonces, compared without an early exit.
|
||||
pub fn proof_matches(token: &str, role: ProofRole, client_nonce: &str, server_nonce: &str, supplied: &str) -> bool {
|
||||
handshake_proof(token, role, client_nonce, server_nonce).is_ok_and(|expected| token_matches(&expected, supplied))
|
||||
}
|
||||
|
||||
/// Where a connection's authentication stands after one frame.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AuthStep {
|
||||
/// Authenticated: dispatch the frames that follow.
|
||||
Authenticated,
|
||||
/// A challenge was answered: the next frame must be `auth` with the client's proof.
|
||||
Challenged,
|
||||
/// Refused: send the reply, then close the connection.
|
||||
Rejected,
|
||||
}
|
||||
|
||||
/// The server side of a connection's authentication, one per connection. It accepts either
|
||||
///
|
||||
/// - the challenge handshake: `auth.challenge {clientNonce}` is answered with
|
||||
/// `{serverNonce, serverProof}`, then `auth {proof}` authenticates. The token never crosses the
|
||||
/// wire, and the client learns that the server holds the token before it reveals anything
|
||||
/// derived from it; or
|
||||
/// - the one-frame `auth {token}`, which existing clients and scripts send.
|
||||
///
|
||||
/// A refusal is `{"id", "ok": false, "error": "authentication required"}` (`"id": null` for a line
|
||||
/// that is not JSON); success is `{"id", "ok": true, "result": {"authenticated": true}}`. No control
|
||||
/// method is answered before authentication.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ServerHandshake {
|
||||
/// The client and server nonces of the challenge this connection was given, until its `auth`.
|
||||
challenge: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl ServerHandshake {
|
||||
/// A handshake for a freshly accepted connection: no challenge issued yet.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Answers one frame received before authentication. Never dispatches a control method.
|
||||
pub fn reply(&mut self, line: &str, token: &str) -> (Value, AuthStep) {
|
||||
let refused = |id: Value| (json!({"id": id, "ok": false, "error": "authentication required"}), AuthStep::Rejected);
|
||||
let authenticated = |id: Value| (json!({"id": id, "ok": true, "result": {"authenticated": true}}), AuthStep::Authenticated);
|
||||
let Ok(req) = serde_json::from_str::<Value>(line) else {
|
||||
return refused(Value::Null);
|
||||
};
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
let param = |key: &str| req.get("params").and_then(|p| p.get(key)).and_then(Value::as_str);
|
||||
match (req.get("method").and_then(Value::as_str), self.challenge.take()) {
|
||||
(Some(CHALLENGE_METHOD), None) => {
|
||||
let Some(client_nonce) = param("clientNonce").filter(|n| is_hex256(n)).map(str::to_ascii_lowercase) else {
|
||||
return refused(id);
|
||||
};
|
||||
let Ok(server_nonce) = generate_nonce() else {
|
||||
return (json!({"id": id, "ok": false, "error": "cannot generate an authentication challenge"}), AuthStep::Rejected);
|
||||
};
|
||||
let Ok(server_proof) = handshake_proof(token, ProofRole::Server, &client_nonce, &server_nonce) else {
|
||||
return refused(id);
|
||||
};
|
||||
let reply = json!({"id": id, "ok": true, "result": {"serverNonce": server_nonce, "serverProof": server_proof}});
|
||||
self.challenge = Some((client_nonce, server_nonce));
|
||||
(reply, AuthStep::Challenged)
|
||||
}
|
||||
// After a challenge only the proof authenticates; the token is never needed.
|
||||
(Some(AUTH_METHOD), Some((client_nonce, server_nonce))) => match param("proof") {
|
||||
Some(proof) if proof_matches(token, ProofRole::Client, &client_nonce, &server_nonce, proof) => authenticated(id),
|
||||
_ => refused(id),
|
||||
},
|
||||
(Some(AUTH_METHOD), None) if token_matches(token, param("token").unwrap_or("")) => authenticated(id),
|
||||
_ => refused(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An `auth` request on an already authenticated connection gets
|
||||
/// An `auth` or `auth.challenge` request on an already authenticated connection gets
|
||||
/// `{"id", "ok": false, "error": "already authenticated"}`; any other line (or one that is not
|
||||
/// JSON) is `None` and goes to the method dispatcher as usual.
|
||||
pub fn repeat_auth_reply(line: &str) -> Option<Value> {
|
||||
let req: Value = serde_json::from_str(line).ok()?;
|
||||
if req.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
|
||||
if !matches!(req.get("method").and_then(Value::as_str), Some(AUTH_METHOD | CHALLENGE_METHOD)) {
|
||||
return None;
|
||||
}
|
||||
let id = req.get("id").cloned().unwrap_or(Value::Null);
|
||||
|
||||
@@ -17,31 +17,104 @@ fn scratch_dir(name: &str) -> std::path::PathBuf {
|
||||
dir
|
||||
}
|
||||
|
||||
// A connection's first line must be a matching `auth`; anything else is refused and closes.
|
||||
/// One frame through a fresh handshake: the reply and whether it authenticated.
|
||||
fn one_frame(line: &str, token: &str) -> (Value, bool) {
|
||||
let (reply, step) = ServerHandshake::new().reply(line, token);
|
||||
(reply, step == AuthStep::Authenticated)
|
||||
}
|
||||
|
||||
fn auth_line(token: &str) -> String {
|
||||
format!(r#"{{"id": 7, "method": "auth", "params": {{"token": "{token}"}}}}"#)
|
||||
}
|
||||
|
||||
fn challenge_line(client_nonce: &str) -> String {
|
||||
serde_json::json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}}).to_string()
|
||||
}
|
||||
|
||||
fn proof_line(proof: &str) -> String {
|
||||
serde_json::json!({"id": 2, "method": AUTH_METHOD, "params": {"proof": proof}}).to_string()
|
||||
}
|
||||
|
||||
// The one-frame `auth {token}` still authenticates; anything else as a first line is refused.
|
||||
#[trial]
|
||||
fn first_line_must_authenticate() {
|
||||
let auth = |token: &str| format!(r#"{{"id": 7, "method": "auth", "params": {{"token": "{token}"}}}}"#);
|
||||
fn the_one_frame_token_auth_still_authenticates() {
|
||||
let refused = |id: Value| serde_json::json!({"id": id, "ok": false, "error": "authentication required"});
|
||||
|
||||
let (reply, ok) = authentication_reply(&auth(TOKEN), TOKEN);
|
||||
let (reply, ok) = one_frame(&auth_line(TOKEN), TOKEN);
|
||||
assert!(ok);
|
||||
assert_eq!(reply, serde_json::json!({"id": 7, "ok": true, "result": {"authenticated": true}}));
|
||||
|
||||
// The server's copy is lower-cased; a client sends the token as configured.
|
||||
assert!(authentication_reply(&auth(&TOKEN.to_uppercase()), TOKEN).1);
|
||||
assert!(one_frame(&auth_line(&TOKEN.to_uppercase()), TOKEN).1);
|
||||
|
||||
let wrong = TOKEN.replace('0', "1");
|
||||
assert_eq!(authentication_reply(&auth(&wrong), TOKEN), (refused(7.into()), false));
|
||||
assert_eq!(authentication_reply(&auth("short"), TOKEN), (refused(7.into()), false));
|
||||
assert_eq!(one_frame(&auth_line(&wrong), TOKEN), (refused(7.into()), false));
|
||||
assert_eq!(one_frame(&auth_line("short"), TOKEN), (refused(7.into()), false));
|
||||
let other_method = format!(r#"{{"id": 8, "method": "ui.click", "params": {{"token": "{TOKEN}"}}}}"#);
|
||||
assert_eq!(authentication_reply(&other_method, TOKEN), (refused(8.into()), false));
|
||||
assert_eq!(authentication_reply("not json", TOKEN), (refused(Value::Null), false));
|
||||
assert_eq!(one_frame(&other_method, TOKEN), (refused(8.into()), false));
|
||||
assert_eq!(one_frame("not json", TOKEN), (refused(Value::Null), false));
|
||||
|
||||
assert_eq!(repeat_auth_reply(&auth(TOKEN)).unwrap(), serde_json::json!({"id": 7, "ok": false, "error": "already authenticated"}));
|
||||
let already = |id: i64| serde_json::json!({"id": id, "ok": false, "error": "already authenticated"});
|
||||
assert_eq!(repeat_auth_reply(&auth_line(TOKEN)).unwrap(), already(7));
|
||||
assert_eq!(repeat_auth_reply(&challenge_line(TOKEN)).unwrap(), already(1));
|
||||
assert_eq!(repeat_auth_reply(r#"{"id": 1, "method": "ui.click"}"#), None);
|
||||
assert_eq!(repeat_auth_reply("not json"), None);
|
||||
}
|
||||
|
||||
// A client proves it holds the token, and learns that the server does, without the token crossing
|
||||
// the wire.
|
||||
#[trial]
|
||||
fn challenge_authentication_proves_the_token_both_ways_without_sending_it() {
|
||||
let token = generate_token().unwrap();
|
||||
let client_nonce = generate_nonce().unwrap();
|
||||
let mut server = ServerHandshake::new();
|
||||
let (reply, step) = server.reply(&challenge_line(&client_nonce), &token);
|
||||
assert_eq!(step, AuthStep::Challenged, "{reply}");
|
||||
assert!(!reply.to_string().contains(&token), "the challenge reply must not carry the token");
|
||||
let server_nonce = reply["result"]["serverNonce"].as_str().unwrap();
|
||||
let server_proof = reply["result"]["serverProof"].as_str().unwrap();
|
||||
assert!(is_hex256(server_nonce) && server_nonce != client_nonce);
|
||||
assert!(proof_matches(&token, ProofRole::Server, &client_nonce, server_nonce, server_proof));
|
||||
// A server holding another token cannot produce that proof.
|
||||
let other = generate_token().unwrap();
|
||||
assert!(!proof_matches(&other, ProofRole::Server, &client_nonce, server_nonce, server_proof));
|
||||
// The server's proof is not the client's: replaying it back does not authenticate.
|
||||
assert!(!proof_matches(&token, ProofRole::Client, &client_nonce, server_nonce, server_proof));
|
||||
|
||||
let proof = handshake_proof(&token, ProofRole::Client, &client_nonce, server_nonce).unwrap();
|
||||
assert_ne!(proof, token);
|
||||
let (reply, step) = server.reply(&proof_line(&proof), &token);
|
||||
assert_eq!(step, AuthStep::Authenticated, "{reply}");
|
||||
assert_eq!(reply["result"]["authenticated"], true);
|
||||
}
|
||||
|
||||
// After a challenge, a wrong, missing or token-shaped proof, the token itself, a second challenge
|
||||
// and a control method are all refused, and a malformed nonce gets no challenge.
|
||||
#[trial]
|
||||
fn challenge_authentication_refuses_a_wrong_or_missing_proof() {
|
||||
let token = generate_token().unwrap();
|
||||
let client_nonce = generate_nonce().unwrap();
|
||||
let wrong = handshake_proof(&generate_token().unwrap(), ProofRole::Client, &client_nonce, &client_nonce).unwrap();
|
||||
let bad_proofs = [proof_line(&wrong), proof_line(&token), serde_json::json!({"id": 2, "method": AUTH_METHOD, "params": {}}).to_string()];
|
||||
for line in bad_proofs {
|
||||
let mut server = ServerHandshake::new();
|
||||
assert_eq!(server.reply(&challenge_line(&client_nonce), &token).1, AuthStep::Challenged);
|
||||
let (reply, step) = server.reply(&line, &token);
|
||||
assert_eq!(step, AuthStep::Rejected, "{line}: {reply}");
|
||||
assert_eq!(reply["error"], "authentication required");
|
||||
}
|
||||
for line in [auth_line(&token), challenge_line(&client_nonce), r#"{"id":3,"method":"methods"}"#.to_owned()] {
|
||||
let mut server = ServerHandshake::new();
|
||||
assert_eq!(server.reply(&challenge_line(&client_nonce), &token).1, AuthStep::Challenged);
|
||||
assert_eq!(server.reply(&line, &token).1, AuthStep::Rejected, "{line}");
|
||||
}
|
||||
for nonce in ["", "short", &"g".repeat(64), &"a".repeat(65)] {
|
||||
let (reply, step) = ServerHandshake::new().reply(&challenge_line(nonce), &token);
|
||||
assert_eq!(step, AuthStep::Rejected, "{nonce}: {reply}");
|
||||
assert!(reply.get("result").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
// Tokens are 64 lower-case hex; a file token is trimmed; both supplied is a conflict.
|
||||
#[trial]
|
||||
fn server_token_sources_and_validation() {
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
|
||||
use crate::control::{ControlRequest, REPLY_DEADLINE};
|
||||
use crate::protocol::write_reply;
|
||||
use crate::security::{
|
||||
AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream,
|
||||
AUTH_DEADLINE, AuthDeadlineStream, AuthStep, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ServerHandshake, configure_stream,
|
||||
read_bounded_line, repeat_auth_reply,
|
||||
};
|
||||
|
||||
@@ -63,8 +63,8 @@ pub fn start_with_deadline(
|
||||
Ok((rx, addr))
|
||||
}
|
||||
|
||||
/// Serve one connection: it must complete `auth` within `auth_deadline` of connecting, however
|
||||
/// much it sends meanwhile; after that only the idle timeout applies.
|
||||
/// Serve one connection: it must authenticate ([`ServerHandshake`]) within `auth_deadline` of
|
||||
/// connecting, however much it sends meanwhile; after that only the idle timeout applies.
|
||||
fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &WindowHost, auth_deadline: Duration) {
|
||||
if configure_stream(&stream).is_err() {
|
||||
return;
|
||||
@@ -73,6 +73,7 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &Win
|
||||
let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
|
||||
let mut out = stream;
|
||||
let mut line = String::new();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut authenticated = false;
|
||||
loop {
|
||||
match read_bounded_line(&mut reader, &mut line) {
|
||||
@@ -91,12 +92,12 @@ fn serve(stream: TcpStream, token: &str, tx: &Sender<ControlRequest>, host: &Win
|
||||
Ok(LineRead::Line) => {}
|
||||
}
|
||||
if !authenticated {
|
||||
let (reply, ok) = authentication_reply(&line, token);
|
||||
authenticated = ok;
|
||||
if ok && reader.get_mut().authenticated().is_err() {
|
||||
let (reply, step) = handshake.reply(&line, token);
|
||||
authenticated = step == AuthStep::Authenticated;
|
||||
if authenticated && reader.get_mut().authenticated().is_err() {
|
||||
break;
|
||||
}
|
||||
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || !authenticated {
|
||||
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || step == AuthStep::Rejected {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::Duration;
|
||||
|
||||
use craft_automation::client::ControlClient;
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply, expired_error, result_reply, timeout_error};
|
||||
use craft_automation::security::MAX_REQUEST_BYTES;
|
||||
use craft_automation::security::{CHALLENGE_METHOD, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
use craft_automation::server;
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
@@ -139,6 +139,33 @@ fn an_over_long_request_is_refused_and_closes_the_connection() {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
/// A connection that authenticates with the challenge handshake learns the server holds the token, never sends it,
|
||||
/// and then has its requests dispatched.
|
||||
#[trial]
|
||||
fn a_challenge_authenticated_connection_is_served() {
|
||||
let (rx, addr) = server::start(0, TOKEN.into(), host()).expect("started");
|
||||
let handler = std::thread::spawn(move || {
|
||||
let req = rx.recv_timeout(Duration::from_secs(5)).expect("a request");
|
||||
assert_eq!(req.method, "test.ping");
|
||||
req.reply.send(json!({"ok": true, "result": "pong"})).expect("replied");
|
||||
});
|
||||
let mut stream = TcpStream::connect(addr).expect("connected");
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout");
|
||||
let mut reader = BufReader::new(stream.try_clone().expect("cloned"));
|
||||
let client_nonce = generate_nonce().expect("a nonce");
|
||||
writeln!(stream, "{}", json!({"id": 1, "method": CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})).expect("written");
|
||||
let challenge = read_json(&mut reader).expect("a reply");
|
||||
let server_nonce = challenge["result"]["serverNonce"].as_str().expect("a server nonce").to_owned();
|
||||
let server_proof = challenge["result"]["serverProof"].as_str().expect("a server proof");
|
||||
assert!(proof_matches(TOKEN, ProofRole::Server, &client_nonce, &server_nonce, server_proof), "{challenge}");
|
||||
let proof = handshake_proof(TOKEN, ProofRole::Client, &client_nonce, &server_nonce).expect("a proof");
|
||||
writeln!(stream, "{}", json!({"id": 2, "method": "auth", "params": {"proof": proof}})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply")["result"]["authenticated"], true);
|
||||
writeln!(stream, "{}", json!({"id": 3, "method": "test.ping"})).expect("written");
|
||||
assert_eq!(read_json(&mut reader).expect("a reply"), json!({"id": 3, "ok": true, "result": "pong"}));
|
||||
handler.join().expect("handler ran");
|
||||
}
|
||||
|
||||
/// Sends one state of a states file and saves its capture as `<label>-<id>.png`: the client sample of
|
||||
/// docs/porting.md, section 6.4.
|
||||
fn capture_state(client: &mut ControlClient, doc: &Value, state: &Value, label: &str) -> Result<Value, String> {
|
||||
|
||||
Reference in New Issue
Block a user