cosmian_kms_interfaces 5.25.0

Crate exposing APIs for plugins to the Cosmian KMS
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
use std::fmt::{self, Display, Formatter};

use cosmian_kmip::{
    KmipError,
    kmip_0::kmip_types::{CryptographicUsageMask, ErrorReason, State},
    kmip_2_1::{
        kmip_attributes::Attributes,
        kmip_objects::Object,
        kmip_types::{CryptographicAlgorithm, UsageLimitsUnit},
    },
    time_normalize,
};

/// An object with its metadata such as owner, permissions and state
///
/// This is the main representation of objects through the KMS server.
/// Mpe APIs should use this representation.
#[derive(Clone)]
pub struct ObjectWithMetadata {
    id: String,
    // this is the object as registered in the DN. For a key, it may be wrapped or unwrapped
    object: Object,
    owner: String,
    state: State,
    attributes: Attributes,
}

impl ObjectWithMetadata {
    #[must_use]
    pub const fn new(
        id: String,
        object: Object,
        owner: String,
        state: State,
        attributes: Attributes,
    ) -> Self {
        Self {
            id,
            object,
            owner,
            state,
            attributes,
        }
    }

    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    #[must_use]
    pub const fn object(&self) -> &Object {
        &self.object
    }

    /// Set a new object, clearing the cached unwrapped version
    /// if any
    pub fn set_object(&mut self, object: Object) {
        self.object = object;
    }

    /// Return a mutable borrow to the Object
    /// Do not use this to set a new object or make sure you clear
    /// the cached unwrapped object
    pub const fn object_mut(&mut self) -> &mut Object {
        &mut self.object
    }

    #[must_use]
    pub fn owner(&self) -> &str {
        &self.owner
    }

    #[must_use]
    pub const fn state(&self) -> State {
        self.state
    }

    #[must_use]
    pub const fn attributes(&self) -> &Attributes {
        &self.attributes
    }

    pub const fn attributes_mut(&mut self) -> &mut Attributes {
        &mut self.attributes
    }

    /// Resolve the effective cryptographic algorithm for this managed object.
    ///
    /// Checks the key block's algorithm first, then falls back to the object's
    /// external attributes. Returns `None` when neither source provides a value.
    #[must_use]
    pub fn resolve_key_algorithm(&self) -> Option<CryptographicAlgorithm> {
        self.object
            .key_block()
            .ok()
            .and_then(|kb| kb.cryptographic_algorithm().copied())
            .or(self.attributes.cryptographic_algorithm)
    }

    // ─── Lifecycle predicates ────────────────────────────────────────────────

    /// Determine the effective KMIP state based on stored state and time-based
    /// transitions (activation / deactivation).
    ///
    /// - `PreActive` → `Active` when `activation_date` ≤ now.
    /// - `Active` → `Deactivated` when `deactivation_date` ≤ now.
    ///
    /// Falls back to the stored state if the system clock cannot be read.
    #[must_use]
    pub fn effective_state(&self) -> State {
        let Ok(now) = time_normalize() else {
            return self.state;
        };
        match self.state {
            State::PreActive => {
                let activation_date = self.attributes.activation_date.or_else(|| {
                    self.object
                        .attributes()
                        .ok()
                        .and_then(|attrs| attrs.activation_date)
                });
                if activation_date.is_some_and(|d| d <= now) {
                    State::Active
                } else {
                    State::PreActive
                }
            }
            State::Active => {
                let deactivation_date = self.attributes.deactivation_date.or_else(|| {
                    self.object
                        .attributes()
                        .ok()
                        .and_then(|attrs| attrs.deactivation_date)
                });
                if deactivation_date.is_some_and(|d| d <= now) {
                    State::Deactivated
                } else {
                    State::Active
                }
            }
            other => other,
        }
    }

    /// Check whether the current time falls within the KMIP process window
    /// (`ProcessStartDate`..`ProtectStopDate`).
    ///
    /// Returns `true` when usage is allowed (window is open or no window is set).
    /// Returns `false` when the key is outside its process window.
    /// Falls back to `true` if the system clock cannot be read.
    ///
    /// # Attribute precedence
    ///
    /// The external (database) attributes stored in `self.attributes` are checked
    /// first, with the embedded key-block attributes as fallback.  This mirrors
    /// `effective_state()` and ensures that `SetAttribute ProcessStartDate / ProtectStopDate`
    /// calls are honoured even when the key block itself was not modified.
    #[must_use]
    pub fn is_within_process_window(&self) -> bool {
        if self.effective_state() != State::Active {
            return true; // window only applies to Active keys
        }
        let Ok(now) = time_normalize() else {
            return true;
        };
        // Prefer external (database) attributes; fall back to embedded key-block attributes.
        let kb_attrs = self.object.attributes().ok();
        let process_start = self
            .attributes
            .process_start_date
            .or_else(|| kb_attrs.as_ref().and_then(|a| a.process_start_date));
        let protect_stop = self
            .attributes
            .protect_stop_date
            .or_else(|| kb_attrs.as_ref().and_then(|a| a.protect_stop_date));
        let too_early = process_start.is_some_and(|d| now < d);
        let too_late = protect_stop.is_some_and(|d| now > d);
        !(too_early || too_late)
    }

    // ─── Usage predicates ────────────────────────────────────────────────────

    /// Check whether the object's usage mask permits the given operation.
    ///
    /// In **lenient** mode a missing mask (`None`) is treated as "allowed",
    /// which supports legacy Certificates/Public Keys imported without masks.
    #[must_use]
    pub fn has_usage_mask(&self, required: CryptographicUsageMask, lenient: bool) -> bool {
        let attributes = self
            .object
            .attributes()
            .unwrap_or_else(|_| self.attributes());
        if lenient && attributes.cryptographic_usage_mask.is_none() {
            return true;
        }
        attributes
            .is_usage_authorized_for(required)
            .unwrap_or(false)
    }

    /// Check whether the key's remaining usage budget is sufficient for
    /// `data_len` bytes of payload.
    ///
    /// Returns `true` when no `UsageLimits` are set or the budget is sufficient.
    #[must_use]
    pub fn has_usage_budget(&self, data_len: usize) -> bool {
        let Some(ul) = self.attributes.usage_limits.as_ref() else {
            return true;
        };
        match ul.usage_limits_unit {
            UsageLimitsUnit::Byte => {
                let needed = i64::try_from(data_len).unwrap_or(i64::MAX);
                ul.usage_limits_total >= needed
            }
            UsageLimitsUnit::Object | UsageLimitsUnit::Block | UsageLimitsUnit::Operation => {
                ul.usage_limits_total > 0
            }
        }
    }

    // ─── Enforcement (error-returning) ───────────────────────────────────────

    /// Enforce the KMIP process-window constraints.
    ///
    /// An Active key whose current time is before `ProcessStartDate` or after
    /// `ProtectStopDate` is rejected with `Wrong_Key_Lifecycle_State`.
    pub fn check_process_window(&self) -> Result<(), KmipError> {
        if !self.is_within_process_window() {
            return Err(KmipError::Kmip21(
                ErrorReason::Wrong_Key_Lifecycle_State,
                "DENIED".to_owned(),
            ));
        }
        Ok(())
    }

    /// Enforce `UsageLimits` before a cryptographic operation.
    ///
    /// Returns `Err(Permission_Denied)` when the key's remaining usage budget
    /// is insufficient for the requested `data_len` bytes.
    pub fn enforce_usage_limits(&self, data_len: usize) -> Result<(), KmipError> {
        if !self.has_usage_budget(data_len) {
            return Err(KmipError::Kmip21(
                ErrorReason::Permission_Denied,
                "DENIED".to_owned(),
            ));
        }
        Ok(())
    }
}

impl Display for ObjectWithMetadata {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ObjectWithMetadata {{ id: {}, object: {}, owner: {}, state: {}, attributes: {} }}",
            self.id, self.object, self.owner, self.state, self.attributes
        )
    }
}

#[cfg(test)]
#[allow(clippy::panic_in_result_fn)]
mod tests {
    use cosmian_kmip::{
        kmip_0::kmip_types::State,
        kmip_2_1::{
            kmip_attributes::Attributes,
            kmip_data_structures::{KeyBlock, KeyMaterial, KeyValue},
            kmip_objects::{Object, SymmetricKey},
            kmip_types::{CryptographicAlgorithm, KeyFormatType},
        },
        time_normalize,
    };
    use time::Duration;
    use zeroize::Zeroizing;

    use super::ObjectWithMetadata;

    /// Build a minimal `Object::SymmetricKey` with empty embedded attributes.
    fn test_object() -> Object {
        Object::SymmetricKey(SymmetricKey {
            key_block: KeyBlock {
                key_format_type: KeyFormatType::Raw,
                key_value: Some(KeyValue::Structure {
                    key_material: KeyMaterial::ByteString(Zeroizing::new(vec![0_u8; 32])),
                    attributes: Some(Attributes::default()),
                }),
                key_compression_type: None,
                cryptographic_algorithm: Some(CryptographicAlgorithm::AES),
                cryptographic_length: Some(256),
                key_wrapping_data: None,
            },
        })
    }

    fn active_owm(ext_attrs: Attributes) -> ObjectWithMetadata {
        ObjectWithMetadata::new(
            "test-key".to_owned(),
            test_object(),
            "owner".to_owned(),
            State::Active,
            ext_attrs,
        )
    }

    // ── is_within_process_window ──────────────────────────────────────────────

    #[test]
    fn test_process_window_no_dates_is_open() {
        let owm = active_owm(Attributes::default());
        assert!(owm.is_within_process_window());
    }

    /// `ProtectStopDate` set via `SetAttribute` (external DB attrs) in the past
    /// must be honoured.  This verifies the bug-fix: the old code only checked the
    /// key-block embedded attributes and would have returned `true` here.
    #[test]
    fn test_process_window_protect_stop_past_in_external_attrs_is_closed()
    -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        let owm = active_owm(Attributes {
            protect_stop_date: Some(now - Duration::hours(1)),
            ..Default::default()
        });
        assert!(!owm.is_within_process_window());
        Ok(())
    }

    #[test]
    fn test_process_window_protect_stop_future_is_open() -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        let owm = active_owm(Attributes {
            protect_stop_date: Some(now + Duration::hours(1)),
            ..Default::default()
        });
        assert!(owm.is_within_process_window());
        Ok(())
    }

    /// `ProcessStartDate` set via `SetAttribute` (external DB attrs) in the future
    /// must be honoured.  Same fix as the `ProtectStopDate` case above.
    #[test]
    fn test_process_window_process_start_future_in_external_attrs_is_closed()
    -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        let owm = active_owm(Attributes {
            process_start_date: Some(now + Duration::hours(1)),
            ..Default::default()
        });
        assert!(!owm.is_within_process_window());
        Ok(())
    }

    #[test]
    fn test_process_window_process_start_past_is_open() -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        let owm = active_owm(Attributes {
            process_start_date: Some(now - Duration::hours(1)),
            ..Default::default()
        });
        assert!(owm.is_within_process_window());
        Ok(())
    }

    #[test]
    fn test_process_window_both_dates_valid_is_open() -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        let owm = active_owm(Attributes {
            process_start_date: Some(now - Duration::hours(1)),
            protect_stop_date: Some(now + Duration::hours(1)),
            ..Default::default()
        });
        assert!(owm.is_within_process_window());
        Ok(())
    }

    /// `ProtectStopDate` embedded inside the key block (not via `SetAttribute`)
    /// must still be honoured — the fallback path remains correct.
    #[test]
    fn test_process_window_protect_stop_past_in_key_block_is_closed()
    -> Result<(), Box<dyn std::error::Error>> {
        let now = time_normalize()?;
        // Build an object with ProtectStopDate inside the key block's embedded attrs.
        let kb_attrs = Attributes {
            protect_stop_date: Some(now - Duration::hours(1)),
            ..Default::default()
        };
        let object = Object::SymmetricKey(SymmetricKey {
            key_block: KeyBlock {
                key_format_type: KeyFormatType::Raw,
                key_value: Some(KeyValue::Structure {
                    key_material: KeyMaterial::ByteString(Zeroizing::new(vec![0_u8; 32])),
                    attributes: Some(kb_attrs),
                }),
                key_compression_type: None,
                cryptographic_algorithm: Some(CryptographicAlgorithm::AES),
                cryptographic_length: Some(256),
                key_wrapping_data: None,
            },
        });
        let owm = ObjectWithMetadata::new(
            "test-key".to_owned(),
            object,
            "owner".to_owned(),
            State::Active,
            Attributes::default(), // no external attrs
        );
        assert!(!owm.is_within_process_window());
        Ok(())
    }

    /// Non-Active keys bypass the process-window check (always open).
    #[test]
    fn test_process_window_non_active_state_always_open() -> Result<(), Box<dyn std::error::Error>>
    {
        let now = time_normalize()?;
        for state in [
            State::Compromised,
            State::Deactivated,
            State::Destroyed,
            State::PreActive,
        ] {
            let owm = ObjectWithMetadata::new(
                "test-key".to_owned(),
                test_object(),
                "owner".to_owned(),
                state,
                Attributes {
                    protect_stop_date: Some(now - Duration::hours(1)),
                    ..Default::default()
                },
            );
            assert!(
                owm.is_within_process_window(),
                "expected window open for state {state:?}"
            );
        }
        Ok(())
    }
}