Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pkgs/id/src/pull_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
//! sync sessions check the gate before any event is sent. A refused peer gets no event, and the
//! refusal is clean. An open gate never reads membership.
//!
//! This is a config setting, not a protocol rule. The policy belongs with the world's policy, but
//! `id serve` does not read it yet, and no session builds a gate from config. Blobs are not
//! This is a config setting, not a protocol rule. The policy belongs with the world's policy. The
//! server config's `[policy]` table parses it ([`crate::server_config::ServerConfig::pull_policy`]),
//! but `id serve` does not read it yet, and no session builds a gate from config. Blobs are not
//! governed here. The blob gate ([`crate::blob_gate`]) still requires membership to fetch, whatever
//! this policy says. Authorized pull is advisory: it stops an honest server from serving a
//! non-member. It does not stop re-serving, recall copies, or hide metadata.
Expand Down
43 changes: 43 additions & 0 deletions pkgs/id/src/server_config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
//! [[groups.members]]
//! user = "bo"
//! role = "write" # pull, read, write, manage, or admin
//!
//! [policy] # absent: the code defaults apply
//! freshness_window_seconds = 300 # the server-level freshness window (N23)
//! pull_policy = "open" # who may pull a world's events: "open" or "members" (P6.5)
//! ```
//!
//! [`ServerConfig::parse`] checks the whole file and translates every key to its ID, so a bad file
Expand All @@ -35,10 +39,13 @@ pub mod provision;

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::time::Duration;

use p2panda_core::Hash;

use crate::groups::{Key, Projection, Role};
use crate::pull_policy::PullPolicy;
use crate::seitan::Freshness;

/// Re-exported so `crate::server_config::Object` keeps working: the type now lives in
/// [`crate::aliases`] so alias display builds without the `world` feature.
Expand All @@ -52,6 +59,7 @@ pub struct ServerConfig {
users: Vec<UserSpec>,
groups: Vec<GroupSpec>,
create: CreateRule,
policy: PolicySpec,
/// Every local key, for users and groups alike. Keys are unique within the config.
names: BTreeMap<String, Object>,
/// The primary alias of each object that has one.
Expand Down Expand Up @@ -82,6 +90,17 @@ pub struct GroupSpec {
pub members: Vec<(Key, Role)>,
}

/// The server's serving policy: the operator-set knobs of the freshness window (N23) and the
/// pull policy (P6.5). Both have code defaults, so a config that sets neither behaves exactly
/// as before: a five-minute window and open pull.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PolicySpec {
/// The server-level freshness window. `None` keeps [`crate::seitan::DEFAULT_WINDOW`].
pub freshness_window: Option<Duration>,
/// Who may pull a world's events from this server.
pub pull_policy: PullPolicy,
}

/// Who may create a group. Anyone may by default. A config may list who may.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CreateRule {
Expand Down Expand Up @@ -164,6 +183,30 @@ impl ServerConfig {
&self.create
}

/// The server's serving policy, as the `[policy]` table set it (or the code defaults).
#[must_use]
pub const fn policy(&self) -> PolicySpec {
self.policy
}

/// The freshness settings this server applies: the configured window at the server
/// level, with the world and inviter levels unset, so a more specific setting made
/// elsewhere still wins and the code default still applies when nothing is set.
#[must_use]
pub fn freshness(&self) -> Freshness {
Freshness {
server: self.policy.freshness_window,
world: None,
inviter: None,
}
}

/// Who may pull a world's events from this server, as configured.
#[must_use]
pub const fn pull_policy(&self) -> PullPolicy {
self.policy.pull_policy
}

/// The public key a user key names.
#[must_use]
pub fn user_id(&self, key: &str) -> Option<Key> {
Expand Down
102 changes: 100 additions & 2 deletions pkgs/id/src/server_config/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@
//! key. A key is claimed once across users and groups, so it names one object.

use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;

use p2panda_core::Hash;
use serde::Deserialize;
use thiserror::Error;

use super::{CreateRule, GroupSpec, Object, ServerConfig, UserSpec};
use super::{CreateRule, GroupSpec, Object, PolicySpec, ServerConfig, UserSpec};
use crate::directory::{hex_to_array, normalize_key};
use crate::groups::{Key, Role};
use crate::pull_policy::PullPolicy;

/// Why a config was refused.
#[derive(Clone, Debug, PartialEq, Eq, Error)]
Expand Down Expand Up @@ -85,6 +87,17 @@ pub enum ConfigError {
/// The creator's key.
creator: String,
},
/// A pull policy name is neither of the two policies.
#[error("`{policy}` in {place} is not a pull policy; use open or members")]
UnknownPullPolicy {
/// The name given.
policy: String,
/// Where it is.
place: String,
},
/// The freshness window is zero seconds, so no accept could ever fall inside it.
#[error("the freshness window in [policy] is 0 seconds; omit it or give at least 1")]
ZeroWindow,
/// A group lists one member twice.
#[error("group `{group}` lists member `{member}` more than once")]
DuplicateMember {
Expand All @@ -99,6 +112,7 @@ pub enum ConfigError {
#[serde(deny_unknown_fields)]
struct Raw {
create: Option<RawCreate>,
policy: Option<RawPolicy>,
#[serde(default)]
users: Vec<RawUser>,
#[serde(default)]
Expand All @@ -115,6 +129,13 @@ struct RawCreate {
min_role: Option<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPolicy {
freshness_window_seconds: Option<u64>,
pull_policy: Option<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawUser {
Expand Down Expand Up @@ -217,15 +238,49 @@ pub(super) fn parse(text: &str) -> Result<ServerConfig, ConfigError> {
None => CreateRule::Anyone,
Some(rule) => create_rule(rule, &names)?,
};
let policy = match &raw.policy {
None => PolicySpec::default(),
Some(raw_policy) => policy_spec(raw_policy)?,
};
Ok(ServerConfig {
users,
groups,
create,
policy,
names,
aliases,
})
}

/// The serving policy from its `[policy]` table. An absent table, and a table that sets
/// neither knob, both give the code defaults.
fn policy_spec(raw: &RawPolicy) -> Result<PolicySpec, ConfigError> {
let freshness_window = match raw.freshness_window_seconds {
None => None,
Some(0) => return Err(ConfigError::ZeroWindow),
Some(seconds) => Some(Duration::from_secs(seconds)),
};
let pull_policy = match &raw.pull_policy {
None => PullPolicy::Open,
Some(name) => parse_pull_policy(name, "[policy].pull_policy")?,
};
Ok(PolicySpec {
freshness_window,
pull_policy,
})
}

fn parse_pull_policy(name: &str, place: &str) -> Result<PullPolicy, ConfigError> {
match name.trim().to_ascii_lowercase().as_str() {
"open" => Ok(PullPolicy::Open),
"members" => Ok(PullPolicy::Members),
_ => Err(ConfigError::UnknownPullPolicy {
policy: name.to_owned(),
place: place.to_owned(),
}),
}
}

/// The create rule from its `[create]` table, with every name resolved.
fn create_rule(
rule: &RawCreate,
Expand Down Expand Up @@ -364,7 +419,8 @@ mod tests {
use ed25519_dalek::SigningKey;

use crate::groups::{Key, Role};
use crate::server_config::{ConfigError, CreateRule, Object, ServerConfig};
use crate::pull_policy::PullPolicy;
use crate::server_config::{ConfigError, CreateRule, Object, PolicySpec, ServerConfig};
use crate::world::hex_encode;

/// The public key of the account that the test calls `n`.
Expand Down Expand Up @@ -412,6 +468,48 @@ mod tests {
assert_eq!(config.group_id("ann"), None, "a user key is not a group");
}

#[test]
fn test_no_policy_table_keeps_the_code_defaults() {
let config = config("").unwrap();
assert_eq!(config.pull_policy(), PullPolicy::Open);
assert_eq!(config.freshness().window(), crate::seitan::DEFAULT_WINDOW);
assert_eq!(config.policy(), PolicySpec::default());
}

#[test]
fn test_a_policy_table_sets_both_knobs() {
let config =
config("\n[policy]\nfreshness_window_seconds = 60\npull_policy = \"members\"\n")
.unwrap();
assert_eq!(config.pull_policy(), PullPolicy::Members);
assert_eq!(
config.freshness().server,
Some(std::time::Duration::from_secs(60))
);
assert_eq!(
config.freshness().window(),
std::time::Duration::from_secs(60)
);
}

#[test]
fn test_an_unknown_pull_policy_fails_startup() {
let refused = config("\n[policy]\npull_policy = \"friends\"\n").unwrap_err();
assert!(matches!(refused, ConfigError::UnknownPullPolicy { .. }));
}

#[test]
fn test_an_unknown_policy_key_fails_startup() {
let refused = config("\n[policy]\npull_policy = \"open\"\nwindow = 60\n").unwrap_err();
assert!(matches!(refused, ConfigError::Parse(_)));
}

#[test]
fn test_a_zero_freshness_window_fails_startup() {
let refused = config("\n[policy]\nfreshness_window_seconds = 0\n").unwrap_err();
assert_eq!(refused, ConfigError::ZeroWindow);
}

#[test]
fn test_the_same_text_parses_to_the_same_config() {
assert_eq!(config(TEAM).unwrap(), config(TEAM).unwrap());
Expand Down
Loading