Files
opengenesislinkserver/tools/ci/SysApiSmoke/Program.cs
T

134 lines
6.2 KiB
C#

// SPDX-License-Identifier: MPL-2.0
using System.Net;
using Nini.Config;
using System.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.Json;
using OpenMetaverse;
using OpenSim.Services.Interfaces;
using OpenGenesisLINK.SysApi;
using OpenSim.Framework;
using System.Security.Cryptography;
// Invalid opt-in settings must not crash ROBUST or disable the legacy World API.
var unavailable = new IniConfigSource();
unavailable.Configs.Add("SysApi").Set("Enabled", "true");
new SysApiConnector(unavailable, null!, "SysApi");
var dir = Path.Combine(Path.GetTempPath(), "ogl-sysapi-smoke-" + Guid.NewGuid().ToString("N"));
string first = PortalSecretStore.OpenOrCreate(dir);
string second = PortalSecretStore.OpenOrCreate(dir);
if (first != second || first.Length != 128 || File.ReadAllText(Path.Combine(dir, ".env")).Contains("CorrectSecret"))
throw new Exception("Token store not stable or secure");
if (!OperatingSystem.IsWindows() &&
(File.GetUnixFileMode(Path.Combine(dir, ".env")) &
(UnixFileMode.GroupRead | UnixFileMode.OtherRead)) != 0)
throw new Exception("Secret permissions not private");
using var free = new TcpListener(IPAddress.Loopback, 0);
free.Start();
int port = ((IPEndPoint)free.LocalEndpoint).Port;
free.Stop();
using var host = new SysApiHost(port, "https://sysapi.example.test:8850",
DispatchProxy.Create<IUserAccountService, AccountProxy>(),
DispatchProxy.Create<IAuthenticationService, AuthenticationProxy>(), first);
host.Start();
try
{
using var client = new HttpClient(new HttpClientHandler { UseCookies = true })
{
BaseAddress = new Uri($"http://127.0.0.1:{port}/"),
Timeout = TimeSpan.FromSeconds(8)
};
static void Expect(HttpStatusCode actual, HttpStatusCode desired, string test)
{ if (actual != desired) throw new Exception($"{test}: expected {desired}, got {actual}"); }
using var index = await client.GetAsync("/");
Expect(index.StatusCode, HttpStatusCode.OK, "Index");
if (!(await index.Content.ReadAsStringAsync()).Contains("Control the"))
throw new Exception("Interactive command center absent");
if (!index.Headers.Contains("Content-Security-Policy"))
throw new Exception("Missing restrictive CSP");
foreach (string asset in new[] {"/style.css","/app.js","/ogl-mascot.webp"})
{
using var file = await client.GetAsync(asset);
Expect(file.StatusCode, HttpStatusCode.OK, "asset "+asset);
if (asset.EndsWith(".webp") && (await file.Content.ReadAsByteArrayAsync()).Length < 60000)
throw new Exception("Official OGL mascot asset not embedded");
}
using var health = await client.GetAsync("/v1/health");
Expect(health.StatusCode, HttpStatusCode.OK, "health");
using var anonymous = await client.GetAsync("/api/admin/overview");
Expect(anonymous.StatusCode, HttpStatusCode.Unauthorized, "dashboard 401");
using var noToken = await client.GetAsync("/api/v1/portal/ping");
Expect(noToken.StatusCode, HttpStatusCode.Unauthorized, "portal no token");
client.DefaultRequestHeaders.Authorization = new("Bearer", first);
using var yesToken = await client.GetAsync("/api/v1/portal/ping");
Expect(yesToken.StatusCode, HttpStatusCode.OK, "portal token");
client.DefaultRequestHeaders.Authorization = new("Bearer", new string('a',128));
using var badToken = await client.GetAsync("/api/v1/portal/ping");
Expect(badToken.StatusCode, HttpStatusCode.Unauthorized, "portal wrong token");
client.DefaultRequestHeaders.Authorization = null;
async Task<HttpResponseMessage> LoginAsync(string pw)
{
return await client.PostAsync("/api/session/login",
new StringContent(JsonSerializer.Serialize(new { username="Test Operator",password=pw }),
Encoding.UTF8, "application/json"));
}
using var bad = await LoginAsync("bad-password");
Expect(bad.StatusCode, HttpStatusCode.Unauthorized, "wrong password");
AccountProxy.Level = 199;
using var denied = await LoginAsync("CorrectSecret");
Expect(denied.StatusCode, HttpStatusCode.Forbidden, "user level below 200");
AccountProxy.Level = 200;
using var allowed = await LoginAsync("CorrectSecret");
Expect(allowed.StatusCode, HttpStatusCode.OK, "user level 200");
using var admin = await client.GetAsync("/api/admin/overview");
Expect(admin.StatusCode, HttpStatusCode.OK, "authorized dashboard");
AccountProxy.Level = 0;
using var revoked = await client.GetAsync("/api/admin/overview");
Expect(revoked.StatusCode, HttpStatusCode.Unauthorized, "revoked permission");
var forged = new HttpRequestMessage(HttpMethod.Post,"/api/session/login");
forged.Headers.TryAddWithoutValidation("Origin","https://attacker.example");
forged.Content = new StringContent("{}",Encoding.UTF8,"application/json");
using var forgedResult = await client.SendAsync(forged);
Expect(forgedResult.StatusCode, HttpStatusCode.Forbidden, "cross-origin");
var foreignHost = new HttpRequestMessage(HttpMethod.Get,"/");
foreignHost.Headers.Host="attacker.example";
using var foreign = await client.SendAsync(foreignHost);
Expect(foreign.StatusCode, HttpStatusCode.NotFound, "host binding");
Console.WriteLine("PASS: sys.api avatar UserLevel 200 gate, revoked session, OAuth-free portal token, official mascot, CSP and origin security");
}
finally
{
Directory.Delete(dir,recursive:true);
}
public class AccountProxy : DispatchProxy
{
public static int Level = 199;
public static UUID Principal = UUID.Random();
protected override object? Invoke(MethodInfo? method, object?[]? args)
{
if (method?.Name == "GetUserAccount")
return new UserAccount(UUID.Zero, Principal, "Test", "Operator", "")
{
UserLevel = Level
};
throw new NotImplementedException(method?.Name);
}
}
public class AuthenticationProxy : DispatchProxy
{
protected override object? Invoke(MethodInfo? method, object?[]? args) =>
method?.Name switch
{
"Authenticate" when (string)args![1]! == Util.Md5Hash("CorrectSecret") => UUID.Random().ToString(),
"Authenticate" => "",
"Release" => true,
_ => throw new NotImplementedException(method?.Name)
};
}