mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Where named destinations are kept between invocations.
//!
//! The store is a single file in the configuration directory. It is read once
//! per invocation and written only when a command changes it, and every write
//! replaces the file in one step so a reader never sees a half-written store.

use super::profile::Profile;
use crate::error::{Failure, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// The name of the file the store writes inside the configuration directory.
const STORE_FILE: &str = "profiles.toml";

/// The document the store writes and reads.
///
/// It deliberately carries no default of its own. Which destination applies
/// when none is named is the published setting `conn.default`, and a second
/// copy here would be a value the caller can set and the work can ignore —
/// exactly the defect the settings registry exists to prevent. A document
/// written by an older build may still carry the field; it is read and
/// discarded rather than refused, so an upgrade costs nobody their store.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct StoreDocument {
    /// Every stored profile, in the order they were written.
    #[serde(default, rename = "profile")]
    profiles: Vec<Profile>,
}

/// The profiles held on disk, loaded once per invocation.
#[derive(Debug, Clone)]
pub struct ProfileStore {
    path: PathBuf,
    document: StoreDocument,
}

impl ProfileStore {
    /// Loads the store from a configuration directory.
    ///
    /// A directory with no store yet is not a failure: it is an empty store,
    /// so the first `conn add` on a fresh host works without a setup step.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the file exists but cannot be read
    /// or does not parse.
    pub fn open(directory: &Path) -> Result<Self> {
        let path = directory.join(STORE_FILE);
        if !path.exists() {
            return Ok(Self {
                path,
                document: StoreDocument::default(),
            });
        }

        let text = std::fs::read_to_string(&path).map_err(|cause| {
            Failure::config(
                "profile.store_unreadable",
                "the profile store cannot be read",
            )
            .with_hint("check the permissions of the configuration directory")
            .with_cause(cause.to_string())
        })?;

        let document = toml::from_str(&text).map_err(|cause| {
            Failure::config(
                "profile.store_malformed",
                "the profile store is not in the expected form",
            )
            .with_hint("repair the file by hand, or remove it to start from an empty store")
            .with_cause(cause.to_string())
        })?;

        Ok(Self { path, document })
    }

    /// Builds an empty store bound to a path, without touching the disk.
    #[must_use]
    pub fn empty_at(path: PathBuf) -> Self {
        Self {
            path,
            document: StoreDocument::default(),
        }
    }

    /// The file this store reads and writes.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Every stored profile, in storage order.
    #[must_use]
    pub fn list(&self) -> &[Profile] {
        &self.document.profiles
    }

    /// Borrows one profile by name.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when no profile carries that name.
    pub fn get(&self, name: &str) -> Result<&Profile> {
        self.document
            .profiles
            .iter()
            .find(|profile| profile.name == name)
            .ok_or_else(|| Self::unknown(name))
    }

    /// Borrows one profile by name for change.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when no profile carries that name.
    pub fn get_mut(&mut self, name: &str) -> Result<&mut Profile> {
        self.document
            .profiles
            .iter_mut()
            .find(|profile| profile.name == name)
            .ok_or_else(|| Self::unknown(name))
    }

    /// Whether a profile with this name is stored.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.document
            .profiles
            .iter()
            .any(|profile| profile.name == name)
    }

    /// Adds a profile.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the name is empty or already taken,
    /// because silently replacing a destination would point later calls at a
    /// different server without saying so.
    pub fn add(&mut self, profile: Profile) -> Result<()> {
        if profile.name.trim().is_empty() {
            return Err(Failure::config(
                "profile.empty_name",
                "a profile name may not be empty",
            ));
        }
        if self.contains(&profile.name) {
            // The name alone, and never a sentence built around it. A message
            // the source words in one language arrives at the catalogue as the
            // value it substitutes, so a reader asking for another language
            // would be handed English inside their own prose.
            return Err(
                Failure::config("profile.already_exists", format!("`{}`", profile.name))
                    .with_detail("detail", profile.name.clone())
                    .with_hint("change it with `conn edit`, or remove it first"),
            );
        }
        self.document.profiles.push(profile);
        Ok(())
    }

    /// Removes a profile and clears the default when it pointed at it.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when no profile carries that name.
    pub fn remove(&mut self, name: &str) -> Result<Profile> {
        let position = self
            .document
            .profiles
            .iter()
            .position(|profile| profile.name == name)
            .ok_or_else(|| Self::unknown(name))?;
        Ok(self.document.profiles.remove(position))
    }

    /// Refuses a name no profile carries, for a caller about to mark it.
    ///
    /// The mark itself is not written here: which destination applies when none
    /// is named lives in the settings registry under `conn.default`. What the
    /// store owns is whether the name exists at all.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when no profile carries that name.
    pub fn ensure_exists(&self, name: &str) -> Result<()> {
        if self.contains(name) {
            return Ok(());
        }
        Err(Self::unknown(name))
    }

    /// Resolves the profile a call applies to.
    ///
    /// The stored default is handed in rather than kept here, because it is the
    /// published setting `conn.default` and the layer that reads settings is
    /// the only one allowed to read it.
    ///
    /// # Errors
    ///
    /// Returns an absence failure when the named profile is unknown, and a
    /// configuration failure when nothing was named and no default exists.
    pub fn resolve(
        &self,
        requested: Option<&str>,
        stored_default: Option<&str>,
    ) -> Result<&Profile> {
        // A profile the caller named and this host does not have is a
        // configuration failure, not a missing server object: nothing was
        // ever asked of a server.
        if let Some(name) = requested {
            return self.get(name).map_err(|_| {
                Failure::config("profile.unknown", format!("`{name}`"))
                    .with_detail("detail", format!("`{name}`"))
                    .with_hint("list the ones that exist with `conn list`")
            });
        }

        let name = stored_default.ok_or_else(|| {
            Failure::config(
                "profile.no_default",
                "no profile was named and none is marked as the default",
            )
            .with_hint("name one with --profile, or mark one with `conn default`")
        })?;
        // A key naming a profile the store lost is a configuration failure and
        // never an empty answer, or the caller would reach a destination they
        // never chose.
        self.get(name).map_err(|_| {
            // Which layer named the profile is recorded as a value rather than
            // written into the sentence, so every language words the two cases
            // itself. Losing the distinction would send the caller looking at a
            // --profile they never passed.
            Failure::config("profile.unknown", format!("`{name}`"))
                .with_detail("detail", format!("`{name}`"))
                .with_detail("named", "default")
                .with_hint("list the ones that exist with `conn list`")
        })
    }

    /// Writes the store back to disk.
    ///
    /// The write is atomic and the file is readable by its owner alone, so a
    /// half-written store never replaces a good one and no other account on the
    /// host can read where this one connects.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the directory cannot be created or
    /// the file cannot be replaced.
    pub fn save(&self) -> Result<()> {
        let directory = self.path.parent().ok_or_else(|| {
            Failure::config(
                "profile.store_path_invalid",
                "the profile store path has no directory",
            )
        })?;
        std::fs::create_dir_all(directory).map_err(|cause| {
            Failure::config(
                "profile.store_directory_unwritable",
                "the configuration directory cannot be created",
            )
            .with_cause(cause.to_string())
        })?;

        let text = toml::to_string_pretty(&self.document).map_err(|cause| {
            Failure::config(
                "profile.store_unserialisable",
                "the profile store cannot be written in the expected form",
            )
            .with_cause(cause.to_string())
        })?;

        write_private_atomically(&self.path, directory, text.as_bytes())
    }

    /// The failure raised for a name no profile carries.
    ///
    /// The message is the name and nothing else. The catalogue of the reader's
    /// language words the sentence around it, which it can only do if the
    /// source hands it the bare value instead of a sentence of its own.
    fn unknown(name: &str) -> Failure {
        Failure::absence("profile.unknown", format!("`{name}`"))
            .with_detail("detail", format!("`{name}`"))
            .with_hint("run `conn list` to see the stored profiles")
    }
}

/// Narrows the profile store to its owner alone.
///
/// The same shape as the settings store, and reusing its number rather than
/// writing `0o600` a second time, so the two files this product owns cannot
/// drift apart on which one is private.
#[cfg(unix)]
fn restrict(file: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt as _;

    std::fs::set_permissions(
        file,
        std::fs::Permissions::from_mode(crate::config::store::OWNER_ONLY),
    )
    .map_err(|cause| {
        Failure::config(
            "profile.store_permissions",
            "the profile store could not be restricted to its owner",
        )
        .with_cause(cause.to_string())
    })
}

/// Systems without file permission bits carry no restriction to apply.
///
/// Written out rather than left to an absent block. This file holds the secret
/// of every stored destination, and it was the one place in the product where
/// the difference between a system that narrows the file and one that cannot
/// was decided by a block simply vanishing. The settings store and the doctor
/// both state it; the more sensitive of the three did not.
#[cfg(not(unix))]
fn restrict(file: &Path) -> Result<()> {
    crate::i18n::report::permissions_unavailable_profiles(&file.display().to_string());
    Ok(())
}

/// Replaces a file in one step, readable by its owner alone.
///
/// A temporary file in the same directory is written, given its permissions
/// and only then renamed, so a reader never sees a partial store and a secret
/// path is never briefly world-readable.
fn write_private_atomically(path: &Path, directory: &Path, bytes: &[u8]) -> Result<()> {
    use std::io::Write;

    let mut temporary = tempfile::NamedTempFile::new_in(directory).map_err(|cause| {
        Failure::config(
            "profile.store_unwritable",
            "no temporary file could be created next to the profile store",
        )
        .with_cause(cause.to_string())
    })?;

    temporary.write_all(bytes).map_err(|cause| {
        Failure::config(
            "profile.store_unwritable",
            "the profile store cannot be written",
        )
        .with_cause(cause.to_string())
    })?;

    restrict(temporary.path())?;

    temporary.persist(path).map_err(|cause| {
        Failure::config(
            "profile.store_not_replaced",
            "the profile store could not be replaced",
        )
        .with_cause(cause.to_string())
    })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::conn::profile::SecretRef;

    fn store() -> ProfileStore {
        ProfileStore::empty_at(PathBuf::from("/nonexistent/profiles.toml"))
    }

    fn sample(name: &str) -> Profile {
        Profile {
            host: Some("db.example".to_owned()),
            user: Some("reader".to_owned()),
            secret: Some(SecretRef::for_profile(name)),
            ..Profile::named(name)
        }
    }

    /// The store keeps no default of its own, because that is the published
    /// setting `conn.default` and two copies of one decision is how a setting
    /// comes to be ignored. What the store owns is whether a name exists.
    #[test]
    fn the_store_owns_the_names_and_never_the_default() {
        let mut store = store();
        store.add(sample("first")).expect("added");
        assert!(store.ensure_exists("first").is_ok());
        assert!(store.ensure_exists("second").is_err());
    }

    /// Adding a name twice is refused, because replacing a destination in
    /// silence would point later calls at a different server.
    #[test]
    fn a_repeated_name_is_refused() {
        let mut store = store();
        store.add(sample("main")).expect("added");
        let failure = store.add(sample("main")).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.already_exists");
    }

    /// An empty name is refused, because nothing could ever address it.
    #[test]
    fn an_empty_name_is_refused() {
        let failure = store().add(Profile::named("  ")).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.empty_name");
    }

    /// A default naming a profile the store lost is a configuration failure and
    /// never an empty answer, or the caller would reach a destination they
    /// never chose.
    #[test]
    fn a_default_naming_a_lost_profile_is_reported() {
        let mut store = store();
        store.add(sample("first")).expect("added");
        store.remove("first").expect("removed");
        let failure = store.resolve(None, Some("first")).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.unknown");
        assert_eq!(failure.category(), crate::error::Category::Config);
    }

    /// An unknown name is an absence and carries the pointer to `conn list`.
    #[test]
    fn an_unknown_name_is_an_absence() {
        let failure = store().get("ghost").expect_err("must refuse");
        assert_eq!(failure.category(), crate::error::Category::Absence);
        assert!(failure.hint().is_some());
        assert!(store().ensure_exists("ghost").is_err());
        assert!(store().resolve(Some("ghost"), None).is_err());
    }

    /// With nothing named and no default stored, the caller is told what to do
    /// instead of being connected to an arbitrary destination.
    #[test]
    fn resolving_without_a_default_is_a_configuration_failure() {
        let failure = store().resolve(None, None).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_default");
    }

    /// Naming nothing resolves to the marked default.
    #[test]
    fn resolving_without_a_name_takes_the_marked_default() {
        let mut store = store();
        store.add(sample("first")).expect("added");
        store.add(sample("second")).expect("added");
        assert_eq!(
            store.resolve(None, Some("second")).expect("resolved").name,
            "second"
        );
    }

    /// The store survives a write and a read without changing shape, and a
    /// directory with no store yet reads as an empty one.
    #[test]
    fn the_store_round_trips_through_its_file() {
        let directory = tempfile::tempdir().expect("temporary directory");
        assert!(ProfileStore::open(directory.path())
            .expect("opened")
            .list()
            .is_empty());

        let mut written = ProfileStore::empty_at(directory.path().join(STORE_FILE));
        written.add(sample("main")).expect("added");
        written.save().expect("saved");

        let read = ProfileStore::open(directory.path()).expect("opened");
        assert_eq!(read.list().len(), 1);
        assert_eq!(
            read.get("main").expect("present").host.as_deref(),
            Some("db.example")
        );
    }

    /// A store that cannot be read is a configuration failure naming the cause,
    /// never an empty store that would hide every destination the host has.
    #[test]
    fn a_malformed_store_is_reported_and_not_treated_as_empty() {
        let directory = tempfile::tempdir().expect("temporary directory");
        std::fs::write(directory.path().join(STORE_FILE), "this is not = [valid").expect("written");
        let failure = ProfileStore::open(directory.path()).expect_err("must refuse");
        assert_eq!(failure.code(), "profile.store_malformed");
        assert!(failure.hint().is_some());
    }

    /// The written file is readable by its owner alone, so no other account on
    /// the host learns where this one connects.
    #[cfg(unix)]
    #[test]
    fn the_written_store_is_private_to_its_owner() {
        use std::os::unix::fs::PermissionsExt;
        let directory = tempfile::tempdir().expect("temporary directory");
        let mut store = ProfileStore::empty_at(directory.path().join(STORE_FILE));
        store.add(sample("main")).expect("added");
        store.save().expect("saved");
        let mode = std::fs::metadata(store.path())
            .expect("metadata")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600);
    }
}