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#[derive(Clone, Debug)]
20pub struct CheatsConfig {
21 pub ffi: bool,
23 pub always_use_create_2_factory: bool,
25 pub prompt_timeout: Duration,
27 pub rpc_storage_caching: StorageCachingConfig,
29 pub no_storage_caching: bool,
31 pub rpc_endpoints: ResolvedRpcEndpoints,
33 pub paths: ProjectPathsConfig,
35 pub bind_json_path: PathBuf,
37 pub fs_permissions: FsPermissions,
39 pub root: PathBuf,
41 pub broadcast: PathBuf,
43 pub evm_opts: EvmOpts,
45 pub labels: AddressHashMap<String>,
47 pub available_artifacts: Option<ContractsByArtifact>,
51 pub running_artifact: Option<ArtifactId>,
53 pub assertions_revert: bool,
55 pub seed: Option<U256>,
57 pub internal_expect_revert: bool,
59 pub fee_token: Option<Address>,
61}
62
63impl CheatsConfig {
64 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 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 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 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 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 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 pub fn is_foundry_toml(&self, path: impl AsRef<Path>) -> bool {
157 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 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 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 if url_or_alias.starts_with("http") ||
192 url_or_alias.starts_with("ws") ||
193 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 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}