pub const GRANT_DIMENSIONS: &[&str] = &[
"approver",
"budget",
"candidate",
"channel",
"operation",
"policy",
"project",
"proposal",
"revision",
"scope",
"task",
];
pub const GRANT_COMPARED_DIMENSIONS: &[&str] = &[
"budget",
"candidate",
"operation",
"policy",
"project",
"proposal",
"revision",
"scope",
"task",
];
pub const GRANT_RECORDED_DIMENSIONS: &[&str] = &["approver", "channel"];
pub const GRANT_CHANNELS: &[&str] = &["host-confirmation", "interactive-cli", "studio"];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Budget {
pub files: Option<u64>,
pub executions: Option<u64>,
}
impl Budget {
pub fn parse_limits(text: &str) -> Result<Self, String> {
let mut budget = Self::default();
for part in text.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let (key, value) = part.split_once('=').ok_or_else(|| {
format!("`{part}` is not a budget limit; write `files=<n>` or `executions=<n>`")
})?;
let value = value.trim();
let count: u64 = value.parse().map_err(|_| {
format!("`{value}` is not a number of {key}; a budget names how many, not how much it hopes")
})?;
match key.trim() {
"files" => budget.files = Some(count),
"executions" => budget.executions = Some(count),
other => {
return Err(format!(
"`{other}` is not a budget dimension; the limits this workspace enforces are files and executions"
));
}
}
}
Ok(budget)
}
pub fn text(&self) -> String {
let mut parts = Vec::new();
if let Some(files) = self.files {
parts.push(format!("files={files}"));
}
if let Some(executions) = self.executions {
parts.push(format!("executions={executions}"));
}
if parts.is_empty() {
"none".to_owned()
} else {
parts.join(",")
}
}
pub fn covers(&self, cost: &Self) -> Result<(), String> {
if let (Some(allowed), Some(used)) = (self.files, cost.files)
&& used > allowed
{
return Err(format!(
"this landing would publish {used} file(s), and the approval covers {allowed}"
));
}
if let (Some(allowed), Some(used)) = (self.executions, cost.executions)
&& used > allowed
{
return Err(format!(
"this use would take the {used} execution(s) it asks for, and the approval covers {allowed}"
));
}
Ok(())
}
}
pub const GRANT_OPERATIONS: &[&str] = &["land", "publish", "widen"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Grant {
fields: Vec<(String, String)>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UseRequest<'a> {
pub project: &'a str,
pub task: &'a str,
pub candidate: &'a str,
pub proposal: &'a str,
pub revision: &'a str,
pub operation: &'a str,
pub paths: &'a [String],
pub policy: &'a str,
pub cost: Budget,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Allowance {
Covered,
Refused(String),
}
impl Allowance {
pub fn is_covered(&self) -> bool {
matches!(self, Self::Covered)
}
pub fn reason(&self) -> Option<&str> {
match self {
Self::Covered => None,
Self::Refused(reason) => Some(reason),
}
}
}
impl Grant {
pub fn issue<I, K, V>(fields: I) -> Result<Self, String>
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
let mut bound: Vec<(String, String)> = Vec::new();
for (name, value) in fields {
let name = name.into();
let value = value.into();
if !GRANT_DIMENSIONS.contains(&name.as_str()) {
return Err(format!(
"`{name}` is not a grant dimension; the list is fixed so a new one cannot be forgotten silently"
));
}
let value = value.trim().to_owned();
if value.is_empty() {
return Err(format!(
"grant dimension `{name}` has no value; a grant binds facts, not places where a fact would go"
));
}
if matches!(name.as_str(), "approver" | "channel") && value == "unknown" {
return Err(format!(
"`{name}` cannot be `unknown`: an approval nobody and no channel stands behind is not an approval"
));
}
if name == "budget" {
Budget::parse_limits(&value)?;
}
if name == "channel" && !GRANT_CHANNELS.contains(&value.as_str()) {
return Err(format!(
"`{value}` is not an approval channel; the channels are {} — a fourth one is invented, not approved",
GRANT_CHANNELS.join(", ")
));
}
if name == "operation" {
let members: Vec<&str> = value.split(',').map(str::trim).collect();
if members.is_empty() || members.iter().any(|member| member.is_empty()) {
return Err(
"`operation` names an empty verb; a grant authorises operations, not the absence of one"
.to_owned(),
);
}
if let Some(unknown) = members
.iter()
.find(|member| !GRANT_OPERATIONS.contains(member))
{
return Err(format!(
"`{unknown}` is not an operation a grant can authorize; the operations are {}",
GRANT_OPERATIONS.join(", ")
));
}
}
bound.push((name, value));
}
let missing: Vec<&str> = GRANT_DIMENSIONS
.iter()
.copied()
.filter(|name| !bound.iter().any(|(bound_name, _)| bound_name == name))
.collect();
if !missing.is_empty() {
return Err(format!(
"a grant is missing {} — a grant that leaves a dimension out cannot be compared, so it is not issued",
missing.join(", ")
));
}
bound.sort();
Ok(Self { fields: bound })
}
pub fn fields(&self) -> &[(String, String)] {
&self.fields
}
pub fn field(&self, name: &str) -> Option<&str> {
self.fields
.iter()
.find(|(field, _)| field == name)
.map(|(_, value)| value.as_str())
}
pub fn digest(&self) -> String {
xirang_kernel_sha256(&format!("{:?}", self.fields))
}
pub fn covers(&self, request: &UseRequest<'_>) -> Allowance {
let comparisons = [
("project", request.project),
("task", request.task),
("candidate", request.candidate),
("proposal", request.proposal),
("revision", request.revision),
];
for (name, used) in comparisons {
let granted = self.field(name).unwrap_or("");
if name == "revision" {
if matches!(
(granted.parse::<u64>(), used.parse::<u64>()),
(Ok(granted), Ok(used)) if granted >= used
) {
continue;
}
}
if granted != used {
return Allowance::Refused(format!(
"this use relies on `{name}` = `{used}`, and the grant says `{granted}`; an approval for one {name} never vouches for another"
));
}
}
let policy = self.field("policy").unwrap_or("");
if policy != request.policy {
return Allowance::Refused(format!(
"this use runs under policy `{}`, and the grant was issued under `{policy}`; an approval for one version of the policy never vouches for another",
request.policy
));
}
let granted = match Budget::parse_limits(self.field("budget").unwrap_or("")) {
Ok(budget) => budget,
Err(reason) => return Allowance::Refused(reason),
};
if let Err(reason) = granted.covers(&request.cost) {
return Allowance::Refused(reason);
}
let operations: Vec<&str> = self
.field("operation")
.unwrap_or("")
.split(',')
.map(str::trim)
.collect();
if !operations.contains(&request.operation) {
return Allowance::Refused(format!(
"this use is an `{}`, and the grant authorises `{}`; an approval for one operation never vouches for another",
request.operation,
operations.join(", ")
));
}
let scope: Vec<&str> = self.field("scope").unwrap_or("").split(',').collect();
for path in request.paths {
if !scope.iter().any(|prefix| {
let prefix = prefix.trim();
!prefix.is_empty() && (path == prefix || path.starts_with(&format!("{prefix}/")))
}) {
return Allowance::Refused(format!(
"`{path}` is outside the approved scope ({}); the grant covers the scope it names and nothing else",
scope.join(", ")
));
}
}
Allowance::Covered
}
}
fn xirang_kernel_sha256(input: &str) -> String {
super::super::identity::sha256_hex(input.as_bytes())
}
#[cfg(test)]
#[path = "grant_tests.rs"]
mod grant_tests;