1
0
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:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "bakashrot-config"
description = "BakaShrot's server config: topics, retention, replication, roles and what they may do."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# The name rules, the limits.
bakashrot-proto = { path = "../bakashrot-proto" }
# Sections kept in the file's order ([retention]'s first matching pattern
# wins): toml's `preserve_order` reads them in order, IndexMap keeps it.
indexmap = { version = "2.14.2", features = ["serde"] }
serde = { version = "1.0.229", features = ["derive"] }
# Reading only (`display`: values quoted back in errors).
toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde", "display", "preserve_order"] }
[lints]
workspace = true
@@ -0,0 +1,67 @@
# A BakaShrot server's config, every key with its default where it has
# one. Read by bakashrot-config, explained in Source/docs/config.md.
#
# Names (topics, nodes, roles): 1-64 of A-Z a-z 0-9 _ . -, not only digits,
# case doesn't matter. Lists of topics or nodes also take patterns: * any
# characters, ? one ("sensors.*"), or "*" for all.
# Names with dots are quoted when they're keys: "sensors.kitchen" = "12h",
# [roles."site.reader"]. Durations: numbers with a unit (s m h d w), like
# "30s" or "1d12h". Relative paths are from this file's folder.
[server]
listen = "0.0.0.0:7000" # required: address and port
# The certificates (bakashrot-cert), required. The node this server is,
# for its peers, is its certificate's name.
ca = "ca.crt"
certificate = "server-1.crt"
key = "server-1.key"
# crl = "ca.crl" # the CA's CRL, watched: optional
database = "bakashrot.sqlite"
# The topics clients push to. Peers may bring others (accept_topics).
topics = ["logs", "sensors.kitchen", "sensors.garage"]
# "full": every push flushed to disk before it's answered, it survives a
# power loss. "normal": about twice the pushes, a power loss loses the last
# second or so. ("off" isn't allowed.)
synchronous = "full"
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
retention_interval = "1m" # how often old messages are deleted
# How long each topic's messages are kept, from when they were first
# pushed. A topic takes its name's line, else the first pattern matching
# it, else "*"'s; without any, it's kept forever.
[retention]
logs = "30d"
"sensors.*" = "12h"
"*" = "forever"
[replication]
peers = [] # dialed: ["10.0.0.2:7000", "server-2.lan:7000"]
# The only topics replicated at all, whatever the roles say: a filter for
# edge nodes. Without it, no filter; [] replicates nothing.
# replicated_topics = ["logs", "alerts.*"]
retry_delay = "10s"
sync_interval = "5s"
batch_size = 100 # messages per packet, 1-10000
# What certificates with a role may do. A certificate gets everything its
# roles allow; one without any role listed here is refused. Every key is
# optional: an empty list allows nothing.
[roles.sensor]
push_topics = ["sensors.*"] # always as its own node (its name)
[roles.dashboard]
read_topics = ["*"]
query = true # read-only SQL, reads every topic
# Peers are roles too: what's replicated with a server whose certificate
# has this role, whichever end dials.
[roles.peer]
send_topics = ["logs", "sensors.*"]
accept_topics = ["logs"]
send_nodes = ["*"] # the default
accept_nodes = ["*"] # the default
+317
View File
@@ -0,0 +1,317 @@
//! The server's config: a TOML file, read and checked in one go.
//!
//! - [`Server`]: where it listens, its files, its topics, its database.
//! - [`Retention`]: how long each topic's messages are kept.
//! - [`Replication`]: the peers it dials, what it replicates, how often.
//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what
//! a certificate's roles allow together.
//!
//! Who connects is the certificate's (`bakashrot-pki`): its name is its
//! node, its roles are looked up here. Peers too: what's replicated with a
//! peer is its roles'. The file, every key and its default:
//! `Source/docs/config.md`.
//!
//! Every value is checked as serde reads it, so a wrong one is refused with
//! its line.
mod roles;
mod values;
pub use roles::{NameList, Permissions, Role};
use bakashrot_proto::names::{is_valid_name, is_valid_pattern, names_equal, pattern_matches};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, de::Error as _};
use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use values::{DURATION_HELP, NAME_HELP, parse_age};
/// What's wrong with a config, in words: where (the file, the line) and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// A server's config.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// `[server]`.
pub server: Server,
/// `[retention]`.
#[serde(default)]
pub retention: Retention,
/// `[replication]`.
#[serde(default)]
pub replication: Replication,
/// `[roles.<name>]`, in the file's order.
#[serde(default, deserialize_with = "roles")]
pub roles: Vec<Role>,
}
/// `[server]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Server {
/// The address and port it listens on.
#[serde(deserialize_with = "values::listen")]
pub listen: SocketAddr,
/// The CA's certificate.
pub ca: PathBuf,
/// The server's certificate.
pub certificate: PathBuf,
/// The server's key.
pub key: PathBuf,
/// The CA's CRL, watched; none: nothing revoked.
#[serde(default)]
pub crl: Option<PathBuf>,
/// The SQLite database; `bakashrot.sqlite` by default.
#[serde(default = "defaults::database")]
pub database: PathBuf,
/// The topics clients push to, by name.
#[serde(default, deserialize_with = "values::topic_names")]
pub topics: Vec<String>,
/// How hard a push is made sure to be on disk.
#[serde(default)]
pub synchronous: Synchronous,
/// The biggest attachment taken, in bytes; 0: none. 1G by default.
#[serde(
default = "defaults::max_attachment_size",
deserialize_with = "values::size"
)]
pub max_attachment_size: u64,
/// How often messages past their age are deleted; 1m by default.
#[serde(
default = "defaults::retention_interval",
deserialize_with = "values::duration"
)]
pub retention_interval: Duration,
}
impl Server {
/// Whether `topic` is one of its topics.
pub fn has_topic(&self, topic: &str) -> bool {
self.topics.iter().any(|own| names_equal(own, topic))
}
}
/// How hard the database makes sure a push is on disk before answering it
/// (SQLite's `synchronous`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub enum Synchronous {
/// Every commit flushed: an answered push survives a power loss. The
/// default.
#[default]
Full,
/// Flushed about once a second: faster, a power loss loses the last
/// second or so of answered pushes.
Normal,
}
impl TryFrom<String> for Synchronous {
type Error = String;
fn try_from(text: String) -> std::result::Result<Self, String> {
match text.trim().to_ascii_lowercase().as_str() {
"full" => Ok(Synchronous::Full),
"normal" => Ok(Synchronous::Normal),
"off" => Err(
"\"off\" isn't allowed: a power loss could corrupt the database. \
\"full\", or \"normal\" to only risk the last second of messages"
.into(),
),
"extra" => Err("\"extra\" does nothing more than \"full\" here: write \"full\"".into()),
_ => Err(format!("'{text}' isn't \"full\" or \"normal\"")),
}
}
}
/// `[retention]`: how long each topic's messages are kept, from when they
/// were first pushed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "IndexMap<String, toml::Value>")]
pub struct Retention {
/// Names and patterns with their age (none: forever), in the file's
/// order.
lines: Vec<(String, Option<Duration>)>,
}
impl TryFrom<IndexMap<String, toml::Value>> for Retention {
type Error = String;
fn try_from(table: IndexMap<String, toml::Value>) -> std::result::Result<Self, String> {
let mut lines: Vec<(String, Option<Duration>)> = Vec::with_capacity(table.len());
for (key, value) in table {
if !is_valid_pattern(&key) && !is_valid_name(&key) {
return Err(format!(
"'{key}' isn't a topic name or a pattern ({NAME_HELP})"
));
}
if lines.iter().any(|(before, _)| names_equal(before, &key)) {
return Err(format!("'{key}' is given twice"));
}
let age = match &value {
toml::Value::String(text) => parse_age(text),
toml::Value::Table(_) => {
return Err(format!(
"'{key}' is a table: quote names with dots, \"{key}.x\" = \"30d\""
));
}
_ => None,
};
let age = age.ok_or_else(|| {
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"")
})?;
lines.push((key, age));
}
Ok(Retention { lines })
}
}
impl Retention {
/// How long `topic`'s messages are kept, `None` for forever: its name's
/// line, else the first pattern matching it, else `*`'s, else forever.
pub fn age(&self, topic: &str) -> Option<Duration> {
let line = |found: fn(&str, &str) -> bool| {
self.lines
.iter()
.find(|(key, _)| key != "*" && found(key, topic))
};
line(names_equal)
.or_else(|| line(|key, topic| is_valid_pattern(key) && pattern_matches(key, topic)))
.or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
.and_then(|(_, age)| *age)
}
}
/// `[replication]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Replication {
/// The peers it dials (`host:port`); peers dialing in come by
/// themselves. What's replicated with each is its roles'.
#[serde(deserialize_with = "values::peers")]
pub peers: Vec<String>,
/// The only topics replicated at all, whatever the roles say (an edge
/// node's filter); none: no filter.
pub replicated_topics: Option<NameList>,
/// How long to wait before dialing a peer again; 10s by default.
#[serde(deserialize_with = "values::duration")]
pub retry_delay: Duration,
/// How often a linked peer is sent what it misses; 5s by default.
#[serde(deserialize_with = "values::duration")]
pub sync_interval: Duration,
/// The most messages sent to a peer per packet; 100 by default.
#[serde(deserialize_with = "values::batch_size")]
pub batch_size: u32,
}
impl Default for Replication {
fn default() -> Self {
Replication {
peers: Vec::new(),
replicated_topics: None,
retry_delay: Duration::from_secs(10),
sync_interval: Duration::from_secs(5),
batch_size: 100,
}
}
}
/// `[server]`'s defaults.
mod defaults {
use std::path::PathBuf;
use std::time::Duration;
pub(crate) fn database() -> PathBuf {
"bakashrot.sqlite".into()
}
pub(crate) fn max_attachment_size() -> u64 {
1 << 30
}
pub(crate) fn retention_interval() -> Duration {
Duration::from_secs(60)
}
}
/// `[roles.*]`: each section's name is its role's, none twice.
fn roles<'de, D: Deserializer<'de>>(reader: D) -> std::result::Result<Vec<Role>, D::Error> {
let table = IndexMap::<String, Role>::deserialize(reader)?;
let mut roles: Vec<Role> = Vec::with_capacity(table.len());
for (name, mut role) in table {
if !is_valid_name(&name) {
return Err(D::Error::custom(format!(
"'{name}' isn't a role name ({NAME_HELP})"
)));
}
if let Some(before) = roles.iter().find(|role| names_equal(&role.name, &name)) {
return Err(D::Error::custom(format!(
"'{}' and '{name}' are the same role (case doesn't matter)",
before.name
)));
}
role.name = name;
roles.push(role);
}
Ok(roles)
}
impl Config {
/// Reads the config file at `path`. Relative paths in it are from its
/// folder.
pub fn load(path: &Path) -> Result<Config> {
let in_file = |error: &dyn fmt::Display| Error(format!("{}: {error}", path.display()));
let text = std::fs::read_to_string(path).map_err(|error| in_file(&error))?;
let mut config = Config::parse(&text).map_err(|error| in_file(&error))?;
let folder = path.parent().unwrap_or(Path::new(""));
let server = &mut config.server;
for file in [
&mut server.ca,
&mut server.certificate,
&mut server.key,
&mut server.database,
]
.into_iter()
.chain(server.crl.as_mut())
{
*file = folder.join(&*file);
}
Ok(config)
}
/// Reads a config, paths as they're written.
pub fn parse(text: &str) -> Result<Config> {
toml::from_str(text).map_err(|error| Error(error.to_string().trim_end().to_owned()))
}
/// What a certificate with these roles may do: everything its roles
/// with a section allow. `None` if none has one: it's refused.
pub fn permissions<S: AsRef<str>>(&self, roles: &[S]) -> Option<Permissions> {
let roles: Vec<Role> = self
.roles
.iter()
.filter(|role| {
roles
.iter()
.any(|own| names_equal(own.as_ref(), &role.name))
})
.cloned()
.collect();
(!roles.is_empty()).then(|| Permissions {
roles,
replicated_topics: self.replication.replicated_topics.clone(),
})
}
}
+143
View File
@@ -0,0 +1,143 @@
//! Roles, and what a certificate's roles allow together.
use crate::values::check_names;
use bakashrot_proto::names::{names_equal, pattern_matches};
use serde::Deserialize;
/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "Vec<String>")]
pub struct NameList(Vec<String>);
impl TryFrom<Vec<String>> for NameList {
type Error = String;
fn try_from(list: Vec<String>) -> Result<Self, String> {
check_names(&list, true)?;
Ok(NameList(list))
}
}
impl NameList {
/// `*`: every name.
pub fn every() -> NameList {
NameList(vec!["*".to_owned()])
}
/// Whether `name` is in it: one of its names, or matched by one of its
/// patterns (without case).
pub fn matches(&self, name: &str) -> bool {
self.0
.iter()
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
}
/// Whether it has nothing: matches nothing.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Its names and patterns, as written.
pub fn entries(&self) -> &[String] {
&self.0
}
}
/// A `[roles.<name>]` section: what certificates with this role may do.
/// Every key is optional.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Role {
/// The role, as certificates say it (compared without case): the
/// section's name.
#[serde(skip)]
pub name: String,
/// The topics it may push to, always as its own node.
#[serde(default)]
pub push_topics: NameList,
/// The topics it may read the messages of.
#[serde(default)]
pub read_topics: NameList,
/// Whether it may run read-only SQL, which reads every topic.
#[serde(default)]
pub query: bool,
/// Replication: the topics sent to it.
#[serde(default)]
pub send_topics: NameList,
/// Replication: the topics taken from it.
#[serde(default)]
pub accept_topics: NameList,
/// Replication: the nodes whose messages are sent to it (all by default).
#[serde(default = "NameList::every")]
pub send_nodes: NameList,
/// Replication: the nodes whose messages are taken from it (all by
/// default).
#[serde(default = "NameList::every")]
pub accept_nodes: NameList,
}
/// What a certificate may do: everything one of its roles allows, each role
/// on its own (a role's topics go with that role's nodes), replication
/// within the server's `replicated_topics`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Permissions {
pub(crate) roles: Vec<Role>,
pub(crate) replicated_topics: Option<NameList>,
}
impl Permissions {
/// Its roles that this server has a section for.
pub fn roles(&self) -> impl Iterator<Item = &str> {
self.roles.iter().map(|role| role.name.as_str())
}
/// Whether it may push to `topic`.
pub fn can_push(&self, topic: &str) -> bool {
self.roles
.iter()
.any(|role| role.push_topics.matches(topic))
}
/// Whether it may read `topic`'s messages.
pub fn can_read(&self, topic: &str) -> bool {
self.roles
.iter()
.any(|role| role.read_topics.matches(topic))
}
/// Whether it may run read-only SQL.
pub fn can_query(&self) -> bool {
self.roles.iter().any(|role| role.query)
}
/// Whether `node`'s messages in `topic` are sent to it.
pub fn sends(&self, topic: &str, node: &str) -> bool {
self.replicated(topic)
&& self
.roles
.iter()
.any(|role| role.send_topics.matches(topic) && role.send_nodes.matches(node))
}
/// Whether `node`'s messages in `topic` are taken from it.
pub fn accepts(&self, topic: &str, node: &str) -> bool {
self.replicated(topic)
&& self
.roles
.iter()
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
}
/// Whether it replicates at all: a peer.
pub fn replicates(&self) -> bool {
self.roles
.iter()
.any(|role| !role.send_topics.is_empty() || !role.accept_topics.is_empty())
}
fn replicated(&self, topic: &str) -> bool {
self.replicated_topics
.as_ref()
.is_none_or(|topics| topics.matches(topic))
}
}
@@ -0,0 +1,253 @@
//! The values that need more than a type: durations, ages, sizes,
//! addresses, names.
use bakashrot_proto::limits::{MAX_ATTACHMENT_SIZE, MAX_MESSAGES_PER_PACKET};
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern, names_equal};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use std::net::{Ipv6Addr, SocketAddr};
use std::time::Duration;
/// What a duration looks like, for errors.
pub(crate) const DURATION_HELP: &str = "numbers with a unit (s m h d w), like 30s or 1d12h";
/// What a name looks like, for errors.
pub(crate) const NAME_HELP: &str = "1-64 of A-Z a-z 0-9 _ . -, not only digits; patterns: * and ?";
/// A duration: numbers with a unit, added up (`1d12h`). Units `s m h d w`,
/// without case. More than 0.
pub(crate) fn parse_duration(text: &str) -> Option<Duration> {
let mut seconds: u64 = 0;
let mut number: Option<u64> = None;
for c in text.trim().chars() {
if let Some(digit) = c.to_digit(10) {
number = Some(
number
.unwrap_or(0)
.checked_mul(10)?
.checked_add(digit.into())?,
);
continue;
}
let unit: u64 = match c.to_ascii_lowercase() {
's' => 1,
'm' => 60,
'h' => 3600,
'd' => 86_400,
'w' => 604_800,
_ => return None,
};
seconds = seconds.checked_add(number.take()?.checked_mul(unit)?)?;
}
if number.is_some() || seconds == 0 {
return None;
}
Some(Duration::from_secs(seconds))
}
/// A retention age: a duration, or `forever` (`Some(None)`).
pub(crate) fn parse_age(text: &str) -> Option<Option<Duration>> {
if text.trim().eq_ignore_ascii_case("forever") {
return Some(None);
}
parse_duration(text).map(Some)
}
/// A size: bytes (a number), or text with K, M, G or T (1024-based, without
/// case), up to `MAX_ATTACHMENT_SIZE`. 0 is a size.
pub(crate) fn parse_size(value: &toml::Value) -> Option<u64> {
let size = match value {
toml::Value::Integer(bytes) => u64::try_from(*bytes).ok()?,
toml::Value::String(text) => {
let text = text.trim();
let (digits, unit) = match text.char_indices().last()? {
(at, c) if c.is_ascii_alphabetic() => (&text[..at], c.to_ascii_uppercase()),
_ => (text, 'B'),
};
let shift = match unit {
'B' => 0,
'K' => 10,
'M' => 20,
'G' => 30,
'T' => 40,
_ => return None,
};
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
digits.parse::<u64>().ok()?.checked_mul(1 << shift)?
}
_ => return None,
};
(size <= MAX_ATTACHMENT_SIZE).then_some(size)
}
/// Whether `text` is a host and a port: `10.0.0.2:7000`,
/// `server-2.lan:7000`, `[fd00::2]:7000`. The port isn't 0.
pub(crate) fn is_peer_address(text: &str) -> bool {
let Some((host, port)) = text.rsplit_once(':') else {
return false;
};
let port = port.parse::<u16>().is_ok_and(|port| port != 0);
let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
Some(v6) => v6.parse::<Ipv6Addr>().is_ok(),
None => {
!host.is_empty()
&& host
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
}
};
port && host
}
// As serde reads them (`deserialize_with`): a value that's wrong fails
// there, and toml says on which line.
/// A duration, more than 0.
pub(crate) fn duration<'de, D: Deserializer<'de>>(reader: D) -> Result<Duration, D::Error> {
let text = String::deserialize(reader)?;
parse_duration(&text)
.ok_or_else(|| D::Error::custom(format!("'{text}' isn't a duration: {DURATION_HELP}")))
}
/// A size up to `MAX_ATTACHMENT_SIZE`.
pub(crate) fn size<'de, D: Deserializer<'de>>(reader: D) -> Result<u64, D::Error> {
let value = toml::Value::deserialize(reader)?;
parse_size(&value).ok_or_else(|| {
D::Error::custom(format!(
"{value} isn't a size up to 1T: bytes, or a number with K, M, G or T, like \"500M\" \
(0: no attachments)"
))
})
}
/// An address and a port to listen on.
pub(crate) fn listen<'de, D: Deserializer<'de>>(reader: D) -> Result<SocketAddr, D::Error> {
let text = String::deserialize(reader)?;
text.parse().map_err(|_| {
D::Error::custom(format!(
"'{text}' isn't an address and a port, like \"0.0.0.0:7000\""
))
})
}
/// Peer addresses, none twice.
pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
let peers = Vec::<String>::deserialize(reader)?;
for (at, peer) in peers.iter().enumerate() {
if !is_peer_address(peer) {
return Err(D::Error::custom(format!(
"'{peer}' isn't a host and a port, like \"10.0.0.2:7000\" or \
\"server-2.lan:7000\""
)));
}
if peers[..at].contains(peer) {
return Err(D::Error::custom(format!("'{peer}' is given twice")));
}
}
Ok(peers)
}
/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`.
pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D::Error> {
let size = u32::deserialize(reader)?;
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&size) {
return Err(D::Error::custom(format!(
"the batch size must be 1 to {MAX_MESSAGES_PER_PACKET}"
)));
}
Ok(size)
}
/// Topic names (no patterns), none twice.
pub(crate) fn topic_names<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
let names = Vec::<String>::deserialize(reader)?;
check_names(&names, false).map_err(D::Error::custom)?;
Ok(names)
}
/// Checks a list of names (`patterns`: or patterns), none twice.
pub(crate) fn check_names(list: &[String], patterns: bool) -> Result<(), String> {
for (at, entry) in list.iter().enumerate() {
let (valid, what) = if patterns {
(is_valid_name_or_pattern(entry), "a name or a pattern")
} else {
(is_valid_name(entry), "a name")
};
if !valid {
return Err(format!("'{entry}' isn't {what} ({NAME_HELP})"));
}
if list[..at].iter().any(|before| names_equal(before, entry)) {
return Err(format!("'{entry}' is given twice"));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn durations() {
let s = Duration::from_secs;
assert_eq!(parse_duration("30s"), Some(s(30)));
assert_eq!(parse_duration("1d12h"), Some(s(129_600)));
assert_eq!(parse_duration(" 2W "), Some(s(1_209_600)));
assert_eq!(parse_duration("1m30s"), Some(s(90)));
for bad in [
"",
"30",
"s",
"1x",
"0s",
"1h 30m",
"-1s",
"99999999999999999999w",
] {
assert_eq!(parse_duration(bad), None, "{bad}");
}
assert_eq!(parse_age("Forever"), Some(None));
assert_eq!(parse_age("30d"), Some(Some(s(2_592_000))));
assert_eq!(parse_age("never"), None);
}
#[test]
fn sizes() {
let text = |t: &str| parse_size(&toml::Value::String(t.into()));
assert_eq!(text("0"), Some(0));
assert_eq!(text("500"), Some(500));
assert_eq!(text("500k"), Some(500 << 10));
assert_eq!(text("1G"), Some(1 << 30));
assert_eq!(text("1T"), Some(1 << 40));
assert_eq!(parse_size(&toml::Value::Integer(1024)), Some(1024));
for bad in ["", "G", "2T", "1.5G", "1GB", "-1", "1 G"] {
assert_eq!(text(bad), None, "{bad}");
}
assert_eq!(parse_size(&toml::Value::Integer(-1)), None);
assert_eq!(parse_size(&toml::Value::Boolean(true)), None);
}
#[test]
fn peer_addresses() {
for good in [
"10.0.0.2:7000",
"server-2.lan:7000",
"[fd00::2]:7000",
"localhost:1",
] {
assert!(is_peer_address(good), "{good}");
}
for bad in [
"10.0.0.2",
"10.0.0.2:0",
":7000",
"fd00::2:7000",
"a b:7000",
"x:70000",
] {
assert!(!is_peer_address(bad), "{bad}");
}
}
}
@@ -0,0 +1,372 @@
//! Configs taken and refused, and what they mean.
use bakashrot_config::{Config, Synchronous};
use std::path::Path;
use std::time::Duration;
const EXAMPLE: &str = include_str!("../example.toml");
/// The least a config has.
const MINIMAL: &str = r#"
[server]
listen = "127.0.0.1:7000"
ca = "ca.crt"
certificate = "server.crt"
key = "server.key"
"#;
fn with(extra: &str) -> String {
format!("{MINIMAL}{extra}")
}
/// The error of a config that must be refused.
fn refused(text: &str) -> String {
match Config::parse(text) {
Ok(config) => panic!("taken: {config:?}\n{text}"),
Err(error) => error.to_string(),
}
}
fn days(days: u64) -> Option<Duration> {
Some(Duration::from_secs(days * 86_400))
}
#[test]
fn the_example() {
let config = Config::parse(EXAMPLE).unwrap();
let server = &config.server;
assert_eq!(server.listen, "0.0.0.0:7000".parse().unwrap());
assert_eq!(server.crl, None);
assert_eq!(server.topics.len(), 3);
assert!(server.has_topic("Sensors.Kitchen"));
assert!(!server.has_topic("sensors"));
assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(config.replication.peers, Vec::<String>::new());
assert_eq!(config.retention.age("logs"), days(30));
assert_eq!(
config.retention.age("sensors.kitchen"),
Some(Duration::from_secs(43_200))
);
assert_eq!(config.retention.age("other"), None);
let names: Vec<&str> = config.roles.iter().map(|role| role.name.as_str()).collect();
assert_eq!(names, ["sensor", "dashboard", "peer"]);
}
#[test]
fn defaults() {
let config = Config::parse(MINIMAL).unwrap();
let server = &config.server;
assert_eq!(server.database, Path::new("bakashrot.sqlite"));
assert!(server.topics.is_empty());
assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(server.retention_interval, Duration::from_secs(60));
assert_eq!(config.retention.age("logs"), None);
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
assert_eq!(config.replication.batch_size, 100);
assert_eq!(config.replication.replicated_topics, None);
assert!(config.roles.is_empty());
assert!(config.permissions(&["anything"]).is_none());
}
#[test]
fn settings() {
let config = Config::parse(&with(
r#"crl = "ca.crl"
database = "data/messages.sqlite"
synchronous = "NORMAL"
max_attachment_size = 0
retention_interval = "1h30m"
[replication]
peers = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
retry_delay = "1m"
sync_interval = "2s"
batch_size = 10000
replicated_topics = ["logs"]
"#,
))
.unwrap();
assert_eq!(config.server.crl.as_deref(), Some(Path::new("ca.crl")));
assert_eq!(config.server.synchronous, Synchronous::Normal);
assert_eq!(config.server.max_attachment_size, 0);
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
assert_eq!(config.replication.peers.len(), 3);
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
assert_eq!(config.replication.batch_size, 10_000);
}
#[test]
fn retention_order() {
let config = Config::parse(&with(
r#"
[retention]
"*" = "365d"
"sensors.?????" = "1h"
"sensors.*" = "12h"
"sensors.k*" = "2h"
"Sensors.Kitchen" = "forever"
logs = "30d"
"#,
))
.unwrap();
let age = |topic| config.retention.age(topic);
let hours = |hours: u64| Some(Duration::from_secs(hours * 3600));
// Its name's line first, wherever it is.
assert_eq!(age("sensors.kitchen"), None);
assert_eq!(age("LOGS"), days(30));
// Else the first pattern in the file's order (sorted, "sensors.*"
// would come first), not the closest.
assert_eq!(age("sensors.alpha"), hours(1));
assert_eq!(age("sensors.kettle"), hours(12));
// "*" last, though it's first.
assert_eq!(age("other"), days(365));
}
#[test]
fn permissions() {
let config = Config::parse(&with(
r#"
[roles.sensor]
push_topics = ["sensors.*"]
[roles.Reader]
read_topics = ["logs", "sensors.kitchen"]
[roles.admin]
query = true
[roles.peer]
send_topics = ["logs"]
send_nodes = ["kitchen-*"]
[roles.backup]
send_topics = ["sensors.*"]
accept_topics = ["*"]
accept_nodes = ["garage"]
[roles.idle]
"#,
))
.unwrap();
// None of its roles here: refused. Roles compare without case.
assert!(config.permissions(&["unknown"]).is_none());
assert!(config.permissions::<&str>(&[]).is_none());
let idle = config.permissions(&["IDLE", "unknown"]).unwrap();
assert_eq!(idle.roles().collect::<Vec<_>>(), ["idle"]);
assert!(!idle.can_push("logs") && !idle.can_read("logs") && !idle.can_query());
assert!(!idle.replicates());
// Everything its roles allow.
let both = config.permissions(&["sensor", "reader"]).unwrap();
assert!(both.can_push("sensors.garage"));
assert!(!both.can_push("logs"));
assert!(both.can_read("Logs"));
assert!(!both.can_read("sensors.garage"));
assert!(!both.can_query());
assert!(config.permissions(&["admin"]).unwrap().can_query());
// Replication: each role's topics with that role's nodes, not mixed.
let peer = config.permissions(&["peer", "backup"]).unwrap();
assert!(peer.replicates());
assert!(peer.sends("logs", "kitchen-1"));
assert!(!peer.sends("logs", "garage"));
assert!(peer.sends("sensors.a", "garage"));
assert!(!peer.sends("other", "kitchen-1"));
assert!(peer.accepts("anything", "garage"));
assert!(!peer.accepts("logs", "kitchen-1"));
// A role without the topics replicates nothing, whatever its nodes.
let only_peer = config.permissions(&["peer"]).unwrap();
assert!(!only_peer.accepts("logs", "kitchen-1"));
}
#[test]
fn replicated_topics_filter_the_roles() {
let config = Config::parse(&with(
r#"
[replication]
replicated_topics = ["logs", "alerts.*"]
[roles.peer]
send_topics = ["*"]
accept_topics = ["*"]
[roles.sensor]
push_topics = ["*"]
"#,
))
.unwrap();
let peer = config.permissions(&["peer", "sensor"]).unwrap();
assert!(peer.sends("logs", "kitchen") && peer.accepts("Logs", "kitchen"));
assert!(peer.sends("alerts.fire", "kitchen"));
assert!(!peer.sends("sensors.a", "kitchen") && !peer.accepts("sensors.a", "kitchen"));
assert!(peer.replicates());
// Only replication: pushing isn't filtered.
assert!(peer.can_push("sensors.a"));
// Empty: nothing replicated.
let none = Config::parse(&with(
"[replication]\nreplicated_topics = []\n[roles.peer]\nsend_topics = [\"*\"]\n",
))
.unwrap();
assert!(
!none
.permissions(&["peer"])
.unwrap()
.sends("logs", "kitchen")
);
assert!(refused(&with("[replication]\nreplicated_topics = [\"a b\"]\n")).contains("'a b'"));
}
#[test]
fn files_are_from_the_configs_folder() {
let folder = std::env::temp_dir().join(format!("bakashrot-config-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("server.toml");
std::fs::write(&path, with("crl = \"revoked/ca.crl\"\n")).unwrap();
let config = Config::load(&path).unwrap();
assert_eq!(config.server.ca, folder.join("ca.crt"));
assert_eq!(config.server.crl, Some(folder.join("revoked/ca.crl")));
assert_eq!(config.server.database, folder.join("bakashrot.sqlite"));
std::fs::write(&path, "[server]\n").unwrap();
let error = Config::load(&path).unwrap_err().to_string();
assert!(error.starts_with(&path.display().to_string()), "{error}");
assert!(error.contains("listen"), "{error}");
std::fs::remove_dir_all(&folder).unwrap();
let error = Config::load(&folder.join("missing.toml")).unwrap_err();
assert!(error.to_string().contains("missing.toml"), "{error}");
}
#[test]
fn refusals() {
let cases: &[(&str, &str)] = &[
// Not TOML, or another shape: the line is said.
("[server", "line 1"),
("", "missing field `server`"),
(&with("lsiten = \"x\"\n"), "unknown field `lsiten`"),
(&with("[other]\n"), "unknown field `other`"),
// The old ini's keys.
(&with("PrivateKey = \"x\"\n"), "unknown field `PrivateKey`"),
(
&with("[roles.sensor]\nAllowWrite = 1\n"),
"unknown field `AllowWrite`",
),
(
&with("[roles.sensor]\ndefault_topic = \"x\"\n"),
"unknown field `default_topic`",
),
// [server]
(
&MINIMAL.replace("127.0.0.1:7000", "127.0.0.1"),
"'127.0.0.1' isn't an address and a port",
),
(&with("topics = [\"a b\"]\n"), "'a b' isn't a name ("),
(
&with("topics = [\"sensors.*\"]\n"),
"'sensors.*' isn't a name (",
),
(&with("topics = [\"12\"]\n"), "'12' isn't a name"),
(
&with("topics = [\"logs\", \"Logs\"]\n"),
"'Logs' is given twice",
),
(
&with("synchronous = \"OFF\"\n"),
"isn't allowed: a power loss",
),
(&with("synchronous = \"extra\"\n"), "write \"full\""),
(
&with("synchronous = \"fast\"\n"),
"'fast' isn't \"full\" or \"normal\"",
),
(
&with("max_attachment_size = \"2T\"\n"),
"isn't a size up to 1T",
),
(&with("max_attachment_size = -1\n"), "isn't a size up to 1T"),
(
&with("max_attachment_size = \"1GB\"\n"),
"isn't a size up to 1T",
),
(&with("retention_interval = \"3600\"\n"), "isn't a duration"),
(&with("retention_interval = 60\n"), "invalid type: integer"),
// Gone with protocol 7: no upload waits for its message.
(
&with("upload_timeout = \"1h\"\n"),
"unknown field `upload_timeout`",
),
(
&with("retention_interval = \"0s\"\n"),
"'0s' isn't a duration",
),
// [retention]
(
&with("[retention]\nlogs = \"30\"\n"),
"logs = \"30\" isn't an age",
),
(&with("[retention]\nlogs = 30\n"), "isn't an age"),
(
&with("[retention]\n\"a b\" = \"1d\"\n"),
"'a b' isn't a topic name or a pattern",
),
(
&with("[retention]\nlogs = \"1d\"\nLOGS = \"2d\"\n"),
"'LOGS' is given twice",
),
(
&with("[retention]\nsensors.kitchen = \"1d\"\n"),
"quote names with dots",
),
// [replication]
(
&with("[replication]\npeers = [\"10.0.0.2\"]\n"),
"isn't a host and a port",
),
(
&with("[replication]\npeers = [\"a:1\", \"a:1\"]\n"),
"'a:1' is given twice",
),
(
&with("[replication]\nbatch_size = 0\n"),
"batch size must be 1 to 10000",
),
(
&with("[replication]\nbatch_size = 10001\n"),
"batch size must be 1 to 10000",
),
(
&with("[replication]\nsync_interval = \"soon\"\n"),
"'soon' isn't a duration",
),
// [roles]
(&with("[roles.\"a b\"]\n"), "'a b' isn't a role name"),
(
&with("[roles.peer]\n[roles.Peer]\n"),
"'peer' and 'Peer' are the same role",
),
(
&with("[roles.r]\npush_topics = [\"a b\"]\n"),
"'a b' isn't a name or a pattern",
),
(
&with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"),
"'X' is given twice",
),
(&with("[roles.r]\nquery = 1\n"), "invalid type: integer"),
(&with("[roles.site.reader]\n"), "unknown field `reader`"),
];
for (text, expected) in cases {
let error = refused(text);
assert!(
error.contains(expected),
"expected {expected:?} in:\n{error}"
);
// Every refusal says where.
assert!(error.contains("line "), "no line in:\n{error}");
}
}