From b61c047068ec4c8b44ba058d6cb9ebb1cf6c4dff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:21:43 -0600 Subject: fix ApiKeyOnly policy issue --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 +- src/slskd/Common/Authentication/AuthPolicy.cs | 2 +- src/slskd/Program.cs | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index a41a9d59..7c6c9235 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -34,7 +34,7 @@ namespace slskd.Authentication /// /// Gets the API key authentication scheme name. /// - public static string AuthenticationScheme { get; } = "API Key"; + public static string AuthenticationScheme { get; } = "ApiKey"; } /// diff --git a/src/slskd/Common/Authentication/AuthPolicy.cs b/src/slskd/Common/Authentication/AuthPolicy.cs index 040104da..47d430c9 100644 --- a/src/slskd/Common/Authentication/AuthPolicy.cs +++ b/src/slskd/Common/Authentication/AuthPolicy.cs @@ -23,7 +23,7 @@ namespace slskd public static class AuthPolicy { public const string JwtOnly = "Jwt"; - public const string ApiKeyOnly = "ApiKeyOnly"; + public const string ApiKeyOnly = "ApiKey"; public const string Any = "Any"; } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d0b670a2..28ef7279 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -696,6 +696,12 @@ namespace slskd policy.RequireAuthenticatedUser(); }); + options.AddPolicy(AuthPolicy.ApiKeyOnly, policy => + { + policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme); + policy.RequireAuthenticatedUser(); + }); + options.AddPolicy(AuthPolicy.JwtOnly, policy => { policy.AuthenticationSchemes.Add(PassthroughAuthentication.AuthenticationScheme); -- cgit v1.2.3 From ee01ea15c674882b4e79da9c0364727f1e86c965 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:22:01 -0600 Subject: log file resolution --- src/slskd/Transfers/Uploads/UploadService.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c1184b21..cfbeeb8b 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -121,6 +121,8 @@ namespace slskd.Transfers.Uploads { (host, localFilename) = await Shares.ResolveFileAsync(filename); + Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); + if (host == Program.LocalHostName) { // if it's local, do a quick check to see if it exists to spare the caller from -- cgit v1.2.3 From 3ce9de999597db6ae742722c86a7179c5d3282e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:29:23 -0600 Subject: solve for relay debugging in file resolution logic --- src/slskd/Shares/ShareService.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 8f78ed55..bdc18859 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -26,6 +26,7 @@ namespace slskd.Shares using System.Threading; using System.Threading.Tasks; using Serilog; + using slskd.Relay; using Soulseek; /// @@ -269,10 +270,22 @@ namespace slskd.Shares { string resolvedFilename = Local.Repository.FindFilename(remoteFilename); - if (!string.IsNullOrEmpty(resolvedFilename)) + // when we're debugging the relay (running as both controller and agent on the same instance) + // always resolve files from remote hosts, ignoring local. this is a crappy hack, but it is the + // least crappy way to maintain sanity while trying to debug this feature. + if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum() == RelayMode.Debug) { + Log.Warning("Ignoring resolved local file to facilitate Relay debugging."); + } + else if (!string.IsNullOrEmpty(resolvedFilename)) + { + Log.Debug("Resolved remote file to {ResolvedFilename} on local host", resolvedFilename); return Task.FromResult((Program.LocalHostName, resolvedFilename)); } + else + { + Log.Debug("Failed to resolve remote file on local host; searching remote hosts: {Hosts}", HostDictionary.Values.Select(h => h.Host.Name)); + } // file not found locally. begin searching other hosts one by one. // this is the slow, dumb way to do this, but it's plenty fast in this context. @@ -282,8 +295,11 @@ namespace slskd.Shares if (!string.IsNullOrEmpty(resolvedFilename)) { + Log.Debug("Resolved remote file to {ResolvedFilename} on host {Host}", remoteFilename, host.Host.Name); return Task.FromResult((host.Host.Name, resolvedFilename)); } + + Log.Debug("Failed to resolve remote file on host {Host}", host.Host.Name); } throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a physical file"); -- cgit v1.2.3 From 8bcfe480bc0ec641dedb384a2af8e5f3866dcbb8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:06 -0600 Subject: use named params to avoid issues with positional weirdness --- src/slskd/Relay/API/Controllers/RelayController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index d4fb4810..69087310 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -200,7 +200,7 @@ namespace slskd.Relay // provide the encrypted value as the credential with the request. the validation below verifies a bunch of // things, including that the encrypted value matches the expected value. the goal here is to ensure that the // caller is the same caller that received the request, and that the caller knows the shared secret. - if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) + if (!Relay.TryValidateFileStreamResponseCredential(token: guid, agentName: agentName, filename: filename, credential: credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", guid, agentName); return Unauthorized(); -- cgit v1.2.3 From c0b9ef897914242f4cb0556f5feae73f34914f9f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:38 -0600 Subject: validate filename and stream from multipart uploads --- src/slskd/Relay/API/Controllers/RelayController.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 69087310..a36e643d 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -185,6 +185,16 @@ namespace slskd.Relay var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); filename = contentDisposition.FileName.Value; stream = fileSection.Body; + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentException("Upload filename is null or empty"); + } + + if (stream == null || !stream.CanRead) + { + throw new ArgumentException("Unable to obtain stream from request"); + } } catch (Exception ex) { -- cgit v1.2.3 From 8e73db196759307c89a7e5da1f87d49be9ba56c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 10:30:56 -0600 Subject: remove deprecated parts from multipart upload --- src/slskd/Relay/RelayClient.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index d6bde1d7..f506ab8f 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -321,8 +321,6 @@ namespace slskd.Relay using var content = new MultipartFormDataContent { - { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, - { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; -- cgit v1.2.3 From 87f72f7f482953c90ed50eca647f36827cdd64cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:00 -0600 Subject: polish logging --- src/slskd/Relay/API/Controllers/RelayController.cs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index a36e643d..f6c6d778 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -21,6 +21,7 @@ namespace slskd.Relay { using System; using System.Collections.Generic; + using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -115,7 +116,7 @@ namespace slskd.Relay return BadRequest(); } - Log.Information("Handling file download for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. // this is done to support retries @@ -127,9 +128,9 @@ namespace slskd.Relay var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); - Log.Information("Agent {Agent} authenticated. Sending file {File}", agentName, filename); + Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename); - var stream = new FileStream(Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename), FileMode.Open); + var stream = new FileStream(sourceFile, FileMode.Open); return File(stream, "application/octet-stream"); } @@ -204,7 +205,7 @@ namespace slskd.Relay return BadRequest(); } - Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); + Log.Information("Handling file upload of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // agents must encrypt the Id they were given in the request with the secret they share with the controller, and // provide the encrypted value as the credential with the request. the validation below verifies a bunch of @@ -216,7 +217,7 @@ namespace slskd.Relay return Unauthorized(); } - Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName); + Log.Information("Agent {Agent} authenticated for token {Token}. Forwarding file stream for {Filename}", agentName, guid, filename); // pass the stream back to the relay service, which will in turn pass it to the upload service, and use it to // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. @@ -279,6 +280,8 @@ namespace slskd.Relay return BadRequest(); } + Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName); + if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); @@ -290,14 +293,19 @@ namespace slskd.Relay try { - Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); + Log.Information("Agent {Agent} authenticated for token {Token}. Beginning download of shares to {Filename}", agentName, guid, temp); + + var sw = new Stopwatch(); + sw.Start(); using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); using var inputStream = database.OpenReadStream(); await inputStream.CopyToAsync(outputStream); - Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); + sw.Stop(); + + Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds); await Relay.HandleShareUpload(agentName, id: guid, shares, temp); -- cgit v1.2.3 From f734a9a8cce50e4ed638274758dd1ff0f99e14e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:15 -0600 Subject: polish logging --- src/slskd/Relay/RelayService.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 47879b19..1dda50c2 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -456,7 +456,7 @@ namespace slskd.Relay var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); - Log.Information("Created wait {Key}", key); + Log.Debug("Created wait {Key}", key); try { @@ -624,6 +624,8 @@ namespace slskd.Relay /// The operation context. public Task HandleShareUpload(string agentName, Guid id, IEnumerable shares, string filename) { + Log.Information("Loading shares from agent {Agent}", agentName); + using var repository = ShareRepositoryFactory.CreateFromFile(filename); if (!repository.TryValidate(out var problems)) @@ -637,6 +639,8 @@ namespace slskd.Relay Shares.AddOrUpdateHost(new Host(agentName, shares)); + Log.Information("Shares from agent {Agent} ready.", agentName); + return Task.CompletedTask; } @@ -694,8 +698,12 @@ namespace slskd.Relay if (TryGetAgentRegistration(connectionId, out var found)) { + Log.Information("Unloading shares for agent {Agent}", found.Agent.Name); + Shares.TryRemoveHost(found.Agent.Name); removed = RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); + + Log.Information("Shares for agent {Agent} unloaded", found.Agent.Name); } State.SetValue(state => state with { Agents = RegisteredAgents }); -- cgit v1.2.3 From f07a7758b47388c793d73ca54727db95abfcd229 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Jan 2023 16:14:32 -0600 Subject: localize filename --- src/slskd/Relay/RelayClient.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index f506ab8f..c2d396a8 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -416,6 +416,10 @@ namespace slskd.Relay destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); } + // if the controller is Windows and the agent is Linux or vice versa, we need to translate + // the filename to the local OS or we're going to get funny results when we go to write the file + destinationFile = destinationFile.LocalizePath(); + await Retry.Do(task: async () => { using var request = new HttpRequestMessage(HttpMethod.Get, $"api/v0/relay/downloads/{token}"); -- cgit v1.2.3