Skip to main content

foundry_cheatcodes/
config.rs

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