coreason-urn-authority 0.45.1

Epistemic Ledger & OCI Trust Anchor for CoReason URNs.
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
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
// Copyright (c) 2026 CoReason, Inc.
// All rights reserved.

use clap::{Parser, Subcommand};
use std::path::PathBuf;

mod crypto;
mod epistemic;
mod ledger;
mod routing;

#[derive(Parser)]
#[command(name = "urn-authority")]
#[command(about = "CoReason URN Authority — OCI Trust Anchor CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Resolve a URN to its verified OCI artifact URI
    Resolve {
        urn: String,
        #[arg(long)]
        ledger_path: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// List all URNs in the OCI Artifact Ledger
    List {
        #[arg(long)]
        ledger_path: Option<PathBuf>,
        #[arg(long)]
        json: bool,
    },
    /// Promote a URN from a testing network to the global ledger
    Promote {
        #[arg(long)]
        urn: String,
        #[arg(long)]
        oci_uri: String,
        #[arg(long)]
        did: String,
        #[arg(long, default_value = "urn:tenant:coreason:global:authority")]
        tenant_cid: String,
        #[arg(long)]
        mcp_namespace: Option<String>,
        #[arg(long)]
        dependency: Vec<String>,
        #[arg(long)]
        royalty_share: Vec<String>,
        #[arg(long)]
        payment_splitter_address: Option<String>,
        #[arg(long)]
        ledger_path: Option<PathBuf>,
        #[arg(long)]
        skip_git: bool,
    },
    /// Verify zero-trust code attestation against sidecar hash
    VerifyAttestation {
        code_file: PathBuf,
        #[arg(long)]
        expected_hash: Option<String>,
    },

    /// Scan payload for DLP violations
    ScanDlp {
        #[arg(long)]
        payload: Option<String>,
        #[arg(long)]
        payload_file: Option<PathBuf>,
    },
    /// Verify EZKL zk-SNARK proof for Proof-of-Valid-Inference
    VerifyProof {
        #[arg(long)]
        proof: PathBuf,
        #[arg(long)]
        vk: PathBuf,
        #[arg(long)]
        settings: PathBuf,
    },
    /// Calculate the Epistemic Merkle Root
    EpistemicRoot {
        #[arg(long)]
        project_path: PathBuf,
        #[arg(long)]
        manifest_version: Option<String>,
    },
    /// Register a URN capability in the NATS capability registry
    NatsRegister {
        #[arg(long)]
        urn: String,
        #[arg(long, default_value = "RESTRICTED")]
        clearance: String,
        #[arg(long, default_value = "DRAFT")]
        epistemic_status: String,
        #[arg(long)]
        capability_metadata: Option<String>,
        #[arg(long, default_value = "")]
        content_hash: String,
        #[arg(long, default_value = "nats://localhost:4222")]
        nats_url: String,
        #[arg(long, default_value = "coreason-registry")]
        bucket: String,
    },
    /// Look up a URN in the NATS capability registry
    NatsResolve {
        #[arg(long)]
        urn: String,
        #[arg(long, default_value = "nats://localhost:4222")]
        nats_url: String,
        #[arg(long, default_value = "coreason-registry")]
        bucket: String,
    },
    /// List all registered capabilities in the NATS capability registry
    NatsList {
        #[arg(long, default_value = "nats://localhost:4222")]
        nats_url: String,
        #[arg(long, default_value = "coreason-registry")]
        bucket: String,
        #[arg(long)]
        json: bool,
    },

    /// Output the PostgreSQL schema for thermodynamic cost tracking
    CostTrackerSchema,
    /// Verify a thermodynamic cost record and output the updated JSON cost records list
    CostTrackerVerify {
        #[arg(long)]
        budget: f64,
        #[arg(long)]
        records_json: String,
        #[arg(long)]
        new_record_json: String,
    },
    /// Check if a tenant tier and license is authorized to execute a capability
    LedgerCheckAccess {
        #[arg(long)]
        ledger_path: Option<PathBuf>,
        #[arg(long)]
        urn: String,
        #[arg(long)]
        tenant_tier: String,
        #[arg(long)]
        tenant_license: String,
    },
    /// Initialize workspace by detecting RAM/GPU, hashing KYC, and writing egress rules
    InitWorkspace {
        #[arg(long)]
        target_path: PathBuf,
        #[arg(long)]
        categories: String, // comma separated
        #[arg(long)]
        kyc: String, // JSON format
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Resolve {
            urn,
            ledger_path,
            json,
        } => match routing::resolve_capability(&urn, ledger_path) {
            Ok(receipt) => {
                if json {
                    println!("{}", serde_json::to_string(&receipt).unwrap());
                } else {
                    println!("--- Verified Capability Receipt ---");
                    println!("URN:    {}", receipt.urn);
                    println!("OCI:    {}", receipt.oci_uri);
                    println!("Signer: {}", receipt.authorized_signer_did);
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        },
        Commands::List { ledger_path, json } => match ledger::load_ledger(ledger_path) {
            Ok(entries) => {
                if json {
                    println!("{}", serde_json::to_string(&entries).unwrap());
                } else {
                    if entries.is_empty() {
                        println!("No capabilities registered in the ledger.");
                        return;
                    }
                    println!(
                        "--- OCI Artifact Ledger ({} capabilities) ---",
                        entries.len()
                    );
                    for entry in entries {
                        println!("  {}", entry.urn);
                        println!("    OCI:    {}", entry.oci_uri);
                        println!("    Signer: {}", entry.authorized_signer_did);
                        println!();
                    }
                }
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        },
        Commands::Promote {
            urn,
            oci_uri,
            did,
            tenant_cid,
            mcp_namespace,
            dependency,
            royalty_share,
            payment_splitter_address,
            ledger_path,
            skip_git,
        } => {
            if !urn.starts_with("urn:coreason:") {
                eprintln!("Error: URN must follow the 'urn:coreason:' schema.");
                std::process::exit(1);
            }
            if !did.starts_with("did:key:") {
                eprintln!("Error: Signer DID must follow the 'did:key:' format.");
                std::process::exit(1);
            }

            let mut royalty_shares = std::collections::HashMap::new();
            for share_str in royalty_share {
                if !share_str.contains('=') {
                    eprintln!("Error: Royalty share must be in format 'did:key:xyz=percentage'");
                    std::process::exit(1);
                }
                let parts: Vec<&str> = share_str.splitn(2, '=').collect();
                let signer_did = parts[0];
                if !signer_did.starts_with("did:key:") {
                    eprintln!("Error: Royalty share DID must follow the 'did:key:' format.");
                    std::process::exit(1);
                }
                let pct: u32 = match parts[1].parse() {
                    Ok(p) => p,
                    Err(_) => {
                        eprintln!(
                            "Error: Royalty share percentage must be an integer: {}",
                            parts[1]
                        );
                        std::process::exit(1);
                    }
                };
                royalty_shares.insert(signer_did.to_string(), pct);
            }

            if !royalty_shares.is_empty() {
                let sum: u32 = royalty_shares.values().sum();
                if sum != 100 {
                    eprintln!(
                        "Error: Royalty shares must sum to 100. Current sum: {}",
                        sum
                    );
                    std::process::exit(1);
                }
            }

            match ledger::promote_capability(
                &urn,
                &oci_uri,
                &did,
                &tenant_cid,
                mcp_namespace.as_deref(),
                dependency,
                royalty_shares,
                payment_splitter_address.as_deref(),
                ledger_path,
                skip_git,
            ) {
                Ok(_) => {}
                Err(e) => {
                    eprintln!("Error promoting capability: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::VerifyAttestation {
            code_file,
            expected_hash,
        } => match crypto::verify_code_attestation(&code_file, expected_hash.as_deref()) {
            Ok(_) => {
                println!("Attestation succeeded: Code fingerprint matches signature.");
            }
            Err(e) => {
                eprintln!("Error: {}", e);
                std::process::exit(1);
            }
        },

        Commands::ScanDlp {
            payload,
            payload_file,
        } => {
            let text = if let Some(p) = payload {
                p
            } else if let Some(pf) = payload_file {
                match std::fs::read_to_string(&pf) {
                    Ok(t) => t,
                    Err(e) => {
                        eprintln!("Error reading payload file: {}", e);
                        std::process::exit(1);
                    }
                }
            } else {
                eprintln!("Error: Either --payload or --payload-file must be provided.");
                std::process::exit(1);
            };

            let violations = coreason_urn_authority::scan_dlp_violations(&text);
            let is_clean = violations.is_empty();
            let result = serde_json::json!({
                "clean": is_clean,
                "violations": violations,
            });
            println!("{}", serde_json::to_string(&result).unwrap());
        }
        Commands::VerifyProof {
            proof,
            vk,
            settings,
        } => match crypto::verify_ezkl_proof(&proof, &vk, &settings) {
            Ok(verified) => {
                if verified {
                    println!("zk-SNARK Verification Succeeded: Proof of Valid Inference is mathematically valid.");
                } else {
                    eprintln!("zk-SNARK Verification Failed: Invalid Proof of Valid Inference.");
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Error verifying proof: {}", e);
                std::process::exit(1);
            }
        },
        Commands::EpistemicRoot {
            project_path,
            manifest_version,
        } => {
            match epistemic::calculate_epistemic_root(&project_path, manifest_version.as_deref()) {
                Ok(root_hash) => {
                    println!("{}", root_hash);
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::NatsRegister {
            urn,
            clearance,
            epistemic_status,
            capability_metadata,
            content_hash,
            nats_url,
            bucket,
        } => {
            let metadata = match capability_metadata {
                Some(s) => serde_json::from_str(&s).unwrap_or(serde_json::Value::Null),
                None => serde_json::Value::Object(serde_json::Map::new()),
            };
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            match rt.block_on(coreason_urn_authority::nats_registry::register_capability(
                &nats_url,
                &bucket,
                &urn,
                &clearance,
                &epistemic_status,
                metadata,
                &content_hash,
            )) {
                Ok(_) => {
                    println!("Successfully registered capability: {}", urn);
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::NatsResolve {
            urn,
            nats_url,
            bucket,
        } => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            match rt.block_on(coreason_urn_authority::nats_registry::resolve_urn(
                &nats_url, &bucket, &urn,
            )) {
                Ok(entry) => {
                    println!("{}", serde_json::to_string(&entry).unwrap());
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::NatsList {
            nats_url,
            bucket,
            json,
        } => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            match rt.block_on(
                coreason_urn_authority::nats_registry::list_all_capabilities(&nats_url, &bucket),
            ) {
                Ok(caps) => {
                    if json {
                        println!("{}", serde_json::to_string(&caps).unwrap());
                    } else {
                        println!("Registered capabilities in NATS KV ({} total):", caps.len());
                        for (urn, entry) in caps {
                            println!("  {} (clearance={})", urn, entry.clearance);
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    std::process::exit(1);
                }
            }
        }

        Commands::CostTrackerSchema => {
            println!(
                "{}",
                coreason_urn_authority::cost_tracker::get_postgres_schema()
            );
        }
        Commands::CostTrackerVerify {
            budget,
            records_json,
            new_record_json,
        } => {
            let records: Vec<coreason_urn_authority::cost_tracker::ThermodynamicCostRecord> =
                match serde_json::from_str(&records_json) {
                    Ok(r) => r,
                    Err(e) => {
                        eprintln!("Invalid records JSON: {}", e);
                        std::process::exit(1);
                    }
                };
            let new_record: coreason_urn_authority::cost_tracker::ThermodynamicCostRecord =
                match serde_json::from_str(&new_record_json) {
                    Ok(r) => r,
                    Err(e) => {
                        eprintln!("Invalid new record JSON: {}", e);
                        std::process::exit(1);
                    }
                };
            match coreason_urn_authority::cost_tracker::verify_cost_and_update(
                budget, records, new_record,
            ) {
                Ok(updated) => {
                    println!("{}", serde_json::to_string(&updated).unwrap());
                }
                Err(e) => {
                    eprintln!("{}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::LedgerCheckAccess {
            ledger_path,
            urn,
            tenant_tier,
            tenant_license,
        } => {
            let entries = match coreason_urn_authority::ledger::load_ledger(ledger_path) {
                Ok(e) => e,
                Err(e) => {
                    eprintln!("Failed to load ledger: {}", e);
                    std::process::exit(1);
                }
            };
            if coreason_urn_authority::ledger::check_ledger_access(
                &entries,
                &urn,
                &tenant_tier,
                &tenant_license,
            ) {
                println!("true");
            } else {
                println!("false");
                std::process::exit(1);
            }
        }
        Commands::InitWorkspace {
            target_path,
            categories,
            kyc,
        } => {
            let categories_vec: Vec<String> = categories
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            let ram_gb = coreason_urn_authority::init::get_ram_gb();
            let has_gpu = coreason_urn_authority::init::detect_gpu();
            let (canonical_kyc, tenant_cid) =
                match coreason_urn_authority::init::calculate_tenant_cid(&kyc) {
                    Ok(res) => res,
                    Err(e) => {
                        eprintln!("Invalid KYC format: {}", e);
                        std::process::exit(1);
                    }
                };
            match coreason_urn_authority::init::generate_egress_rules(&target_path, &categories_vec)
            {
                Ok(_) => {
                    let out = serde_json::json!({
                        "ram_gb": ram_gb,
                        "has_gpu": has_gpu,
                        "canonical_kyc": canonical_kyc,
                        "tenant_cid": tenant_cid,
                    });
                    println!("{}", serde_json::to_string(&out).unwrap());
                }
                Err(e) => {
                    eprintln!("Failed to generate egress rules: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }
}