auths-sdk 0.1.2

Application services layer for Auths identity operations
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Runtime dependency container for auths-sdk operations.
//!
//! [`AuthsContext`] carries all injected infrastructure adapters. Config structs
//! (e.g. [`crate::types::CreateDeveloperIdentityConfig`]) remain Plain Old Data with no
//! trait objects.

use std::sync::Arc;

use auths_core::ports::clock::ClockProvider;
use auths_core::ports::id::{SystemUuidProvider, UuidProvider};
use auths_core::signing::PassphraseProvider;
use auths_core::storage::keychain::KeyStorage;
use auths_id::attestation::export::AttestationSink;
use auths_id::ports::registry::RegistryBackend;
use auths_id::storage::attestation::AttestationSource;
use auths_id::storage::identity::IdentityStorage;

use crate::ports::agent::{AgentSigningPort, NoopAgentProvider};

/// Re-export the canonical `EventSink` trait from `auths-telemetry`.
pub use auths_telemetry::EventSink;

struct NoopSink;

impl EventSink for NoopSink {
    fn emit(&self, _payload: &str) {}
    fn flush(&self) {}
}

struct NoopPassphraseProvider;

impl PassphraseProvider for NoopPassphraseProvider {
    fn get_passphrase(
        &self,
        _prompt: &str,
    ) -> Result<zeroize::Zeroizing<String>, auths_core::AgentError> {
        Err(auths_core::AgentError::SigningFailed(
            "no passphrase provider configured — call .passphrase_provider(...) on AuthsContextBuilder".into(),
        ))
    }
}

/// All runtime dependencies for auths-sdk operations.
///
/// Construct via [`AuthsContext::builder()`]. Config structs carry serializable
/// data; `AuthsContext` carries injected infrastructure adapters. This separation
/// allows the SDK to operate as a headless, storage-agnostic library that can be
/// embedded in cloud SaaS, WASM, or C-FFI runtimes without pulling in tokio,
/// git2, or std::fs.
///
/// Usage:
/// ```ignore
/// use std::sync::Arc;
/// use auths_sdk::context::AuthsContext;
///
/// let ctx = AuthsContext::builder()
///     .registry(Arc::new(my_registry))
///     .key_storage(Arc::new(my_keychain))
///     .clock(Arc::new(SystemClock))
///     .identity_storage(Arc::new(my_identity_storage))
///     .attestation_sink(Arc::new(my_store.clone()))
///     .attestation_source(Arc::new(my_store))
///     .build();
/// sdk::initialize(config, &ctx)?;
/// ```
pub struct AuthsContext {
    /// Pre-initialized registry storage backend.
    pub registry: Arc<dyn RegistryBackend + Send + Sync>,
    /// Platform keychain or test fake for key material storage.
    pub key_storage: Arc<dyn KeyStorage + Send + Sync>,
    /// Wall-clock provider for deterministic testing.
    pub clock: Arc<dyn ClockProvider + Send + Sync>,
    /// Telemetry sink (defaults to `NoopSink` when not specified).
    pub event_sink: Arc<dyn EventSink>,
    /// Identity storage adapter (load/save managed identity).
    pub identity_storage: Arc<dyn IdentityStorage + Send + Sync>,
    /// Attestation sink for writing signed attestations.
    pub attestation_sink: Arc<dyn AttestationSink + Send + Sync>,
    /// Attestation source for reading existing attestations.
    pub attestation_source: Arc<dyn AttestationSource + Send + Sync>,
    /// Passphrase provider for key decryption during signing operations.
    /// Defaults to `NoopPassphraseProvider` — set via `.passphrase_provider(...)` when
    /// SDK functions need to sign with encrypted key material.
    pub passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
    /// UUID generator port. Defaults to [`SystemUuidProvider`] (random v4 UUIDs).
    /// Override with a deterministic stub in tests.
    pub uuid_provider: Arc<dyn UuidProvider + Send + Sync>,
    /// Agent-based signing port for delegating operations to a running agent process.
    /// Defaults to [`NoopAgentProvider`] (all operations return `Unavailable`)
    /// when not called. Set this on Unix platforms where the auths-agent daemon
    /// is available.
    pub agent_signing: Arc<dyn AgentSigningPort + Send + Sync>,
    /// Witness configuration for KEL event receipting.
    /// When set and enabled, ixn events are submitted to witnesses after commit.
    pub witness_config: Option<auths_id::witness_config::WitnessConfig>,
    /// Path to the registry repository (needed for witness receipt storage).
    pub repo_path: Option<std::path::PathBuf>,
}

impl AuthsContext {
    /// Build witness params from the context's configuration.
    ///
    /// Returns `WitnessParams::Enabled` when both `witness_config` and `repo_path`
    /// are set, `WitnessParams::Disabled` otherwise.
    pub fn witness_params(&self) -> auths_id::witness_config::WitnessParams<'_> {
        match (&self.witness_config, &self.repo_path) {
            (Some(config), Some(path)) => auths_id::witness_config::WitnessParams::Enabled {
                config,
                repo_path: path,
            },
            _ => auths_id::witness_config::WitnessParams::Disabled,
        }
    }
}

impl AuthsContext {
    /// Creates a builder for [`AuthsContext`].
    ///
    /// All six required fields (`registry`, `key_storage`, `clock`,
    /// `identity_storage`, `attestation_sink`, `attestation_source`) are enforced
    /// at compile time — the `build()` method is only available once all six are set.
    ///
    /// Usage:
    /// ```ignore
    /// let ctx = AuthsContext::builder()
    ///     .registry(Arc::new(my_registry))
    ///     .key_storage(Arc::new(my_keychain))
    ///     .clock(Arc::new(SystemClock))
    ///     .identity_storage(Arc::new(my_identity_storage))
    ///     .attestation_sink(Arc::new(my_store.clone()))
    ///     .attestation_source(Arc::new(my_store))
    ///     .build();
    /// ```
    pub fn builder() -> AuthsContextBuilder<Missing, Missing, Missing, Missing, Missing, Missing> {
        AuthsContextBuilder {
            registry: Missing,
            key_storage: Missing,
            clock: Missing,
            identity_storage: Missing,
            attestation_sink: Missing,
            attestation_source: Missing,
            event_sink: None,
            passphrase_provider: None,
            uuid_provider: None,
            agent_signing: None,
            witness_config: None,
            repo_path: None,
        }
    }
}

/// Typestate marker: required field not yet set.
pub struct Missing;

/// Typestate marker: required field has been set.
pub struct Set<T>(T);

/// Typestate builder for [`AuthsContext`].
///
/// Call [`AuthsContext::builder()`] to obtain an instance. The `build()` method
/// is only available once all six required fields have been supplied — omitting any
/// produces a compile-time error.
pub struct AuthsContextBuilder<R, K, C, IS, AS, ASrc> {
    registry: R,
    key_storage: K,
    clock: C,
    identity_storage: IS,
    attestation_sink: AS,
    attestation_source: ASrc,
    event_sink: Option<Arc<dyn EventSink>>,
    passphrase_provider: Option<Arc<dyn PassphraseProvider + Send + Sync>>,
    uuid_provider: Option<Arc<dyn UuidProvider + Send + Sync>>,
    agent_signing: Option<Arc<dyn AgentSigningPort + Send + Sync>>,
    witness_config: Option<auths_id::witness_config::WitnessConfig>,
    repo_path: Option<std::path::PathBuf>,
}

// ── Required field setters (each transitions one typestate slot) ──────────────

impl<K, C, IS, AS, ASrc> AuthsContextBuilder<Missing, K, C, IS, AS, ASrc> {
    /// Set the registry storage backend.
    ///
    /// Args:
    /// * `registry`: Pre-initialized registry backend.
    ///
    /// Usage:
    /// ```ignore
    /// builder.registry(Arc::new(my_git_backend))
    /// ```
    pub fn registry(
        self,
        registry: Arc<dyn RegistryBackend + Send + Sync>,
    ) -> AuthsContextBuilder<Set<Arc<dyn RegistryBackend + Send + Sync>>, K, C, IS, AS, ASrc> {
        AuthsContextBuilder {
            registry: Set(registry),
            key_storage: self.key_storage,
            clock: self.clock,
            identity_storage: self.identity_storage,
            attestation_sink: self.attestation_sink,
            attestation_source: self.attestation_source,
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

impl<R, C, IS, AS, ASrc> AuthsContextBuilder<R, Missing, C, IS, AS, ASrc> {
    /// Set the key storage backend.
    ///
    /// Args:
    /// * `key_storage`: Platform keychain or in-memory test fake.
    ///
    /// Usage:
    /// ```ignore
    /// builder.key_storage(Arc::new(my_keychain))
    /// ```
    pub fn key_storage(
        self,
        key_storage: Arc<dyn KeyStorage + Send + Sync>,
    ) -> AuthsContextBuilder<R, Set<Arc<dyn KeyStorage + Send + Sync>>, C, IS, AS, ASrc> {
        AuthsContextBuilder {
            registry: self.registry,
            key_storage: Set(key_storage),
            clock: self.clock,
            identity_storage: self.identity_storage,
            attestation_sink: self.attestation_sink,
            attestation_source: self.attestation_source,
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

impl<R, K, IS, AS, ASrc> AuthsContextBuilder<R, K, Missing, IS, AS, ASrc> {
    /// Set the clock provider.
    ///
    /// Args:
    /// * `clock`: Wall-clock implementation (`SystemClock` in production,
    ///   `MockClock` in tests).
    ///
    /// Usage:
    /// ```ignore
    /// builder.clock(Arc::new(SystemClock))
    /// ```
    pub fn clock(
        self,
        clock: Arc<dyn ClockProvider + Send + Sync>,
    ) -> AuthsContextBuilder<R, K, Set<Arc<dyn ClockProvider + Send + Sync>>, IS, AS, ASrc> {
        AuthsContextBuilder {
            registry: self.registry,
            key_storage: self.key_storage,
            clock: Set(clock),
            identity_storage: self.identity_storage,
            attestation_sink: self.attestation_sink,
            attestation_source: self.attestation_source,
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

impl<R, K, C, AS, ASrc> AuthsContextBuilder<R, K, C, Missing, AS, ASrc> {
    /// Set the identity storage adapter.
    ///
    /// Args:
    /// * `storage`: Pre-initialized identity storage implementation.
    ///
    /// Usage:
    /// ```ignore
    /// builder.identity_storage(Arc::new(my_identity_storage))
    /// ```
    pub fn identity_storage(
        self,
        storage: Arc<dyn IdentityStorage + Send + Sync>,
    ) -> AuthsContextBuilder<R, K, C, Set<Arc<dyn IdentityStorage + Send + Sync>>, AS, ASrc> {
        AuthsContextBuilder {
            registry: self.registry,
            key_storage: self.key_storage,
            clock: self.clock,
            identity_storage: Set(storage),
            attestation_sink: self.attestation_sink,
            attestation_source: self.attestation_source,
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

impl<R, K, C, IS, ASrc> AuthsContextBuilder<R, K, C, IS, Missing, ASrc> {
    /// Set the attestation sink adapter.
    ///
    /// Args:
    /// * `sink`: Pre-initialized attestation sink implementation.
    ///
    /// Usage:
    /// ```ignore
    /// builder.attestation_sink(Arc::new(my_attestation_store))
    /// ```
    pub fn attestation_sink(
        self,
        sink: Arc<dyn AttestationSink + Send + Sync>,
    ) -> AuthsContextBuilder<R, K, C, IS, Set<Arc<dyn AttestationSink + Send + Sync>>, ASrc> {
        AuthsContextBuilder {
            registry: self.registry,
            key_storage: self.key_storage,
            clock: self.clock,
            identity_storage: self.identity_storage,
            attestation_sink: Set(sink),
            attestation_source: self.attestation_source,
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

impl<R, K, C, IS, AS> AuthsContextBuilder<R, K, C, IS, AS, Missing> {
    /// Set the attestation source adapter.
    ///
    /// Args:
    /// * `source`: Pre-initialized attestation source implementation.
    ///
    /// Usage:
    /// ```ignore
    /// builder.attestation_source(Arc::new(my_attestation_store))
    /// ```
    pub fn attestation_source(
        self,
        source: Arc<dyn AttestationSource + Send + Sync>,
    ) -> AuthsContextBuilder<R, K, C, IS, AS, Set<Arc<dyn AttestationSource + Send + Sync>>> {
        AuthsContextBuilder {
            registry: self.registry,
            key_storage: self.key_storage,
            clock: self.clock,
            identity_storage: self.identity_storage,
            attestation_sink: self.attestation_sink,
            attestation_source: Set(source),
            event_sink: self.event_sink,
            passphrase_provider: self.passphrase_provider,
            uuid_provider: self.uuid_provider,
            agent_signing: self.agent_signing,
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}

// ── Optional field setters (available at any typestate, return Self) ──────────

impl<R, K, C, IS, AS, ASrc> AuthsContextBuilder<R, K, C, IS, AS, ASrc> {
    /// Set an optional event sink.
    ///
    /// Defaults to a no-op sink (all events discarded) when not called.
    ///
    /// Args:
    /// * `sink`: Any type implementing [`EventSink`].
    ///
    /// Usage:
    /// ```ignore
    /// builder.event_sink(Arc::new(my_sink))
    /// ```
    pub fn event_sink(mut self, sink: Arc<dyn EventSink>) -> Self {
        self.event_sink = Some(sink);
        self
    }

    /// Set the passphrase provider for key decryption during signing operations.
    ///
    /// Defaults to a noop provider that returns an error. Set this when SDK
    /// workflow functions will perform signing with encrypted key material.
    ///
    /// Args:
    /// * `provider`: Any type implementing [`PassphraseProvider`].
    ///
    /// Usage:
    /// ```ignore
    /// builder.passphrase_provider(Arc::new(PrefilledPassphraseProvider::new(passphrase)))
    /// ```
    pub fn passphrase_provider(
        mut self,
        provider: Arc<dyn PassphraseProvider + Send + Sync>,
    ) -> Self {
        self.passphrase_provider = Some(provider);
        self
    }

    /// Set the UUID provider.
    ///
    /// Defaults to [`SystemUuidProvider`] (random v4 UUIDs) when not called.
    /// Override with a deterministic stub in tests.
    ///
    /// Args:
    /// * `provider`: Any type implementing [`UuidProvider`].
    ///
    /// Usage:
    /// ```ignore
    /// builder.uuid_provider(Arc::new(my_uuid_stub))
    /// ```
    pub fn uuid_provider(mut self, provider: Arc<dyn UuidProvider + Send + Sync>) -> Self {
        self.uuid_provider = Some(provider);
        self
    }

    /// Set the agent signing port for delegating signing to a running agent process.
    ///
    /// Defaults to a noop provider (all operations return `Unavailable`)
    /// when not called. Set this on Unix platforms where the auths-agent daemon
    /// is available.
    ///
    /// Args:
    /// * `provider`: Any type implementing [`AgentSigningPort`].
    ///
    /// Usage:
    /// ```ignore
    /// builder.agent_signing(Arc::new(CliAgentAdapter::new(socket_path)))
    /// ```
    pub fn agent_signing(mut self, provider: Arc<dyn AgentSigningPort + Send + Sync>) -> Self {
        self.agent_signing = Some(provider);
        self
    }

    /// Set witness configuration for KEL event receipting.
    pub fn witness_config(mut self, config: auths_id::witness_config::WitnessConfig) -> Self {
        self.witness_config = Some(config);
        self
    }

    /// Set the repository path (needed for witness receipt storage).
    pub fn repo_path(mut self, path: std::path::PathBuf) -> Self {
        self.repo_path = Some(path);
        self
    }
}

// ── Infallible build — only available when all six required fields are set ────

impl
    AuthsContextBuilder<
        Set<Arc<dyn RegistryBackend + Send + Sync>>,
        Set<Arc<dyn KeyStorage + Send + Sync>>,
        Set<Arc<dyn ClockProvider + Send + Sync>>,
        Set<Arc<dyn IdentityStorage + Send + Sync>>,
        Set<Arc<dyn AttestationSink + Send + Sync>>,
        Set<Arc<dyn AttestationSource + Send + Sync>>,
    >
{
    /// Build the [`AuthsContext`].
    ///
    /// Infallible — only callable once all six required fields are set.
    /// Omitting any required field is a compile-time error.
    ///
    /// Usage:
    /// ```ignore
    /// let ctx = AuthsContext::builder()
    ///     .registry(Arc::new(my_registry))
    ///     .key_storage(Arc::new(my_keychain))
    ///     .clock(Arc::new(SystemClock))
    ///     .identity_storage(Arc::new(my_identity_storage))
    ///     .attestation_sink(Arc::new(my_store.clone()))
    ///     .attestation_source(Arc::new(my_store))
    ///     .build();
    /// ```
    pub fn build(self) -> AuthsContext {
        AuthsContext {
            registry: self.registry.0,
            key_storage: self.key_storage.0,
            clock: self.clock.0,
            identity_storage: self.identity_storage.0,
            attestation_sink: self.attestation_sink.0,
            attestation_source: self.attestation_source.0,
            event_sink: self.event_sink.unwrap_or_else(|| Arc::new(NoopSink)),
            passphrase_provider: self
                .passphrase_provider
                .unwrap_or_else(|| Arc::new(NoopPassphraseProvider)),
            uuid_provider: self
                .uuid_provider
                .unwrap_or_else(|| Arc::new(SystemUuidProvider)),
            agent_signing: self
                .agent_signing
                .unwrap_or_else(|| Arc::new(NoopAgentProvider)),
            witness_config: self.witness_config,
            repo_path: self.repo_path,
        }
    }
}