add a bunch of authentication stuff

This commit is contained in:
sam 2024-05-19 17:20:45 +02:00
parent 996e59f49a
commit aca83fa1ef
Signed by: sam
GPG key ID: B4EF20DDE721CAA1
22 changed files with 681 additions and 28 deletions

View file

@ -30,12 +30,12 @@ public partial class RequestSigningService
if (!resp.IsSuccessStatusCode)
{
var error = await resp.Content.ReadAsStringAsync();
throw new FoxchatError.OutgoingFederationError($"Request to {domain}/{requestPath} returned an error", DeserializeObject<ApiError>(error));
throw new FoxchatError.OutgoingFederationError($"Request to {domain}{requestPath} returned an error", DeserializeObject<ApiError>(error));
}
var bodyString = await resp.Content.ReadAsStringAsync();
return DeserializeObject<T>(bodyString)
?? throw new FoxchatError.OutgoingFederationError($"Request to {domain}/{requestPath} returned invalid response body");
?? throw new FoxchatError.OutgoingFederationError($"Request to {domain}{requestPath} returned invalid response body");
}
private HttpRequestMessage BuildHttpRequest(HttpMethod method, string domain, string requestPath, string? userId = null, object? bodyData = null)
@ -55,9 +55,7 @@ public partial class RequestSigningService
if (userId != null)
request.Headers.Add(USER_HEADER, userId);
if (body != null)
{
request.Content = new StringContent(body, new MediaTypeHeaderValue("application/json", "utf-8"));
}
return request;
}

View file

@ -2,7 +2,7 @@ using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Foxchat.Core.Database;
using Microsoft.AspNetCore.WebUtilities;
using Foxchat.Core.Utils;
using NodaTime;
using NodaTime.Text;
using Serilog;
@ -28,7 +28,7 @@ public partial class RequestSigningService(ILogger logger, IClock clock, IDataba
var signature = formatter.CreateSignature(hash);
_logger.Debug("Generated signature for {Host} {RequestPath}", data.Host, data.RequestPath);
return WebEncoders.Base64UrlEncode(signature);
return Convert.ToBase64String(signature);
}
public bool VerifySignature(
@ -51,7 +51,11 @@ public partial class RequestSigningService(ILogger logger, IClock clock, IDataba
var plaintext = GeneratePlaintext(new SignatureData(time, host, requestPath, contentLength, userId));
var plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
var hash = SHA256.HashData(plaintextBytes);
var signature = WebEncoders.Base64UrlDecode(encodedSignature);
if (!CryptoUtils.TryFromBase64String(encodedSignature, out var signature))
{
throw new FoxchatError.IncomingFederationError("Invalid base64 signature");
}
var deformatter = new RSAPKCS1SignatureDeformatter(rsa);
deformatter.SetHashAlgorithm(nameof(SHA256));