Skip to main content

pb_mapper_auth/persistence/
admin_key.rs

1//! Administrator key files: the live key, the one a rotation stages, the
2//! candidate the CLI and SDK stage, and whether a key opens the encrypted state.
3use super::super::*;
4use super::{
5    ADMIN_KEY_FILE, admin_key_path, atomic_write, auth_snapshot_path, auth_wal_path,
6    create_new_write, encrypted_auth_state_exists, open_blob, rotation_key_path, truncate_auth_wal,
7    wal::read_wal_record,
8};
9
10pub(crate) fn read_admin_key(path: &Path) -> Result<Option<String>, AuthFailure> {
11    if !path.exists() {
12        return Ok(None);
13    }
14    #[cfg(unix)]
15    {
16        let metadata = std::fs::metadata(path).map_err(|error| {
17            AuthFailure::new(
18                codes::ADMINISTRATOR_KEY_REQUIRED,
19                format!(
20                    "administrator key file `{}` metadata could not be read: {error}",
21                    path.display()
22                ),
23                false,
24            )
25        })?;
26        if metadata.permissions().mode() & 0o077 != 0 {
27            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
28                |error| {
29                    AuthFailure::new(
30                        codes::ADMINISTRATOR_KEY_REQUIRED,
31                        format!(
32                            "administrator key file `{}` permissions could not be secured: {error}",
33                            path.display()
34                        ),
35                        false,
36                    )
37                },
38            )?;
39            tracing::warn!(
40                event = "administrator_key_permissions_repaired",
41                path = %path.display(),
42                "restricted administrator key file permissions to 0600"
43            );
44        }
45    }
46    std::fs::read_to_string(path).map(Some).map_err(|error| {
47        AuthFailure::new(
48            codes::ADMINISTRATOR_KEY_REQUIRED,
49            format!(
50                "administrator key file `{}` could not be read: {error}",
51                path.display()
52            ),
53            false,
54        )
55    })
56}
57
58pub(crate) fn persist_recovery_admin_key(
59    state_dir: &Path,
60    key: &str,
61    mismatch_message: &'static str,
62) -> Result<(), AuthFailure> {
63    if encrypted_auth_state_exists(state_dir) && !key_matches_existing_state(Some(state_dir), key) {
64        return Err(AuthFailure::new(
65            codes::ADMINISTRATOR_KEY_INVALID,
66            mismatch_message,
67            false,
68        ));
69    }
70    write_admin_key(state_dir, key)
71}
72
73pub(crate) fn recover_admin_key_after_rotation(
74    state_dir: &Path,
75    current: &str,
76) -> Result<String, AuthFailure> {
77    let snapshot_path = auth_snapshot_path(state_dir);
78    if !snapshot_path.exists() {
79        return Ok(current.to_string());
80    }
81    let bytes = std::fs::read(&snapshot_path).map_err(|error| {
82        AuthFailure::new(
83            codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
84            format!("failed to read `{}`: {error}", snapshot_path.display()),
85            false,
86        )
87    })?;
88    if let Ok(Credential::Admin(current_key)) = parse_credential(current.trim())
89        && open_blob(&current_key, &bytes).is_ok()
90    {
91        return Ok(current.to_string());
92    }
93    let Some(next) = read_admin_key(&rotation_key_path(state_dir))? else {
94        return Ok(current.to_string());
95    };
96    let Ok(Credential::Admin(next_key)) = parse_credential(next.trim()) else {
97        return Ok(current.to_string());
98    };
99    if open_blob(&next_key, &bytes).is_err() {
100        return Ok(current.to_string());
101    }
102    // The rotation snapshot is complete under the staged key. Leftover WAL
103    // records are still encrypted with the previous key.
104    truncate_auth_wal(state_dir)?;
105    write_admin_key(state_dir, next.trim())?;
106    let _ = std::fs::remove_file(rotation_key_path(state_dir));
107    Ok(next)
108}
109
110pub(crate) fn write_admin_key(state_dir: &Path, key: &str) -> Result<(), AuthFailure> {
111    atomic_write(
112        &admin_key_path(state_dir),
113        format!("{key}\n").as_bytes(),
114        0o600,
115    )
116}
117
118pub fn generate_admin_key() -> String {
119    const CHARSET: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
120    let mut rng = rand::rng();
121    (0..32)
122        .map(|_| CHARSET[rng.random_range(0..CHARSET.len())] as char)
123        .collect()
124}
125
126pub fn initialize_admin_key(path: &Path, force: bool) -> Result<String, AuthFailure> {
127    if path.exists() && !force {
128        return Err(AuthFailure::new(
129            codes::ADMINISTRATOR_KEY_EXISTS,
130            format!("administrator key file `{}` already exists", path.display()),
131            false,
132        ));
133    }
134    refuse_write_if_encrypted_state(path, force)?;
135    let key = generate_admin_key();
136    atomic_write(path, format!("{key}\n").as_bytes(), 0o600)?;
137    Ok(key)
138}
139
140/// Reject anything that is not a 32-byte administrator key before it reaches disk.
141pub(crate) fn validate_admin_key(key: &str) -> Result<(), AuthFailure> {
142    let Credential::Admin(_) = parse_credential(key)
143        .map_err(|error| AuthFailure::new(codes::ADMINISTRATOR_KEY_INVALID, error, false))?
144    else {
145        return Err(AuthFailure::new(
146            codes::ADMINISTRATOR_KEY_INVALID,
147            "administrator key file requires a 32-byte administrator key",
148            false,
149        ));
150    };
151    Ok(())
152}
153
154pub fn write_admin_key_file(path: &Path, key: &str, force: bool) -> Result<(), AuthFailure> {
155    validate_admin_key(key)?;
156    if path.exists() && !force {
157        return Err(AuthFailure::new(
158            codes::ADMINISTRATOR_KEY_EXISTS,
159            format!(
160                "administrator key file `{}` already exists; pass --force to replace it",
161                path.display()
162            ),
163            false,
164        ));
165    }
166    if path.file_name() == Some(std::ffi::OsStr::new(ADMIN_KEY_FILE))
167        && !key_matches_existing_state(path.parent(), key)
168    {
169        refuse_write_if_encrypted_state(path, force)?;
170    }
171    atomic_write(path, format!("{key}\n").as_bytes(), 0o600)
172}
173
174/// The sibling path a root-rotation candidate is staged at, next to the live
175/// administrator key file `path`.
176///
177/// A dotted sibling rather than a subdirectory, so the candidate lands on the
178/// same filesystem as `path` and inherits the directory's permissions.
179pub fn staged_admin_key_path(path: &Path) -> PathBuf {
180    let name = path
181        .file_name()
182        .and_then(|name| name.to_str())
183        .unwrap_or(ADMIN_KEY_FILE);
184    path.with_file_name(format!(".{name}.next"))
185}
186
187/// Write a root-rotation candidate to the staged sibling of `path`, returning
188/// the staged path.
189///
190/// Refuses to replace a candidate that is already staged under a *different*
191/// key. Rotation is not idempotent, so a staged file that outlived its rotation
192/// attempt means the relay's active key is unknown: it is either the live key at
193/// `path` or that candidate. Overwriting it would destroy the only copy of a key
194/// the relay may already have installed, locking the operator out. Restaging the
195/// same key is allowed, so retrying a rotation with the candidate in hand works.
196pub fn stage_admin_key_candidate(path: &Path, key: &str) -> Result<PathBuf, AuthFailure> {
197    let staged_path = staged_admin_key_path(path);
198    if let Some(staged) = read_admin_key_file(&staged_path)? {
199        return accept_staged_candidate(path, staged_path, &staged, key);
200    }
201    validate_admin_key(key)?;
202    // Claims the path itself rather than renaming onto it. The read above is a
203    // check-then-act: two rotations racing here both pass it, and a rename always
204    // wins, so the loser's candidate — possibly the only copy of the key the
205    // relay just installed — would vanish. `O_EXCL` makes exactly one of them the
206    // winner and sends the other through the same decision as a pre-existing file.
207    if !create_new_write(&staged_path, format!("{key}\n").as_bytes(), 0o600)? {
208        let staged = read_admin_key_file(&staged_path)?.unwrap_or_default();
209        return accept_staged_candidate(path, staged_path, &staged, key);
210    }
211    Ok(staged_path)
212}
213
214/// Whether the candidate already at `staged_path` can stand in for `key`.
215///
216/// The same key means this is a retry of the rotation that staged it, so the
217/// staged file is exactly what the caller wanted. A different one — including
218/// the empty or short file a crash mid-write leaves behind — means the relay's
219/// active key is unknown, and only the operator can say which it is.
220fn accept_staged_candidate(
221    path: &Path,
222    staged_path: PathBuf,
223    staged: &str,
224    key: &str,
225) -> Result<PathBuf, AuthFailure> {
226    if staged.trim() == key.trim() {
227        return Ok(staged_path);
228    }
229    Err(AuthFailure::new(
230        codes::ADMINISTRATOR_KEY_STAGED,
231        format!(
232            "a previous root rotation left an unresolved candidate at `{}`, so the relay's active \
233             administrator key is either `{}` or that candidate; determine which key the relay \
234             accepts, install it at `{}`, and delete the staged file before rotating again",
235            staged_path.display(),
236            path.display(),
237            path.display()
238        ),
239        false,
240    ))
241}
242
243/// Drop a staged candidate once the rotation it belongs to is durably recorded
244/// at the live key file.
245///
246/// A leftover staged file blocks the next rotation, but failing to remove it is
247/// not worth failing a rotation that already succeeded, so this only warns.
248pub fn discard_staged_admin_key(staged_path: &Path) {
249    if let Err(error) = std::fs::remove_file(staged_path) {
250        tracing::warn!(
251            path = %staged_path.display(),
252            %error,
253            "administrator key was rotated, but the staged candidate could not be removed"
254        );
255    }
256}
257
258/// Read an administrator key file, or `None` when it does not exist.
259fn read_admin_key_file(path: &Path) -> Result<Option<String>, AuthFailure> {
260    match std::fs::read_to_string(path) {
261        Ok(contents) => Ok(Some(contents)),
262        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
263        Err(error) => Err(AuthFailure::new(
264            codes::AUTH_STATE_UNAVAILABLE,
265            format!("failed to read `{}`: {error}", path.display()),
266            false,
267        )),
268    }
269}
270
271pub(crate) fn rotation_already_installed(state_dir: &Path, new_key: &str) -> bool {
272    key_matches_existing_snapshot(Some(state_dir), new_key)
273        && live_admin_key_matches(state_dir, new_key)
274}
275
276fn live_admin_key_matches(state_dir: &Path, new_key: &str) -> bool {
277    let Ok(raw) = std::fs::read(admin_key_path(state_dir)) else {
278        return false;
279    };
280    let Ok(text) = std::str::from_utf8(&raw) else {
281        return false;
282    };
283    text.trim().as_bytes() == new_key.trim().as_bytes()
284}
285
286fn key_matches_existing_snapshot(state_dir: Option<&Path>, key: &str) -> bool {
287    let Some(state_dir) = state_dir else {
288        return false;
289    };
290    let snapshot_path = auth_snapshot_path(state_dir);
291    if !snapshot_path.exists() {
292        return false;
293    }
294    let Ok(Credential::Admin(admin_key)) = parse_credential(key) else {
295        return false;
296    };
297    let Ok(bytes) = std::fs::read(&snapshot_path) else {
298        return false;
299    };
300    open_blob(&admin_key, &bytes).is_ok()
301}
302
303fn key_matches_existing_state(state_dir: Option<&Path>, key: &str) -> bool {
304    if key_matches_existing_snapshot(state_dir, key) {
305        return true;
306    }
307    let Some(state_dir) = state_dir else {
308        return false;
309    };
310    if auth_snapshot_path(state_dir).exists() {
311        return false;
312    }
313    let wal_path = auth_wal_path(state_dir);
314    if !wal_path.exists() {
315        return false;
316    }
317    let Ok(Credential::Admin(admin_key)) = parse_credential(key) else {
318        return false;
319    };
320    wal_decrypts_with_key(&wal_path, &admin_key)
321}
322
323/// Whether `admin_key` opens the first record of the WAL at `path`. An empty WAL
324/// fits any key, and a zero-length record none: sealing always adds a header.
325fn wal_decrypts_with_key(path: &Path, admin_key: &AesKeyType) -> bool {
326    let Ok(mut file) = File::open(path) else {
327        return false;
328    };
329    let Ok(metadata) = file.metadata() else {
330        return false;
331    };
332    if metadata.len() == 0 {
333        return true;
334    }
335    let mut prefix = [0_u8; 4];
336    if file.read_exact(&mut prefix).is_err() || prefix == [0; 4] {
337        return false;
338    }
339    let mut sealed = Vec::new();
340    if read_wal_record(&mut file, prefix, &mut sealed).is_err() {
341        return false;
342    }
343    open_blob(admin_key, &sealed).is_ok()
344}
345
346fn refuse_write_if_encrypted_state(path: &Path, force: bool) -> Result<(), AuthFailure> {
347    // Creating or replacing the live root while snapshot/WAL remain leaves
348    // those files encrypted under the previous key. Staging `admin.key.next`
349    // is the rotate path and must stay allowed.
350    let Some(state_dir) = path.parent() else {
351        return Ok(());
352    };
353    if !encrypted_auth_state_exists(state_dir) {
354        return Ok(());
355    }
356    Err(AuthFailure::new(
357        codes::ADMINISTRATOR_KEY_STATE_EXISTS,
358        format!(
359            "refusing to {} `{}` while encrypted auth state exists; use `pb-mapper admin root-key rotate` or `pb-mapper admin auth-state reset --confirm`",
360            if force { "replace" } else { "create" },
361            path.display()
362        ),
363        false,
364    ))
365}