openmoat_core/ir.rs
1//! The policy compiler's intermediate representation (ADR-019).
2//!
3//! [`lower()`] derives from `policy.yaml` the part of a decision an operating
4//! system layer can enforce: which paths may be read or written and which
5//! hosts may be reached. Every OS backend (a host's sandbox settings, Seatbelt,
6//! Landlock, the egress proxy) is generated from this one [`Enforcement`]; the
7//! hook backend is the engine itself ([`crate::CompiledPolicy`]), compiled from
8//! the same policy and context.
9//!
10//! An OS layer can only allow or deny, so lowering never widens: a hook `review`
11//! becomes a deny, and whatever cannot be represented exactly is narrowed and
12//! recorded as a [`Loss`]. The IR's verdict on any read, write or host is
13//! therefore the engine's verdict with `review` read as `deny`, or stricter,
14//! except on the paths of a `hook_only` deny group, which only the hook
15//! denies and [`Enforcement::decide_only`] lists (ADR-034).
16
17use std::fmt;
18
19use serde::Serialize;
20
21use crate::kind::Kind;
22
23mod braces;
24mod check;
25mod lower;
26
27pub use braces::alternatives as brace_alternatives;
28pub use check::Checker;
29pub use lower::{CLOUD_METADATA, CLOUD_METADATA_RULE, READ_ROOTS_RULE, lower};
30
31/// What an OS layer may enforce for one policy in one context.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
33pub struct Enforcement {
34 /// File reads and writes.
35 pub fs: Filesystem,
36 /// Outbound network.
37 pub egress: Egress,
38 /// Secrets the egress proxy and Claude Code's own broker inject for the
39 /// agent (ADR-020). One entry per policy `secrets:` item; OS backends
40 /// consume these without reading the policy again.
41 pub secrets: Vec<BrokeredSecret>,
42 /// Limits on the agent's processes. Always empty: no policy key sets one yet.
43 pub limits: Vec<ProcessLimit>,
44 /// Rules only the hook can apply, by kind. Shell semantics, environment
45 /// variables, MCP tool names and executable pins name things an OS layer
46 /// cannot see (a command line, a variable, a tool), so they are not lowered
47 /// and stay with the hook decision (ADR-018). The file paths of a `deny`
48 /// group marked `hook_only` stay with it too (ADR-034): OS layers leave
49 /// them to the other rules, so these are the one place the IR's own
50 /// verdicts may be wider than the hook's.
51 pub decide_only: Vec<DecideOnly>,
52 /// Where the IR is stricter than the hook decision, with the reason.
53 pub losses: Vec<Loss>,
54 /// Where OS layers may be wider than the hook decision, listed in the
55 /// policy (`sandbox.read_roots`). The hook keeps deciding these accesses;
56 /// deny rules still win over them. Not part of [`Filesystem`], so the IR's
57 /// own verdicts stay the hook's or stricter.
58 pub allowances: Vec<Allowance>,
59}
60
61/// File access rules. Paths are absolute, slash-separated globs with `~` and
62/// `${project}` already expanded once per spelling of each root (the home
63/// directory and project as given and with their symlinks resolved), and each
64/// brace group's alternatives written out ([`brace_alternatives`]).
65#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
66pub struct Filesystem {
67 /// Whether paths compare case-insensitively (default macOS and Windows file systems).
68 pub case_insensitive: bool,
69 /// Reads.
70 pub read: Access,
71 /// Writes, creates, deletes and moves.
72 pub write: Access,
73}
74
75/// Network rules. Hosts are lowercase globs and always compare case-insensitively.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
77pub struct Egress {
78 /// Any connection, a host fetch tool's included.
79 pub net: Access,
80 /// Requests by a host's read-only fetch tool (`WebFetch`), which `fetch`
81 /// and `net` rules both govern (ADR-017).
82 pub fetch: Access,
83}
84
85/// The rules for one kind of access, applied in order: a matching `deny` rule
86/// denies; otherwise a matching `allow` rule allows; otherwise `default`.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
88pub struct Access {
89 /// The effect when no rule matches.
90 pub default: Effect,
91 /// Rules that deny; an allow never overrides them.
92 pub deny: Vec<Rule>,
93 /// Rules that allow.
94 pub allow: Vec<Rule>,
95}
96
97/// One policy rule group's patterns from one list. It matches when at least
98/// one pattern matches and no `!` exclusion does, as in the policy.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
100pub struct Rule {
101 /// The policy rule group's id ([`CLOUD_METADATA_RULE`] for the built-in one).
102 pub id: String,
103 /// The policy list the patterns come from (`net` patterns also govern `fetch`).
104 pub list: Kind,
105 /// Expanded globs; a leading `!` excludes.
106 pub patterns: Vec<String>,
107}
108
109/// What an OS layer does with an access.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
111#[serde(rename_all = "lowercase")]
112pub enum Effect {
113 /// The access may proceed.
114 Allow,
115 /// The access is blocked.
116 Deny,
117}
118
119/// The policy rules of one kind that only the hook applies.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
121pub struct DecideOnly {
122 /// `shell`, `env.read`, `env.set`, `mcp` or `executables`; `fs.read` or
123 /// `fs.write` for `hook_only` groups; `when` for groups with argument
124 /// conditions (ADR-113).
125 pub kind: String,
126 /// Rule group ids, or program names for `executables`.
127 pub rules: Vec<String>,
128}
129
130/// A place where the IR denies something the hook would not deny.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
132pub struct Loss {
133 /// The access the loss applies to.
134 pub kind: Kind,
135 /// The rule group id, or `default.<kind>`/`default` for the defaults table.
136 pub rule: String,
137 /// What the hook does and what OS layers do instead.
138 pub message: String,
139}
140
141impl fmt::Display for Loss {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 write!(f, "{} `{}`: {}", self.kind, self.rule, self.message)
144 }
145}
146
147/// Accesses OS layers allow although the hook would not (ADR-019: the only
148/// way an OS layer may be wider than the hook, and always listed).
149#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
150pub struct Allowance {
151 /// The access the allowance applies to.
152 pub kind: Kind,
153 /// Where it comes from (`sandbox.read_roots`).
154 pub rule: String,
155 /// Expanded globs: each root and everything below it.
156 pub patterns: Vec<String>,
157 /// What the hook does and what OS layers do instead.
158 pub message: String,
159}
160
161impl fmt::Display for Allowance {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 write!(f, "{} `{}`: {}", self.kind, self.rule, self.message)
164 }
165}
166
167/// A secret the egress proxy or Claude Code's own broker injects (ADR-020).
168/// A copy of [`crate::Secret`]: the IR carries only the fields OS backends
169/// need, so a backend can read `ir.secrets` without the policy. Its `Debug`
170/// output names only the id, as for [`crate::Secret`].
171#[derive(Clone, PartialEq, Eq, Serialize)]
172pub struct BrokeredSecret {
173 /// Stable identifier (lowercase letters, digits and `-`).
174 pub id: String,
175 /// The one host whose requests receive the secret, lowercase DNS or IPv4.
176 pub host: String,
177 /// The request header the secret goes in (`Authorization`, `X-Api-Key`).
178 pub header: String,
179 /// Where OpenMoat reads the value.
180 pub source: crate::SecretSource,
181 /// Also inject into plain-HTTP requests; off unless the policy sets it.
182 pub plain_http: bool,
183 /// The one port of the plain-HTTP requests that get the value, when the
184 /// policy names one (80 otherwise).
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub port: Option<u16>,
187 /// `tls: terminate`: `openmoat run`'s proxy decrypts HTTPS to the host
188 /// and injects there (ADR-043).
189 #[serde(skip_serializing_if = "std::ops::Not::not")]
190 pub tls_terminate: bool,
191 /// The secret's `allow` rules (`METHOD /path`); empty when every request
192 /// to the host may receive it. A backend that cannot hold a secret to
193 /// them must not inject it.
194 #[serde(skip_serializing_if = "Vec::is_empty")]
195 pub allow: Vec<String>,
196}
197
198impl std::fmt::Debug for BrokeredSecret {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 f.debug_struct("BrokeredSecret")
201 .field("id", &self.id)
202 .finish_non_exhaustive()
203 }
204}
205
206/// A process limit. No value exists until the policy schema defines one.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
208pub enum ProcessLimit {}
209
210#[cfg(test)]
211mod tests;