diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Validation/ValidateAttribute.cs | 36 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 12 | ||||
| -rw-r--r-- | src/slskd/Core/Constants.cs | 23 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 100 | ||||
| -rw-r--r-- | src/slskd/Events/API/EventsController.cs | 33 | ||||
| -rw-r--r-- | src/slskd/Events/EventBus.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Integrations/Pushbullet/PushbulletService.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Integrations/Scripts/ScriptService.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Integrations/Webhooks/WebhookService.cs | 122 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 14 |
10 files changed, 340 insertions, 20 deletions
diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index c7efaa92..540e61bc 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,6 +17,7 @@ namespace slskd.Validation { + using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; @@ -34,22 +35,43 @@ namespace slskd.Validation return ValidationResult.Success; } + // note: here's a great place to log the type and value if there are issues: + // Console.WriteLine($"{value.GetType()}: {value.ToJson()}"); var results = new List<ValidationResult>(); var context = new ValidationContext(value, null, null); - if (value.IsDictionary()) + // we should only be using dictionaries and arrays (e.g. []), not IEnumerable, because the YAML library + // somehow has nondeterministic behavior, sometimes turning YAML arrays into arrays, and sometimes List + // this could be handled by checking for List<T> but let's just keep it simple and remember to use arrays + if (value.IsDictionary() || value is Array) { var compositeResults = new CompositeValidationResult(validationContext.DisplayName); - // given the context in this application, key type should never be anything but a string - foreach (string key in ((IDictionary)value).Keys) + if (value.IsDictionary()) { - var val = ((IDictionary)value)[key]; - var result = IsValid(val, new ValidationContext(val, null, null)); + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); - if (result != ValidationResult.Success) + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + } + else if (value is Array array) + { + for (int i = 0; i < array.Length; i++) { - compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + var val = array.GetValue(i); + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(i.ToString(), new[] { result }.ToList())); + } } } diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 790b6b3d..be646ae7 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -26,6 +26,7 @@ namespace slskd.Core.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; + using Serilog; /// <summary> /// Application. @@ -53,6 +54,7 @@ namespace slskd.Core.API private IStateMonitor<State> ApplicationStateMonitor { get; } private IOptionsMonitor<Options> OptionsMonitor { get; } private IHostApplicationLifetime Lifetime { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<ApplicationController>(); /// <summary> /// Gets the current state of the application. @@ -149,5 +151,13 @@ namespace slskd.Core.API return PhysicalFile(file, "application/octet-stream", "slskd.dmp"); } + + [HttpPost("loopback")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult Loopback([FromBody] object body) + { + Log.Information("Loopback POST: {Body}", body); + return Ok(); + } } -} +}
\ No newline at end of file diff --git a/src/slskd/Core/Constants.cs b/src/slskd/Core/Constants.cs new file mode 100644 index 00000000..380a3519 --- /dev/null +++ b/src/slskd/Core/Constants.cs @@ -0,0 +1,23 @@ +// <copyright file="Constants.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; + +public static class Constants +{ + public static readonly string IgnoreCertificateErrors = nameof(IgnoreCertificateErrors); +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 306f9b87..e5f16b1e 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2006,6 +2006,12 @@ namespace slskd public class IntegrationOptions { /// <summary> + /// Gets webhook configuration. + /// </summary> + [Validate] + public Dictionary<string, WebhookOptions> Webhooks { get; init; } = []; + + /// <summary> /// Gets script configuration. /// </summary> [Validate] @@ -2024,6 +2030,100 @@ namespace slskd public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); /// <summary> + /// Webhook configuration. + /// </summary> + public class WebhookOptions + { + /// <summary> + /// Gets the list of Event types that trigger the webhook. + /// </summary> + [Enum(typeof(EventType))] + public string[] On { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Gets details about the webhook call. + /// </summary> + [Validate] + public WebhookHttpOptions Call { get; init; } = new WebhookHttpOptions(); + + /// <summary> + /// Gets the time to wait before timing out, in milliseconds. + /// </summary> + [Range(500, int.MaxValue)] + public int Timeout { get; init; } = 5000; + + /// <summary> + /// Gets the retry configuration. + /// </summary> + [Validate] + public RetryOptions Retry { get; init; } = new RetryOptions(); + } + + /// <summary> + /// Webhook HTTP options. + /// </summary> + public class WebhookHttpOptions : IValidatableObject + { + /// <summary> + /// Gets the fully qualified URL for the webhook. + /// </summary> + [NotNullOrWhiteSpace] + public string Url { get; init; } + + /// <summary> + /// Gets the HTTP headers to include with the webhook. + /// </summary> + [Validate] + public WebhookHttpHeader[] Headers { get; init; } = []; + + /// <summary> + /// Gets a value indicating whether HTTPS certificate errors should be ignored. + /// </summary> + public bool IgnoreCertificateErrors { get; init; } = false; + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (!Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + results.Add(new ValidationResult($"The {nameof(Url)} field must contain a fully qualified URL, including protocol (e.g. http:// or https://)")); + } + + return results; + } + } + + /// <summary> + /// Webhook HTTP header configuration. + /// </summary> + public class WebhookHttpHeader + { + /// <summary> + /// Gets the name of the header. + /// </summary> + [NotNullOrWhiteSpace] + public string Name { get; init; } + + /// <summary> + /// Gets the header's value. + /// </summary> + public string Value { get; init; } + } + + /// <summary> + /// Retry configuration. + /// </summary> + public class RetryOptions + { + /// <summary> + /// Gets the number of attempts to make before failing. + /// </summary> + [Range(1, int.MaxValue)] + public int Attempts { get; init; } = 1; + } + + /// <summary> /// Script configuration. /// </summary> public class ScriptOptions diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index e9780fad..46afa5c7 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -17,6 +17,8 @@ namespace slskd.Events.API; +using System; +using System.Collections.Generic; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -42,13 +44,24 @@ public class EventsController : ControllerBase private EventService Events { get; } private ILogger Log { get; } = Serilog.Log.ForContext<EventsController>(); - [HttpGet("")] + /// <summary> + /// Retrieves a paginated list of past <see cref="Event"/> records. + /// </summary> + /// <param name="offset">The offset (number of records) at which to start the requested page.</param> + /// <param name="limit">The page size.</param> + /// <returns>The list of <see cref="Event"/> records.</returns> + [HttpGet("", Name = nameof(GetEvents))] [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(typeof(string), 400)] + [ProducesResponseType(401)] + [ProducesResponseType(403)] + [ProducesResponseType(typeof(IEnumerable<EventRecord>), 200)] + [ProducesResponseType(typeof(string), 500)] public IActionResult GetEvents([FromQuery] int offset = 0, [FromQuery] int limit = 100) { if (offset < 0) { - return BadRequest("Offset must be greater than or equal to zero."); + return BadRequest("Offset must be greater than or equal to zero"); } if (limit <= 0) @@ -56,11 +69,19 @@ public class EventsController : ControllerBase return BadRequest("Limit must be greater than zero"); } - var events = Events.Get(offset, limit); - var count = Events.Count(); + try + { + var eventRecords = Events.Get(offset, limit); + var count = Events.Count(); - Response.Headers.Append("X-Total-Count", count.ToString()); + Response.Headers.Append("X-Total-Count", count.ToString()); - return Ok(events); + return Ok(eventRecords); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list events: {Message}", ex.Message); + throw; + } } }
\ No newline at end of file diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 16b7c9e1..ae3350f0 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -88,7 +88,9 @@ public class EventBus // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func<T, Task>)(data)) - .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); + .ContinueWith( + task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message), + continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } else { @@ -103,7 +105,9 @@ public class EventBus // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func<Event, Task>)(data)) - .ContinueWith(task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message)))); + .ContinueWith( + task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message), + continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } } diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index 5328f4d6..29033381 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -145,9 +145,13 @@ namespace slskd.Integrations.Pushbullet Log.LogDebug("Sending Pushbullet notification {Title} {Body}", title, body); await Retry.Do( - task: () => http.PostAsync(PushUri, content), + task: async () => + { + using var response = await http.PostAsync(PushUri, content); + response.EnsureSuccessStatusCode(); + }, isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => Log.LogWarning("Failed attempt {Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), + onFailure: (attempts, ex) => Log.LogWarning("Failed attempt #{Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), maxAttempts: PushbulletOptions.RetryAttempts, maxDelayInMilliseconds: 30000); diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs index 48916b2d..227f2fb1 100644 --- a/src/slskd/Integrations/Scripts/ScriptService.cs +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -120,7 +120,7 @@ public class ScriptService } catch (Exception ex) { - Log.Warning(ex, "Failed to run script '{Script}': {Message}", script.Key, ex.Message); + Log.Warning(ex, "Failed to run script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); } finally { @@ -130,7 +130,7 @@ public class ScriptService } catch (Exception ex) { - Log.Warning(ex, "Failed to clean up process started from script '{Script}': {Message}", script.Key, ex.Message); + Log.Warning(ex, "Failed to clean up process started from script '{Script}' for event type {Event}: {Message}", script.Key, data.Type, ex.Message); } } }); diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs new file mode 100644 index 00000000..62f097b7 --- /dev/null +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -0,0 +1,122 @@ +// <copyright file="WebhookService.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> + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.Webhooks; + +using System; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using Serilog; +using slskd.Events; + +public class WebhookService +{ + public WebhookService( + EventBus eventBus, + IOptionsMonitor<Options> optionsMonitor, + IHttpClientFactory httpClientFactory) + { + Events = eventBus; + OptionsMonitor = optionsMonitor; + HttpClientFactory = httpClientFactory; + + Events.Subscribe<Event>(nameof(WebhookService), HandleEvent); + + Log.Debug("{Service} initialized", nameof(WebhookService)); + } + + private ILogger Log { get; } = Serilog.Log.ForContext<WebhookService>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } + private EventBus Events { get; } + private IHttpClientFactory HttpClientFactory { get; } + + private async Task HandleEvent(Event data) + { + await Task.Yield(); + + Log.Debug("Handling event {Event}", data); + + bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase); + bool EqualsLiterallyAnyEvent(string type) => type.Equals(EventType.Any.ToString(), StringComparison.OrdinalIgnoreCase); + + var options = OptionsMonitor.CurrentValue; + var webhooksTriggeredByThisEventType = options.Integration.Webhooks + .Where(kvp => kvp.Value.On.Any(EqualsThisEvent) || kvp.Value.On.Any(EqualsLiterallyAnyEvent)); + + foreach (var webhook in webhooksTriggeredByThisEventType) + { + _ = Task.Run(async () => + { + var call = webhook.Value.Call; + + using var http = call.IgnoreCertificateErrors + ? HttpClientFactory.CreateClient(Constants.IgnoreCertificateErrors) + : HttpClientFactory.CreateClient(); + + http.Timeout = TimeSpan.FromMilliseconds(webhook.Value.Timeout); + + foreach (var header in call.Headers) + { + http.DefaultRequestHeaders.TryAddWithoutValidation(header.Name, header.Value); + } + + var content = new StringContent(data.ToJson(), Encoding.UTF8, "application/json"); + + HttpStatusCode? statusCode = null; + + try + { + Log.Debug("Calling webhook '{Name}': {Url}", webhook.Key, webhook.Value.Call.Url); + + var sw = Stopwatch.StartNew(); + + await Retry.Do( + task: async () => + { + using var response = await http.PostAsync(call.Url, content); + response.EnsureSuccessStatusCode(); + statusCode = response.StatusCode; + }, + isRetryable: (attempts, ex) => true, // retry everything + onFailure: (attempts, ex) => + { + if (webhook.Value.Retry.Attempts > 1) + { + Log.Warning(ex, "Failed attempt #{Attempts} to send webhook '{Name}' for event type {Event}: {Message}", attempts, webhook.Key, data.Type, ex.Message); + } + }, + maxAttempts: webhook.Value.Retry.Attempts, + maxDelayInMilliseconds: 30000); + + sw.Stop(); + + Log.Debug("Webhook '{Name}' called successfully in {Duration}ms; status code: {StatusCode}", webhook.Key, sw.ElapsedMilliseconds, statusCode); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to call webhook '{Name}' for event type {Event} after exhausting retries: {Message}", webhook.Key, data.Type, ex.Message); + } + }); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f18d9c09..1ac798c1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -26,6 +26,7 @@ namespace slskd using System.IO; using System.Linq; using System.Net; + using System.Net.Http; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -61,6 +62,7 @@ namespace slskd using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Integrations.Scripts; + using slskd.Integrations.Webhooks; using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -488,6 +490,7 @@ namespace slskd // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService<ScriptService>(); + _ = app.Services.GetService<WebhookService>(); app.ConfigureAspDotNetPipeline(); @@ -544,6 +547,15 @@ namespace slskd // this is important to prevent memory leaks services.AddHttpClient(); + // add a special HttpClientFactory to DI that disables SSL. access it via: + // 'using var http = HttpClientFactory.CreateClient(Constants.IgnoreCertificateErrors)' + // thanks Microsoft, makes total sense and surely won't be easy to fuck up later! + services.AddHttpClient(Constants.IgnoreCertificateErrors) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler + { + ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, + }); + // add a partially configured instance of SoulseekClient. the Application instance will // complete configuration at startup. services.AddSingleton<ISoulseekClient, SoulseekClient>(_ => @@ -583,6 +595,7 @@ namespace slskd services.AddSingleton<EventBus>(); services.AddSingleton<ScriptService>(); + services.AddSingleton<WebhookService>(); services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); @@ -836,6 +849,7 @@ namespace slskd private static WebApplication ConfigureAspDotNetPipeline(this WebApplication app) { + // stop ASP.NET from sending a full stack trace and ProblemDetails for unhandled exceptions app.UseExceptionHandler(a => a.Run(async context => { await context.Response.WriteAsJsonAsync(context.Features.Get<IExceptionHandlerPathFeature>().Error.Message); |
