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 std::{
12    collections::HashMap,
13    path::{Path, PathBuf},
14    time::Duration,
15};
16
17/// Additional, configurable context the `Cheatcodes` inspector has access to
18///
19/// This is essentially a subset of various `Config` settings `Cheatcodes` needs to know.
20#[derive(Clone, Debug)]
21pub struct CheatsConfig {
22    /// Whether the FFI cheatcode is enabled.
23    pub ffi: bool,
24    /// Use the create 2 factory in all cases including tests and non-broadcasting scripts.
25    pub always_use_create_2_factory: bool,
26    /// Sets a timeout for vm.prompt cheatcodes
27    pub prompt_timeout: Duration,
28    /// RPC storage caching settings determines what chains and endpoints to cache
29    pub rpc_storage_caching: StorageCachingConfig,
30    /// Disables storage caching entirely.
31    pub no_storage_caching: bool,
32    /// All known endpoints and their aliases
33    pub rpc_endpoints: ResolvedRpcEndpoints,
34    /// Project's paths as configured
35    pub paths: ProjectPathsConfig,
36    /// Path to the directory that contains the bindings generated by `forge bind-json`.
37    pub bind_json_path: PathBuf,
38    /// Filesystem permissions for cheatcodes like `writeFile`, `readFile`
39    pub fs_permissions: FsPermissions,
40    /// Project root
41    pub root: PathBuf,
42    /// Absolute Path to broadcast dir i.e project_root/broadcast
43    pub broadcast: PathBuf,
44    /// Paths (directories) where file reading/writing is allowed
45    pub allowed_paths: Vec<PathBuf>,
46    /// How the evm was configured by the user
47    pub evm_opts: EvmOpts,
48    /// Address labels from config
49    pub labels: AddressHashMap<String>,
50    /// Artifacts which are guaranteed to be fresh (either recompiled or cached).
51    /// If Some, `vm.getDeployedCode` invocations are validated to be in scope of this list.
52    /// If None, no validation is performed.
53    pub available_artifacts: Option<ContractsByArtifact>,
54    /// Currently running artifact.
55    pub running_artifact: Option<ArtifactId>,
56    /// Whether to enable legacy (non-reverting) assertions.
57    pub assertions_revert: bool,
58    /// Optional seed for the RNG algorithm.
59    pub seed: Option<U256>,
60    /// Whether to allow `expectRevert` to work for internal calls.
61    pub internal_expect_revert: bool,
62    /// Mapping of chain aliases to chain data
63    pub chains: HashMap<String, ChainData>,
64    /// Mapping of chain IDs to their aliases
65    pub chain_id_to_alias: HashMap<u64, String>,
66}
67
68/// Chain data for getChain cheatcodes
69#[derive(Clone, Debug)]
70pub struct ChainData {
71    pub name: String,
72    pub chain_id: u64,
73    pub default_rpc_url: String, // Store default RPC URL
74}
75
76impl CheatsConfig {
77    /// Extracts the necessary settings from the Config
78    pub fn new(
79        config: &Config,
80        evm_opts: EvmOpts,
81        available_artifacts: Option<ContractsByArtifact>,
82        running_artifact: Option<ArtifactId>,
83    ) -> Self {
84        let mut allowed_paths = vec![config.root.clone()];
85        allowed_paths.extend(config.libs.iter().cloned());
86        allowed_paths.extend(config.allow_paths.iter().cloned());
87
88        let rpc_endpoints = config.rpc_endpoints.clone().resolved();
89        trace!(?rpc_endpoints, "using resolved rpc endpoints");
90
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
95        Self {
96            ffi: evm_opts.ffi,
97            always_use_create_2_factory: evm_opts.always_use_create_2_factory,
98            prompt_timeout: Duration::from_secs(config.prompt_timeout),
99            rpc_storage_caching: config.rpc_storage_caching.clone(),
100            no_storage_caching: config.no_storage_caching,
101            rpc_endpoints,
102            paths: config.project_paths(),
103            bind_json_path: config.bind_json.out.clone(),
104            fs_permissions: config.fs_permissions.clone().joined(config.root.as_ref()),
105            root: config.root.clone(),
106            broadcast: config.root.clone().join(&config.broadcast),
107            allowed_paths,
108            evm_opts,
109            labels: config.labels.clone(),
110            available_artifacts,
111            running_artifact,
112            assertions_revert: config.assertions_revert,
113            seed: config.fuzz.seed,
114            internal_expect_revert: config.allow_internal_expect_revert,
115            chains: HashMap::new(),
116            chain_id_to_alias: HashMap::new(),
117        }
118    }
119
120    /// Returns a new `CheatsConfig` configured with the given `Config` and `EvmOpts`.
121    pub fn clone_with(&self, config: &Config, evm_opts: EvmOpts) -> Self {
122        Self::new(config, evm_opts, self.available_artifacts.clone(), self.running_artifact.clone())
123    }
124
125    /// Attempts to canonicalize (see [std::fs::canonicalize]) the path.
126    ///
127    /// Canonicalization fails for non-existing paths, in which case we just normalize the path.
128    pub fn normalized_path(&self, path: impl AsRef<Path>) -> PathBuf {
129        let path = self.root.join(path);
130        canonicalize(&path).unwrap_or_else(|_| normalize_path(&path))
131    }
132
133    /// Returns true if the given path is allowed, if any path `allowed_paths` is an ancestor of the
134    /// path
135    ///
136    /// We only allow paths that are inside  allowed paths. To prevent path traversal
137    /// ("../../etc/passwd") we canonicalize/normalize the path first. We always join with the
138    /// configured root directory.
139    pub fn is_path_allowed(&self, path: impl AsRef<Path>, kind: FsAccessKind) -> bool {
140        self.is_normalized_path_allowed(&self.normalized_path(path), kind)
141    }
142
143    fn is_normalized_path_allowed(&self, path: &Path, kind: FsAccessKind) -> bool {
144        self.fs_permissions.is_path_allowed(path, kind)
145    }
146
147    /// Returns an error if no access is granted to access `path`, See also [Self::is_path_allowed]
148    ///
149    /// Returns the normalized version of `path`, see [`CheatsConfig::normalized_path`]
150    pub fn ensure_path_allowed(
151        &self,
152        path: impl AsRef<Path>,
153        kind: FsAccessKind,
154    ) -> Result<PathBuf> {
155        let path = path.as_ref();
156        let normalized = self.normalized_path(path);
157        ensure!(
158            self.is_normalized_path_allowed(&normalized, kind),
159            "the path {} is not allowed to be accessed for {kind} operations",
160            normalized.strip_prefix(&self.root).unwrap_or(path).display()
161        );
162        Ok(normalized)
163    }
164
165    /// Returns true if the given `path` is the project's foundry.toml file
166    ///
167    /// Note: this should be called with normalized path
168    pub fn is_foundry_toml(&self, path: impl AsRef<Path>) -> bool {
169        // path methods that do not access the filesystem are such as [`Path::starts_with`], are
170        // case-sensitive no matter the platform or filesystem. to make this case-sensitive
171        // we convert the underlying `OssStr` to lowercase checking that `path` and
172        // `foundry.toml` are the same file by comparing the FD, because it may not exist
173        let foundry_toml = self.root.join(Config::FILE_NAME);
174        Path::new(&foundry_toml.to_string_lossy().to_lowercase())
175            .starts_with(Path::new(&path.as_ref().to_string_lossy().to_lowercase()))
176    }
177
178    /// Same as [`Self::is_foundry_toml`] but returns an `Err` if [`Self::is_foundry_toml`] returns
179    /// true
180    pub fn ensure_not_foundry_toml(&self, path: impl AsRef<Path>) -> Result<()> {
181        ensure!(!self.is_foundry_toml(path), "access to `foundry.toml` is not allowed");
182        Ok(())
183    }
184
185    /// Returns the RPC to use
186    ///
187    /// If `url_or_alias` is a known alias in the `ResolvedRpcEndpoints` then it returns the
188    /// corresponding URL of that alias. otherwise this assumes `url_or_alias` is itself a URL
189    /// if it starts with a `http` or `ws` scheme.
190    ///
191    /// If the url is a path to an existing file, it is also considered a valid RPC URL, IPC path.
192    ///
193    /// # Errors
194    ///
195    ///  - Returns an error if `url_or_alias` is a known alias but references an unresolved env var.
196    ///  - Returns an error if `url_or_alias` is not an alias but does not start with a `http` or
197    ///    `ws` `scheme` and is not a path to an existing file
198    pub fn rpc_endpoint(&self, url_or_alias: &str) -> Result<ResolvedRpcEndpoint> {
199        if let Some(endpoint) = self.rpc_endpoints.get(url_or_alias) {
200            Ok(endpoint.clone().try_resolve())
201        } else {
202            // check if it's a URL or a path to an existing file to an ipc socket
203            if url_or_alias.starts_with("http") ||
204                url_or_alias.starts_with("ws") ||
205                // check for existing ipc file
206                Path::new(url_or_alias).exists()
207            {
208                let url = RpcEndpointUrl::Env(url_or_alias.to_string());
209                Ok(RpcEndpoint::new(url).resolve())
210            } else {
211                Err(fmt_err!("invalid rpc url: {url_or_alias}"))
212            }
213        }
214    }
215    /// Returns all the RPC urls and their alias.
216    pub fn rpc_urls(&self) -> Result<Vec<Rpc>> {
217        let mut urls = Vec::with_capacity(self.rpc_endpoints.len());
218        for alias in self.rpc_endpoints.keys() {
219            let url = self.rpc_endpoint(alias)?.url()?;
220            urls.push(Rpc { key: alias.clone(), url });
221        }
222        Ok(urls)
223    }
224}
225
226impl Default for CheatsConfig {
227    fn default() -> Self {
228        Self {
229            ffi: false,
230            always_use_create_2_factory: false,
231            prompt_timeout: Duration::from_secs(120),
232            rpc_storage_caching: Default::default(),
233            no_storage_caching: false,
234            rpc_endpoints: Default::default(),
235            paths: ProjectPathsConfig::builder().build_with_root("./"),
236            fs_permissions: Default::default(),
237            root: Default::default(),
238            bind_json_path: PathBuf::default().join("utils").join("jsonBindings.sol"),
239            broadcast: Default::default(),
240            allowed_paths: vec![],
241            evm_opts: Default::default(),
242            labels: Default::default(),
243            available_artifacts: Default::default(),
244            running_artifact: Default::default(),
245            assertions_revert: true,
246            seed: None,
247            internal_expect_revert: false,
248            chains: HashMap::new(),
249            chain_id_to_alias: HashMap::new(),
250        }
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use foundry_config::fs_permissions::PathPermission;
258
259    fn config(root: &str, fs_permissions: FsPermissions) -> CheatsConfig {
260        CheatsConfig::new(
261            &Config { root: root.into(), fs_permissions, ..Default::default() },
262            Default::default(),
263            None,
264            None,
265        )
266    }
267
268    #[test]
269    fn test_allowed_paths() {
270        let root = "/my/project/root/";
271        let config = config(root, FsPermissions::new(vec![PathPermission::read_write("./")]));
272
273        assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Read).is_ok());
274        assert!(config.ensure_path_allowed("./t.txt", FsAccessKind::Write).is_ok());
275        assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Read).is_ok());
276        assert!(config.ensure_path_allowed("../root/t.txt", FsAccessKind::Write).is_ok());
277        assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Read).is_err());
278        assert!(config.ensure_path_allowed("../../root/t.txt", FsAccessKind::Write).is_err());
279    }
280
281    #[test]
282    fn test_is_foundry_toml() {
283        let root = "/my/project/root/";
284        let config = config(root, FsPermissions::new(vec![PathPermission::read_write("./")]));
285
286        let f = format!("{root}foundry.toml");
287        assert!(config.is_foundry_toml(f));
288
289        let f = format!("{root}Foundry.toml");
290        assert!(config.is_foundry_toml(f));
291
292        let f = format!("{root}lib/other/foundry.toml");
293        assert!(!config.is_foundry_toml(f));
294    }
295}