-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauthorization.rs
More file actions
583 lines (522 loc) · 19.4 KB
/
authorization.rs
File metadata and controls
583 lines (522 loc) · 19.4 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use anyhow::{Context, Result, anyhow};
use clap::{Args, Subcommand};
use log::warn;
use serde::Serialize;
use serde_json::Value;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use auths_core::config::EnvironmentConfig;
use auths_core::signing::{PassphraseProvider, UnifiedPassphraseProvider};
use auths_core::storage::keychain::KeyAlias;
use auths_id::attestation::group::AttestationGroup;
use auths_id::identity::helpers::ManagedIdentity;
use auths_id::storage::attestation::AttestationSource;
use auths_id::storage::identity::IdentityStorage;
use auths_id::storage::layout::{self, StorageLayoutConfig};
use auths_storage::git::{
GitRegistryBackend, RegistryAttestationStorage, RegistryConfig, RegistryIdentityStorage,
};
use chrono::Utc;
use crate::commands::registry_overrides::RegistryOverrides;
use crate::factories::storage::build_auths_context;
use crate::ux::format::{JsonResponse, is_json_mode};
#[derive(Serialize)]
struct DeviceEntry {
id: String,
status: String,
public_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
created_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
expires_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
note: Option<String>,
}
#[derive(Args, Debug, Clone)]
#[command(about = "Manage device authorizations within an identity repository.")]
pub struct DeviceCommand {
#[command(subcommand)]
pub command: DeviceSubcommand,
#[command(flatten)]
pub overrides: RegistryOverrides,
}
#[derive(Subcommand, Debug, Clone)]
pub enum DeviceSubcommand {
/// List all authorized devices for the current identity.
List {
/// Include devices with revoked or expired authorizations in the output.
#[arg(
long,
help = "Include devices with revoked or expired authorizations in the output."
)]
include_revoked: bool,
},
/// Authorize a new device to act on behalf of the identity.
#[command(visible_alias = "add")]
Link {
#[arg(long, help = "Local alias of the *identity's* key (used for signing).")]
key: String,
#[arg(
long,
help = "Local alias of the *new device's* key (must be imported first)."
)]
device_key: String,
#[arg(
long,
visible_alias = "device",
help = "Identity ID of the new device being authorized (must match --device-key)."
)]
device_did: String,
#[arg(
long,
value_name = "PAYLOAD_PATH",
help = "Optional path to a JSON file containing arbitrary payload data for the authorization."
)]
payload: Option<PathBuf>,
#[arg(
long,
value_name = "SCHEMA_PATH",
help = "Optional path to a JSON schema for validating the payload (experimental)."
)]
schema: Option<PathBuf>,
/// Duration in seconds until expiration (per RFC 6749).
#[arg(
long = "expires-in",
value_name = "SECS",
help = "Optional number of seconds until this device authorization expires."
)]
expires_in: Option<u64>,
#[arg(
long,
help = "Optional description/note for this device authorization."
)]
note: Option<String>,
#[arg(
long,
value_delimiter = ',',
help = "Permissions to grant this device (comma-separated)"
)]
capabilities: Option<Vec<String>>,
},
/// Revoke an existing device authorization using the identity key.
Revoke {
#[arg(
long,
visible_alias = "device",
help = "Identity ID of the device authorization to revoke."
)]
device_did: String,
#[arg(
long,
help = "Local alias of the *identity's* key (required to authorize revocation)."
)]
key: String,
#[arg(long, help = "Optional note explaining the revocation.")]
note: Option<String>,
#[arg(long, help = "Preview actions without making changes.")]
dry_run: bool,
},
/// Resolve a device DID to its controller identity DID.
Resolve {
#[arg(
long,
visible_alias = "device",
help = "The device DID to resolve (e.g. did:key:z6Mk...)."
)]
device_did: String,
},
/// Link devices to your identity via QR code or short code.
Pair(super::pair::PairCommand),
/// Verify device authorization signatures (attestation).
#[command(name = "verify")]
VerifyAttestation(super::verify_attestation::VerifyCommand),
/// Extend the expiration date of an existing device authorization.
Extend {
#[arg(
long,
visible_alias = "device",
help = "Identity ID of the device authorization to extend."
)]
device_did: String,
/// Duration in seconds until expiration (per RFC 6749).
#[arg(
long = "expires-in",
value_name = "SECS",
help = "Number of seconds to extend the expiration by (from now)."
)]
expires_in: u64,
#[arg(
long,
help = "Local alias of the *identity's* key (required for re-signing)."
)]
key: String,
#[arg(
long,
help = "Local alias of the *device's* key (required for re-signing)."
)]
device_key: String,
},
}
#[allow(clippy::too_many_arguments)]
pub fn handle_device(
cmd: DeviceCommand,
repo_opt: Option<PathBuf>,
identity_ref_override: Option<String>,
identity_blob_name_override: Option<String>,
attestation_prefix_override: Option<String>,
attestation_blob_name_override: Option<String>,
passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
env_config: &EnvironmentConfig,
) -> Result<()> {
#[allow(clippy::disallowed_methods)]
let now = Utc::now();
let repo_path = layout::resolve_repo_path(repo_opt)?;
let mut config = StorageLayoutConfig::default();
if let Some(identity_ref) = identity_ref_override {
config.identity_ref = identity_ref.into();
}
if let Some(blob_name) = identity_blob_name_override {
config.identity_blob_name = blob_name.into();
}
if let Some(prefix) = attestation_prefix_override {
config.device_attestation_prefix = prefix.into();
}
if let Some(blob_name) = attestation_blob_name_override {
config.attestation_blob_name = blob_name.into();
}
match cmd.command {
DeviceSubcommand::List { include_revoked } => {
list_devices(now, &repo_path, &config, include_revoked)
}
DeviceSubcommand::Resolve { device_did } => resolve_device(&repo_path, &device_did),
DeviceSubcommand::Pair(pair_cmd) => super::pair::handle_pair(pair_cmd, env_config),
DeviceSubcommand::VerifyAttestation(verify_cmd) => {
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(super::verify_attestation::handle_verify(verify_cmd))
}
DeviceSubcommand::Link {
key,
device_key,
device_did,
payload: payload_path_opt,
schema: schema_path_opt,
expires_in,
note,
capabilities,
} => {
let payload = read_payload_file(payload_path_opt.as_deref())?;
validate_payload_schema(schema_path_opt.as_deref(), &payload)?;
let caps: Vec<auths_verifier::Capability> = capabilities
.unwrap_or_default()
.into_iter()
.filter_map(|s| auths_verifier::Capability::parse(&s).ok())
.collect();
let link_config = auths_sdk::types::DeviceLinkConfig {
identity_key_alias: KeyAlias::new_unchecked(key),
device_key_alias: Some(KeyAlias::new_unchecked(device_key)),
device_did: Some(device_did.clone()),
capabilities: caps,
expires_in,
note,
payload,
};
let passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync> =
Arc::new(UnifiedPassphraseProvider::new(passphrase_provider));
let ctx = build_auths_context(
&repo_path,
env_config,
Some(Arc::clone(&passphrase_provider)),
)?;
let result = auths_sdk::device::link_device(
link_config,
&ctx,
&auths_core::ports::clock::SystemClock,
)
.map_err(anyhow::Error::new)?;
display_link_result(&result, &device_did)
}
DeviceSubcommand::Revoke {
device_did,
key,
note,
dry_run,
} => {
if dry_run {
return display_dry_run_revoke(&device_did, &key);
}
let ctx = build_auths_context(
&repo_path,
env_config,
Some(Arc::clone(&passphrase_provider)),
)?;
let identity_key_alias = KeyAlias::new_unchecked(key);
auths_sdk::device::revoke_device(
&device_did,
&identity_key_alias,
&ctx,
note,
&auths_core::ports::clock::SystemClock,
)
.map_err(anyhow::Error::new)?;
display_revoke_result(&device_did, &repo_path)
}
DeviceSubcommand::Extend {
device_did,
expires_in,
key,
device_key,
} => handle_extend(
&repo_path,
&config,
&device_did,
expires_in,
&key,
&device_key,
passphrase_provider,
env_config,
),
}
}
fn display_link_result(
result: &auths_sdk::result::DeviceLinkResult,
device_did: &str,
) -> Result<()> {
println!(
"\n✅ Successfully linked device {} (attestation: {})",
device_did, result.attestation_id
);
Ok(())
}
fn display_dry_run_revoke(device_did: &str, identity_key_alias: &str) -> Result<()> {
if is_json_mode() {
JsonResponse::success(
"device revoke",
&serde_json::json!({
"dry_run": true,
"device_did": device_did,
"identity_key_alias": identity_key_alias,
"actions": [
"Revoke device authorization",
"Create signed revocation attestation",
"Store revocation in Git repository"
]
}),
)
.print()
.map_err(|e| anyhow!("{e}"))
} else {
let out = crate::ux::format::Output::new();
out.print_info("Dry run mode — no changes will be made");
out.newline();
out.println("Would perform the following actions:");
out.println(&format!(
" 1. Revoke device authorization for {}",
device_did
));
out.println(" 2. Create signed revocation attestation");
out.println(" 3. Store revocation in Git repository");
Ok(())
}
}
fn display_revoke_result(device_did: &str, repo_path: &Path) -> Result<()> {
let identity_storage = RegistryIdentityStorage::new(repo_path.to_path_buf());
let identity: ManagedIdentity = identity_storage
.load_identity()
.context("Failed to load identity")?;
println!(
"\n✅ Successfully revoked device {} for identity {}",
device_did, identity.controller_did
);
Ok(())
}
fn read_payload_file(path: Option<&Path>) -> Result<Option<Value>> {
match path {
Some(p) => {
let content = fs::read_to_string(p)
.with_context(|| format!("Failed to read payload file {:?}", p))?;
let value: Value = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse JSON from payload file {:?}", p))?;
Ok(Some(value))
}
None => Ok(None),
}
}
fn validate_payload_schema(schema_path: Option<&Path>, payload: &Option<Value>) -> Result<()> {
match (schema_path, payload) {
(Some(schema_path), Some(payload_val)) => {
let schema_content = fs::read_to_string(schema_path)
.with_context(|| format!("Failed to read schema file {:?}", schema_path))?;
let schema_json: serde_json::Value = serde_json::from_str(&schema_content)
.with_context(|| format!("Failed to parse JSON schema from {:?}", schema_path))?;
let validator = jsonschema::validator_for(&schema_json)
.map_err(|e| anyhow!("Invalid JSON schema in {:?}: {}", schema_path, e))?;
let errors: Vec<String> = validator
.iter_errors(payload_val)
.map(|e| format!(" - {}", e))
.collect();
if !errors.is_empty() {
return Err(anyhow!(
"Payload does not conform to schema:\n{}",
errors.join("\n")
));
}
Ok(())
}
(Some(_), None) => {
warn!("--schema specified but no --payload provided; skipping validation.");
Ok(())
}
_ => Ok(()),
}
}
#[allow(clippy::too_many_arguments)]
fn handle_extend(
repo_path: &Path,
_config: &StorageLayoutConfig,
device_did: &str,
expires_in: u64,
key: &str,
device_key: &str,
passphrase_provider: Arc<dyn PassphraseProvider + Send + Sync>,
env_config: &EnvironmentConfig,
) -> Result<()> {
let config = auths_sdk::types::DeviceExtensionConfig {
repo_path: repo_path.to_path_buf(),
#[allow(clippy::disallowed_methods)] // INVARIANT: device_did from CLI arg validated upstream
device_did: auths_verifier::types::DeviceDID::new_unchecked(device_did),
expires_in,
identity_key_alias: KeyAlias::new_unchecked(key),
device_key_alias: Some(KeyAlias::new_unchecked(device_key)),
};
let ctx = build_auths_context(repo_path, env_config, Some(passphrase_provider))?;
let result =
auths_sdk::device::extend_device(config, &ctx, &auths_core::ports::clock::SystemClock)
.with_context(|| {
format!("Failed to extend device authorization for '{}'", device_did)
})?;
println!(
"Successfully extended expiration for {} to {}",
result.device_did,
result.new_expires_at.date_naive()
);
Ok(())
}
fn resolve_device(repo_path: &Path, device_did_str: &str) -> Result<()> {
let attestation_storage = RegistryAttestationStorage::new(repo_path.to_path_buf());
#[allow(clippy::disallowed_methods)] // INVARIANT: device_did_str from attestation storage
let device_did = auths_verifier::types::DeviceDID::new_unchecked(device_did_str);
let attestations = attestation_storage
.load_attestations_for_device(&device_did)
.with_context(|| format!("Failed to load attestations for device {device_did_str}"))?;
let latest = attestations
.last()
.ok_or_else(|| anyhow!("No attestation found for device {device_did_str}"))?;
println!("{}", latest.issuer);
Ok(())
}
fn list_devices(
now: chrono::DateTime<Utc>,
repo_path: &Path,
_config: &StorageLayoutConfig,
include_revoked: bool,
) -> Result<()> {
let identity_storage = RegistryIdentityStorage::new(repo_path.to_path_buf());
let attestation_storage = RegistryAttestationStorage::new(repo_path.to_path_buf());
let backend = Arc::new(GitRegistryBackend::from_config_unchecked(
RegistryConfig::single_tenant(repo_path),
)) as Arc<dyn auths_id::ports::registry::RegistryBackend + Send + Sync>;
let resolver = auths_id::identity::resolve::RegistryDidResolver::new(backend);
let identity: ManagedIdentity = identity_storage
.load_identity()
.with_context(|| format!("Failed to load identity from {:?}", repo_path))?;
let attestations = attestation_storage
.load_all_attestations()
.context("Could not load device attestations")?;
let grouped = AttestationGroup::from_list(attestations);
let mut entries: Vec<DeviceEntry> = Vec::new();
for (device_did_str, att_entries) in grouped.by_device.iter() {
#[allow(clippy::expect_used)] // INVARIANT: BTreeMap groups are never empty by construction
let latest = att_entries
.last()
.expect("Grouped attestations should not be empty");
let verification_result =
auths_id::attestation::verify::verify_with_resolver(now, &resolver, latest, None);
let status_string = match verification_result {
Ok(()) => {
if latest.is_revoked() {
"revoked".to_string()
} else if let Some(expiry) = latest.expires_at {
if now > expiry {
"expired".to_string()
} else {
format!("active (expires {})", expiry.date_naive())
}
} else {
"active".to_string()
}
}
Err(err) => {
let err_msg = err.to_string().to_lowercase();
if err_msg.contains("revoked") {
format!(
"revoked{}",
latest
.timestamp
.map(|ts| format!(" ({})", ts.date_naive()))
.unwrap_or_default()
)
} else if err_msg.contains("expired") {
format!(
"expired{}",
latest
.expires_at
.map(|ts| format!(" ({})", ts.date_naive()))
.unwrap_or_default()
)
} else {
format!("invalid ({})", err)
}
}
};
let is_inactive = latest.is_revoked() || latest.expires_at.is_some_and(|e| now > e);
if !include_revoked && is_inactive {
continue;
}
entries.push(DeviceEntry {
id: device_did_str.clone(),
status: status_string,
public_key: hex::encode(latest.device_public_key.as_bytes()),
created_at: latest.timestamp.map(|ts| ts.to_rfc3339()),
expires_at: latest.expires_at.map(|ts| ts.to_rfc3339()),
note: latest.note.clone().filter(|n| !n.is_empty()),
});
}
if is_json_mode() {
return JsonResponse::success(
"device list",
&serde_json::json!({
"identity": identity.controller_did.to_string(),
"devices": entries,
}),
)
.print()
.map_err(|e| anyhow!("{e}"));
}
println!("Devices for identity: {}", identity.controller_did);
if entries.is_empty() {
if include_revoked {
println!(" No authorized devices found.");
} else {
println!(" (No active devices. Use --include-revoked to see all.)");
}
return Ok(());
}
for (i, entry) in entries.iter().enumerate() {
println!("{:>2}. {} {}", i + 1, entry.id, entry.status);
if let Some(note) = &entry.note {
println!(" Note: {}", note);
}
}
Ok(())
}