1//! Cookie-based authentication for the RPC server.
23use base64::{engine::general_purpose::URL_SAFE, Engine as _};
4use color_eyre::Result;
5use rand::RngCore;
67use std::{
8 fs::{remove_file, File},
9 io::Write,
10 path::Path,
11};
1213/// The name of the cookie file on the disk
14const FILE: &str = ".cookie";
1516/// If the RPC authentication is enabled, all requests must contain this cookie.
17#[derive(Clone, Debug)]
18pub struct Cookie(String);
1920impl Cookie {
21/// Checks if the given passwd matches the contents of the cookie.
22pub fn authenticate(&self, passwd: String) -> bool {
23*passwd == self.0
24}
25}
2627impl Default for Cookie {
28fn default() -> Self {
29let mut bytes = [0u8; 32];
30 rand::thread_rng().fill_bytes(&mut bytes);
3132Self(URL_SAFE.encode(bytes))
33 }
34}
3536/// Writes the given cookie to the given dir.
37pub fn write_to_disk(cookie: &Cookie, dir: &Path) -> Result<()> {
38// Create the directory if needed.
39std::fs::create_dir_all(dir)?;
40 File::create(dir.join(FILE))?.write_all(format!("__cookie__:{}", cookie.0).as_bytes())?;
4142tracing::info!("RPC auth cookie written to disk");
4344Ok(())
45}
4647/// Removes a cookie from the given dir.
48pub fn remove_from_disk(dir: &Path) -> Result<()> {
49 remove_file(dir.join(FILE))?;
5051tracing::info!("RPC auth cookie removed from disk");
5253Ok(())
54}