auths-sdk 0.1.16

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
//! Organization member lookups.
//!
//! KERI-native membership — adding, revoking, listing, and authority resolution —
//! lives in [`crate::domains::org::delegation`], where a member is a `dip`
//! delegated by the org AID (authority is KEL-authoritative and fail-closed). This
//! module retains member-lookup helpers that accept an [`OrgContext`] carrying
//! injected infrastructure adapters (registry, clock, signer, passphrase provider).

use std::ops::ControlFlow;
use std::sync::Arc;

use auths_core::ports::clock::ClockProvider;
use auths_core::ports::id::UuidProvider;
use auths_core::signing::{PassphraseProvider, SecureSigner, StorageSigner};
use auths_core::storage::keychain::{KeyAlias, extract_public_key_bytes};
use auths_id::attestation::create::{AttestationInput, create_signed_attestation};
use auths_id::keri::{parse_did_keri, try_stage_anchor};
use auths_id::ports::registry::RegistryBackend;
use auths_id::storage::git_refs::AttestationMetadata;
use auths_id::storage::registry::backend::AtomicWriteBatch;
use auths_id::witness_config::WitnessParams;
use auths_verifier::core::Attestation;
pub use auths_verifier::core::Role;
use auths_verifier::types::CanonicalDid;
use chrono::{DateTime, Utc};

use crate::context::AuthsContext;
use crate::domains::org::error::OrgError;
use crate::identity::initialize_registry_identity;

/// Runtime dependency container for organization workflows.
///
/// Bundles all injected infrastructure adapters needed by org operations.
/// The CLI constructs this from real implementations; tests inject fakes.
///
/// Args:
/// * `registry`: Backend for reading/writing org member attestations.
/// * `clock`: Wall-clock provider (use `SystemClock` in production, `MockClock` in tests).
/// * `uuid_provider`: UUID generator for attestation resource IDs.
/// * `signer`: Signing backend for creating cryptographic signatures.
/// * `passphrase_provider`: Provider for obtaining key decryption passphrases.
///
/// Usage:
/// ```ignore
/// let ctx = OrgContext {
///     registry: &backend,
///     clock: &SystemClock,
///     uuid_provider: &uuid_provider,
///     signer: &signer,
///     passphrase_provider: passphrase_provider.as_ref(),
/// };
/// let att = update_organization_member(&ctx, cmd)?;
/// ```
pub struct OrgContext<'a> {
    /// Backend for reading/writing org member attestations.
    pub registry: &'a dyn RegistryBackend,
    /// Wall-clock provider (use `SystemClock` in production, `MockClock` in tests).
    pub clock: &'a dyn ClockProvider,
    /// UUID generator for attestation resource IDs.
    pub uuid_provider: &'a dyn UuidProvider,
    /// Signing backend for creating cryptographic signatures.
    pub signer: &'a dyn SecureSigner,
    /// Provider for obtaining key decryption passphrases.
    pub passphrase_provider: &'a dyn PassphraseProvider,
    /// Witness receipting configuration for KEL event anchoring.
    pub witness_params: WitnessParams<'a>,
}

/// Ordering key for org member display: admin < member < readonly < unknown.
///
/// Args:
/// * `role`: Optional role as stored in an attestation.
///
/// Usage:
/// ```ignore
/// members.sort_by(|a, b| member_role_order(&a.role).cmp(&member_role_order(&b.role)));
/// ```
pub fn member_role_order(role: &Option<Role>) -> u8 {
    match role {
        Some(Role::Admin) => 0,
        Some(Role::Member) => 1,
        Some(Role::Readonly) => 2,
        None => 3,
    }
}

/// Find a member's current attestation by their DID within an org.
///
/// Args:
/// * `backend`: Registry backend to query.
/// * `org_prefix`: The KERI method-specific ID of the organization.
/// * `member_did`: Full DID of the member to look up.
///
/// Usage:
/// ```ignore
/// let att = find_member(backend, "EOrg1234567890", "did:key:z6Mk...")?;
/// ```
pub(crate) fn find_member(
    backend: &dyn RegistryBackend,
    org_prefix: &str,
    member_did: &str,
) -> Result<Option<Attestation>, OrgError> {
    let mut found: Option<Attestation> = None;

    backend
        .visit_org_member_attestations(org_prefix, &mut |entry| {
            if entry.did.as_str() == member_did
                && let Ok(att) = &entry.attestation
            {
                found = Some(att.clone());
                return ControlFlow::Break(());
            }
            ControlFlow::Continue(())
        })
        .map_err(OrgError::Storage)?;

    Ok(found)
}

// ── Command structs ───────────────────────────────────────────────────────────

/// Accepts either a KERI prefix or a full DID.
///
/// Auto-detected by whether the string starts with `did:`.
#[derive(Debug, Clone)]
pub enum OrgIdentifier {
    /// Bare KERI prefix (e.g. `EOrg1234567890`).
    Prefix(String),
    /// Full DID (e.g. `did:keri:EOrg1234567890`).
    Did(String),
}

impl OrgIdentifier {
    /// Parse a string into an `OrgIdentifier`, auto-detecting the format.
    pub fn parse(s: &str) -> Self {
        if s.starts_with("did:") {
            OrgIdentifier::Did(s.to_owned())
        } else {
            OrgIdentifier::Prefix(s.to_owned())
        }
    }

    /// Extract the KERI prefix regardless of format.
    pub fn prefix(&self) -> &str {
        match self {
            OrgIdentifier::Prefix(p) => p,
            OrgIdentifier::Did(d) => d.strip_prefix("did:keri:").unwrap_or(d),
        }
    }
}

impl From<&str> for OrgIdentifier {
    fn from(s: &str) -> Self {
        OrgIdentifier::parse(s)
    }
}

// ── Workflow functions ────────────────────────────────────────────────────────

/// Outcome of creating a new organization identity.
#[derive(Debug, Clone)]
pub struct OrgCreated {
    /// The org's `did:keri:` (self-certifying — derived from its inception SAID).
    pub org_did: String,
    /// The org's KEL prefix.
    pub org_prefix: String,
    /// The admin DID anchored by the self-attestation (equal to `org_did` for a
    /// single-controller org).
    pub admin_did: String,
    /// Keychain alias the org's signing key was stored under.
    pub key_alias: String,
    /// Resolved org metadata (`type`/`name`/`created_at` plus any merged extras).
    pub metadata: serde_json::Value,
}

/// Build the org's descriptive metadata, merging caller-supplied extras.
///
/// `type` and `name` are reserved and never overwritten by `extra`.
fn build_org_metadata(
    name: &str,
    now: DateTime<Utc>,
    extra: Option<serde_json::Value>,
) -> serde_json::Value {
    let mut metadata = serde_json::json!({
        "type": "org",
        "name": name,
        "created_at": now.to_rfc3339(),
    });
    if let Some(serde_json::Value::Object(add)) = extra
        && let Some(base) = metadata.as_object_mut()
    {
        for (k, v) in add {
            if k != "type" && k != "name" {
                base.insert(k, v);
            }
        }
    }
    metadata
}

/// Create a new organization as a self-certifying KERI identity.
///
/// Mints a `kt=1` org AID via the registry backend and anchors a self-signed admin
/// attestation in the org's KEL — the same on-disk layout the inline CLI path
/// produced, now reusable by the CLI, Node, and Python surfaces and by the
/// deployment kit for programmatic provisioning. The clock is read from
/// `ctx.clock`; no `Utc::now()` is called in domain code. Fails closed if an
/// identity already exists in the context's registry.
///
/// Args:
/// * `ctx`: Auths context (registry, key storage, clock, passphrase provider).
/// * `name`: Human-readable organization name (recorded in the admin attestation).
/// * `admin_alias`: Keychain alias to store the org's signing key under.
/// * `curve`: Signing curve for the org's inception key.
/// * `metadata`: Optional extra metadata merged into the org descriptor.
///
/// Usage:
/// ```ignore
/// let created = create_org(&ctx, "Acme Security", &alias, CurveType::default(), None)?;
/// println!("org: {}", created.org_did);
/// ```
pub fn create_org(
    ctx: &AuthsContext,
    name: &str,
    admin_alias: &KeyAlias,
    curve: auths_crypto::CurveType,
    metadata: Option<serde_json::Value>,
) -> Result<OrgCreated, OrgError> {
    let now = ctx.clock.now();

    if ctx.identity_storage.load_identity().is_ok() {
        return Err(OrgError::IdentityExists {
            location: ctx
                .repo_path
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "the registry".to_string()),
        });
    }

    let metadata_json = build_org_metadata(name, now, metadata);

    let (controller_did, alias) = initialize_registry_identity(
        Arc::clone(&ctx.registry),
        admin_alias,
        ctx.passphrase_provider.as_ref(),
        ctx.key_storage.as_ref(),
        ctx.witness_params(),
        curve,
        now,
    )
    .map_err(OrgError::IdentityInit)?;

    let managed = ctx
        .identity_storage
        .load_identity()
        .map_err(|e| OrgError::Identity(e.to_string()))?;
    let rid = managed.storage_id;

    let (org_pk_bytes, org_curve) = extract_public_key_bytes(
        ctx.key_storage.as_ref(),
        admin_alias,
        ctx.passphrase_provider.as_ref(),
    )
    .map_err(OrgError::CryptoError)?;

    let signer = StorageSigner::new(Arc::clone(&ctx.key_storage));

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: controller_did is freshly minted by inception — a valid did:keri
    let org_did = CanonicalDid::new_unchecked(controller_did.to_string());

    let meta = AttestationMetadata {
        note: Some(format!("Organization '{name}' root admin")),
        timestamp: Some(now),
        expires_at: None,
    };

    let issuer_canonical = CanonicalDid::from(controller_did.clone());
    let attestation = create_signed_attestation(
        now,
        AttestationInput {
            rid: &rid,
            issuer: &issuer_canonical,
            subject: &org_did,
            device_public_key: &org_pk_bytes,
            device_curve: org_curve,
            payload: Some(serde_json::json!({ "org_role": "admin", "org_name": name })),
            meta: &meta,
            identity_alias: Some(&alias),
            device_alias: None,
            delegated_by: None,
            commit_sha: None,
            signer_type: None,
            oidc_binding: None,
        },
        &signer,
        ctx.passphrase_provider.as_ref(),
    )
    .map_err(OrgError::Attestation)?;

    let org_prefix =
        parse_did_keri(controller_did.as_str()).map_err(|e| OrgError::InvalidDid(e.to_string()))?;

    let mut batch = AtomicWriteBatch::new();
    batch.stage_attestation(attestation);
    try_stage_anchor(
        ctx.registry.as_ref(),
        &signer,
        &alias,
        ctx.passphrase_provider.as_ref(),
        &org_prefix,
        &serde_json::json!({}),
        &mut batch,
    )?;
    ctx.registry
        .commit_batch(&batch)
        .map_err(OrgError::Storage)?;

    Ok(OrgCreated {
        org_did: controller_did.to_string(),
        org_prefix: org_prefix.as_str().to_string(),
        admin_did: org_did.to_string(),
        key_alias: alias.as_str().to_string(),
        metadata: metadata_json,
    })
}

/// The default keychain alias for an org's signing key, derived from its
/// identifier (`org-{slug}`).
///
/// This is only the *fallback* convention used by [`resolve_org_signing_alias`]
/// when the keychain holds no Primary key for the org DID (e.g. a server-side
/// caller that pre-stored its key under this exact alias). The authoritative
/// resolution is the keychain lookup, not this slug — `org create` and the
/// org-signing commands once derived this slug from *different* inputs (the org
/// name vs. the org DID), so the two never matched.
pub fn org_slug_alias(org: &str) -> String {
    format!(
        "org-{}",
        org.chars()
            .filter(|c| c.is_alphanumeric())
            .take(20)
            .collect::<String>()
            .to_lowercase()
    )
}

/// Resolve the keychain alias of an organization's signing (Primary) key.
///
/// The keychain is the single source of truth: an org's signing key is stored
/// under [`KeyRole::Primary`] keyed by the org's controller DID, regardless of
/// the human-readable alias chosen at `org create` time. Given the org DID we
/// ask the keychain which alias holds that Primary key, so every org-signing
/// command (`add-member`, `revoke-member`, `policy set`, `anchor-oidc-policy`,
/// compliance) resolves to the *same* alias `create` actually stored — no
/// fragile slug reconstruction that breaks when name and DID disagree.
///
/// Args:
/// * `keychain`: The key storage port to query.
/// * `org_prefix`: The org's KERI prefix (the `did:keri:` identifier portion).
/// * `explicit`: An operator-supplied `--key` alias; when present it wins.
///
/// Resolution order:
/// 1. `explicit` (the operator overrode the default).
/// 2. The single Primary alias bound to the org DID in the keychain.
/// 3. The `org-{slug}` fallback derived from the org prefix (only when the
///    keychain has no Primary key for the DID — a pre-seeded server key).
///
/// Usage:
/// ```ignore
/// let alias = resolve_org_signing_alias(ctx.key_storage.as_ref(), org_prefix.as_str(), key)?;
/// ```
pub fn resolve_org_signing_alias(
    keychain: &(dyn auths_core::storage::keychain::KeyStorage + Send + Sync),
    org_prefix: &str,
    explicit: Option<String>,
) -> Result<KeyAlias, OrgError> {
    if let Some(alias) = explicit {
        return Ok(KeyAlias::new_unchecked(alias));
    }

    let org_did = auths_verifier::types::IdentityDID::from_prefix(org_prefix)
        .map_err(|e| OrgError::InvalidDid(e.to_string()))?;

    let primaries = keychain
        .list_aliases_for_identity_with_role(
            &org_did,
            auths_core::storage::keychain::KeyRole::Primary,
        )
        .map_err(OrgError::CryptoError)?;

    match primaries.into_iter().next() {
        Some(alias) => Ok(alias),
        None => Ok(KeyAlias::new_unchecked(org_slug_alias(org_prefix))),
    }
}

/// Look up a single org member by DID (O(1) with the right backend).
pub fn get_organization_member(
    backend: &dyn RegistryBackend,
    org_prefix: &str,
    member_did: &str,
) -> Result<Attestation, OrgError> {
    find_member(backend, org_prefix, member_did)?.ok_or_else(|| OrgError::MemberNotFound {
        org: org_prefix.to_owned(),
        did: member_did.to_owned(),
    })
}