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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Network policy primitives.
use alloc::string::String;
use alloc::vec::Vec;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Network protocols supported by allow lists.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Protocol {
/// Hypertext Transfer Protocol.
Http,
/// Hypertext Transfer Protocol Secure.
Https,
/// Generic TCP connectivity.
Tcp,
/// Generic UDP connectivity.
Udp,
/// gRPC.
Grpc,
/// Any protocol not covered above.
Custom(String),
}
/// Allow list describing permitted domains, ports, and protocols.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct AllowList {
/// Allowed domain suffixes or exact hosts.
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub domains: Vec<String>,
/// Allowed port numbers.
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub ports: Vec<u16>,
/// Allowed network protocols.
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub protocols: Vec<Protocol>,
}
impl AllowList {
/// Creates an empty allow list.
pub fn empty() -> Self {
Self {
domains: Vec::new(),
ports: Vec::new(),
protocols: Vec::new(),
}
}
/// Returns `true` when the allow list contains no rules.
pub fn is_empty(&self) -> bool {
self.domains.is_empty() && self.ports.is_empty() && self.protocols.is_empty()
}
}
impl Default for AllowList {
fn default() -> Self {
Self::empty()
}
}
/// High-level network policy composed of allow lists.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct NetworkPolicy {
/// Allow list enforced for egress connections.
pub egress: AllowList,
/// Whether destinations not present in the allow list should be denied.
pub deny_on_miss: bool,
}
impl NetworkPolicy {
/// Creates a policy denying unknown destinations by default.
pub fn strict(egress: AllowList) -> Self {
Self {
egress,
deny_on_miss: true,
}
}
}
/// Result of evaluating a network policy.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct PolicyDecision {
/// Canonical status for the decision.
pub status: PolicyDecisionStatus,
/// Optional list of reasons.
pub reasons: Vec<String>,
/// Legacy allow flag (retained for backward compatibility).
pub allow: Option<bool>,
/// Legacy single reason (retained for backward compatibility).
pub reason: Option<String>,
}
/// Status for a policy decision.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum PolicyDecisionStatus {
/// Request is allowed.
Allow,
/// Request is denied.
Deny,
}
#[cfg(feature = "serde")]
mod serde_impls {
use super::{PolicyDecision, PolicyDecisionStatus};
use alloc::vec::Vec;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
impl Serialize for PolicyDecision {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// status + reasons always emitted; legacy fields only when present.
let mut len = 2;
if self.allow.is_some() {
len += 1;
}
if self.reason.is_some() {
len += 1;
}
let mut state = serializer.serialize_struct("PolicyDecision", len)?;
state.serialize_field("status", &self.status)?;
state.serialize_field("reasons", &self.reasons)?;
if let Some(allow) = &self.allow {
state.serialize_field("allow", allow)?;
}
if let Some(reason) = &self.reason {
state.serialize_field("reason", reason)?;
}
state.end()
}
}
impl<'de> Deserialize<'de> for PolicyDecision {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
enum Field {
Allow,
Reason,
Status,
Reasons,
Unknown,
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D2>(deserializer: D2) -> Result<Self, D2::Error>
where
D2: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(
&self,
formatter: &mut core::fmt::Formatter,
) -> core::fmt::Result {
formatter.write_str("`allow`, `reason`, `status`, or `reasons`")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(match value {
"allow" => Field::Allow,
"reason" => Field::Reason,
"status" => Field::Status,
"reasons" => Field::Reasons,
_ => Field::Unknown,
})
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct PolicyDecisionVisitor;
impl<'de> Visitor<'de> for PolicyDecisionVisitor {
type Value = PolicyDecision;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str("policy decision")
}
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut allow: Option<Option<bool>> = None;
let mut reason: Option<Option<String>> = None;
let mut status: Option<PolicyDecisionStatus> = None;
let mut reasons: Option<Vec<String>> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Allow => {
if allow.is_some() {
return Err(de::Error::duplicate_field("allow"));
}
allow = Some(map.next_value()?);
}
Field::Reason => {
if reason.is_some() {
return Err(de::Error::duplicate_field("reason"));
}
reason = Some(map.next_value()?);
}
Field::Status => {
if status.is_some() {
return Err(de::Error::duplicate_field("status"));
}
status = Some(map.next_value()?);
}
Field::Reasons => {
if reasons.is_some() {
return Err(de::Error::duplicate_field("reasons"));
}
reasons = Some(map.next_value()?);
}
Field::Unknown => {
// Ignore unknown fields for forward compatibility.
let _ = map.next_value::<de::IgnoredAny>()?;
}
}
}
let status = status
.or_else(|| {
allow.flatten().map(|flag| {
if flag {
PolicyDecisionStatus::Allow
} else {
PolicyDecisionStatus::Deny
}
})
})
.unwrap_or(PolicyDecisionStatus::Allow);
let reasons_vec = match (reasons, reason.clone()) {
(Some(list), _) => list,
(None, Some(Some(msg))) => alloc::vec![msg],
(None, _) => Vec::new(),
};
Ok(PolicyDecision {
status,
reasons: reasons_vec,
allow: allow.flatten(),
reason: reason.flatten(),
})
}
}
deserializer.deserialize_struct(
"PolicyDecision",
&["status", "reasons", "allow", "reason"],
PolicyDecisionVisitor,
)
}
}
}