1use std::{sync::Arc, time::Duration};
10
11use candid::{CandidType, Principal};
12use ic_agent::{
13 Agent, AgentError, Identity,
14 identity::{BasicIdentity, Prime256v1Identity, Secp256k1Identity},
15};
16use serde::{Deserialize, de::DeserializeOwned};
17use thiserror::Error as ThisError;
18
19use super::{
20 model::IcpCli,
21 run::{run_json, run_secret_output},
22};
23
24const MANAGEMENT_CANISTER_STATUS: &str = "canister_status";
25const MANAGEMENT_INGRESS_EXPIRY: Duration = Duration::from_mins(4);
26
27#[derive(Debug, Deserialize)]
28struct IcpNetworkStatus {
29 api_url: String,
30 root_key: String,
31}
32
33#[derive(Debug, ThisError)]
36pub enum IcpManagementCallError {
37 #[error("failed to encode the management-canister argument: {0}")]
38 CandidEncode(#[source] candid::Error),
39
40 #[error("failed to decode the management-canister response: {0}")]
41 CandidResponse(#[source] candid::Error),
42
43 #[error("failed to build the management-canister agent: {0}")]
44 AgentBuild(#[source] AgentError),
45
46 #[error("the effective-ID-correct management-canister call failed: {0}")]
47 AgentCall(#[source] AgentError),
48
49 #[error("failed to create the management-canister async runtime: {0}")]
50 AsyncRuntime(#[source] std::io::Error),
51
52 #[error(transparent)]
53 Icp(#[from] super::IcpCommandError),
54
55 #[error("ICP CLI reported an invalid network root key: {0}")]
56 NetworkRootKey(#[source] canic_core::cdk::utils::hash::DecodeHexError),
57
58 #[error("the selected ICP identity cannot be represented by a supported exported PEM")]
59 UnsupportedExportedIdentity,
60
61 #[error("failed to resolve the Principal of the exported ICP identity: {message}")]
62 ExportedIdentityPrincipal { message: String },
63
64 #[error(
65 "the exported ICP identity Principal {exported} conflicts with the active ICP identity {active}"
66 )]
67 ExportedIdentityConflict { active: String, exported: String },
68
69 #[error("an ICP environment is required for the management-canister call")]
70 MissingEnvironment,
71}
72
73impl IcpCli {
74 #[must_use]
76 pub(crate) fn uses_direct_local_replica(&self) -> bool {
77 self.local_replica
78 .as_ref()
79 .is_some_and(|target| self.environment.as_deref() == Some(target.environment.as_str()))
80 }
81
82 pub(crate) fn management_canister_status_candid<I, O>(
85 &self,
86 effective_canister_id: Principal,
87 input: &I,
88 ) -> Result<O, IcpManagementCallError>
89 where
90 I: CandidType,
91 O: CandidType + DeserializeOwned,
92 {
93 let argument = candid::encode_one(input).map_err(IcpManagementCallError::CandidEncode)?;
94 let agent = self.authenticated_agent()?;
95 self.record_remote_call();
96 let response = call_management_update(
97 &LiveAgentUpdateBoundary { agent: &agent },
98 effective_canister_id,
99 MANAGEMENT_CANISTER_STATUS,
100 argument,
101 )?;
102 candid::decode_one(&response).map_err(IcpManagementCallError::CandidResponse)
103 }
104
105 pub fn authenticated_agent(&self) -> Result<Agent, IcpManagementCallError> {
109 self.build_authenticated_agent(None)
110 }
111
112 pub(crate) fn authenticated_agent_with_response_limit(
114 &self,
115 maximum: usize,
116 ) -> Result<Agent, IcpManagementCallError> {
117 self.build_authenticated_agent(Some(maximum))
118 }
119
120 fn build_authenticated_agent(
121 &self,
122 maximum: Option<usize>,
123 ) -> Result<Agent, IcpManagementCallError> {
124 let environment = self
125 .environment
126 .as_deref()
127 .ok_or(IcpManagementCallError::MissingEnvironment)?;
128 let network = self.network_status(environment)?;
129 let identity = self.exported_active_identity()?;
130 let mut builder = Agent::builder()
131 .with_url(&network.api_url)
132 .with_arc_identity(identity)
133 .with_ingress_expiry(MANAGEMENT_INGRESS_EXPIRY);
134 if let Some(maximum) = maximum {
135 builder = builder.with_max_response_body_size(maximum);
136 }
137 let agent = builder
138 .build()
139 .map_err(IcpManagementCallError::AgentBuild)?;
140 let root_key = canic_core::cdk::utils::hash::decode_hex(&network.root_key)
141 .map_err(IcpManagementCallError::NetworkRootKey)?;
142 agent.set_root_key(root_key);
143 Ok(agent)
144 }
145
146 fn network_status(
147 &self,
148 environment: &str,
149 ) -> Result<IcpNetworkStatus, IcpManagementCallError> {
150 if let Some(target) = &self.local_replica
151 && environment == target.environment
152 {
153 return Ok(IcpNetworkStatus {
154 api_url: target.url.clone(),
155 root_key: target.root_key.clone(),
156 });
157 }
158 let mut command = self.request_command();
159 command.args(["network", "status", "--environment", environment, "--json"]);
160 run_json(&mut command, self).map_err(Into::into)
161 }
162
163 fn exported_active_identity(&self) -> Result<Arc<dyn Identity>, IcpManagementCallError> {
164 let identity_name = self.selected_identity_name()?;
165
166 let mut export_command = self.request_command();
167 export_command.args(["identity", "export", &identity_name]);
168 if let Some(password_file) = self.identity_password_file.as_deref() {
169 export_command.arg("--password-file").arg(password_file);
170 }
171 let mut pem = run_secret_output(&mut export_command, self)?;
172 let identity = parse_exported_identity(&pem);
173 pem.fill(0);
174 let identity = identity?;
175 let exported = identity
176 .sender()
177 .map_err(|message| IcpManagementCallError::ExportedIdentityPrincipal { message })?;
178 let active = self.identity_principal_text()?;
179 if exported.to_text() != active {
180 return Err(IcpManagementCallError::ExportedIdentityConflict {
181 active,
182 exported: exported.to_text(),
183 });
184 }
185 Ok(identity)
186 }
187}
188
189fn parse_exported_identity(pem: &[u8]) -> Result<Arc<dyn Identity>, IcpManagementCallError> {
190 if let Ok(identity) = BasicIdentity::from_pem(pem) {
191 return Ok(Arc::new(identity));
192 }
193 if let Ok(identity) = Secp256k1Identity::from_pem(pem) {
194 return Ok(Arc::new(identity));
195 }
196 if let Ok(identity) = Prime256v1Identity::from_pem(pem) {
197 return Ok(Arc::new(identity));
198 }
199 Err(IcpManagementCallError::UnsupportedExportedIdentity)
200}
201
202#[derive(Debug, Eq, PartialEq)]
203struct ManagementUpdateRequest {
204 argument: Vec<u8>,
205 canister_id: Principal,
206 effective_canister_id: Principal,
207 method: String,
208}
209
210trait AgentUpdateBoundary {
211 fn update(&self, request: ManagementUpdateRequest) -> Result<Vec<u8>, IcpManagementCallError>;
212}
213
214struct LiveAgentUpdateBoundary<'a> {
215 agent: &'a Agent,
216}
217
218impl AgentUpdateBoundary for LiveAgentUpdateBoundary<'_> {
219 fn update(&self, request: ManagementUpdateRequest) -> Result<Vec<u8>, IcpManagementCallError> {
220 let runtime = tokio::runtime::Builder::new_current_thread()
221 .enable_all()
222 .build()
223 .map_err(IcpManagementCallError::AsyncRuntime)?;
224 runtime
225 .block_on(
226 self.agent
227 .update(&request.canister_id, request.method)
228 .with_effective_canister_id(request.effective_canister_id)
229 .with_arg(request.argument)
230 .call_and_wait(),
231 )
232 .map_err(IcpManagementCallError::AgentCall)
233 }
234}
235
236fn call_management_update(
237 boundary: &impl AgentUpdateBoundary,
238 effective_canister_id: Principal,
239 method: &str,
240 argument: Vec<u8>,
241) -> Result<Vec<u8>, IcpManagementCallError> {
242 boundary.update(ManagementUpdateRequest {
243 argument,
244 canister_id: Principal::management_canister(),
245 effective_canister_id,
246 method: method.to_string(),
247 })
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253 use crate::icp::LocalReplicaTarget;
254 use std::cell::RefCell;
255
256 struct RecordingAgentBoundary {
257 request: RefCell<Option<ManagementUpdateRequest>>,
258 }
259
260 impl AgentUpdateBoundary for RecordingAgentBoundary {
261 fn update(
262 &self,
263 request: ManagementUpdateRequest,
264 ) -> Result<Vec<u8>, IcpManagementCallError> {
265 self.request.replace(Some(request));
266 Ok(vec![1, 2, 3])
267 }
268 }
269
270 #[test]
271 fn management_status_routes_through_the_target_effective_canister_id() {
272 let target =
273 Principal::from_text("rrkah-fqaaa-aaaaa-aaaaq-cai").expect("effective canister ID");
274 let boundary = RecordingAgentBoundary {
275 request: RefCell::new(None),
276 };
277 let response =
278 call_management_update(&boundary, target, MANAGEMENT_CANISTER_STATUS, vec![7, 8, 9])
279 .expect("record routed management update");
280
281 assert_eq!(response, vec![1, 2, 3]);
282 assert_eq!(
283 boundary.request.into_inner(),
284 Some(ManagementUpdateRequest {
285 argument: vec![7, 8, 9],
286 canister_id: Principal::management_canister(),
287 effective_canister_id: target,
288 method: MANAGEMENT_CANISTER_STATUS.to_string(),
289 })
290 );
291 }
292
293 #[test]
294 fn explicit_local_replica_owns_management_network_resolution() {
295 let target = LocalReplicaTarget {
296 environment: "local-qualification".into(),
297 root_key: "010203".to_string(),
298 url: "http://127.0.0.1:4943/".to_string(),
299 };
300 let icp = IcpCli::new("missing-icp", Some(target.environment.clone()))
301 .with_local_replica(Some(target.clone()));
302
303 let status = icp
304 .network_status(&target.environment)
305 .expect("resolve explicit local replica without invoking ICP CLI");
306
307 assert_eq!(status.api_url, target.url);
308 assert_eq!(status.root_key, target.root_key);
309 assert!(icp.uses_direct_local_replica());
310 let mut direct = std::process::Command::new("icp");
311 icp.add_target_args(&mut direct);
312 assert_eq!(
313 direct.get_args().collect::<Vec<_>>(),
314 ["-n", &target.url, "-k", &target.root_key].map(std::ffi::OsStr::new)
315 );
316 let other = IcpCli::new("missing-icp", Some("ic".into())).with_local_replica(Some(target));
317 assert!(!other.uses_direct_local_replica());
318 let mut named = std::process::Command::new("icp");
319 other.add_target_args(&mut named);
320 assert_eq!(
321 named.get_args().collect::<Vec<_>>(),
322 ["-e", "ic"].map(std::ffi::OsStr::new)
323 );
324 }
325}