axonflow-sdk-rust 0.11.0

Rust SDK for the AxonFlow AI governance platform
Documentation
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use serde::{Deserialize, Serialize};
use std::fmt;

/// Policy categories for organization and filtering.
///
/// The platform ships and extends its categories as data, so a category this
/// build does not name arrives as [`PolicyCategory::Unknown`], carrying the
/// platform's string verbatim, rather than failing the read it arrived in. It
/// re-serializes byte-identical. The known set is pinned to the categories the
/// platform's shipped posture uses (`testdata/shipped_posture_categories.json`),
/// because the spec's own enum is stale (getaxonflow/axonflow-enterprise#4224).
///
/// `#[non_exhaustive]` because `Unknown` does not make this enum additive for a
/// downstream crate: a match over the known variants plus `Unknown(_)` is
/// exhaustive today and would stop compiling the moment a category is added.
/// With the attribute, that match needs a `_` arm, and a new category is a
/// minor release rather than a breaking one.
///
/// Cross-SDK parity:
///   Go:     axonflow-sdk-go/policies.go (PolicyCategory)
///   Python: axonflow-sdk-python/axonflow/policies.py (PolicyCategory)
///   TS:     axonflow-sdk-typescript/src/types/policies.ts (PolicyCategory)
///   Java:   axonflow-sdk-java PolicyTypes.PolicyCategory
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[non_exhaustive]
pub enum PolicyCategory {
    /// `security-sqli`
    SecuritySqli,
    /// `security-admin`
    SecurityAdmin,
    /// `pii-global`
    PiiGlobal,
    /// `pii-us`
    PiiUs,
    /// `pii-eu`
    PiiEu,
    /// `pii-india`
    PiiIndia,
    /// `pii-singapore`
    PiiSingapore,
    /// `pii-indonesia`
    PiiIndonesia,
    /// `code-secrets`
    CodeSecrets,
    /// `code-unsafe`
    CodeUnsafe,
    /// `code-compliance`
    CodeCompliance,
    /// `sensitive-data`
    SensitiveData,
    /// `media-safety`
    MediaSafety,
    /// `media-biometric`
    MediaBiometric,
    /// `media-document`
    MediaDocument,
    /// `media-pii`
    MediaPii,
    /// `dynamic-risk`
    DynamicRisk,
    /// `dynamic-compliance`
    DynamicCompliance,
    /// `dynamic-security`
    DynamicSecurity,
    /// `dynamic-cost`
    DynamicCost,
    /// `dynamic-access`
    DynamicAccess,
    /// `security-dangerous`
    SecurityDangerous,
    /// `compliance-euaiact`
    ComplianceEuaiact,
    /// `dangerous_queries`
    DangerousQueries,
    /// `pii_detection`
    PiiDetection,
    /// `sql_injection`
    SqlInjection,
    /// A category this build does not know, carried verbatim.
    Unknown(String),
}

impl PolicyCategory {
    /// Every wire value this build knows.
    pub const KNOWN_WIRE_VALUES: &'static [&'static str] = &[
        "security-sqli",
        "security-admin",
        "pii-global",
        "pii-us",
        "pii-eu",
        "pii-india",
        "pii-singapore",
        "pii-indonesia",
        "code-secrets",
        "code-unsafe",
        "code-compliance",
        "sensitive-data",
        "media-safety",
        "media-biometric",
        "media-document",
        "media-pii",
        "dynamic-risk",
        "dynamic-compliance",
        "dynamic-security",
        "dynamic-cost",
        "dynamic-access",
        "security-dangerous",
        "compliance-euaiact",
        "dangerous_queries",
        "pii_detection",
        "sql_injection",
    ];

    /// The wire value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::SecuritySqli => "security-sqli",
            Self::SecurityAdmin => "security-admin",
            Self::PiiGlobal => "pii-global",
            Self::PiiUs => "pii-us",
            Self::PiiEu => "pii-eu",
            Self::PiiIndia => "pii-india",
            Self::PiiSingapore => "pii-singapore",
            Self::PiiIndonesia => "pii-indonesia",
            Self::CodeSecrets => "code-secrets",
            Self::CodeUnsafe => "code-unsafe",
            Self::CodeCompliance => "code-compliance",
            Self::SensitiveData => "sensitive-data",
            Self::MediaSafety => "media-safety",
            Self::MediaBiometric => "media-biometric",
            Self::MediaDocument => "media-document",
            Self::MediaPii => "media-pii",
            Self::DynamicRisk => "dynamic-risk",
            Self::DynamicCompliance => "dynamic-compliance",
            Self::DynamicSecurity => "dynamic-security",
            Self::DynamicCost => "dynamic-cost",
            Self::DynamicAccess => "dynamic-access",
            Self::SecurityDangerous => "security-dangerous",
            Self::ComplianceEuaiact => "compliance-euaiact",
            Self::DangerousQueries => "dangerous_queries",
            Self::PiiDetection => "pii_detection",
            Self::SqlInjection => "sql_injection",
            Self::Unknown(v) => v.as_str(),
        }
    }

    /// Whether this is a value this build knows.
    ///
    /// A false result is not an error: a newer platform ships categories this
    /// SDK was built without. It IS a reason not to treat the value as
    /// equivalent to any known one.
    pub fn is_known(&self) -> bool {
        !matches!(self, Self::Unknown(_))
    }
}

impl From<String> for PolicyCategory {
    fn from(v: String) -> Self {
        match v.as_str() {
            "security-sqli" => Self::SecuritySqli,
            "security-admin" => Self::SecurityAdmin,
            "pii-global" => Self::PiiGlobal,
            "pii-us" => Self::PiiUs,
            "pii-eu" => Self::PiiEu,
            "pii-india" => Self::PiiIndia,
            "pii-singapore" => Self::PiiSingapore,
            "pii-indonesia" => Self::PiiIndonesia,
            "code-secrets" => Self::CodeSecrets,
            "code-unsafe" => Self::CodeUnsafe,
            "code-compliance" => Self::CodeCompliance,
            "sensitive-data" => Self::SensitiveData,
            "media-safety" => Self::MediaSafety,
            "media-biometric" => Self::MediaBiometric,
            "media-document" => Self::MediaDocument,
            "media-pii" => Self::MediaPii,
            "dynamic-risk" => Self::DynamicRisk,
            "dynamic-compliance" => Self::DynamicCompliance,
            "dynamic-security" => Self::DynamicSecurity,
            "dynamic-cost" => Self::DynamicCost,
            "dynamic-access" => Self::DynamicAccess,
            "security-dangerous" => Self::SecurityDangerous,
            "compliance-euaiact" => Self::ComplianceEuaiact,
            "dangerous_queries" => Self::DangerousQueries,
            "pii_detection" => Self::PiiDetection,
            "sql_injection" => Self::SqlInjection,
            _ => Self::Unknown(v),
        }
    }
}

impl From<PolicyCategory> for String {
    fn from(v: PolicyCategory) -> Self {
        match v {
            PolicyCategory::Unknown(s) => s,
            known => known.as_str().to_string(),
        }
    }
}

impl fmt::Display for PolicyCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;

    fn posture() -> Value {
        serde_json::from_str(include_str!(
            "../../testdata/shipped_posture_categories.json"
        ))
        .expect("the vendored posture fixture")
    }

    #[test]
    fn pii_indonesia_serializes_to_wire_name() {
        let cat = PolicyCategory::PiiIndonesia;
        let json = serde_json::to_string(&cat).unwrap();
        assert_eq!(json, r#""pii-indonesia""#);
    }

    #[test]
    fn pii_indonesia_round_trips() {
        let cat = PolicyCategory::PiiIndonesia;
        let json = serde_json::to_string(&cat).unwrap();
        let back: PolicyCategory = serde_json::from_str(&json).unwrap();
        assert_eq!(back, PolicyCategory::PiiIndonesia);
    }

    #[test]
    fn all_categories_serialize_to_expected_wire_names() {
        let cases = vec![
            (PolicyCategory::SecuritySqli, "security-sqli"),
            (PolicyCategory::SecurityAdmin, "security-admin"),
            (PolicyCategory::PiiGlobal, "pii-global"),
            (PolicyCategory::PiiUs, "pii-us"),
            (PolicyCategory::PiiEu, "pii-eu"),
            (PolicyCategory::PiiIndia, "pii-india"),
            (PolicyCategory::PiiSingapore, "pii-singapore"),
            (PolicyCategory::PiiIndonesia, "pii-indonesia"),
            (PolicyCategory::CodeSecrets, "code-secrets"),
            (PolicyCategory::CodeUnsafe, "code-unsafe"),
            (PolicyCategory::CodeCompliance, "code-compliance"),
            (PolicyCategory::SensitiveData, "sensitive-data"),
            (PolicyCategory::MediaSafety, "media-safety"),
            (PolicyCategory::MediaBiometric, "media-biometric"),
            (PolicyCategory::MediaDocument, "media-document"),
            (PolicyCategory::MediaPii, "media-pii"),
            (PolicyCategory::DynamicRisk, "dynamic-risk"),
            (PolicyCategory::DynamicCompliance, "dynamic-compliance"),
            (PolicyCategory::DynamicSecurity, "dynamic-security"),
            (PolicyCategory::DynamicCost, "dynamic-cost"),
            (PolicyCategory::DynamicAccess, "dynamic-access"),
            (PolicyCategory::SecurityDangerous, "security-dangerous"),
            (PolicyCategory::ComplianceEuaiact, "compliance-euaiact"),
            (PolicyCategory::DangerousQueries, "dangerous_queries"),
            (PolicyCategory::PiiDetection, "pii_detection"),
            (PolicyCategory::SqlInjection, "sql_injection"),
        ];
        assert_eq!(cases.len(), PolicyCategory::KNOWN_WIRE_VALUES.len());
        for (variant, expected) in cases {
            let json = serde_json::to_string(&variant).unwrap();
            assert_eq!(json, format!(r#""{}""#, expected), "variant {:?}", variant);
            let back: PolicyCategory = serde_json::from_str(&json).unwrap();
            assert_eq!(back, variant, "{expected} parses back to its variant");
        }
    }

    #[test]
    fn every_known_wire_value_parses_to_a_known_variant_and_back() {
        for value in PolicyCategory::KNOWN_WIRE_VALUES {
            let category: PolicyCategory =
                serde_json::from_value(Value::String(value.to_string())).unwrap();
            assert!(category.is_known(), "{value} must be known");
            assert_eq!(category.as_str(), *value);
            assert_eq!(String::from(category), *value);
        }
    }

    /// The categories the platform's shipped posture uses that this enum
    /// lacked: `security-dangerous` failed a whole static-policy read in the
    /// other SDKs before they learned it.
    #[test]
    fn the_five_categories_the_platform_added_are_known() {
        for (value, variant) in [
            ("security-dangerous", PolicyCategory::SecurityDangerous),
            ("compliance-euaiact", PolicyCategory::ComplianceEuaiact),
            ("dangerous_queries", PolicyCategory::DangerousQueries),
            ("pii_detection", PolicyCategory::PiiDetection),
            ("sql_injection", PolicyCategory::SqlInjection),
        ] {
            let parsed: PolicyCategory = serde_json::from_str(&format!("\"{value}\"")).unwrap();
            assert_eq!(parsed, variant, "{value}");
        }
    }

    /// A category from a later platform is kept, not refused, and goes back
    /// out exactly as it came in.
    #[test]
    fn an_unknown_category_is_kept_and_re_serializes_byte_identical() {
        let wire = r#""a-category-from-a-later-platform""#;
        let parsed: PolicyCategory = serde_json::from_str(wire).unwrap();
        assert_eq!(
            parsed,
            PolicyCategory::Unknown("a-category-from-a-later-platform".into())
        );
        assert!(!parsed.is_known());
        assert_eq!(parsed.as_str(), "a-category-from-a-later-platform");
        assert_eq!(parsed.to_string(), "a-category-from-a-later-platform");
        assert_eq!(serde_json::to_string(&parsed).unwrap(), wire);
    }

    /// The read that failed in the other SDKs: an object carrying a category
    /// this enum did not name deserializes, and the category is kept.
    #[test]
    fn a_platform_object_with_an_unknown_category_deserializes() {
        #[derive(Deserialize)]
        struct Policy {
            category: PolicyCategory,
        }
        let known: Policy = serde_json::from_str(r#"{"category":"security-dangerous"}"#).unwrap();
        assert_eq!(known.category, PolicyCategory::SecurityDangerous);
        let unknown: Policy = serde_json::from_str(r#"{"category":"brand-new"}"#).unwrap();
        assert_eq!(
            unknown.category,
            PolicyCategory::Unknown("brand-new".into())
        );
    }

    /// Pinned to the platform's shipped posture, because the spec's enum is
    /// stale (getaxonflow/axonflow-enterprise#4224): a category the platform
    /// adds to its posture fails here, not as a read that loses its type.
    #[test]
    fn every_category_the_shipped_posture_uses_is_known() {
        let posture = posture();
        let missing: Vec<&str> = posture["categories"]
            .as_array()
            .expect("categories")
            .iter()
            .map(|c| c.as_str().expect("a category string"))
            .filter(|c| !PolicyCategory::KNOWN_WIRE_VALUES.contains(c))
            .collect();
        assert!(
            missing.is_empty(),
            "the platform's shipped posture at {} uses categories PolicyCategory lacks: \
             {missing:?} (getaxonflow/axonflow-enterprise#4224)",
            posture["platform_commit"]
        );
    }

    /// Every variant but `Unknown`, beside a match with no `_` arm: a variant
    /// added to the enum does not compile here until it is listed, and each
    /// listed variant is then held to `KNOWN_WIRE_VALUES` and `From<String>`.
    #[test]
    fn every_variant_is_in_the_known_set_and_parses_back() {
        use PolicyCategory::*;
        let all = [
            SecuritySqli,
            SecurityAdmin,
            PiiGlobal,
            PiiUs,
            PiiEu,
            PiiIndia,
            PiiSingapore,
            PiiIndonesia,
            CodeSecrets,
            CodeUnsafe,
            CodeCompliance,
            SensitiveData,
            MediaSafety,
            MediaBiometric,
            MediaDocument,
            MediaPii,
            DynamicRisk,
            DynamicCompliance,
            DynamicSecurity,
            DynamicCost,
            DynamicAccess,
            SecurityDangerous,
            ComplianceEuaiact,
            DangerousQueries,
            PiiDetection,
            SqlInjection,
        ];
        for c in &all {
            match c {
                SecuritySqli | SecurityAdmin | PiiGlobal | PiiUs | PiiEu | PiiIndia
                | PiiSingapore | PiiIndonesia | CodeSecrets | CodeUnsafe | CodeCompliance
                | SensitiveData | MediaSafety | MediaBiometric | MediaDocument | MediaPii
                | DynamicRisk | DynamicCompliance | DynamicSecurity | DynamicCost
                | DynamicAccess | SecurityDangerous | ComplianceEuaiact | DangerousQueries
                | PiiDetection | SqlInjection => {}
                Unknown(_) => unreachable!("the list names known variants only"),
            }
        }
        assert_eq!(all.len(), PolicyCategory::KNOWN_WIRE_VALUES.len());
        for c in all {
            let wire = c.as_str().to_string();
            assert!(
                PolicyCategory::KNOWN_WIRE_VALUES.contains(&wire.as_str()),
                "{wire}"
            );
            assert_eq!(PolicyCategory::from(wire.clone()), c, "{wire}");
        }
    }

    /// The fixture names where it came from, so a stale one is visible: the
    /// source path, a full platform commit, the source's sha256, and a sorted,
    /// de-duplicated category list (getaxonflow/axonflow-enterprise#4224).
    ///
    /// It is kept byte-identical to the other SDKs' copies, so its `_comment`
    /// names the Python test that reads it there; here, this test and
    /// `every_category_the_shipped_posture_uses_is_known` read it.
    #[test]
    fn the_posture_fixture_names_its_source() {
        let posture = posture();
        assert_eq!(
            posture["source"],
            "platform/decision/pdp/shipped_posture.json"
        );
        let commit = posture["platform_commit"].as_str().expect("commit");
        assert!(
            commit.len() == 40 && commit.bytes().all(|b| b.is_ascii_hexdigit()),
            "{commit}"
        );
        let sha = posture["source_sha256"].as_str().expect("sha256");
        assert!(
            sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()),
            "{sha}"
        );
        let categories: Vec<&str> = posture["categories"]
            .as_array()
            .expect("categories")
            .iter()
            .map(|c| c.as_str().expect("a category string"))
            .collect();
        let mut canonical = categories.clone();
        canonical.sort_unstable();
        canonical.dedup();
        assert_eq!(categories, canonical);
    }
}