Skip to main content

fedimint_cli/
secret_input.rs

1//! Resolve root protected inputs and preflight legacy sources before startup.
2//!
3//! Module handlers retain their existing parsing lifecycle, but their stdin
4//! consumers are counted before any root input is read or the client is opened.
5
6use std::path::{Path, PathBuf};
7
8use anyhow::ensure;
9use fedimint_core::util::{ensure_single_stdin, read_secret_file};
10
11use crate::cli::{AdminCmd, Command, DecodeType, DevCmd, EncodeType, Opts};
12use crate::client::ClientCmd;
13
14const CREDENTIAL_LIMIT: usize = 1024 * 1024;
15const PAYLOAD_LIMIT: usize = 16 * 1024 * 1024;
16
17struct Source<'a> {
18    value: &'a mut Option<String>,
19    file: &'a Option<PathBuf>,
20    required: bool,
21    limit: usize,
22}
23
24impl<'a> Source<'a> {
25    fn credential(
26        value: &'a mut Option<String>,
27        file: &'a Option<PathBuf>,
28        required: bool,
29    ) -> Self {
30        Self {
31            value,
32            file,
33            required,
34            limit: CREDENTIAL_LIMIT,
35        }
36    }
37
38    fn payload(value: &'a mut Option<String>, file: &'a Option<PathBuf>) -> Self {
39        Self {
40            value,
41            file,
42            required: true,
43            limit: PAYLOAD_LIMIT,
44        }
45    }
46}
47
48impl Opts {
49    pub(crate) fn resolve_secret_inputs(&mut self) -> anyhow::Result<()> {
50        let notes_files: Vec<PathBuf> = if let Command::Client(command) = &self.command {
51            command.validate_notes_sources()?;
52            command
53                .notes_file_paths()
54                .into_iter()
55                .map(Path::to_path_buf)
56                .collect()
57        } else {
58            vec![]
59        };
60        let has_federation_secret =
61            self.federation_secret_hex.is_some() || self.federation_secret_hex_file.is_some();
62        if let Command::Client(ClientCmd::Restore {
63            mnemonic,
64            mnemonic_file,
65            ..
66        }) = &self.command
67        {
68            let has_mnemonic = mnemonic.is_some() || mnemonic_file.is_some();
69            ensure!(
70                has_mnemonic != has_federation_secret,
71                "Restore requires exactly one mnemonic or federation secret input"
72            );
73        }
74        ensure!(
75            !has_federation_secret || !matches!(self.command, Command::Join { .. }),
76            "A custom federation secret cannot be used with join"
77        );
78        let mut sources = vec![
79            Source::credential(&mut self.password, &self.password_file, false),
80            Source::credential(
81                &mut self.federation_secret_hex,
82                &self.federation_secret_hex_file,
83                false,
84            ),
85        ];
86        match &mut self.command {
87            Command::Join {
88                invite_code,
89                invite_code_file,
90            }
91            | Command::Dev(
92                DevCmd::QueryFederationIps {
93                    invite_code,
94                    invite_code_file,
95                    ..
96                }
97                | DevCmd::Decode {
98                    decode_type:
99                        DecodeType::InviteCode {
100                            invite_code,
101                            invite_code_file,
102                        },
103                },
104            ) => sources.push(Source::credential(invite_code, invite_code_file, true)),
105            Command::Client(ClientCmd::Restore {
106                mnemonic,
107                mnemonic_file,
108                invite_code,
109                invite_code_file,
110            }) => {
111                sources.push(Source::credential(mnemonic, mnemonic_file, false));
112                sources.push(Source::credential(invite_code, invite_code_file, true));
113            }
114            Command::Admin(AdminCmd::Auth {
115                password,
116                password_file,
117                ..
118            })
119            | Command::Dev(
120                DevCmd::ConfigDecrypt {
121                    password,
122                    password_file,
123                    ..
124                }
125                | DevCmd::ConfigEncrypt {
126                    password,
127                    password_file,
128                    ..
129                },
130            ) => sources.push(Source::credential(password, password_file, true)),
131            Command::Dev(DevCmd::Api {
132                password,
133                password_file,
134                params,
135                params_file,
136                ..
137            }) => {
138                sources.push(Source::credential(password, password_file, false));
139                sources.push(Source {
140                    value: params,
141                    file: params_file,
142                    required: false,
143                    limit: PAYLOAD_LIMIT,
144                });
145            }
146            Command::Dev(DevCmd::Decode {
147                decode_type: DecodeType::Notes { notes, file },
148            }) => sources.push(Source::payload(notes, file)),
149            Command::Dev(DevCmd::Encode {
150                encode_type:
151                    EncodeType::Notes {
152                        notes_json,
153                        notes_json_file,
154                    },
155            }) => sources.push(Source::payload(notes_json, notes_json_file)),
156            Command::Dev(DevCmd::Encode {
157                encode_type:
158                    EncodeType::InviteCode {
159                        api_secret,
160                        api_secret_file,
161                        ..
162                    },
163            }) => sources.push(Source::credential(api_secret, api_secret_file, false)),
164            _ => {}
165        }
166        // Validate all sources before opening any file or consuming stdin. Runtime
167        // errors avoid clap diagnostics that could echo positional secret values.
168        for source in &sources {
169            ensure!(
170                source.value.is_none() || source.file.is_none(),
171                "A direct or environment input cannot be combined with its file input"
172            );
173            ensure!(
174                !source.required || source.value.is_some() || source.file.is_some(),
175                "Required input missing: supply a value or its file option"
176            );
177        }
178        ensure_single_stdin(
179            sources
180                .iter()
181                .filter_map(|source| source.file.as_deref())
182                .chain(notes_files.iter().map(PathBuf::as_path)),
183        )?;
184        for source in sources {
185            if let Some(path) = source.file {
186                *source.value = Some(read_secret_file(path, source.limit)?);
187            }
188        }
189        Ok(())
190    }
191}
192
193/// Module arguments are parsed by the modules themselves, after the global CLI
194/// options. Reserve their stdin before reading a global secret input.
195pub(crate) fn check_module_stdin(opts: &Opts) -> anyhow::Result<()> {
196    let Command::Client(ClientCmd::Module { args, .. }) = &opts.command else {
197        return Ok(());
198    };
199    let mut stdin_inputs = [&opts.password_file, &opts.federation_secret_hex_file]
200        .into_iter()
201        .flatten()
202        .filter(|path| *path == Path::new("-"))
203        .count();
204    let mut args = args.iter();
205    while let Some(arg) = args.next() {
206        if arg == "--" {
207            break;
208        }
209        if arg == "--notes-file=-" || arg == "--ecash-file=-" {
210            stdin_inputs += 1;
211        }
212        if (arg == "--notes-file" || arg == "--ecash-file")
213            && args.next().is_some_and(|value| value == "-")
214        {
215            stdin_inputs += 1;
216        }
217    }
218    ensure!(
219        stdin_inputs <= 1,
220        "Only one secret input may read standard input"
221    );
222    Ok(())
223}
224
225#[cfg(test)]
226mod tests;