mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Made the roles the only lists of topics, Refused PRAGMAs in queries
- Removed `[server] topics` and `[replication] replicated_topics`: a push is taken by its roles' `push_topics`, a replicated message by the peer's `accept_topics`; a topic exists from its first message. - Topics that only came from a peer are read and listed like any other; `ListNames` lists the topics with messages, filtered by the roles. - A push to a topic no role names is `NotAllowed`; `UnknownName` is only for nodes. - Clients' queries: every PRAGMA refused as it's prepared (SQLite's authorizer), `PRAGMA query_only = 0` used to take effect. - Noted the leads found by reading the code in `docs/known-issues.md`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -668,8 +668,9 @@ fn list(kind: NameKind) -> i32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists the topics this client may push to or read (every one if it may
|
||||
/// query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`.
|
||||
/// Lists the topics with messages that this client may push to or read
|
||||
/// (every one if it may query): how many, -1 on failure. Then
|
||||
/// `BakaShrot_GetNamesList()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_ListTopics() -> i32 {
|
||||
list(NameKind::Topic)
|
||||
|
||||
@@ -12,7 +12,6 @@ listen = "127.0.0.1:0"
|
||||
ca = "ca.crt"
|
||||
certificate = "server.crt"
|
||||
key = "server.key"
|
||||
topics = ["logs", "secret"]
|
||||
|
||||
[roles.home]
|
||||
push_topics = ["logs", "secret"]
|
||||
|
||||
@@ -125,8 +125,8 @@ fn exports() {
|
||||
-1
|
||||
);
|
||||
let (failed, why) = error();
|
||||
assert_eq!(failed, code(ErrorCode::UnknownName));
|
||||
assert!(why.contains("unknown topic"), "{why}");
|
||||
assert_eq!(failed, code(ErrorCode::NotAllowed));
|
||||
assert!(why.contains("may not push to 'nothing'"), "{why}");
|
||||
|
||||
// The latest; none yet in another topic.
|
||||
assert_eq!(
|
||||
@@ -199,10 +199,11 @@ fn exports() {
|
||||
assert_eq!(bytes[1..3], [b'{', 0]);
|
||||
|
||||
// Names, queries.
|
||||
assert_eq!(BakaShrot_ListTopics(), 2);
|
||||
// Topics: those with messages (nothing in `secret` yet).
|
||||
assert_eq!(BakaShrot_ListTopics(), 1);
|
||||
assert_eq!(
|
||||
get_w(BakaShrot_GetNamesListW),
|
||||
r#"{"kind":"topic","names":["logs","secret"],"truncated":false}"#
|
||||
r#"{"kind":"topic","names":["logs"],"truncated":false}"#
|
||||
);
|
||||
assert_eq!(BakaShrot_ListNodes(), 1);
|
||||
assert_eq!(
|
||||
|
||||
@@ -413,8 +413,9 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
/// The topics this client may push to or read (every one if it may
|
||||
/// query), or every node with messages. `truncated` if some didn't fit.
|
||||
/// The topics with messages that this client may push to or read
|
||||
/// (every one if it may query), or every node with messages.
|
||||
/// `truncated` if some didn't fit.
|
||||
pub fn list_names(&mut self, kind: NameKind) -> Result<NamesList> {
|
||||
match self.request(ListNames { kind }.into())? {
|
||||
Packet::NamesList(names) => Ok(names),
|
||||
|
||||
@@ -20,9 +20,6 @@ key = "server-1.key"
|
||||
|
||||
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.)
|
||||
@@ -44,16 +41,15 @@ logs = "30d"
|
||||
[replication]
|
||||
push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"]
|
||||
accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"]
|
||||
# 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 = 1000 # 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.
|
||||
# optional: an empty list allows nothing. The topics are only named here:
|
||||
# one exists from its first message, pushed (push_topics) or replicated
|
||||
# (accept_topics).
|
||||
[roles.sensor]
|
||||
push_topics = ["sensors.*"] # always as its own node (its name)
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
//! The server's config: a TOML file, read and checked in one go.
|
||||
//!
|
||||
//! - [`Server`]: where it listens, its files, its topics, its database.
|
||||
//! - [`Server`]: where it listens, its files, its database.
|
||||
//! - [`Retention`]: how long each topic's messages are kept.
|
||||
//! - [`Replication`]: the servers it sends to and takes from, what it
|
||||
//! replicates, how often.
|
||||
//! - [`Replication`]: the servers it sends to and takes from, 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:
|
||||
//! peer is its roles'. Topics aren't listed anywhere else: one exists
|
||||
//! once a role let a message in. The file, every key and its default:
|
||||
//! `docs/config.md`.
|
||||
//!
|
||||
//! Every value is checked as serde reads it, so a wrong one is refused with
|
||||
@@ -80,9 +80,6 @@ pub struct Server {
|
||||
/// 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,
|
||||
@@ -100,13 +97,6 @@ pub struct Server {
|
||||
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)]
|
||||
@@ -210,9 +200,6 @@ pub struct Replication {
|
||||
/// roles' `accept_*`.
|
||||
#[serde(deserialize_with = "values::hosts")]
|
||||
pub accept_from: 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,
|
||||
@@ -230,7 +217,6 @@ impl Default for Replication {
|
||||
Replication {
|
||||
push_to: Vec::new(),
|
||||
accept_from: Vec::new(),
|
||||
replicated_topics: None,
|
||||
retry_delay: Duration::from_secs(10),
|
||||
sync_interval: Duration::from_secs(5),
|
||||
batch_size: 1000,
|
||||
@@ -317,9 +303,6 @@ impl Config {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
(!roles.is_empty()).then(|| Permissions {
|
||||
roles,
|
||||
replicated_topics: self.replication.replicated_topics.clone(),
|
||||
})
|
||||
(!roles.is_empty()).then_some(Permissions { roles })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ impl TryFrom<Vec<String>> for NameList {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(list: Vec<String>) -> Result<Self, String> {
|
||||
check_names(&list, true)?;
|
||||
check_names(&list)?;
|
||||
Ok(NameList(list))
|
||||
}
|
||||
}
|
||||
@@ -77,12 +77,11 @@ pub struct Role {
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
/// on its own (a role's topics go with that role's nodes). The roles are
|
||||
/// all there is: no other list of topics.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Permissions {
|
||||
pub(crate) roles: Vec<Role>,
|
||||
pub(crate) replicated_topics: Option<NameList>,
|
||||
}
|
||||
|
||||
impl Permissions {
|
||||
@@ -112,20 +111,16 @@ impl Permissions {
|
||||
|
||||
/// 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))
|
||||
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))
|
||||
self.roles
|
||||
.iter()
|
||||
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
|
||||
}
|
||||
|
||||
/// The topics and the nodes taken from it, as `SyncState` lists them:
|
||||
@@ -158,10 +153,4 @@ impl Permissions {
|
||||
.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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! 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 bakashrot_proto::names::{is_valid_name_or_pattern, names_equal};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::net::{Ipv6Addr, SocketAddr};
|
||||
@@ -184,23 +184,11 @@ pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D:
|
||||
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> {
|
||||
/// Checks a list of names or patterns, none twice.
|
||||
pub(crate) fn check_names(list: &[String]) -> 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 !is_valid_name_or_pattern(entry) {
|
||||
return Err(format!("'{entry}' isn't a name or a pattern ({NAME_HELP})"));
|
||||
}
|
||||
if list[..at].iter().any(|before| names_equal(before, entry)) {
|
||||
return Err(format!("'{entry}' is given twice"));
|
||||
|
||||
@@ -37,9 +37,6 @@ fn the_example() {
|
||||
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.push_to, Vec::<String>::new());
|
||||
@@ -59,7 +56,6 @@ 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));
|
||||
@@ -67,7 +63,6 @@ fn defaults() {
|
||||
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, 1000);
|
||||
assert_eq!(config.replication.replicated_topics, None);
|
||||
assert!(config.roles.is_empty());
|
||||
assert!(config.permissions(&["anything"]).is_none());
|
||||
}
|
||||
@@ -87,7 +82,6 @@ accept_from = ["10.0.0.2", "server-3.lan", "fd00::4"]
|
||||
retry_delay = "1m"
|
||||
sync_interval = "2s"
|
||||
batch_size = 10000
|
||||
replicated_topics = ["logs"]
|
||||
"#,
|
||||
))
|
||||
.unwrap();
|
||||
@@ -191,41 +185,13 @@ accept_nodes = ["garage"]
|
||||
}
|
||||
|
||||
#[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();
|
||||
fn topics_are_only_in_the_roles() {
|
||||
// No list of topics beside the roles': the old keys are refused.
|
||||
assert!(refused(&with("topics = [\"logs\"]\n")).contains("unknown field `topics`"));
|
||||
assert!(
|
||||
!none
|
||||
.permissions(&["peer"])
|
||||
.unwrap()
|
||||
.sends("logs", "kitchen")
|
||||
refused(&with("[replication]\nreplicated_topics = [\"logs\"]\n"))
|
||||
.contains("unknown field `replicated_topics`")
|
||||
);
|
||||
assert!(refused(&with("[replication]\nreplicated_topics = [\"a b\"]\n")).contains("'a b'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -272,16 +238,6 @@ fn refusals() {
|
||||
&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",
|
||||
|
||||
@@ -67,7 +67,7 @@ macro_rules! error_codes {
|
||||
error_codes! {
|
||||
// Refused by the server: the connection is still open.
|
||||
NotAllowed = 1, "Not allowed to this client: its roles' permissions, or a request only peers may make.";
|
||||
UnknownName = 2, "A topic or node this server doesn't know.";
|
||||
UnknownName = 2, "A node this server has no message of.";
|
||||
NotFound = 3, "No such message or attachment.";
|
||||
NotReady = 4, "The attachment isn't on this server yet (still being replicated).";
|
||||
TooBig = 5, "A message, attachment or query result over a limit, or an attachment bigger than this server keeps.";
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! field names is taken too, `serde`'s derive: nothing writes that form, it
|
||||
//! isn't part of the format, its values are checked all the same.) Whatever isn't right is a
|
||||
//! [`DecodeError`]: the connection is aborted. What's well-formed but not
|
||||
//! allowed or not found (a topic this server doesn't have) is the server's
|
||||
//! allowed or not found (a node without messages) is the server's
|
||||
//! to refuse, with a `RequestRefused`.
|
||||
//!
|
||||
//! Topics and nodes are names everywhere, never ids.
|
||||
|
||||
@@ -219,12 +219,6 @@ async fn push(
|
||||
frames: &mut Frames,
|
||||
push: PushMessage,
|
||||
) -> Result<Packet, String> {
|
||||
if !shared.config.server.has_topic(&push.topic) {
|
||||
return Ok(refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", push.topic),
|
||||
));
|
||||
}
|
||||
if !peer.permissions.can_push(&push.topic) {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
@@ -378,12 +372,6 @@ async fn get_attachment(
|
||||
format!("{} may not read '{}'", peer.node, get.topic),
|
||||
)));
|
||||
}
|
||||
if !shared.config.server.has_topic(&get.topic) {
|
||||
return Ok(Some(refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", get.topic),
|
||||
)));
|
||||
}
|
||||
let message = format!("{}:{}#{}", get.topic, get.node, get.message_id);
|
||||
let GetAttachment {
|
||||
topic,
|
||||
@@ -462,12 +450,6 @@ async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Pa
|
||||
format!("{} may not read '{}'", peer.node, get.topic),
|
||||
);
|
||||
}
|
||||
if !shared.config.server.has_topic(&get.topic) {
|
||||
return refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", get.topic),
|
||||
);
|
||||
}
|
||||
let GetMessages {
|
||||
topic,
|
||||
node,
|
||||
@@ -490,27 +472,21 @@ async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Pa
|
||||
}
|
||||
}
|
||||
|
||||
/// Topics: the server's, those it may push to or read unless it may query
|
||||
/// (queries read everything). Nodes: every one with messages.
|
||||
/// Topics: those with messages (pushed here or replicated) that it may
|
||||
/// push to or read, every one if it may query (queries read everything).
|
||||
/// Nodes: every one with messages.
|
||||
async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packet {
|
||||
let mut names = match list.kind {
|
||||
NameKind::Topic => shared
|
||||
.config
|
||||
.server
|
||||
.topics
|
||||
.iter()
|
||||
.filter(|topic| {
|
||||
peer.permissions.can_query()
|
||||
|| peer.permissions.can_push(topic)
|
||||
|| peer.permissions.can_read(topic)
|
||||
})
|
||||
.cloned()
|
||||
.collect(),
|
||||
NameKind::Node => match shared.read(|reader| reader.nodes()).await {
|
||||
Ok(nodes) => nodes,
|
||||
Err(refused) => return refused.into(),
|
||||
},
|
||||
let found = match list.kind {
|
||||
NameKind::Topic => shared.read(|reader| reader.topics()).await,
|
||||
NameKind::Node => shared.read(|reader| reader.nodes()).await,
|
||||
};
|
||||
let mut names = match found {
|
||||
Ok(names) => names,
|
||||
Err(refused) => return refused.into(),
|
||||
};
|
||||
if list.kind == NameKind::Topic && !peer.permissions.can_query() {
|
||||
names.retain(|topic| peer.permissions.can_push(topic) || peer.permissions.can_read(topic));
|
||||
}
|
||||
let truncated = names.len() > MAX_NAMES_LIST_ENTRIES;
|
||||
names.truncate(MAX_NAMES_LIST_ENTRIES);
|
||||
NamesList {
|
||||
|
||||
@@ -28,7 +28,6 @@ ca = "ca.crt"
|
||||
certificate = "server.crt"
|
||||
key = "server.key"
|
||||
crl = "ca.crl"
|
||||
topics = ["logs", "sensors"]
|
||||
|
||||
[roles.sensor]
|
||||
push_topics = ["logs", "sensors"]
|
||||
@@ -237,9 +236,10 @@ fn refusals_keep_the_connection() {
|
||||
refused(reader.push("logs", "{}")),
|
||||
ErrorCode::NotAllowed.code()
|
||||
);
|
||||
// A topic is its roles': one that none of them names.
|
||||
assert_eq!(
|
||||
refused(sensor.push("nope", "{}")),
|
||||
ErrorCode::UnknownName.code()
|
||||
ErrorCode::NotAllowed.code()
|
||||
);
|
||||
// The client checks names before sending.
|
||||
assert_eq!(
|
||||
@@ -487,9 +487,13 @@ fn runs_of_messages() {
|
||||
refused(screen.get_messages("sensors", "kitchen", None, 1)),
|
||||
ErrorCode::NotAllowed.code()
|
||||
);
|
||||
assert_eq!(
|
||||
refused(kitchen.get_messages("nothing", "kitchen", None, 1)),
|
||||
ErrorCode::UnknownName.code()
|
||||
// A topic without messages: none, for a node that has some elsewhere.
|
||||
assert!(
|
||||
kitchen
|
||||
.get_messages("nothing", "kitchen", None, 1)
|
||||
.unwrap()
|
||||
.messages
|
||||
.is_empty()
|
||||
);
|
||||
assert_eq!(
|
||||
refused(kitchen.get_messages("logs", "nobody", None, 1)),
|
||||
@@ -746,7 +750,7 @@ fn attachments() {
|
||||
let error = kitchen
|
||||
.get_attachment("nothing", "kitchen", 1, &mut Vec::new())
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::UnknownName.code(), "{error}");
|
||||
assert_eq!(error.code(), ErrorCode::NotFound.code(), "{error}");
|
||||
let mut logs_only = running
|
||||
.connect(&running.issue("lounge", &["logs"]))
|
||||
.unwrap();
|
||||
@@ -1511,6 +1515,42 @@ fn replication_edges() {
|
||||
raw.refused(ErrorCode::DataMismatch);
|
||||
assert_eq!(sync_state(&mut raw).missing[0].next_part, 0);
|
||||
|
||||
// A topic nobody pushed here: it's there from its first replicated
|
||||
// message, read and listed by the roles that name it.
|
||||
raw.send(ReplicateMessages {
|
||||
topic: "elsewhere".into(),
|
||||
node: "far".into(),
|
||||
messages: vec![message(1, now, None)],
|
||||
});
|
||||
assert_eq!(raw.receive(), Some(MessagePushed { message_id: 1 }.into()));
|
||||
let mut reader = running
|
||||
.connect(&running.issue("screen", &["reader"]))
|
||||
.unwrap();
|
||||
let got = reader
|
||||
.get_messages("elsewhere", "far", Some(0), 10)
|
||||
.unwrap();
|
||||
assert_eq!(got.messages[0].data, "m1");
|
||||
// (`old` had a message, past its age.)
|
||||
assert_eq!(
|
||||
reader.list_names(NameKind::Topic).unwrap().names,
|
||||
["elsewhere", "logs", "old"]
|
||||
);
|
||||
let mut logs_only = running
|
||||
.connect(&running.issue("lounge", &["logs"]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
logs_only.list_names(NameKind::Topic).unwrap().names,
|
||||
["logs"]
|
||||
);
|
||||
assert_eq!(
|
||||
code(
|
||||
logs_only
|
||||
.get_messages("elsewhere", "far", Some(0), 10)
|
||||
.unwrap_err()
|
||||
),
|
||||
ErrorCode::NotAllowed.code()
|
||||
);
|
||||
|
||||
// A certificate whose roles take nothing: refused.
|
||||
let mut other = Raw::connect(&running, &running.issue("nosy", &["reader"]));
|
||||
let state = sync_state(&mut other);
|
||||
|
||||
@@ -16,8 +16,9 @@ bakashrot-proto = { path = "../bakashrot-proto" }
|
||||
bakashrot-config = { path = "../bakashrot-config" }
|
||||
# SQLite itself compiled in (`bundled`): the same version everywhere, with
|
||||
# its JSON functions, no system library to install. `fallible_uint`: u64
|
||||
# in and out, an error past i64::MAX instead of a wrap.
|
||||
rusqlite = { version = "0.42.0", features = ["bundled", "fallible_uint"] }
|
||||
# in and out, an error past i64::MAX instead of a wrap. `hooks`: the
|
||||
# authorizer that refuses PRAGMAs in clients' queries.
|
||||
rusqlite = { version = "0.42.0", features = ["bundled", "fallible_uint", "hooks"] }
|
||||
# Query results as JSON.
|
||||
serde_json = "1.0.154"
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer};
|
||||
use bakashrot_config::Synchronous;
|
||||
use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -126,10 +127,18 @@ impl Database {
|
||||
Ok(Reader::new(self.connect()?))
|
||||
}
|
||||
|
||||
/// A connection for clients' queries: read-only (`query_only`).
|
||||
/// A connection for clients' queries: read-only (`query_only`), and
|
||||
/// every PRAGMA refused from then on (SQLite's authorizer). Some take
|
||||
/// effect when they're prepared, before a statement can be refused
|
||||
/// for what it is: `PRAGMA query_only = 0` turned `query_only` off
|
||||
/// for the connection's next queries.
|
||||
pub fn query_runner(&self) -> Result<QueryRunner> {
|
||||
let connection = self.connect()?;
|
||||
let mut connection = self.connect()?;
|
||||
connection.pragma_update(None, "query_only", true)?;
|
||||
connection.authorizer(Some(|context: AuthContext<'_>| match context.action {
|
||||
AuthAction::Pragma { .. } => Authorization::Deny,
|
||||
_ => Authorization::Allow,
|
||||
}))?;
|
||||
Ok(QueryRunner::new(connection))
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! Read-only three ways: the connection has `query_only` on (SQLite
|
||||
//! refuses any write), the statement must be one SQLite says only reads
|
||||
//! (`sqlite3_stmt_readonly`), and only one statement runs (more is an
|
||||
//! error, not ignored). The result is JSON, every value a string or null
|
||||
//! error, not ignored). PRAGMAs are refused as they're prepared
|
||||
//! (`Database::query_runner`'s authorizer): some would change the
|
||||
//! connection, `query_only` included, before the statement is looked
|
||||
//! at. The result is JSON, every value a string or null
|
||||
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
@@ -702,6 +702,25 @@ fn queries() {
|
||||
] {
|
||||
assert!(matches!(runner.run(sql), Err(Error::Query(_))), "{sql}");
|
||||
}
|
||||
// PRAGMAs are refused as they're prepared, reading ones too: one that
|
||||
// changes the connection would have by the time it's looked at.
|
||||
for sql in [
|
||||
"PRAGMA query_only = 0",
|
||||
"PRAGMA query_only",
|
||||
"PRAGMA locking_mode = EXCLUSIVE",
|
||||
"PRAGMA database_list",
|
||||
"SELECT * FROM pragma_database_list",
|
||||
] {
|
||||
match runner.run(sql) {
|
||||
Err(Error::Query(why)) => assert!(why.contains("not authorized"), "{sql}: {why}"),
|
||||
other => panic!("{sql}: {other:?}"),
|
||||
}
|
||||
}
|
||||
// Still read-only, still answering.
|
||||
assert_eq!(
|
||||
json("SELECT count(*) FROM messages")["rows"],
|
||||
serde_json::json!([["3"]])
|
||||
);
|
||||
// A failing row fails it all, with SQLite's message.
|
||||
match runner.run("SELECT message_data ->> '$.t' FROM messages") {
|
||||
Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"),
|
||||
|
||||
@@ -101,8 +101,8 @@ enum Command {
|
||||
/// standard input's.
|
||||
sql: String,
|
||||
},
|
||||
/// Lists the topics this client may use (every one if it may query) and
|
||||
/// the nodes with messages.
|
||||
/// Lists the topics with messages that 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)]
|
||||
|
||||
@@ -18,7 +18,6 @@ listen = "127.0.0.1:0"
|
||||
ca = "ca.crt"
|
||||
certificate = "server.crt"
|
||||
key = "server.key"
|
||||
topics = ["logs", "secret"]
|
||||
synchronous = "normal"
|
||||
|
||||
[roles.home]
|
||||
@@ -214,7 +213,7 @@ fn pushes_and_latest() {
|
||||
server
|
||||
.tool("lounge", &["push", "logs", "{}"])
|
||||
.fails(1, "Refused by the server (NotAllowed)");
|
||||
push(&["nope", "{}"]).fails(1, "Refused by the server (UnknownName): ");
|
||||
push(&["nope", "{}"]).fails(1, "Refused by the server (NotAllowed): ");
|
||||
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);
|
||||
@@ -319,7 +318,13 @@ fn messages() {
|
||||
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("kitchen", &["nothing", "kitchen"])
|
||||
.ok()
|
||||
.out
|
||||
.is_empty(),
|
||||
"a topic without messages"
|
||||
);
|
||||
assert!(
|
||||
messages("lounge", &["logs", "lounge"]).ok().out.is_empty(),
|
||||
"its own node, none yet"
|
||||
@@ -448,10 +453,7 @@ fn queries_and_lists() {
|
||||
.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!(all.ok().out, "Topics (1):\n logs\nNodes (1):\n kitchen\n");
|
||||
assert_eq!(
|
||||
server.tool("lounge", &["list", "topics"]).ok().out,
|
||||
"Topics (1):\n logs\n"
|
||||
@@ -534,7 +536,7 @@ fn settings() {
|
||||
&["list", "topics"],
|
||||
None,
|
||||
);
|
||||
assert_eq!(up.ok().out, "Topics (2):\n logs\n secret\n");
|
||||
assert_eq!(up.ok().out, "Topics (0):\n");
|
||||
|
||||
let kitchen = fs::read_to_string(folder.join("kitchen.toml")).unwrap();
|
||||
fs::write(
|
||||
|
||||
Reference in New Issue
Block a user