aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-01-30 18:15:12 -0600
committerGitHub <noreply@github.com>2026-01-30 18:15:12 -0600
commit09eabbce7d9bd4d42ffa9c30f97faa909a9ff8b0 (patch)
tree19e3a3da819dcd0568a10377fe8a6eacf3998902
parent92b49b7a4035822240ba51ffdf3383eb9a30b164 (diff)
parentd2bf89cc204e89c04f66b778d9f94e325deb5a3d (diff)
downloadslskd-09eabbce7d9bd4d42ffa9c30f97faa909a9ff8b0.tar.gz
Merge pull request #1623 from slskd/runtime-config
Add the ability to apply an options 'overlay' at run-time; enabling update of listen IP and port
-rw-r--r--docs/config.md24
-rw-r--r--src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs1
-rw-r--r--src/slskd/Common/Configuration/VolatileOverlayConfigurationSource.cs163
-rw-r--r--src/slskd/Common/Validation/Extensions.cs20
-rw-r--r--src/slskd/Common/Validation/ValidationExtensions.cs3
-rw-r--r--src/slskd/Core/API/Controllers/OptionsController.cs51
-rw-r--r--src/slskd/Core/Extensions.cs15
-rw-r--r--src/slskd/Core/OptionsOverlay.cs66
-rw-r--r--src/slskd/Program.cs15
-rw-r--r--src/web/src/lib/options.js2
10 files changed, 352 insertions, 8 deletions
diff --git a/docs/config.md b/docs/config.md
index 9836a063..d1ad2dd1 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -13,7 +13,7 @@ The application supports several different configuration sources to make it easy
The configuration options used by the application derive from the values specified by each of the sources, with sources higher in the hierarchy overwriting or expanding the configuration set earlier. The hierarchy is:
```
-Default Values < Environment Variables < YAML Configuration File < Command Line Arguments
+Default Values < Environment Variables < YAML Configuration File < Command Line Arguments < Run-Time Overlay
```
Some options can be specified as lists. In these cases, when combining configurations from multiple sources, care should be taken. .NET framework not only appends but also overwrites values. If a list of `one;two;three` is defined in an environment variable for an option, and the YAML configuration specifies a list of `foo` and `bar`, the resulting configuration will be a list containing `foo, bar, three`.
@@ -58,6 +58,28 @@ Some options are backed by arrays or lists and allow multiple options to be set
--some-option 1 --some-option 2 --some-option 3
```
+## Run-Time Overlay
+
+A small subset of options can be set at run-time via an API call. These options take precedence over all other sources and the values persist through configuration changes; they are 'sticky' but also volatile, meaning they are lost when the application is restarted.
+
+Details about the API endpoint (including the full set of available options) can be found in the OpenAPI specification that can be generated by enabling the 'swagger' feature.
+
+The following is a complete example (currently only `listenPort` and `listenIpAddress` are supported):
+
+```bash
+curl --location --request PATCH 'http://localhost:5030/api/v0/options' \
+--header 'X-API-Key: <an API key with administrator role>' \
+--header 'Content-Type: application/json' \
+--data '{
+ "soulseek": {
+ "listenPort": 52342,
+ "listenIpAddress": "0.0.0.0"
+ }
+}'
+```
+
+Note: the Soulseek server is updated to reflect changes in `listenPort` automatically; there is no need to reconnect.
+
# Remote Configuration
The application contains APIs for retrieving and updating the YAML configuration file. By default, this option is disabled. Applications run within untrusted networks, especially those where the application is internet-facing, should consider the risks of enabling this option.
diff --git a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
index 8cf62e91..f125b1fc 100644
--- a/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
+++ b/src/slskd/Common/Configuration/DefaultValueConfigurationSource.cs
@@ -85,6 +85,7 @@ namespace slskd.Configuration
/// </summary>
public override void Load()
{
+ // note: pretty much the same as VolatileOverlayConfigurationProvider; the two should be updated in lockstep
void Map(Type type, string path)
{
var defaults = Activator.CreateInstance(type);
diff --git a/src/slskd/Common/Configuration/VolatileOverlayConfigurationSource.cs b/src/slskd/Common/Configuration/VolatileOverlayConfigurationSource.cs
new file mode 100644
index 00000000..0d6debec
--- /dev/null
+++ b/src/slskd/Common/Configuration/VolatileOverlayConfigurationSource.cs
@@ -0,0 +1,163 @@
+// <copyright file="VolatileOverlayConfigurationSource.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Configuration
+{
+ using System;
+ using System.Linq;
+ using System.Reflection;
+ using System.Text.Json;
+ using Microsoft.Extensions.Configuration;
+
+ /// <summary>
+ /// A <see cref="ConfigurationProvider"/> that provides a volatile, run-time overlay that supersedes other configuration
+ /// sources.
+ /// </summary>
+ /// <remarks>
+ /// To use this provider as intended, the application must instantiate and store an instance of either <see cref="VolatileOverlayConfigurationProvider{T}"/>
+ /// or <see cref="VolatileOverlayConfigurationSource{T}"/>, and then invoke <see cref="Apply"/> with the desired overlay object.
+ /// </remarks>
+ /// <typeparam name="T">The Type of the overlay.</typeparam>
+ public class VolatileOverlayConfigurationProvider<T> : ConfigurationProvider
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VolatileOverlayConfigurationProvider{T}"/> class.
+ /// </summary>
+ public VolatileOverlayConfigurationProvider()
+ {
+ TargetType = typeof(T);
+ Namespace = TargetType.Namespace.Split('.').First();
+ }
+
+ /// <summary>
+ /// Gets the current overlay value.
+ /// </summary>
+ public T CurrentValue { get; private set; }
+
+ private string Namespace { get; set; }
+ private Type TargetType { get; set; }
+
+ /// <summary>
+ /// Loads values from the <see cref="CurrentValue"/> overlay.
+ /// </summary>
+ public override void Load()
+ {
+ if (CurrentValue is null)
+ {
+ return;
+ }
+
+ // note: pretty much the same as DefaultValueConfigurationProvider; the two should be updated in lockstep
+ void Map(Type type, string path, object instance)
+ {
+ if (instance is null)
+ {
+ return;
+ }
+
+ var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
+
+ foreach (PropertyInfo property in props)
+ {
+ var key = ConfigurationPath.Combine(path, property.Name.ToLowerInvariant());
+
+ if (property.PropertyType.Namespace.StartsWith(Namespace))
+ {
+ Map(property.PropertyType, key, property.GetValue(instance));
+ }
+ else
+ {
+ // don't add array values to the configuration; these are additive across providers
+ // and the default value from the class is "stuck", so adding them again results in duplicates.
+ if (!property.PropertyType.IsArray)
+ {
+ var value = property.GetValue(instance);
+
+ if (value != null)
+ {
+ Data[key] = value.ToString();
+ }
+ }
+ else
+ {
+ // serialize array defaults and stick them on the parent key
+ // (not indexed by array position). this value is "stuck", and
+ // we want to show that in the config debug view. this isn't really
+ // functional, just illustrative.
+ Data[key] = JsonSerializer.Serialize(property.GetValue(instance));
+ }
+ }
+ }
+ }
+
+ Map(TargetType, Namespace, CurrentValue);
+ }
+
+ /// <summary>
+ /// Applies the given <paramref name="overlay"/>.
+ /// </summary>
+ /// <param name="overlay">An object containing the values to overlay.</param>
+ public void Apply(T overlay)
+ {
+ CurrentValue = overlay;
+ Load();
+ OnReload();
+ }
+ }
+
+ /// <summary>
+ /// Represents values that are provided at run-time as an <see cref="IConfigurationSource"/>.
+ /// </summary>
+ /// <remarks>
+ /// To use this provider as intended, the application must instantiate and store an instance of either <see cref="VolatileOverlayConfigurationProvider{T}"/>
+ /// or <see cref="VolatileOverlayConfigurationSource{T}"/>, and then invoke <see cref="Apply"/> with the desired overlay object.
+ /// </remarks>
+ /// <typeparam name="T">The Type of the overlay.</typeparam>
+ public class VolatileOverlayConfigurationSource<T> : IConfigurationSource
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="VolatileOverlayConfigurationSource{T}"/> class.
+ /// </summary>
+ public VolatileOverlayConfigurationSource()
+ {
+ Provider = new VolatileOverlayConfigurationProvider<T>();
+ }
+
+ /// <summary>
+ /// Gets the current overlay value.
+ /// </summary>
+ public T CurrentValue => Provider.CurrentValue;
+
+ private VolatileOverlayConfigurationProvider<T> Provider { get; set; }
+
+ /// <summary>
+ /// Applies the given <paramref name="overlay"/> to the underlying <see cref="VolatileOverlayConfigurationProvider{T}"/>.
+ /// </summary>
+ /// <param name="overlay">An object containing the values to overlay.</param>
+ public void Apply(T overlay) => Provider.Apply(overlay);
+
+ /// <summary>
+ /// Builds the <see cref="VolatileOverlayConfigurationSource{T}"/> for this source.
+ /// </summary>
+ /// <param name="builder">The <see cref="IConfigurationBuilder"/>.</param>
+ /// <returns>A <see cref="VolatileOverlayConfigurationProvider{T}"/>.</returns>
+ public IConfigurationProvider Build(IConfigurationBuilder builder)
+ {
+ return Provider;
+ }
+ }
+}
diff --git a/src/slskd/Common/Validation/Extensions.cs b/src/slskd/Common/Validation/Extensions.cs
index b7e396a3..87d83965 100644
--- a/src/slskd/Common/Validation/Extensions.cs
+++ b/src/slskd/Common/Validation/Extensions.cs
@@ -44,5 +44,25 @@ namespace slskd.Validation
return true;
}
+
+ /// <summary>
+ /// Validates options.
+ /// </summary>
+ /// <param name="overlay">The options overlay instance to validate.</param>
+ /// <param name="result">The result of the validation, if invalid.</param>
+ /// <returns>A value indicating whether the instance is valid.</returns>
+ public static bool TryValidate(this OptionsOverlay overlay, out CompositeValidationResult result)
+ {
+ result = null;
+ var results = new List<ValidationResult>();
+
+ if (!Validator.TryValidateObject(overlay, new ValidationContext(overlay), results, true))
+ {
+ result = new CompositeValidationResult("Invalid configuration", results);
+ return false;
+ }
+
+ return true;
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/ValidationExtensions.cs b/src/slskd/Common/Validation/ValidationExtensions.cs
index 7a85a995..a29667a2 100644
--- a/src/slskd/Common/Validation/ValidationExtensions.cs
+++ b/src/slskd/Common/Validation/ValidationExtensions.cs
@@ -26,6 +26,9 @@ namespace slskd.Validation
/// </summary>
public static class ValidationExtensions
{
+ public static string GetResultString(this CompositeValidationResult result)
+ => string.Join(' ', result.GetResultView(0).Select(s => s.Trim()));
+
public static string GetResultView(this CompositeValidationResult result)
=> string.Join("\n", result.GetResultView(0));
diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs
index 25e9095a..f5c1a5b6 100644
--- a/src/slskd/Core/API/Controllers/OptionsController.cs
+++ b/src/slskd/Core/API/Controllers/OptionsController.cs
@@ -53,7 +53,7 @@ namespace slskd.Core.API
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private OptionsAtStartup OptionsAtStartup { get; }
private IStateMutator<State> StateMutator { get; }
- private ILogger Logger { get; } = Log.ForContext(typeof(OptionsController));
+ private ILogger Log { get; } = Serilog.Log.ForContext<OptionsController>();
/// <summary>
/// Gets the current application options.
@@ -68,6 +68,45 @@ namespace slskd.Core.API
}
/// <summary>
+ /// Overlay the application options with new values.
+ /// </summary>
+ /// <param name="overlay">The overlay to apply.</param>
+ /// <returns></returns>
+ [HttpPatch]
+ [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
+ [ProducesResponseType(typeof(OptionsOverlay), 200)]
+ public IActionResult ApplyOverlay([FromBody] OptionsOverlay overlay)
+ {
+ if (!OptionsSnapshot.Value.RemoteConfiguration)
+ {
+ Log.Warning("Blocked options overlay application; remote configuration is disabled");
+ return Forbid();
+ }
+
+ if (overlay is null)
+ {
+ return NoContent();
+ }
+
+ if (!overlay.TryValidate(out var result))
+ {
+ Log.Warning("Options patch validation failed: {Message}", result.GetResultString());
+ return BadRequest(result.GetResultString());
+ }
+
+ try
+ {
+ Program.ApplyConfigurationOverlay(overlay);
+ return Ok(Program.ConfigurationOverlay?.Redact());
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to apply options patch: {Message}", ex.Message);
+ return StatusCode(500, $"Failed to apply options patch: {ex.Message}");
+ }
+ }
+
+ /// <summary>
/// Gets the application options provided at startup.
/// </summary>
/// <returns></returns>
@@ -130,7 +169,7 @@ namespace slskd.Core.API
return Ok(yaml);
}
- [HttpPost]
+ [HttpPut]
[Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)]
[Route("yaml")]
public IActionResult UpdateYamlFile([FromBody] string yaml)
@@ -142,17 +181,19 @@ namespace slskd.Core.API
if (!TryValidateYaml(yaml, out var error))
{
- Logger.Error(error, "Failed to validate YAML configuration");
+ Log.Error(error, "Failed to validate YAML configuration");
return BadRequest(error);
}
try
{
+ IOFile.Copy(Program.ConfigurationFile, $"{Program.ConfigurationFile}.bak", overwrite: true);
+
IOFile.WriteAllText(Program.ConfigurationFile, yaml);
if (OptionsSnapshot.Value.Flags.NoConfigWatch)
{
- Logger.Information("Configuration watch is disabled; restart required for changes to take effect");
+ Log.Information("Configuration watch is disabled; restart required for changes to take effect");
StateMutator.SetValue(state => state with { PendingRestart = true });
}
@@ -203,7 +244,7 @@ namespace slskd.Core.API
}
catch (Exception ex)
{
- Logger.Warning(ex, "Configuration validation failed");
+ Log.Warning(ex, "Configuration validation failed");
error = ex.Message;
diff --git a/src/slskd/Core/Extensions.cs b/src/slskd/Core/Extensions.cs
index db75cc9c..0789fa38 100644
--- a/src/slskd/Core/Extensions.cs
+++ b/src/slskd/Core/Extensions.cs
@@ -42,6 +42,21 @@ namespace slskd
}
/// <summary>
+ /// Redacts this instance of OptionsOverlay, replacing properties marked with <see cref="SecretAttribute"/> with '*****'.
+ /// </summary>
+ /// <remarks>
+ /// Creates a deep clone before redacting.
+ /// </remarks>
+ /// <param name="options">The OptionsOverlay instance to redact.</param>
+ /// <returns>A redacted instance.</returns>
+ public static OptionsOverlay Redact(this OptionsOverlay options)
+ {
+ var redacted = options.ToJson().FromJson<OptionsOverlay>();
+ Redactor.Redact(redacted, redactWith: "*****");
+ return redacted;
+ }
+
+ /// <summary>
/// Creates a copy of this instance with the specified parameters changed.
/// </summary>
/// <param name="o">The options instance to copy.</param>
diff --git a/src/slskd/Core/OptionsOverlay.cs b/src/slskd/Core/OptionsOverlay.cs
new file mode 100644
index 00000000..11167da5
--- /dev/null
+++ b/src/slskd/Core/OptionsOverlay.cs
@@ -0,0 +1,66 @@
+// <copyright file="OptionsOverlay.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+namespace slskd
+{
+ using System;
+ using System.ComponentModel.DataAnnotations;
+ using slskd.Validation;
+
+ /// <summary>
+ /// Volatile run-time overlay for application <see cref="Options"/>.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// The values specified in this overlay are applied at run-time only, are volatile (lost when the application restarts),
+ /// and take precedence over all other options, regardless of which method was used to define them.
+ /// </para>
+ /// <para>
+ /// Only options that can be applied while the application is running can be overlaid, given the nature of how
+ /// an overlay is applied.
+ /// </para>
+ /// <para>
+ /// Every property in this class must be nullable, and must have a null default value; the application
+ /// selectively applies the patch overlay only to information that is explicitly supplied.
+ /// </para>
+ /// </remarks>
+ public class OptionsOverlay
+ {
+ /// <summary>
+ /// Gets options for the Soulseek client.
+ /// </summary>
+ [Validate]
+ public SoulseekOptionsPatch Soulseek { get; init; } = null;
+
+ /// <summary>
+ /// Soulseek client options.
+ /// </summary>
+ public class SoulseekOptionsPatch
+ {
+ /// <summary>
+ /// Gets the local IP address on which to listen for incoming connections.
+ /// </summary>
+ [IPAddress]
+ public string ListenIpAddress { get; init; } = null;
+
+ /// <summary>
+ /// Gets the port on which to listen for incoming connections.
+ /// </summary>
+ [Range(1024, 65535)]
+ public int? ListenPort { get; init; } = null;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index d6873dc0..75c51355 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -190,6 +190,11 @@ namespace slskd
public static string ConfigurationFile { get; private set; } = null;
/// <summary>
+ /// Gets the current configuration overlay, if one has been applied.
+ /// </summary>
+ public static OptionsOverlay ConfigurationOverlay => VolatileOverlayConfigurationSource?.CurrentValue;
+
+ /// <summary>
/// Gets the path where persistent data is saved.
/// </summary>
public static string DataDirectory { get; private set; } = null;
@@ -244,6 +249,7 @@ namespace slskd
private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
private static Mutex Mutex { get; set; }
private static IDisposable DotNetRuntimeStats { get; set; }
+ private static VolatileOverlayConfigurationSource<OptionsOverlay> VolatileOverlayConfigurationSource { get; set; } = new VolatileOverlayConfigurationSource<OptionsOverlay>();
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
private static bool GenerateCertificate { get; set; }
@@ -270,6 +276,12 @@ namespace slskd
public static void Exit(int code = 1) => Environment.Exit(code);
/// <summary>
+ /// Apply an instance of <see cref="OptionsOverlay"/> on top of the existing application configuration.
+ /// </summary>
+ /// <param name="overlay">The overlay containing the property values to be overlaid.</param>
+ public static void ApplyConfigurationOverlay(OptionsOverlay overlay) => VolatileOverlayConfigurationSource.Apply(overlay);
+
+ /// <summary>
/// Entrypoint.
/// </summary>
/// <param name="args">Command line arguments.</param>
@@ -1281,7 +1293,8 @@ namespace slskd
.AddCommandLine(
targetType: typeof(Options),
multiValuedArguments,
- commandLine: Environment.CommandLine);
+ commandLine: Environment.CommandLine)
+ .Add(VolatileOverlayConfigurationSource); // this must come last in order to supersede all other sources
}
private static IServiceCollection AddDbContext<T>(this IServiceCollection services, string connectionString)
diff --git a/src/web/src/lib/options.js b/src/web/src/lib/options.js
index 620be946..1c3c55c5 100644
--- a/src/web/src/lib/options.js
+++ b/src/web/src/lib/options.js
@@ -21,5 +21,5 @@ export const validateYaml = async ({ yaml }) => {
};
export const updateYaml = async ({ yaml }) => {
- return (await api.post('/options/yaml', yaml)).data;
+ return (await api.put('/options/yaml', yaml)).data;
};