1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image

Source/'s content is at the root now, Source/README.md merged into
readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1),
release.ps1 (over release.py) and clean.ps1. Everything is LF except the
.ps1 files.

CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks,
then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on
its own kind of runner, the archives kept as artifacts. release.py names
the platform from the Rust host, make_wheel.py tags the wheel from the
library's header.

docker/: the server's image (built from source, the tools beside it, uid
10001), compose.yml and test.sh. CI builds amd64 and arm64 natively,
checks them, and on a tag pushes them to ghcr.io with an index for
<version> and latest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 01:13:44 +01:00
parent 17ec69c03c
commit 5045019df4
93 changed files with 634 additions and 277 deletions
@@ -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 `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 \
(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(())
}
+388
View File
@@ -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
//! `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"),
}
}