Skip to main content

ai6_secret_bitwarden/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-secret-bitwarden`: the `bitwarden` secret provider. A secret is a field of one item of a
6//! Bitwarden or Vaultwarden vault, read through the `bw` command line, which decrypts on this
7//! host: the server only ever holds the encrypted vault. Credentials reach `bw` in its
8//! environment, never in an argument. Calls block; the host calls them off its async runtime.
9
10#![doc = include_str!("../README.md")]
11#![forbid(unsafe_code)]
12#![warn(missing_docs)]
13
14ai6::guatiao::providers!(Bitwarden);
15
16mod proc;
17
18use std::fmt;
19use std::path::PathBuf;
20use std::sync::{Arc, Mutex};
21use std::time::Duration;
22
23use ai6::directorates::q::secret_kind::{SecretAsk, SecretProvider, SecretRead};
24use ai6::guatiao::library::ProviderError;
25use ai6::guatiao::{Alloc, FromValue, Schema, Secret, Status, ToValue, Value};
26use serde::Deserialize;
27use url::Url;
28use zeroize::{Zeroize, Zeroizing};
29
30/// The provider ID a `[secret_provider.<name>]` instance or a secret names.
31pub const PROVIDER_ID: &str = "bitwarden";
32
33/// One instance's settings, from `[secret_provider.<name>]`.
34///
35/// A credential is a secret reference the Station reads when it builds the instance; the
36/// provider holds the value in memory only.
37#[derive(ToValue, FromValue, Schema, Debug, Clone)]
38#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
39pub struct BitwardenConfig {
40    /// The `bw` program, found on the `PATH` when not a path. Default `bw`.
41    #[schema(title = "Bitwarden CLI")]
42    #[map(default = "bw".to_owned())]
43    pub program: String,
44    /// The server, such as a Vaultwarden's address; `https`. The CLI's own choice (Bitwarden's
45    /// cloud, or what it was last pointed at) when unset.
46    #[schema(title = "Server")]
47    pub server: Option<String>,
48    /// Accept an `http` server address. Reported as a weakening: the vault is encrypted, but
49    /// the API key and the master password's proof cross in the clear. Default off.
50    #[schema(title = "Allow an unencrypted server address")]
51    #[map(default = false)]
52    pub allow_http: bool,
53    /// The directory the CLI keeps its state in (`BITWARDENCLI_APPDATA_DIR`). Set a directory of
54    /// its own, so this provider never logs out or locks a CLI a person uses; the CLI's own
55    /// directory when unset.
56    #[schema(title = "CLI state directory")]
57    pub data_dir: Option<PathBuf>,
58    /// A session key of an unlocked vault (`bw unlock --raw`), a secret reference. Set this or
59    /// `password`.
60    #[schema(title = "Session key", sensitive)]
61    pub session: Option<Secret<String>>,
62    /// The master password the provider unlocks the vault with, a secret reference. Set this or
63    /// `session`.
64    #[schema(title = "Master password", sensitive)]
65    pub password: Option<Secret<String>>,
66    /// The API key's `client_id` (`user.<uuid>`), to log the CLI in when it is not. Needs
67    /// `client_secret`.
68    #[schema(title = "API key's client ID")]
69    pub client_id: Option<String>,
70    /// The API key's `client_secret`, a secret reference. Needs `client_id`.
71    #[schema(title = "API key's client secret", sensitive)]
72    pub client_secret: Option<Secret<String>>,
73    /// Seconds one call to `bw` may take; a call past it is stopped. Default 60.
74    #[schema(title = "A call may take", format = "seconds")]
75    #[map(default = 60)]
76    pub timeout_secs: u64,
77}
78
79impl Default for BitwardenConfig {
80    fn default() -> Self {
81        Self {
82            program: "bw".to_owned(),
83            server: None,
84            allow_http: false,
85            data_dir: None,
86            session: None,
87            password: None,
88            client_id: None,
89            client_secret: None,
90            timeout_secs: 60,
91        }
92    }
93}
94
95/// What one secret names besides `key` (the item's name or ID).
96#[derive(ToValue, FromValue, Schema, Debug, Clone, Default)]
97#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
98pub struct BitwardenFields {
99    /// What to read of the item: `password`, `username`, `notes`, `uri` (the first), `totp` (the
100    /// seed), or `custom:NAME` for a custom field. Default `password`.
101    #[schema(title = "Field")]
102    pub field: Option<String>,
103}
104
105/// One call of `bw`: its arguments (never a secret) and the variables it runs with.
106pub struct Call {
107    /// The arguments after the program name.
108    pub args: Vec<String>,
109    /// The variables set for this call, among them every credential it needs.
110    pub env: Vec<(String, Zeroizing<String>)>,
111}
112
113impl fmt::Debug for Call {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.debug_struct("Call")
116            .field("args", &self.args)
117            .field(
118                "env",
119                &self.env.iter().map(|(name, _)| name).collect::<Vec<_>>(),
120            )
121            .finish()
122    }
123}
124
125/// What `bw` left.
126pub struct Outcome {
127    /// Whether it exited with success.
128    pub ok: bool,
129    /// What it wrote to standard output.
130    pub stdout: Zeroizing<Vec<u8>>,
131    /// What it wrote to standard error. Read to tell failures apart, never shown.
132    pub stderr: Zeroizing<Vec<u8>>,
133}
134
135/// Why `bw` could not be run to its end. The text holds no value.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct RunError(pub String);
138
139/// Runs the `bw` program: what the provider needs of the Bitwarden CLI.
140pub trait Runner: Send + Sync {
141    /// Runs one call.
142    ///
143    /// # Errors
144    ///
145    /// The program could not be started or ran past its deadline.
146    fn run(&self, call: &Call) -> Result<Outcome, RunError>;
147}
148
149/// How the provider gets a session key.
150enum Auth {
151    /// The instance holds one.
152    Session(Secret<String>),
153    /// Unlock the vault, logging in first with an API key when the CLI is not logged in.
154    Unlock {
155        password: Secret<String>,
156        api_key: Option<(String, Secret<String>)>,
157    },
158}
159
160/// Reads fields of a Bitwarden vault's items through the `bw` command line.
161#[derive(ai6::guatiao::Provider)]
162#[provider(
163    SecretProvider,
164    id = "bitwarden",
165    name = "Bitwarden",
166    config = BitwardenConfig,
167    crate = ::ai6::guatiao
168)]
169pub struct Bitwarden {
170    runner: Arc<dyn Runner>,
171    server: Option<String>,
172    data_dir: Option<PathBuf>,
173    auth: Auth,
174    /// The session an unlock gave, and whether the server was checked.
175    state: Mutex<State>,
176}
177
178#[derive(Default)]
179struct State {
180    session: Option<Zeroizing<String>>,
181    server_checked: bool,
182}
183
184impl fmt::Debug for Bitwarden {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        f.debug_struct("Bitwarden")
187            .field("server", &self.server)
188            .finish_non_exhaustive()
189    }
190}
191
192impl Bitwarden {
193    /// A provider that runs the real `bw`.
194    ///
195    /// # Errors
196    ///
197    /// A message for a setting that cannot work.
198    pub fn new(config: BitwardenConfig) -> Result<Self, String> {
199        let runner = Arc::new(proc::Cli {
200            program: config.program.clone(),
201            timeout: Duration::from_secs(config.timeout_secs),
202        });
203        Self::with_runner(config, runner)
204    }
205
206    /// A provider that runs `bw` through `runner`, for a test or a host with its own way.
207    ///
208    /// # Errors
209    ///
210    /// A message for a setting that cannot work.
211    pub fn with_runner(config: BitwardenConfig, runner: Arc<dyn Runner>) -> Result<Self, String> {
212        if config.program.trim().is_empty() {
213            return Err("program must name the Bitwarden CLI".to_owned());
214        }
215        if config.timeout_secs == 0 {
216            return Err("timeout_secs must be at least 1".to_owned());
217        }
218        let server = match config.server.as_deref().map(str::trim) {
219            None => None,
220            Some(address) => {
221                let url = Url::parse(address).map_err(|error| format!("server: {error}"))?;
222                if url.scheme() != "https" && !(url.scheme() == "http" && config.allow_http) {
223                    return Err(
224                        "server must be an https address (allow_http accepts http)".to_owned()
225                    );
226                }
227                if url.host_str().is_none() {
228                    return Err("server must name a host".to_owned());
229                }
230                Some(address.trim_end_matches('/').to_owned())
231            }
232        };
233        let api_key = match (config.client_id, config.client_secret) {
234            (None, None) => None,
235            (Some(id), Some(secret)) if !id.trim().is_empty() => Some((id, secret)),
236            _ => return Err("client_id and client_secret are set together".to_owned()),
237        };
238        let auth = match (config.session, config.password) {
239            (Some(_), Some(_)) => return Err("set session or password, not both".to_owned()),
240            (Some(session), None) => {
241                if api_key.is_some() {
242                    return Err(
243                        "an API key logs in to unlock with `password`, not `session`".to_owned(),
244                    );
245                }
246                Auth::Session(session)
247            }
248            (None, Some(password)) => Auth::Unlock { password, api_key },
249            (None, None) => {
250                return Err("set session (an unlocked vault's key) or password".to_owned());
251            }
252        };
253        if let Auth::Session(session) = &auth
254            && session.expose().trim().is_empty()
255        {
256            return Err("session is empty".to_owned());
257        }
258        Ok(Self {
259            runner,
260            server,
261            data_dir: config.data_dir,
262            auth,
263            state: Mutex::new(State::default()),
264        })
265    }
266
267    fn base_env(&self) -> Vec<(String, Zeroizing<String>)> {
268        self.data_dir
269            .iter()
270            .map(|dir| {
271                (
272                    "BITWARDENCLI_APPDATA_DIR".to_owned(),
273                    Zeroizing::new(dir.display().to_string()),
274                )
275            })
276            .collect()
277    }
278
279    /// Runs `bw` with `args` and `env` besides the instance's own.
280    fn bw(&self, args: &[&str], env: Vec<(&str, &str)>) -> Result<Outcome, ProviderError> {
281        let mut vars = self.base_env();
282        vars.extend(
283            env.into_iter()
284                .map(|(name, value)| (name.to_owned(), Zeroizing::new(value.to_owned()))),
285        );
286        let mut all = args.to_vec();
287        all.push("--nointeraction");
288        self.runner
289            .run(&Call {
290                args: all.into_iter().map(str::to_owned).collect(),
291                env: vars,
292            })
293            .map_err(|error| failure(Status::GUATIAO_ERR_INTERNAL, &error.0))
294    }
295
296    /// Points the CLI at `server` when it is not, once.
297    fn check_server(&self, state: &mut State) -> Result<(), ProviderError> {
298        let Some(server) = &self.server else {
299            return Ok(());
300        };
301        if state.server_checked {
302            return Ok(());
303        }
304        let status = self.bw(&["status"], Vec::new())?;
305        let report = parse_status(&status)?;
306        let current = report
307            .server_url
308            .as_deref()
309            .map(|url| url.trim_end_matches('/'));
310        if current != Some(server.as_str()) {
311            if report.status != "unauthenticated" {
312                return Err(failure(
313                    Status::GUATIAO_ERR_BAD_VALUE,
314                    "the Bitwarden CLI is logged in to another server: set `data_dir` to a \
315                     directory of its own, or log it out",
316                ));
317            }
318            let set = self.bw(&["config", "server", server], Vec::new())?;
319            if !set.ok {
320                return Err(failure(
321                    Status::GUATIAO_ERR_INTERNAL,
322                    "the Bitwarden CLI refused the server address",
323                ));
324            }
325        }
326        state.server_checked = true;
327        Ok(())
328    }
329
330    /// A session key: the one configured, the one an earlier unlock gave, or a new one.
331    fn session(&self, state: &mut State) -> Result<Zeroizing<String>, ProviderError> {
332        let (password, api_key) = match &self.auth {
333            Auth::Session(session) => return Ok(Zeroizing::new(session.expose().clone())),
334            Auth::Unlock { password, api_key } => (password, api_key),
335        };
336        if let Some(session) = &state.session {
337            return Ok(session.clone());
338        }
339        self.check_server(state)?;
340        let status = parse_status(&self.bw(&["status"], Vec::new())?)?;
341        if status.status == "unauthenticated" {
342            let Some((id, secret)) = api_key else {
343                return Err(failure(
344                    Status::GUATIAO_ERR_BAD_VALUE,
345                    "the Bitwarden CLI is not logged in and no client_id and client_secret are set",
346                ));
347            };
348            let login = self.bw(
349                &["login", "--apikey"],
350                vec![
351                    ("BW_CLIENTID", id.as_str()),
352                    ("BW_CLIENTSECRET", secret.expose()),
353                ],
354            )?;
355            if !login.ok {
356                return Err(failure(
357                    Status::GUATIAO_ERR_INTERNAL,
358                    "the Bitwarden CLI did not log in with the API key",
359                ));
360            }
361        }
362        let unlock = self.bw(
363            &["unlock", "--passwordenv", "BW_PASSWORD", "--raw"],
364            vec![("BW_PASSWORD", password.expose())],
365        )?;
366        let key = std::str::from_utf8(&unlock.stdout)
367            .ok()
368            .map(str::trim)
369            .filter(|key| unlock.ok && !key.is_empty());
370        let Some(key) = key else {
371            return Err(failure(
372                Status::GUATIAO_ERR_INTERNAL,
373                "the Bitwarden CLI did not unlock the vault; is the master password right?",
374            ));
375        };
376        let session = Zeroizing::new(key.to_owned());
377        state.session = Some(session.clone());
378        Ok(session)
379    }
380
381    fn get_item(&self, key: &str, session: &str) -> Result<Outcome, ProviderError> {
382        self.bw(&["get", "item", key], vec![("BW_SESSION", session)])
383    }
384}
385
386impl TryFrom<BitwardenConfig> for Bitwarden {
387    type Error = ProviderError;
388
389    fn try_from(config: BitwardenConfig) -> Result<Self, Self::Error> {
390        Self::new(config).map_err(|why| failure(Status::GUATIAO_ERR_BAD_VALUE, &why))
391    }
392}
393
394fn failure(status: Status, message: &str) -> ProviderError {
395    ProviderError::new(status, message)
396}
397
398struct StatusReport {
399    status: String,
400    server_url: Option<String>,
401}
402
403fn parse_status(outcome: &Outcome) -> Result<StatusReport, ProviderError> {
404    #[derive(Deserialize)]
405    struct Raw {
406        status: String,
407        #[serde(rename = "serverUrl")]
408        server_url: Option<String>,
409    }
410    let raw: Raw = outcome
411        .ok
412        .then(|| serde_json::from_slice(&outcome.stdout).ok())
413        .flatten()
414        .ok_or_else(|| {
415            failure(
416                Status::GUATIAO_ERR_INTERNAL,
417                "the Bitwarden CLI's status could not be read",
418            )
419        })?;
420    Ok(StatusReport {
421        status: raw.status,
422        server_url: raw.server_url,
423    })
424}
425
426/// A string of an item that is wiped when dropped.
427#[derive(Deserialize, Default)]
428#[serde(transparent)]
429struct Text(String);
430
431impl Drop for Text {
432    fn drop(&mut self) {
433        self.0.zeroize();
434    }
435}
436
437#[derive(Deserialize, Default)]
438struct Item {
439    #[serde(default)]
440    login: Option<Login>,
441    #[serde(default)]
442    notes: Option<Text>,
443    #[serde(default)]
444    fields: Option<Vec<CustomField>>,
445}
446
447#[derive(Deserialize, Default)]
448struct Login {
449    #[serde(default)]
450    username: Option<Text>,
451    #[serde(default)]
452    password: Option<Text>,
453    #[serde(default)]
454    totp: Option<Text>,
455    #[serde(default)]
456    uris: Option<Vec<Uri>>,
457}
458
459#[derive(Deserialize, Default)]
460struct Uri {
461    #[serde(default)]
462    uri: Option<Text>,
463}
464
465#[derive(Deserialize, Default)]
466struct CustomField {
467    #[serde(default)]
468    name: Option<String>,
469    #[serde(default)]
470    value: Option<Text>,
471}
472
473/// What of an item `field` names.
474enum Pick {
475    Username,
476    Password,
477    Notes,
478    Uri,
479    Totp,
480    Custom(String),
481}
482
483fn pick(field: Option<&str>) -> Result<Pick, ProviderError> {
484    Ok(match field.unwrap_or("password") {
485        "password" => Pick::Password,
486        "username" => Pick::Username,
487        "notes" => Pick::Notes,
488        "uri" => Pick::Uri,
489        "totp" => Pick::Totp,
490        other => match other.strip_prefix("custom:") {
491            Some(name) if !name.is_empty() => Pick::Custom(name.to_owned()),
492            _ => {
493                return Err(failure(
494                    Status::GUATIAO_ERR_BAD_VALUE,
495                    "field is one of password, username, notes, uri, totp, or custom:NAME",
496                ));
497            }
498        },
499    })
500}
501
502fn value_of(item: Item, pick: &Pick) -> Option<Zeroizing<String>> {
503    let mut item = item;
504    let text = match pick {
505        Pick::Notes => item.notes.take(),
506        Pick::Username => item.login.as_mut().and_then(|login| login.username.take()),
507        Pick::Password => item.login.as_mut().and_then(|login| login.password.take()),
508        Pick::Totp => item.login.as_mut().and_then(|login| login.totp.take()),
509        Pick::Uri => item
510            .login
511            .as_mut()
512            .and_then(|login| login.uris.as_mut())
513            .and_then(|uris| uris.first_mut())
514            .and_then(|uri| uri.uri.take()),
515        Pick::Custom(name) => item.fields.as_mut().and_then(|fields| {
516            fields
517                .iter_mut()
518                .find(|field| field.name.as_deref() == Some(name))
519                .and_then(|field| field.value.take())
520        }),
521    };
522    text.map(|mut text| Zeroizing::new(std::mem::take(&mut text.0)))
523        .filter(|text| !text.is_empty())
524}
525
526fn fields_of(ask: &SecretAsk) -> Result<BitwardenFields, ProviderError> {
527    let map = ask
528        .fields
529        .clone_in(Alloc::wiping())
530        .map_err(|_| failure(Status::GUATIAO_ERR_ALLOC, "the fields could not be read"))?;
531    BitwardenFields::from_value(&Value::from(map))
532        .map_err(|error| failure(Status::GUATIAO_ERR_BAD_VALUE, &error.to_string()))
533}
534
535impl SecretProvider for Bitwarden {
536    fn read(&self, ask: &Value) -> Result<Value, ProviderError> {
537        self.read_in(ask, Alloc::wiping())
538    }
539
540    fn read_in(&self, ask: &Value, alloc: Alloc) -> Result<Value, ProviderError> {
541        let ask = SecretAsk::from_value(ask)
542            .map_err(|error| failure(Status::GUATIAO_ERR_BAD_VALUE, &error.to_string()))?;
543        if ask.key.trim().is_empty() {
544            return Err(failure(
545                Status::GUATIAO_ERR_BAD_VALUE,
546                "a secret of the bitwarden provider names its item (a name or an ID) in `key`",
547            ));
548        }
549        let pick = pick(fields_of(&ask)?.field.as_deref())?;
550
551        let mut state = self.state.lock().map_err(|_| {
552            failure(
553                Status::GUATIAO_ERR_INTERNAL,
554                "the provider's lock was poisoned",
555            )
556        })?;
557        self.check_server(&mut state)?;
558        let derived = matches!(self.auth, Auth::Unlock { .. });
559        let mut session = self.session(&mut state)?;
560        let mut item = self.get_item(&ask.key, &session)?;
561        if !item.ok && derived && !says(&item, "not found") && !says(&item, "more than one") {
562            // A session key an earlier unlock gave may have lapsed: unlock once more.
563            state.session = None;
564            session = self.session(&mut state)?;
565            item = self.get_item(&ask.key, &session)?;
566        }
567        drop(state);
568        if !item.ok {
569            return Err(if says(&item, "not found") {
570                failure(
571                    Status::GUATIAO_ERR_NOT_FOUND,
572                    &format!("the vault has no item {:?}", ask.key),
573                )
574            } else if says(&item, "more than one") {
575                failure(
576                    Status::GUATIAO_ERR_BAD_VALUE,
577                    &format!(
578                        "more than one item is named {:?}: name it by its ID in `key`",
579                        ask.key
580                    ),
581                )
582            } else {
583                failure(
584                    Status::GUATIAO_ERR_INTERNAL,
585                    "the Bitwarden CLI could not read the item; is the vault unlocked?",
586                )
587            });
588        }
589        let parsed: Item = serde_json::from_slice(&item.stdout).map_err(|_| {
590            failure(
591                Status::GUATIAO_ERR_BAD_VALUE,
592                "the Bitwarden CLI's answer is not an item",
593            )
594        })?;
595        let value = value_of(parsed, &pick).ok_or_else(|| {
596            failure(
597                Status::GUATIAO_ERR_NOT_FOUND,
598                &format!("the item {:?} has no value in that field", ask.key),
599            )
600        })?;
601        SecretRead {
602            value: Secret::new(value.as_str().to_owned()),
603            revision: None,
604        }
605        .to_value_in(alloc)
606        .map_err(|error| failure(Status::GUATIAO_ERR_ALLOC, &error.to_string()))
607    }
608
609    fn fields(&self) -> Result<Value, ProviderError> {
610        BitwardenFields::schema()
611            .map_err(|error| failure(Status::GUATIAO_ERR_INTERNAL, &error.to_string()))
612    }
613}
614
615/// Whether what `bw` wrote to standard error says `needle`, in any case. The text itself is
616/// never kept past this.
617fn says(outcome: &Outcome, needle: &str) -> bool {
618    String::from_utf8_lossy(&outcome.stderr)
619        .to_lowercase()
620        .contains(needle)
621}