Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(server): every connection presents a token, minted when none is set

Jareere35b2d9685d2
diff --git a/SECURITY.md b/SECURITY.md
index f64e99d9..1f7bcaea 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -39,10 +39,11 @@ Concat runs entirely on your machine. Reports we care about most:
- A downloaded model or its mirror being swapped for something else
without the digest check catching it.
- The API server (`concat-cli serve`, or Settings › Remote) accepting a
- call it should have refused: a missing or wrong token, or a bind off
- loopback with no token.
+ call it should have refused: a missing or wrong token, on any address,
+ or a server that started with no token at all.
By design, and not a vulnerability: the API server does whatever the
person who started it can do on that machine, and it is not encrypted.
-Binding it to anything other than 127.0.0.1 requires a token and should
-sit behind something that provides transport security.
+Every connection presents a token, minted when none was set; binding to
+anything other than 127.0.0.1 should sit behind something that provides
+transport security.
diff --git a/src/Cargo.lock b/src/Cargo.lock
index a09670c4..5387696a 100644
--- a/src/Cargo.lock
+++ b/src/Cargo.lock
@@ -1345,6 +1345,7 @@ name = "concat-server"
version = "0.2.2"
dependencies = [
"concat-api",
+ "getrandom 0.3.4",
"prost",
"protox",
"serde_json",
diff --git a/src/README.md b/src/README.md
index ed88c99d..bdd2f035 100644
--- a/src/README.md
+++ b/src/README.md
@@ -146,13 +146,17 @@ the number is JSON-RPC's, the name in `data` is the API's - `parse`,
events follow, to every connected caller, each naming its job and project.
`concat-cli serve` puts the same lines on a socket. It binds loopback unless
-told otherwise and refuses any other address without `--token` (or
-`CONCAT_API_TOKEN`), which a connection then presents as its first line,
-`{"jsonrpc":"2.0","id":0,"method":"auth","params":{"token":"..."}}`. There
-is no encryption; a bind off loopback belongs behind something that has it.
-With the `grpc` feature the same API is served over HTTP/2 from
-`crates/concat-server/proto/concat.proto`, a thin envelope carrying the
-same JSON, with the token as `authorization: Bearer ...` metadata.
+told otherwise, and every connection, loopback included, presents a token
+as its first line, `{"jsonrpc":"2.0","id":0,"method":"auth","params":{"token":"..."}}`:
+the one given with `--token` (or `CONCAT_API_TOKEN`), or else one minted
+at start and printed under the addresses, so only whoever started the
+server can hand it out. There is no encryption; a bind off loopback belongs
+behind something that has it. With the `grpc` feature the same API is
+served over HTTP/2 from `crates/concat-server/proto/concat.proto`, a thin
+envelope carrying the same JSON, with the token as `authorization: Bearer
+...` metadata. `version` is the call to make first: its reply's
+`capabilities` names what the build serves (`events`, `json-rpc`,
+`unix-socket`, `grpc`, `gpu`) before anything is asked of it.
## Reading this codebase cold
diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rs
index 1eebe109..d09f58d3 100644
--- a/src/crates/concat-api/src/lib.rs
+++ b/src/crates/concat-api/src/lib.rs
@@ -61,6 +61,10 @@ const DEFAULT_CRF: u8 = 20;
/// The x264 preset every export uses unless told otherwise.
const DEFAULT_PRESET: &str = "medium";
+/// What every build of the API serves, before what is decided by the
+/// build or the embedder is added; see [`VersionInfo::capabilities`].
+const CAPABILITIES: &[&str] = &["events"];
+
/// Where a job's events go. Called from the job's thread, so a transport
/// that writes them to a caller locks its writer inside.
pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
@@ -76,6 +80,8 @@ pub struct Api {
exporter: Exporter,
events: EventSink,
jobs: Jobs,
+ /// [`VersionInfo::capabilities`], in the order they were added.
+ capabilities: Vec<String>,
}
impl Api {
@@ -97,6 +103,7 @@ impl Api {
events,
jobs: Jobs::default(),
dirs,
+ capabilities: CAPABILITIES.iter().map(|name| (*name).to_owned()).collect(),
}
}
@@ -105,6 +112,16 @@ impl Api {
&self.dirs
}
+ /// Adds a name to [`VersionInfo::capabilities`]: what the transport
+ /// or embedder around this API serves that the API cannot know of
+ /// itself, such as the sockets it is listening on. A name already
+ /// there is not repeated.
+ pub fn add_capability(&mut self, name: &str) {
+ if !self.capabilities.iter().any(|known| known == name) {
+ self.capabilities.push(name.to_owned());
+ }
+ }
+
/// The export slot, for an embedder that shares it with a window.
pub fn exporter(&self) -> Exporter {
self.exporter.clone()
@@ -200,6 +217,13 @@ impl Api {
api_version: API_VERSION.to_owned(),
concat: env!("CARGO_PKG_VERSION").to_owned(),
dirs: Dirs::from(&self.dirs),
+ capabilities: {
+ let mut capabilities = self.capabilities.clone();
+ if self.monitor.has_gpu() {
+ capabilities.push("gpu".to_owned());
+ }
+ capabilities
+ },
}
}
@@ -772,6 +796,25 @@ mod tests {
format!("{location}/{name}")
}
+ #[test]
+ fn version_names_what_the_build_serves() {
+ let (mut api, _scratch, _events) = api();
+ let base = api.version();
+ assert_eq!(base.api_version, API_VERSION);
+ assert_eq!(base.capabilities, vec!["events".to_owned()]);
+ assert!(!base.capabilities.iter().any(|name| name == "gpu"));
+
+ api.add_capability("json-rpc");
+ api.add_capability("json-rpc");
+ api.add_capability("grpc");
+ let served = serde_json::to_value(ok(api.dispatch(Request::Version))).expect("JSON");
+ assert_eq!(
+ served["capabilities"],
+ json!(["events", "json-rpc", "grpc"]),
+ "each name once, in the order added"
+ );
+ }
+
#[test]
fn a_request_parses_by_method_and_carries_a_command_verbatim() {
let request: Request = serde_json::from_value(json!({
diff --git a/src/crates/concat-api/src/message.rs b/src/crates/concat-api/src/message.rs
index b7f60a3a..2b8b91da 100644
--- a/src/crates/concat-api/src/message.rs
+++ b/src/crates/concat-api/src/message.rs
@@ -49,7 +49,10 @@ pub const API_VERSION: &str = "0.2";
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "method", rename_all_fields = "camelCase")]
pub enum Request {
- /// The API's version and the build behind it.
+ /// The API's version, the build behind it, and what that build
+ /// serves. The one method to call first: its reply's `capabilities`
+ /// names the transports and optional features this server has, so a
+ /// caller knows what to ask for before it asks.
#[serde(rename = "version")]
Version,
@@ -318,6 +321,14 @@ pub struct VersionInfo {
pub concat: String,
/// Where this machine keeps recents, templates and models.
pub dirs: Dirs,
+ /// What this build serves, as names a caller tests for membership:
+ /// what the API itself provides in every build, `events`, and what
+ /// only some builds do, `gpu` when frames composite on one; then what
+ /// the transport around it adds, `json-rpc`, `unix-socket` and `grpc`
+ /// for each of the socket transports listening. A name absent from
+ /// the list is not served, whatever the build; a name added later is
+ /// not a version bump, so a caller ignores names it does not know.
+ pub capabilities: Vec<String>,
}
/// The app's directories, as paths.
diff --git a/src/crates/concat-cli/src/main.rs b/src/crates/concat-cli/src/main.rs
index 3dc0a18a..4503b3a0 100644
--- a/src/crates/concat-cli/src/main.rs
+++ b/src/crates/concat-cli/src/main.rs
@@ -66,7 +66,9 @@ enum Command {
/// Serve the Concat API on a socket until the process is stopped:
/// JSON-RPC lines over TCP or a Unix socket, and gRPC in a build that
- /// has it. With no address given, JSON-RPC on 127.0.0.1:7420.
+ /// has it. With no address given, JSON-RPC on 127.0.0.1:7420. Every
+ /// connection presents a token first; with none given, one is minted
+ /// and printed with the addresses.
Serve {
/// The TCP address for JSON-RPC lines, e.g. 127.0.0.1:7420.
#[arg(long)]
@@ -77,8 +79,8 @@ enum Command {
/// The TCP address for gRPC. Needs a build with the `grpc` feature.
#[arg(long)]
grpc: Option<SocketAddr>,
- /// The token every connection presents first. Required for any
- /// address that is not loopback.
+ /// The token every connection presents first. Minted when not
+ /// given, and printed either way.
#[arg(long, env = "CONCAT_API_TOKEN")]
token: Option<String>,
},
@@ -171,8 +173,8 @@ fn emit(message: &Message) {
}
/// The socket transports, until the process is stopped. Where they listen
-/// is printed, one line each, so a script that started this knows where
-/// to connect.
+/// is printed, one line each, and then the token they take, so a script
+/// that started this knows where to connect and what to present.
fn serve(
json: Option<SocketAddr>,
socket: Option<PathBuf>,
@@ -203,6 +205,11 @@ fn serve(
if let Some(address) = server.grpc_addr() {
println!("Concat API {}: gRPC on {address}", concat_api::API_VERSION);
}
+ println!(
+ "Concat API {}: token {}",
+ concat_api::API_VERSION,
+ server.token()
+ );
loop {
std::thread::park();
}
diff --git a/src/crates/concat-server/Cargo.toml b/src/crates/concat-server/Cargo.toml
index b46bb703..3f3e96b4 100644
--- a/src/crates/concat-server/Cargo.toml
+++ b/src/crates/concat-server/Cargo.toml
@@ -24,6 +24,9 @@ grpc = [
[dependencies]
concat-api.workspace = true
serde_json.workspace = true
+# A token minted when none was given: 128 bits the operating system
+# hands out, so the server is never open to whoever reaches the socket.
+getrandom = "0.3"
tonic = { version = "0.14", optional = true }
tonic-prost = { version = "0.14", optional = true }
prost = { version = "0.14", optional = true }
diff --git a/src/crates/concat-server/src/grpc.rs b/src/crates/concat-server/src/grpc.rs
index ebeb7765..103fc283 100644
--- a/src/crates/concat-server/src/grpc.rs
+++ b/src/crates/concat-server/src/grpc.rs
@@ -14,8 +14,8 @@
//! call is handed to the [`Hub`] from a blocking task, the same way a
//! JSON-RPC connection thread hands one over, and waits there.
//!
-//! With a token, every call carries it as `authorization: Bearer ...`
-//! metadata; one without is `UNAUTHENTICATED`.
+//! Every call carries the server's token as `authorization: Bearer ...`
+//! metadata; one without it, or with another, is `UNAUTHENTICATED`.
use std::net::SocketAddr;
use std::sync::Arc;
@@ -29,7 +29,7 @@ use serde_json::{Value, json};
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Status};
-use crate::Hub;
+use crate::{Hub, token};
/// The generated messages and service.
pub mod proto {
@@ -128,7 +128,7 @@ fn encode_event(event: &Event) -> proto::Event {
pub(crate) fn serve(
address: SocketAddr,
hub: Hub,
- token: Option<String>,
+ token: String,
stop: Arc<AtomicBool>,
) -> Result<(SocketAddr, JoinHandle<()>), String> {
let could_not =
@@ -173,22 +173,20 @@ pub(crate) fn serve(
Ok((bound, thread))
}
-/// The check every call passes through: the token as a bearer, when
-/// there is one.
-fn bearer(token: Option<String>) -> impl Fn(Request<()>) -> Result<Request<()>, Status> + Clone {
- let expected = token.map(|token| format!("Bearer {token}"));
- move |request: Request<()>| match &expected {
- None => Ok(request),
- Some(expected) => {
- let presented = request
- .metadata()
- .get("authorization")
- .and_then(|value| value.to_str().ok());
- if presented == Some(expected.as_str()) {
- Ok(request)
- } else {
- Err(Status::unauthenticated("the token is missing or wrong"))
- }
+/// The check every call passes through: the token as a bearer, compared
+/// in constant time.
+fn bearer(token: String) -> impl Fn(Request<()>) -> Result<Request<()>, Status> + Clone {
+ let expected = format!("Bearer {token}");
+ move |request: Request<()>| {
+ let presented = request
+ .metadata()
+ .get("authorization")
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or_default();
+ if token::matches(presented.as_bytes(), expected.as_bytes()) {
+ Ok(request)
+ } else {
+ Err(Status::unauthenticated("the token is missing or wrong"))
}
}
}
@@ -216,6 +214,16 @@ mod tests {
(server, scratch)
}
+ /// `request`, with `token` as its bearer.
+ fn with_bearer<T>(request: T, token: &str) -> Request<T> {
+ let mut request = Request::new(request);
+ request.metadata_mut().insert(
+ "authorization",
+ format!("Bearer {token}").parse().expect("a value"),
+ );
+ request
+ }
+
#[tokio::test]
async fn a_call_answers_in_json_text_and_an_error_carries_its_code() {
let (server, _scratch) = server(None);
@@ -224,10 +232,13 @@ mod tests {
.await
.expect("connects");
let version = client
- .call(proto::Request {
- method: "version".to_owned(),
- params: String::new(),
- })
+ .call(with_bearer(
+ proto::Request {
+ method: "version".to_owned(),
+ params: String::new(),
+ },
+ server.token(),
+ ))
.await
.expect("answers")
.into_inner();
@@ -236,12 +247,16 @@ mod tests {
};
let value: Value = serde_json::from_str(&text).expect("JSON");
assert_eq!(value["apiVersion"], concat_api::API_VERSION);
+ assert_eq!(value["capabilities"], json!(["events", "grpc"]));
let refused = client
- .call(proto::Request {
- method: "project.get".to_owned(),
- params: r#"{"path":"/none"}"#.to_owned(),
- })
+ .call(with_bearer(
+ proto::Request {
+ method: "project.get".to_owned(),
+ params: r#"{"path":"/none"}"#.to_owned(),
+ },
+ server.token(),
+ ))
.await
.expect("answers")
.into_inner();
@@ -268,13 +283,18 @@ mod tests {
};
let refused = client.call(version()).await.expect_err("no token");
assert_eq!(refused.code(), tonic::Code::Unauthenticated);
+ let refused = client
+ .call(with_bearer(version(), "open"))
+ .await
+ .expect_err("wrong token");
+ assert_eq!(refused.code(), tonic::Code::Unauthenticated);
- let mut request = Request::new(version());
- request.metadata_mut().insert(
- "authorization",
- "Bearer open sesame".parse().expect("a value"),
+ assert!(
+ client
+ .call(with_bearer(version(), "open sesame"))
+ .await
+ .is_ok()
);
- assert!(client.call(request).await.is_ok());
drop(client);
tokio::task::spawn_blocking(move || server.stop())
.await
diff --git a/src/crates/concat-server/src/json.rs b/src/crates/concat-server/src/json.rs
index 40deb8da..aba0f470 100644
--- a/src/crates/concat-server/src/json.rs
+++ b/src/crates/concat-server/src/json.rs
@@ -10,9 +10,9 @@
//! interleaves with a response half-written. The wire is exactly what
//! `concat-cli api` reads and writes; see `concat_api::rpc`.
//!
-//! When the server has a token, a connection's first line must be
-//! `{"jsonrpc": "2.0", "id": 1, "method": "auth", "params": {"token":
-//! "..."}}`. Anything else first is answered with an `unauthorized` error
+//! A connection's first line is `{"jsonrpc": "2.0", "id": 1, "method":
+//! "auth", "params": {"token": "..."}}`, with the server's token. Anything
+//! else first, or the wrong token, is answered with an `unauthorized` error
//! and the connection is closed. `auth` is the transport's word, not the
//! API's: it never reaches the hub.
@@ -27,13 +27,13 @@ use concat_api::rpc::{Call, Id, Message};
use concat_api::{ApiError, Done, ErrorCode, Reply, Response};
use serde_json::Value;
-use crate::{Connections, Hub};
+use crate::{Connections, Hub, token};
/// Accepts JSON-RPC connections on `listener` until `stop` is set.
pub(crate) fn serve_tcp(
listener: TcpListener,
hub: Hub,
- token: Option<String>,
+ token: String,
stop: Arc<AtomicBool>,
connections: Connections,
) -> JoinHandle<()> {
@@ -75,7 +75,7 @@ pub(crate) fn serve_tcp(
pub(crate) fn serve_unix(
listener: std::os::unix::net::UnixListener,
hub: Hub,
- token: Option<String>,
+ token: String,
stop: Arc<AtomicBool>,
connections: Connections,
) -> JoinHandle<()> {
@@ -112,30 +112,23 @@ pub(crate) fn serve_unix(
}
/// One caller, start to end: the handshake, then a call per line.
-fn connection(
- reader: impl BufRead,
- writer: impl Write + Send + 'static,
- hub: Hub,
- token: Option<String>,
-) {
+fn connection(reader: impl BufRead, writer: impl Write + Send + 'static, hub: Hub, token: String) {
let outbox = Outbox::start(writer);
let mut lines = reader.lines().map_while(Result::ok);
- if let Some(token) = token {
- let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
- outbox.close();
- return;
- };
- let (id, outcome) = handshake(&first, &token);
- let ok = outcome.is_ok();
- outbox.send(Message::Reply {
- id,
- response: outcome.into(),
- });
- if !ok {
- outbox.close();
- return;
- }
+ let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
+ outbox.close();
+ return;
+ };
+ let (id, outcome) = handshake(&first, &token);
+ let ok = outcome.is_ok();
+ outbox.send(Message::Reply {
+ id,
+ response: outcome.into(),
+ });
+ if !ok {
+ outbox.close();
+ return;
}
// Events reach this caller from here on: the outbox is shared with the
@@ -160,7 +153,8 @@ fn connection(
outbox.close();
}
-/// Reads the first line as the `auth` call and checks its token.
+/// Reads the first line as the `auth` call and checks its token, in
+/// constant time.
fn handshake(line: &str, token: &str) -> (Option<Id>, Result<Reply, ApiError>) {
let refuse = |id: Option<Id>, why: &str| {
(
@@ -180,7 +174,7 @@ fn handshake(line: &str, token: &str) -> (Option<Id>, Result<Reply, ApiError>) {
.and_then(|params| params.get("token"))
.or_else(|| object.get("token"))
.and_then(Value::as_str);
- if presented == Some(token) {
+ if token::matches(presented.unwrap_or_default().as_bytes(), token.as_bytes()) {
(id, Ok(Reply::Done(Done {})))
} else {
refuse(id, "wrong token")
@@ -247,7 +241,19 @@ mod tests {
}
impl Client {
+ /// A connection with the server's token presented, ready to call.
fn connect(server: &crate::Server) -> Client {
+ let mut client = Client::reach(server);
+ let welcomed = client.ask(&format!(
+ r#"{{"jsonrpc":"2.0","id":0,"method":"auth","params":{{"token":"{}"}}}}"#,
+ server.token()
+ ));
+ assert_eq!(welcomed["result"], serde_json::json!({}), "{welcomed}");
+ client
+ }
+
+ /// A connection with nothing said yet.
+ fn reach(server: &crate::Server) -> Client {
let stream =
TcpStream::connect(server.json_addr().expect("listening")).expect("connects");
Client {
@@ -271,6 +277,11 @@ mod tests {
let reply = client.ask(r#"{"jsonrpc":"2.0","id":41,"method":"version"}"#);
assert_eq!(reply["id"], 41);
assert_eq!(reply["result"]["apiVersion"], concat_api::API_VERSION);
+ assert_eq!(
+ reply["result"]["capabilities"],
+ serde_json::json!(["events", "json-rpc"]),
+ "the transport listening is named"
+ );
let refused = client
.ask(r#"{"jsonrpc":"2.0","id":42,"method":"project.get","params":{"path":"/none"}}"#);
assert_eq!(refused["error"]["data"]["code"], "notOpen");
@@ -298,17 +309,23 @@ mod tests {
#[test]
fn a_token_is_presented_first_or_the_connection_ends() {
let (server, _scratch) = server(Some("open sesame"));
- let mut wrong = Client::connect(&server);
- let refused = wrong.ask(r#"{"jsonrpc":"2.0","id":1,"method":"version"}"#);
+ let mut silent = Client::reach(&server);
+ let refused = silent.ask(r#"{"jsonrpc":"2.0","id":1,"method":"version"}"#);
assert_eq!(refused["error"]["data"]["code"], "unauthorized");
let mut after = String::new();
assert_eq!(
- wrong.reader.read_line(&mut after).expect("eof"),
+ silent.reader.read_line(&mut after).expect("eof"),
0,
"closed"
);
- let mut right = Client::connect(&server);
+ let mut wrong = Client::reach(&server);
+ let refused =
+ wrong.ask(r#"{"jsonrpc":"2.0","id":1,"method":"auth","params":{"token":"open"}}"#);
+ assert_eq!(refused["error"]["data"]["code"], "unauthorized");
+ assert_eq!(wrong.reader.read_line(&mut after).expect("eof"), 0);
+
+ let mut right = Client::reach(&server);
let welcomed = right
.ask(r#"{"jsonrpc":"2.0","id":1,"method":"auth","params":{"token":"open sesame"}}"#);
assert_eq!(welcomed["result"], serde_json::json!({}));
@@ -317,4 +334,17 @@ mod tests {
assert_eq!(server.connections(), 1);
server.stop();
}
+
+ #[test]
+ fn a_minted_token_is_required_on_loopback_too() {
+ let (server, _scratch) = server(None);
+ let mut silent = Client::reach(&server);
+ let refused = silent.ask(r#"{"jsonrpc":"2.0","id":1,"method":"version"}"#);
+ assert_eq!(refused["error"]["data"]["code"], "unauthorized");
+
+ let mut right = Client::connect(&server);
+ let reply = right.ask(r#"{"jsonrpc":"2.0","id":2,"method":"version"}"#);
+ assert_eq!(reply["result"]["apiVersion"], concat_api::API_VERSION);
+ server.stop();
+ }
}
diff --git a/src/crates/concat-server/src/lib.rs b/src/crates/concat-server/src/lib.rs
index d9fe2f15..d3fee2ee 100644
--- a/src/crates/concat-server/src/lib.rs
+++ b/src/crates/concat-server/src/lib.rs
@@ -21,13 +21,19 @@
//! it asked for.
//!
//! The API reads and writes whatever paths it is given, so a server is a
-//! door into the machine. It binds loopback unless told otherwise, and it
-//! refuses to bind anything else without a token every connection must
-//! present before its first call. There is no encryption: a bind off
-//! loopback belongs behind something that provides it.
+//! door into the machine. Every connection presents a token before its
+//! first call, loopback included: another user's process on the same
+//! machine reaches 127.0.0.1 as easily as this one does. A server given
+//! no token mints one, 128 bits from the operating system's randomness,
+//! that only the process that started it knows; [`Server::token`] is how
+//! that process passes it on, to a page or a terminal. The token is
+//! compared in constant time, whichever transport carries it. There is
+//! no encryption: a bind off loopback belongs behind something that
+//! provides it.
mod hub;
pub mod json;
+mod token;
#[cfg(feature = "grpc")]
pub mod grpc;
@@ -52,25 +58,17 @@ pub struct Config {
pub socket: Option<PathBuf>,
/// A TCP address for gRPC. Needs the `grpc` feature.
pub grpc: Option<SocketAddr>,
- /// What a connection presents before its first call. Required for
- /// any address that is not loopback.
+ /// What every connection presents before its first call. `None` or
+ /// empty means the server mints one at start, which only the process
+ /// that started it can learn, through [`Server::token`]; that is the
+ /// point, and it is why a bind off loopback needs no token set here
+ /// to be safe to make.
pub token: Option<String>,
}
impl Config {
- /// Refuses a configuration that would open the machine: a TCP bind
- /// off loopback with no token.
+ /// Refuses a configuration this build or platform cannot serve.
pub fn check(&self) -> Result<(), String> {
- for (what, address) in [("JSON-RPC", self.json), ("gRPC", self.grpc)] {
- if let Some(address) = address
- && !address.ip().is_loopback()
- && self.token.as_deref().is_none_or(str::is_empty)
- {
- return Err(format!(
- "{what} on {address} is reachable from other machines: set a token, or bind 127.0.0.1"
- ));
- }
- }
#[cfg(not(unix))]
if self.socket.is_some() {
return Err("a Unix socket needs a Unix".to_owned());
@@ -92,6 +90,7 @@ pub struct Server {
json: Option<SocketAddr>,
socket: Option<PathBuf>,
grpc: Option<SocketAddr>,
+ token: String,
stop: Arc<AtomicBool>,
listeners: Vec<JoinHandle<()>>,
connections: Connections,
@@ -103,13 +102,33 @@ pub(crate) type Connections = Arc<Mutex<Vec<Box<dyn Fn() + Send>>>>;
impl Server {
/// Binds every address in `config` and starts serving. `make` builds
- /// the API on the hub's thread, given the sink its jobs report through.
+ /// the API on the hub's thread, given the sink its jobs report through;
+ /// the transports listening are added to what its `version` reports.
+ /// With no token in `config`, one is minted; [`Server::token`] is it.
pub fn start(
config: Config,
make: impl FnOnce(EventSink) -> Result<Api, String> + Send + 'static,
) -> Result<Server, String> {
config.check()?;
- let (hub, dispatcher) = Hub::start(make)?;
+ let token = match config.token.filter(|token| !token.is_empty()) {
+ Some(token) => token,
+ None => token::mint()?,
+ };
+ let transports: Vec<&str> = [
+ config.json.map(|_| "json-rpc"),
+ config.socket.as_ref().map(|_| "unix-socket"),
+ config.grpc.map(|_| "grpc"),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ let (hub, dispatcher) = Hub::start(move |events| {
+ let mut api = make(events)?;
+ for transport in transports {
+ api.add_capability(transport);
+ }
+ Ok(api)
+ })?;
let stop = Arc::new(AtomicBool::new(false));
let connections: Connections = Arc::new(Mutex::new(Vec::new()));
let mut server = Server {
@@ -118,11 +137,11 @@ impl Server {
json: None,
socket: None,
grpc: None,
+ token,
stop: Arc::clone(&stop),
listeners: Vec::new(),
connections: Arc::clone(&connections),
};
- let token = config.token.filter(|token| !token.is_empty());
if let Some(address) = config.json {
let listener = TcpListener::bind(address)
@@ -135,7 +154,7 @@ impl Server {
server.listeners.push(json::serve_tcp(
listener,
server.hub.clone(),
- token.clone(),
+ server.token.clone(),
Arc::clone(&stop),
Arc::clone(&connections),
));
@@ -149,7 +168,7 @@ impl Server {
server.listeners.push(json::serve_unix(
listener,
server.hub.clone(),
- token.clone(),
+ server.token.clone(),
Arc::clone(&stop),
Arc::clone(&connections),
));
@@ -158,8 +177,12 @@ impl Server {
#[cfg(feature = "grpc")]
if let Some(address) = config.grpc {
- let (bound, thread) =
- grpc::serve(address, server.hub.clone(), token, Arc::clone(&stop))?;
+ let (bound, thread) = grpc::serve(
+ address,
+ server.hub.clone(),
+ server.token.clone(),
+ Arc::clone(&stop),
+ )?;
server.grpc = Some(bound);
server.listeners.push(thread);
}
@@ -187,6 +210,13 @@ impl Server {
self.grpc
}
+ /// The token every connection presents: the one configured, or the
+ /// one minted because none was. Whoever started the server shows or
+ /// prints this so a caller can present it.
+ pub fn token(&self) -> &str {
+ &self.token
+ }
+
/// How many callers are connected.
pub fn connections(&self) -> usize {
self.hub.subscribers()
@@ -262,22 +292,15 @@ pub(crate) mod tests {
}
#[test]
- fn a_bind_off_loopback_needs_a_token() {
- let open = Config {
- json: Some("0.0.0.0:0".parse().expect("an address")),
- ..Config::default()
- };
- assert!(open.check().is_err());
- let closed = Config {
- token: Some("s".to_owned()),
- ..open.clone()
- };
- assert!(closed.check().is_ok());
- let local = Config {
- json: Some("127.0.0.1:0".parse().expect("an address")),
- ..Config::default()
- };
- assert!(local.check().is_ok());
+ fn a_server_keeps_the_token_it_is_given_and_mints_one_otherwise() {
+ let (given, _scratch) = server(Some("open sesame"));
+ assert_eq!(given.token(), "open sesame");
+ let (minted, _scratch) = server(None);
+ assert_eq!(minted.token().len(), 32);
+ assert!(minted.token().bytes().all(|byte| byte.is_ascii_hexdigit()));
+ let (empty, _scratch) = server(Some(""));
+ assert_eq!(empty.token().len(), 32, "an empty token is no token");
+ assert_ne!(empty.token(), minted.token());
}
#[test]
diff --git a/src/crates/concat-server/src/token.rs b/src/crates/concat-server/src/token.rs
new file mode 100644
index 00000000..be1ba243
--- /dev/null
+++ b/src/crates/concat-server/src/token.rs
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The token a connection presents: where one comes from when nobody
+//! gave one, and how a presented one is checked.
+//!
+//! The check takes the same time whether the first byte is wrong or the
+//! last, so a caller on the socket learns nothing from how quickly it is
+//! refused. A library would do; this is short enough to read, and its
+//! test says what it promises.
+
+use std::hint::black_box;
+
+/// A fresh token: 128 bits from the operating system's randomness, as
+/// 32 hex digits.
+pub(crate) fn mint() -> Result<String, String> {
+ let mut bytes = [0u8; 16];
+ getrandom::fill(&mut bytes).map_err(|error| format!("could not mint a token: {error}"))?;
+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
+}
+
+/// Whether `presented` is `expected`, in time that depends on the length
+/// of `expected` and on nothing about where the two differ.
+///
+/// Every byte of `expected` is compared, against a zero where `presented`
+/// has run out, and the differences are or'd together with the lengths'
+/// difference; only at the end is the total looked at. `black_box` keeps
+/// the compiler from turning the loop back into an early return.
+pub(crate) fn matches(presented: &[u8], expected: &[u8]) -> bool {
+ let mut difference = presented.len() ^ expected.len();
+ for (index, byte) in expected.iter().enumerate() {
+ let other = presented.get(index).copied().unwrap_or(0);
+ difference = black_box(difference | usize::from(byte ^ other));
+ }
+ black_box(difference) == 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_minted_token_is_thirty_two_hex_digits_and_never_the_same() {
+ let first = mint().expect("mints");
+ let second = mint().expect("mints");
+ assert_eq!(first.len(), 32);
+ assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit()));
+ assert_ne!(first, second);
+ }
+
+ #[test]
+ fn the_compare_accepts_the_token_and_nothing_near_it() {
+ assert!(matches(b"open sesame", b"open sesame"));
+ assert!(matches(b"", b""));
+ assert!(!matches(b"open sesamf", b"open sesame"), "last byte");
+ assert!(!matches(b"npen sesame", b"open sesame"), "first byte");
+ assert!(!matches(b"open sesam", b"open sesame"), "a prefix");
+ assert!(!matches(b"open sesame!", b"open sesame"), "too long");
+ assert!(!matches(b"", b"open sesame"), "nothing");
+ assert!(!matches(b"open sesame", b""), "something for nothing");
+ // Where the presented token is short, the missing bytes read as
+ // zero: a zero there must still not be taken as a match.
+ assert!(!matches(b"a", b"a\0"), "a zero is not a missing byte");
+ }
+}