pic-pca 0.1.3

PCA and PoC types for PIC Protocol
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
447
/*
 * Copyright Nitro Agility S.r.l.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! PCA (Provenance Causal Authority) payload model.
//!
//! Defines the PCA data structure for CBOR serialization within COSE_Sign1 envelope.
//! Based on PIC Spec v0.1.

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

// ============================================================================
// Dynamic Binding
// ============================================================================

/// Generic dynamic key-value map with nested structure support.
///
/// Used for flexible executor bindings that vary by deployment context
/// (e.g., Kubernetes, cloud provider, SPIFFE federation).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct DynamicMap(pub HashMap<String, Value>);

impl DynamicMap {
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    /// Adds a string value.
    pub fn with(mut self, key: &str, value: &str) -> Self {
        self.0.insert(key.into(), Value::String(value.into()));
        self
    }

    /// Adds a nested map.
    pub fn with_map(mut self, key: &str, value: DynamicMap) -> Self {
        self.0
            .insert(key.into(), serde_json::to_value(value).unwrap());
        self
    }

    /// Adds an arbitrary JSON value.
    pub fn with_value(mut self, key: &str, value: Value) -> Self {
        self.0.insert(key.into(), value);
        self
    }

    /// Adds a string array.
    pub fn with_array(mut self, key: &str, values: Vec<&str>) -> Self {
        let arr: Vec<Value> = values
            .into_iter()
            .map(|s| Value::String(s.into()))
            .collect();
        self.0.insert(key.into(), Value::Array(arr));
        self
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    pub fn get_str(&self, key: &str) -> Option<&str> {
        self.0.get(key)?.as_str()
    }

    pub fn get_map(&self, key: &str) -> Option<DynamicMap> {
        let value = self.0.get(key)?;
        serde_json::from_value(value.clone()).ok()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Executor binding - identifies executor within a federation context.
pub type ExecutorBinding = DynamicMap;

// ============================================================================
// Executor
// ============================================================================

/// Executor at the current hop.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Executor {
    pub binding: ExecutorBinding,
}

// ============================================================================
// Provenance Chain
// ============================================================================

/// Key material for signature verification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct KeyMaterial {
    #[serde(with = "serde_bytes")]
    pub public_key: Vec<u8>,
    pub alg: String,
}

/// CAT provenance - identifies who signed the previous PCA.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CatProvenance {
    pub issuer: String,
    #[serde(with = "serde_bytes")]
    pub signature: Vec<u8>,
    pub key: KeyMaterial,
}

/// Executor provenance - identifies who signed the PoC.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExecutorProvenance {
    pub issuer: String,
    #[serde(with = "serde_bytes")]
    pub signature: Vec<u8>,
    pub key: KeyMaterial,
}

/// Provenance chain linking to the previous hop.
///
/// Contains both CAT and executor signatures for chain verification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Provenance {
    pub cat: CatProvenance,
    pub executor: ExecutorProvenance,
}

// ============================================================================
// Constraints
// ============================================================================

/// Temporal constraints on PCA validity.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TemporalConstraints {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<String>,
}

/// All constraints on PCA validity.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Constraints {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temporal: Option<TemporalConstraints>,
}

// ============================================================================
// PCA Payload
// ============================================================================

/// PCA Payload - the CBOR content signed with COSE_Sign1.
///
/// The issuer and signature are stored in the COSE header, not here.
/// This structure contains only the payload fields.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PcaPayload {
    /// Unique identifier for this hop
    pub hop: String,
    /// Immutable origin principal (p_0)
    pub p_0: String,
    /// Authority set (ops_i ⊆ ops_{i-1})
    pub ops: Vec<String>,
    /// Current executor binding
    pub executor: Executor,
    /// Causal chain reference (None for PCA_0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<Provenance>,
    /// Validity constraints
    #[serde(skip_serializing_if = "Option::is_none")]
    pub constraints: Option<Constraints>,
}

impl PcaPayload {
    /// Serializes to CBOR bytes.
    pub fn to_cbor(&self) -> Result<Vec<u8>, ciborium::ser::Error<std::io::Error>> {
        let mut buf = Vec::new();
        ciborium::into_writer(self, &mut buf)?;
        Ok(buf)
    }

    /// Deserializes from CBOR bytes.
    pub fn from_cbor(bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> {
        ciborium::from_reader(bytes)
    }

    /// Serializes to JSON string.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Serializes to pretty-printed JSON string.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserializes from JSON string.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    fn sample_pca_0() -> PcaPayload {
        let binding = ExecutorBinding::new().with("org", "acme-corp");

        PcaPayload {
            hop: "gateway".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["read:/user/*".into(), "write:/user/*".into()],
            executor: Executor { binding },
            provenance: None,
            constraints: Some(Constraints {
                temporal: Some(TemporalConstraints {
                    iat: Some("2025-12-11T10:00:00Z".into()),
                    exp: Some("2025-12-11T11:00:00Z".into()),
                    nbf: None,
                }),
            }),
        }
    }

    fn sample_pca_n() -> PcaPayload {
        let binding = ExecutorBinding::new().with("org", "acme-corp");

        PcaPayload {
            hop: "storage".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["read:/user/*".into()],
            executor: Executor { binding },
            provenance: Some(Provenance {
                cat: CatProvenance {
                    issuer: "https://cat.acme-corp.com".into(),
                    signature: vec![0u8; 64],
                    key: KeyMaterial {
                        public_key: vec![0u8; 32],
                        alg: "EdDSA".into(),
                    },
                },
                executor: ExecutorProvenance {
                    issuer: "spiffe://acme-corp/archive".into(),
                    signature: vec![0u8; 64],
                    key: KeyMaterial {
                        public_key: vec![0u8; 32],
                        alg: "EdDSA".into(),
                    },
                },
            }),
            constraints: Some(Constraints {
                temporal: Some(TemporalConstraints {
                    iat: Some("2025-12-11T10:00:00Z".into()),
                    exp: Some("2025-12-11T10:30:00Z".into()),
                    nbf: None,
                }),
            }),
        }
    }

    #[test]
    fn test_pca_0_cbor_roundtrip() {
        let pca = sample_pca_0();
        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();
        assert_eq!(pca, decoded);
        assert_eq!(decoded.hop, "gateway");
        assert!(decoded.provenance.is_none());
    }

    #[test]
    fn test_pca_n_cbor_roundtrip() {
        let pca = sample_pca_n();
        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();
        assert_eq!(pca, decoded);
        assert_eq!(decoded.hop, "storage");
        assert!(decoded.provenance.is_some());
    }

    #[test]
    fn test_json_roundtrip() {
        let pca = sample_pca_n();
        let json = pca.to_json().unwrap();
        let decoded = PcaPayload::from_json(&json).unwrap();
        assert_eq!(pca, decoded);
    }

    #[test]
    fn test_cbor_smaller_than_json() {
        let pca = sample_pca_n();
        let cbor = pca.to_cbor().unwrap();
        let json = pca.to_json().unwrap();

        println!("CBOR: {} bytes", cbor.len());
        println!("JSON: {} bytes", json.len());

        assert!(cbor.len() < json.len());
    }

    #[test]
    fn test_json_output() {
        let pca = sample_pca_n();
        let json = pca.to_json_pretty().unwrap();
        println!("{}", json);
    }

    #[test]
    fn test_monotonicity_ops_reduced() {
        let pca_0 = sample_pca_0();
        let pca_n = sample_pca_n();

        assert_eq!(pca_0.ops.len(), 2);
        assert_eq!(pca_n.ops.len(), 1);
        assert_eq!(pca_0.p_0, pca_n.p_0);
    }

    #[test]
    fn test_minimal_executor_binding() {
        let binding = ExecutorBinding::new().with("org", "simple-org");

        let pca = PcaPayload {
            hop: "service-a".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["read:/user/*".into()],
            executor: Executor { binding },
            provenance: None,
            constraints: None,
        };

        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();

        assert_eq!(decoded.executor.binding.get_str("org"), Some("simple-org"));
    }

    #[test]
    fn test_executor_binding_flexible() {
        let binding = ExecutorBinding::new()
            .with("org", "acme-corp")
            .with("region", "eu-west-1")
            .with("env", "prod");

        let pca = PcaPayload {
            hop: "api-gateway".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["invoke:*".into()],
            executor: Executor { binding },
            provenance: None,
            constraints: None,
        };

        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();

        assert_eq!(decoded.executor.binding.get_str("org"), Some("acme-corp"));
        assert_eq!(
            decoded.executor.binding.get_str("region"),
            Some("eu-west-1")
        );
    }

    #[test]
    fn test_nested_binding() {
        let k8s = DynamicMap::new()
            .with("cluster", "prod-eu")
            .with("namespace", "default");

        let binding = ExecutorBinding::new()
            .with("org", "acme-corp")
            .with_map("kubernetes", k8s)
            .with_array("regions", vec!["eu-west-1", "eu-west-2"]);

        let pca = PcaPayload {
            hop: "k8s-service".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["read:*".into()],
            executor: Executor { binding },
            provenance: None,
            constraints: None,
        };

        let json = pca.to_json_pretty().unwrap();
        println!("{}", json);

        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();

        let k8s_decoded = decoded.executor.binding.get_map("kubernetes").unwrap();
        assert_eq!(k8s_decoded.get_str("cluster"), Some("prod-eu"));
        assert_eq!(k8s_decoded.get_str("namespace"), Some("default"));
    }

    #[test]
    fn test_binding_with_json_value() {
        let binding = ExecutorBinding::new().with("org", "acme-corp").with_value(
            "metadata",
            serde_json::json!({
                "version": "1.2.3",
                "replicas": 3,
                "labels": {
                    "app": "gateway",
                    "tier": "frontend"
                }
            }),
        );

        let pca = PcaPayload {
            hop: "gateway".into(),
            p_0: "https://idp.example.com/users/alice".into(),
            ops: vec!["read:*".into()],
            executor: Executor { binding },
            provenance: None,
            constraints: None,
        };

        let json = pca.to_json_pretty().unwrap();
        println!("{}", json);

        let cbor = pca.to_cbor().unwrap();
        let decoded = PcaPayload::from_cbor(&cbor).unwrap();

        let metadata = decoded.executor.binding.get("metadata").unwrap();
        assert_eq!(metadata["version"], "1.2.3");
        assert_eq!(metadata["replicas"], 3);
    }
}