mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-27 16:23:30 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7adf3ad56 |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408289866,
|
||||
"producer_workflow_id": 429719786,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: cadcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
|
||||
app-name: cadcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
Generated
-12
@@ -887,11 +887,9 @@ dependencies = [
|
||||
"craft-jsonrpc",
|
||||
"craft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
"hmac",
|
||||
"libc",
|
||||
"log",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tiny-skia",
|
||||
]
|
||||
|
||||
@@ -2067,7 +2065,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3233,15 +3230,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
|
||||
|
||||
- **Drawing files.** Opening a DXF, DWG or other file must not run code, write outside the paths the user chose, or crash the app. Panics are bugs too, but memory exhaustion or a decoder abort on a crafted file is the more serious case.
|
||||
- **AutoLISP in a drawing's folder.** A drawing must not run code that the user didn't choose to load.
|
||||
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability. The MCP bridge sends requests only to a server that proves it holds the token, so a program listening on the port in the app's place gets none.
|
||||
- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability.
|
||||
- **Temporary and autosave files.** Autosave files are unsaved drawings: another account must not be able to read them or redirect a write through them.
|
||||
- **Updates.** A release must not be replaceable by someone other than the project.
|
||||
|
||||
@@ -25,7 +25,7 @@ CADCraft treats these as untrusted, and a way past these defences is a vulnerabi
|
||||
These are known and being worked on, so they don't need a report:
|
||||
|
||||
- Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet.
|
||||
- A local process without the token can hold the control channel's 16 connections for up to 10 seconds at a time, with at most 64 KiB of request line each, so it can keep an agent from reaching the app while it keeps reconnecting. It can't make the app run anything.
|
||||
- A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit.
|
||||
- The DWG worker process has no memory limit of its own yet, so a crafted file can use a lot of memory before it stops. It ends that one open or save, not the app.
|
||||
- The web build has no autosave yet.
|
||||
|
||||
|
||||
@@ -60,19 +60,10 @@ fn no_connect_still_serves_headless() {
|
||||
fn connect_with_address_routes_to_that_endpoint() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback");
|
||||
let addr = listener.local_addr().expect("local addr").to_string();
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
// As the app does: write the session token, and prove holding it when the bridge says hello.
|
||||
let token = cadcraft_mcp::control_token::issue(port).expect("issue token");
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().expect("accept");
|
||||
let mut reader = BufReader::new(conn.try_clone().expect("clone"));
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).expect("read hello");
|
||||
let hello: Value = serde_json::from_str(&line).expect("json hello");
|
||||
assert_eq!(hello["method"], "hello", "the bridge says hello first: {line}");
|
||||
let proof = cadcraft_mcp::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap_or_default());
|
||||
writeln!(&conn, "{}", json!({"id": hello["id"], "ok": true, "result": {"proof": proof}})).expect("write proof");
|
||||
line.clear();
|
||||
reader.read_line(&mut line).expect("read request");
|
||||
let req: Value = serde_json::from_str(&line).expect("json request");
|
||||
let reply = json!({"id": req["id"], "ok": true, "result": {"fixture": "loopback"}});
|
||||
@@ -84,7 +75,6 @@ fn connect_with_address_routes_to_that_endpoint() {
|
||||
let out = mcp(&["--connect", &addr], &format!("{INIT}\n{call}\n"));
|
||||
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
||||
let req = server.join().expect("server thread");
|
||||
cadcraft_mcp::control_token::revoke(port);
|
||||
assert_eq!(req["method"], "ui.inspect");
|
||||
let r = replies(&out);
|
||||
let instructions = r.iter().find(|v| v["id"] == 1).and_then(|v| v["result"]["instructions"].as_str()).unwrap_or_default();
|
||||
|
||||
@@ -5,19 +5,15 @@
|
||||
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
|
||||
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
|
||||
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
|
||||
//! connection has carried the token), queued requests, how long a connection may stay open before
|
||||
//! it has shown the token, and how long a socket may sit idle or blocked on a write.
|
||||
//!
|
||||
//! A `hello` with a nonce is answered before the token check with a proof that the server holds
|
||||
//! the token ([`cadcraft_mcp::control_token::server_proof`]), so a client can tell the app from
|
||||
//! another program on the port before it sends anything else (#1925).
|
||||
//! connection has carried the token), queued requests, and how long a socket may sit idle or
|
||||
//! blocked on a write.
|
||||
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
||||
use std::io::{BufRead, BufReader, ErrorKind, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{Receiver, SyncSender, TrySendError, sync_channel};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
@@ -37,9 +33,6 @@ struct Limits {
|
||||
total_bytes: usize,
|
||||
/// Requests waiting for the app at once; more are answered `busy`.
|
||||
queue: usize,
|
||||
/// How long a connection may stay open before a request on it has carried the right token; it
|
||||
/// is closed then, so peers without the token can't hold the connection slots (#1925).
|
||||
preauth_time: Duration,
|
||||
/// How long a connection may go without sending a byte before it is closed.
|
||||
idle_timeout: Duration,
|
||||
/// How long a reply write may block before the connection is closed.
|
||||
@@ -58,7 +51,6 @@ impl Default for Limits {
|
||||
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
|
||||
total_bytes: 512 * 1024 * 1024,
|
||||
queue: 64,
|
||||
preauth_time: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_TIME,
|
||||
idle_timeout: Duration::from_secs(600),
|
||||
write_timeout: Duration::from_secs(30),
|
||||
reply_timeout: Duration::from_secs(60),
|
||||
@@ -346,47 +338,6 @@ fn is_http_request_line(text: &str) -> bool {
|
||||
|| text.rsplit_once(' ').is_some_and(|(_, version)| version.starts_with("HTTP/"))
|
||||
}
|
||||
|
||||
/// The method a client sends, before any request with the token, to have the server prove it holds
|
||||
/// the token.
|
||||
const HELLO: &str = "hello";
|
||||
|
||||
/// `hello`'s parameters.
|
||||
#[derive(serde::Deserialize)]
|
||||
struct HelloParams {
|
||||
nonce: String,
|
||||
}
|
||||
|
||||
/// The proof answering a `hello` with `params`, or the error that closes the connection.
|
||||
fn hello_proof(params: Option<&serde_json::value::RawValue>, token: &str) -> Result<String, String> {
|
||||
let nonce = params.and_then(|p| serde_json::from_str::<HelloParams>(p.get()).ok()).map(|p| p.nonce).unwrap_or_default();
|
||||
if !cadcraft_mcp::control_token::valid_nonce(&nonce) {
|
||||
let digits = &cadcraft_mcp::control_token::NONCE_DIGITS;
|
||||
return Err(format!("`hello` needs a `nonce` of {} to {} hexadecimal digits; closing the connection", digits.start(), digits.end()));
|
||||
}
|
||||
Ok(cadcraft_mcp::control_token::server_proof(token, &nonce))
|
||||
}
|
||||
|
||||
/// A connection's read side. Until `until` (the end of [`Limits::preauth_time`]), each read waits
|
||||
/// at most until then, however the bytes trickle in; after it, reads fail as timed out.
|
||||
struct Timed {
|
||||
stream: TcpStream,
|
||||
idle: Duration,
|
||||
until: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Read for Timed {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if let Some(until) = self.until {
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(ErrorKind::TimedOut, "no request with the control token in time"));
|
||||
}
|
||||
self.stream.set_read_timeout(Some(left.min(self.idle)))?;
|
||||
}
|
||||
self.stream.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI.
|
||||
/// Invalid credentials close the connection; queue and reply limits report whether a request ran.
|
||||
fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context, limits: Limits, token: &str, budget: Budget) {
|
||||
@@ -395,8 +346,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
}
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let mut out = stream;
|
||||
let until = Instant::now().checked_add(limits.preauth_time);
|
||||
let mut reader = BufReader::new(Timed { stream: read, idle: limits.idle_timeout, until });
|
||||
let mut reader = BufReader::new(read);
|
||||
let mut buf = Vec::new();
|
||||
let mut held = Held::new(budget);
|
||||
// The token is checked only after the whole line is read, so until a request here has carried
|
||||
@@ -418,17 +368,6 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
Ok(true) => match parse_line(&buf) {
|
||||
Line::Blank => continue,
|
||||
Line::Reject(e) => e,
|
||||
// Answered without the token and without authenticating the connection: the proof
|
||||
// shows the token is known here, not that the peer knows it.
|
||||
Line::Request { id, method, params, .. } if method == HELLO => match hello_proof(params, token) {
|
||||
Ok(proof) => {
|
||||
if writeln!(out, "{}", json!({"id": id, "ok": true, "result": {"proof": proof}})).is_err() {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Line::Request { id, method, params, token: given } => {
|
||||
// Authenticate the peer before dispatching: loopback TCP does not identify the
|
||||
// OS user, so only a client holding the owner-only session token may drive the
|
||||
@@ -441,14 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
|
||||
let _ = writeln!(out, "{r}");
|
||||
break;
|
||||
}
|
||||
if !authenticated {
|
||||
authenticated = true;
|
||||
let timed = reader.get_mut();
|
||||
timed.until = None;
|
||||
if timed.stream.set_read_timeout(Some(limits.idle_timeout)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
authenticated = true;
|
||||
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
|
||||
// error, not a request run with defaults.
|
||||
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
|
||||
@@ -812,87 +744,6 @@ mod tests {
|
||||
assert_eq!((v["ok"].as_bool(), v["method"].as_str()), (Some(true), Some("ping")), "{line}");
|
||||
}
|
||||
|
||||
/// A `hello` line with `nonce` and no token.
|
||||
fn hello_line(nonce: &str) -> String {
|
||||
json!({"id": "h", "method": "hello", "params": {"nonce": nonce}}).to_string() + "\n"
|
||||
}
|
||||
|
||||
/// A `hello` is answered with a proof of the token before any token has been shown, and the
|
||||
/// connection stays open for requests; the `hello` itself authenticates nothing.
|
||||
#[test]
|
||||
fn a_hello_is_answered_with_a_proof_of_the_token() {
|
||||
let addr = serve_echo_with(preauth());
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut r = BufReader::new(c.try_clone().unwrap());
|
||||
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
|
||||
c.write_all(hello_line(&nonce).as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(v["id"], "h", "{line}");
|
||||
let proof = v["result"]["proof"].as_str().unwrap();
|
||||
assert!(cadcraft_mcp::control_token::verify_server_proof(TEST_TOKEN, &nonce, proof), "{line}");
|
||||
assert!(!line.contains(TEST_TOKEN), "the token itself is never sent");
|
||||
// Still unauthenticated: a line past the preauth bound is refused…
|
||||
let refused = exchange(addr, format!("{}{}", hello_line(&nonce), long_req_line(1, 2000)).as_bytes());
|
||||
assert_eq!(refused.len(), 2, "{refused:?}");
|
||||
assert!(refused[1]["error"].as_str().unwrap().contains("longer than 1000 bytes"), "{refused:?}");
|
||||
// …and a request with the token after the hello goes through on the same connection.
|
||||
c.write_all(req_line(2, "ping").as_bytes()).unwrap();
|
||||
line.clear();
|
||||
r.read_line(&mut line).unwrap();
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!((v["id"].as_i64(), v["method"].as_str()), (Some(2), Some("ping")), "{line}");
|
||||
}
|
||||
|
||||
/// A `hello` without a usable nonce gets an error and the connection is closed.
|
||||
#[test]
|
||||
fn a_hello_without_a_usable_nonce_closes_the_connection() {
|
||||
let addr = serve_echo();
|
||||
for bad in [r#"{"method":"hello"}"#.to_string(), hello_line("abc").trim_end().to_string(), hello_line(&"z".repeat(64)).trim_end().to_string()]
|
||||
{
|
||||
let replies = exchange(addr, format!("{bad}\n{}", req_line(1, "ping")).as_bytes());
|
||||
assert_eq!(replies.len(), 1, "{bad}: {replies:?}");
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("`nonce`"), "{bad}: {replies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection that doesn't show the token within `preauth_time` is closed even while it keeps
|
||||
/// sending (a byte at a time, or `hello`s), so peers without the token can't hold the slots;
|
||||
/// one that has shown it stays open past that time.
|
||||
#[test]
|
||||
fn a_connection_that_never_shows_the_token_is_closed_in_time() {
|
||||
let limits = Limits { preauth_time: Duration::from_millis(400), idle_timeout: Duration::from_secs(5), ..short() };
|
||||
let addr = serve_echo_with(limits);
|
||||
let nonce = cadcraft_mcp::control_token::new_nonce().unwrap();
|
||||
for trickle in [b"{".to_vec(), hello_line(&nonce).into_bytes()] {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let reader = std::thread::spawn({
|
||||
let c = c.try_clone().unwrap();
|
||||
move || BufReader::new(c).lines().count()
|
||||
});
|
||||
let t = std::time::Instant::now();
|
||||
while c.write_all(&trickle).is_ok() && t.elapsed() < Duration::from_secs(4) && !reader.is_finished() {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(reader.is_finished() && t.elapsed() < Duration::from_secs(3), "still open after {:?}", t.elapsed());
|
||||
let _ = reader.join();
|
||||
}
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut r = BufReader::new(c.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
c.write_all(req_line(1, "ping").as_bytes()).unwrap();
|
||||
r.read_line(&mut line).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
c.write_all(req_line(2, "pong").as_bytes()).unwrap();
|
||||
line.clear();
|
||||
r.read_line(&mut line).unwrap();
|
||||
assert!(line.contains("pong"), "an authenticated connection outlives the preauth time: {line:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let addr = serve_echo();
|
||||
|
||||
@@ -19,9 +19,6 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Secure randomness for the per-session control token (MIT OR Apache-2.0).
|
||||
getrandom = "0.4"
|
||||
# The control server's proof that it holds the session token (MIT OR Apache-2.0).
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
# Reads the pixels of rendered PNGs in the tests.
|
||||
|
||||
+33
-215
@@ -3,7 +3,7 @@
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::file_access::{self, AutomationRoots};
|
||||
@@ -35,9 +35,6 @@ pub struct Remote {
|
||||
authed: bool,
|
||||
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
|
||||
max_reply: usize,
|
||||
/// When the current connection was opened: the server closes one that hasn't shown the token
|
||||
/// within `MAX_UNAUTHENTICATED_TIME`.
|
||||
opened: Option<Instant>,
|
||||
}
|
||||
|
||||
/// The port component of a `HOST:PORT` address, for locating the token file.
|
||||
@@ -53,13 +50,6 @@ const LAUNCH_WAIT: Duration = Duration::from_secs(30);
|
||||
/// can't make the client allocate without bound (#1925).
|
||||
const MAX_REPLY_LINE: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Longest reply to a `hello` the client reads: it comes before the peer has proved anything.
|
||||
const MAX_HELLO_REPLY: usize = 4096;
|
||||
|
||||
/// How long before the server's `MAX_UNAUTHENTICATED_TIME` runs out an unauthenticated connection
|
||||
/// is replaced instead of used, so a request is never written to a connection about to close.
|
||||
const PREAUTH_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Read one `\n`-terminated reply of at most `max` bytes (newline excluded). `Ok(0)` is end of
|
||||
/// stream; a longer line is an `InvalidData` error and the rest of it stays unread.
|
||||
fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) -> std::io::Result<usize> {
|
||||
@@ -77,7 +67,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
|
||||
impl Remote {
|
||||
/// Connect to a running control server; its session token is read lazily when the first request is sent.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let mut r = Self::lazy(addr, false);
|
||||
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -85,11 +75,12 @@ impl Remote {
|
||||
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
|
||||
/// opens the app with that control port first (macOS) and waits for it.
|
||||
pub fn lazy(addr: &str, launch: bool) -> Self {
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, opened: None }
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
|
||||
}
|
||||
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file
|
||||
/// (`None` when there is none; then nothing is sent, see [`Remote::prove_server`]).
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file. A
|
||||
/// missing file is not fatal here: the request is sent without a token and the server replies
|
||||
/// with an authentication error the user can act on.
|
||||
///
|
||||
/// The desktop app listens only on `127.0.0.1:PORT`, so the token goes only to that exact
|
||||
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
|
||||
@@ -143,65 +134,15 @@ impl Remote {
|
||||
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
|
||||
let read = s.try_clone()?;
|
||||
self.conn = Some((BufReader::new(read), s));
|
||||
self.opened = Some(Instant::now());
|
||||
// A peer that can't prove it is the app gets nothing; another address may be.
|
||||
match self.prove_server() {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => {
|
||||
self.conn = None;
|
||||
last = e;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = e,
|
||||
}
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
/// Have the peer just connected to prove it holds this port's session token before anything
|
||||
/// else is sent to it: any program that listens on the port first would otherwise receive the
|
||||
/// requests and could answer them (#1925). The `hello` carries a fresh nonce and no token; the
|
||||
/// app answers with [`crate::control_token::server_proof`]. A proof made with another token is
|
||||
/// checked once more against the token file, which a restarted app has rewritten.
|
||||
fn prove_server(&mut self) -> std::io::Result<()> {
|
||||
let refused = |addr: &str, why: &str| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!(
|
||||
"the program listening at {addr} {why}, so nothing was sent to it; is CADCraft running with its control port under this account?"
|
||||
),
|
||||
)
|
||||
};
|
||||
if self.token().is_none() {
|
||||
return Err(refused(&self.addr, "is not a CADCraft session whose control token this account can read"));
|
||||
}
|
||||
let nonce = crate::control_token::new_nonce()?;
|
||||
let hello = json!({"method": "hello", "params": {"nonce": nonce}}).to_string();
|
||||
let reply = self.roundtrip_within(&hello, MAX_HELLO_REPLY).map_err(|(e, _)| e)?;
|
||||
let reply = serde_json::from_str::<Value>(&reply).unwrap_or_default();
|
||||
let Some(proof) = reply.pointer("/result/proof").and_then(Value::as_str) else {
|
||||
// The app refuses a connection past its limit before reading anything: say why.
|
||||
return Err(match reply.get("error").and_then(Value::as_str) {
|
||||
Some(e) => std::io::Error::other(e.to_string()),
|
||||
None => refused(&self.addr, "did not answer as CADCraft's control server does"),
|
||||
});
|
||||
};
|
||||
let holds = |token: Option<&str>| token.is_some_and(|t| crate::control_token::verify_server_proof(t, &nonce, proof));
|
||||
if holds(self.token.as_deref()) {
|
||||
return Ok(());
|
||||
}
|
||||
self.token = None;
|
||||
if holds(self.token()) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(refused(&self.addr, "could not prove it holds this account's control token"))
|
||||
}
|
||||
/// On failure the flag says whether the request may already have reached the server.
|
||||
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
|
||||
self.roundtrip_within(line, self.max_reply)
|
||||
}
|
||||
/// [`Remote::roundtrip`], reading a reply of at most `max` bytes.
|
||||
fn roundtrip_within(&mut self, line: &str, max: usize) -> Result<String, (std::io::Error, bool)> {
|
||||
if self.conn.is_none() {
|
||||
self.reach().map_err(|e| (e, false))?;
|
||||
}
|
||||
@@ -214,7 +155,7 @@ impl Remote {
|
||||
return Err((e, true));
|
||||
}
|
||||
let mut reply = String::new();
|
||||
match read_reply_line(reader, &mut reply, max) {
|
||||
match read_reply_line(reader, &mut reply, self.max_reply) {
|
||||
Ok(0) => {
|
||||
self.conn = None;
|
||||
Err((std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"), true))
|
||||
@@ -284,11 +225,6 @@ impl Remote {
|
||||
/// passed the check (#1925), so a long request on a new connection goes after a `ping` with the
|
||||
/// token; when the `ping` is refused its reply comes back instead and the request isn't sent.
|
||||
fn sign_and_send(&mut self, req: &mut Value) -> Result<String, (std::io::Error, bool)> {
|
||||
// The app closes a connection that hasn't shown the token in time; a request written to it
|
||||
// then would be lost with its fate unknown, so such a connection is replaced first.
|
||||
if !self.authed && self.opened.is_some_and(|t| t.elapsed() + PREAUTH_MARGIN >= crate::control_token::MAX_UNAUTHENTICATED_TIME) {
|
||||
self.conn = None;
|
||||
}
|
||||
if self.conn.is_none() {
|
||||
self.reach().map_err(|e| (e, false))?;
|
||||
}
|
||||
@@ -592,40 +528,15 @@ mod tests {
|
||||
use std::net::TcpListener;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The app's reply to `req` when it is a `hello`: a proof made with the token in this port's
|
||||
/// file now (the app's own token).
|
||||
fn hello_reply(req: &Value, port: u16) -> Option<Value> {
|
||||
(req["method"] == "hello").then(|| {
|
||||
let token = crate::control_token::read(port).unwrap_or_default();
|
||||
let proof = crate::control_token::server_proof(&token, req["params"]["nonce"].as_str().unwrap_or_default());
|
||||
json!({"ok": true, "result": {"proof": proof}})
|
||||
})
|
||||
}
|
||||
|
||||
/// Answer the `hello` a client opens a connection with, as the app does; `false` when the
|
||||
/// client sent nothing.
|
||||
fn answer_hello(reader: &mut impl BufRead, out: &mut impl Write, port: u16) -> bool {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return false;
|
||||
}
|
||||
let reply = hello_reply(&serde_json::from_str(&line).unwrap(), port).expect("a hello first");
|
||||
writeln!(out, "{reply}").is_ok()
|
||||
}
|
||||
|
||||
/// A peer squatting on the control port can't make the client buffer an endless reply line (#1925).
|
||||
#[test]
|
||||
fn an_overlong_reply_is_refused_without_buffering_it() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
// No newline: the reply never ends. A bounded client gives up after the limit.
|
||||
let _ = conn.write_all(&[b'x'; 4096]);
|
||||
let _ = conn.flush();
|
||||
@@ -638,7 +549,6 @@ mod tests {
|
||||
assert!(err.to_string().contains("longer than 100 bytes"), "{err}");
|
||||
assert!(remote.conn.is_none());
|
||||
server.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -653,17 +563,13 @@ mod tests {
|
||||
#[test]
|
||||
fn lost_reply_to_a_mutation_is_not_resent() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut requests = 0;
|
||||
listener.set_nonblocking(false).unwrap();
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
BufReader::new(conn).read_line(&mut line).unwrap();
|
||||
requests += 1;
|
||||
// Anything arriving on a second connection would be a resend.
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
@@ -676,7 +582,6 @@ mod tests {
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.contains("may or may not have been applied"), "{err}");
|
||||
assert_eq!(server.join().unwrap(), 1);
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none());
|
||||
assert!(remote.conn.is_none());
|
||||
}
|
||||
@@ -686,22 +591,18 @@ mod tests {
|
||||
fn timeout_reply_says_whether_a_retry_is_safe() {
|
||||
for (state, want) in [("not-run", "safe to send again"), ("may-have-run", "Inspect the drawing first")] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut out, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(out.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut out, port));
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let mut out = conn;
|
||||
writeln!(out, "{}", json!({"id": 1, "ok": false, "error": "timeout", "state": state})).unwrap();
|
||||
});
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.starts_with("timeout") && err.contains(want), "{err}");
|
||||
server.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
}
|
||||
/// Retrying a read after a lost reply reloads the replacement server session token.
|
||||
@@ -711,21 +612,17 @@ mod tests {
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let old = crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
|
||||
let mut reader = BufReader::new(conn);
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let first: Value = serde_json::from_str(&line).unwrap();
|
||||
assert!(first["token"].as_str() == Some(old.as_str()));
|
||||
let fresh = crate::control_token::issue(addr.port()).unwrap();
|
||||
drop((reader, conn));
|
||||
drop(reader);
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
line.clear();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
// The new session proves itself with its new token, which the client reads again.
|
||||
assert!(answer_hello(&mut reader, &mut conn, addr.port()));
|
||||
reader.read_line(&mut line).unwrap();
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let retry: Value = serde_json::from_str(&line).unwrap();
|
||||
assert!(retry["token"].as_str() == Some(fresh.as_str()));
|
||||
writeln!(conn, "{}", json!({"ok": true, "result": "pong"})).unwrap();
|
||||
@@ -739,7 +636,6 @@ mod tests {
|
||||
/// and the connection number and says what to send back; the server closes after each reply.
|
||||
/// Returns how many requests arrived, waiting a short while for each next connection.
|
||||
fn fake_app(listener: TcpListener, reply: impl Fn(&Value, usize) -> Value + Send + 'static) -> std::thread::JoinHandle<usize> {
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let mut seen = 0;
|
||||
@@ -752,13 +648,11 @@ mod tests {
|
||||
Err(_) => break None,
|
||||
}
|
||||
};
|
||||
let Some(mut out) = conn else { return seen };
|
||||
out.set_nonblocking(false).unwrap();
|
||||
let mut reader = BufReader::new(out.try_clone().unwrap());
|
||||
let Some(conn) = conn else { return seen };
|
||||
conn.set_nonblocking(false).unwrap();
|
||||
let mut line = String::new();
|
||||
if !answer_hello(&mut reader, &mut out, port) || reader.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
continue;
|
||||
}
|
||||
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let mut out = conn;
|
||||
writeln!(out, "{}", reply(&serde_json::from_str(&line).unwrap(), seen)).unwrap();
|
||||
seen += 1;
|
||||
}
|
||||
@@ -766,84 +660,21 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A listener on another loopback address with the desktop's port (here `::1`) never receives
|
||||
/// the desktop's token, nor any request: the client can't check it is the app.
|
||||
/// the desktop's token.
|
||||
#[test]
|
||||
fn nothing_is_sent_to_another_loopback_listener() {
|
||||
fn token_is_not_sent_to_another_loopback_listener() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0") else { return };
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut got = Vec::new();
|
||||
BufReader::new(conn).read_to_end(&mut got).unwrap();
|
||||
got
|
||||
let server = fake_app(listener, move |req, _| {
|
||||
assert!(req.get("token").is_none(), "token leaked to {addr}");
|
||||
json!({"ok": true, "result": "x"})
|
||||
});
|
||||
let mut remote = Remote::lazy(&addr.to_string(), false);
|
||||
let got = remote.call("ping", json!({}));
|
||||
drop(remote);
|
||||
crate::control_token::revoke(addr.port());
|
||||
assert!(got.as_ref().is_err_and(|e| e.contains("nothing was sent")), "{got:?}");
|
||||
assert!(server.join().unwrap().is_empty(), "the listener received bytes");
|
||||
}
|
||||
|
||||
/// A program on the app's port that answers the `hello` without the token's proof (here it
|
||||
/// echoes the nonce back, or another session's proof) gets no request, whatever it replies.
|
||||
#[test]
|
||||
fn a_peer_that_cannot_prove_the_token_gets_no_request() {
|
||||
for forged in ["echo", "other session", "error"] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut lines = Vec::new();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let start = Instant::now();
|
||||
while start.elapsed() < Duration::from_millis(500) {
|
||||
let Ok((mut out, _)) = listener.accept() else {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
continue;
|
||||
};
|
||||
out.set_nonblocking(false).unwrap();
|
||||
for line in BufReader::new(out.try_clone().unwrap()).lines() {
|
||||
let req: Value = serde_json::from_str(&line.unwrap()).unwrap();
|
||||
let nonce = req["params"]["nonce"].as_str().unwrap_or_default().to_string();
|
||||
lines.push(req["method"].as_str().unwrap_or_default().to_string());
|
||||
let reply = match forged {
|
||||
"echo" => json!({"ok": true, "result": {"proof": nonce}}),
|
||||
"other session" => json!({"ok": true, "result": {"proof": crate::control_token::server_proof("another", &nonce)}}),
|
||||
_ => json!({"ok": false, "error": "pretend error"}),
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
}
|
||||
}
|
||||
lines
|
||||
});
|
||||
let mut remote = Remote::lazy(&addr.to_string(), false);
|
||||
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
|
||||
drop(remote);
|
||||
let lines = server.join().unwrap();
|
||||
crate::control_token::revoke(addr.port());
|
||||
assert!(got.is_err(), "{forged}: {got:?}");
|
||||
assert!(lines.iter().all(|m| m == "hello"), "{forged}: {lines:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An unauthenticated connection about to reach the app's `MAX_UNAUTHENTICATED_TIME` is
|
||||
/// replaced before a request is written to it, so the request isn't lost when the app closes it.
|
||||
#[test]
|
||||
fn an_unauthenticated_connection_near_the_app_deadline_is_replaced() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
crate::control_token::issue(addr.port()).unwrap();
|
||||
let server = fake_app(listener, |_, n| json!({"ok": true, "result": n}));
|
||||
let mut remote = Remote::connect(&addr.to_string()).unwrap();
|
||||
remote.opened = Some(Instant::now() - crate::control_token::MAX_UNAUTHENTICATED_TIME);
|
||||
let got = remote.call("engine.execute", json!({"command": "circle", "params": {}}));
|
||||
drop(remote);
|
||||
let requests = server.join().unwrap();
|
||||
crate::control_token::revoke(addr.port());
|
||||
// The first connection only saw the `hello`; the request went on the second.
|
||||
assert_eq!((got, requests), (Ok(json!(0)), 1));
|
||||
assert_eq!(got, Ok(json!("x")));
|
||||
assert_eq!(server.join().unwrap(), 1);
|
||||
}
|
||||
|
||||
/// `--launch` reads the token before it opens the app, so the first request carries the token
|
||||
@@ -883,9 +714,7 @@ mod tests {
|
||||
fn unauthorized_is_resent_at_most_once_and_only_when_not_run() {
|
||||
for (state, connections) in [(Some("not-run"), 2), (Some("may-have-run"), 1), (None, 1)] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let server = fake_app(listener, move |_, _| {
|
||||
let mut r = json!({"ok": false, "error": "unauthorized: missing or invalid control token"});
|
||||
if let (Some(o), Some(state)) = (r.as_object_mut(), state) {
|
||||
@@ -897,7 +726,6 @@ mod tests {
|
||||
let err = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(err.starts_with("unauthorized"), "{err}");
|
||||
assert_eq!(server.join().unwrap(), connections, "{state:?}");
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none() && remote.conn.is_none());
|
||||
}
|
||||
}
|
||||
@@ -905,25 +733,20 @@ mod tests {
|
||||
#[test]
|
||||
fn failed_mutation_write_is_not_resent() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
crate::control_token::issue(port).unwrap();
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(conn.try_clone().unwrap());
|
||||
assert!(answer_hello(&mut reader, &mut conn, port));
|
||||
let (conn, _) = listener.accept().unwrap();
|
||||
let mut line = String::new();
|
||||
assert_eq!(reader.read_line(&mut line).unwrap(), 0);
|
||||
assert_eq!(BufReader::new(conn).read_line(&mut line).unwrap(), 0);
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
listener.accept().is_ok()
|
||||
});
|
||||
let mut remote = Remote::connect(&addr).unwrap();
|
||||
remote.conn.as_ref().unwrap().1.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
let error = remote.call("engine.execute", json!({"command": "circle", "params": {}})).unwrap_err();
|
||||
assert!(error.contains("may or may not have been applied"));
|
||||
assert!(!server.join().unwrap(), "a failed mutation write was retried");
|
||||
crate::control_token::revoke(port);
|
||||
assert!(remote.token.is_none());
|
||||
}
|
||||
|
||||
@@ -938,7 +761,6 @@ mod tests {
|
||||
listener: TcpListener,
|
||||
mut valid: impl FnMut(usize) -> Result<String, Value> + Send + 'static,
|
||||
) -> std::thread::JoinHandle<Vec<(usize, String, usize)>> {
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let mut seen = Vec::new();
|
||||
@@ -961,10 +783,6 @@ mod tests {
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
let len = line.trim_end().len();
|
||||
line.clear();
|
||||
if let Some(reply) = hello_reply(&req, port) {
|
||||
writeln!(out, "{reply}").unwrap();
|
||||
continue;
|
||||
}
|
||||
seen.push((conn_no, req["method"].as_str().unwrap_or_default().to_string(), len));
|
||||
let reply = if !authed && len > crate::control_token::MAX_UNAUTHENTICATED_LINE {
|
||||
json!({"ok": false, "error": "request line too long before a request with the control token"})
|
||||
|
||||
@@ -11,9 +11,6 @@
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
|
||||
/// Length of the token in bytes (256 bits), rendered as lowercase hex.
|
||||
const TOKEN_BYTES: usize = 32;
|
||||
|
||||
@@ -24,68 +21,6 @@ const TOKEN_BYTES: usize = 32;
|
||||
/// with the token has been answered on the same connection.
|
||||
pub const MAX_UNAUTHENTICATED_LINE: usize = 64 * 1024;
|
||||
|
||||
/// How long a connection may stay open before a request on it has carried the right token; the
|
||||
/// server closes it then, so peers without the token can't hold every connection slot until the
|
||||
/// idle timeout (#1925). A client that keeps an unauthenticated connection this long opens a new one.
|
||||
pub const MAX_UNAUTHENTICATED_TIME: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Shortest and longest `hello` nonce, in hexadecimal digits.
|
||||
pub const NONCE_DIGITS: std::ops::RangeInclusive<usize> = 32..=128;
|
||||
|
||||
/// What the server's proof is computed over besides the nonce, so a proof is never a valid token or
|
||||
/// a MAC made for anything else.
|
||||
const PROOF_LABEL: &[u8] = b"cadcraft control server proof v1\n";
|
||||
|
||||
/// A fresh nonce for a `hello` (256 bits of operating-system randomness, hex).
|
||||
pub fn new_nonce() -> io::Result<String> {
|
||||
random_hex()
|
||||
}
|
||||
|
||||
/// Whether `nonce` is one the server answers: hexadecimal digits, [`NONCE_DIGITS`] long.
|
||||
pub fn valid_nonce(nonce: &str) -> bool {
|
||||
NONCE_DIGITS.contains(&nonce.len()) && nonce.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// HMAC-SHA-256 of the proof label and `nonce`, keyed with the session token (HMAC takes keys of
|
||||
/// any length, so it is always `Some`).
|
||||
fn proof_mac(token: &str, nonce: &str) -> Option<Hmac<Sha256>> {
|
||||
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(token.as_bytes()).ok()?;
|
||||
mac.update(PROOF_LABEL);
|
||||
mac.update(nonce.as_bytes());
|
||||
Some(mac)
|
||||
}
|
||||
|
||||
/// The server's answer to a `hello` carrying `nonce`: it shows the server holds the session token
|
||||
/// without sending the token, so a client can tell the app from another program listening on its
|
||||
/// port before it sends a request (#1925).
|
||||
pub fn server_proof(token: &str, nonce: &str) -> String {
|
||||
proof_mac(token, nonce).map(|mac| hex(&mac.finalize().into_bytes())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether `proof` is [`server_proof`] for `token` and `nonce`, compared in constant time.
|
||||
pub fn verify_server_proof(token: &str, nonce: &str, proof: &str) -> bool {
|
||||
let (Some(bytes), Some(mac)) = (unhex(proof), proof_mac(token, nonce)) else { return false };
|
||||
mac.verify_slice(&bytes).is_ok()
|
||||
}
|
||||
|
||||
/// Lowercase hexadecimal.
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(s, "{b:02x}");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The bytes of an even-length hexadecimal string, or `None`.
|
||||
fn unhex(text: &str) -> Option<Vec<u8>> {
|
||||
if !text.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
text.as_bytes().chunks(2).map(|pair| std::str::from_utf8(pair).ok().and_then(|p| u8::from_str_radix(p, 16).ok())).collect()
|
||||
}
|
||||
|
||||
/// The file holding the control token for `port`, inside a per-user private directory.
|
||||
///
|
||||
/// On Unix the runtime dir (`XDG_RUNTIME_DIR`, already `0700` and per-user) is preferred, else the
|
||||
@@ -205,7 +140,12 @@ pub fn matches(expected: &str, given: &str) -> bool {
|
||||
fn random_hex() -> io::Result<String> {
|
||||
let mut bytes = [0u8; TOKEN_BYTES];
|
||||
getrandom::fill(&mut bytes).map_err(|e| io::Error::other(format!("no secure randomness: {e}")))?;
|
||||
Ok(hex(&bytes))
|
||||
let mut s = String::with_capacity(TOKEN_BYTES * 2);
|
||||
for b in bytes {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(s, "{b:02x}");
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// Replace a stale token with an exclusively created file using Unix mode `0600`, then flush its bytes.
|
||||
@@ -235,32 +175,6 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A proof checks out only for the token and nonce it was made with, and is neither the token
|
||||
/// nor readable as one.
|
||||
#[test]
|
||||
fn a_server_proof_holds_only_for_its_token_and_nonce() {
|
||||
let (token, nonce) = (random_hex().unwrap(), new_nonce().unwrap());
|
||||
let proof = server_proof(&token, &nonce);
|
||||
assert!(verify_server_proof(&token, &nonce, &proof));
|
||||
assert!(!verify_server_proof(&random_hex().unwrap(), &nonce, &proof), "another token");
|
||||
assert!(!verify_server_proof(&token, &new_nonce().unwrap(), &proof), "another nonce");
|
||||
assert!(!matches(&token, &proof));
|
||||
let mut flipped = proof.clone().into_bytes();
|
||||
flipped[0] = if flipped[0] == b'0' { b'1' } else { b'0' };
|
||||
for bad in [String::from_utf8(flipped).unwrap(), proof[1..].to_string(), format!("{}zz", &proof[2..]), String::new()] {
|
||||
assert!(!verify_server_proof(&token, &nonce, &bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonces_are_hex_of_a_bounded_length() {
|
||||
let nonce = new_nonce().unwrap();
|
||||
assert!(valid_nonce(&nonce));
|
||||
for bad in ["", "abc", &"0".repeat(*NONCE_DIGITS.end() + 1), &format!("{}g", &nonce[1..])] {
|
||||
assert!(!valid_nonce(bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An issued token has the expected size, can be read back, and disappears after revocation.
|
||||
#[test]
|
||||
fn issue_then_read_round_trips() {
|
||||
|
||||
+2
-11
@@ -261,28 +261,19 @@ fn a_lazy_bridge_starts_without_the_app_and_says_how_to_open_it() {
|
||||
let msg = r["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(msg.contains("not answering") && msg.contains("--control"), "{msg}");
|
||||
|
||||
// Once the app listens (and has written its token), the next call reaches it.
|
||||
// Once the app listens, the next call reaches it.
|
||||
let listener = std::net::TcpListener::bind(&addr).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let token = crate::control_token::issue(port).unwrap();
|
||||
let app = std::thread::spawn(move || {
|
||||
use std::io::{BufRead, Write};
|
||||
let (sock, _) = listener.accept().unwrap();
|
||||
let mut reader = std::io::BufReader::new(sock.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
let hello = serde_json::from_str::<Value>(&line).unwrap();
|
||||
let proof = crate::control_token::server_proof(&token, hello["params"]["nonce"].as_str().unwrap());
|
||||
writeln!(&sock, "{}", json!({"ok": true, "result": {"proof": proof}})).unwrap();
|
||||
line.clear();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
std::io::BufReader::new(sock.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
let id = serde_json::from_str::<Value>(&line).unwrap()["id"].clone();
|
||||
writeln!(&sock, "{}", json!({"id": id, "ok": true, "result": {"prompt": "Command:"}})).unwrap();
|
||||
});
|
||||
let r = call(&mut s, 4, "tools/call", json!({"name": "command_line", "arguments": {"text": ""}}));
|
||||
assert_ne!(r["result"]["isError"], json!(true), "{r}");
|
||||
app.join().unwrap();
|
||||
crate::control_token::revoke(port);
|
||||
}
|
||||
|
||||
/// The pixels of a `render` tool result.
|
||||
|
||||
@@ -23,22 +23,6 @@ reply and the connection is closed. To send a longer request (a script, a drawin
|
||||
new connection, first send a short one with the token, such as `ping`, and wait for its reply.
|
||||
The MCP bridge does this too.
|
||||
|
||||
Any program can listen on the port while the app isn't, so a client can first ask the server to
|
||||
prove it is the app, before it sends anything else on the connection:
|
||||
|
||||
```json
|
||||
{"id": "h", "method": "hello", "params": {"nonce": "<32 to 128 hexadecimal digits>"}}
|
||||
{"id": "h", "ok": true, "result": {"proof": "<64 hexadecimal digits>"}}
|
||||
```
|
||||
|
||||
`hello` needs no token and doesn't count as showing it. The proof is HMAC-SHA-256 keyed with the
|
||||
session token, over the bytes `cadcraft control server proof v1` and a newline followed by the
|
||||
nonce, in lowercase hexadecimal. A client that computes the same value from the token file knows the
|
||||
server holds the token; use a fresh random nonce each time. A `hello` without a valid nonce gets an
|
||||
error and the connection is closed. The MCP bridge sends a `hello` on every new connection and
|
||||
sends nothing more to a server that can't prove it holds the token, or when it can't read a token
|
||||
for the port.
|
||||
|
||||
Errors come back as `{"id": …, "ok": false, "error": "message"}`. An unknown method's error points
|
||||
to `control.methods`, which lists the methods the server answers.
|
||||
|
||||
@@ -48,8 +32,7 @@ after it runs. Blank lines are skipped.
|
||||
|
||||
The server bounds what a client can hold: 16 connections at once (more get an error line and are
|
||||
closed), 256 MiB per request line (64 KiB until the connection has shown the token; longer closes
|
||||
the connection), 10 seconds from connecting to the first request with the token (then the
|
||||
connection is closed, whatever it has sent), 64 queued requests (more are
|
||||
the connection), 64 queued requests (more are
|
||||
answered `{"ok": false, "error": "busy: …", "state": "not-run"}`), and 10 minutes idle or 30 seconds
|
||||
per blocked reply write before the socket is closed.
|
||||
|
||||
|
||||
@@ -33,11 +33,12 @@ OUTPUT="$DIST/cadcraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/CADCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/CADCraft"
|
||||
cp "$ROOT/assets/app-icon/cadcraft-nightly.icns" "$APP/Contents/Resources/cadcraft-nightly.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# Launcher admits notices under Resources/docs, not beside the icon.
|
||||
nightly_copy_notices "$APP/Contents/Resources/docs"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
|
||||
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"cadcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "CADCraft Nightly.app"
|
||||
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
|
||||
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
@@ -183,6 +185,50 @@ class Fixture:
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def package(self, font_licences):
|
||||
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
|
||||
source = HERE.parents[1]
|
||||
checkout = self.root / "source"
|
||||
checkout.mkdir()
|
||||
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
|
||||
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
|
||||
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
|
||||
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
|
||||
"assets/app-icon/cadcraft-nightly.icns"):
|
||||
target = checkout / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(source / relative, target)
|
||||
env = self.env(**dict.fromkeys(SECRETS))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
|
||||
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
|
||||
|
||||
git("init", "-q")
|
||||
git("add", "--", ".")
|
||||
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
|
||||
commit = git("rev-parse", "HEAD").strip()
|
||||
version = VERSION[:-12] + commit[:12]
|
||||
# Generated licence text exercises the copier without depending on a font checkout.
|
||||
fonts = self.root / "craft-fonts"
|
||||
for family, data in font_licences.items():
|
||||
licence = fonts / "fonts" / family / "OFL.txt"
|
||||
licence.parent.mkdir(parents=True)
|
||||
licence.write_bytes(data)
|
||||
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
|
||||
(self.bin / "cargo").write_text(
|
||||
'#!/bin/sh\nset -eu\n'
|
||||
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/cadcraft"\n'
|
||||
'mkdir -p "$(dirname "$gui")"\n'
|
||||
"printf \"#!/bin/sh\\necho 'CADCraft %s (nightly-v1)'\\n\" \"$CADCRAFT_VERSION\" >\"$gui\"\n",
|
||||
)
|
||||
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
|
||||
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
|
||||
CADCRAFT_BUILD_CHANNEL="nightly-v1", CADCRAFT_VERSION=version,
|
||||
CADCRAFT_BUILD_SHA=commit, CADCRAFT_BUILD_DATE="2026-11-23")
|
||||
assert result.returncode == 0, result.stdout
|
||||
return self.dist / ASSET.replace(VERSION, version)
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
@@ -410,6 +456,40 @@ class Verify(unittest.TestCase):
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
|
||||
f = Fixture(self)
|
||||
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
|
||||
archive = f.package(fonts)
|
||||
source = HERE.parents[1]
|
||||
resources = f"{APP}/Contents/Resources"
|
||||
icon = "cadcraft-nightly.icns"
|
||||
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
|
||||
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
|
||||
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
|
||||
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
|
||||
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
|
||||
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
|
||||
contents = f"{APP}/Contents"
|
||||
gui = f"{contents}/MacOS/CADCraft"
|
||||
with zipfile.ZipFile(archive) as zipped:
|
||||
entries = zipped.infolist()
|
||||
names = {entry.filename for entry in entries}
|
||||
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
|
||||
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
|
||||
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
|
||||
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
|
||||
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
|
||||
for path, data in expected_files.items():
|
||||
with self.subTest(path=path):
|
||||
self.assertEqual(zipped.read(path), data)
|
||||
mode = zipped.getinfo(path).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode))
|
||||
self.assertFalse(mode & 0o111)
|
||||
mode = zipped.getinfo(gui).external_attr >> 16
|
||||
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
|
||||
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
|
||||
@@ -13,6 +13,12 @@ INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
|
||||
SIGNER_BRANCH = "nightly-signer"
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# The pinned shared registry enables Windows, Linux and macOS for CADCraft.
|
||||
SIGNER_SECRETS = {
|
||||
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
|
||||
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
|
||||
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
|
||||
}
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
@@ -46,6 +52,49 @@ def assert_nightly_serialization(source):
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def caller_entries(lines, indent):
|
||||
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
|
||||
entries = {}
|
||||
children = None
|
||||
for line in lines:
|
||||
if children is not None and line.startswith(" " * (indent + 1)):
|
||||
children.append(line)
|
||||
continue
|
||||
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
|
||||
if row is None or row[1] in entries:
|
||||
raise ValueError("malformed or duplicate caller mapping entry")
|
||||
children = []
|
||||
entries[row[1]] = row[2], children
|
||||
return entries
|
||||
|
||||
|
||||
def assert_caller_secrets(source, job_name, names):
|
||||
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
|
||||
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
|
||||
root = caller_entries(lines, 0)
|
||||
job_marker, job_lines = root.pop("jobs", (None, []))
|
||||
jobs = caller_entries(job_lines, 2)
|
||||
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
|
||||
raise ValueError("the caller must have one plain job block")
|
||||
job = caller_entries(jobs[job_name][1], 4)
|
||||
if "environment" in job or "environment" in root or "secrets" in root:
|
||||
raise ValueError("only the native callee may bind the environment")
|
||||
if names:
|
||||
if "secrets" not in job:
|
||||
raise ValueError("signer requires an explicit target-specific secret map")
|
||||
mode, secret_lines = job.pop("secrets")
|
||||
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
|
||||
if mode is not None or caller_entries(secret_lines, 6) != expected:
|
||||
raise ValueError("signer must forward exactly the reviewed same-name secret references")
|
||||
elif "secrets" in job:
|
||||
raise ValueError("unsigned caller must not pass secrets")
|
||||
for value, children in (*root.values(), *job.values()):
|
||||
outside_map = "\n".join([value or "", *children])
|
||||
# Scan all remaining text: quoted braces can appear before a secret reference.
|
||||
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
|
||||
raise ValueError("secret bindings belong only in the signer map")
|
||||
|
||||
|
||||
def job_conditions(jobs):
|
||||
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
|
||||
lines = jobs.splitlines()
|
||||
@@ -182,8 +231,49 @@ class TrustedSourcePreparation(unittest.TestCase):
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
header = " secrets:\n"
|
||||
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
|
||||
self.assertIn(linux, signer)
|
||||
mutations = {
|
||||
"missing name": signer.replace(linux, ""),
|
||||
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
|
||||
"duplicate name": signer.replace(linux, linux + linux),
|
||||
"duplicate map": signer + header + linux,
|
||||
"quoted duplicate map": signer + ' "secrets": inherit\n',
|
||||
"inherit": signer.split(header)[0] + " secrets: inherit\n",
|
||||
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
|
||||
"yaml merge": signer + " <<: *other\n",
|
||||
"environment": signer + " environment: release\n",
|
||||
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
|
||||
}
|
||||
for change, source in mutations.items():
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(source, "release", SIGNER_SECRETS)
|
||||
|
||||
def test_unsigned_caller_has_no_secrets(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
assert_caller_secrets(producer, "unsigned", set())
|
||||
for suffix in (" secrets: {}\n", " secrets: inherit\n",
|
||||
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
|
||||
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
|
||||
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
|
||||
assert_caller_secrets(producer + suffix, "unsigned", set())
|
||||
|
||||
def test_unsigned_caller_refuses_secret_after_format_brace(self):
|
||||
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
# This inert fixture is never dispatched; the brace is part of the format string.
|
||||
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
|
||||
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
|
||||
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
|
||||
assert_caller_secrets(source, "unsigned", set())
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user