Skip to main content

foundry_cheatcodes/
config.rs

1use super::Result;
2use crate::Vm::Rpc;
3use alloy_primitives::{U256, map::AddressHashMap};
4use foundry_common::{ContractsByArtifact, fs::normalize_path};
5use foundry_compilers::{ArtifactId, ProjectPathsConfig, utils::canonicalize};
6use foundry_config::{
7    Config, FsPermissions, ResolvedRpcEndpoint, ResolvedRpcEndpoints, RpcEndpoint, RpcEndpointUrl,
8    cache::StorageCachingConfig, fs_permissions::FsAccessKind,
9};
10use foundry_evm_core::opts::EvmOpts;
11use foundry_evm_traces::identifier::ExternalIdentifierConfig;
12use itertools::Itertools;
13use std::{
14    path::{Path, PathBuf},
15    time::Duration,
16};
17
18/// Additional, configurable context the `Cheatcodes` inspector has access to
19///
20/// This is essentially a subset of various `Config` settings `Cheatcodes` needs to know.
21#[derive(Clone, Debug)]
22pub struct CheatsConfig {
23    /// Whether the FFI cheatcode is enabled.
24    pub ffi: bool,
25    /// Cheatcode selectors rejected before dispatch for restricted executions.
26    pub blocked_cheatcodes: Vec<[u8; 4]>,
27    /// Use the create 2 factory in all cases including tests and non-broadcasting scripts.
28    pub always_use_create_2_factory: bool,
29    /// Rewrite plain CREATE to CREATE2 for `forge script --batch`.
30    pub batch_rewrite_creates: bool,
31    /// Sets a timeout for vm.prompt cheatcodes
32    pub prompt_timeout: Duration,
33    /// RPC storage caching settings determines what chains and endpoints to cache
34    pub rpc_storage_caching: StorageCachingConfig,
35    /// Disables storage caching entirely.
36    pub no_storage_caching: bool,
37    /// All known endpoints and their aliases
38    pub rpc_endpoints: ResolvedRpcEndpoints,
39    /// Project's paths as configured
40    pub paths: ProjectPathsConfig,
41    /// Path to the directory that contains the bindings generated by `forge bind-json`.
42    pub bind_json_path: PathBuf,
43    /// Filesystem permissions for cheatcodes like `writeFile`, `readFile`
44    pub fs_permissions: FsPermissions,
45    /// Project root
46    pub root: PathBuf,
47    /// Absolute Path to broadcast dir i.e project_root/broadcast
48    pub broadcast: PathBuf,
49    /// Whether isolated test execution is enabled.
50    pub isolate: bool,
51    /// How the evm was configured by the user
52    pub evm_opts: EvmOpts,
53    /// Address labels from config
54    pub labels: AddressHashMap<String>,
55    /// Artifacts which are guaranteed to be fresh (either recompiled or cached).
56    /// If Some, `vm.getDeployedCode` invocations are validated to be in scope of this list.
57    /// If None, no validation is performed.
58    pub available_artifacts: Option<ContractsByArtifact>,
59    /// Artifacts used to resolve cheatcode artifact references.
60    /// Unlike `available_artifacts`, this is retained when artifact safety checks are disabled.
61    pub artifact_lookup: Option<ContractsByArtifact>,
62    /// Whether to decode the storage layouts of contracts outside the local project in state
63    /// diffs, by fetching their verified source code from a block explorer.
64    pub decode_external_storage: bool,
65    /// Settings for looking contracts up on block explorers, resolved lazily against the chain a
66    /// test is running on: a `vm.createSelectFork` can change it after this config was built.
67    pub external_sources: ExternalIdentifierConfig,
68    /// Currently running artifact.
69    pub running_artifact: Option<ArtifactId>,
70    /// Whether to enable legacy (non-reverting) assertions.
71    pub assertions_revert: bool,
72    /// Optional seed for the RNG algorithm.
73    pub seed: Option<U256>,
74    /// Whether to allow `expectRevert` to work for internal calls.
75    pub internal_expect_revert: bool,
76}
77
78impl CheatsConfig {
79    /// Extracts the necessary settings from the Config
80    pub fn new(
81        config: &Config,
82        evm_opts: EvmOpts,
83        available_artifacts: Option<ContractsByArtifact>,
84        running_artifact: Option<ArtifactId>,
85        batch_rewrite_creates: bool,
86    ) -> Self {
87        let rpc_endpoints = config.rpc_endpoints.clone().resolved();
88        trace!(?rpc_endpoints, "using resolved rpc endpoints");
89
90        let artifact_lookup = available_artifacts.clone();
91        // If user explicitly disabled safety checks, do not set available_artifacts.
92        let available_artifacts =
93            if config.unchecked_cheatcode_artifacts { None } else { available_artifacts };
94        let mut labels = config.labels.clone();
95        labels.extend(config.tracing.labels.clone());
96
97        Self {
98            ffi: evm_opts.ffi,
99            blocked_cheatcodes: Vec::new(),
100            always_use_create_2_factory: evm_opts.always_use_create_2_factory,
101            batch_rewrite_creates,
102            prompt_timeout: Duration::from_secs(config.prompt_timeout),
103            rpc_storage_caching: config.rpc_storage_caching.clone(),
104            no_storage_caching: config.no_storage_caching,
105            rpc_endpoints,
106            paths: config.project_paths(),
107            bind_json_path: config.bind_json.out.clone(),
108            fs_permissions: config.fs_permissions.clone().joined(config.root.as_ref()),
109            root: config.root.clone(),
110            broadcast: config.root.clone().join(&config.broadcast),
111            isolate: config.isolate,
112            evm_opts,
113            labels,
114            available_artifacts,
115            artifact_lookup,
116            decode_external_storage: config.decode_external_storage,
117            external_sources: ExternalIdentifierConfig::new(config),
118            running_artifact,
119            assertions_revert: config.assertions_revert,
120            seed: config.fuzz.seed,
121            internal_expect_revert: config.allow_internal_expect_revert,
122        }
123    }
124
125    /// Returns a new `CheatsConfig` configured with the given `Config` and `EvmOpts`.
126    pub fn clone_with(&self, config: &Config, evm_opts: EvmOpts) -> Self {
127        let mut cloned = Self::new(
128            config,
129            evm_opts,
130            self.artifact_lookup.clone().or_else(|| self.available_artifacts.clone()),
131            self.running_artifact.clone(),
132            self.batch_rewrite_creates,
133        );
134        cloned.blocked_cheatcodes.clone_from(&self.blocked_cheatcodes);
135        cloned
136    }
137
138    /// Attempts to canonicalize (see [std::fs::canonicalize]) the path.
139    ///
140    /// Canonicalization fails for non-existing paths, in which case we just normalize the path.
141    pub fn normalized_path(&self, path: impl AsRef<Path>) -> PathBuf {
142        let path = self.root.join(path);
143        canonicalize(&path).unwrap_or_else(|_| canonicalize_existing_ancestor(&path))
144    }
145
146    /// Returns true if the given path is allowed, if any path `allowed_paths` is an ancestor of the
147    /// path
148    ///
149    /// We only allow paths that are inside  allowed paths. To prevent path traversal
150    /// ("../../etc/passwd") we canonicalize/normalize the path first. We always join with the
151    /// configured root directory.
152    pub fn is_path_allowed(&self, path: impl AsRef<Path>, kind: FsAccessKind) -> bool {
153        self.is_normalized_path_allowed(&self.normalized_path(path), kind)
154    }
155
156    fn is_normalized_path_allowed(&self, path: &Path, kind: FsAccessKind) -> bool {
157        self.fs_permissions.is_path_allowed(path, kind)
158    }
159
160    /// Returns an error if no access is granted to access `path`, See also [Self::is_path_allowed]
161    ///
162    /// Returns the normalized version of `path`, see [`CheatsConfig::normalized_path`]
163    pub fn ensure_path_allowed(
164        &self,
165        path: impl AsRef<Path>,
166        kind: FsAccessKind,
167    ) -> Result<PathBuf> {
168        let path = path.as_ref();
169        let normalized = self.normalized_path(path);
170        ensure!(
171            self.is_normalized_path_allowed(&normalized, kind),
172            "the path {} is not allowed to be accessed for {kind} operations",
173            normalized.strip_prefix(&self.root).unwrap_or(path).display()
174        );
175        Ok(normalized)
176    }
177
178    /// Returns true if the given `path` is the project's foundry.toml file
179    ///
180    /// Note: this should be called with normalized path
181    pub fn is_foundry_toml(&self, path: impl AsRef<Path>) -> bool {
182        // path methods that do not access the filesystem are such as [`Path::starts_with`], are
183        // case-sensitive no matter the platform or filesystem. to make this case-sensitive
184        // we convert the underlying `OssStr` to lowercase checking that `path` and
185        // `foundry.toml` are the same file by comparing the FD, because it may not exist
186        let foundry_toml = self.root.join(Config::FILE_NAME);
187        Path::new(&foundry_toml.to_string_lossy().to_lowercase())
188            .starts_with(Path::new(&path.as_ref().to_string_lossy().to_lowercase()))
189    }
190
191    /// Same as [`Self::is_foundry_toml`] but returns an `Err` if [`Self::is_foundry_toml`] returns
192    /// true
193    pub fn ensure_not_foundry_toml(&self, path: impl AsRef<Path>) -> Result<()> {
194        ensure!(!self.is_foundry_toml(path), "access to `foundry.toml` is not allowed");
195        Ok(())
196    }
197
198    /// Returns the RPC to use
199    ///
200    /// If `url_or_alias` is a known alias in the `ResolvedRpcEndpoints` then it returns the
201    /// corresponding URL of that alias. otherwise this assumes `url_or_alias` is itself a URL
202    /// if it starts with a `http` or `ws` scheme.
203    ///
204    /// A URL that configured entries resolve to keeps their settings when the entries agree.
205    ///
206    /// If the url is a path to an existing file, it is also considered a valid RPC URL, IPC path.
207    ///
208    /// # Errors
209    ///
210    ///  - Returns an error if `url_or_alias` is a known alias but references an unresolved env var.
211    ///  - Returns an error if `url_or_alias` is not an alias but does not start with a `http` or
212    ///    `ws` `scheme` and is not a path to an existing file
213    ///  - Returns an error if network access is disabled.
214    pub fn rpc_endpoint(&self, url_or_alias: &str) -> Result<ResolvedRpcEndpoint> {
215        // Every cheatcode that opens a connection to a URL or alias resolves it here.
216        if self.evm_opts.no_network {
217            return Err(fmt_err!("network access is disabled"));
218        }
219        if let Some(endpoint) = self.rpc_endpoints.get(url_or_alias) {
220            Ok(endpoint.clone().try_resolve())
221        } else if let Ok(endpoint) = self
222            .rpc_endpoints
223            .values()
224            .map(|endpoint| endpoint.clone().try_resolve())
225            .filter(|endpoint| endpoint.endpoint.as_ref().is_ok_and(|url| url == url_or_alias))
226            .all_equal_value()
227        {
228            // A URL that entries resolve to, such as one `vm.rpcUrl` returns, keeps their settings
229            // when they agree. Entries are resolved again, as `vm.rpcUrl` does, so an env var set
230            // during the run matches too.
231            Ok(endpoint)
232        } else if let Some(builtin_url) = foundry_config::builtin_rpc_url(url_or_alias) {
233            let url = RpcEndpointUrl::Url(builtin_url.to_string());
234            Ok(RpcEndpoint::new(url).resolve())
235        } else {
236            // check if it's a URL or a path to an existing file to an ipc socket
237            if url_or_alias.starts_with("http") ||
238                url_or_alias.starts_with("ws") ||
239                // check for existing ipc file
240                Path::new(url_or_alias).exists()
241            {
242                let url = RpcEndpointUrl::Env(url_or_alias.to_string());
243                Ok(RpcEndpoint::new(url).resolve())
244            } else {
245                Err(fmt_err!("invalid rpc url: {url_or_alias}"))
246            }
247        }
248    }
249    /// Returns all the RPC urls and their alias.
250    pub fn rpc_urls(&self) -> Result<Vec<Rpc>> {
251        let mut urls = Vec::with_capacity(self.rpc_endpoints.len());
252        for alias in self.rpc_endpoints.keys() {
253            let url = self.rpc_endpoint(alias)?.url()?;
254            urls.push(Rpc { key: alias.clone(), url });
255        }
256        Ok(urls)
257    }
258}
259
260impl Default for CheatsConfig {
261    fn default() -> Self {
262        Self {
263            ffi: false,
264            blocked_cheatcodes: Vec::new(),
265            always_use_create_2_factory: false,
266            batch_rewrite_creates: false,
267            prompt_timeout: Duration::from_secs(120),
268            rpc_storage_caching: Default::default(),
269            no_storage_caching: false,
270            rpc_endpoints: Default::default(),
271            paths: ProjectPathsConfig::builder().build_with_root("./"),
272            fs_permissions: Default::default(),
273            root: Default::default(),
274            bind_json_path: PathBuf::default().join("utils").join("jsonBindings.sol"),
275            broadcast: Default::default(),
276            isolate: Config::default().isolate,
277            evm_opts: Default::default(),
278            labels: Default::default(),
279            available_artifacts: Default::default(),
280            artifact_lookup: Default::default(),
281            decode_external_storage: false,
282            external_sources: Default::default(),
283            running_artifact: Default::default(),
284            assertions_revert: true,
285            seed: None,
286            internal_expect_revert: false,
287        }
288    }
289}
290
291fn canonicalize_existing_ancestor(path: &Path) -> PathBuf {
292    let normalized = normalize_path(path);
293    let mut missing = Vec::new();
294    let mut ancestor = normalized.as_path();
295    while !ancestor.exists() {
296        let Some(name) = ancestor.file_name() else { return normalized };
297        missing.push(name.to_owned());
298        let Some(parent) = ancestor.parent() else { return normalized };
299        ancestor = parent;
300    }
301
302    let mut path = canonicalize(ancestor).unwrap_or_else(|_| ancestor.to_path_buf());
303    for component in missing.iter().rev() {
304        path.push(component);
305    }
306    path
307}
308
309#[cfg(test)]
310mod tests {
311
312    use super::*;
313    use alloy_primitives::Address;
314    use foundry_config::{RpcEndpoints, fs_permissions::PathPermission};
315    use tempfile::TempDir;
316
317    fn config(root: &Path, fs_permissions: FsPermissions) -> CheatsConfig {
318        CheatsConfig::new(
319            &Config { root: root.into(), fs_permissions, ..Default::default() },
320            Default::default(),
321            None,
322            None,
323            false,
324        )
325    }
326
327    #[test]
328    fn test_allowed_paths() {
329        let temp = TempDir::new().unwrap();
330        let root = temp.path().join("my/project/root");
331        std::fs::create_dir_all(&root).unwrap();
332        let config = config(&root, FsPermissions::new(vec![PathPermission::read_write("./")]));
333
334        assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Read).is_ok());
335        assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Write).is_ok());
336        assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Read).is_ok());
337        assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Write).is_ok());
338        assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Read).is_err());
339        assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Write).is_err());
340    }
341
342    #[test]
343    fn test_batch_rewrite_creates_flag_plumbing() {
344        assert!(!CheatsConfig::default().batch_rewrite_creates);
345
346        let on = CheatsConfig::new(&Config::default(), Default::default(), None, None, true);
347        assert!(on.batch_rewrite_creates);
348
349        let cloned = on.clone_with(&Config::default(), Default::default());
350        assert!(cloned.batch_rewrite_creates);
351    }
352
353    #[test]
354    fn unchecked_artifacts_retain_lookup_without_validation() {
355        let config = Config { unchecked_cheatcode_artifacts: true, ..Default::default() };
356        let cheats = CheatsConfig::new(
357            &config,
358            Default::default(),
359            Some(ContractsByArtifact::default()),
360            None,
361            false,
362        );
363
364        assert!(cheats.available_artifacts.is_none());
365        assert!(cheats.artifact_lookup.is_some());
366
367        let cloned = cheats.clone_with(&config, Default::default());
368        assert!(cloned.available_artifacts.is_none());
369        assert!(cloned.artifact_lookup.is_some());
370    }
371
372    #[test]
373    fn clone_with_preserves_available_artifacts_without_lookup() {
374        let cheats = CheatsConfig {
375            available_artifacts: Some(ContractsByArtifact::default()),
376            ..Default::default()
377        };
378
379        let cloned = cheats.clone_with(&Config::default(), Default::default());
380        assert!(cloned.available_artifacts.is_some());
381        assert!(cloned.artifact_lookup.is_some());
382    }
383
384    #[test]
385    fn tracing_labels_override_legacy_labels() {
386        let address = Address::with_last_byte(1);
387        let mut config = Config::default();
388        config.labels.insert(address, "legacy".to_string());
389        config.tracing.labels.insert(address, "canonical".to_string());
390
391        let config = CheatsConfig::new(&config, Default::default(), None, None, false);
392
393        assert_eq!(config.labels.get(&address).map(String::as_str), Some("canonical"));
394    }
395
396    #[test]
397    fn test_is_foundry_toml() {
398        let root = Path::new("/my/project/root/");
399        let config = config(root, FsPermissions::new(vec![PathPermission::read_write("./")]));
400
401        let f = root.join("foundry.toml");
402        assert!(config.is_foundry_toml(f));
403
404        let f = root.join("Foundry.toml");
405        assert!(config.is_foundry_toml(f));
406
407        let f = root.join("lib/other/foundry.toml");
408        assert!(!config.is_foundry_toml(f));
409    }
410
411    #[test]
412    fn test_rpc_endpoint_url_keeps_entry_config() {
413        let mut endpoint = RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18429".into()));
414        endpoint.config.retries = Some(2);
415        endpoint.config.retry_backoff = Some(100);
416        let shared = || RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18430".into()));
417        let mut retrying = shared();
418        retrying.config.retries = Some(5);
419        let mut same = RpcEndpoint::new(RpcEndpointUrl::Url("http://127.0.0.1:18431".into()));
420        same.config.retries = Some(3);
421        let config = Config {
422            rpc_endpoints: RpcEndpoints::new([
423                ("stub", endpoint),
424                ("plain", shared()),
425                ("retrying", retrying),
426                ("same_a", same.clone()),
427                ("same_b", same),
428            ]),
429            ..Default::default()
430        };
431        let config = CheatsConfig::new(&config, Default::default(), None, None, false);
432        let settings = |url_or_alias| {
433            let config = config.rpc_endpoint(url_or_alias).unwrap().config;
434            (config.retries, config.retry_backoff)
435        };
436
437        assert_eq!(settings("stub"), (Some(2), Some(100)));
438        assert_eq!(settings("http://127.0.0.1:18429"), (Some(2), Some(100)));
439        // Two entries with different settings resolve to this URL, so neither applies.
440        assert_eq!(settings("http://127.0.0.1:18430"), (None, None));
441        assert_eq!(settings("retrying"), (Some(5), None));
442        // Two entries with the same settings resolve to this URL, so they apply.
443        assert_eq!(settings("http://127.0.0.1:18431"), (Some(3), None));
444        assert_eq!(settings("http://127.0.0.1:18432"), (None, None));
445    }
446}