Skip to main content

domainforge_core/projection/rego/
mod.rs

1//! OPA/Rego projection: a SEA model's `Policy` declarations become Rego v1
2//! modules that reproduce the DomainForge evaluator's three-valued result per
3//! policy and aggregate those results into an allow / deny / escalate decision.
4//!
5//! Scope:
6//! - Policies are lowered from the resolved graph into a narrow policy IR
7//!   ([`ir::RegoPolicyIr`]). A policy using any construct outside that IR
8//!   fails the whole projection with [`RegoProjectionError::Unrepresentable`];
9//!   nothing is approximated or dropped.
10//! - `True` / `False` / `Unknown` and evaluation errors stay distinct end to
11//!   end. Rego `undefined` never stands in for `Unknown`.
12//! - The aggregate decision is this projection's own contract
13//!   (`domainforge.rego.decision/v1`): the evaluator has no aggregate outcome.
14//!   The fidelity report records it as `adapter`, not `isomorphic`.
15//!
16//! Output tree (deterministic; only `provenance.json` carries `created_at`):
17//!
18//! ```text
19//! bundle/.manifest                          OPA bundle manifest (roots, revision)
20//! bundle/data.json                          policy metadata + model identity
21//! bundle/domainforge/sea/lib.rego           three-valued helpers (static)
22//! bundle/domainforge/policy/decision.rego   decision contract (static)
23//! bundle/domainforge/policy/policies.rego   one rule per policy (generated)
24//! contracts/input.schema.json               typed input contract
25//! contracts/decision.schema.json            decision contract
26//! fixtures/<name>.json                      input + evaluator-derived expectation
27//! tests/decision_test.rego                  `opa test` cases from the fixtures
28//! fidelity-report.json                      per-policy fidelity classification
29//! provenance.json                           model identity + file hashes
30//! ```
31
32pub mod ir;
33pub mod reference;
34mod render;
35
36use crate::formatter::{format as format_source, FormatConfig};
37use crate::graph::Graph;
38use crate::projection::sink::ArtifactSink;
39use ir::RegoPolicyIr;
40use serde_json::{json, Map, Value};
41use sha2::{Digest, Sha256};
42use std::collections::BTreeMap;
43
44/// Version of the emitted artifact layout and Rego library.
45pub const PROJECTION_VERSION: &str = "domainforge-rego/v1";
46pub const FIDELITY_SCHEMA: &str = "domainforge.rego.fidelity/v1";
47pub const PROVENANCE_SCHEMA: &str = "domainforge.rego.provenance/v1";
48
49const LIB_REGO: &str = include_str!("rego/lib.rego");
50const DECISION_REGO: &str = include_str!("rego/decision.rego");
51
52pub const MANIFEST_FILE: &str = "bundle/.manifest";
53pub const DATA_FILE: &str = "bundle/data.json";
54pub const LIB_FILE: &str = "bundle/domainforge/sea/lib.rego";
55pub const DECISION_FILE: &str = "bundle/domainforge/policy/decision.rego";
56pub const POLICIES_FILE: &str = "bundle/domainforge/policy/policies.rego";
57pub const INPUT_SCHEMA_FILE: &str = "contracts/input.schema.json";
58pub const DECISION_SCHEMA_FILE: &str = "contracts/decision.schema.json";
59pub const TEST_FILE: &str = "tests/decision_test.rego";
60pub const FIDELITY_FILE: &str = "fidelity-report.json";
61pub const PROVENANCE_FILE: &str = "provenance.json";
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum RegoProjectionError {
65    /// A policy uses a construct the projection cannot express faithfully.
66    Unrepresentable {
67        policy: String,
68        construct: String,
69        reason: String,
70    },
71    /// The model could not be turned into projection input.
72    Model(String),
73    /// An artifact could not be written.
74    Write(String),
75}
76
77impl std::fmt::Display for RegoProjectionError {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Self::Unrepresentable {
81                policy,
82                construct,
83                reason,
84            } => write!(
85                f,
86                "REGO001 unrepresentable: policy '{policy}' uses {construct}: {reason}"
87            ),
88            Self::Model(message) => write!(f, "REGO002 model: {message}"),
89            Self::Write(message) => write!(f, "REGO003 write: {message}"),
90        }
91    }
92}
93
94impl std::error::Error for RegoProjectionError {}
95
96fn sha256(content: &str) -> String {
97    format!("sha256:{}", hex::encode(Sha256::digest(content.as_bytes())))
98}
99
100fn pretty(value: &Value) -> String {
101    let mut out = serde_json::to_string_pretty(value).expect("JSON values serialize");
102    out.push('\n');
103    out
104}
105
106/// The same model hash `cell.lock` records: sha256 of the canonically
107/// formatted source, so whitespace-only edits do not change the identity.
108pub fn model_hash(source: &str) -> Result<String, RegoProjectionError> {
109    let canonical = format_source(source, FormatConfig::default())
110        .map_err(|e| RegoProjectionError::Model(format!("failed to canonicalize source: {e}")))?;
111    Ok(sha256(&canonical))
112}
113
114fn identity(model_hash: &str) -> Value {
115    json!({ "hash": model_hash, "projection": PROJECTION_VERSION })
116}
117
118fn data_document(ir: &RegoPolicyIr, model_hash: &str) -> Value {
119    let mut policies = Map::new();
120    for p in &ir.policies {
121        policies.insert(
122            p.key.clone(),
123            json!({
124                "id": p.id,
125                "name": p.name,
126                "namespace": p.namespace,
127                "version": p.version,
128                "modality": p.modality,
129                "kind": p.kind,
130                "priority": p.priority,
131                "severity": p.severity,
132                "rationale": p.rationale,
133                "tags": p.tags,
134            }),
135        );
136    }
137    json!({
138        "domainforge": {
139            "model": {
140                "identity": identity(model_hash),
141                "collections": ir.collections,
142                "policies": policies,
143            }
144        }
145    })
146}
147
148fn input_schema(ir: &RegoPolicyIr) -> Value {
149    let mut collections = Map::new();
150    for name in &ir.collections {
151        let fields: Map<String, Value> = ir
152            .fields
153            .iter()
154            .filter(|(collection, _)| collection == name)
155            .map(|(_, field)| (field.clone(), json!({})))
156            .collect();
157        collections.insert(
158            name.clone(),
159            json!({
160                "type": "array",
161                "items": {
162                    "type": "object",
163                    "description": "Fields the policies read. A missing field is Unknown, not false.",
164                    "properties": fields,
165                },
166            }),
167        );
168    }
169    json!({
170        "$schema": "https://json-schema.org/draft/2020-12/schema",
171        "$id": "domainforge.rego.input/v1",
172        "type": "object",
173        "required": ["facts"],
174        "properties": {
175            "facts": {
176                "type": "object",
177                "required": ir.collections,
178                "properties": collections,
179            }
180        },
181    })
182}
183
184fn decision_schema() -> Value {
185    let tri = json!({ "enum": ["true", "false", "unknown", "error"] });
186    json!({
187        "$schema": "https://json-schema.org/draft/2020-12/schema",
188        "$id": reference::DECISION_CONTRACT,
189        "type": "object",
190        "additionalProperties": false,
191        "required": ["contract", "outcome", "results", "reasons", "input_errors", "model"],
192        "properties": {
193            "contract": { "const": reference::DECISION_CONTRACT },
194            "outcome": { "enum": ["allow", "deny", "escalate"] },
195            "results": { "type": "object", "additionalProperties": tri },
196            "reasons": {
197                "type": "array",
198                "items": {
199                    "type": "object",
200                    "additionalProperties": false,
201                    "required": ["policy", "code", "modality", "severity", "priority", "blocking"],
202                    "properties": {
203                        "policy": { "type": "string" },
204                        "code": { "enum": ["violated", "unknown", "evaluation_error", "malformed_input"] },
205                        "modality": { "type": "string" },
206                        "severity": { "enum": ["error", "warning", "info"] },
207                        "priority": { "type": "integer" },
208                        "blocking": { "type": "boolean" },
209                    },
210                },
211            },
212            "input_errors": { "type": "array", "items": { "type": "string" } },
213            "model": {
214                "type": "object",
215                "required": ["hash", "projection"],
216                "properties": {
217                    "hash": { "type": "string" },
218                    "projection": { "type": "string" },
219                },
220            },
221        },
222    })
223}
224
225/// Fixture inputs derived from the model. Each expectation is computed by the
226/// DomainForge evaluator, so `opa test` on the output is itself a differential
227/// check for this model.
228fn fixtures(
229    graph: &Graph,
230    ir: &RegoPolicyIr,
231    identity: &Value,
232) -> Result<Vec<(&'static str, Value)>, RegoProjectionError> {
233    let model = reference::facts_from_graph(graph, ir).map_err(RegoProjectionError::Model)?;
234
235    let empty: Map<String, Value> = ir
236        .collections
237        .iter()
238        .map(|name| (name.clone(), json!([])))
239        .collect();
240
241    // Incomplete information: every field a policy reads is absent.
242    let mut incomplete = model.clone();
243    for (collection, field) in &ir.fields {
244        if let Some(items) = incomplete["facts"][collection].as_array_mut() {
245            for item in items {
246                if let Some(object) = item.as_object_mut() {
247                    object.remove(field);
248                }
249            }
250        }
251    }
252
253    let inputs = [
254        ("model", model),
255        ("empty", json!({ "facts": empty })),
256        ("incomplete", incomplete),
257        ("malformed", json!({ "facts": null })),
258    ];
259    Ok(inputs
260        .into_iter()
261        .map(|(name, input)| {
262            let expected = reference::decide(ir, identity, &input);
263            (name, json!({ "input": input, "expected": expected }))
264        })
265        .collect())
266}
267
268fn test_module(fixtures: &[(&'static str, Value)]) -> String {
269    let mut out = String::from(
270        "# Generated by `domainforge project --format rego`. Do not edit.\n\
271         # Expectations come from the DomainForge evaluator (see fixtures/).\n\
272         package domainforge.policy_test\n\nimport rego.v1\n\nimport data.domainforge.policy\n",
273    );
274    for (name, fixture) in fixtures {
275        out.push_str(&format!(
276            "\ntest_{name} if {{\n\tpolicy.decision == {} with input as {}\n}}\n",
277            fixture["expected"], fixture["input"]
278        ));
279    }
280    out
281}
282
283fn fidelity_report(ir: &RegoPolicyIr, model_hash: &str) -> Value {
284    let policies: Vec<Value> = ir
285        .policies
286        .iter()
287        .map(|p| {
288            json!({
289                "policy": p.key,
290                "classification": "isomorphic",
291                "constructs": p.constructs,
292            })
293        })
294        .collect();
295    json!({
296        "schema": FIDELITY_SCHEMA,
297        "projection": PROJECTION_VERSION,
298        "model": identity(model_hash),
299        "classes": {
300            "isomorphic": "the per-policy True/False/Unknown/error result equals the DomainForge evaluator's",
301            "structural": "carried as data with the same shape; not evaluated",
302            "adapter": "an explicit target adaptation, verified against a reference implementation",
303            "unrepresentable": "cannot be projected; the projection fails with REGO001",
304        },
305        "policies": policies,
306        "decision_contract": {
307            "classification": "adapter",
308            "contract": reference::DECISION_CONTRACT,
309            "reason": "The evaluator reports per-policy violations and has no aggregate outcome. \
310                       deny: any error-severity policy is violated or fails to evaluate, or the input is malformed; \
311                       escalate: otherwise, any error-severity policy is Unknown; allow: otherwise. \
312                       Priority orders reasons only; the evaluator does not use it to resolve conflicts.",
313        },
314        "metadata": {
315            "classification": "structural",
316            "fields": ["id", "name", "namespace", "version", "kind", "rationale", "tags"],
317        },
318        "caveats": [
319            "Numbers compare exactly in OPA and as f64 in the evaluator; results can differ for integers beyond 2^53.",
320            "Equality on array- or object-valued fields compares integer and float forms of the same number as equal in OPA and as different in the evaluator.",
321            "Results reflect the evaluator's default three-valued mode; the boolean mode is not projected.",
322        ],
323        "verification": {
324            "reference": "domainforge_core::policy::Policy::evaluate_with_mode (three-valued)",
325            "suite": "domainforge-core/tests/rego_projection_tests.rs",
326            "evaluator": "opa (see tests/decision_test.rego for this model's fixtures)",
327        },
328    })
329}
330
331/// Emit the Rego projection into `sink`; returns the emitted relative paths.
332pub fn emit(
333    graph: &Graph,
334    source: &str,
335    model_ref: &str,
336    created_at: Option<String>,
337    sink: &mut ArtifactSink,
338) -> Result<Vec<String>, RegoProjectionError> {
339    let created_at = created_at.unwrap_or_else(crate::timefmt::now_rfc3339);
340    let ir = RegoPolicyIr::build(graph)?;
341    let model_hash = model_hash(source)?;
342    let identity = identity(&model_hash);
343    let fixtures = fixtures(graph, &ir, &identity)?;
344
345    let mut files: BTreeMap<String, String> = BTreeMap::new();
346    files.insert(
347        MANIFEST_FILE.to_string(),
348        pretty(&json!({
349            "revision": model_hash,
350            "roots": ["domainforge"],
351            "rego_version": 1,
352            "metadata": { "projection": PROJECTION_VERSION },
353        })),
354    );
355    files.insert(
356        DATA_FILE.to_string(),
357        pretty(&data_document(&ir, &model_hash)),
358    );
359    files.insert(LIB_FILE.to_string(), LIB_REGO.to_string());
360    files.insert(DECISION_FILE.to_string(), DECISION_REGO.to_string());
361    files.insert(
362        POLICIES_FILE.to_string(),
363        render::policies_module(&ir.policies, &model_hash),
364    );
365    files.insert(INPUT_SCHEMA_FILE.to_string(), pretty(&input_schema(&ir)));
366    files.insert(DECISION_SCHEMA_FILE.to_string(), pretty(&decision_schema()));
367    for (name, fixture) in &fixtures {
368        files.insert(format!("fixtures/{name}.json"), pretty(fixture));
369    }
370    files.insert(TEST_FILE.to_string(), test_module(&fixtures));
371    files.insert(
372        FIDELITY_FILE.to_string(),
373        pretty(&fidelity_report(&ir, &model_hash)),
374    );
375
376    let hashes: Map<String, Value> = files
377        .iter()
378        .map(|(path, content)| (path.clone(), json!(sha256(content))))
379        .collect();
380    files.insert(
381        PROVENANCE_FILE.to_string(),
382        pretty(&json!({
383            "schema": PROVENANCE_SCHEMA,
384            "projection": PROJECTION_VERSION,
385            "generator": format!("domainforge-core {}", env!("CARGO_PKG_VERSION")),
386            "model_ref": model_ref,
387            "created_at": created_at,
388            "model": identity,
389            "policy_count": ir.policies.len(),
390            "files": hashes,
391        })),
392    );
393
394    for (path, content) in &files {
395        sink.write(path, content)
396            .map_err(RegoProjectionError::Write)?;
397    }
398    Ok(files.into_keys().collect())
399}
400
401/// Binding surface: source in, path→content map out, no filesystem.
402pub fn project_rego_in_memory(
403    graph: &Graph,
404    source: &str,
405    model_ref: &str,
406    created_at: Option<String>,
407) -> Result<BTreeMap<String, String>, RegoProjectionError> {
408    let mut map = BTreeMap::new();
409    let mut sink = ArtifactSink::Memory {
410        prefix: String::new(),
411        map: &mut map,
412    };
413    emit(graph, source, model_ref, created_at, &mut sink)?;
414    Ok(map)
415}