pinakes-server: TLS support; session persistence and security polish
Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: If2c9c3e3af62bbf9f33a97be89ac40bc6a6a6964
This commit is contained in:
parent
758aba0f7a
commit
87a4482576
19 changed files with 1835 additions and 111 deletions
|
|
@ -2,6 +2,78 @@ use std::path::{Path, PathBuf};
|
|||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Expand environment variables in a string.
|
||||
/// Supports both ${VAR_NAME} and $VAR_NAME syntax.
|
||||
/// Returns an error if a referenced variable is not set.
|
||||
fn expand_env_var_string(input: &str) -> crate::error::Result<String> {
|
||||
let mut result = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '$' {
|
||||
// Check if it's ${VAR} or $VAR syntax
|
||||
let use_braces = chars.peek() == Some(&'{');
|
||||
if use_braces {
|
||||
chars.next(); // consume '{'
|
||||
}
|
||||
|
||||
// Collect variable name
|
||||
let mut var_name = String::new();
|
||||
while let Some(&next_ch) = chars.peek() {
|
||||
if use_braces {
|
||||
if next_ch == '}' {
|
||||
chars.next(); // consume '}'
|
||||
break;
|
||||
}
|
||||
var_name.push(next_ch);
|
||||
chars.next();
|
||||
} else {
|
||||
// For $VAR syntax, stop at non-alphanumeric/underscore
|
||||
if next_ch.is_alphanumeric() || next_ch == '_' {
|
||||
var_name.push(next_ch);
|
||||
chars.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if var_name.is_empty() {
|
||||
return Err(crate::error::PinakesError::Config(
|
||||
"empty environment variable name".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Look up the environment variable
|
||||
match std::env::var(&var_name) {
|
||||
Ok(value) => result.push_str(&value),
|
||||
Err(_) => {
|
||||
return Err(crate::error::PinakesError::Config(format!(
|
||||
"environment variable not set: {}",
|
||||
var_name
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else if ch == '\\' {
|
||||
// Handle escaped characters
|
||||
if let Some(&next_ch) = chars.peek() {
|
||||
if next_ch == '$' {
|
||||
chars.next(); // consume the escaped $
|
||||
result.push('$');
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Config {
|
||||
pub storage: StorageConfig,
|
||||
|
|
@ -456,6 +528,15 @@ pub struct PostgresConfig {
|
|||
pub username: String,
|
||||
pub password: String,
|
||||
pub max_connections: usize,
|
||||
/// Enable TLS for PostgreSQL connections
|
||||
#[serde(default)]
|
||||
pub tls_enabled: bool,
|
||||
/// Verify TLS certificates (default: true)
|
||||
#[serde(default = "default_true")]
|
||||
pub tls_verify_ca: bool,
|
||||
/// Path to custom CA certificate file (PEM format)
|
||||
#[serde(default)]
|
||||
pub tls_ca_cert_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
|
|
@ -484,6 +565,11 @@ pub struct ServerConfig {
|
|||
/// If set, all requests (except /health) must include `Authorization: Bearer <key>`.
|
||||
/// Can also be set via `PINAKES_API_KEY` environment variable.
|
||||
pub api_key: Option<String>,
|
||||
/// Explicitly disable authentication (INSECURE - use only for development).
|
||||
/// When true, all requests are allowed without authentication.
|
||||
/// This must be explicitly set to true; empty api_key alone is not sufficient.
|
||||
#[serde(default)]
|
||||
pub authentication_disabled: bool,
|
||||
/// TLS/HTTPS configuration
|
||||
#[serde(default)]
|
||||
pub tls: TlsConfig,
|
||||
|
|
@ -570,8 +656,45 @@ impl Config {
|
|||
let content = std::fs::read_to_string(path).map_err(|e| {
|
||||
crate::error::PinakesError::Config(format!("failed to read config file: {e}"))
|
||||
})?;
|
||||
toml::from_str(&content)
|
||||
.map_err(|e| crate::error::PinakesError::Config(format!("failed to parse config: {e}")))
|
||||
let mut config: Self = toml::from_str(&content).map_err(|e| {
|
||||
crate::error::PinakesError::Config(format!("failed to parse config: {e}"))
|
||||
})?;
|
||||
config.expand_env_vars()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Expand environment variables in secret fields.
|
||||
/// Supports ${VAR_NAME} and $VAR_NAME syntax.
|
||||
fn expand_env_vars(&mut self) -> crate::error::Result<()> {
|
||||
// Postgres password
|
||||
if let Some(ref mut postgres) = self.storage.postgres {
|
||||
postgres.password = expand_env_var_string(&postgres.password)?;
|
||||
}
|
||||
|
||||
// Server API key
|
||||
if let Some(ref api_key) = self.server.api_key {
|
||||
self.server.api_key = Some(expand_env_var_string(api_key)?);
|
||||
}
|
||||
|
||||
// Webhook secrets
|
||||
for webhook in &mut self.webhooks {
|
||||
if let Some(ref secret) = webhook.secret {
|
||||
webhook.secret = Some(expand_env_var_string(secret)?);
|
||||
}
|
||||
}
|
||||
|
||||
// Enrichment API keys
|
||||
if let Some(ref api_key) = self.enrichment.sources.musicbrainz.api_key {
|
||||
self.enrichment.sources.musicbrainz.api_key = Some(expand_env_var_string(api_key)?);
|
||||
}
|
||||
if let Some(ref api_key) = self.enrichment.sources.tmdb.api_key {
|
||||
self.enrichment.sources.tmdb.api_key = Some(expand_env_var_string(api_key)?);
|
||||
}
|
||||
if let Some(ref api_key) = self.enrichment.sources.lastfm.api_key {
|
||||
self.enrichment.sources.lastfm.api_key = Some(expand_env_var_string(api_key)?);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Try loading from file, falling back to defaults if the file doesn't exist.
|
||||
|
|
@ -643,6 +766,50 @@ impl Config {
|
|||
if self.scanning.import_concurrency == 0 || self.scanning.import_concurrency > 256 {
|
||||
return Err("import_concurrency must be between 1 and 256".into());
|
||||
}
|
||||
|
||||
// Validate authentication configuration
|
||||
let has_api_key = self
|
||||
.server
|
||||
.api_key
|
||||
.as_ref()
|
||||
.map_or(false, |k| !k.is_empty());
|
||||
let has_accounts = !self.accounts.users.is_empty();
|
||||
let auth_disabled = self.server.authentication_disabled;
|
||||
|
||||
if !auth_disabled && !has_api_key && !has_accounts {
|
||||
return Err(
|
||||
"authentication is not configured: set an api_key, configure user accounts, \
|
||||
or explicitly set authentication_disabled = true"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
// Empty API key is not allowed (must use authentication_disabled flag)
|
||||
if let Some(ref api_key) = self.server.api_key {
|
||||
if api_key.is_empty() {
|
||||
return Err("empty api_key is not allowed. To disable authentication, \
|
||||
set authentication_disabled = true instead"
|
||||
.into());
|
||||
}
|
||||
}
|
||||
|
||||
// Require TLS when authentication is enabled on non-localhost
|
||||
let is_localhost = self.server.host == "127.0.0.1"
|
||||
|| self.server.host == "localhost"
|
||||
|| self.server.host == "::1";
|
||||
|
||||
if (has_api_key || has_accounts)
|
||||
&& !auth_disabled
|
||||
&& !is_localhost
|
||||
&& !self.server.tls.enabled
|
||||
{
|
||||
return Err(
|
||||
"TLS must be enabled when authentication is used on non-localhost hosts. \
|
||||
Set server.tls.enabled = true or bind to localhost only"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
// Validate TLS configuration
|
||||
self.server.tls.validate()?;
|
||||
Ok(())
|
||||
|
|
@ -690,6 +857,7 @@ impl Default for Config {
|
|||
host: "127.0.0.1".to_string(),
|
||||
port: 3000,
|
||||
api_key: None,
|
||||
authentication_disabled: false,
|
||||
tls: TlsConfig::default(),
|
||||
},
|
||||
ui: UiConfig::default(),
|
||||
|
|
@ -714,6 +882,7 @@ mod tests {
|
|||
fn test_config_with_concurrency(concurrency: usize) -> Config {
|
||||
let mut config = Config::default();
|
||||
config.scanning.import_concurrency = concurrency;
|
||||
config.server.authentication_disabled = true; // Disable auth for concurrency tests
|
||||
config
|
||||
}
|
||||
|
||||
|
|
@ -758,4 +927,125 @@ mod tests {
|
|||
let config = test_config_with_concurrency(256);
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
|
||||
// Environment variable expansion tests
|
||||
#[test]
|
||||
fn test_expand_env_var_simple() {
|
||||
unsafe {
|
||||
std::env::set_var("TEST_VAR_SIMPLE", "test_value");
|
||||
}
|
||||
let result = expand_env_var_string("$TEST_VAR_SIMPLE");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "test_value");
|
||||
unsafe {
|
||||
std::env::remove_var("TEST_VAR_SIMPLE");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_braces() {
|
||||
unsafe {
|
||||
std::env::set_var("TEST_VAR_BRACES", "test_value");
|
||||
}
|
||||
let result = expand_env_var_string("${TEST_VAR_BRACES}");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "test_value");
|
||||
unsafe {
|
||||
std::env::remove_var("TEST_VAR_BRACES");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_embedded() {
|
||||
unsafe {
|
||||
std::env::set_var("TEST_VAR_EMBEDDED", "value");
|
||||
}
|
||||
let result = expand_env_var_string("prefix_${TEST_VAR_EMBEDDED}_suffix");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "prefix_value_suffix");
|
||||
unsafe {
|
||||
std::env::remove_var("TEST_VAR_EMBEDDED");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_multiple() {
|
||||
unsafe {
|
||||
std::env::set_var("VAR1", "value1");
|
||||
std::env::set_var("VAR2", "value2");
|
||||
}
|
||||
let result = expand_env_var_string("${VAR1}_${VAR2}");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "value1_value2");
|
||||
unsafe {
|
||||
std::env::remove_var("VAR1");
|
||||
std::env::remove_var("VAR2");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_missing() {
|
||||
let result = expand_env_var_string("${NONEXISTENT_VAR}");
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("environment variable not set")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_empty_name() {
|
||||
let result = expand_env_var_string("${}");
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("empty environment variable name")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_escaped() {
|
||||
let result = expand_env_var_string("\\$NOT_A_VAR");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "$NOT_A_VAR");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_no_vars() {
|
||||
let result = expand_env_var_string("plain_text");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "plain_text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_underscore() {
|
||||
unsafe {
|
||||
std::env::set_var("TEST_VAR_NAME", "value");
|
||||
}
|
||||
let result = expand_env_var_string("$TEST_VAR_NAME");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "value");
|
||||
unsafe {
|
||||
std::env::remove_var("TEST_VAR_NAME");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_expand_env_var_mixed_syntax() {
|
||||
unsafe {
|
||||
std::env::set_var("VAR1_MIXED", "v1");
|
||||
std::env::set_var("VAR2_MIXED", "v2");
|
||||
}
|
||||
let result = expand_env_var_string("$VAR1_MIXED and ${VAR2_MIXED}");
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(result.unwrap(), "v1 and v2");
|
||||
unsafe {
|
||||
std::env::remove_var("VAR1_MIXED");
|
||||
std::env::remove_var("VAR2_MIXED");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue