mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/
The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done: the workspace and checks, bakashrot-proto, bakashrot-pki and bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the server and the client library (every request but replication's, attachments and retention included), the C DLL with its C, PureBasic and Python bindings, and the bakashrot tool. Step 11 (replication) is next. OldSource/ is the old implementation, kept building and passing as the reference. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "bakashrot-tools"
|
||||
description = "BakaShrot's command-line tools: bakashrot pushes and reads messages, bakashrot-cert issues certificates and revokes them."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
# No API to document, and its name is the DLL's library's (cargo doc would
|
||||
# collide).
|
||||
[[bin]]
|
||||
name = "bakashrot"
|
||||
doc = false
|
||||
|
||||
[dependencies]
|
||||
bakashrot-client = { path = "../bakashrot-client" }
|
||||
bakashrot-pki = { path = "../bakashrot-pki" }
|
||||
bakashrot-proto = { path = "../bakashrot-proto" }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
time = "0.3.55"
|
||||
toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde"] }
|
||||
|
||||
[dev-dependencies]
|
||||
bakashrot-config = { path = "../bakashrot-config" }
|
||||
bakashrot-server = { path = "../bakashrot-server" }
|
||||
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,241 @@
|
||||
//! `bakashrot-cert`: makes a CA, issues certificates, revokes them, shows
|
||||
//! them. Every file is PEM; keys are written once, never over an existing
|
||||
//! file. See `Source/docs/certificates.md`.
|
||||
|
||||
use bakashrot_pki::{
|
||||
CA_DAYS, CERTIFICATE_DAYS, Ca, IDENTITY_OID_IS_PLACEHOLDER, Identity, Revocations, Usage,
|
||||
summarize,
|
||||
};
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "bakashrot-cert",
|
||||
version,
|
||||
about = "Issues and revokes BakaShrot's certificates"
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the
|
||||
/// servers: whoever has it can make any identity.
|
||||
Ca {
|
||||
/// The CA's name (its certificate's CN).
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// How long it's valid, in days.
|
||||
#[arg(long, default_value_t = CA_DAYS)]
|
||||
days: u32,
|
||||
/// Where to write ca.crt and ca.key.
|
||||
#[arg(long, default_value = ".")]
|
||||
out: PathBuf,
|
||||
},
|
||||
/// Issues a certificate for a node: NAME.crt and NAME.key in --out
|
||||
/// (or --file's).
|
||||
Issue {
|
||||
/// The node's name.
|
||||
#[arg(long)]
|
||||
name: String,
|
||||
/// A role, any number of times (the server's config says what each
|
||||
/// may do).
|
||||
#[arg(long = "role")]
|
||||
roles: Vec<String>,
|
||||
/// A server's certificate (clients and peers connect to it), not a
|
||||
/// client's.
|
||||
#[arg(long)]
|
||||
server: bool,
|
||||
/// How long it's valid, in days.
|
||||
#[arg(long, default_value_t = CERTIFICATE_DAYS)]
|
||||
days: u32,
|
||||
/// The folder of ca.crt and ca.key.
|
||||
#[arg(long, default_value = ".")]
|
||||
ca: PathBuf,
|
||||
/// Where to write the certificate and its key.
|
||||
#[arg(long, default_value = ".")]
|
||||
out: PathBuf,
|
||||
/// The files' name, without .crt and .key (the node's name by
|
||||
/// default): another certificate for the same name, beside the
|
||||
/// first one (two servers of the same name, a new one before the
|
||||
/// old one is revoked).
|
||||
#[arg(long)]
|
||||
file: Option<String>,
|
||||
},
|
||||
/// Revokes certificates: (re)writes ca.crl in --ca, with every one
|
||||
/// revoked before. Push it to the servers' folders.
|
||||
Revoke {
|
||||
/// The certificates to revoke.
|
||||
#[arg(required = true)]
|
||||
certificates: Vec<PathBuf>,
|
||||
/// The folder of ca.crt, ca.key and ca.crl.
|
||||
#[arg(long, default_value = ".")]
|
||||
ca: PathBuf,
|
||||
/// When to expect the next CRL, in days.
|
||||
#[arg(long, default_value_t = CERTIFICATE_DAYS)]
|
||||
days: u32,
|
||||
},
|
||||
/// Shows what a certificate says.
|
||||
Show {
|
||||
/// The certificate.
|
||||
certificate: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run(Cli::parse().command) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("bakashrot-cert: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Said whenever a certificate is made while the OID is the placeholder.
|
||||
const PLACEHOLDER_WARNING: &str = "warning: the identity extension's OID is still a placeholder \
|
||||
(Source/docs/oid.md): fine for tests, not for certificates in use";
|
||||
|
||||
fn run(command: Command) -> Result<(), String> {
|
||||
if IDENTITY_OID_IS_PLACEHOLDER && matches!(command, Command::Ca { .. } | Command::Issue { .. })
|
||||
{
|
||||
eprintln!("{PLACEHOLDER_WARNING}");
|
||||
}
|
||||
match command {
|
||||
Command::Ca { name, days, out } => {
|
||||
let ca = Ca::create(&name, days).map_err(|e| e.to_string())?;
|
||||
write_new(&out.join("ca.crt"), &ca.certificate, false)?;
|
||||
write_new(&out.join("ca.key"), &ca.key, true)?;
|
||||
}
|
||||
Command::Issue {
|
||||
name,
|
||||
roles,
|
||||
server,
|
||||
days,
|
||||
ca,
|
||||
out,
|
||||
file,
|
||||
} => {
|
||||
let roles: Vec<&str> = roles.iter().map(String::as_str).collect();
|
||||
let identity = Identity::new(&name, &roles).map_err(|e| e.to_string())?;
|
||||
let usage = if server { Usage::Server } else { Usage::Client };
|
||||
let issued = load_ca(&ca)?
|
||||
.issue(&identity, usage, days)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let file = file.unwrap_or(name);
|
||||
write_new(&out.join(format!("{file}.crt")), &issued.certificate, false)?;
|
||||
write_new(&out.join(format!("{file}.key")), &issued.key, true)?;
|
||||
}
|
||||
Command::Revoke {
|
||||
certificates,
|
||||
ca: folder,
|
||||
days,
|
||||
} => revoke(&folder, &certificates, days)?,
|
||||
Command::Show { certificate } => show(&certificate)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<String, String> {
|
||||
fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
fn load_ca(folder: &Path) -> Result<Ca, String> {
|
||||
Ca::load(
|
||||
&read(&folder.join("ca.crt"))?,
|
||||
&read(&folder.join("ca.key"))?,
|
||||
)
|
||||
.map_err(|error| format!("the CA in {}: {error}", folder.display()))
|
||||
}
|
||||
|
||||
/// Writes a new file, never over an existing one; a key readable by its
|
||||
/// owner only (on Unix).
|
||||
fn write_new(path: &Path, text: &str, private: bool) -> Result<(), String> {
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
let mut file = options
|
||||
.open(path)
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
file.write_all(text.as_bytes())
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
println!("Wrote {}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn revoke(folder: &Path, certificates: &[PathBuf], days: u32) -> Result<(), String> {
|
||||
let ca = load_ca(folder)?;
|
||||
let ca_certificate = read(&folder.join("ca.crt"))?;
|
||||
let crl_path = folder.join("ca.crl");
|
||||
|
||||
// Those revoked before stay revoked.
|
||||
let mut serials: Vec<Vec<u8>> = if crl_path.exists() {
|
||||
Revocations::load(&read(&crl_path)?, &ca_certificate)
|
||||
.map_err(|error| format!("{}: {error}", crl_path.display()))?
|
||||
.serials()
|
||||
.map(<[u8]>::to_vec)
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for path in certificates {
|
||||
let certificate = read(path)?;
|
||||
if !ca
|
||||
.issued(&certificate)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?
|
||||
{
|
||||
return Err(format!("{}: not issued by this CA", path.display()));
|
||||
}
|
||||
let summary = summarize(&certificate).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !serials.contains(&summary.serial) {
|
||||
serials.push(summary.serial);
|
||||
}
|
||||
println!("Revoked {} ({})", path.display(), summary.subject);
|
||||
}
|
||||
|
||||
// Written aside then moved: a server reading it never sees half of it.
|
||||
let crl = ca
|
||||
.revocation_list(&serials, days)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let temporary = folder.join("ca.crl.new");
|
||||
fs::write(&temporary, crl).map_err(|error| format!("{}: {error}", temporary.display()))?;
|
||||
fs::rename(&temporary, &crl_path)
|
||||
.map_err(|error| format!("{}: {error}", crl_path.display()))?;
|
||||
println!("Wrote {} ({} revoked)", crl_path.display(), serials.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn show(path: &Path) -> Result<(), String> {
|
||||
let summary = summarize(&read(path)?).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
println!("{}", path.display());
|
||||
match &summary.identity {
|
||||
Some(identity) => {
|
||||
println!(" name: {}", identity.name);
|
||||
println!(" roles: {}", identity.roles.join(", "));
|
||||
}
|
||||
None => println!(" subject: {}", summary.subject),
|
||||
}
|
||||
let usage = match (summary.is_ca, summary.usage) {
|
||||
(true, _) => "CA",
|
||||
(false, Some(Usage::Server)) => "server",
|
||||
(false, Some(Usage::Client)) => "client",
|
||||
(false, None) => "other",
|
||||
};
|
||||
println!(" usage: {usage}");
|
||||
println!(" issuer: {}", summary.issuer);
|
||||
println!(" valid: {} to {}", summary.not_before, summary.not_after);
|
||||
println!(" serial: {}", summary.serial_hex());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! `bakashrot`: pushes messages, reads them and their attachments, runs
|
||||
//! queries and lists names from the command line, connecting with a
|
||||
//! `client.toml`. The old `BakaShrot*` tools in one program; see
|
||||
//! `Source/docs/client.md`, "The tools".
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::error::{code_name, is_refusal_code};
|
||||
use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "bakashrot",
|
||||
version,
|
||||
about = "Pushes and reads BakaShrot's messages",
|
||||
after_help = "Exits with 0 on success, 1 on a failure, 2 on bad arguments."
|
||||
)]
|
||||
struct Cli {
|
||||
/// The client's settings: the server, the CA's certificate, this
|
||||
/// client's certificate and key, the CRL.
|
||||
#[arg(short, long, global = true, default_value = "client.toml")]
|
||||
config: PathBuf,
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Pushes a message as this client's node, prints its id.
|
||||
Push {
|
||||
/// The topic to push to.
|
||||
topic: String,
|
||||
/// The message (JSON or any text), @FILE for a file's, - for the
|
||||
/// standard input's (PowerShell before 7.3 drops the double quotes
|
||||
/// inside arguments: use @FILE or - there).
|
||||
message: String,
|
||||
/// A file to attach (1 byte and up, as much as the server takes):
|
||||
/// the message is stored once all of it came.
|
||||
#[arg(short, long)]
|
||||
attachment: Option<PathBuf>,
|
||||
},
|
||||
/// Prints a topic and node's latest message: its id, when it was pushed
|
||||
/// (UTC), its attachment if it has one, then its data.
|
||||
Latest {
|
||||
/// The topic.
|
||||
topic: String,
|
||||
/// The node that pushed it.
|
||||
node: String,
|
||||
},
|
||||
/// Saves a message's attachment as FILE (replaced), checked with its
|
||||
/// SHA-256, and prints its size. A failed one leaves no file.
|
||||
Attachment {
|
||||
/// The topic.
|
||||
topic: String,
|
||||
/// The node that pushed it.
|
||||
node: String,
|
||||
/// The message's id.
|
||||
id: u64,
|
||||
/// Where to save it.
|
||||
file: PathBuf,
|
||||
},
|
||||
/// Prints a topic and node's messages in order, a line each: its id, a
|
||||
/// tab, its data as stored (a line break in it spans lines).
|
||||
Messages {
|
||||
/// The topic.
|
||||
topic: String,
|
||||
/// The node that pushed them.
|
||||
node: String,
|
||||
/// Starts after this message id: 0 from the first one, "latest"
|
||||
/// after the latest one (only new ones, with --follow).
|
||||
#[arg(long, default_value = "0", value_parser = after)]
|
||||
after: After,
|
||||
/// Stops after this many, 0 for no limit [default: 100, none with
|
||||
/// --follow].
|
||||
#[arg(long)]
|
||||
limit: Option<u64>,
|
||||
/// Keeps going once caught up, checking every --interval, until
|
||||
/// stopped (Ctrl+C) or the connection fails.
|
||||
#[arg(short, long)]
|
||||
follow: bool,
|
||||
/// How often --follow checks, in milliseconds.
|
||||
#[arg(long, default_value_t = 500, value_parser = clap::value_parser!(u64).range(10..=3_600_000))]
|
||||
interval: u64,
|
||||
/// Also prints when each was pushed (UTC), between its id and its
|
||||
/// data.
|
||||
#[arg(short, long)]
|
||||
time: bool,
|
||||
},
|
||||
/// Runs read-only SQL on the server, prints its result as JSON:
|
||||
/// {"columns":[...],"rows":[[...],...]}. The client's roles must allow
|
||||
/// queries.
|
||||
Query {
|
||||
/// One SELECT (or WITH ... SELECT), @FILE for a file's, - for the
|
||||
/// standard input's.
|
||||
sql: String,
|
||||
},
|
||||
/// Lists the topics this client may use (every one if it may query) and
|
||||
/// the nodes with messages.
|
||||
List {
|
||||
/// What to list.
|
||||
#[arg(value_enum, default_value_t = What::All)]
|
||||
what: What,
|
||||
/// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Where `messages` starts.
|
||||
#[derive(Clone, Copy)]
|
||||
enum After {
|
||||
Id(u64),
|
||||
Latest,
|
||||
}
|
||||
|
||||
fn after(text: &str) -> Result<After, String> {
|
||||
if text.eq_ignore_ascii_case("latest") {
|
||||
return Ok(After::Latest);
|
||||
}
|
||||
text.parse()
|
||||
.map(After::Id)
|
||||
.map_err(|_| "a message id or \"latest\"".to_owned())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum What {
|
||||
Topics,
|
||||
Nodes,
|
||||
All,
|
||||
}
|
||||
|
||||
/// `client.toml`: paths are relative to its folder.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ClientToml {
|
||||
server: String,
|
||||
ca: PathBuf,
|
||||
certificate: PathBuf,
|
||||
key: PathBuf,
|
||||
crl: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
match run(&cli.config, cli.command) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(message) => {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
match command {
|
||||
Command::Push {
|
||||
topic,
|
||||
message,
|
||||
attachment,
|
||||
} => {
|
||||
let message = input(&message)?;
|
||||
let Some(path) = attachment else {
|
||||
let id = connect(config)?.push(&topic, &message).map_err(failed)?;
|
||||
println!("Pushed as message #{id}");
|
||||
return Ok(());
|
||||
};
|
||||
let mut file = fs::File::open(&path)
|
||||
.map_err(|error| format!("Can't read {}: {error}", path.display()))?;
|
||||
let id = connect(config)?
|
||||
.push_with_attachment(&topic, &message, &mut file)
|
||||
.map_err(failed)?;
|
||||
let size = file.metadata().map_or(0, |metadata| metadata.len());
|
||||
println!("Pushed as message #{id}, with an attachment of {size} bytes");
|
||||
}
|
||||
Command::Attachment {
|
||||
topic,
|
||||
node,
|
||||
id,
|
||||
file,
|
||||
} => {
|
||||
let size = connect(config)?
|
||||
.save_attachment(&topic, &node, id, &file)
|
||||
.map_err(failed)?;
|
||||
println!("Saved {size} bytes as {}", file.display());
|
||||
}
|
||||
Command::Latest { topic, node } => {
|
||||
let message = latest(&mut connect(config)?, &topic, &node)?
|
||||
.ok_or_else(|| format!("No message yet in {topic}:{node}"))?;
|
||||
println!(
|
||||
"Message {topic}:{node}#{}, pushed {}",
|
||||
message.id,
|
||||
utc(message.pushed_at)
|
||||
);
|
||||
if let Some(attachment) = &message.attachment {
|
||||
let here = if attachment.ready {
|
||||
""
|
||||
} else {
|
||||
", not on this server yet"
|
||||
};
|
||||
println!("Attachment: {} bytes{here}", attachment.size);
|
||||
}
|
||||
println!("{}", message.data);
|
||||
}
|
||||
Command::Messages {
|
||||
topic,
|
||||
node,
|
||||
after,
|
||||
limit,
|
||||
follow,
|
||||
interval,
|
||||
time,
|
||||
} => {
|
||||
let mut client = connect(config)?;
|
||||
let mut after = match after {
|
||||
After::Id(id) => id,
|
||||
After::Latest => latest(&mut client, &topic, &node)?.map_or(0, |m| m.id),
|
||||
};
|
||||
let limit = limit.unwrap_or(if follow { 0 } else { 100 });
|
||||
let mut printed = 0;
|
||||
let mut out = io::BufWriter::new(io::stdout().lock());
|
||||
loop {
|
||||
let left = if limit > 0 { limit - printed } else { u64::MAX };
|
||||
let asked = left.min(u64::from(MAX_MESSAGES_PER_PACKET)) as u32;
|
||||
let batch = client
|
||||
.get_messages(&topic, &node, Some(after), asked)
|
||||
.map_err(failed)?;
|
||||
for message in &batch.messages {
|
||||
after = message.id;
|
||||
let written = if time {
|
||||
let at = utc(message.pushed_at);
|
||||
writeln!(out, "{after}\t{at}\t{}", message.data)
|
||||
} else {
|
||||
writeln!(out, "{after}\t{}", message.data)
|
||||
};
|
||||
written.map_err(cant_write)?;
|
||||
}
|
||||
out.flush().map_err(cant_write)?;
|
||||
printed += batch.messages.len() as u64;
|
||||
if (limit > 0 && printed >= limit) || (!batch.more && !follow) {
|
||||
break;
|
||||
}
|
||||
if !batch.more {
|
||||
std::thread::sleep(Duration::from_millis(interval));
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Query { sql } => {
|
||||
let sql = input(&sql)?;
|
||||
println!("{}", connect(config)?.query(&sql).map_err(failed)?);
|
||||
}
|
||||
Command::List { what, json } => {
|
||||
let mut client = connect(config)?;
|
||||
let kinds = [
|
||||
(NameKind::Topic, "topic", "Topics"),
|
||||
(NameKind::Node, "node", "Nodes"),
|
||||
];
|
||||
for (kind, name, label) in kinds {
|
||||
if matches!(
|
||||
(what, kind),
|
||||
(What::Topics, NameKind::Node) | (What::Nodes, NameKind::Topic)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let list = client.list_names(kind).map_err(failed)?;
|
||||
if json {
|
||||
let json = serde_json::json!({
|
||||
"kind": name,
|
||||
"names": list.names,
|
||||
"truncated": list.truncated,
|
||||
});
|
||||
println!("{json}");
|
||||
continue;
|
||||
}
|
||||
println!("{label} ({}):", list.names.len());
|
||||
for name in &list.names {
|
||||
println!(" {name}");
|
||||
}
|
||||
if list.truncated {
|
||||
println!(" ... more than fit in one answer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A topic and node's latest message, if any.
|
||||
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> {
|
||||
let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
|
||||
Ok(latest.messages.into_iter().next_back())
|
||||
}
|
||||
|
||||
/// Connects with the settings in `config`.
|
||||
fn connect(config: &Path) -> Result<Client, String> {
|
||||
let text = fs::read_to_string(config).map_err(|error| {
|
||||
format!(
|
||||
"Can't read {}: {error} (the client's settings, see --help)",
|
||||
config.display()
|
||||
)
|
||||
})?;
|
||||
let settings: ClientToml =
|
||||
toml::from_str(&text).map_err(|error| format!("{}: {error}", config.display()))?;
|
||||
let folder = config.parent().unwrap_or(Path::new(""));
|
||||
let pem = |what: &str, path: &Path| {
|
||||
let path = folder.join(path);
|
||||
fs::read_to_string(&path)
|
||||
.map_err(|error| format!("Can't read the {what} {}: {error}", path.display()))
|
||||
};
|
||||
let ca = pem("CA's certificate", &settings.ca)?;
|
||||
let certificate = pem("certificate", &settings.certificate)?;
|
||||
let key = pem("key", &settings.key)?;
|
||||
let crl = settings
|
||||
.crl
|
||||
.as_deref()
|
||||
.map(|path| pem("CRL", path))
|
||||
.transpose()?;
|
||||
let pems = Settings {
|
||||
ca: &ca,
|
||||
certificate: &certificate,
|
||||
key: &key,
|
||||
crl: crl.as_deref(),
|
||||
};
|
||||
Client::connect(&settings.server, &pems).map_err(|error| {
|
||||
format!(
|
||||
"Failed to connect to {} ({}): {}",
|
||||
settings.server,
|
||||
code_name(error.code()),
|
||||
error.message()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// A message or SQL from the command line: as is, `@FILE` for a file's,
|
||||
/// `-` for the standard input's (a UTF-8 BOM dropped).
|
||||
fn input(text: &str) -> Result<String, String> {
|
||||
let read = if text == "-" {
|
||||
let mut read = String::new();
|
||||
io::stdin()
|
||||
.read_to_string(&mut read)
|
||||
.map_err(|error| format!("Can't read the standard input: {error}"))?;
|
||||
read
|
||||
} else if let Some(path) = text.strip_prefix('@') {
|
||||
fs::read_to_string(path).map_err(|error| format!("Can't read {path}: {error}"))?
|
||||
} else {
|
||||
return Ok(text.to_owned());
|
||||
};
|
||||
Ok(match read.strip_prefix('\u{feff}') {
|
||||
Some(rest) => rest.to_owned(),
|
||||
None => read,
|
||||
})
|
||||
}
|
||||
|
||||
fn failed(error: Error) -> String {
|
||||
let what = if is_refusal_code(error.code()) {
|
||||
"Refused by the server"
|
||||
} else {
|
||||
"Failed"
|
||||
};
|
||||
format!("{what} ({}): {}", code_name(error.code()), error.message())
|
||||
}
|
||||
|
||||
fn cant_write(error: io::Error) -> String {
|
||||
format!("Can't write the output: {error}")
|
||||
}
|
||||
|
||||
/// Milliseconds since 1970 as "2026-11-08T14:03:59.123Z".
|
||||
fn utc(ms: u64) -> String {
|
||||
match time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(ms) * 1_000_000) {
|
||||
Ok(t) => format!(
|
||||
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
|
||||
t.year(),
|
||||
u8::from(t.month()),
|
||||
t.day(),
|
||||
t.hour(),
|
||||
t.minute(),
|
||||
t.second(),
|
||||
t.millisecond()
|
||||
),
|
||||
Err(_) => format!("{ms} ms"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
//! `bakashrot` end to end against a server on a free port: the old suites'
|
||||
//! tool checks (GetMessages, Names, BigMessages).
|
||||
|
||||
use bakashrot_client::{Client, Settings};
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Ca, Identity, Usage};
|
||||
use bakashrot_server::Server;
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const CONFIG: &str = r#"
|
||||
[server]
|
||||
listen = "127.0.0.1:0"
|
||||
ca = "ca.crt"
|
||||
certificate = "server.crt"
|
||||
key = "server.key"
|
||||
topics = ["logs", "secret"]
|
||||
synchronous = "normal"
|
||||
|
||||
[roles.home]
|
||||
push_topics = ["logs", "secret"]
|
||||
read_topics = ["*"]
|
||||
query = true
|
||||
|
||||
[roles.lounge]
|
||||
read_topics = ["logs"]
|
||||
"#;
|
||||
|
||||
/// A server in a folder of its own, with `kitchen` (home) and `lounge`
|
||||
/// (lounge) issued: `<name>.crt`, `.key` and `.toml`.
|
||||
struct Running {
|
||||
folder: PathBuf,
|
||||
port: u16,
|
||||
runtime: Option<tokio::runtime::Runtime>,
|
||||
}
|
||||
|
||||
impl Running {
|
||||
fn start(name: &str) -> Running {
|
||||
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("tool-{name}"));
|
||||
let _ = fs::remove_dir_all(&folder);
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
let issued = Ca::create("Test CA", 10).unwrap();
|
||||
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
|
||||
let server = ca
|
||||
.issue(
|
||||
&Identity::new("server-1", &["peer"]).unwrap(),
|
||||
Usage::Server,
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
|
||||
fs::write(folder.join("server.crt"), &server.certificate).unwrap();
|
||||
fs::write(folder.join("server.key"), &server.key).unwrap();
|
||||
fs::write(folder.join("server.toml"), CONFIG).unwrap();
|
||||
let server = Server::start(Config::load(&folder.join("server.toml")).unwrap()).unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let listener = runtime
|
||||
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
|
||||
.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
runtime.spawn(async move { server.serve(listener).await });
|
||||
|
||||
for (name, role) in [("kitchen", "home"), ("lounge", "lounge")] {
|
||||
let issued = ca
|
||||
.issue(&Identity::new(name, &[role]).unwrap(), Usage::Client, 10)
|
||||
.unwrap();
|
||||
fs::write(folder.join(format!("{name}.crt")), &issued.certificate).unwrap();
|
||||
fs::write(folder.join(format!("{name}.key")), &issued.key).unwrap();
|
||||
let toml = format!(
|
||||
"server = \"127.0.0.1:{port}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n"
|
||||
);
|
||||
fs::write(folder.join(format!("{name}.toml")), toml).unwrap();
|
||||
}
|
||||
Running {
|
||||
folder,
|
||||
port,
|
||||
runtime: Some(runtime),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the tool as `who` (`kitchen`, `lounge`).
|
||||
fn tool(&self, who: &str, args: &[&str]) -> Run {
|
||||
run(&self.folder, who, args, None)
|
||||
}
|
||||
|
||||
/// A client of the library's, as kitchen: pushing many is quicker.
|
||||
fn client(&self) -> Client {
|
||||
let read = |name: &str| fs::read_to_string(self.folder.join(name)).unwrap();
|
||||
let (ca, certificate, key) = (read("ca.crt"), read("kitchen.crt"), read("kitchen.key"));
|
||||
let settings = Settings {
|
||||
ca: &ca,
|
||||
certificate: &certificate,
|
||||
key: &key,
|
||||
crl: None,
|
||||
};
|
||||
Client::connect(&format!("127.0.0.1:{}", self.port), &settings).unwrap()
|
||||
}
|
||||
|
||||
/// Stops the server: its connections close.
|
||||
fn stop(&mut self) {
|
||||
if let Some(runtime) = self.runtime.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a run printed, and its exit code.
|
||||
#[derive(Debug)]
|
||||
struct Run {
|
||||
code: i32,
|
||||
out: String,
|
||||
err: String,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn lines(&self) -> Vec<&str> {
|
||||
self.out.lines().collect()
|
||||
}
|
||||
|
||||
/// The ids `messages` printed.
|
||||
fn ids(&self) -> Vec<u64> {
|
||||
self.lines()
|
||||
.iter()
|
||||
.filter_map(|line| line.split('\t').next()?.parse().ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn ok(&self) -> &Run {
|
||||
assert_eq!(self.code, 0, "{self:?}");
|
||||
self
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn fails(&self, code: i32, text: &str) {
|
||||
assert_eq!(self.code, code, "{self:?}");
|
||||
assert!(self.err.contains(text), "expected '{text}': {self:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run(folder: &Path, who: &str, args: &[&str], stdin: Option<&str>) -> Run {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_bakashrot"))
|
||||
.args(["-c", &format!("{who}.toml")])
|
||||
.args(args)
|
||||
.current_dir(folder)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut input = child.stdin.take().unwrap();
|
||||
if let Some(text) = stdin {
|
||||
input.write_all(text.as_bytes()).unwrap();
|
||||
}
|
||||
drop(input);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
Run {
|
||||
code: output.status.code().unwrap_or(-1),
|
||||
out: String::from_utf8(output.stdout).unwrap(),
|
||||
err: String::from_utf8(output.stderr).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn range(from: u64, to: u64) -> Vec<u64> {
|
||||
(from..=to).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pushes_and_latest() {
|
||||
let server = Running::start("push");
|
||||
let push = |args: &[&str]| server.tool("kitchen", &[&["push"], args].concat());
|
||||
|
||||
assert_eq!(
|
||||
push(&["logs", r#"{"t":21,"room":"kitchen"}"#]).ok().out,
|
||||
"Pushed as message #1\n"
|
||||
);
|
||||
fs::write(server.folder.join("m.json"), "\u{feff}{\"from\":\"file\"}").unwrap();
|
||||
assert_eq!(
|
||||
push(&["logs", "@m.json"]).ok().out,
|
||||
"Pushed as message #2\n"
|
||||
);
|
||||
let piped = run(
|
||||
&server.folder,
|
||||
"kitchen",
|
||||
&["push", "logs", "-"],
|
||||
Some("piped\ntext"),
|
||||
);
|
||||
assert_eq!(piped.ok().out, "Pushed as message #3\n");
|
||||
assert_eq!(push(&["secret", "{}"]).ok().out, "Pushed as message #1\n");
|
||||
|
||||
let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]);
|
||||
let lines = latest.ok().lines();
|
||||
assert!(
|
||||
lines[0].starts_with("Message logs:kitchen#3, pushed 20"),
|
||||
"{lines:?}"
|
||||
);
|
||||
assert!(
|
||||
lines[0].ends_with('Z')
|
||||
&& lines[0].len() == "Message logs:kitchen#3, pushed 2026-11-08T14:03:59.123Z".len()
|
||||
);
|
||||
assert_eq!(lines[1..], ["piped", "text"]);
|
||||
let messages = server.tool("kitchen", &["messages", "logs", "kitchen"]);
|
||||
assert_eq!(
|
||||
messages.ok().lines()[..2],
|
||||
[r#"1 {"t":21,"room":"kitchen"}"#, r#"2 {"from":"file"}"#]
|
||||
);
|
||||
|
||||
// Refusals, the client's own failures.
|
||||
server
|
||||
.tool("lounge", &["push", "logs", "{}"])
|
||||
.fails(1, "Refused by the server (NotAllowed)");
|
||||
push(&["nope", "{}"]).fails(1, "Refused by the server (UnknownName): ");
|
||||
push(&["bad name!", "{}"]).fails(1, "Failed (InvalidArgument)");
|
||||
push(&["logs", "@missing.json"]).fails(1, "Can't read missing.json");
|
||||
let big = "x".repeat(bakashrot_proto::limits::MAX_MESSAGE_SIZE + 1);
|
||||
fs::write(server.folder.join("big.txt"), big).unwrap();
|
||||
push(&["logs", "@big.txt"]).fails(1, "Failed (");
|
||||
server
|
||||
.tool("lounge", &["latest", "logs", "lounge"])
|
||||
.fails(1, "No message yet in logs:lounge");
|
||||
server
|
||||
.tool("lounge", &["latest", "secret", "kitchen"])
|
||||
.fails(1, "(NotAllowed)");
|
||||
server
|
||||
.tool("kitchen", &["push", "logs"])
|
||||
.fails(2, "MESSAGE");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages() {
|
||||
let server = Running::start("messages");
|
||||
assert!(
|
||||
server
|
||||
.tool("kitchen", &["messages", "logs", "kitchen"])
|
||||
.ok()
|
||||
.out
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
server
|
||||
.tool(
|
||||
"kitchen",
|
||||
&["messages", "logs", "kitchen", "--after", "latest"]
|
||||
)
|
||||
.ok()
|
||||
.out
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let mut client = server.client();
|
||||
for i in 1..=120 {
|
||||
client.push("logs", &format!(r#"{{"i":{i}}}"#)).unwrap();
|
||||
}
|
||||
let messages = |who: &str, args: &[&str]| server.tool(who, &[&["messages"], args].concat());
|
||||
|
||||
let first = messages("kitchen", &["logs", "kitchen"]);
|
||||
assert_eq!(first.ok().ids(), range(1, 100), "the first 100 by default");
|
||||
assert_eq!(first.lines()[0], r#"1 {"i":1}"#);
|
||||
assert_eq!(first.lines()[99], r#"100 {"i":100}"#);
|
||||
assert_eq!(
|
||||
messages("kitchen", &["logs", "kitchen", "--limit", "0"])
|
||||
.ok()
|
||||
.ids(),
|
||||
range(1, 120)
|
||||
);
|
||||
assert_eq!(
|
||||
messages("kitchen", &["logs", "kitchen", "--after", "115"])
|
||||
.ok()
|
||||
.ids(),
|
||||
range(116, 120)
|
||||
);
|
||||
assert_eq!(
|
||||
messages(
|
||||
"kitchen",
|
||||
&["logs", "kitchen", "--after", "10", "--limit", "7"]
|
||||
)
|
||||
.ok()
|
||||
.ids(),
|
||||
range(11, 17)
|
||||
);
|
||||
assert!(
|
||||
messages("kitchen", &["logs", "kitchen", "--after", "120"])
|
||||
.ok()
|
||||
.out
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
messages("kitchen", &["logs", "kitchen", "--after", "LATEST"])
|
||||
.ok()
|
||||
.out
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
messages("kitchen", &["LOGS", "Kitchen", "--after", "118"])
|
||||
.ok()
|
||||
.ids(),
|
||||
range(119, 120)
|
||||
);
|
||||
assert_eq!(
|
||||
messages("lounge", &["logs", "kitchen", "--after", "100"])
|
||||
.ok()
|
||||
.ids(),
|
||||
range(101, 120)
|
||||
);
|
||||
let timed = messages("kitchen", &["logs", "kitchen", "--after", "119", "--time"]);
|
||||
let fields: Vec<&str> = timed.ok().out.trim_end().split('\t').collect();
|
||||
assert_eq!(
|
||||
(fields[0], fields[2], fields[1].len()),
|
||||
("120", r#"{"i":120}"#, 24),
|
||||
"{fields:?}"
|
||||
);
|
||||
|
||||
client.push("secret", "{}").unwrap();
|
||||
assert_eq!(messages("kitchen", &["secret", "kitchen"]).ok().ids(), [1]);
|
||||
messages("lounge", &["secret", "kitchen"]).fails(1, "(NotAllowed)");
|
||||
messages("kitchen", &["logs", "nobody"]).fails(1, "(UnknownName)");
|
||||
messages("kitchen", &["nothing", "kitchen"]).fails(1, "(UnknownName)");
|
||||
assert!(
|
||||
messages("lounge", &["logs", "lounge"]).ok().out.is_empty(),
|
||||
"its own node, none yet"
|
||||
);
|
||||
messages("kitchen", &["logs", "kitchen", "--after", "soon"])
|
||||
.fails(2, "a message id or \"latest\"");
|
||||
messages("kitchen", &["logs", "kitchen", "--nope"]).fails(2, "--nope");
|
||||
messages("kitchen", &["logs", "kitchen", "--interval", "5"]).fails(2, "--interval");
|
||||
|
||||
// As stored: not JSON, a line break spanning lines; big ones over
|
||||
// several answers.
|
||||
client.push("logs", "plain\ntext").unwrap();
|
||||
let big: Vec<String> = (0..5)
|
||||
.map(|i| format!("{i}{}", "y".repeat(600_000)))
|
||||
.collect();
|
||||
for data in &big {
|
||||
client.push("logs", data).unwrap();
|
||||
}
|
||||
let read = messages("kitchen", &["logs", "kitchen", "--after", "120"]);
|
||||
let lines = read.ok().lines();
|
||||
assert_eq!(lines[..2], ["121\tplain", "text"]);
|
||||
for (i, data) in big.iter().enumerate() {
|
||||
assert_eq!(lines[2 + i], format!("{}\t{data}", 122 + i));
|
||||
}
|
||||
assert_eq!(
|
||||
messages(
|
||||
"kitchen",
|
||||
&["logs", "kitchen", "--after", "121", "--limit", "2"]
|
||||
)
|
||||
.ok()
|
||||
.ids(),
|
||||
[122, 123]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows() {
|
||||
let mut server = Running::start("follow");
|
||||
let mut client = server.client();
|
||||
client.push("logs", "old").unwrap();
|
||||
|
||||
let mut follower = Command::new(env!("CARGO_BIN_EXE_bakashrot"))
|
||||
.args([
|
||||
"-c",
|
||||
"lounge.toml",
|
||||
"messages",
|
||||
"logs",
|
||||
"kitchen",
|
||||
"-f",
|
||||
"--after",
|
||||
"latest",
|
||||
"--interval",
|
||||
"20",
|
||||
])
|
||||
.current_dir(&server.folder)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let (lines, read) = mpsc::channel();
|
||||
let stdout = follower.stdout.take().unwrap();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let _ = lines.send(line.unwrap());
|
||||
}
|
||||
});
|
||||
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
assert!(
|
||||
follower.try_wait().unwrap().is_none(),
|
||||
"keeps running once caught up"
|
||||
);
|
||||
for i in 1..=3 {
|
||||
client.push("logs", &format!("new {i}")).unwrap();
|
||||
}
|
||||
let got: Vec<String> = (0..3)
|
||||
.map(|_| read.recv_timeout(Duration::from_secs(10)).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
["2\tnew 1", "3\tnew 2", "4\tnew 3"],
|
||||
"only the new ones"
|
||||
);
|
||||
|
||||
drop(client);
|
||||
server.stop();
|
||||
let started = Instant::now();
|
||||
let status = loop {
|
||||
if let Some(status) = follower.try_wait().unwrap() {
|
||||
break status;
|
||||
}
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(20),
|
||||
"still following"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
};
|
||||
assert_eq!(status.code(), Some(1), "fails once the server is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queries_and_lists() {
|
||||
let server = Running::start("query");
|
||||
server.client().push("logs", r#"{"t":1}"#).unwrap();
|
||||
|
||||
let query = server.tool("kitchen", &["query", "SELECT 1 AS one"]);
|
||||
assert_eq!(
|
||||
query.ok().out,
|
||||
"{\"columns\":[\"one\"],\"rows\":[[\"1\"]]}\n"
|
||||
);
|
||||
fs::write(server.folder.join("q.sql"), r#"SELECT "two" AS "a b""#).unwrap();
|
||||
assert!(
|
||||
server
|
||||
.tool("kitchen", &["query", "@q.sql"])
|
||||
.ok()
|
||||
.out
|
||||
.contains(r#""a b""#)
|
||||
);
|
||||
let piped = run(&server.folder, "kitchen", &["query", "-"], Some("SELECT 3"));
|
||||
assert!(piped.ok().out.contains(r#"[["3"]]"#), "{piped:?}");
|
||||
server
|
||||
.tool("lounge", &["query", "SELECT 1"])
|
||||
.fails(1, "(NotAllowed)");
|
||||
server
|
||||
.tool("kitchen", &["query", "DELETE FROM messages"])
|
||||
.fails(1, "(QueryFailed)");
|
||||
|
||||
let all = server.tool("kitchen", &["list"]);
|
||||
assert_eq!(
|
||||
all.ok().out,
|
||||
"Topics (2):\n logs\n secret\nNodes (1):\n kitchen\n"
|
||||
);
|
||||
assert_eq!(
|
||||
server.tool("lounge", &["list", "topics"]).ok().out,
|
||||
"Topics (1):\n logs\n"
|
||||
);
|
||||
let json = server.tool("kitchen", &["list", "nodes", "--json"]);
|
||||
assert_eq!(
|
||||
json.ok().out,
|
||||
"{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n"
|
||||
);
|
||||
server
|
||||
.tool("kitchen", &["list", "everything"])
|
||||
.fails(2, "everything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attachments() {
|
||||
let server = Running::start("attachments");
|
||||
let photo: Vec<u8> = (0..2_500_000u32).map(|i| (i % 253) as u8).collect();
|
||||
fs::write(server.folder.join("photo.jpg"), &photo).unwrap();
|
||||
|
||||
let pushed = server.tool(
|
||||
"kitchen",
|
||||
&["push", "logs", r#"{"photo":1}"#, "-a", "photo.jpg"],
|
||||
);
|
||||
assert_eq!(
|
||||
pushed.ok().out,
|
||||
"Pushed as message #1, with an attachment of 2500000 bytes\n"
|
||||
);
|
||||
server.tool("kitchen", &["push", "logs", "{}"]).ok();
|
||||
server
|
||||
.tool(
|
||||
"kitchen",
|
||||
&["push", "logs", "{}", "--attachment", "missing.jpg"],
|
||||
)
|
||||
.fails(1, "Can't read missing.jpg");
|
||||
|
||||
let saved = server.tool(
|
||||
"lounge",
|
||||
&["attachment", "logs", "kitchen", "1", "copy.jpg"],
|
||||
);
|
||||
assert_eq!(saved.ok().out, "Saved 2500000 bytes as copy.jpg\n");
|
||||
assert_eq!(fs::read(server.folder.join("copy.jpg")).unwrap(), photo);
|
||||
server
|
||||
.tool(
|
||||
"lounge",
|
||||
&["attachment", "logs", "kitchen", "2", "none.jpg"],
|
||||
)
|
||||
.fails(
|
||||
1,
|
||||
"Refused by the server (NotFound): no attachment for logs:kitchen#2",
|
||||
);
|
||||
assert!(
|
||||
!server.folder.join("none.jpg").exists(),
|
||||
"a refused one leaves no file"
|
||||
);
|
||||
|
||||
let mut client = server.client();
|
||||
client.push("logs", "{}").unwrap();
|
||||
let mut tiny = std::io::Cursor::new(b"tiny".to_vec());
|
||||
client
|
||||
.push_with_attachment("logs", "last", &mut tiny)
|
||||
.unwrap();
|
||||
let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]);
|
||||
let lines = latest.ok().lines();
|
||||
assert!(lines[0].starts_with("Message logs:kitchen#4,"), "{lines:?}");
|
||||
assert_eq!(lines[1..], ["Attachment: 4 bytes", "last"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings() {
|
||||
let server = Running::start("settings");
|
||||
let folder = &server.folder;
|
||||
run(folder, "nobody", &["list"], None).fails(1, "Can't read nobody.toml");
|
||||
|
||||
// Paths are relative to the file's folder, wherever it runs from.
|
||||
fs::create_dir_all(folder.join("elsewhere")).unwrap();
|
||||
let up = run(
|
||||
&folder.join("elsewhere"),
|
||||
"../kitchen",
|
||||
&["list", "topics"],
|
||||
None,
|
||||
);
|
||||
assert_eq!(up.ok().out, "Topics (2):\n logs\n secret\n");
|
||||
|
||||
let kitchen = fs::read_to_string(folder.join("kitchen.toml")).unwrap();
|
||||
fs::write(
|
||||
folder.join("typo.toml"),
|
||||
kitchen.replace("certificate =", "certficate ="),
|
||||
)
|
||||
.unwrap();
|
||||
run(folder, "typo", &["list"], None).fails(1, "certficate");
|
||||
fs::write(
|
||||
folder.join("crl.toml"),
|
||||
format!("{kitchen}crl = \"none.crl\"\n"),
|
||||
)
|
||||
.unwrap();
|
||||
run(folder, "crl", &["list"], None).fails(1, "Can't read the CRL");
|
||||
let closed = kitchen.replace(&server.port.to_string(), "1");
|
||||
fs::write(folder.join("closed.toml"), closed).unwrap();
|
||||
run(folder, "closed", &["list"], None)
|
||||
.fails(1, "Failed to connect to 127.0.0.1:1 (ConnectFailed)");
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! `bakashrot-cert` end to end, in a folder of the build's.
|
||||
|
||||
use bakashrot_pki::{Revocations, summarize};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
|
||||
let _ = fs::remove_dir_all(&folder);
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
folder
|
||||
}
|
||||
|
||||
/// Runs the tool in `folder`: whether it succeeded, and what it printed.
|
||||
fn cert(folder: &Path, args: &[&str]) -> (bool, String) {
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_bakashrot-cert"))
|
||||
.args(args)
|
||||
.current_dir(folder)
|
||||
.output()
|
||||
.unwrap();
|
||||
let text = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
(output.status.success(), text)
|
||||
}
|
||||
|
||||
fn read(folder: &Path, name: &str) -> String {
|
||||
fs::read_to_string(folder.join(name)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ca_issues_and_revokes() {
|
||||
let folder = folder("cert-tool");
|
||||
let (ok, text) = cert(&folder, &["ca", "--name", "Test CA"]);
|
||||
assert!(ok, "{text}");
|
||||
if bakashrot_pki::IDENTITY_OID_IS_PLACEHOLDER {
|
||||
assert!(text.contains("OID is still a placeholder"), "{text}");
|
||||
}
|
||||
assert!(
|
||||
cert(
|
||||
&folder,
|
||||
&[
|
||||
"issue", "--name", "kitchen", "--role", "sensor", "--role", "reader"
|
||||
]
|
||||
)
|
||||
.0
|
||||
);
|
||||
assert!(cert(&folder, &["issue", "--name", "garage"]).0);
|
||||
assert!(
|
||||
cert(
|
||||
&folder,
|
||||
&["issue", "--name", "server-1", "--role", "peer", "--server"]
|
||||
)
|
||||
.0
|
||||
);
|
||||
|
||||
let (ok, text) = cert(&folder, &["show", "kitchen.crt"]);
|
||||
assert!(ok, "{text}");
|
||||
assert!(
|
||||
text.contains("name: kitchen") && text.contains("roles: sensor, reader"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("usage: client") && text.contains("issuer: Test CA"),
|
||||
"{text}"
|
||||
);
|
||||
let (_, text) = cert(&folder, &["show", "server-1.crt"]);
|
||||
assert!(text.contains("usage: server"), "{text}");
|
||||
let (_, text) = cert(&folder, &["show", "ca.crt"]);
|
||||
assert!(text.contains("usage: CA"), "{text}");
|
||||
|
||||
// Revoking twice keeps the first.
|
||||
assert!(cert(&folder, &["revoke", "kitchen.crt"]).0);
|
||||
let (ok, text) = cert(&folder, &["revoke", "garage.crt", "kitchen.crt"]);
|
||||
assert!(ok && text.contains("(2 revoked)"), "{text}");
|
||||
let revocations =
|
||||
Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap();
|
||||
assert_eq!(revocations.len(), 2);
|
||||
for (name, revoked) in [("kitchen", true), ("garage", true), ("server-1", false)] {
|
||||
let serial = summarize(&read(&folder, &format!("{name}.crt")))
|
||||
.unwrap()
|
||||
.serial;
|
||||
assert_eq!(
|
||||
revocations.serials().any(|s| s == serial),
|
||||
revoked,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert!(!folder.join("ca.crl.new").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_can_have_several_certificates() {
|
||||
let folder = folder("cert-tool-same-name");
|
||||
assert!(cert(&folder, &["ca", "--name", "Test CA"]).0);
|
||||
let server = ["issue", "--name", "server-1", "--role", "peer", "--server"];
|
||||
assert!(cert(&folder, &server).0);
|
||||
assert!(!cert(&folder, &server).0, "server-1.crt is there already");
|
||||
let (ok, text) = cert(&folder, &[&server[..], &["--file", "server-1b"]].concat());
|
||||
assert!(ok, "{text}");
|
||||
|
||||
let first = summarize(&read(&folder, "server-1.crt")).unwrap();
|
||||
let second = summarize(&read(&folder, "server-1b.crt")).unwrap();
|
||||
assert_eq!(first.identity, second.identity);
|
||||
assert_ne!(first.serial, second.serial);
|
||||
|
||||
// Revoking one leaves the other.
|
||||
assert!(cert(&folder, &["revoke", "server-1b.crt"]).0);
|
||||
let revocations =
|
||||
Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap();
|
||||
assert!(revocations.serials().any(|s| s == second.serial));
|
||||
assert!(!revocations.serials().any(|s| s == first.serial));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_overwritten_or_mixed_up() {
|
||||
let folder = folder("cert-tool-refusals");
|
||||
assert!(cert(&folder, &["ca", "--name", "Test CA"]).0);
|
||||
let key = read(&folder, "ca.key");
|
||||
let (ok, text) = cert(&folder, &["ca", "--name", "Another"]);
|
||||
assert!(!ok, "{text}");
|
||||
assert_eq!(read(&folder, "ca.key"), key, "the CA's key is still there");
|
||||
|
||||
assert!(cert(&folder, &["issue", "--name", "kitchen"]).0);
|
||||
assert!(
|
||||
!cert(&folder, &["issue", "--name", "kitchen"]).0,
|
||||
"already there"
|
||||
);
|
||||
assert!(!cert(&folder, &["issue", "--name", "12"]).0, "not a name");
|
||||
assert!(
|
||||
!cert(&folder, &["issue", "--name", "garage", "--role", "a b"]).0,
|
||||
"not a role"
|
||||
);
|
||||
|
||||
// A certificate of another CA isn't revoked by this one.
|
||||
let other = folder.join("other");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
assert!(cert(&other, &["ca", "--name", "Other CA"]).0);
|
||||
assert!(cert(&other, &["issue", "--name", "stranger"]).0);
|
||||
let (ok, text) = cert(&folder, &["revoke", "other/stranger.crt"]);
|
||||
assert!(!ok && text.contains("not issued by this CA"), "{text}");
|
||||
assert!(!folder.join("ca.crl").exists());
|
||||
|
||||
let (ok, text) = cert(&folder, &["show", "missing.crt"]);
|
||||
assert!(!ok && text.contains("missing.crt"), "{text}");
|
||||
}
|
||||
Reference in New Issue
Block a user