From ea085ba5fa7a2f555b0118f944939fe221082189 Mon Sep 17 00:00:00 2001 From: NotAShelf Date: Sun, 22 Dec 2024 19:24:41 +0300 Subject: [PATCH] read authentication token from the environment --- src/cli.rs | 1 - src/server.rs | 25 +++++++++++++++++++------ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 1b4cc022..999aca2a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -216,7 +216,6 @@ async fn main() -> io::Result<()> { break; } - // I don't like this either, but it looks cleaner than a multi-line // print macro just cramped in here. let commands = vec![ diff --git a/src/server.rs b/src/server.rs index 20b589f7..5989dcd4 100644 --- a/src/server.rs +++ b/src/server.rs @@ -5,11 +5,9 @@ use native_tls::{Identity, TlsAcceptor as NativeTlsAcceptor}; use serde_json::json; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_native_tls::TlsAcceptor; -use tracing::{info, debug, error}; +use tracing::{debug, error, info}; -use mrc::{set_property, get_property, playlist_clear, playlist_next, playlist_prev, quit, seek}; - -const AUTH_TOKEN: &str = "your_secure_token"; +use mrc::{get_property, playlist_clear, playlist_next, playlist_prev, quit, seek, set_property}; async fn handle_connection( stream: tokio::net::TcpStream, @@ -24,13 +22,28 @@ async fn handle_connection( debug!("Received request:\n{}", request); let headers = request.split("\r\n").collect::>(); - let token_line = headers.iter().find(|&&line| line.starts_with("Authorization:")); + let token_line = headers + .iter() + .find(|&&line| line.starts_with("Authorization:")); let token = match token_line { Some(line) => line.split(" ").nth(1).unwrap_or_default(), None => "", }; - if token != AUTH_TOKEN { + let auth_token = match env::var("AUTH_TOKEN") { + Ok(token) => token, + Err(_) => { + error!("Authentication token is not set. Connection cannot be accepted."); + stream.write_all(b"Authentication token not set\n").await?; + + // You know what? I do not care to panic when the token is missing. + // Sure, start the server and hell even accept the connection. Auth + // will be refused if token is incorrect, so we can just continue here. + return Ok(()); + } + }; + + if token != auth_token { stream.write_all(b"Authentication failed\n").await?; return Ok(()); }