cloud-sdk 0.80.0

no_std-first provider-neutral cloud SDK foundations.
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
448
449
450
451
452
453
454
455
456
457
458
459
use core::sync::atomic::{AtomicU32, Ordering};

const REJECTED: u32 = 1;
const GENERATION_SHIFT: u32 = 1;
const MAX_GENERATION: u32 = u32::MAX >> GENERATION_SHIFT;

/// Monotonic identity of one credential-attempt generation.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CredentialAttemptGeneration(u32);

impl CredentialAttemptGeneration {
    /// Initial generation assigned to newly admitted credentials.
    pub const INITIAL: Self = Self(1);

    /// Returns the generation as a nonzero integer.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// Proof that one credential generation was open when execution began.
///
/// Owner identity is deliberately not hashable because exposing it to a
/// caller-supplied hasher could disclose a process address.
///
/// ```compile_fail
/// use cloud_sdk::authentication::CredentialAttempt;
/// fn require_hash<T: core::hash::Hash>() {}
/// require_hash::<CredentialAttempt<'static>>();
/// ```
#[derive(Clone, Copy)]
pub struct CredentialAttempt<'a> {
    owner: &'a SharedCredentialAttemptState,
    generation: CredentialAttemptGeneration,
}

impl CredentialAttempt<'_> {
    /// Returns the generation used by this attempt.
    #[must_use]
    pub const fn generation(self) -> CredentialAttemptGeneration {
        self.generation
    }
}

impl core::fmt::Debug for CredentialAttempt<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("CredentialAttempt")
            .field("owner", &"[bound]")
            .field("generation", &self.generation)
            .finish()
    }
}

impl PartialEq for CredentialAttempt<'_> {
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self.owner, other.owner) && self.generation == other.generation
    }
}

impl Eq for CredentialAttempt<'_> {}

/// Explicit caller acknowledgement for retrying unchanged credentials.
///
/// Constructing this token must be an operator-level decision. Automatic
/// retry, pagination, polling, and client policy must not create it.
#[derive(Debug)]
pub struct CredentialReconfirmation {
    _private: (),
}

impl CredentialReconfirmation {
    /// Explicitly acknowledges reuse of the same credential material.
    #[must_use]
    pub const fn acknowledge_same_credentials() -> Self {
        Self { _private: () }
    }
}

/// Observable credential-attempt lifecycle state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CredentialAttemptStatus {
    /// The current generation may begin new executions.
    Open,
    /// Authentication rejection closed the current generation.
    Rejected,
}

/// Credential-attempt lifecycle transition failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CredentialAttemptError {
    /// The attempt belongs to another credential lifecycle.
    ForeignState,
    /// Authentication rejection closed the current generation.
    GenerationRejected,
    /// The supplied generation is no longer current.
    StaleGeneration,
    /// Explicit reconfirmation is valid only after authentication rejection.
    ReconfirmationNotRequired,
    /// The bounded monotonic generation cannot advance without wrapping.
    GenerationExhausted,
}

impl_static_error!(CredentialAttemptError,
    Self::ForeignState => "credential attempt belongs to another state",
    Self::GenerationRejected => "credential attempt generation was rejected",
    Self::StaleGeneration => "credential attempt generation is stale",
    Self::ReconfirmationNotRequired => "credential attempt generation is still open",
    Self::GenerationExhausted => "credential attempt generation is exhausted",
);

/// Caller-owned concurrent lockout state for one credential lifecycle.
///
/// Cloned clients share this object by reference. Multiple attempts may begin
/// on one open generation, but the first authentication rejection closes that
/// generation for every later execution. Only replacement credentials or an
/// explicit [`CredentialReconfirmation`] advance to a new open generation.
pub struct SharedCredentialAttemptState {
    packed: AtomicU32,
}

impl SharedCredentialAttemptState {
    /// Creates one open initial credential generation.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            packed: AtomicU32::new(pack(CredentialAttemptGeneration::INITIAL, false)),
        }
    }

    /// Returns the current generation and status.
    #[must_use]
    pub fn observe(&self) -> (CredentialAttemptGeneration, CredentialAttemptStatus) {
        unpack(self.packed.load(Ordering::Acquire))
    }

    /// Begins execution only when the current generation remains open.
    pub fn begin(&self) -> Result<CredentialAttempt<'_>, CredentialAttemptError> {
        let (generation, status) = self.observe();
        if status == CredentialAttemptStatus::Rejected {
            return Err(CredentialAttemptError::GenerationRejected);
        }
        Ok(CredentialAttempt {
            owner: self,
            generation,
        })
    }

    /// Revalidates an attempt immediately before credential use.
    pub fn validate(&self, attempt: CredentialAttempt<'_>) -> Result<(), CredentialAttemptError> {
        self.validate_owner(attempt)?;
        self.validate_generation(attempt.generation)
    }

    pub(crate) fn validate_generation(
        &self,
        expected: CredentialAttemptGeneration,
    ) -> Result<(), CredentialAttemptError> {
        let (generation, status) = self.observe();
        if generation != expected {
            return Err(CredentialAttemptError::StaleGeneration);
        }
        if status == CredentialAttemptStatus::Rejected {
            return Err(CredentialAttemptError::GenerationRejected);
        }
        Ok(())
    }

    /// Closes the exact generation that received authentication rejection.
    ///
    /// Repeated concurrent rejection reports for the same generation are
    /// idempotent. A stale report cannot close replacement credentials.
    pub fn reject(&self, attempt: CredentialAttempt<'_>) -> Result<(), CredentialAttemptError> {
        self.validate_owner(attempt)?;
        self.reject_generation(attempt.generation)
    }

    pub(crate) fn reject_generation(
        &self,
        expected: CredentialAttemptGeneration,
    ) -> Result<(), CredentialAttemptError> {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (generation, status) = unpack(current);
            if generation != expected {
                return Err(CredentialAttemptError::StaleGeneration);
            }
            if status == CredentialAttemptStatus::Rejected {
                return Ok(());
            }
            let next = pack(generation, true);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(());
            }
        }
    }

    /// Opens a new generation after replacement credentials were admitted.
    pub fn replace(
        &self,
        expected: CredentialAttemptGeneration,
    ) -> Result<CredentialAttemptGeneration, CredentialAttemptError> {
        self.advance(expected)
    }

    /// Opens a new generation after explicit unchanged-credential confirmation.
    pub fn reconfirm(
        &self,
        expected: CredentialAttemptGeneration,
        _acknowledgement: CredentialReconfirmation,
    ) -> Result<CredentialAttemptGeneration, CredentialAttemptError> {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (generation, status) = unpack(current);
            if generation != expected {
                return Err(CredentialAttemptError::StaleGeneration);
            }
            if status != CredentialAttemptStatus::Rejected {
                return Err(CredentialAttemptError::ReconfirmationNotRequired);
            }
            let next_generation = checked_next(generation)?;
            let next = pack(next_generation, false);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(next_generation);
            }
        }
    }

    fn advance(
        &self,
        expected: CredentialAttemptGeneration,
    ) -> Result<CredentialAttemptGeneration, CredentialAttemptError> {
        loop {
            let current = self.packed.load(Ordering::Acquire);
            let (generation, _) = unpack(current);
            if generation != expected {
                return Err(CredentialAttemptError::StaleGeneration);
            }
            let next_generation = checked_next(generation)?;
            let next = pack(next_generation, false);
            if self
                .packed
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(next_generation);
            }
        }
    }

    fn validate_owner(&self, attempt: CredentialAttempt<'_>) -> Result<(), CredentialAttemptError> {
        if !core::ptr::eq(self, attempt.owner) {
            return Err(CredentialAttemptError::ForeignState);
        }
        Ok(())
    }

    #[cfg(test)]
    fn set_generation_for_test(&mut self, generation: u32, rejected: bool) {
        *self.packed.get_mut() = pack(CredentialAttemptGeneration(generation), rejected);
    }
}

fn checked_next(
    generation: CredentialAttemptGeneration,
) -> Result<CredentialAttemptGeneration, CredentialAttemptError> {
    generation
        .0
        .checked_add(1)
        .filter(|candidate| *candidate <= MAX_GENERATION)
        .map(CredentialAttemptGeneration)
        .ok_or(CredentialAttemptError::GenerationExhausted)
}

impl Default for SharedCredentialAttemptState {
    fn default() -> Self {
        Self::new()
    }
}

impl core::fmt::Debug for SharedCredentialAttemptState {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let (generation, status) = self.observe();
        formatter
            .debug_struct("SharedCredentialAttemptState")
            .field("generation", &generation)
            .field("status", &status)
            .finish()
    }
}

const fn pack(generation: CredentialAttemptGeneration, rejected: bool) -> u32 {
    (generation.0 << GENERATION_SHIFT) | (rejected as u32)
}

const fn unpack(value: u32) -> (CredentialAttemptGeneration, CredentialAttemptStatus) {
    let generation = CredentialAttemptGeneration(value >> GENERATION_SHIFT);
    let status = if value & REJECTED == 0 {
        CredentialAttemptStatus::Open
    } else {
        CredentialAttemptStatus::Rejected
    };
    (generation, status)
}

#[cfg(test)]
mod tests {
    use super::{
        CredentialAttemptError, CredentialAttemptGeneration, CredentialAttemptStatus,
        CredentialReconfirmation, MAX_GENERATION, SharedCredentialAttemptState,
    };

    #[test]
    fn rejection_closes_one_generation_until_replaced_or_reconfirmed() {
        let state = SharedCredentialAttemptState::new();
        let first = state
            .begin()
            .unwrap_or_else(|_| unreachable!("initial credential generation was closed"));
        assert_eq!(first.generation(), CredentialAttemptGeneration::INITIAL);
        assert_eq!(
            state.reconfirm(
                first.generation(),
                CredentialReconfirmation::acknowledge_same_credentials(),
            ),
            Err(CredentialAttemptError::ReconfirmationNotRequired)
        );
        assert_eq!(state.reject(first), Ok(()));
        assert_eq!(
            state.validate(first),
            Err(CredentialAttemptError::GenerationRejected)
        );
        assert_eq!(state.reject(first), Ok(()));
        assert_eq!(
            state.begin(),
            Err(CredentialAttemptError::GenerationRejected)
        );

        let second = state
            .reconfirm(
                first.generation(),
                CredentialReconfirmation::acknowledge_same_credentials(),
            )
            .unwrap_or_else(|_| unreachable!("explicit reconfirmation was rejected"));
        assert_eq!(second.get(), 2);
        assert!(state.begin().is_ok());

        let third = state
            .replace(second)
            .unwrap_or_else(|_| unreachable!("replacement generation was rejected"));
        assert_eq!(third.get(), 3);
        assert!(state.begin().is_ok());
    }

    #[test]
    fn stale_transitions_cannot_close_or_reopen_replacement_credentials() {
        let state = SharedCredentialAttemptState::new();
        let stale = state
            .begin()
            .unwrap_or_else(|_| unreachable!("initial credential generation was closed"));
        let current = state
            .replace(stale.generation())
            .unwrap_or_else(|_| unreachable!("replacement generation was rejected"));
        assert_eq!(
            state.reject(stale),
            Err(CredentialAttemptError::StaleGeneration)
        );
        assert_eq!(
            state.validate(stale),
            Err(CredentialAttemptError::StaleGeneration)
        );
        assert_eq!(
            state.replace(stale.generation()),
            Err(CredentialAttemptError::StaleGeneration)
        );
        assert_eq!(
            state.reconfirm(
                stale.generation(),
                CredentialReconfirmation::acknowledge_same_credentials(),
            ),
            Err(CredentialAttemptError::StaleGeneration)
        );
        assert_eq!(state.observe(), (current, CredentialAttemptStatus::Open));
    }

    #[test]
    fn foreign_attempts_never_validate_or_close_equal_generations() {
        let owner_a = SharedCredentialAttemptState::new();
        let owner_b = SharedCredentialAttemptState::new();
        let foreign = owner_a
            .begin()
            .unwrap_or_else(|_| unreachable!("owner A generation was closed"));

        assert_eq!(
            owner_b.validate(foreign),
            Err(CredentialAttemptError::ForeignState)
        );
        assert_eq!(
            owner_b.reject(foreign),
            Err(CredentialAttemptError::ForeignState)
        );
        assert_eq!(
            owner_b.observe(),
            (
                CredentialAttemptGeneration::INITIAL,
                CredentialAttemptStatus::Open
            )
        );

        let generation_a = owner_a
            .replace(CredentialAttemptGeneration::INITIAL)
            .unwrap_or_else(|_| unreachable!("owner A replacement failed"));
        let generation_b = owner_b
            .replace(CredentialAttemptGeneration::INITIAL)
            .unwrap_or_else(|_| unreachable!("owner B replacement failed"));
        assert_eq!(generation_a, generation_b);
        let foreign_replacement = owner_a
            .begin()
            .unwrap_or_else(|_| unreachable!("owner A replacement was closed"));
        assert_eq!(
            owner_b.reject(foreign_replacement),
            Err(CredentialAttemptError::ForeignState)
        );
        assert_eq!(
            owner_b.observe(),
            (generation_b, CredentialAttemptStatus::Open)
        );
    }

    #[test]
    fn generation_exhaustion_fails_closed_without_wrapping() {
        let mut state = SharedCredentialAttemptState::new();
        state.set_generation_for_test(MAX_GENERATION, true);
        let generation = state.observe().0;
        assert_eq!(
            state.replace(generation),
            Err(CredentialAttemptError::GenerationExhausted)
        );
        assert_eq!(
            state.reconfirm(
                generation,
                CredentialReconfirmation::acknowledge_same_credentials(),
            ),
            Err(CredentialAttemptError::GenerationExhausted)
        );
        assert_eq!(
            state.observe(),
            (generation, CredentialAttemptStatus::Rejected)
        );
    }
}