Skip to main content

bynk_project/
hyperdrive.rs

1//! #3319: the Hyperdrive settings of `bynk.toml`.
2//!
3//! Two tables name a `Postgres` capability (`capability Main = Postgres`) and
4//! say where its connection string comes from. Neither holds a connection
5//! string: a string is a secret, and `bynk.toml` is committed. Each names an
6//! environment variable to read it from.
7//!
8//! ```toml
9//! # Deploy: `bynk deploy` makes or updates the Hyperdrive config from the
10//! # variable, or adopts a config that already exists (no string needed).
11//! [deploy.hyperdrive.Main]
12//! connection_env = "MAIN_DATABASE_URL"
13//! config_id = { production = "0123…" }
14//!
15//! # Development: `bynk dev` hands the variable's value to `wrangler dev`.
16//! [dev.hyperdrive.Main]
17//! connection_env = "MAIN_LOCAL_DATABASE_URL"
18//! ```
19
20use crate::discovery::read_source;
21use crate::paths::{ProjectPathsError, did_you_mean};
22use std::collections::{BTreeMap, HashMap};
23use std::path::{Path, PathBuf};
24
25/// One capability's `[deploy.hyperdrive.<Capability>]` entry.
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub struct HyperdriveDeploy {
28    /// The environment variable `bynk deploy` reads the connection string
29    /// from. Never the string itself.
30    pub connection_env: Option<String>,
31    /// Per deployment environment (`default`, or an `--env` name): the id of
32    /// a Hyperdrive config that already exists. An environment listed here is
33    /// adopted, and needs no connection string.
34    pub config_id: BTreeMap<String, String>,
35}
36
37/// The `[deploy.hyperdrive]` entries, by capability name.
38pub type HyperdriveDeployConfig = BTreeMap<String, HyperdriveDeploy>;
39
40/// The `[dev.hyperdrive]` entries, by capability name: the environment
41/// variable `bynk dev` reads each connection string from.
42pub type HyperdriveDevConfig = BTreeMap<String, String>;
43
44/// The keys of a `[deploy.hyperdrive.<Capability>]` entry.
45pub const DEPLOY_ENTRY_KEYS: &[&str] = &["connection_env", "config_id"];
46
47/// The keys of a `[dev.hyperdrive.<Capability>]` entry.
48pub const DEV_ENTRY_KEYS: &[&str] = &["connection_env"];
49
50fn bad(table: &'static str, capability: &str, reason: String) -> ProjectPathsError {
51    ProjectPathsError::BadHyperdrive {
52        table,
53        capability: capability.to_string(),
54        reason,
55    }
56}
57
58/// Whether `name` can be an environment variable's name: a letter or `_`,
59/// then letters, digits and `_`. A value that is not (`postgres://…`) is a
60/// connection string written where a variable's name belongs, which the
61/// reader refuses without ever echoing it.
62pub fn is_env_var_name(name: &str) -> bool {
63    let mut chars = name.chars();
64    chars
65        .next()
66        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
67        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
68}
69
70/// Whether `id` is shaped like a Hyperdrive config id: 32 hexadecimal
71/// characters. It goes into an authenticated API path, so nothing else (a `/`,
72/// `?` or `..`) may reach it.
73pub fn is_config_id(id: &str) -> bool {
74    id.len() == 32 && id.chars().all(|c| c.is_ascii_hexdigit())
75}
76
77/// `connection_env`'s value, checked. The refusal never repeats the value: a
78/// connection string pasted here would otherwise be printed by the error.
79fn connection_env(
80    table: &'static str,
81    capability: &str,
82    value: &toml::Value,
83) -> Result<String, ProjectPathsError> {
84    let Some(name) = value.as_str() else {
85        return Err(bad(
86            table,
87            capability,
88            "`connection_env` must be a string naming an environment variable".to_string(),
89        ));
90    };
91    if !is_env_var_name(name) {
92        return Err(bad(
93            table,
94            capability,
95            "`connection_env` names the environment variable the connection string is read from, \
96             not the string itself (a name is letters, digits and `_`)"
97                .to_string(),
98        ));
99    }
100    Ok(name.to_string())
101}
102
103/// The entries of `hyperdrive` (a table of capability name to entry), each
104/// checked against `keys`. `table` is `deploy` or `dev`.
105fn entries<'a>(
106    table: &'static str,
107    parent: &'a toml::Table,
108) -> Result<Option<&'a toml::Table>, ProjectPathsError> {
109    let Some(value) = parent.get("hyperdrive") else {
110        return Ok(None);
111    };
112    value.as_table().map(Some).ok_or_else(|| {
113        bad(
114            table,
115            "…",
116            format!(
117                "`hyperdrive` must be a table of capabilities, like `[{table}.hyperdrive.Main]`"
118            ),
119        )
120    })
121}
122
123fn entry_table<'a>(
124    table: &'static str,
125    capability: &str,
126    value: &'a toml::Value,
127    keys: &[&str],
128) -> Result<&'a toml::Table, ProjectPathsError> {
129    let entry = value
130        .as_table()
131        .ok_or_else(|| bad(table, capability, "must be a table".to_string()))?;
132    for key in entry.keys() {
133        if !keys.contains(&key.as_str()) {
134            let hint = did_you_mean(key, keys.iter().copied())
135                .map(|k| format!(" — did you mean `{k}`?"))
136                .unwrap_or_default();
137            return Err(bad(
138                table,
139                capability,
140                format!(
141                    "has no key named `{key}`{hint} (its keys are {})",
142                    keys.iter()
143                        .map(|k| format!("`{k}`"))
144                        .collect::<Vec<_>>()
145                        .join(" and ")
146                ),
147            ));
148        }
149    }
150    Ok(entry)
151}
152
153/// The `[deploy]` table's `hyperdrive` entries.
154pub fn deploy_hyperdrive_from(
155    deploy: &toml::Table,
156) -> Result<HyperdriveDeployConfig, ProjectPathsError> {
157    let mut out = HyperdriveDeployConfig::new();
158    let Some(all) = entries("deploy", deploy)? else {
159        return Ok(out);
160    };
161    for (capability, value) in all {
162        let entry = entry_table("deploy.hyperdrive", capability, value, DEPLOY_ENTRY_KEYS)?;
163        let mut deploy = HyperdriveDeploy::default();
164        if let Some(v) = entry.get("connection_env") {
165            deploy.connection_env = Some(connection_env("deploy.hyperdrive", capability, v)?);
166        }
167        if let Some(v) = entry.get("config_id") {
168            let ids = v.as_table().ok_or_else(|| {
169                bad(
170                    "deploy.hyperdrive",
171                    capability,
172                    "`config_id` must be a table of environment to Hyperdrive config id, \
173                     like `config_id = { default = \"…\" }`"
174                        .to_string(),
175                )
176            })?;
177            for (environment, id) in ids {
178                let id = id.as_str().filter(|s| is_config_id(s)).ok_or_else(|| {
179                    bad(
180                        "deploy.hyperdrive",
181                        capability,
182                        format!(
183                            "`config_id.{environment}` must be a Hyperdrive config id: 32 hexadecimal characters, as `wrangler hyperdrive list` shows"
184                        ),
185                    )
186                })?;
187                deploy.config_id.insert(environment.clone(), id.to_string());
188            }
189        }
190        if deploy.connection_env.is_none() && deploy.config_id.is_empty() {
191            return Err(bad(
192                "deploy.hyperdrive",
193                capability,
194                "needs a `connection_env`, a `config_id`, or both".to_string(),
195            ));
196        }
197        out.insert(capability.clone(), deploy);
198    }
199    Ok(out)
200}
201
202/// The `[dev]` table's `hyperdrive` entries.
203pub fn dev_hyperdrive_from(dev: &toml::Table) -> Result<HyperdriveDevConfig, ProjectPathsError> {
204    let mut out = HyperdriveDevConfig::new();
205    let Some(all) = entries("dev", dev)? else {
206        return Ok(out);
207    };
208    for (capability, value) in all {
209        let entry = entry_table("dev.hyperdrive", capability, value, DEV_ENTRY_KEYS)?;
210        let Some(v) = entry.get("connection_env") else {
211            return Err(bad(
212                "dev.hyperdrive",
213                capability,
214                "needs a `connection_env`".to_string(),
215            ));
216        };
217        out.insert(
218            capability.clone(),
219            connection_env("dev.hyperdrive", capability, v)?,
220        );
221    }
222    Ok(out)
223}
224
225fn table_of(
226    project_root: &Path,
227    overlay: &HashMap<PathBuf, String>,
228    name: &str,
229) -> Result<Option<toml::Table>, ProjectPathsError> {
230    let Ok(content) = read_source(&project_root.join("bynk.toml"), overlay) else {
231        return Ok(None);
232    };
233    let doc = content
234        .parse::<toml::Table>()
235        .map_err(|_| ProjectPathsError::Malformed)?;
236    Ok(doc.get(name).and_then(|v| v.as_table()).cloned())
237}
238
239/// Read `bynk.toml`'s `[deploy.hyperdrive]` entries, honouring `overlay`. No
240/// manifest, or none of the table, is empty.
241pub fn try_read_hyperdrive_deploy_with(
242    project_root: &Path,
243    overlay: &HashMap<PathBuf, String>,
244) -> Result<HyperdriveDeployConfig, ProjectPathsError> {
245    match table_of(project_root, overlay, "deploy")? {
246        Some(t) => deploy_hyperdrive_from(&t),
247        None => Ok(HyperdriveDeployConfig::new()),
248    }
249}
250
251/// [`try_read_hyperdrive_deploy_with`], reading `bynk.toml` from disk.
252pub fn try_read_hyperdrive_deploy(
253    project_root: &Path,
254) -> Result<HyperdriveDeployConfig, ProjectPathsError> {
255    try_read_hyperdrive_deploy_with(project_root, &disk_overlay(project_root))
256}
257
258/// `bynk.toml` as the overlay a reader takes: [`read_source`] consults the
259/// overlay, not the disk.
260fn disk_overlay(project_root: &Path) -> HashMap<PathBuf, String> {
261    let path = project_root.join("bynk.toml");
262    match std::fs::read_to_string(&path) {
263        Ok(text) => HashMap::from([(path, text)]),
264        Err(_) => HashMap::new(),
265    }
266}
267
268/// Read `bynk.toml`'s `[dev.hyperdrive]` entries, honouring `overlay`.
269pub fn try_read_hyperdrive_dev_with(
270    project_root: &Path,
271    overlay: &HashMap<PathBuf, String>,
272) -> Result<HyperdriveDevConfig, ProjectPathsError> {
273    match table_of(project_root, overlay, "dev")? {
274        Some(t) => dev_hyperdrive_from(&t),
275        None => Ok(HyperdriveDevConfig::new()),
276    }
277}
278
279/// [`try_read_hyperdrive_dev_with`], reading `bynk.toml` from disk.
280pub fn try_read_hyperdrive_dev(
281    project_root: &Path,
282) -> Result<HyperdriveDevConfig, ProjectPathsError> {
283    try_read_hyperdrive_dev_with(project_root, &disk_overlay(project_root))
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    fn deploy(text: &str) -> Result<HyperdriveDeployConfig, String> {
291        let doc: toml::Table = text.parse().unwrap();
292        deploy_hyperdrive_from(doc["deploy"].as_table().unwrap()).map_err(|e| e.to_string())
293    }
294
295    fn dev(text: &str) -> Result<HyperdriveDevConfig, String> {
296        let doc: toml::Table = text.parse().unwrap();
297        dev_hyperdrive_from(doc["dev"].as_table().unwrap()).map_err(|e| e.to_string())
298    }
299
300    #[test]
301    fn a_deploy_entry_names_a_variable_and_per_environment_ids() {
302        let config = deploy(
303            "[deploy.hyperdrive.Main]\nconnection_env = \"MAIN_DATABASE_URL\"\n\
304             config_id = { production = \"0123456789abcdef0123456789abcdef\" }\n",
305        )
306        .unwrap();
307        let main = &config["Main"];
308        assert_eq!(main.connection_env.as_deref(), Some("MAIN_DATABASE_URL"));
309        assert_eq!(
310            main.config_id["production"],
311            "0123456789abcdef0123456789abcdef"
312        );
313    }
314
315    #[test]
316    fn an_entry_with_neither_a_variable_nor_an_id_is_refused() {
317        let message = deploy("[deploy.hyperdrive.Main]\n").unwrap_err();
318        assert!(message.contains("`[deploy.hyperdrive.Main]`"), "{message}");
319        assert!(message.contains("connection_env"), "{message}");
320    }
321
322    #[test]
323    fn an_unknown_key_suggests_the_nearest() {
324        let message = deploy("[deploy.hyperdrive.Main]\nconnection_evn = \"X\"\n").unwrap_err();
325        assert!(
326            message.contains("did you mean `connection_env`?"),
327            "{message}"
328        );
329    }
330
331    /// R-16: a connection string written where a variable's name belongs is
332    /// refused, and the refusal does not print it.
333    #[test]
334    fn a_connection_string_in_the_manifest_is_refused_without_being_echoed() {
335        let secret = "postgres://app:[email protected]:5432/app";
336        for text in [
337            format!("[deploy.hyperdrive.Main]\nconnection_env = \"{secret}\"\n"),
338            format!("[dev.hyperdrive.Main]\nconnection_env = \"{secret}\"\n"),
339        ] {
340            let doc: toml::Table = text.parse().unwrap();
341            let message = if doc.contains_key("deploy") {
342                deploy(&text)
343            } else {
344                dev(&text).map(|_| BTreeMap::new())
345            }
346            .unwrap_err();
347            assert!(message.contains("not the string itself"), "{message}");
348            assert!(
349                !message.contains("hunter2") && !message.contains("db.example.com"),
350                "{message}"
351            );
352        }
353    }
354
355    #[test]
356    fn config_id_is_a_table_of_non_empty_strings() {
357        assert!(
358            deploy("[deploy.hyperdrive.Main]\nconfig_id = \"abc\"\n")
359                .unwrap_err()
360                .contains("must be a table")
361        );
362        assert!(
363            deploy("[deploy.hyperdrive.Main]\nconfig_id = { staging = \"\" }\n")
364                .unwrap_err()
365                .contains("`config_id.staging` must be a Hyperdrive config id")
366        );
367        for bad in [
368            "../../workers/scripts/x",
369            "x?foo=",
370            "abc",
371            "0123456789abcdef0123456789abcdeg",
372            "0123456789abcdef0123456789abcdef/",
373        ] {
374            let text = format!("[deploy.hyperdrive.Main]\nconfig_id = {{ staging = \"{bad}\" }}\n");
375            assert!(deploy(&text).is_err(), "{bad} is not a config id");
376        }
377    }
378
379    #[test]
380    fn a_dev_entry_names_a_variable() {
381        assert_eq!(
382            dev("[dev.hyperdrive.Main]\nconnection_env = \"LOCAL_URL\"\n").unwrap()["Main"],
383            "LOCAL_URL"
384        );
385        assert!(
386            dev("[dev.hyperdrive.Main]\n")
387                .unwrap_err()
388                .contains("needs a `connection_env`")
389        );
390        assert!(
391            dev("[dev.hyperdrive.Main]\nconfig_id = { default = \"a\" }\n")
392                .unwrap_err()
393                .contains("has no key named `config_id`")
394        );
395    }
396
397    #[test]
398    fn the_disk_readers_read_bynk_toml() {
399        let root = std::env::temp_dir().join(format!("bynk-hd-read-{}", std::process::id()));
400        std::fs::create_dir_all(&root).unwrap();
401        std::fs::write(
402            root.join("bynk.toml"),
403            "[deploy.hyperdrive.Main]\nconnection_env = \"A\"\n\n[dev.hyperdrive.Main]\nconnection_env = \"B\"\n",
404        )
405        .unwrap();
406        assert_eq!(
407            try_read_hyperdrive_deploy(&root).unwrap()["Main"]
408                .connection_env
409                .as_deref(),
410            Some("A")
411        );
412        assert_eq!(try_read_hyperdrive_dev(&root).unwrap()["Main"], "B");
413        assert!(
414            try_read_hyperdrive_dev(&root.join("missing"))
415                .unwrap()
416                .is_empty()
417        );
418    }
419
420    #[test]
421    fn variable_names_are_checked() {
422        assert!(is_env_var_name("MAIN_DATABASE_URL"));
423        assert!(is_env_var_name("_x1"));
424        assert!(!is_env_var_name(""));
425        assert!(!is_env_var_name("1X"));
426        assert!(!is_env_var_name("A-B"));
427        assert!(!is_env_var_name("postgres://x"));
428    }
429}