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
//! Platform identity claim workflow orchestration.
//!
//! Orchestrates OAuth device flow, proof publishing, and registry submission
//! for linking platform identities (e.g. GitHub) to a controller DID.

use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use auths_core::ports::platform::{
    ClaimResponse, DeviceCodeResponse, OAuthDeviceFlowProvider, PlatformError,
    PlatformProofPublisher, PlatformUserProfile, RegistryClaimClient, SshSigningKeyUploader,
};
use auths_core::signing::{SecureSigner, StorageSigner};
use auths_core::storage::keychain::{IdentityDID, KeyAlias};
use auths_id::storage::identity::IdentityStorage;

use crate::context::AuthsContext;
use crate::pairing::PairingError;

/// Signed platform claim linking a controller DID to a platform identity.
///
/// Canonicalized (RFC 8785) before signing so that the Ed25519 signature
/// can be verified by anyone using only the DID's public key.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlatformClaim {
    /// Claim type discriminant; always `"platform_claim"`.
    #[serde(rename = "type")]
    pub claim_type: String,
    /// Platform identifier (e.g. `"github"`).
    pub platform: String,
    /// Username on the platform.
    pub namespace: String,
    /// Controller DID being linked.
    pub did: String,
    /// RFC 3339 timestamp of claim creation.
    pub timestamp: String,
    /// Base64url-encoded Ed25519 signature over the canonical unsigned JSON.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

/// Configuration for GitHub identity claim workflow.
///
/// Args:
/// * `client_id`: GitHub OAuth application client ID.
/// * `registry_url`: Base URL of the auths registry.
/// * `scopes`: OAuth scopes to request (e.g. `"read:user gist"`).
pub struct GitHubClaimConfig {
    /// GitHub OAuth application client ID.
    pub client_id: String,
    /// Base URL of the auths registry.
    pub registry_url: String,
    /// OAuth scopes to request.
    pub scopes: String,
}

/// Create and sign a platform claim JSON string.
///
/// Builds the claim, canonicalizes (RFC 8785), signs with the identity key,
/// and returns the pretty-printed signed JSON.
///
/// Args:
/// * `platform`: Platform name (e.g. `"github"`).
/// * `namespace`: Username on the platform.
/// * `did`: Controller DID.
/// * `key_alias`: Keychain alias for the signing key.
/// * `ctx`: Runtime context supplying `key_storage` and `passphrase_provider`.
/// * `now`: Current time (injected by caller — no `Utc::now()` in SDK).
///
/// Usage:
/// ```ignore
/// let claim_json = create_signed_platform_claim("github", "octocat", &did, &alias, &ctx, now)?;
/// ```
pub fn create_signed_platform_claim(
    platform: &str,
    namespace: &str,
    did: &str,
    key_alias: &KeyAlias,
    ctx: &AuthsContext,
    now: DateTime<Utc>,
) -> Result<String, PairingError> {
    let mut claim = PlatformClaim {
        claim_type: "platform_claim".to_string(),
        platform: platform.to_string(),
        namespace: namespace.to_string(),
        did: did.to_string(),
        timestamp: now.to_rfc3339(),
        signature: None,
    };

    let unsigned_json = serde_json::to_value(&claim)
        .map_err(|e| PairingError::AttestationFailed(format!("failed to serialize claim: {e}")))?;
    let canonical = json_canon::to_string(&unsigned_json).map_err(|e| {
        PairingError::AttestationFailed(format!("failed to canonicalize claim: {e}"))
    })?;

    let signer = StorageSigner::new(std::sync::Arc::clone(&ctx.key_storage));
    let signature_bytes = signer
        .sign_with_alias(
            key_alias,
            ctx.passphrase_provider.as_ref(),
            canonical.as_bytes(),
        )
        .map_err(|e| {
            PairingError::AttestationFailed(format!("failed to sign platform claim: {e}"))
        })?;

    claim.signature = Some(URL_SAFE_NO_PAD.encode(&signature_bytes));

    serde_json::to_string_pretty(&claim).map_err(|e| {
        PairingError::AttestationFailed(format!("failed to serialize signed claim: {e}"))
    })
}

/// Orchestrate GitHub identity claiming end-to-end.
///
/// Steps:
/// 1. Request OAuth device code.
/// 2. Fire `on_device_code` callback (CLI displays `user_code`, opens browser).
/// 3. Poll for access token (RFC 8628 device flow).
/// 4. Fetch GitHub user profile.
/// 5. Create signed platform claim (injected `now`, no `Utc::now()` in SDK).
/// 6. Publish claim as a GitHub Gist proof.
/// 7. Submit claim to registry.
///
/// Args:
/// * `oauth`: OAuth device flow provider.
/// * `publisher`: Proof publisher (publishes Gist).
/// * `registry_claim`: Registry claim client.
/// * `ctx`: Runtime context (identity, key storage, passphrase provider).
/// * `config`: GitHub client ID, registry URL, and OAuth scopes.
/// * `now`: Current time (injected by caller).
/// * `on_device_code`: Callback fired after device code is obtained; CLI shows
///   `user_code`, opens browser, displays instructions.
///
/// Usage:
/// ```ignore
/// let response = claim_github_identity(
///     &oauth_provider,
///     &gist_publisher,
///     &registry_client,
///     &ctx,
///     GitHubClaimConfig { client_id: "...".into(), registry_url: "...".into(), scopes: "read:user gist".into() },
///     Utc::now(),
///     &|code| { open::that(&code.verification_uri).ok(); },
/// ).await?;
/// ```
pub async fn claim_github_identity<
    O: OAuthDeviceFlowProvider,
    P: PlatformProofPublisher,
    C: RegistryClaimClient,
>(
    oauth: &O,
    publisher: &P,
    registry_claim: &C,
    ctx: &AuthsContext,
    config: GitHubClaimConfig,
    now: DateTime<Utc>,
    on_device_code: &(dyn Fn(&DeviceCodeResponse) + Send + Sync),
) -> Result<ClaimResponse, PlatformError> {
    let device_code = oauth
        .request_device_code(&config.client_id, &config.scopes)
        .await?;

    on_device_code(&device_code);

    let expires_in = Duration::from_secs(device_code.expires_in);
    let interval = Duration::from_secs(device_code.interval);

    let access_token = oauth
        .poll_for_token(
            &config.client_id,
            &device_code.device_code,
            interval,
            expires_in,
        )
        .await?;

    let profile = oauth.fetch_user_profile(&access_token).await?;

    let controller_did = crate::pairing::load_controller_did(ctx.identity_storage.as_ref())
        .map_err(|e| PlatformError::Platform {
            message: e.to_string(),
        })?;

    let key_alias = resolve_signing_key_alias(ctx, &controller_did)?;

    let claim_json = create_signed_platform_claim(
        "github",
        &profile.login,
        &controller_did,
        &key_alias,
        ctx,
        now,
    )
    .map_err(|e| PlatformError::Platform {
        message: e.to_string(),
    })?;

    let proof_url = publisher.publish_proof(&access_token, &claim_json).await?;

    registry_claim
        .submit_claim(&config.registry_url, &controller_did, &proof_url)
        .await
}

/// Configuration for claiming an npm platform identity.
pub struct NpmClaimConfig {
    /// Registry URL to submit the claim to.
    pub registry_url: String,
}

/// Claims an npm platform identity by verifying an npm access token.
///
/// Args:
/// * `npm_username`: The verified npm username (from `HttpNpmAuthProvider::verify_token`).
/// * `registry_claim`: Client for submitting the claim to the auths registry.
/// * `ctx`: Auths context with identity storage and signing keys.
/// * `config`: npm claim configuration (registry URL).
/// * `now`: Current time for timestamp in the claim.
///
/// Usage:
/// ```ignore
/// let response = claim_npm_identity("bordumb", &registry_client, &ctx, config, now).await?;
/// ```
pub async fn claim_npm_identity<C: RegistryClaimClient>(
    npm_username: &str,
    npm_token: &str,
    registry_claim: &C,
    ctx: &AuthsContext,
    config: NpmClaimConfig,
    now: DateTime<Utc>,
) -> Result<ClaimResponse, PlatformError> {
    let controller_did = crate::pairing::load_controller_did(ctx.identity_storage.as_ref())
        .map_err(|e| PlatformError::Platform {
            message: e.to_string(),
        })?;

    let key_alias = resolve_signing_key_alias(ctx, &controller_did)?;

    let claim_json =
        create_signed_platform_claim("npm", npm_username, &controller_did, &key_alias, ctx, now)
            .map_err(|e| PlatformError::Platform {
                message: e.to_string(),
            })?;

    // npm has no Gist equivalent. Encode both the npm token (for server-side
    // verification via npm whoami) and the signed claim (for signature verification).
    // The server detects the "npm-token:" prefix, verifies the token, then discards it.
    let encoded_claim = URL_SAFE_NO_PAD.encode(claim_json.as_bytes());
    let encoded_token = URL_SAFE_NO_PAD.encode(npm_token.as_bytes());
    let proof_url = format!("npm-token:{encoded_token}:{encoded_claim}");

    registry_claim
        .submit_claim(&config.registry_url, &controller_did, &proof_url)
        .await
}

/// Configuration for claiming a PyPI platform identity.
pub struct PypiClaimConfig {
    /// Registry URL to submit the claim to.
    pub registry_url: String,
}

/// Claims a PyPI platform identity via self-reported username + signed claim.
///
/// SECURITY: PyPI's token verification API (/danger-api/echo) is unreliable,
/// so we don't verify tokens. Instead, the platform claim is a self-reported
/// username backed by a DID-signed proof. The real security check happens at
/// namespace claim time, when the PyPI verifier checks the public pypi.org
/// JSON API to confirm the username is a maintainer of the target package.
///
/// This is equivalent to the GitHub flow's trust model: the claim is signed
/// with the device key (stored in platform keychain, not in CI), so a stolen
/// PyPI token alone cannot produce a valid claim.
///
/// Args:
/// * `pypi_username`: The user's self-reported PyPI username.
/// * `registry_claim`: Client for submitting the claim to the auths registry.
/// * `ctx`: Auths context with identity storage and signing keys.
/// * `config`: PyPI claim configuration (registry URL).
/// * `now`: Current time for timestamp in the claim.
///
/// Usage:
/// ```ignore
/// let response = claim_pypi_identity("bordumb", &registry_client, &ctx, config, now).await?;
/// ```
pub async fn claim_pypi_identity<C: RegistryClaimClient>(
    pypi_username: &str,
    registry_claim: &C,
    ctx: &AuthsContext,
    config: PypiClaimConfig,
    now: DateTime<Utc>,
) -> Result<ClaimResponse, PlatformError> {
    let controller_did = crate::pairing::load_controller_did(ctx.identity_storage.as_ref())
        .map_err(|e| PlatformError::Platform {
            message: e.to_string(),
        })?;

    let key_alias = resolve_signing_key_alias(ctx, &controller_did)?;

    let claim_json =
        create_signed_platform_claim("pypi", pypi_username, &controller_did, &key_alias, ctx, now)
            .map_err(|e| PlatformError::Platform {
                message: e.to_string(),
            })?;

    // PyPI's token verification API is unreliable. Submit the signed claim
    // directly. The server verifies the Ed25519 signature but does not
    // independently verify the username via PyPI. The real ownership check
    // happens at namespace claim time via the public PyPI JSON API.
    let encoded_claim = URL_SAFE_NO_PAD.encode(claim_json.as_bytes());
    let proof_url = format!("pypi-claim:{encoded_claim}");

    registry_claim
        .submit_claim(&config.registry_url, &controller_did, &proof_url)
        .await
}

fn resolve_signing_key_alias(
    ctx: &AuthsContext,
    controller_did: &str,
) -> Result<KeyAlias, PlatformError> {
    #[allow(clippy::disallowed_methods)]
    // INVARIANT: controller_did comes from load_controller_did() which returns into_inner() of a validated IdentityDID from storage
    let identity_did = IdentityDID::new_unchecked(controller_did.to_string());
    let aliases = ctx
        .key_storage
        .list_aliases_for_identity(&identity_did)
        .map_err(|e| PlatformError::Platform {
            message: format!("failed to list key aliases: {e}"),
        })?;

    aliases
        .into_iter()
        .find(|a| !a.contains("--next-"))
        .ok_or_else(|| PlatformError::Platform {
            message: format!("no signing key found for identity {controller_did}"),
        })
}

/// Upload the SSH signing key for the identity to GitHub.
///
/// Stores metadata about the uploaded key (key ID, GitHub username, timestamp)
/// in the identity metadata for future reference and idempotency.
///
/// Args:
/// * `uploader`: HTTP implementation of SSH key uploader.
/// * `access_token`: GitHub OAuth access token with `write:ssh_signing_key` scope.
/// * `public_key`: SSH public key in OpenSSH format (ssh-ed25519 AAAA...).
/// * `key_alias`: Keychain alias for the device key.
/// * `hostname`: Machine hostname for the key title.
/// * `identity_storage`: Storage backend for persisting metadata.
/// * `now`: Current time (injected by caller; SDK does not call Utc::now()).
///
/// Returns: Ok(()) on success, PlatformError on failure (non-fatal; init continues).
///
/// Usage:
/// ```ignore
/// upload_github_ssh_signing_key(
///     &uploader,
///     "ghu_token...",
///     "ssh-ed25519 AAAA...",
///     "main",
///     "MacBook-Pro.local",
///     &identity_storage,
///     Utc::now(),
/// ).await?;
/// ```
pub async fn upload_github_ssh_signing_key<U: SshSigningKeyUploader + ?Sized>(
    uploader: &U,
    access_token: &str,
    public_key: &str,
    key_alias: &str,
    hostname: &str,
    identity_storage: &(dyn IdentityStorage + Send + Sync),
    now: DateTime<Utc>,
) -> Result<(), PlatformError> {
    let title = format!("auths/{key_alias} ({hostname})");

    let key_id = uploader
        .upload_signing_key(access_token, public_key, &title)
        .await?;

    // Load existing identity to get the controller DID
    let existing = identity_storage
        .load_identity()
        .map_err(|e| PlatformError::Platform {
            message: format!("failed to load identity: {e}"),
        })?;

    let metadata = serde_json::json!({
        "github_ssh_key": {
            "key_id": key_id,
            "uploaded_at": now.to_rfc3339(),
        }
    });

    identity_storage
        .create_identity(existing.controller_did.as_ref(), Some(metadata))
        .map_err(|e| PlatformError::Platform {
            message: format!("failed to store SSH key metadata: {e}"),
        })?;

    Ok(())
}

/// Re-authorize with GitHub and optionally upload the SSH signing key.
///
/// Re-runs the OAuth device flow to obtain a fresh token with potentially
/// new scopes, then attempts to upload the SSH signing key if provided.
///
/// Args:
/// * `oauth`: OAuth device flow provider.
/// * `uploader`: SSH key uploader.
/// * `identity_storage`: Storage backend for identity and metadata.
/// * `ctx`: Runtime context (key storage, passphrase provider).
/// * `config`: GitHub OAuth client ID and registry URL.
/// * `key_alias`: Keychain alias for the device key.
/// * `hostname`: Machine hostname for the key title.
/// * `public_key`: SSH public key in OpenSSH format (optional).
/// * `now`: Current time (injected by caller).
/// * `on_device_code`: Callback fired after device code is obtained.
///
/// Usage:
/// ```ignore
/// update_github_ssh_scopes(
///     &oauth_provider,
///     &uploader,
///     &identity_storage,
///     &ctx,
///     &config,
///     "main",
///     "MacBook.local",
///     Some("ssh-ed25519 AAAA..."),
///     Utc::now(),
///     &|code| { println!("Authorize at: {}", code.verification_uri); },
/// ).await?;
/// ```
#[allow(clippy::too_many_arguments)]
pub async fn update_github_ssh_scopes<
    O: OAuthDeviceFlowProvider + ?Sized,
    U: SshSigningKeyUploader + ?Sized,
>(
    oauth: &O,
    uploader: &U,
    identity_storage: &(dyn IdentityStorage + Send + Sync),
    _ctx: &AuthsContext,
    config: &GitHubClaimConfig,
    key_alias: &str,
    hostname: &str,
    public_key: Option<&str>,
    now: DateTime<Utc>,
    on_device_code: &dyn Fn(&DeviceCodeResponse),
) -> Result<PlatformUserProfile, PlatformError> {
    let resp = oauth
        .request_device_code(&config.client_id, &config.scopes)
        .await?;
    on_device_code(&resp);

    let access_token = oauth
        .poll_for_token(
            &config.client_id,
            &resp.device_code,
            Duration::from_secs(resp.interval),
            Duration::from_secs(resp.expires_in),
        )
        .await?;

    let profile = oauth.fetch_user_profile(&access_token).await?;

    if let Some(key) = public_key {
        let _ = upload_github_ssh_signing_key(
            uploader,
            &access_token,
            key,
            key_alias,
            hostname,
            identity_storage,
            now,
        )
        .await;
    }

    Ok(profile)
}