Repository navigation
Expand file tree
/
Copy pathengine.rs
More file actions
179 lines (166 loc) · 5.71 KB
/
Copy pathengine.rs
File metadata and controls
179 lines (166 loc) · 5.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::GuardError;
use crate::protocol::{
API_VERSION_V2, AnalyzerIdentity, Completeness, Enforcement, GuardContract, GuardFact,
GuardFacts, GuardSubject,
};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RuleStatus {
Pass,
Fail,
ReviewRequired,
Indeterminate,
NotApplicable,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Decision {
Allow,
Block,
RequireApproval,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuleEvaluation {
pub rule_id: String,
pub status: RuleStatus,
pub enforcement: Enforcement,
pub matched_facts: Vec<GuardFact>,
pub detail: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GuardReport {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub kind: String,
pub evaluation_id: String,
pub engine_version: String,
pub contract_id: String,
pub contract_revision: String,
pub contract_digest: String,
pub facts_digest: String,
pub analyzer: AnalyzerIdentity,
pub subject: GuardSubject,
pub evaluations: Vec<RuleEvaluation>,
pub decision: Decision,
pub signed: bool,
}
/// A stable hexadecimal SHA-256 digest over a canonical serialization of the provided struct.
/// Struct field order is deterministic; caller-supplied fact ordering is normalized before hashing.
pub fn digest_json<T: Serialize>(value: &T) -> Result<String, GuardError> {
let bytes =
serde_json::to_vec(value).map_err(|error| GuardError::Serialization(error.to_string()))?;
let mut hasher = Sha256::new();
hasher.update(bytes);
Ok(format!("sha256:{:x}", hasher.finalize()))
}
pub fn evaluate(
contract: &GuardContract,
fact_set: &GuardFacts,
) -> Result<GuardReport, GuardError> {
contract.validate()?;
fact_set.validate()?;
let mut canonical_facts = fact_set.clone();
canonical_facts.facts.sort();
canonical_facts.facts.dedup();
if let Some(coverage) = &mut canonical_facts.coverage {
coverage.entities.sort();
coverage.predicates.sort();
}
let contract_digest = digest_json(contract)?;
let facts_digest = digest_json(&canonical_facts)?;
let evaluation_id = digest_json(&(
&contract.api_version,
env!("CARGO_PKG_VERSION"),
&contract_digest,
&facts_digest,
))?;
let mut evaluations = Vec::with_capacity(contract.spec.rules.len());
for rule in &contract.spec.rules {
let (violated, matched) =
crate::graph_evaluation::violation(&rule.assertion, &canonical_facts.facts);
let coverage_problem = crate::graph_evaluation::coverage_problem(
&rule.assertion,
&canonical_facts,
contract.api_version == API_VERSION_V2,
);
let (status, detail) = if canonical_facts.completeness == Completeness::Partial {
(
RuleStatus::Indeterminate,
format!(
"analyzer did not provide a complete fact set: {}",
canonical_facts.diagnostics.join("; ")
),
)
} else if let Some(problem) = coverage_problem {
(RuleStatus::Indeterminate, problem)
} else if !violated {
(
RuleStatus::Pass,
"constraint satisfied within declared scope".to_owned(),
)
} else {
match rule.enforcement {
Enforcement::Enforce => (
RuleStatus::Fail,
format!("constraint violated; {} witness edge(s)", matched.len()),
),
Enforcement::Review => (
RuleStatus::ReviewRequired,
format!("{} relation(s) need approval", matched.len()),
),
Enforcement::Advise => (
RuleStatus::Pass,
format!("advisory: found {} matching relation(s)", matched.len()),
),
}
};
evaluations.push(RuleEvaluation {
rule_id: rule.id.clone(),
status,
enforcement: rule.enforcement.clone(),
matched_facts: matched,
detail,
});
}
let decision = if evaluations
.iter()
.any(|item| matches!(item.status, RuleStatus::Fail | RuleStatus::Indeterminate))
{
Decision::Block
} else if evaluations
.iter()
.any(|item| matches!(item.status, RuleStatus::ReviewRequired))
{
Decision::RequireApproval
} else {
Decision::Allow
};
Ok(GuardReport {
api_version: contract.api_version.clone(),
kind: "GuardReport".into(),
evaluation_id,
engine_version: env!("CARGO_PKG_VERSION").into(),
contract_id: contract.metadata.id.clone(),
contract_revision: contract.metadata.revision.clone(),
contract_digest,
facts_digest,
analyzer: fact_set.analyzer.clone(),
subject: fact_set.subject.clone(),
evaluations,
decision,
// Local reports are UNSIGNED by design. A trusted CI can later issue attestations.
signed: false,
})
}
/// Recompute the entire report; self-described digests are never accepted as verification proof.
pub fn verify_report(
report: &GuardReport,
contract: &GuardContract,
facts: &GuardFacts,
) -> Result<bool, GuardError> {
Ok(&evaluate(contract, facts)? == report)
}