Restore all production-proven SYS.API citizen-rules, policy and resident-management sources and assets, keep secure POST login plus authenticated NexBus global alerts, restore live OglLiveAccessPolicy and login-service/bridge dependencies; add fail-closed citizen policy regressions and full SYS.API smoke guard. Production restored, isolated build and HTTP smoke passed. NexVerse CI and source gates passed; Linux/Windows/ARM64 builds and ROBUST boot passed, artifact uploads blocked by GitHub quota.
221 lines
9.8 KiB
C#
221 lines
9.8 KiB
C#
// SPDX-License-Identifier: LicenseRef-OpenGenesisLINK-EULA
|
|
// SYS.API admin-only bridge to the private loopback OGL Update Center.
|
|
// No node credentials or private repository access are ever exposed.
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using log4net;
|
|
|
|
namespace OpenGenesisLINK.SysApi;
|
|
|
|
internal static class SysApiUpdatePublisher
|
|
{
|
|
private static readonly ILog Log = LogManager.GetLogger(typeof(SysApiUpdatePublisher));
|
|
private static readonly HttpClient Client = new(
|
|
new HttpClientHandler { AllowAutoRedirect = false })
|
|
{ Timeout = TimeSpan.FromMinutes(12) };
|
|
private static readonly Uri Base = new("http://127.0.0.1:19052/");
|
|
private static readonly Regex ReleaseId = new(
|
|
@"^g1-[0-9]{1,4}(?:\.[0-9]{1,4}){3}-(?:linux|windows)-(?:x64|arm64)$",
|
|
RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
|
private static readonly Regex Version = new(
|
|
@"^[0-9]{1,4}(?:\.[0-9]{1,4}){3}$",
|
|
RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
|
private const long MaxUpload = 768L * 1024 * 1024;
|
|
private const string SecretPath = "/etc/ogl-updateservice/sysapi-publisher.env";
|
|
|
|
private sealed record PublishInput(string Id, string Sha256, string Notes, bool Confirm);
|
|
|
|
private static string? PublisherCredential()
|
|
{
|
|
// Robust owns the host and reads a local 0600 file. The credential is
|
|
// not in any /etc/ogl-update-nodes file, browser cookie, or API result.
|
|
try
|
|
{
|
|
string line = File.ReadLines(SecretPath).FirstOrDefault(x =>
|
|
x.StartsWith("OGL_UPDATE_PUBLISH_TOKEN=", StringComparison.Ordinal)) ?? "";
|
|
string token = line["OGL_UPDATE_PUBLISH_TOKEN=".Length..].Trim();
|
|
return token.Length is >= 48 and <= 128 &&
|
|
token.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')
|
|
? token : null;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Log.Warn("[SYS.API UPDATES] Publisher credential unavailable: " + e.GetType().Name);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static async Task Reply(HttpListenerResponse r, int code, object message)
|
|
{
|
|
byte[] data = JsonSerializer.SerializeToUtf8Bytes(message,
|
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
|
r.StatusCode = code;
|
|
r.ContentType = "application/json; charset=utf-8";
|
|
r.ContentLength64 = data.LongLength;
|
|
await r.OutputStream.WriteAsync(data);
|
|
}
|
|
|
|
private static async Task Proxy(HttpListenerResponse response,
|
|
HttpRequestMessage request, CancellationToken stop)
|
|
{
|
|
string? secret = PublisherCredential();
|
|
if (secret is null)
|
|
{
|
|
await Reply(response, 503, new { error = "Updateverwaltung zentral nicht bereit." });
|
|
return;
|
|
}
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", secret);
|
|
try
|
|
{
|
|
using HttpResponseMessage upstream = await Client.SendAsync(request,
|
|
HttpCompletionOption.ResponseHeadersRead, stop);
|
|
if (upstream.Content.Headers.ContentLength is > 1048576)
|
|
{
|
|
await Reply(response, 502, new { error = "Ungültige Antwort des Updatecenters." });
|
|
return;
|
|
}
|
|
await using Stream data = await upstream.Content.ReadAsStreamAsync(stop);
|
|
using var stream = new MemoryStream();
|
|
byte[] buffer = new byte[8192];
|
|
int n;
|
|
while ((n = await data.ReadAsync(buffer, stop)) != 0)
|
|
{
|
|
if (stream.Length + n > 1048576)
|
|
{
|
|
await Reply(response, 502, new { error = "Updatecenter antwortet zu umfangreich." });
|
|
return;
|
|
}
|
|
await stream.WriteAsync(buffer.AsMemory(0, n), stop);
|
|
}
|
|
// The central service only returns JSON; do not relay arbitrary HTML.
|
|
try
|
|
{
|
|
using JsonDocument json = JsonDocument.Parse(stream.ToArray());
|
|
await Reply(response, (int)upstream.StatusCode, json.RootElement);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
await Reply(response, 502, new { error = "Ungültige Updatecenter-Antwort." });
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Warn("[SYS.API UPDATES] Updatecenter communication unavailable (" +
|
|
ex.GetType().Name + ")");
|
|
await Reply(response, 503, new { error = "Updatecenter derzeit nicht erreichbar." });
|
|
}
|
|
}
|
|
|
|
public static async Task Handle(HttpListenerRequest request,
|
|
HttpListenerResponse response, string route, CancellationToken stop)
|
|
{
|
|
if (request.HttpMethod == "GET" && route == "/api/admin/updates")
|
|
{
|
|
using var get = new HttpRequestMessage(HttpMethod.Get,
|
|
new Uri(Base, "/v1/admin/releases"));
|
|
await Proxy(response, get, stop);
|
|
return;
|
|
}
|
|
if (request.HttpMethod == "POST" && route == "/api/admin/updates/stage")
|
|
{
|
|
string? type = request.ContentType?.Split(';',2)[0].Trim();
|
|
if (!string.Equals(type, "application/zip", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
await Reply(response, 415, new { error = "Bitte ein ZIP-Binärpaket auswählen." });
|
|
return;
|
|
}
|
|
long length = request.ContentLength64;
|
|
if (length is < 100 or > MaxUpload)
|
|
{
|
|
await Reply(response, 413, new { error = "ZIP-Datei muss 100 Byte bis 768 MiB groß sein." });
|
|
return;
|
|
}
|
|
var query = System.Web.HttpUtility.ParseQueryString(request.Url?.Query ?? "");
|
|
string version = query["version"] ?? "";
|
|
string os = query["os"] ?? "";
|
|
string arch = query["arch"] ?? "";
|
|
if (!Version.IsMatch(version) ||
|
|
os is not ("linux" or "windows") ||
|
|
arch is not ("x64" or "arm64") ||
|
|
query.AllKeys.Length != 3)
|
|
{
|
|
await Reply(response, 400, new { error = "Version, Zielsystem oder Architektur ungültig." });
|
|
return;
|
|
}
|
|
string path = "/v1/admin/releases/stage?version=" +
|
|
Uri.EscapeDataString(version) + "&os=" + os + "&arch=" + arch;
|
|
using var upstream = new HttpRequestMessage(HttpMethod.Post, new Uri(Base, path));
|
|
upstream.Content = new StreamContent(request.InputStream, 131072);
|
|
upstream.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
|
|
upstream.Content.Headers.ContentLength = length;
|
|
await Proxy(response, upstream, stop);
|
|
return;
|
|
}
|
|
if (request.HttpMethod == "POST" && route == "/api/admin/updates/publish")
|
|
{
|
|
if (request.ContentLength64 is < 5 or > 4096 ||
|
|
!(request.ContentType?.StartsWith("application/json",
|
|
StringComparison.OrdinalIgnoreCase) ?? false))
|
|
{
|
|
await Reply(response, 400, new { error = "Ungültige Veröffentlichungsanfrage." });
|
|
return;
|
|
}
|
|
try
|
|
{
|
|
using var input = new MemoryStream();
|
|
await request.InputStream.CopyToAsync(input, stop);
|
|
if (input.Length > 4096) throw new JsonException();
|
|
var body = JsonSerializer.Deserialize<PublishInput>(input.ToArray(),
|
|
new JsonSerializerOptions(JsonSerializerDefaults.Web));
|
|
if (body is null || !ReleaseId.IsMatch(body.Id) ||
|
|
body.Sha256.Length != 64 || !body.Sha256.All(Uri.IsHexDigit) ||
|
|
body.Notes.Length > 2000 || !body.Confirm)
|
|
throw new JsonException();
|
|
using var publish = new HttpRequestMessage(HttpMethod.Post,
|
|
new Uri(Base, "/v1/admin/releases/publish"));
|
|
publish.Content = new StringContent(
|
|
JsonSerializer.Serialize(body, new JsonSerializerOptions(JsonSerializerDefaults.Web)),
|
|
Encoding.UTF8, "application/json");
|
|
await Proxy(response, publish, stop);
|
|
}
|
|
catch (Exception ex) when (ex is JsonException or ArgumentException or NullReferenceException)
|
|
{
|
|
await Reply(response, 400, new { error = "Ungültige Freigabedaten." });
|
|
}
|
|
return;
|
|
}
|
|
if (request.HttpMethod == "DELETE" &&
|
|
route.StartsWith("/api/admin/updates/staged/", StringComparison.Ordinal))
|
|
{
|
|
string id = route["/api/admin/updates/staged/".Length..];
|
|
if (!ReleaseId.IsMatch(id))
|
|
{
|
|
await Reply(response, 400, new { error = "Releasekennung ungültig." });
|
|
return;
|
|
}
|
|
using var delete = new HttpRequestMessage(HttpMethod.Delete,
|
|
new Uri(Base, "/v1/admin/releases/pending/" + id));
|
|
await Proxy(response, delete, stop);
|
|
return;
|
|
}
|
|
if (request.HttpMethod == "DELETE" &&
|
|
route.StartsWith("/api/admin/updates/releases/", StringComparison.Ordinal))
|
|
{
|
|
string id = route["/api/admin/updates/releases/".Length..];
|
|
if (!ReleaseId.IsMatch(id))
|
|
{
|
|
await Reply(response, 400, new { error = "Releasekennung ungültig." });
|
|
return;
|
|
}
|
|
using var withdraw = new HttpRequestMessage(HttpMethod.Delete,
|
|
new Uri(Base, "/v1/admin/releases/" + id));
|
|
await Proxy(response, withdraw, stop);
|
|
return;
|
|
}
|
|
await Reply(response, 404, new { error = "Unbekannte Updatefunktion." });
|
|
}
|
|
}
|