Skip to main content

schedr_agent/
connection_env.rs

1//! What a command gets of a connection (decisions 184, 190-192): `PREFIX_*` variables, and
2//! the files its tools read (curl's `-K` config, an SSH key and config, Postgres's
3//! `.pgpass`, a MySQL option file), written in the attempt's folder.
4//!
5//! A secret goes into its tool's file and into a variable for scripts; a URL variable never
6//! holds a password (`psql "$DB_URL"` puts none on a command line). What a command gets
7//! verifies TLS as the Python clients do (decision 191): SQL's `sslmode=verify-full`,
8//! Mongo's `tls=true`, SSH only its `known_hosts`. Only prefixed names (decision 192).
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::fmt::Write as _;
12use std::fs::{DirBuilder, OpenOptions};
13use std::io::Write as _;
14use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};
15use std::path::{Path, PathBuf};
16
17use schedr_model::Encoding;
18use schedr_model::connection::ConnectionType;
19use serde_json::{Map, Value};
20
21#[cfg(test)]
22mod tests;
23
24/// A connection as a command gets it, before it is written.
25#[derive(Debug, Default, PartialEq, Eq)]
26pub struct View {
27    /// The variables, by name after `PREFIX_` (`URL`, `PGPASSFILE`).
28    pub variables: BTreeMap<String, String>,
29    /// The files, by name in the connection's folder, with their contents.
30    pub files: BTreeMap<String, String>,
31    /// Forms of secrets the masker doesn't know, each with what it came from: a password
32    /// taken out of a URL, one escaped for a tool's file (`.pgpass`'s `\:`). Masked when what
33    /// it came from is.
34    pub derived: Vec<(String, String)>,
35}
36
37impl View {
38    /// Records `form`, written from `source`, for the masker.
39    fn derive(&mut self, source: &str, form: &str) {
40        if form != source && !form.is_empty() {
41            self.derived.push((source.to_owned(), form.to_owned()));
42        }
43    }
44
45    fn var(&mut self, suffix: &str, value: impl Into<String>) {
46        self.variables.insert(suffix.to_owned(), value.into());
47    }
48
49    /// Adds the file `name` and the variable `suffix` holding its path.
50    fn file(&mut self, dir: &Path, suffix: &str, name: &str, contents: String) -> String {
51        let path = dir.join(name).to_string_lossy().into_owned();
52        self.files.insert(name.to_owned(), contents);
53        self.var(suffix, path.clone());
54        path
55    }
56}
57
58/// The view of a connection of type `kind` (a `@connection` function's: `None`), its values
59/// rendered and shown as plain JSON, its files to go in `dir`.
60///
61/// # Errors
62///
63/// A value a tool's file can't hold (a quote in an SSH config's value), a password given
64/// twice, a parameter that can't be a variable's name.
65pub fn view(
66    kind: Option<ConnectionType>,
67    values: &Map<String, Value>,
68    dir: &Path,
69) -> Result<View, String> {
70    let mut view = View::default();
71    match kind {
72        Some(ConnectionType::Http) => http(values, dir, &mut view)?,
73        Some(ConnectionType::Ssh) => ssh(values, dir, &mut view)?,
74        Some(ConnectionType::Mongo) => mongo(values, dir, &mut view)?,
75        Some(ConnectionType::Sql) => sql(values, dir, &mut view)?,
76        Some(ConnectionType::Generic | ConnectionType::Schedr) | None => own(values, &mut view)?,
77    }
78    let json = Value::Object(values.clone()).to_string();
79    view.file(dir, "JSON", "connection.json", json);
80    Ok(view)
81}
82
83/// Writes `view`'s files in `dir` (mode 0700; each file 0600), and gives its variables, named
84/// `PREFIX_...`.
85///
86/// # Errors
87///
88/// A file that can't be written.
89pub fn write(view: &View, prefix: &str, dir: &Path) -> Result<BTreeMap<String, String>, String> {
90    let failed =
91        |e: std::io::Error| format!("can't write a connection file in {}: {e}", dir.display());
92    DirBuilder::new()
93        .recursive(true)
94        .mode(0o700)
95        .create(dir)
96        .map_err(failed)?;
97    for (name, contents) in &view.files {
98        // Written aside, then renamed over: a process reading the file (the same connection
99        // asked for again) reads the old one or the new one whole, and a file someone made
100        // there first is replaced, never reused with its own mode.
101        let aside = dir.join(format!(".{name}.{}", unique()));
102        let mut file = OpenOptions::new()
103            .write(true)
104            .create_new(true)
105            .mode(0o600)
106            .open(&aside)
107            .map_err(failed)?;
108        let written = file
109            .write_all(contents.as_bytes())
110            .and_then(|()| std::fs::rename(&aside, dir.join(name)));
111        if let Err(e) = written {
112            let _ = std::fs::remove_file(&aside);
113            return Err(failed(e));
114        }
115    }
116    Ok(view
117        .variables
118        .iter()
119        .map(|(suffix, value)| (format!("{prefix}_{suffix}"), value.clone()))
120        .collect())
121}
122
123/// A name no other write in this process uses: the process and a counter.
124fn unique() -> String {
125    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
126    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
127    format!("{}-{n}", std::process::id())
128}
129
130/// Where a worker writes its commands' connection files when `[worker] connection_dir`
131/// isn't set (decision 201): in memory, under `shm` (`/dev/shm`) when it is a folder, in a
132/// folder of the user's own named after the data directory (so workers of one user sharing
133/// an ID, a standalone's and a worker's, never sweep each other's); else the data directory.
134#[must_use]
135pub fn default_dir(data_dir: &Path, shm: &Path, uid: u32) -> PathBuf {
136    if shm.is_dir() {
137        use sha2::Digest as _;
138        let digest = sha2::Sha256::digest(data_dir.as_os_str().as_encoded_bytes());
139        let mut name = String::new();
140        for byte in &digest[..8] {
141            let _ = write!(name, "{byte:02x}");
142        }
143        shm.join(format!("schedr-{uid}")).join(name)
144    } else {
145        data_dir.join("connections")
146    }
147}
148
149/// Makes `dir` (a worker's connection folder) and the folder holding it, mode 0700, before
150/// the worker starts (decision 201), and checks the whole path. In a folder others can write
151/// in (`/dev/shm`), another user could have made a folder on it first, or a link, and swap
152/// what is below: the secrets would go where they can read them. So every folder on the path
153/// must be the user's or root's, closed to others' writes unless sticky (`/dev/shm`, `/tmp`),
154/// and to group writes unless the group is the user's own; a link on it must be root's
155/// (`/var/run`); the last two folders the user's alone, mode 0700.
156///
157/// # Errors
158///
159/// A folder that can't be made, or a path someone else could change.
160pub fn prepare(dir: &Path) -> Result<(), String> {
161    use std::os::unix::fs::MetadataExt as _;
162    let uid = rustix::process::geteuid().as_raw();
163    let gid = rustix::process::getegid().as_raw();
164    let parent = dir.parent().ok_or_else(|| {
165        format!(
166            "{}: a connection folder has a folder above it",
167            dir.display()
168        )
169    })?;
170    if let Some(above) = parent.parent() {
171        std::fs::create_dir_all(above)
172            .map_err(|e| format!("can't make {}: {e}", above.display()))?;
173    }
174    for folder in [parent, dir] {
175        match DirBuilder::new().mode(0o700).create(folder) {
176            Ok(()) => {}
177            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
178            Err(e) => return Err(format!("can't make {}: {e}", folder.display())),
179        }
180    }
181    let refuse = |path: &Path, why: &str| {
182        Err(format!(
183            "{} {why}: connection files (secrets) can't go below it; remove it, or set \
184             [worker] connection_dir",
185            path.display()
186        ))
187    };
188    let mut walked = PathBuf::new();
189    for component in dir.components() {
190        walked.push(component);
191        let meta = std::fs::symlink_metadata(&walked)
192            .map_err(|e| format!("can't read {}: {e}", walked.display()))?;
193        let private = walked == parent || walked == dir;
194        let mode = meta.mode();
195        if meta.file_type().is_symlink() {
196            if private || meta.uid() != 0 {
197                return refuse(&walked, "is a link another user could have made");
198            }
199            continue;
200        }
201        if !meta.file_type().is_dir() {
202            return refuse(&walked, "isn't a folder");
203        }
204        if private {
205            if meta.uid() != uid || mode & 0o077 != 0 {
206                return refuse(
207                    &walked,
208                    &format!(
209                        "must be the worker's user's alone, mode 0700 (it is uid {}, mode {:o})",
210                        meta.uid(),
211                        mode & 0o7777
212                    ),
213                );
214            }
215            continue;
216        }
217        let sticky = mode & 0o1000 != 0;
218        let owned = meta.uid() == uid || meta.uid() == 0;
219        let others_write = mode & 0o002 != 0 && !sticky;
220        let group_write = mode & 0o020 != 0 && meta.gid() != gid && !sticky;
221        if !owned || others_write || group_write {
222            return refuse(
223                &walked,
224                &format!(
225                    "can be changed by another user (uid {}, gid {}, mode {:o})",
226                    meta.uid(),
227                    meta.gid(),
228                    mode & 0o7777
229                ),
230            );
231        }
232    }
233    Ok(())
234}
235
236/// The folder of the connection given as `prefix` in an attempt's folder.
237#[must_use]
238pub fn folder(attempt_dir: &Path, prefix: &str) -> PathBuf {
239    attempt_dir.join(prefix)
240}
241
242/// A value as text: text as it is, a number or a flag as JSON; `None` when absent or null.
243fn text(values: &Map<String, Value>, key: &str) -> Option<String> {
244    match values.get(key)? {
245        Value::Null => None,
246        Value::String(text) => Some(text.clone()),
247        other => Some(other.to_string()),
248    }
249}
250
251fn required(values: &Map<String, Value>, key: &str) -> Result<String, String> {
252    text(values, key).ok_or_else(|| format!("`{key}` has no value"))
253}
254
255/// A timeout's whole seconds, at least 1, as tools take it.
256fn seconds(values: &Map<String, Value>) -> Option<u64> {
257    let timeout = values.get("timeout")?.as_f64()?;
258    // Seconds as a tool takes them, rounded up; a timeout is never negative or huge.
259    #[expect(
260        clippy::cast_possible_truncation,
261        clippy::cast_sign_loss,
262        reason = "rounded, clamped"
263    )]
264    Some(timeout.ceil().clamp(1.0, 86_400.0) as u64)
265}
266
267/// A curl config value's inside: `\` and `"` escaped.
268fn curl_escaped(text: &str) -> String {
269    text.replace('\\', "\\\\").replace('"', "\\\"")
270}
271
272/// A curl config value: double-quoted. A line break is refused: curl turns `\n` back into
273/// one, and in a header that is another header (`token\r\nX-Admin: yes`).
274fn curl_quoted(what: &str, text: &str) -> Result<String, String> {
275    if text.contains(['\n', '\r', '\0']) {
276        return Err(format!(
277            "`{what}` has a line break: curl's config would send it as more of the request"
278        ));
279    }
280    Ok(format!("\"{}\"", curl_escaped(text)))
281}
282
283/// A URL with its user and password taken out (`https://u:p@h/x` gives `https://h/x`, `u`,
284/// `p`), decoded.
285fn without_userinfo(url: &str) -> (String, Option<String>, Option<String>) {
286    let Some((scheme, rest)) = url.split_once("://") else {
287        return (url.to_owned(), None, None);
288    };
289    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
290    let Some(at) = rest[..end].rfind('@') else {
291        return (url.to_owned(), None, None);
292    };
293    let (user, password) = match rest[..at].split_once(':') {
294        Some((user, password)) => (decoded(user), Some(decoded(password))),
295        None => (decoded(&rest[..at]), None),
296    };
297    let user = Some(user).filter(|user| !user.is_empty());
298    (format!("{scheme}://{}", &rest[at + 1..]), user, password)
299}
300
301fn http(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
302    let source = required(values, "base_url")?;
303    // A user and a password in the URL go to curl's config, never a command line.
304    let (base_url, url_user, url_password) = without_userinfo(&source);
305    let mut user = text(values, "user");
306    let mut password = text(values, "password");
307    if url_user.is_some() || url_password.is_some() {
308        if user.is_some() || password.is_some() || values.get("token").is_some_and(|t| !t.is_null())
309        {
310            return Err(
311                "a user in `base_url` and `user=`, `password=` or `token=`: give it once"
312                    .to_owned(),
313            );
314        }
315        if let Some(from_url) = &url_password {
316            view.derive(&source, from_url);
317        }
318        user = url_user;
319        password = url_password;
320    }
321    view.var("BASE_URL", base_url);
322    let mut config = String::new();
323    if let Some(token) = text(values, "token") {
324        let header = curl_quoted("token", &format!("Authorization: Bearer {token}"))?;
325        let _ = writeln!(config, "header = {header}");
326        view.derive(&token, &curl_escaped(&token));
327        view.var("TOKEN", token);
328    }
329    if let Some(user) = user {
330        let given = password.clone().unwrap_or_default();
331        let login = curl_quoted("user", &format!("{user}:{given}"))?;
332        let _ = writeln!(config, "user = {login}");
333        view.derive(&given, &curl_escaped(&given));
334        view.var("USER", user);
335        if let Some(password) = password {
336            view.var("PASSWORD", password);
337        }
338    }
339    if let Some(Value::Object(headers)) = values.get("headers") {
340        for (name, value) in headers {
341            let value = value
342                .as_str()
343                .map_or_else(|| value.to_string(), str::to_owned);
344            let header = curl_quoted(&format!("headers[{name:?}]"), &format!("{name}: {value}"))?;
345            let _ = writeln!(config, "header = {header}");
346            view.derive(&value, &curl_escaped(&value));
347        }
348    }
349    if let Some(ca) = text(values, "ca_cert") {
350        let path = view.file(dir, "CA_FILE", "ca.pem", ca);
351        let _ = writeln!(config, "cacert = {}", curl_quoted("ca file", &path)?);
352    }
353    if let Some(cert) = text(values, "client_cert") {
354        let path = view.file(dir, "CERT_FILE", "client-cert.pem", cert);
355        let _ = writeln!(config, "cert = {}", curl_quoted("cert file", &path)?);
356    }
357    if let Some(key) = text(values, "client_key") {
358        let path = view.file(dir, "KEY_FILE", "client-key.pem", key);
359        let _ = writeln!(config, "key = {}", curl_quoted("key file", &path)?);
360    }
361    if let Some(seconds) = seconds(values) {
362        let _ = writeln!(config, "connect-timeout = {seconds}");
363    }
364    view.file(dir, "CURL_CONFIG", "curl.config", config);
365    Ok(())
366}
367
368/// An SSH config value: double-quoted (spaces kept), `%` written `%%` where `escape` (the
369/// keywords OpenSSH expands tokens in). OpenSSH has no escape for `"` or a line break.
370fn ssh_value(what: &str, text: &str, escape: bool) -> Result<String, String> {
371    if text.contains(['"', '\n', '\r', '\0']) {
372        return Err(format!(
373            "`{what}` can't be written in an SSH config (a quote or a line break in it)"
374        ));
375    }
376    let text = if escape {
377        text.replace('%', "%%")
378    } else {
379        text.to_owned()
380    };
381    Ok(format!("\"{text}\""))
382}
383
384fn ssh(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
385    let host = required(values, "host")?;
386    let user = required(values, "user")?;
387    let port = text(values, "port").unwrap_or_else(|| "22".to_owned());
388    let mut config = String::from("Host target\n");
389    let _ = writeln!(config, "  HostName {}", ssh_value("host", &host, true)?);
390    let _ = writeln!(config, "  Port {}", ssh_value("port", &port, false)?);
391    let _ = writeln!(config, "  User {}", ssh_value("user", &user, false)?);
392    view.var("HOST", host);
393    view.var("PORT", port);
394    view.var("USER", user);
395    if let Some(mut key) = text(values, "private_key") {
396        // OpenSSH refuses a key without its last line break ("invalid format").
397        if !key.ends_with('\n') {
398            key.push('\n');
399        }
400        let path = view.file(dir, "KEY_FILE", "id_key", key);
401        let _ = writeln!(
402            config,
403            "  IdentityFile {}",
404            ssh_value("key file", &path, true)?
405        );
406        config.push_str("  IdentitiesOnly yes\n");
407    }
408    if let Some(passphrase) = text(values, "passphrase") {
409        view.var("KEY_PASSPHRASE", passphrase);
410    }
411    let password = text(values, "password");
412    let insecure = values
413        .get("insecure_skip_host_check")
414        .and_then(Value::as_bool)
415        .unwrap_or(false);
416    if insecure {
417        // As the definition says, loudly: any key is taken.
418        config.push_str("  StrictHostKeyChecking no\n  UserKnownHostsFile /dev/null\n");
419    } else {
420        let known = required(values, "known_hosts")?;
421        let path = view.file(dir, "KNOWN_HOSTS", "known_hosts", known);
422        let _ = writeln!(
423            config,
424            "  UserKnownHostsFile {}",
425            ssh_value("known_hosts file", &path, true)?
426        );
427        // Only its own keys: the machine's own aren't the connection's.
428        config.push_str("  GlobalKnownHostsFile /dev/null\n  StrictHostKeyChecking yes\n");
429    }
430    if password.is_none() {
431        // Nothing to type: a prompt would hang the task.
432        config.push_str("  BatchMode yes\n");
433    }
434    if let Some(password) = password {
435        view.var("PASSWORD", password);
436    }
437    if let Some(seconds) = seconds(values) {
438        let _ = writeln!(config, "  ConnectTimeout {seconds}");
439    }
440    view.file(dir, "SSH_CONFIG", "ssh_config", config);
441    Ok(())
442}
443
444/// A URL's parts, as far as a command's view needs them; the authority may list several
445/// hosts (`mongodb://h1:27017,h2:27017/`), which URL parsers refuse.
446struct UrlParts {
447    scheme: String,
448    user: Option<String>,
449    password: Option<String>,
450    hosts: String,
451    /// From the `/` after the hosts to the query, `/` included (empty when none).
452    path: String,
453    /// The query's pairs, decoded, in order.
454    query: Vec<(String, String)>,
455}
456
457impl UrlParts {
458    fn parse(url: &str) -> Result<Self, String> {
459        let (scheme, rest) = url
460            .split_once("://")
461            .ok_or_else(|| "the URL has no `scheme://`".to_owned())?;
462        let rest = rest.split('#').next().unwrap_or_default();
463        let (before_query, query) = rest.split_once('?').unwrap_or((rest, ""));
464        let (authority, path) = match before_query.find('/') {
465            Some(at) => before_query.split_at(at),
466            None => (before_query, ""),
467        };
468        let (userinfo, hosts) = match authority.rfind('@') {
469            Some(at) => (Some(&authority[..at]), &authority[at + 1..]),
470            None => (None, authority),
471        };
472        let (user, password) = match userinfo {
473            None => (None, None),
474            Some(info) => match info.split_once(':') {
475                Some((user, password)) => (Some(decoded(user)), Some(decoded(password))),
476                None => (Some(decoded(info)), None),
477            },
478        };
479        let query = query
480            .split('&')
481            .filter(|pair| !pair.is_empty())
482            .map(|pair| {
483                let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
484                (decoded(key), decoded(value))
485            })
486            .collect();
487        Ok(Self {
488            scheme: scheme.to_owned(),
489            user: user.filter(|user| !user.is_empty()),
490            password,
491            hosts: hosts.to_owned(),
492            path: path.to_owned(),
493            query,
494        })
495    }
496
497    fn has(&self, key: &str) -> bool {
498        self.query.iter().any(|(k, _)| k.eq_ignore_ascii_case(key))
499    }
500
501    fn get(&self, key: &str) -> Option<&str> {
502        self.query
503            .iter()
504            .find(|(k, _)| k.eq_ignore_ascii_case(key))
505            .map(|(_, v)| v.as_str())
506    }
507
508    /// The URL again, with the user only (never a password), every value encoded.
509    fn without_password(&self) -> String {
510        let mut url = format!("{}://", self.scheme);
511        if let Some(user) = &self.user {
512            url.push_str(&Encoding::Url.apply(user));
513            url.push('@');
514        }
515        url.push_str(&self.hosts);
516        url.push_str(&self.path);
517        for (i, (key, value)) in self.query.iter().enumerate() {
518            if i == 0 && self.path.is_empty() {
519                url.push('/');
520            }
521            url.push(if i == 0 { '?' } else { '&' });
522            url.push_str(&Encoding::Url.apply(key));
523            url.push('=');
524            url.push_str(&Encoding::Url.apply(value));
525        }
526        url
527    }
528}
529
530/// Percent-decoded text (`%40` an `@`); a `%` not followed by two hex digits kept.
531fn decoded(text: &str) -> String {
532    let bytes = text.as_bytes();
533    let mut out = Vec::with_capacity(bytes.len());
534    let mut i = 0;
535    while i < bytes.len() {
536        let hex = |b: u8| char::from(b).to_digit(16);
537        if bytes[i] == b'%'
538            && let (Some(high), Some(low)) = (
539                bytes.get(i + 1).copied().and_then(hex),
540                bytes.get(i + 2).copied().and_then(hex),
541            )
542        {
543            // Two hex digits: one byte.
544            #[expect(clippy::cast_possible_truncation, reason = "two hex digits fit a byte")]
545            out.push((high * 16 + low) as u8);
546            i += 3;
547        } else {
548            out.push(bytes[i]);
549            i += 1;
550        }
551    }
552    String::from_utf8_lossy(&out).into_owned()
553}
554
555/// The user and the password, each from its own value or the URL's, given once.
556fn credentials(
557    values: &Map<String, Value>,
558    source: &str,
559    url: &mut UrlParts,
560    view: &mut View,
561) -> Result<(Option<String>, Option<String>), String> {
562    let user = text(values, "user");
563    let password = text(values, "password");
564    if let Some(from_url) = &url.password {
565        // Taken out of a URL a secret holds whole: the masker knows the URL, not it.
566        view.derive(source, from_url);
567    }
568    if url.password.is_some() && password.is_some() {
569        return Err("a password in the URL and `password=` both: give it once".to_owned());
570    }
571    if url.user.is_some() && user.is_some() {
572        return Err("a user in the URL and `user=` both: give it once".to_owned());
573    }
574    if user.is_some() {
575        url.user.clone_from(&user);
576    }
577    Ok((url.user.clone(), password.or_else(|| url.password.take())))
578}
579
580fn mongo(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
581    let source = required(values, "uri")?;
582    let mut url = UrlParts::parse(&source)?;
583    let (user, password) = credentials(values, &source, &mut url, view)?;
584    url.password = None;
585    refuse_secret_query(&url)?;
586    let database = required(values, "database")?;
587    // The database in the path, as the Python client's `client[database]`; a path's database
588    // is also the one a user logs in on unless `authSource` says, so it is said: the URI's
589    // own, else its path's, else `admin`, as pymongo takes it.
590    let written = decoded(url.path.trim_start_matches('/'));
591    let auth_source = url.get("authSource").map_or_else(
592        || {
593            if written.is_empty() {
594                "admin".to_owned()
595            } else {
596                written.clone()
597            }
598        },
599        str::to_owned,
600    );
601    if user.is_some() && !url.has("authSource") {
602        url.query
603            .push(("authSource".to_owned(), auth_source.clone()));
604    }
605    url.path = format!("/{}", Encoding::Url.apply(&database));
606    // TLS, verified, unless the URI says otherwise (decision 191, as 189).
607    if !url.has("tls") && !url.has("ssl") {
608        url.query.push(("tls".to_owned(), "true".to_owned()));
609    }
610    if let Some(ca) = text(values, "ca_cert") {
611        let path = view.file(dir, "CA_FILE", "ca.pem", ca);
612        if !url.has("tlsCAFile") {
613            url.query.push(("tlsCAFile".to_owned(), path));
614        }
615    }
616    // The database tools (`mongodump --config`, decision 194) read the user from the URI and
617    // the password from the file; mongosh would prompt for a user's password, hanging the
618    // task, so its URI names none (it logs in with `db.auth` from the variables).
619    let mut tools = format!("uri: {}\n", Value::from(url.without_password()));
620    if let Some(password) = &password {
621        let _ = writeln!(tools, "password: {}", Value::from(password.as_str()));
622    }
623    url.user = None;
624    view.var("URI", url.without_password());
625    view.file(dir, "TOOLS_CONFIG", "mongo-tools.yaml", tools);
626    view.var("DATABASE", database);
627    view.var("AUTH_SOURCE", auth_source);
628    if let Some(user) = user {
629        view.var("USER", user);
630    }
631    if let Some(password) = password {
632        view.var("PASSWORD", password);
633    }
634    Ok(())
635}
636
637/// A `.pgpass` field: `\` and `:` escaped. A line break is refused: the file is one entry per
638/// line, so libpq would read the password up to it.
639fn pgpass_field(text: &str) -> Result<String, String> {
640    if text.contains(['\n', '\r', '\0']) {
641        return Err(
642            "the password has a line break or a NUL, which `.pgpass` can't hold: read \
643             `_PASSWORD` instead"
644                .to_owned(),
645        );
646    }
647    Ok(text.replace('\\', "\\\\").replace(':', "\\:"))
648}
649
650/// A MySQL option file value's inside: `\` and `"` escaped, a line break `\n`, `\r`.
651fn cnf_escaped(text: &str) -> String {
652    text.replace('\\', "\\\\")
653        .replace('"', "\\\"")
654        .replace('\n', "\\n")
655        .replace('\r', "\\r")
656}
657
658/// A MySQL option file value: double-quoted. A NUL is refused: the clients end the value
659/// there and skip the next line, which could be the TLS mode.
660fn cnf_quoted(what: &str, text: &str) -> Result<String, String> {
661    if text.contains('\0') {
662        return Err(format!(
663            "`{what}` has a NUL, which MySQL's option file can't hold"
664        ));
665    }
666    Ok(format!("\"{}\"", cnf_escaped(text)))
667}
668
669/// Refuses a secret written as a URL's query key (`?sslpassword=`): a URL variable goes on
670/// command lines, where anyone on the machine reads it.
671fn refuse_secret_query(url: &UrlParts) -> Result<(), String> {
672    const SECRET: [&str; 3] = ["password", "sslpassword", "tlsCertificateKeyFilePassword"];
673    match url
674        .query
675        .iter()
676        .find(|(key, _)| SECRET.iter().any(|s| key.eq_ignore_ascii_case(s)))
677    {
678        Some((key, _)) => Err(format!(
679            "`{key}=` in the URL would be on a command's command line: give the password as \
680             `password=` (or in the URL's user part)"
681        )),
682        None => Ok(()),
683    }
684}
685
686fn sql(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
687    let source = required(values, "url")?;
688    let mut url = UrlParts::parse(&source)?;
689    let (user, mut password) = credentials(values, &source, &mut url, view)?;
690    url.password = None;
691    let scheme = url
692        .scheme
693        .split('+')
694        .next()
695        .unwrap_or_default()
696        .to_ascii_lowercase();
697    // libpq takes a password as a query key too: out of the URL, as one in its user part.
698    if matches!(scheme.as_str(), "postgresql" | "postgres")
699        && let Some(at) = url.query.iter().position(|(k, _)| k == "password")
700    {
701        let (_, from_query) = url.query.remove(at);
702        if password.is_some() {
703            return Err("a password in the URL and `password=` both: give it once".to_owned());
704        }
705        view.derive(&source, &from_query);
706        password = Some(from_query);
707    }
708    refuse_secret_query(&url)?;
709    let mode = url.get("sslmode").unwrap_or("verify-full").to_owned();
710    let ca = text(values, "ca_cert").map(|ca| view.file(dir, "CA_FILE", "ca.pem", ca));
711    if let Some(user) = &user {
712        view.var("USER", user.clone());
713    }
714    if let Some(password) = &password {
715        view.var("PASSWORD", password.clone());
716    }
717    match scheme.as_str() {
718        "postgresql" | "postgres" => {
719            // TLS, verified, unless the URL says otherwise (decision 191, as 187).
720            if !url.has("sslmode") {
721                url.query.push(("sslmode".to_owned(), mode.clone()));
722            }
723            if !url.has("sslrootcert") {
724                if let Some(ca) = &ca {
725                    url.query.push(("sslrootcert".to_owned(), ca.clone()));
726                } else if mode == "verify-full" {
727                    url.query
728                        .push(("sslrootcert".to_owned(), "system".to_owned()));
729                }
730            }
731            if let Some(password) = &password {
732                let field = pgpass_field(password)?;
733                view.derive(password, &field);
734                let path = view.file(dir, "PGPASSFILE", "pgpass", format!("*:*:*:*:{field}\n"));
735                // libpq reads it from the URL: `psql "$DB_URL"` logs in, the URL naming the
736                // file, never the password.
737                if !url.has("passfile") {
738                    url.query.push(("passfile".to_owned(), path));
739                }
740            }
741        }
742        "mysql" | "mariadb" => {
743            let login = Login {
744                user: user.as_deref(),
745                password: password.as_deref(),
746                ca: ca.as_deref(),
747            };
748            mysql(values, &url, &mode, &login, dir, view)?;
749        }
750        other => {
751            return Err(format!(
752                "the URL is postgresql://, mysql:// or mariadb://, not {other}://"
753            ));
754        }
755    }
756    view.var("URL", url.without_password());
757    Ok(())
758}
759
760/// What logs in to a database, from its own values or the URL's.
761struct Login<'a> {
762    user: Option<&'a str>,
763    password: Option<&'a str>,
764    /// The path of the CA file written (`ca_cert`).
765    ca: Option<&'a str>,
766}
767
768/// A MySQL or MariaDB database's option file, for either vendor's client (decision 195):
769/// `[client]`, read by every program of both, holds the login and MySQL's TLS as
770/// `loose-ssl-mode` (MariaDB's client skips it, with a warning); `[client-mariadb]`, read
771/// only by MariaDB's programs, holds MariaDB's TLS.
772fn mysql(
773    values: &Map<String, Value>,
774    url: &UrlParts,
775    mode: &str,
776    login: &Login<'_>,
777    dir: &Path,
778    view: &mut View,
779) -> Result<(), String> {
780    let (host, port) = host_and_port(&url.hosts, "3306");
781    let database = decoded(url.path.trim_start_matches('/'));
782    let (ssl_mode, mariadb) = match mode {
783        "disable" => ("DISABLED", "skip-ssl\n"),
784        // MariaDB's client has no "TLS if offered": it requires it.
785        "allow" | "prefer" => ("PREFERRED", "ssl\nskip-ssl-verify-server-cert\n"),
786        "require" => ("REQUIRED", "ssl\nskip-ssl-verify-server-cert\n"),
787        // MariaDB's client checks the name with the certificate, always.
788        "verify-ca" => ("VERIFY_CA", "ssl\nssl-verify-server-cert\n"),
789        _ => ("VERIFY_IDENTITY", "ssl\nssl-verify-server-cert\n"),
790    };
791    // TLS first, the login after: a value a client misreads can't take the TLS mode with it.
792    let mut cnf = String::from("[client]\n");
793    let _ = writeln!(cnf, "loose-ssl-mode = {ssl_mode}");
794    if ssl_mode.starts_with("VERIFY") {
795        match login.ca {
796            Some(ca) => {
797                let _ = writeln!(cnf, "ssl-ca = {}", cnf_quoted("ca file", ca)?);
798            }
799            // The system's CAs, as the Python client's (MySQL's client verifies only
800            // against a CA given; MariaDB's reads this too).
801            None => cnf.push_str("ssl-capath = \"/etc/ssl/certs\"\n"),
802        }
803    }
804    // Else `localhost` is the local socket, whatever the port: maybe another server.
805    cnf.push_str("protocol = TCP\n");
806    let _ = writeln!(cnf, "host = {}", cnf_quoted("host", &host)?);
807    let _ = writeln!(cnf, "port = {port}");
808    if let Some(user) = login.user {
809        let _ = writeln!(cnf, "user = {}", cnf_quoted("user", user)?);
810    }
811    if let Some(password) = login.password {
812        let _ = writeln!(cnf, "password = {}", cnf_quoted("password", password)?);
813        view.derive(password, &cnf_escaped(password));
814    }
815    if let Some(seconds) = seconds(values) {
816        let _ = writeln!(cnf, "connect-timeout = {seconds}");
817    }
818    let _ = write!(cnf, "\n[client-mariadb]\n{mariadb}");
819    if !database.is_empty() {
820        // The `mysql` (`mariadb`) program's own: its default database.
821        let quoted = cnf_quoted("database", &database)?;
822        let _ = writeln!(cnf, "\n[mysql]\ndatabase = {quoted}");
823        view.var("DATABASE", database);
824    }
825    view.var("HOST", host);
826    view.var("PORT", port);
827    view.file(dir, "MYSQL_CNF", "my.cnf", cnf);
828    Ok(())
829}
830
831/// A host and its port (`db:3307`, `[::1]:3307`, `db`), the port `default` when none.
832fn host_and_port(hosts: &str, default: &str) -> (String, String) {
833    if let Some(rest) = hosts.strip_prefix('[')
834        && let Some((host, after)) = rest.split_once(']')
835    {
836        let port = after
837            .strip_prefix(':')
838            .filter(|p| !p.is_empty())
839            .unwrap_or(default);
840        return (host.to_owned(), port.to_owned());
841    }
842    match hosts.rsplit_once(':') {
843        Some((host, port)) if !port.is_empty() => (host.to_owned(), port.to_owned()),
844        _ => (hosts.to_owned(), default.to_owned()),
845    }
846}
847
848/// `Generic`'s keys, or a `@connection`'s parameters: one variable each, text as it is,
849/// anything else as JSON (decided 2026-10-25).
850fn own(values: &Map<String, Value>, view: &mut View) -> Result<(), String> {
851    let mut seen = BTreeSet::new();
852    for (param, value) in values {
853        if !param.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
854            return Err(format!(
855                "`{param}` can't be a variable's name (letters, digits and `_` only): read the \
856                 values with `schedr task-ctx connection NAME --json`"
857            ));
858        }
859        let suffix = param.to_ascii_uppercase();
860        if suffix == "JSON" || !seen.insert(suffix.clone()) {
861            return Err(format!(
862                "`{param}` would be a variable another value has: read the values with \
863                 `schedr task-ctx connection NAME --json`"
864            ));
865        }
866        let text = match value {
867            Value::String(text) => text.clone(),
868            other => other.to_string(),
869        };
870        view.var(&suffix, text);
871    }
872    Ok(())
873}