use crate::errors::{Error, Result};
use crate::rules::{MatchType, Rule};
use crate::textrules::{TextRule, TextTier};
use crate::types::Freshness;
pub use crate::project_queries::{EXPOSURE_POLICY_IRI, POLICY_QUERY, TEXT_POLICY_QUERY};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectedPolicy {
pub rule: Rule,
pub effect: String,
}
pub fn decode_text_rules(sparql_json: &str) -> Result<Vec<TextRule>> {
let value: serde_json::Value = serde_json::from_str(sparql_json)
.map_err(|e| Error::Projection(format!("results are not JSON: {e}")))?;
let bindings = rows_of(&value)?;
let mut out = Vec::with_capacity(bindings.len());
for (i, binding) in bindings.iter().enumerate() {
let get = |key: &str| -> Option<String> { binding_value(binding, key) };
let required = |key: &str| -> Result<String> {
get(key).ok_or_else(|| {
Error::Projection(format!(
"text-rule row {i}: missing required binding `{key}`"
))
})
};
let tier = match required("tier")?.as_str() {
"block" => TextTier::Block,
"warn" => TextTier::Warn,
other => {
return Err(Error::Projection(format!(
"text-rule row {i}: unknown enforcementTier `{other}`"
)));
}
};
let iri = required("s")?;
let name = iri.rsplit('/').next().unwrap_or(&iri).to_string();
let rule = TextRule {
name,
label: get("label"),
pattern: required("regex")?,
tier,
class: get("class"),
exempt_path_regex: get("exempt"),
rationale: get("rationale"),
};
match out.iter_mut().find(|r: &&mut TextRule| r.name == rule.name) {
None => out.push(rule),
Some(existing) => {
if existing.pattern != rule.pattern || existing.tier != rule.tier {
return Err(Error::Projection(format!(
"text-rule `{}` has conflicting definitions in the graph \
(regex or enforcementTier differ across its rows) — \
refusing to guess which one governs",
rule.name
)));
}
merge_optional(&mut existing.rationale, rule.rationale);
merge_optional(&mut existing.label, rule.label);
merge_optional(&mut existing.class, rule.class);
merge_optional(&mut existing.exempt_path_regex, rule.exempt_path_regex);
}
}
}
Ok(out)
}
fn merge_optional(existing: &mut Option<String>, incoming: Option<String>) {
let Some(add) = incoming else { return };
match existing {
None => *existing = Some(add),
Some(have) => {
if !have.split(" — ").any(|part| part == add) {
have.push_str(" — ");
have.push_str(&add);
}
}
}
}
fn rows_of(value: &serde_json::Value) -> Result<&Vec<serde_json::Value>> {
value
.get("results")
.and_then(|r| r.get("bindings"))
.and_then(|b| b.as_array())
.ok_or_else(|| Error::Projection("results have no `results.bindings` array".to_string()))
}
fn binding_value(binding: &serde_json::Value, key: &str) -> Option<String> {
binding
.get(key)
.and_then(|v| v.get("value"))
.and_then(|v| v.as_str())
.map(str::to_string)
}
pub fn fetch_text_rules(endpoint: &str) -> Result<Vec<TextRule>> {
decode_text_rules(&query(endpoint, TEXT_POLICY_QUERY)?)
}
const HTTP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
fn query(endpoint: &str, sparql: &str) -> Result<String> {
let url = format!("{}/query", endpoint.trim_end_matches('/'));
let body = serde_json::json!({ "query": sparql }).to_string();
let resp = ureq::post(&url)
.timeout(HTTP_TIMEOUT)
.set("Content-Type", "application/json")
.set("Accept", "application/sparql-results+json")
.send_string(&body)
.map_err(|e| Error::Projection(format!("POST {url} failed: {e}")))?;
resp.into_string()
.map_err(|e| Error::Projection(format!("could not read /query response: {e}")))
}
pub fn decode_policies(sparql_json: &str) -> Result<Vec<ProjectedPolicy>> {
let value: serde_json::Value = serde_json::from_str(sparql_json)
.map_err(|e| Error::Projection(format!("results are not JSON: {e}")))?;
let bindings = value
.get("results")
.and_then(|r| r.get("bindings"))
.and_then(|b| b.as_array())
.ok_or_else(|| Error::Projection("results have no `results.bindings` array".to_string()))?;
let mut out = Vec::with_capacity(bindings.len());
for (i, binding) in bindings.iter().enumerate() {
let required = |key: &str| -> Result<String> {
binding
.get(key)
.and_then(|v| v.get("value"))
.and_then(|v| v.as_str())
.map(str::to_string)
.ok_or_else(|| {
Error::Projection(format!("row {i}: missing required binding `{key}`"))
})
};
let optional = |key: &str| -> Option<String> {
binding
.get(key)
.and_then(|v| v.get("value"))
.and_then(|v| v.as_str())
.map(str::to_string)
};
let match_type = match required("matchType")?.as_str() {
"must-match" => MatchType::MustMatch,
"must-not-match" => MatchType::MustNotMatch,
"must-exist" => MatchType::MustExist,
other => {
return Err(Error::Projection(format!(
"row {i}: unknown matchType `{other}`"
)))
}
};
let language = required("language")?;
let query = required("query")?;
let pattern = required("pattern")?;
let name = optional("name").unwrap_or_else(|| format!("quipu-policy-{i}"));
let effect = optional("effect").unwrap_or_else(|| "warn".to_string());
out.push(ProjectedPolicy {
rule: Rule {
name,
language,
query,
gate: optional("gate"),
match_type,
pattern,
applies_to: Vec::new(),
message: None,
},
effect,
});
}
Ok(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RepoExposure {
Public,
Internal,
Unknown(String),
}
pub fn fetch_repo_exposure(endpoint: &str, repo: &str) -> RepoExposure {
let url = format!("{}/policy/check", endpoint.trim_end_matches('/'));
let target = format!("http://aegis.gastown.local/ontology/repo_{repo}");
let body = serde_json::json!({ "policy": EXPOSURE_POLICY_IRI, "target": target }).to_string();
let resp = match ureq::post(&url)
.timeout(HTTP_TIMEOUT)
.set("Content-Type", "application/json")
.send_string(&body)
{
Ok(r) => r,
Err(e) => return RepoExposure::Unknown(format!("POST {url} failed: {e}")),
};
let text = match resp.into_string() {
Ok(t) => t,
Err(e) => return RepoExposure::Unknown(format!("unreadable /policy/check reply: {e}")),
};
let value: serde_json::Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(e) => return RepoExposure::Unknown(format!("/policy/check reply is not JSON: {e}")),
};
match value.get("outcome").and_then(|o| o.as_str()) {
Some("satisfied") => RepoExposure::Public,
Some("unsatisfied") => RepoExposure::Internal,
Some("unknown") | None => RepoExposure::Unknown(format!(
"repo `{repo}` is not in the graph (no `repo_{repo}` entity with remote facts)"
)),
Some(other) => RepoExposure::Unknown(format!("unrecognised outcome `{other}`")),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectedViolation {
pub message: String,
pub blocking: bool,
}
#[must_use]
pub fn effect_blocks(effect: &str) -> bool {
!matches!(effect, "warn" | "record" | "allow")
}
#[must_use]
pub fn evaluate_projected(
policies: &[ProjectedPolicy],
source: &str,
language: &str,
rel: &str,
) -> Vec<ProjectedViolation> {
let mut out = Vec::new();
for policy in policies {
let blocking = effect_blocks(&policy.effect);
for violation in
crate::rules::evaluate(std::slice::from_ref(&policy.rule), source, language, rel)
{
out.push(ProjectedViolation {
message: violation.message,
blocking,
});
}
}
out
}
#[derive(Debug, Clone)]
pub struct ProjectionRegistry {
endpoint: String,
policies: Vec<ProjectedPolicy>,
text_rules: Vec<TextRule>,
freshness: Freshness,
}
impl ProjectionRegistry {
#[must_use]
pub fn new(endpoint: &str) -> Self {
Self {
endpoint: endpoint.to_string(),
policies: Vec::new(),
text_rules: Vec::new(),
freshness: Freshness::Stale,
}
}
#[must_use]
pub fn text_rules(&self) -> &[TextRule] {
&self.text_rules
}
#[must_use]
pub fn policies(&self) -> &[ProjectedPolicy] {
&self.policies
}
#[must_use]
pub fn freshness(&self) -> Freshness {
self.freshness
}
pub fn refresh(&mut self) -> Result<()> {
match (
fetch_policies(&self.endpoint),
fetch_text_rules(&self.endpoint),
) {
(Ok(policies), Ok(text_rules)) => {
self.policies = policies;
self.text_rules = text_rules;
self.freshness = Freshness::Fresh;
Ok(())
}
(Err(e), _) | (_, Err(e)) => {
self.freshness = Freshness::Stale;
Err(e)
}
}
}
pub fn set_policies(&mut self, policies: Vec<ProjectedPolicy>) {
self.policies = policies;
self.freshness = Freshness::Fresh;
}
pub fn set_text_rules(&mut self, text_rules: Vec<TextRule>) {
self.text_rules = text_rules;
self.freshness = Freshness::Fresh;
}
}
pub fn fetch_policies(endpoint: &str) -> Result<Vec<ProjectedPolicy>> {
decode_policies(&query(endpoint, POLICY_QUERY)?)
}
#[cfg(test)]
#[path = "project_test.rs"]
mod project_test;