Skip to main content

canic_cli/frontend/
mod.rs

1//! Public CLI adapter for frontend bundle export and integrity verification.
2//!
3//! The host owns source validation, generation and durable publication.
4
5use crate::cli::{
6    clap::{flag_arg, parse_matches, required_string, string_option, value_arg},
7    defaults::local_environment,
8    globals::{internal_environment_arg, internal_icp_arg},
9    help::print_nested_help,
10};
11use crate::support::icp_target::IcpTargetOptions;
12use canic_host::{
13    frontend::{
14        FrontendError,
15        model::{FrontendAssetCapacityInput, FrontendUploadedInput},
16        ops, workflow,
17    },
18    icp_config::resolve_current_canic_icp_root,
19};
20use clap::Command;
21use std::{ffi::OsString, path::Path};
22use thiserror::Error;
23
24/// CLI boundary errors retain the host's exact typed diagnostic.
25#[derive(Debug, Error)]
26pub enum FrontendCommandError {
27    #[error(transparent)]
28    Clap(#[from] clap::Error),
29
30    #[error(transparent)]
31    Host(#[from] FrontendError),
32
33    #[error(transparent)]
34    Json(#[from] serde_json::Error),
35
36    #[error(transparent)]
37    Root(#[from] canic_host::icp_config::IcpConfigError),
38}
39
40fn command() -> Command {
41    Command::new("frontend").bin_name("canic frontend")
42        .about("Export and verify exact browser bindings from a terminal Fleet")
43        .arg(internal_environment_arg().global(true))
44        .arg(internal_icp_arg().global(true))
45        .arg(flag_arg("json").long("json").global(true).help("Print structured JSON"))
46        .subcommand_required(true)
47        .subcommand(Command::new("capacity").about("Check external asset native cycles against an explicit upload floor")
48            .arg(value_arg("canister").required(true).value_parser(clap::value_parser!(ic_platform::principal::ExternalPrincipal)))
49            .arg(value_arg("payload").long("payload").required(true))
50            .arg(value_arg("minimum-native-cycles").long("minimum-native-cycles").required(true).value_parser(clap::value_parser!(u128)))
51            .arg(value_arg("maximum-payload-bytes").long("maximum-payload-bytes").required(true).value_parser(clap::value_parser!(u64).range(1..)))
52            .arg(value_arg("maximum-files").long("maximum-files").required(true).value_parser(clap::value_parser!(u32).range(1..))))
53        .subcommand(Command::new("export").about("Write a reviewed environment and binding bundle")
54            .arg(value_arg("fleet").required(true))
55            .arg(value_arg("input").long("input").required(true).help("Selected-environment frontend JSON"))
56            .arg(value_arg("out").long("out").required(true).help("New or identical bundle directory"))
57            .arg(value_arg("node").long("node").required(true).help("Prepared pinned Node executable"))
58            .arg(value_arg("typescript").long("typescript").required(true).help("Prepared pinned TypeScript package directory")))
59        .subcommand(Command::new("verify").about("Verify files against an independently retained digest")
60            .arg(value_arg("directory").required(true))
61            .arg(value_arg("sha256").long("sha256").required(true)))
62        .subcommand(Command::new("verify-uploaded").about("Read back uploaded handoff files from an asset canister")
63            .arg(value_arg("directory").required(true))
64            .arg(value_arg("sha256").long("sha256").required(true))
65            .arg(value_arg("canister").long("canister").required(true).value_parser(clap::value_parser!(ic_platform::principal::ExternalPrincipal)))
66            .arg(value_arg("prefix").long("prefix").required(true).help("Exact remote handoff directory, such as /canic"))
67            .after_help("Example:\n  canic --environment ic frontend verify-uploaded browser/canic --sha256 <digest> --canister <principal> --prefix /canic"))
68        .after_help("Examples:\n  canic frontend export demo --input frontend-local.json --out browser/canic --node <node> --typescript <typescript>\n  canic frontend verify browser/canic --sha256 <digest>\n  canic --environment ic frontend export demo --input frontend-ic.json --out browser/canic --node <node> --typescript <typescript> --json")
69}
70
71/// Parse the selected environment and delegate to the host handoff owner.
72pub fn run(args: impl IntoIterator<Item = OsString>) -> Result<(), FrontendCommandError> {
73    let args = args.into_iter().collect::<Vec<_>>();
74    if print_nested_help(&args, command()) {
75        return Ok(());
76    }
77    let matches = parse_matches(command(), args)?;
78    let (action, leaf) = matches.subcommand().expect("required frontend subcommand");
79    if action == "capacity" {
80        return capacity(&matches, leaf);
81    }
82    if action == "verify-uploaded" {
83        return verify_uploaded(&matches, leaf);
84    }
85    let manifest = match action {
86        "export" => {
87            let input = ops::read_input(Path::new(&required_string(leaf, "input")))?;
88            let environment =
89                string_option(&matches, "environment").unwrap_or_else(local_environment);
90            if input.environment != environment {
91                return Err(FrontendError::Environment.into());
92            }
93            workflow::prepare_handoff(
94                &resolve_current_canic_icp_root()?,
95                &required_string(leaf, "fleet"),
96                &input,
97                Path::new(&required_string(leaf, "out")),
98                &ops::compiler::BrowserCompiler {
99                    node: required_string(leaf, "node").into(),
100                    typescript: required_string(leaf, "typescript").into(),
101                },
102            )?
103        }
104        "verify" => ops::verify_bundle(
105            Path::new(&required_string(leaf, "directory")),
106            &required_string(leaf, "sha256"),
107        )?,
108        _ => unreachable!("Clap selects the maintained subcommands"),
109    };
110    if matches.get_flag("json") {
111        println!("{}", serde_json::to_string_pretty(&manifest)?);
112    } else {
113        println!(
114            "Frontend bundle: {} / {}",
115            manifest.environment, manifest.fleet
116        );
117        println!("sha256: {}", manifest.manifest_sha256);
118        println!("role instances: {}", manifest.roles.len());
119    }
120    Ok(())
121}
122
123fn verify_uploaded(
124    matches: &clap::ArgMatches,
125    leaf: &clap::ArgMatches,
126) -> Result<(), FrontendCommandError> {
127    let target = IcpTargetOptions::parse(matches);
128    let root = resolve_current_canic_icp_root()?;
129    let input = FrontendUploadedInput {
130        directory: required_string(leaf, "directory").into(),
131        manifest_sha256: required_string(leaf, "sha256"),
132        environment: target.environment.clone(),
133        network: canic_host::network::resolve_canonical_network_id_from_root(
134            &root,
135            &target.environment,
136        )
137        .map_err(FrontendError::from)?,
138        canister_id: *leaf
139            .get_one::<ic_platform::principal::ExternalPrincipal>("canister")
140            .expect("required Principal"),
141        prefix: required_string(leaf, "prefix"),
142    };
143    let selected_environment = sync_variable("ICP_CLI_ENVIRONMENT")?;
144    let selected_canister = sync_variable("ICP_CLI_CID")?;
145    validate_sync_context(
146        &input.environment,
147        input.canister_id,
148        selected_environment.as_deref(),
149        selected_canister.as_deref(),
150    )?;
151    ops::prepare_uploaded(&input)?;
152    let mut reader = ops::IcpFrontendAssetReader::new(&target.icp_cli(&root), &input)?;
153    let report = workflow::verify_uploaded(&input, &mut reader)?;
154    if matches.get_flag("json") {
155        println!("{}", serde_json::to_string_pretty(&report)?);
156    } else {
157        println!(
158            "Verified {} handoff files on {} ({})",
159            report.files.len(),
160            report.canister_id,
161            report.environment
162        );
163        println!("sha256: {}", report.manifest_sha256);
164    }
165    Ok(())
166}
167
168fn sync_variable(name: &str) -> Result<Option<String>, FrontendError> {
169    match std::env::var(name) {
170        Ok(value) => Ok(Some(value)),
171        Err(std::env::VarError::NotPresent) => Ok(None),
172        Err(std::env::VarError::NotUnicode(_)) => Err(FrontendError::Environment),
173    }
174}
175
176fn validate_sync_context(
177    environment: &str,
178    canister: ic_platform::principal::ExternalPrincipal,
179    selected_environment: Option<&str>,
180    selected_canister: Option<&str>,
181) -> Result<(), FrontendError> {
182    if selected_environment.is_some_and(|selected| selected != environment) {
183        return Err(FrontendError::Environment);
184    }
185    if let Some(selected) = selected_canister {
186        let selected = ic_platform::principal::ExternalPrincipal::from_text(selected)
187            .map_err(|_| FrontendError::Principal)?;
188        if selected != canister {
189            return Err(FrontendError::Principal);
190        }
191    }
192    Ok(())
193}
194
195fn capacity(
196    matches: &clap::ArgMatches,
197    leaf: &clap::ArgMatches,
198) -> Result<(), FrontendCommandError> {
199    let target = IcpTargetOptions::parse(matches);
200    let report = ops::asset_capacity(
201        &target.icp_cli(&resolve_current_canic_icp_root()?),
202        &FrontendAssetCapacityInput {
203            environment: target.environment,
204            canister_id: *leaf
205                .get_one::<ic_platform::principal::ExternalPrincipal>("canister")
206                .expect("required Principal"),
207            payload_directory: required_string(leaf, "payload").into(),
208            minimum_native_cycles: *leaf
209                .get_one::<u128>("minimum-native-cycles")
210                .expect("required native floor"),
211            maximum_payload_bytes: *leaf
212                .get_one::<u64>("maximum-payload-bytes")
213                .expect("required byte bound"),
214            maximum_files: *leaf
215                .get_one::<u32>("maximum-files")
216                .expect("required file bound"),
217        },
218    )?;
219    if matches.get_flag("json") {
220        println!("{}", serde_json::to_string_pretty(&report)?);
221    } else {
222        println!(
223            "Asset {}: {} native cycles; required {}",
224            report.canister_id, report.native_cycles, report.minimum_native_cycles
225        );
226        println!(
227            "Payload: {} files, {} bytes, sha256 {}",
228            report.payload.files, report.payload.bytes, report.payload.sha256
229        );
230    }
231    if !report.sufficient {
232        return Err(FrontendError::NativeCapacity {
233            available: report
234                .native_cycles
235                .parse()
236                .map_err(|_| FrontendError::NativeBalance)?,
237            required: report
238                .minimum_native_cycles
239                .parse()
240                .map_err(|_| FrontendError::NativeBalance)?,
241        }
242        .into());
243    }
244    Ok(())
245}
246// -----------------------------------------------------------------------------
247// Tests
248// -----------------------------------------------------------------------------
249#[cfg(test)]
250mod tests {
251    use super::*;
252    #[test]
253    fn sync_context_rejects_another_environment_or_asset() {
254        let canister = ic_platform::principal::ExternalPrincipal::from_slice(&[1]);
255        validate_sync_context("proof", canister, Some("proof"), Some(&canister.to_text())).unwrap();
256        validate_sync_context("proof", canister, None, None).unwrap();
257        assert!(matches!(
258            validate_sync_context("proof", canister, Some("local"), None),
259            Err(FrontendError::Environment)
260        ));
261        assert!(matches!(
262            validate_sync_context("proof", canister, None, Some("2vxsx-fae")),
263            Err(FrontendError::Principal)
264        ));
265        assert!(matches!(
266            validate_sync_context("proof", canister, None, Some("invalid")),
267            Err(FrontendError::Principal)
268        ));
269    }
270    #[test]
271    fn uploaded_verification_requires_independent_digest_and_exact_target() {
272        let command = || super::command();
273        assert!(
274            command()
275                .try_get_matches_from([
276                    "frontend",
277                    "verify-uploaded",
278                    "browser/canic",
279                    "--sha256",
280                    "digest",
281                    "--canister",
282                    "rrkah-fqaaa-aaaaa-aaaaq-cai",
283                    "--prefix",
284                    "/canic"
285                ])
286                .is_ok()
287        );
288        assert!(
289            command()
290                .try_get_matches_from([
291                    "frontend",
292                    "verify-uploaded",
293                    "browser/canic",
294                    "--canister",
295                    "rrkah-fqaaa-aaaaa-aaaaq-cai",
296                    "--prefix",
297                    "/canic"
298                ])
299                .is_err()
300        );
301    }
302}