diff --git a/Utilities/LibMatrix.FederationTest/Controllers/RemoteServerPingController.cs b/Utilities/LibMatrix.FederationTest/Controllers/RemoteServerPingController.cs
new file mode 100644
index 0000000..ce0e119
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/RemoteServerPingController.cs
@@ -0,0 +1,79 @@
+using LibMatrix.Federation;
+using LibMatrix.Federation.Extensions;
+using LibMatrix.FederationTest.Services;
+using LibMatrix.FederationTest.Utilities;
+using LibMatrix.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers;
+
+[ApiController]
+public class RemoteServerPingController(FederationTestConfiguration config, FederationKeyStore keyStore, HomeserverResolverService hsResolver) : ControllerBase {
+ [HttpGet]
+ [Route("/ping/{serverName}")]
+ public async Task<object> PingRemoteServer(string serverName) {
+ Dictionary<string, object> responseMessage = [];
+ var hsResolveResult = await hsResolver.ResolveHomeserverFromWellKnown(serverName, enableClient: false);
+ responseMessage["resolveResult"] = hsResolveResult;
+
+ if (!string.IsNullOrWhiteSpace(hsResolveResult.Server)) {
+ try {
+ var ownKey = keyStore.GetCurrentSigningKey();
+ var hs = new AuthenticatedFederationClient(hsResolveResult.Server, new() {
+ PrivateKey = ownKey.CurrentSigningKey,
+ OriginServerName = config.ServerName
+ });
+ var keys = await hs.GetServerKeysAsync();
+ responseMessage["version"] = await hs.GetServerVersionAsync();
+ responseMessage["keys"] = keys;
+
+ responseMessage["keysAreValid"] = keys.SignaturesById[serverName].ToDictionary(
+ sig => (string)sig.Key,
+ sig => keys.ValidateSignature(serverName, sig.Key, Ed25519Utils.LoadPublicKeyFromEncoded(keys.TypedContent.VerifyKeysById[sig.Key].Key))
+ );
+ }
+ catch (Exception ex) {
+ responseMessage["error"] = new {
+ error = "Failed to connect to remote server",
+ message = ex.Message,
+ st = ex.StackTrace,
+ };
+ return responseMessage;
+ }
+ }
+
+ return responseMessage;
+ }
+
+ [HttpPost]
+ [Route("/ping/")]
+ public async IAsyncEnumerable<KeyValuePair<string, object>> PingRemoteServers([FromBody] List<string>? serverNames) {
+ Dictionary<string, object> responseMessage = [];
+
+ if (serverNames == null || !serverNames.Any()) {
+ responseMessage["error"] = "No server names provided";
+ yield return responseMessage.First();
+ yield break;
+ }
+
+ var results = serverNames!.Select(s => (s, PingRemoteServer(s))).ToList();
+ foreach (var result in results) {
+ var (serverName, pingResult) = result;
+ try {
+ responseMessage[serverName] = await pingResult;
+ if (results.Where(x => !x.Item2.IsCompleted).Select(x => x.s).ToList() is { } servers and not { Count: 0 })
+ Console.WriteLine($"INFO | Waiting for servers: {string.Join(", ", servers)}");
+ }
+ catch (Exception ex) {
+ responseMessage[serverName] = new {
+ error = "Failed to ping remote server",
+ message = ex.Message,
+ st = ex.StackTrace,
+ };
+ }
+
+ yield return new KeyValuePair<string, object>(serverName, responseMessage[serverName]);
+ // await Response.Body.FlushAsync();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/Spec/DirectoryController.cs b/Utilities/LibMatrix.FederationTest/Controllers/Spec/DirectoryController.cs
new file mode 100644
index 0000000..707a149
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/Spec/DirectoryController.cs
@@ -0,0 +1,51 @@
+using System.Net.Http.Headers;
+using LibMatrix.Federation;
+using LibMatrix.FederationTest.Services;
+using LibMatrix.Homeservers;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers.Spec;
+
+[ApiController]
+[Route("_matrix/federation/")]
+public class DirectoryController(ServerAuthService serverAuth) : ControllerBase {
+ [HttpGet("v1/publicRooms")]
+ [HttpPost("v1/publicRooms")]
+ public async Task<IActionResult> GetPublicRooms() {
+ if (Request.Headers.ContainsKey("Authorization")) {
+ Console.WriteLine("INFO | Authorization header found.");
+ await serverAuth.AssertValidAuthentication();
+ }
+ else Console.WriteLine("INFO | Room directory request without auth");
+
+ var rooms = new List<PublicRoomDirectoryResult.PublicRoomListItem> {
+ new() {
+ GuestCanJoin = false,
+ RoomId = "!tuiLEoMqNOQezxILzt:rory.gay",
+ NumJoinedMembers = Random.Shared.Next(),
+ WorldReadable = false,
+ CanonicalAlias = "#libmatrix:rory.gay",
+ Name = "Rory&::LibMatrix",
+ Topic = $"A .NET {Environment.Version.Major} library for interacting with Matrix"
+ }
+ };
+ return Ok(new PublicRoomDirectoryResult() {
+ Chunk = rooms,
+ TotalRoomCountEstimate = rooms.Count
+ });
+ }
+
+ [HttpGet("v1/query/profile")]
+ public async Task<IActionResult> GetProfile([FromQuery(Name = "user_id")] string userId) {
+ if (Request.Headers.ContainsKey("Authorization")) {
+ Console.WriteLine("INFO | Authorization header found.");
+ await serverAuth.AssertValidAuthentication();
+ }
+ else Console.WriteLine("INFO | Profile request without auth");
+
+ return Ok(new {
+ avatar_url = "mxc://rory.gay/ocRVanZoUTCcifcVNwXgbtTg",
+ displayname = "Rory&::LibMatrix.FederationTest"
+ });
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/FederationKeysController.cs b/Utilities/LibMatrix.FederationTest/Controllers/Spec/FederationKeysController.cs
index 33d0b99..d96bef5 100644
--- a/Utilities/LibMatrix.FederationTest/Controllers/FederationKeysController.cs
+++ b/Utilities/LibMatrix.FederationTest/Controllers/Spec/FederationKeysController.cs
@@ -1,10 +1,11 @@
+using LibMatrix.Abstractions;
using LibMatrix.Federation.Extensions;
-using LibMatrix.Federation.Utilities;
using LibMatrix.FederationTest.Services;
using LibMatrix.Homeservers;
+using LibMatrix.Responses.Federation;
using Microsoft.AspNetCore.Mvc;
-namespace LibMatrix.FederationTest.Controllers;
+namespace LibMatrix.FederationTest.Controllers.Spec;
[ApiController]
[Route("_matrix/key/v2/")]
@@ -22,18 +23,19 @@ public class FederationKeysController(FederationTestConfiguration config, Federa
if (_cachedServerKeysResponse == null || _cachedServerKeysResponse.TypedContent.ValidUntil < DateTime.Now + TimeSpan.FromSeconds(30)) {
var keys = keyStore.GetCurrentSigningKey();
_cachedServerKeysResponse = new ServerKeysResponse() {
- ValidUntil = DateTime.Now + TimeSpan.FromMinutes(1),
+ ValidUntil = DateTime.Now + TimeSpan.FromMinutes(5),
ServerName = config.ServerName,
OldVerifyKeys = [],
VerifyKeysById = new() {
{
- new() { Algorithm = "ed25519", KeyId = "0" }, new ServerKeysResponse.CurrentVerifyKey() {
- Key = keys.publicKey.ToUnpaddedBase64(),
+ keys.CurrentSigningKey.KeyId, new ServerKeysResponse.CurrentVerifyKey() {
+ Key = keys.CurrentSigningKey.PublicKey //.ToUnpaddedBase64(),
}
}
}
- }.Sign(config.ServerName, new ServerKeysResponse.VersionedKeyId() { Algorithm = "ed25519", KeyId = "0" }, keys.privateKey);
+ }.Sign(keys.CurrentSigningKey);
}
+
_serverKeyCacheLock.Release();
return _cachedServerKeysResponse;
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/FederationVersionController.cs b/Utilities/LibMatrix.FederationTest/Controllers/Spec/FederationVersionController.cs
index 2c3aaa3..d146cfd 100644
--- a/Utilities/LibMatrix.FederationTest/Controllers/FederationVersionController.cs
+++ b/Utilities/LibMatrix.FederationTest/Controllers/Spec/FederationVersionController.cs
@@ -1,7 +1,8 @@
using LibMatrix.Homeservers;
+using LibMatrix.Responses.Federation;
using Microsoft.AspNetCore.Mvc;
-namespace LibMatrix.FederationTest.Controllers;
+namespace LibMatrix.FederationTest.Controllers.Spec;
[ApiController]
[Route("_matrix/federation/v1/")]
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/Spec/MembershipsController.cs b/Utilities/LibMatrix.FederationTest/Controllers/Spec/MembershipsController.cs
new file mode 100644
index 0000000..7c561ad
--- /dev/null
+++ b/Utilities/LibMatrix.FederationTest/Controllers/Spec/MembershipsController.cs
@@ -0,0 +1,41 @@
+using System.Net.Http.Headers;
+using LibMatrix.Federation;
+using LibMatrix.Federation.FederationTypes;
+using LibMatrix.FederationTest.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace LibMatrix.FederationTest.Controllers.Spec;
+
+[ApiController]
+[Route("_matrix/federation/")]
+public class MembershipsController(ServerAuthService sas) : ControllerBase {
+ [HttpGet("v1/make_join/{roomId}/{userId}")]
+ [HttpPut("v1/send_join/{roomId}/{eventId}")]
+ [HttpPut("v2/send_join/{roomId}/{eventId}")]
+ [HttpGet("v1/make_knock/{roomId}/{userId}")]
+ [HttpPut("v1/send_knock/{roomId}/{eventId}")]
+ [HttpGet("v1/make_leave/{roomId}/{eventId}")]
+ [HttpPut("v1/send_leave/{roomId}/{eventId}")]
+ [HttpPut("v2/send_leave/{roomId}/{eventId}")]
+ public async Task<IActionResult> JoinKnockMemberships() {
+ await sas.AssertValidAuthentication();
+ return NotFound(new MatrixException() {
+ ErrorCode = MatrixException.ErrorCodes.M_NOT_FOUND,
+ Error = "Rory&::LibMatrix.FederationTest does not support membership events."
+ }.GetAsObject());
+ }
+
+ // [HttpPut("v1/invite/{roomId}/{eventId}")]
+ [HttpPut("v2/invite/{roomId}/{eventId}")]
+ public async Task<IActionResult> InviteHandler([FromBody] RoomInvite invite) {
+ await sas.AssertValidAuthentication();
+
+ Console.WriteLine($"Received invite event from {invite.Event.Sender} for room {invite.Event.RoomId} (version {invite.RoomVersion})\n" +
+ $"{invite.InviteRoomState.Count} invite room state events.");
+
+ return NotFound(new MatrixException() {
+ ErrorCode = MatrixException.ErrorCodes.M_NOT_FOUND,
+ Error = "Rory&::LibMatrix.FederationTest does not support membership events."
+ }.GetAsObject());
+ }
+}
\ No newline at end of file
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/WellKnownController.cs b/Utilities/LibMatrix.FederationTest/Controllers/Spec/WellKnownController.cs
index 28fca8d..b91868c 100644
--- a/Utilities/LibMatrix.FederationTest/Controllers/WellKnownController.cs
+++ b/Utilities/LibMatrix.FederationTest/Controllers/Spec/WellKnownController.cs
@@ -1,7 +1,7 @@
using LibMatrix.Services.WellKnownResolver.WellKnownResolvers;
using Microsoft.AspNetCore.Mvc;
-namespace LibMatrix.FederationTest.Controllers;
+namespace LibMatrix.FederationTest.Controllers.Spec;
[ApiController]
[Route(".well-known/")]
diff --git a/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs b/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs
index 4a6bc87..900c8a0 100644
--- a/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs
+++ b/Utilities/LibMatrix.FederationTest/Controllers/TestController.cs
@@ -1,10 +1,8 @@
using System.Text.Json.Nodes;
-using ArcaneLibs.Extensions;
using LibMatrix.Extensions;
using LibMatrix.Federation;
-using LibMatrix.Federation.Utilities;
+using LibMatrix.Federation.Extensions;
using LibMatrix.FederationTest.Services;
-using LibMatrix.Homeservers;
using Microsoft.AspNetCore.Mvc;
namespace LibMatrix.FederationTest.Controllers;
@@ -21,32 +19,33 @@ public class TestController(FederationTestConfiguration config, FederationKeySto
BaseAddress = new Uri("https://matrix.rory.gay")
};
- var keyId = new ServerKeysResponse.VersionedKeyId() {
- Algorithm = "ed25519",
- KeyId = "0"
- };
+ var currentKey = keyStore.GetCurrentSigningKey().CurrentSigningKey;
var signatureData = new XMatrixAuthorizationScheme.XMatrixRequestSignature() {
- Method = "GET",
- Uri = "/_matrix/federation/v1/user/devices/@emma:rory.gay",
- OriginServerName = config.ServerName,
- DestinationServerName = "rory.gay"
- }
- .Sign(config.ServerName, keyId, keyStore.GetCurrentSigningKey().privateKey);
-
- var signature = signatureData.Signatures[config.ServerName][keyId];
- var headerValue = new XMatrixAuthorizationScheme.XMatrixAuthorizationHeader() {
- Origin = config.ServerName,
- Destination = "rory.gay",
- Key = keyId,
- Signature = signature
- }.ToHeaderValue();
+ OriginServerName = config.ServerName,
+ Method = "GET",
+ DestinationServerName = "rory.gay",
+ Uri = "/_matrix/federation/v1/user/devices/@emma:rory.gay",
+ };
+ // .Sign(currentKey);
+ //
+ // var signature = signatureData.Signatures[config.ServerName][currentKey.KeyId];
+ // var headerValue = new XMatrixAuthorizationScheme.XMatrixAuthorizationHeader() {
+ // Origin = config.ServerName,
+ // Key = currentKey.KeyId,
+ // Destination = "rory.gay",
+ // Signature = signature
+ // }.ToHeaderValue();
- var req = new HttpRequestMessage(HttpMethod.Get, "/_matrix/federation/v1/user/devices/@emma:rory.gay");
- req.Headers.Add("Authorization", headerValue);
+ // var req = new HttpRequestMessage(HttpMethod.Get, "/_matrix/federation/v1/user/devices/@emma:rory.gay");
+ // req.Headers.Add("Authorization", headerValue);
+ var req = signatureData.ToSignedHttpRequestMessage(currentKey);
var response = await hc.SendAsync(req);
var content = await response.Content.ReadFromJsonAsync<JsonObject>();
return content!;
}
+
+ // [HttpGet("/testMakeJoin")]
+ // public async Task<JsonObject> GetTestMakeJoin() { }
}
\ No newline at end of file
|