fatoora-cli 0.6.0

Command-line interface for the fatoora ZATCA SDK
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! Command-line interface for the `fatoora-core` ZATCA SDK.
//!
//! # Examples
//! ```bash
//! fatoora csr --csr-config csr.properties --generated-csr csr.pem --private-key key.pem
//! ```
use anyhow::{Context, Result, bail};
use base64ct::{Base64, Encoding};
use clap::{Parser, Subcommand, ValueEnum};
use fatoora_core::{
    config::Environment,
    csr::CsrProperties,
    invoice::{
        FinalizedInvoice, InvoiceHash, SignedInvoice, hash_xml,
        validation::{
            Severity, ValidationFinding, ValidationLocation, Validator, ZatcaStage,
            ZatcaStageStatus, ZatcaValidationOptions, ZatcaValidationReport,
        },
        xml::parse::{parse_finalized_invoice_xml, parse_signed_invoice_xml},
    },
};
use serde_json::json;
use std::io::Read;
use std::process::ExitCode;

#[derive(Parser)]
#[command(name = "fatoora", version)]
#[command(about = "Rust-based ZATCA E-Invoice CLI")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Csr {
        #[arg(long, help = "Path to CSR properties file")]
        csr_config: String,
        #[arg(long, help = "Write generated private key to this path")]
        private_key: Option<String>,
        #[arg(long, help = "Write generated CSR to this path")]
        generated_csr: Option<String>,
        #[arg(long, help = "Output PEM instead of base64 DER")]
        pem: bool,
    },
    Sign {
        #[arg(long, help = "Path to input invoice XML")]
        invoice: String,
        #[arg(long, help = "Path to signing certificate")]
        cert: String,
        #[arg(long, help = "Path to signing key")]
        key: String,
        #[arg(long, value_enum, default_value_t = KeyFormat::Pem, help = "Certificate format")]
        cert_format: KeyFormat,
        #[arg(long, value_enum, default_value_t = KeyFormat::Pem, help = "Key format")]
        key_format: KeyFormat,
        #[arg(long, help = "Write signed invoice XML to this path")]
        signed_invoice: Option<String>,
    },
    Validate {
        #[arg(long, help = "Path to invoice XML")]
        invoice: String,
        #[arg(long, value_enum, default_value_t = ValidationProfile::Xsd, help = "Validation profile")]
        profile: ValidationProfile,
        #[arg(long, value_enum, default_value_t = ValidationFormat::Text, help = "Output format")]
        format: ValidationFormat,
        #[arg(long, help = "Expected predecessor invoice hash (ZATCA profile)")]
        previous_invoice_hash: Option<String>,
        #[arg(
            long,
            help = "Evaluation instant and timezone in RFC3339 format (ZATCA profile)"
        )]
        evaluated_at: Option<String>,
    },
    Qr {
        #[arg(long, help = "Path to invoice XML (finalized or signed)")]
        invoice: String,
        #[arg(
            long,
            help = "Fail if invoice is already signed (contains existing QR/signature fields)"
        )]
        fail_on_signed: bool,
    },
    QrRead {
        #[arg(long, help = "Path to signed invoice XML")]
        invoice: String,
    },
    GenerateHash {
        #[arg(long, help = "Path to invoice XML")]
        invoice: String,
    },
    InvoiceRequest {
        #[arg(long, help = "Path to signed invoice XML")]
        invoice: String,
        #[arg(long, help = "Write JSON request payload to this path")]
        api_request: Option<String>,
    },
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum KeyFormat {
    Pem,
    Der,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum ValidationProfile {
    Xsd,
    Zatca,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum ValidationFormat {
    Text,
    Json,
}

fn main() -> Result<ExitCode> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Csr {
            csr_config,
            private_key,
            generated_csr,
            pem,
        } => {
            let csr_contents = std::fs::read_to_string(&csr_config)
                .with_context(|| format!("failed to read CSR config from {csr_config}"))?;
            let csr_config = csr_contents
                .parse::<CsrProperties>()
                .context("failed to parse CSR config")?;
            let signer = fatoora_core::csr::SigningKey::generate();
            let csr = csr_config
                .build(&signer, Environment::NonProduction)
                .context("failed to generate CSR")?;

            let csr_output = if pem {
                csr.to_pem().context("failed to encode CSR as PEM")?
            } else {
                csr.to_base64().context("failed to encode CSR as base64")?
            };

            let key_output = if pem {
                signer
                    .to_pem()
                    .context("failed to encode private key as PEM")?
            } else {
                let der = signer
                    .to_der()
                    .context("failed to encode private key as DER")?;
                Base64::encode_string(&der)
            };

            if let Some(path) = generated_csr {
                std::fs::write(&path, csr_output.as_bytes())
                    .with_context(|| format!("failed to write CSR to {path}"))?;
            } else {
                println!("{csr_output}");
            }

            if let Some(path) = private_key {
                std::fs::write(&path, key_output.as_bytes())
                    .with_context(|| format!("failed to write private key to {path}"))?;
            } else {
                println!("{key_output}");
            }
        }
        Commands::Sign {
            invoice,
            cert,
            key,
            cert_format,
            key_format,
            signed_invoice,
        } => {
            let xml = std::fs::read_to_string(&invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;

            let signer = match (cert_format, key_format) {
                (KeyFormat::Pem, KeyFormat::Pem) => {
                    let cert_pem = std::fs::read_to_string(&cert)
                        .with_context(|| format!("failed to read cert file {cert}"))?;
                    let key_pem = std::fs::read_to_string(&key)
                        .with_context(|| format!("failed to read key file {key}"))?;
                    fatoora_core::invoice::sign::InvoiceSigner::from_pem(
                        cert_pem.trim(),
                        key_pem.trim(),
                    )?
                }
                (KeyFormat::Der, KeyFormat::Der) => {
                    let cert_der = std::fs::read(&cert)
                        .with_context(|| format!("failed to read cert file {cert}"))?;
                    let key_der = std::fs::read(&key)
                        .with_context(|| format!("failed to read key file {key}"))?;
                    fatoora_core::invoice::sign::InvoiceSigner::from_der(&cert_der, &key_der)?
                }
                _ => {
                    bail!("mixed PEM/DER formats are not supported; use matching formats");
                }
            };

            let signed_xml = signer.sign_xml(&xml)?;
            if let Some(path) = signed_invoice {
                std::fs::write(&path, signed_xml.as_bytes())
                    .with_context(|| format!("failed to write signed invoice to {path}"))?;
            } else {
                println!("{signed_xml}");
            }
        }
        Commands::Validate {
            invoice,
            profile,
            format,
            previous_invoice_hash,
            evaluated_at,
        } => {
            return validate_command(
                &invoice,
                profile,
                format,
                previous_invoice_hash,
                evaluated_at,
            );
        }
        Commands::Qr {
            invoice,
            fail_on_signed,
        } => {
            let xml = std::fs::read_to_string(&invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;
            let qr = match parse_signed_invoice_xml(&xml) {
                Ok(signed) => {
                    if fail_on_signed {
                        bail!(
                            "invoice {invoice} is signed; refuse to regenerate QR when --fail-on-signed is set"
                        );
                    }
                    generate_signed_invoice_qr(&signed)?
                }
                Err(signed_parse_error) => {
                    let finalized = parse_finalized_invoice_xml(&xml).with_context(|| {
                        format!(
                            "failed to parse invoice XML from {invoice}; signed parse error: {signed_parse_error}"
                        )
                    })?;
                    // A failed signed import must never fall back to regeneration.
                    let document = roxmltree::Document::parse(&xml).context("invalid XML")?;
                    let cac =
                        "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
                    let cbc =
                        "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
                    let has_qr = document.root_element().children().any(|n| {
                        n.has_tag_name((cac, "AdditionalDocumentReference"))
                            && n.children()
                                .any(|id| id.has_tag_name((cbc, "ID")) && id.text() == Some("QR"))
                            && n.descendants().any(|value| {
                                value.has_tag_name((cbc, "EmbeddedDocumentBinaryObject"))
                                    && value.text().is_some_and(|text| !text.trim().is_empty())
                            })
                    });
                    if has_qr
                        || document.descendants().any(|n| {
                            n.has_tag_name(("http://www.w3.org/2000/09/xmldsig#", "Signature"))
                        })
                    {
                        return Err(signed_parse_error).context("signed invoice integrity failed");
                    }
                    generate_finalized_invoice_qr(&finalized, &xml)?
                }
            };
            println!("{qr}");
        }
        Commands::QrRead { invoice } => {
            let xml = std::fs::read_to_string(&invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;
            let signed = parse_signed_invoice_xml(&xml)
                .with_context(|| format!("failed to parse signed invoice from {invoice}"))?;
            println!("{}", signed.qr_code());
        }
        Commands::GenerateHash { invoice } => {
            let xml = std::fs::read_to_string(&invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;
            let hash = hash_xml(&xml)
                .with_context(|| format!("failed to hash invoice XML from {invoice}"))?;
            println!("{hash}");
        }
        Commands::InvoiceRequest {
            invoice,
            api_request,
        } => {
            let xml = std::fs::read_to_string(&invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;
            let signed = parse_signed_invoice_xml(&xml)
                .with_context(|| format!("failed to parse signed invoice from {invoice}"))?;
            let payload = json!({
                "invoiceHash": signed.invoice_hash(),
                "uuid": signed.uuid(),
                "invoice": signed.to_xml_base64(),
            });
            let output = serde_json::to_string_pretty(&payload)
                .context("failed to serialize invoice request")?;

            if let Some(path) = api_request {
                std::fs::write(&path, output.as_bytes())
                    .with_context(|| format!("failed to write request to {path}"))?;
            } else {
                println!("{output}");
            }
        }
    }

    Ok(ExitCode::SUCCESS)
}

fn validate_command(
    invoice: &str,
    profile: ValidationProfile,
    format: ValidationFormat,
    previous_invoice_hash: Option<String>,
    evaluated_at: Option<String>,
) -> Result<ExitCode> {
    let validator = Validator::new();
    if profile == ValidationProfile::Xsd {
        if previous_invoice_hash.is_some() || evaluated_at.is_some() {
            return Ok(validation_input_failure(
                format,
                "invalid_options",
                "--previous-invoice-hash and --evaluated-at require --profile zatca",
            ));
        }
        if format == ValidationFormat::Text {
            // Keep the existing default command's output and failure behavior.
            let xml = std::fs::read_to_string(invoice)
                .with_context(|| format!("failed to read invoice file {invoice}"))?;
            validator
                .validate_xml(&xml)
                .map_err(|error| anyhow::anyhow!("XML validation failed: {error}"))?;
            println!("OK");
            return Ok(ExitCode::SUCCESS);
        }
        let xml = match std::fs::read_to_string(invoice) {
            Ok(xml) => xml,
            Err(error) => {
                return Ok(validation_input_failure(
                    format,
                    "io",
                    &format!("failed to read invoice file {invoice}: {error}"),
                ));
            }
        };
        return Ok(match validator.validate_xml_report(&xml) {
            Ok(report) => {
                let code = if report.has_errors() { 2 } else { 0 };
                println!("{}", json!(report));
                ExitCode::from(code)
            }
            Err(error) => {
                println!("{}", fatoora_core::Error::from(error).details_json());
                ExitCode::from(3)
            }
        });
    }

    let previous_invoice_hash = match previous_invoice_hash.map(InvoiceHash::parse).transpose() {
        Ok(hash) => hash,
        Err(error) => {
            return Ok(validation_input_failure(
                format,
                "invalid_options",
                &format!("invalid validation context: previous_invoice_hash: {error}"),
            ));
        }
    };
    let mut options: ZatcaValidationOptions = match serde_json::from_value(json!({
        "evaluated_at": evaluated_at,
    })) {
        Ok(options) => options,
        Err(error) => {
            return Ok(validation_input_failure(
                format,
                "invalid_options",
                &format!("invalid validation context: {error}"),
            ));
        }
    };
    options.previous_invoice_hash = previous_invoice_hash;
    let xml = match read_zatca_xml(invoice) {
        Ok(xml) => xml,
        Err(error) => {
            return Ok(validation_input_failure(
                format,
                "io",
                &format!("failed to read invoice file {invoice}: {error}"),
            ));
        }
    };
    Ok(match validator.validate_zatca(&xml, &options) {
        Ok(report) => {
            // A rejected stage can leave later stages unrun. Preserve rejection
            // as the primary outcome instead of reporting mere incompleteness.
            let (code, outcome) = if report.has_errors() {
                (2, "rejected")
            } else if !report.is_complete() {
                (4, "incomplete")
            } else {
                (0, "valid")
            };
            match format {
                ValidationFormat::Json => println!("{}", json!(report)),
                ValidationFormat::Text => {
                    println!("Validation: {outcome}");
                    print_zatca_report(&report);
                }
            }
            ExitCode::from(code)
        }
        Err(error) => {
            match format {
                ValidationFormat::Json => println!("{}", json!(error)),
                ValidationFormat::Text => {
                    println!("Validation: execution_failed");
                    print_zatca_report(&error.report);
                    eprintln!("{}", error.message);
                    if let Some(site) = &error.assertion_site {
                        eprintln!("Assertion: {site}");
                    }
                    if let Some(location) = &error.location {
                        eprintln!("Location: {}", validation_location(location));
                    }
                }
            }
            ExitCode::from(3)
        }
    })
}

fn read_zatca_xml(path: &str) -> std::io::Result<String> {
    const XML_INPUT_LIMIT: usize = 8 * 1024 * 1024;
    let mut bytes = Vec::new();
    std::fs::File::open(path)?
        .take((XML_INPUT_LIMIT + 1) as u64)
        .read_to_end(&mut bytes)?;
    match String::from_utf8(bytes) {
        Ok(xml) => Ok(xml),
        // The final byte can split a UTF-8 character. Preserve an over-limit
        // length so the core returns its capacity error and partial report.
        Err(error) if error.as_bytes().len() > XML_INPUT_LIMIT => {
            Ok(String::from_utf8_lossy(error.as_bytes()).into_owned())
        }
        Err(error) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, error)),
    }
}

fn validation_input_failure(format: ValidationFormat, kind: &str, message: &str) -> ExitCode {
    match format {
        ValidationFormat::Json => println!(
            "{}",
            json!({
                "type": "cli_validation_execution", "kind": kind, "message": message,
            })
        ),
        ValidationFormat::Text => eprintln!("{message}"),
    }
    ExitCode::from(3)
}

fn print_zatca_report(report: &ZatcaValidationReport) {
    println!("Profile: {}", report.profile);
    println!("Evaluated at: {}", report.evaluated_at.to_rfc3339());
    for stage in &report.stages {
        println!(
            "{}: {}",
            validation_stage(stage.stage),
            validation_stage_status(stage.status)
        );
        for finding in &stage.findings {
            print_validation_finding(&finding.finding);
        }
    }
}

fn validation_stage(stage: ZatcaStage) -> &'static str {
    match stage {
        ZatcaStage::Xsd => "xsd",
        ZatcaStage::Cen => "cen",
        ZatcaStage::Ksa => "ksa",
        ZatcaStage::Signature => "signature",
        ZatcaStage::Qr => "qr",
        ZatcaStage::PreviousInvoiceHash => "previous_invoice_hash",
        _ => "unknown",
    }
}

fn validation_stage_status(status: ZatcaStageStatus) -> &'static str {
    match status {
        ZatcaStageStatus::NotRun => "not_run",
        ZatcaStageStatus::Completed => "completed",
        ZatcaStageStatus::NotApplicable => "not_applicable",
        ZatcaStageStatus::ContextRequired => "context_required",
        ZatcaStageStatus::EvaluationFailed => "evaluation_failed",
        _ => "unknown",
    }
}

fn print_validation_finding(finding: &ValidationFinding) {
    let severity = match finding.severity {
        Severity::Warning => "warning",
        Severity::Error => "error",
    };
    let location = finding
        .location
        .as_ref()
        .map(|location| format!(" at {}", validation_location(location)))
        .unwrap_or_default();
    println!(
        "  {severity} {}{location}: {}",
        finding.code, finding.message
    );
}

fn validation_location(location: &ValidationLocation) -> String {
    match location {
        ValidationLocation::Field(field) => field.clone(),
        ValidationLocation::XPath(xpath) => xpath.clone(),
        ValidationLocation::Xml { line, column } => match column {
            Some(column) => format!("line {line}, column {column}"),
            None => format!("line {line}"),
        },
        _ => format!("{location:?}"),
    }
}

fn generate_finalized_invoice_qr(invoice: &FinalizedInvoice, xml: &str) -> Result<String> {
    build_qr_payload(invoice.data(), xml)
}

fn generate_signed_invoice_qr(invoice: &SignedInvoice) -> Result<String> {
    Ok(invoice.qr_code().to_owned())
}

fn build_qr_payload(data: &fatoora_core::invoice::InvoiceData, xml: &str) -> Result<String> {
    let seller_name = data.seller().name();
    if seller_name.is_empty() {
        bail!("seller legal name is missing");
    }
    let seller_vat = data
        .seller()
        .vat_id()
        .map(|vat| vat.as_str().trim())
        .filter(|vat| !vat.is_empty())
        .ok_or_else(|| anyhow::anyhow!("seller VAT ID is missing"))?;

    let doc = roxmltree::Document::parse(xml).context("invalid XML")?;
    let root = doc.root_element();
    let cbc = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
    let cac = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
    let money = root
        .children()
        .find(|n| n.has_tag_name((cac, "LegalMonetaryTotal")))
        .context("missing monetary total")?;
    let value = |node: roxmltree::Node<'_, '_>, local| -> Result<String> {
        let field = node
            .children()
            .find(|n| n.has_tag_name((cbc, local)))
            .context("missing QR field")?;
        let text: String = field
            .descendants()
            .filter_map(|n| n.is_text().then(|| n.text()).flatten())
            .collect();
        Ok(text.trim_matches([' ', '\t', '\r', '\n']).to_owned())
    };
    let timestamp = format!(
        "{}T{}",
        value(root, "IssueDate")?,
        value(root, "IssueTime")?
    );
    let total_with_vat = value(money, "PayableAmount")?;
    let currency = value(root, "DocumentCurrencyCode")?;
    let tax = root
        .children()
        .find(|n| {
            n.has_tag_name((cac, "TaxTotal"))
                && n.children().any(|a| {
                    a.has_tag_name((cbc, "TaxAmount"))
                        && a.attribute("currencyID") == Some(currency.as_str())
                })
        })
        .context("missing invoice-currency tax total")?;
    let total_vat = value(tax, "TaxAmount")?;

    let mut tlv = Vec::new();
    push_tlv_field(&mut tlv, 1, seller_name.as_bytes())?;
    push_tlv_field(&mut tlv, 2, seller_vat.as_bytes())?;
    push_tlv_field(&mut tlv, 3, timestamp.as_bytes())?;
    push_tlv_field(&mut tlv, 4, total_with_vat.as_bytes())?;
    push_tlv_field(&mut tlv, 5, total_vat.as_bytes())?;

    let encoded = Base64::encode_string(&tlv);
    if encoded.len() > 700 {
        bail!(
            "QR code payload exceeds 700 characters once base64 encoded (len={})",
            encoded.len()
        );
    }
    Ok(encoded)
}

fn push_tlv_field(buffer: &mut Vec<u8>, tag: u8, value: &[u8]) -> Result<()> {
    if value.len() > u8::MAX as usize {
        bail!("TLV field {tag} exceeds 255 bytes (len={})", value.len());
    }
    buffer.push(tag);
    buffer.push(value.len() as u8);
    buffer.extend_from_slice(value);
    Ok(())
}