feat(IAR): avatar-owned World API import/export, >100MiB chunk transfer, live status and MD5 (#350)

* feat(iar): pure safe archive path, fixed-size chunks, and conservative ETA model

* feat(iar): authenticated self-service chunked upload, ownership-bound progress, ranged export, MD5/SHA256

* fix(iar): bind resident authorization to validated token principal Subject

* feat(iar): expose resident self-service endpoint under owner-bound /api/v1/iar/me

* fix(iar): report malformed JSON as safe client error

* config(iar): add opt-in self-service shared archive storage on ROBUST

* config(iar): add opt-in self-service shared archive storage on ROBUST

* config(iar): add opt-in self-service shared archive storage on ROBUST

* security(iar): mark self-service archive jobs for strict export permission filtering

* security(iar): self-service export filters no-copy and no-transfer assets

* test(iar): self-service chunk boundaries and ETA regression

* test(iar): self-service chunk boundaries and ETA regression

* test(iar): enforce ownership, copy-transfer filtering, chunk bounds, hashes and safe disabled defaults

* ci(iar): exercise resident self-service transfer policy and authorization contracts

* docs(iar): configure shared-storage self-service, chunked >100MiB import/export and per-user job progress

* feat(iar): interactive browser upload/export dashboard with 2s status polling and large-file chunking

* test(iar): validate documented per-user operation endpoint and interactive portal widget

* docs(iar): add OAuth-aware interactive portal widget integration and browser capability limits

* fix(iar): fail and remove bad hashes, expire abandoned uploads, allow safe owner-only deletion

* test(iar): require expiry and cleanup for aborted/corrupt uploads

* docs(iar): document owner-only deletion, expired upload cleanup and checksum rejection
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-29 22:20:21 +01:00
1 parent d66c32118f
commit e20a446957
13 files changed
+1274 -1

No files matched your search

+7
View File
@@ -228,6 +228,13 @@ jobs:
shell: bash
run: python3 tools/ci/verify_job_engine.py
- name: Verify IAR self-service bounded transfer, ownership and ETA
shell: bash
run: |
set -euo pipefail
python3 tools/ci/verify_iar_self_service.py
dotnet run --configuration Release --project tools/ci/OglIarSelfServiceRegression/OglIarSelfServiceRegression.csproj
- name: Verify OAR/IAR Job Engine integration
shell: bash
run: python3 tools/ci/verify_job_api_integration.py
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: MPL-2.0
// Pure filename/offset/ETA policy for authenticated IAR transfer.
// Files live under SharedRoot/<trusted Region UUID>/<job GUID>.iar.
// The same SharedRoot must be mounted on ROBUST and on the target simulator.
using System;
using System.IO;
namespace NexVerse.Core.Archives
{
public static class OglIarTransferPolicy
{
public const int MaximumChunkBytes = 4 * 1024 * 1024;
public const long DefaultMaximumArchiveBytes = 2L * 1024 * 1024 * 1024;
public static string Resolve(string sharedRoot, Guid regionId, Guid jobId)
{
if (string.IsNullOrWhiteSpace(sharedRoot) || regionId == Guid.Empty ||
jobId == Guid.Empty)
throw new ArgumentException("Shared root, region and job must be configured.");
string root = Path.GetFullPath(sharedRoot);
if (root == Path.GetPathRoot(root))
throw new ArgumentException("Archive root must not be a filesystem root.");
return Path.Combine(root, regionId.ToString("D"), jobId.ToString("D") + ".iar");
}
public static bool AcceptChunk(long currentBytes, long offset,
long bytes, long expectedTotal, long maximumTotal)
{
return currentBytes >= 0 && offset == currentBytes &&
bytes > 0 && bytes <= MaximumChunkBytes &&
expectedTotal > 0 && expectedTotal <= maximumTotal &&
currentBytes <= expectedTotal &&
bytes <= expectedTotal - currentBytes;
}
// ETA is deliberately unavailable before real progress (or when
// stalled), rather than presenting a fabricated countdown.
public static long? EtaSeconds(long complete, long total,
DateTimeOffset createdAt, DateTimeOffset now)
{
if (total <= 0 || complete <= 0 || complete >= total ||
now <= createdAt)
return null;
double elapsed = (now - createdAt).TotalSeconds;
if (elapsed < 2.0) return null;
double remaining = (total - complete) * elapsed / complete;
if (double.IsNaN(remaining) || double.IsInfinity(remaining) ||
remaining > 7.0 * 86400.0)
return null;
return Math.Max(1L, (long)Math.Ceiling(remaining));
}
public static long? EtaFromJob(int percent, DateTimeOffset? startedAt,
DateTimeOffset now)
{
if (!startedAt.HasValue || percent <= 0 || percent >= 100)
return null;
return EtaSeconds(percent, 100, startedAt.Value, now);
}
}
}
@@ -1975,7 +1975,11 @@ namespace NexVerse.RegionModules.NodeAgent
bool dryRun = nexEvent.Data.TryGetValue("dry_run", out string dryRaw) && bool.TryParse(dryRaw, out bool dry) && dry;
bool merge = nexEvent.Data.TryGetValue("merge", out string mergeRaw) && bool.TryParse(mergeRaw, out bool mergeParsed) && mergeParsed;
OglIarOperation operation = string.Equals(action, "export", StringComparison.OrdinalIgnoreCase)
? operations.StartExport(operationId, user, inventoryPath, fileName)
? operations.StartExport(operationId, user, inventoryPath, fileName,
nexEvent.Data.TryGetValue("self_service", out string selfService) &&
string.Equals(selfService, "true", StringComparison.OrdinalIgnoreCase)
? new Dictionary<string, object> { ["checkPermissions"] = "CT" }
: null)
: string.Equals(action, "import", StringComparison.OrdinalIgnoreCase)
? operations.StartImport(operationId, user, inventoryPath, fileName, merge, dryRun)
: throw new InvalidOperationException("unsupported_iar_action");
@@ -1079,6 +1079,19 @@ namespace NexVerse.Server.Api
"OpenGenesisLINK OAR API"),
true);
// Resident self-service is a distinct owner-bound API.
// Register it on the longer /me prefix so it cannot fall
// through to the administrator's RegionsManage route.
OglIarSelfServiceApi iarSelfService = new OglIarSelfServiceApi(
config, authenticator, nodeRegistry, jobBridge,
jobStore, eventBus, featureControl);
server.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/api/v1/iar/me",
apiGate.Wrap(iarSelfService.Handle),
"OpenGenesisLINK resident IAR self-service"),
true);
OglIarApi iarApi = new OglIarApi(authenticator, nodeRegistry, userAccounts, eventBus, jobBridge, featureControl);
server.AddSimpleStreamHandler(
new SimpleStreamHandler(
+534
View File
@@ -0,0 +1,534 @@
// SPDX-License-Identifier: MPL-2.0
// Authenticated resident-owned IAR transfer over the World API.
// Bounded binary blocks support archives well over 100 MiB without
// buffering the complete HTTP body in ROBUST. Requires explicit
// ROBUST/simulator shared storage, no bus transport of archive bytes.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using NexVerse.Core.Archives;
using NexVerse.Core.ControlPlane;
using NexVerse.Core.Jobs;
using NexVerse.Core.Messaging;
using NexVerse.Core.Security;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using Nini.Config;
namespace NexVerse.Server.Api
{
internal sealed class OglIarSelfServiceApi
{
private readonly NexApiAuthenticator m_Auth;
private readonly NexNodeRegistry m_Nodes;
private readonly OglJobEventBridge m_Bridge;
private readonly IOglJobStore m_Jobs;
private readonly INexEventBus m_Bus;
private readonly OglFeatureControlApi m_Features;
private readonly bool m_Enabled;
private readonly string m_SharedRoot;
private readonly long m_MaxBytes;
private readonly ConcurrentDictionary<string, object> m_Locks = new();
public OglIarSelfServiceApi(IConfigSource config,
NexApiAuthenticator auth, NexNodeRegistry nodes,
OglJobEventBridge bridge, IOglJobStore jobs, INexEventBus bus,
OglFeatureControlApi features)
{
m_Auth = auth; m_Nodes = nodes; m_Bridge = bridge;
m_Jobs = jobs; m_Bus = bus; m_Features = features;
IConfig section = config?.Configs["OglIarSelfService"];
string root = section?.GetString("SharedStorageRoot", "")?.Trim() ?? "";
long maxMib = section?.GetLong("MaximumArchiveMiB", 2048) ?? 2048;
// Fail-closed: must explicitly enable with nonempty shared storage.
m_Enabled = section?.GetBoolean("Enabled", false) == true &&
root.Length > 0 && maxMib >= 101 && maxMib <= 10240;
m_SharedRoot = m_Enabled ? Path.GetFullPath(root) : string.Empty;
m_MaxBytes = checked(Math.Clamp(maxMib, 101, 10240) * 1024L * 1024);
if (m_Enabled && m_SharedRoot == Path.GetPathRoot(m_SharedRoot))
m_Enabled = false;
}
public void Handle(IOSHttpRequest request, IOSHttpResponse response)
{
response.AddHeader("Cache-Control", "no-store");
response.AddHeader("X-Content-Type-Options", "nosniff");
if (!m_Enabled)
{
Error(response, HttpStatusCode.ServiceUnavailable, "iar_self_service_disabled");
return;
}
string method = request?.HttpMethod ?? "";
string path = (request?.UriPath ?? "").TrimEnd('/');
bool read = method.Equals("GET", StringComparison.OrdinalIgnoreCase);
string scope = read ? NexScopes.InventoryRead : NexScopes.InventoryWrite;
if (path == "/api/v1/iar/me/export" && method == "POST")
scope = NexScopes.InventoryRead;
if (!m_Auth.TryAuthenticate(request, scope,
out NexPrincipal principal, out UserAccount user,
out int authStatus, out string authError))
{
response.AddHeader("WWW-Authenticate", "Bearer");
Error(response, (HttpStatusCode)authStatus, authError);
return;
}
// A service/API-key principal is not an authenticated avatar.
// NEVER accept a user_id/owner_id from request data.
if (user == null || user.PrincipalID == UUID.Zero ||
!string.Equals(principal.Subject, user.PrincipalID.ToString(),
StringComparison.OrdinalIgnoreCase))
{
Error(response, HttpStatusCode.Forbidden, "resident_token_required");
return;
}
try
{
if (path == "/api/v1/iar/me/export" && method == "POST")
{ Start(request, response, user, "export"); return; }
if (path == "/api/v1/iar/me/import" && method == "POST")
{ Start(request, response, user, "import"); return; }
const string prefix = "/api/v1/iar/me/operations/";
if (!path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{ Error(response, HttpStatusCode.NotFound, "unknown_iar_route"); return; }
string[] parts = path.Substring(prefix.Length).Split('/');
if (parts.Length == 0 || !Guid.TryParseExact(parts[0], "D", out Guid id))
{ Error(response, HttpStatusCode.NotFound, "invalid_operation_id"); return; }
OglJobSnapshot job = OwnJob(user, id);
if (job == null)
{ Error(response, HttpStatusCode.NotFound, "operation_not_found"); return; }
if (parts.Length == 1 && read)
{ Status(response, job); return; }
if (parts.Length == 1 && method == "DELETE")
{ DeleteArchive(response, job); return; }
if (parts.Length == 2 && parts[1] == "chunks" && method == "PUT")
{ UploadChunk(request, response, job); return; }
if (parts.Length == 2 && parts[1] == "start" && method == "POST")
{ StartUploaded(response, job); return; }
if (parts.Length == 2 && parts[1] == "file" && read)
{ DownloadChunk(request, response, job); return; }
if (parts.Length == 2 && parts[1] == "md5" && read)
{ Md5Manifest(response, job); return; }
Error(response, HttpStatusCode.MethodNotAllowed, "unsupported_operation");
}
catch (JsonException)
{ Error(response, HttpStatusCode.BadRequest, "invalid_json"); }
catch (IOException)
{ Error(response, HttpStatusCode.ServiceUnavailable, "archive_io_unavailable"); }
catch (UnauthorizedAccessException)
{ Error(response, HttpStatusCode.ServiceUnavailable, "archive_access_denied"); }
catch (ArgumentException)
{ Error(response, HttpStatusCode.BadRequest, "invalid_archive_request"); }
catch (InvalidOperationException)
{ Error(response, HttpStatusCode.Conflict, "archive_operation_conflict"); }
}
private void Start(IOSHttpRequest request, IOSHttpResponse response,
UserAccount user, string action)
{
// Small metadata envelope only. Raw archive data is sent via PUT.
if (request.ContentLength < 0 || request.ContentLength > 8192)
{ Error(response, HttpStatusCode.RequestEntityTooLarge, "metadata_too_large"); return; }
using JsonDocument doc = JsonDocument.Parse(request.InputStream,
new JsonDocumentOptions { MaxDepth = 8 });
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{ Error(response, HttpStatusCode.BadRequest, "invalid_metadata"); return; }
string region = ReadString(root, "region_id");
if (!Guid.TryParseExact(region, "D", out Guid regionGuid) ||
regionGuid == Guid.Empty)
{ Error(response, HttpStatusCode.BadRequest, "invalid_region_id"); return; }
string inventoryPath = ReadString(root, "inventory_path");
if (string.IsNullOrEmpty(inventoryPath) || inventoryPath.Length > 255 ||
inventoryPath.Contains("..") || inventoryPath.IndexOfAny(new[] { '\0', '\r', '\n' }) >= 0)
{ Error(response, HttpStatusCode.BadRequest, "invalid_inventory_path"); return; }
long size = action == "import" ? ReadInt64(root, "archive_size_bytes") : 0;
string sha = action == "import" ? ReadString(root, "sha256").ToLowerInvariant() : "";
if (action == "import" &&
(size <= 0 || size > m_MaxBytes || sha.Length != 64 ||
!sha.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f')))
{ Error(response, HttpStatusCode.BadRequest, "invalid_archive_size_or_sha256"); return; }
bool merge = root.TryGetProperty("merge", out JsonElement merging) &&
merging.ValueKind == JsonValueKind.True;
bool dry = root.TryGetProperty("dry_run", out JsonElement checking) &&
checking.ValueKind == JsonValueKind.True;
NexNodeSnapshot node = m_Nodes.FindNodeForRegion(regionGuid.ToString("D"));
if (node == null || !string.Equals(node.State, "online", StringComparison.OrdinalIgnoreCase))
{ Error(response, HttpStatusCode.ServiceUnavailable, "region_node_unavailable"); return; }
int feature = action == "import"
? OglArchiveFeatureGate.IarImport : OglArchiveFeatureGate.IarExport;
if (m_Features != null && !m_Features.Permitted(node.NodeId, feature))
{ Error(response, HttpStatusCode.Forbidden, "iar_feature_not_licensed"); return; }
ExpireStaleUploads(user);
// One live IAR job per resident; prevent unbounded disk reservation.
if (m_Jobs.List(1000).Any(j => j.Actor == Actor(user) &&
(j.State == OglJobState.Queued || j.State == OglJobState.Running)))
{ Error(response, HttpStatusCode.Conflict, "iar_operation_already_active"); return; }
Guid id = Guid.NewGuid();
string file = OglIarTransferPolicy.Resolve(m_SharedRoot, regionGuid, id);
// Do not allow overwriting any existing archive, including symlinks.
if (action == "import")
{
Directory.CreateDirectory(Path.GetDirectoryName(file));
using (new FileStream(file, FileMode.CreateNew,
FileAccess.Write, FileShare.None)) { }
}
Dictionary<string, string> metadata = new()
{
["user_id"] = user.PrincipalID.ToString(),
["region_id"] = regionGuid.ToString("D"),
["node_id"] = node.NodeId,
["action"] = action,
["file_name"] = id.ToString("D") + ".iar",
["inventory_path"] = inventoryPath,
["expected_bytes"] = size.ToString(CultureInfo.InvariantCulture),
["sha256"] = sha,
["merge"] = merge.ToString(),
["dry_run"] = dry.ToString(),
["self_service"] = "true"
};
OglJobSnapshot job;
try
{
job = m_Bridge.RegisterOperation(
"archive.iar." + action, id.ToString("D"), Actor(user),
id.ToString("D"), metadata);
}
catch
{
if (action == "import") File.Delete(file);
throw;
}
if (action == "export")
Publish(job);
Json(response, HttpStatusCode.Accepted,
new { operation_id = job.JobId, state = "queued",
upload_chunk_max_bytes = OglIarTransferPolicy.MaximumChunkBytes,
status_url = "/api/v1/iar/me/operations/" + job.JobId });
}
private void Publish(OglJobSnapshot job)
{
Dictionary<string, string> payload = new()
{
["operation_id"] = job.JobId,
["target_node_id"] = job.Metadata["node_id"],
["region_id"] = job.Metadata["region_id"],
["user_id"] = job.Metadata["user_id"],
["action"] = job.Metadata["action"],
["file_name"] = job.Metadata["file_name"],
["inventory_path"] = job.Metadata["inventory_path"],
["merge"] = job.Metadata["merge"],
["dry_run"] = job.Metadata["dry_run"],
["self_service"] = "true"
};
m_Bus.Publish(new NexEvent("archive.iar.requested",
"opengenesislink.world-api", payload, job.JobId));
}
private OglJobSnapshot OwnJob(UserAccount user, Guid id)
{
OglJobSnapshot job = m_Bridge.Get(id.ToString("D"));
if (job == null || job.Actor != Actor(user) ||
!job.Metadata.TryGetValue("user_id", out string userId) ||
userId != user.PrincipalID.ToString() ||
!job.Metadata.TryGetValue("self_service", out string self) ||
self != "true")
return null;
return job;
}
private static string Actor(UserAccount user) =>
"iar-self-service:" + user.PrincipalID;
private string FileFor(OglJobSnapshot job)
{
if (!Guid.TryParseExact(job.Metadata["region_id"], "D",
out Guid region) ||
!Guid.TryParseExact(job.JobId, "D", out Guid id))
throw new InvalidOperationException("Invalid stored IAR job.");
return OglIarTransferPolicy.Resolve(m_SharedRoot, region, id);
}
private void UploadChunk(IOSHttpRequest req, IOSHttpResponse res, OglJobSnapshot job)
{
if (job.Metadata["action"] != "import" ||
job.State is OglJobState.Completed or OglJobState.Failed or OglJobState.Cancelled ||
(job.State == OglJobState.Running && job.ProgressPhase != "uploading"))
{ Error(res, HttpStatusCode.Conflict, "upload_not_active"); return; }
if (!long.TryParse(req.QueryString?["offset"],
NumberStyles.None, CultureInfo.InvariantCulture, out long offset) ||
req.ContentLength <= 0 || req.ContentLength > OglIarTransferPolicy.MaximumChunkBytes)
{ Error(res, HttpStatusCode.BadRequest, "invalid_chunk_request"); return; }
long expected = long.Parse(job.Metadata["expected_bytes"], CultureInfo.InvariantCulture);
string path = FileFor(job);
lock (m_Locks.GetOrAdd(job.JobId, _ => new object()))
{
using FileStream stream = new(path, FileMode.Open, FileAccess.Write, FileShare.None);
long current = stream.Length;
if (!OglIarTransferPolicy.AcceptChunk(current, offset,
req.ContentLength, expected, m_MaxBytes))
{ Error(res, HttpStatusCode.Conflict, "offset_or_size_mismatch",
new { next_offset = current }); return; }
stream.Position = current;
byte[] buffer = new byte[65536];
long remaining = req.ContentLength;
while (remaining > 0)
{
int n = req.InputStream.Read(buffer, 0,
(int)Math.Min(remaining, buffer.Length));
if (n <= 0) throw new IOException("Upload stream interrupted.");
stream.Write(buffer, 0, n);
remaining -= n;
}
stream.Flush(true);
long next = stream.Length;
if (job.State == OglJobState.Queued)
m_Jobs.Start(job.JobId, "uploading");
int percent = (int)Math.Min(99L, next * 100 / expected);
m_Jobs.Report(job.JobId, percent, "uploading", "archive upload");
Json(res, HttpStatusCode.OK,
new { next_offset = next, expected_bytes = expected,
upload_percent = percent });
}
}
private void StartUploaded(IOSHttpResponse response, OglJobSnapshot job)
{
if (job.Metadata["action"] != "import" ||
job.State is OglJobState.Completed or OglJobState.Failed or OglJobState.Cancelled ||
(job.State == OglJobState.Running && job.ProgressPhase != "uploading"))
{ Error(response, HttpStatusCode.Conflict, "upload_not_active"); return; }
lock (m_Locks.GetOrAdd(job.JobId, _ => new object()))
{
string path = FileFor(job);
long expected = long.Parse(job.Metadata["expected_bytes"],
CultureInfo.InvariantCulture);
if (!File.Exists(path) || new FileInfo(path).Length != expected)
{ Error(response, HttpStatusCode.Conflict, "upload_incomplete"); return; }
string actual = Digest(path, SHA256.Create);
if (!string.Equals(actual, job.Metadata["sha256"], StringComparison.Ordinal))
{
// Never leave a full corrupted archive consuming the
// resident's active-job quota or shared storage.
m_Jobs.Fail(job.JobId, "sha256_mismatch");
File.Delete(path);
Error(response, HttpStatusCode.Conflict, "sha256_mismatch");
return;
}
// Uploaded file already lives where the simulator's IAR
// inspector reads it. Never transfer binary bytes via NexBus.
if (job.State == OglJobState.Queued)
m_Jobs.Start(job.JobId, "uploaded");
else
m_Jobs.Report(job.JobId, 5, "uploaded", "archive received");
Publish(job);
Json(response, HttpStatusCode.Accepted,
new { operation_id = job.JobId, state = "running",
status_url = "/api/v1/iar/me/operations/" + job.JobId });
}
}
private void Status(IOSHttpResponse response, OglJobSnapshot job)
{
bool uploading = job.Metadata["action"] == "import" &&
(job.State == OglJobState.Queued || job.ProgressPhase == "uploading");
long transferred = 0;
long total = 0;
if (uploading)
{
total = long.Parse(job.Metadata["expected_bytes"], CultureInfo.InvariantCulture);
string path = FileFor(job);
transferred = File.Exists(path) ? new FileInfo(path).Length : 0;
}
long? eta = uploading
? OglIarTransferPolicy.EtaSeconds(transferred, total,
job.CreatedAt, DateTimeOffset.UtcNow)
: OglIarTransferPolicy.EtaFromJob(job.ProgressPercent,
job.StartedAt, DateTimeOffset.UtcNow);
string phase = uploading ? "uploading" : job.ProgressPhase;
bool completeExport = job.Metadata["action"] == "export" &&
job.State == OglJobState.Completed;
string file = completeExport ? FileFor(job) : null;
bool ready = completeExport && File.Exists(file) &&
new FileInfo(file).Length > 0 &&
new FileInfo(file).Length <= m_MaxBytes;
Json(response, HttpStatusCode.OK, new
{
operation_id = job.JobId, state = job.State.ToString().ToLowerInvariant(),
action = job.Metadata["action"], phase,
progress_percent = uploading && total > 0
? (int)Math.Min(99L, transferred * 100 / total)
: job.ProgressPercent,
eta_seconds = eta,
uploaded_bytes = uploading ? transferred : (long?)null,
expected_bytes = uploading ? total : (long?)null,
next_offset = uploading ? transferred : (long?)null,
updated_at_utc = job.UpdatedAt,
message = job.Message,
download_ready = ready,
file_size_bytes = ready ? new FileInfo(file).Length : (long?)null,
download_url = ready ?
"/api/v1/iar/me/operations/" + job.JobId + "/file" : null,
md5_url = ready ?
"/api/v1/iar/me/operations/" + job.JobId + "/md5" : null
});
}
private void DownloadChunk(IOSHttpRequest request, IOSHttpResponse res,
OglJobSnapshot job)
{
if (!TryReadyExport(job, out string file))
{ Error(res, HttpStatusCode.Conflict, "export_not_ready"); return; }
long length = new FileInfo(file).Length;
if (!long.TryParse(request.QueryString?["offset"], NumberStyles.None,
CultureInfo.InvariantCulture, out long offset) ||
!int.TryParse(request.QueryString?["length"], NumberStyles.None,
CultureInfo.InvariantCulture, out int chunk) ||
offset < 0 || offset >= length || chunk <= 0 ||
chunk > OglIarTransferPolicy.MaximumChunkBytes)
{ Error(res, HttpStatusCode.BadRequest, "use_bounded_offset_and_length"); return; }
int take = (int)Math.Min((long)chunk, length - offset);
byte[] data = new byte[take];
using (FileStream stream = File.OpenRead(file))
{
stream.Position = offset;
stream.ReadExactly(data);
}
res.StatusCode = (int)HttpStatusCode.PartialContent;
res.ContentType = "application/octet-stream";
res.AddHeader("Content-Disposition", "attachment; filename=\"" + job.JobId + ".iar\"");
res.AddHeader("Content-Range", "bytes " +
offset.ToString(CultureInfo.InvariantCulture) + "-" +
(offset + take - 1).ToString(CultureInfo.InvariantCulture) + "/" +
length.ToString(CultureInfo.InvariantCulture));
res.AddHeader("Accept-Ranges", "bytes");
res.RawBuffer = data;
}
private void Md5Manifest(IOSHttpResponse res, OglJobSnapshot job)
{
if (!TryReadyExport(job, out string file))
{ Error(res, HttpStatusCode.Conflict, "export_not_ready"); return; }
// MD5 for requested legacy tooling only; SHA-256 is the
// security-oriented checksum also published in the manifest.
string md5 = Digest(file, MD5.Create);
string sha = Digest(file, SHA256.Create);
res.StatusCode = (int)HttpStatusCode.OK;
res.ContentType = "text/plain; charset=utf-8";
res.AddHeader("Content-Disposition",
"attachment; filename=\"" + job.JobId + ".iar.md5\"");
res.RawBuffer = Encoding.UTF8.GetBytes(md5 + " " +
job.JobId + ".iar\nSHA256 " + sha + "\n");
}
private void DeleteArchive(IOSHttpResponse response, OglJobSnapshot job)
{
lock (m_Locks.GetOrAdd(job.JobId, _ => new object()))
{
// A running importer/exporter may still have the file open.
// Only staged uploads and terminal jobs can be cleaned up.
bool staged = job.Metadata["action"] == "import" &&
(job.State == OglJobState.Queued ||
(job.State == OglJobState.Running &&
job.ProgressPhase == "uploading"));
bool terminal = job.State is OglJobState.Completed or
OglJobState.Failed or OglJobState.Cancelled;
if (!staged && !terminal)
{
Error(response, HttpStatusCode.Conflict,
"active_archive_cannot_be_deleted");
return;
}
if (staged) m_Jobs.Cancel(job.JobId, "Resident cancelled upload.");
string path = FileFor(job);
if (File.Exists(path)) File.Delete(path);
Json(response, HttpStatusCode.OK,
new { operation_id = job.JobId, archive_deleted = true });
}
}
private void ExpireStaleUploads(UserAccount user)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
foreach (OglJobSnapshot j in m_Jobs.List(1000))
{
if (j.Actor != Actor(user) ||
j.Metadata == null ||
!j.Metadata.TryGetValue("action", out string action) ||
action != "import" ||
!(j.State == OglJobState.Queued ||
(j.State == OglJobState.Running &&
j.ProgressPhase == "uploading")) ||
now - j.UpdatedAt <= TimeSpan.FromHours(24))
continue;
lock (m_Locks.GetOrAdd(j.JobId, _ => new object()))
{
OglJobSnapshot current = m_Jobs.Get(j.JobId);
if (current == null || !(current.State == OglJobState.Queued ||
(current.State == OglJobState.Running &&
current.ProgressPhase == "uploading")) ||
now - current.UpdatedAt <= TimeSpan.FromHours(24))
continue;
m_Jobs.Fail(j.JobId, "Expired incomplete IAR upload.");
string path = FileFor(j);
if (File.Exists(path)) File.Delete(path);
}
}
}
private bool TryReadyExport(OglJobSnapshot job, out string path)
{
path = null;
if (job.Metadata["action"] != "export" ||
job.State != OglJobState.Completed) return false;
path = FileFor(job);
return File.Exists(path) && new FileInfo(path).Length > 0 &&
new FileInfo(path).Length <= m_MaxBytes;
}
private static string Digest(string path, Func<HashAlgorithm> factory)
{
using HashAlgorithm digest = factory();
using FileStream input = File.OpenRead(path);
return Convert.ToHexString(digest.ComputeHash(input)).ToLowerInvariant();
}
private static string ReadString(JsonElement root, string key) =>
root.TryGetProperty(key, out JsonElement entry) &&
entry.ValueKind == JsonValueKind.String
? entry.GetString()?.Trim() ?? "" : "";
private static long ReadInt64(JsonElement root, string key) =>
root.TryGetProperty(key, out JsonElement entry) &&
entry.ValueKind == JsonValueKind.Number &&
entry.TryGetInt64(out long number) ? number : -1L;
private static void Json(IOSHttpResponse r, HttpStatusCode status, object data)
{
r.StatusCode = (int)status;
r.ContentType = "application/json; charset=utf-8";
r.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(data);
}
private static void Error(IOSHttpResponse r, HttpStatusCode status,
string code, object details = null) =>
Json(r, status, new { error = code, details });
}
}
+12
View File
@@ -1068,3 +1068,15 @@
WeatherSeed = 20261028
TimeZone = "Europe/Berlin"
DisplayName = "Stadt-NexVerse"
; ============================================================================
; Resident IAR self-service (World API / ROBUST only).
; Keep disabled until an identical shared storage mount is configured on ROBUST
; and every target simulator's [OpenGenesisLINKIAR].StorageRoot.
; Binary upload/download is chunked (4 MiB), not sent through NexBus.
; ============================================================================
[OglIarSelfService]
Enabled = false
SharedStorageRoot = ""
MaximumArchiveMiB = 2048
+12
View File
@@ -1125,3 +1125,15 @@
WeatherSeed = 20261028
TimeZone = "Europe/Berlin"
DisplayName = "Stadt-NexVerse"
; ============================================================================
; Resident IAR self-service (World API / ROBUST only).
; Keep disabled until an identical shared storage mount is configured on ROBUST
; and every target simulator's [OpenGenesisLINKIAR].StorageRoot.
; Binary upload/download is chunked (4 MiB), not sent through NexBus.
; ============================================================================
[OglIarSelfService]
Enabled = false
SharedStorageRoot = ""
MaximumArchiveMiB = 2048
+12
View File
@@ -830,3 +830,15 @@
WeatherSeed = 20261028
TimeZone = "Europe/Berlin"
DisplayName = "Stadt-NexVerse"
; ============================================================================
; Resident IAR self-service (World API / ROBUST only).
; Keep disabled until an identical shared storage mount is configured on ROBUST
; and every target simulator's [OpenGenesisLINKIAR].StorageRoot.
; Binary upload/download is chunked (4 MiB), not sent through NexBus.
; ============================================================================
[OglIarSelfService]
Enabled = false
SharedStorageRoot = ""
MaximumArchiveMiB = 2048
+248
View File
@@ -0,0 +1,248 @@
# OGL IAR Self-Service – sichere Bürger-Archive (Generation 1)
OpenGenesisLINK erweitert die bestehende **administrative** World API
`/api/v1/iar/*` um einen getrennten, rein **benutzergebundenen** Zugang
für angemeldete lokale Avatar-Konten. Keine Weitergabe von Passwort,
fremdem Benutzerkennzeichen oder rohem Archivinhalt über NexBus.
**Wichtig:** Dies ist eine opt-in **Shared-Storage-Implementierung**.
Im Standardzustand ist sie deaktiviert. Für getrennte Server MUSS
ein gemeinsames verlässliches POSIX-Verzeichnis (z. B. NFS) auf ROBUST
und auf jedem teilnehmenden Regionssimulator gemountet sein.
Es wird **kein** netzwerkübergreifender IAR-Byte-Transport über NexBus
implementiert. Unterschiedliche lokale Verzeichnisse sind nicht ausreichend.
## Berechtigungen / Voraussetzungen
- Aufrufe nur mit OAuth-/Bearer-Token eines **angemeldeten lokalen
Avatars**. Ein Serviceprincipal oder API-Key ist unzureichend.
- GET (eigene Jobs, Fortschritt, Download und MD5) und Export-Start:
`inventory:read`. Import-Start, Upload und Import-Freigabe:
`inventory:write` – benötigt eine explizite OAuth-Einwilligung/Grant,
nicht bloß eine normale öffentliche Besucherberechtigung.
- Die Benutzer-ID stammt **ausschließlich aus dem geprüften Token**;
ein `user_id` aus Request-Daten wird nicht übernommen.
- Ein gestarteter Job kann nur mit demselben lokalen Avatar abgefragt
oder heruntergeladen werden. Job-UUIDs allein autorisieren nichts.
- Der vorhandene signierte IAR-Feature-Gate bleibt aktiv und kann
Importe und Exporte je nach Node-Lizenz verweigern.
- Bürgerexporte wenden im originalen Archiver `checkPermissions=CT`
an. Nur Gegenstände mit **Copy- UND Transfer-Rechten** können
exportiert werden. Das ersetzt keine umfassende Prüfung aller
Asset-Eigentumsrechte und Copybot-Risiken.
## Aktivierung
1. Ein gemeinsames Verzeichnis, etwa `/srv/ogl-iar`, auf ROBUST und
allen beteiligten Simulatorservern mounten. Benutzerkonten, Rechte,
ausreichenden freien Speicher und Netzwerktrennung prüfen.
2. Auf den **Regionssimulatoren** in der tatsächlich geladenen
`OpenSim.ini` setzen:
```ini
[OpenGenesisLINKIAR]
Enabled = true
StorageRoot = "/srv/ogl-iar"
MaximumArchiveMiB = 2048
```
3. Auf **ROBUST/World API** in der tatsächlich geladenen
`Robust.HG.ini` (oder `Robust.ini`) setzen:
```ini
[OglIarSelfService]
Enabled = true
SharedStorageRoot = "/srv/ogl-iar"
MaximumArchiveMiB = 2048
```
4. ROBUST und Simulatoren mit aktualisierten DLLs neu starten.
Der bestehende `NexVerseWorldApi`-Dienst, registrierte
`NexVerseNodeAgent`-Verbindungen und `IInventoryArchiverModule`
müssen verfügbar sein. Nur lokale Avatare, kein HG-Fremdkonto.
**Vorsicht:** Wenn bislang `OpenGenesisLINKIAR` ohne eigene
`StorageRoot`-Konfiguration lief, ändert diese neue Einstellung
den Pfad des administrativen IAR-Archivs. Vor dem Umstellen bestehende
Archive sicher migrieren oder mounten. Das Update setzt den Simulatorpfad
nicht automatisch um.
Für eine produktive verteilte Installation sind außerdem TLS, ein
restriktiver Reverse-Proxy, kein öffentlicher Zugriff auf das
StorageRoot, Speicherquoten/Datei-Retention und Monitoring erforderlich.
`SharedStorageRoot` muss ein absoluter Pfad auf **demselben**
gemeinsamen Dateisystem sein. Nur gleiche Verzeichnisnamen auf
verschiedenen lokalen Festplatten reichen nicht.
## World-API-Endpunkte
Alle folgenden Endpunkte sind beim aktivierten Modul unter
`https://world.stadt-nexverse.de` verfügbar, sofern der Reverse-Proxy
`/api/v1/iar/me` zur bestehenden ROBUST World API durchleitet.
| Methode | Pfad | Funktion |
|---|---|---|
| POST | `/api/v1/iar/me/export` | Eigenen Export beginnen |
| POST | `/api/v1/iar/me/import` | Upload-Job reservieren |
| PUT | `/api/v1/iar/me/operations/{id}/chunks?offset=N` | Nächsten IAR-Block hochladen |
| POST | `/api/v1/iar/me/operations/{id}/start` | SHA-256 prüfen und Import anstoßen |
| GET | `/api/v1/iar/me/operations/{id}` | Eigener Live-Fortschritt, ETA, Status |
| GET | `/api/v1/iar/me/operations/{id}/file?offset=N&length=M` | Export in Blöcken herunterladen (HTTP 206) |
| GET | `/api/v1/iar/me/operations/{id}/md5` | MD5 + SHA-256 Prüfsummenmanifest |
| DELETE | `/api/v1/iar/me/operations/{id}` | Eigenes Archiv löschen oder laufenden Upload abbrechen |
### Export
```http
POST /api/v1/iar/me/export
Authorization: Bearer <aktueller-eigener-oauth-token>
Content-Type: application/json
{"region_id":"REGION_UUID","inventory_path":"/*"}
```
HTTP 202: `operation_id`, `status_url`.
Der Job läuft asynchron über den vorhandenen IAR-Archiver und NexBus.
Alle Ordner-/Asset-Schritte werden über die vorhandene
`IInventoryArchiverProgress`-Schnittstelle geliefert.
Der Export wird mit servergeneriertem, nicht überschreibbarem
Dateinamen `{id}.iar` im Region-Verzeichnis abgelegt.
### Import (auch >100 MiB)
Zuerst lokale Dateigröße und **SHA-256** ermitteln. Die Gesamtgröße
darf standardmäßig bis zu 2 GiB betragen (konfigurierbar bis 10 GiB,
sofern die bestehende Regions-Policy dieselbe Größe zulässt).
```http
POST /api/v1/iar/me/import
Authorization: Bearer <aktueller-eigener-oauth-token>
Content-Type: application/json
{
"region_id":"REGION_UUID",
"inventory_path":"/",
"archive_size_bytes":187654321,
"sha256":"...64 hex digits...",
"merge":true,
"dry_run":false
}
```
Dann PUT mit `Content-Type: application/octet-stream`, **maximal
4 MiB pro Request**. Beim ersten Block `offset=0`, dann das
zurückgelieferte `next_offset` für jeden folgenden Block übernehmen.
Ein fehlgeschlagener Block darf nicht blind erneut bei Offset 0
geschrieben werden: zuerst den aktuellen Offset abfragen.
Eine vollständige Datei mit falscher SHA-256-Prüfsumme wird abgelehnt und vom Shared Storage entfernt. Fehlgeschlagene Uploads lassen sich durch den Besitzer mit DELETE entfernen. Abgebrochene Uploads mit mehr als 24 Stunden Inaktivität werden beim nächsten eigenen Jobstart bereinigt.
Das Archiv wird beim Empfang nicht in den RAM geladen. Beim
Aufruf von `/start` prüft der Server die vollständige Größe und
SHA-256, erst danach startet der Original-IAR-Archiver mit
vorheriger TAR/GZIP-Sicherheitsinspektion.
Während des Uploads liefert `GET /api/v1/iar/me/operations/{id}` z. B.:
```json
{
"operation_id":"...",
"state":"running",
"action":"import",
"phase":"uploading",
"progress_percent":45,
"eta_seconds":75,
"uploaded_bytes":84344832,
"expected_bytes":187654321,
"next_offset":84344832,
"download_ready":false
}
```
`eta_seconds` ist eine **Schätzung aus tatsächlichem Fortschritt**.
Vor ausreichenden Messwerten und bei abgeschlossenen Jobs ist der
Wert `null` – es wird keine künstliche verbleibende Zeit erfunden.
Nach dem Upload beginnt der Fortschritt des eigentlichen IAR-Imports
als separate Phase; diese Prozentwerte sind nicht additiv.
### Exportdatei und Prüfsumme
Sobald `download_ready=true` ist, die Datei in höchstens
4-MiB-Blöcken mit `offset` und `length` herunterladen.
Die Antwort lautet HTTP 206 mit `Content-Range`,
`application/octet-stream` und `Content-Disposition`.
Jeder Download erfordert weiterhin den berechtigten Bearer-Token.
Der `md5`-Endpunkt liefert ein kleines Textmanifest mit
`MD5 Dateiname` plus `SHA256 <hash>`.
**MD5 ist nicht kollisionssicher:** SHA-256 für verlässliche
Integritätsprüfungen bevorzugen. Auf Serverseite werden beide
Prüfsummen aus der fertigen Archivdatei in einem Stream ermittelt.
## Interaktives Stadtportal-Widget
Mitgeliefert: [Beispiel-Widget](examples/ogl-iar-self-service-widget.js).
Das Modul zeigt Import/Export-Aktionen, den aktuellen Jobstatus, einen
Fortschrittsbalken und die geschätzte Restzeit. Es pollt alle
**2 Sekunden** den eigenen geschützten Job-Endpunkt.
Das Stadtportal liefert den gültigen OAuth-Token über eine eigene
Callbackfunktion; **keine Zugangsdaten im Widget fest einkodieren**:
```javascript
import { mountOglIarSelfService } from "./ogl-iar-self-service-widget.js";
const widget = mountOglIarSelfService(
document.getElementById("iar-dashboard"),
{
baseUrl: "", // gleicher Origin oder geschützter Backend-Proxy
regionId: "REGION-UUID-HIER",
getAccessToken: async () => portalOAuth.getAccessToken()
}
);
```
Das Beispiel importiert IARs in 4-MiB-Blöcken und bietet nach
erfolgreichem Export einen Dateidownload sowie ein eigenes
MD5/SHA-256-Manifest. Für große Dateien benötigt der Browser eine
File-System-Access-API (`showSaveFilePicker`); bei fehlender Unterstützung
verweigert das Widget einen RAM-intensiven Komplettdownload. Der
Benutzer muss bei Uploads vorerst den zuvor lokal berechneten
SHA-256-Hash angeben. Ein fertiger eigenständiger
Portal-Login ist **nicht** enthalten: Das Widget benutzt die
authentifizierte OAuth-Sitzung des einbettenden Stadtportals.
## Web-Integration und Einschränkungen
Ein interaktives 2-Sekunden-Statuspolling kann die eigenen Jobdaten
aus dem bestehenden Stadtportal mit dem OAuth-Bearer-Token abrufen.
Es gibt keinen fremdlesbaren öffentlichen Status und keinen
unautorisierten Downloadlink.
**Grenzen dieser Entwicklungsstufe:**
- Keine fertige direkte Inworld-Firestorm-Dateiauswahl; IARs werden
über das authentifizierte **Webportal** oder einen HTTP-Client
hoch- und heruntergeladen.
- Kein echtes Cross-Host-Byte-Routing ohne Shared-Mount.
- **Kein automatischer Resume nach ROBUST-Neustart**, wenn ein
Upload bereits als laufend markiert war. Die vorhandene persistente
Job-Engine kennzeichnet unterbrochene Jobs als fehlgeschlagen;
erneuter Jobstart erforderlich.
- Kein Live-Push/SSE – der Client pollt die fortlaufend
gespeicherten Fortschrittswerte des Original-Archivmoduls.
- Ein Import kann nicht gefahrlos mitten im Inventar-Restore
unterbrochen werden. Deshalb gibt es keinen Abbruchknopf
für aktive Importe.
- Nach erfolgreichem Import ist eine Inventaraktualisierung oder
erneute Anmeldung im Viewer erforderlich, abhängig von dessen
Cache.
- Die im Archiv vorhandenen Rechte bleiben Gegenstand des
ursprünglichen OpenSim-/Asset-/Inventory-Importpfades.
- Vollständige automatische Dateiretention für erfolgreiche Archive,
ein generischer Browser-Download ohne
Clientcode und vollständig gridgebundene Quotenverwaltung sind
Folgeschritte. Ein Export wird in dieser Version nur blockweise
heruntergeladen, um den Arbeitsspeicher des Webservers zu schützen.
Die bestehende administrative `/api/v1/iar`-Schnittstelle und
Regionenverwaltung bleiben separat, unverändert authentifiziert und
benötigen weiterhin `regions:manage`.
@@ -0,0 +1,231 @@
// SPDX-License-Identifier: MPL-2.0
// Browser widget for Stadt-NexVerse. Embed in an authenticated portal page.
// The host MUST supply getAccessToken() backed by the portal's OAuth flow.
// Never write a bearer token to localStorage, a URL or an HTML attribute.
export function mountOglIarSelfService(root, {
getAccessToken, baseUrl = "", regionId
}) {
if (!root || typeof getAccessToken !== "function")
throw new Error("A container and the portal's OAuth token provider are required.");
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(regionId))
throw new Error("A valid region UUID is required.");
root.replaceChildren();
const node = (tag, text, parent = root) => {
const n = document.createElement(tag);
if (text !== undefined) n.textContent = text;
parent.append(n);
return n;
};
node("h2", "Stadt-NexVerse · IAR Import / Export");
node("p", "Nur dein angemeldeter Avatar. Große IAR-Archive werden blockweise übertragen.");
const pathLabel = node("label", "Inventarpfad");
const invPath = node("input", undefined, pathLabel);
invPath.value = "/*";
const actions = node("div");
const exportButton = node("button", "Eigenes Inventar exportieren", actions);
const importButton = node("button", "IAR importieren", actions);
const fileInput = node("input", undefined, actions);
fileInput.type = "file";
fileInput.accept = ".iar";
importButton.disabled = true;
fileInput.addEventListener("change", () => {
importButton.disabled = !fileInput.files?.[0];
});
const progress = node("progress");
progress.max = 100;
progress.value = 0;
progress.style.width = "100%";
const state = node("p", "Keine laufende Operation");
state.setAttribute("role", "status");
const detail = node("p", "");
const downloads = node("div");
let timer = null;
let operationId = null;
let busy = false;
let stopped = false;
const CHUNK = 4 * 1024 * 1024;
async function api(path, init = {}) {
const token = await getAccessToken();
if (!token) throw new Error("Bitte erneut im Stadtportal anmelden.");
const headers = new Headers(init.headers || {});
headers.set("Authorization", "Bearer " + token);
const res = await fetch(baseUrl + path, {
...init, headers, credentials: "omit", cache: "no-store"
});
if (!res.ok) {
let reason = "HTTP " + res.status;
try { reason += ": " + (await res.json()).error; } catch {}
throw new Error(reason);
}
return res;
}
const base = "/api/v1/iar/me";
const op = id => base + "/operations/" + encodeURIComponent(id);
function stopPolling() { if (timer) clearInterval(timer); timer = null; }
function setBusy(value) {
busy = value; exportButton.disabled = value;
importButton.disabled = value || !fileInput.files?.[0];
}
function fail(err) {
stopPolling(); setBusy(false);
state.textContent = "Fehler: " + (err?.message || String(err));
}
const formatSeconds = value => value == null ? "Noch nicht berechenbar"
: value >= 60 ? Math.ceil(value / 60) + " Min."
: value + " Sek.";
function localDownloadText(data, name) {
const blob = new Blob([data], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = name; root.append(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(url), 3000);
}
async function exportFile(id, total) {
if (!window.showSaveFilePicker) {
state.textContent =
"Für den großen IAR-Download bitte einen Browser mit Dateispeicher-API nutzen.";
return;
}
const handle = await window.showSaveFilePicker({
suggestedName: id + ".iar",
types: [{description: "OpenSim Inventory Archive",
accept: {"application/octet-stream": [".iar"]}}]
});
const writable = await handle.createWritable();
try {
let offset = 0;
while (offset < total) {
const take = Math.min(CHUNK, total - offset);
const res = await api(op(id) + "/file?offset=" +
offset + "&length=" + take);
if (res.status !== 206) throw new Error("HTTP 206 erwartet");
const bytes = await res.arrayBuffer();
if (!bytes.byteLength || bytes.byteLength > take)
throw new Error("Ungueltiger IAR-Block");
await writable.write(bytes);
offset += bytes.byteLength;
progress.value = Math.floor(offset * 100 / total);
detail.textContent = "Download " + offset + " / " + total + " Bytes";
}
await writable.close();
} catch (error) { await writable.abort(); throw error; }
const manifest = await api(op(id) + "/md5");
localDownloadText(await manifest.text(), id + ".iar.md5");
state.textContent = "Download abgeschlossen – MD5 und SHA-256 gespeichert";
}
async function renderStatus(id) {
const job = await (await api(op(id))).json();
if (stopped || id !== operationId) return;
progress.value = job.progress_percent || 0;
const eta = formatSeconds(job.eta_seconds);
state.textContent = (job.action === "import" ? "Import" : "Export") +
" · " + job.state + " · " + job.phase + " · " +
progress.value + "%";
detail.textContent = "Geschaetzte Restzeit: " + eta +
(job.next_offset == null ? "" :
" · Upload " + job.next_offset + " / " + job.expected_bytes + " Bytes");
if (["completed", "failed", "cancelled"].includes(job.state)) {
stopPolling(); setBusy(false);
if (job.state === "failed") detail.textContent +=
" · Fehler: " + (job.message || "Unbekannter Fehler");
if (job.download_ready && !downloads.childElementCount) {
const b = node("button", "IAR und MD5 herunterladen", downloads);
b.addEventListener("click", async () => {
b.disabled = true;
try { await exportFile(id, job.file_size_bytes); }
catch (e) { fail(e); }
finally { b.disabled = false; }
});
}
}
}
function watch(id) {
operationId = id;
downloads.replaceChildren();
stopPolling();
timer = setInterval(() => {
renderStatus(id).catch(fail);
}, 2000);
renderStatus(id).catch(fail);
}
exportButton.addEventListener("click", async () => {
setBusy(true);
try {
const res = await api(base + "/export", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ region_id: regionId,
inventory_path: invPath.value || "/*" })
});
watch((await res.json()).operation_id);
} catch (err) { fail(err); }
});
importButton.addEventListener("click", async () => {
const file = fileInput.files?.[0];
if (!file) return;
setBusy(true);
stopPolling();
try {
if (file.size <= 0) throw new Error("Leere IAR-Datei");
// SHA-256 verification is required before the server imports.
// Browser crypto.subtle.digest is not a streaming API. For >100MiB,
// require a checksum calculated out of process instead of allocating
// the entire archive into the JavaScript heap.
const checksum = window.prompt(
"Bitte die SHA-256-Pruefsumme der IAR-Datei eingeben (64 Hexzeichen):");
if (!/^[0-9a-f]{64}$/i.test(checksum || ""))
throw new Error("Gueltige SHA-256-Pruefsumme erforderlich");
const res = await api(base + "/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
region_id: regionId,
inventory_path: invPath.value || "/",
archive_size_bytes: file.size,
sha256: checksum.toLowerCase(),
merge: true,
dry_run: false
})
});
const job = await res.json();
const id = job.operation_id;
operationId = id;
downloads.replaceChildren();
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + CHUNK);
try {
const result = await api(op(id) + "/chunks?offset=" + offset, {
method: "PUT",
headers: { "Content-Type": "application/octet-stream" },
body: chunk
});
offset = (await result.json()).next_offset;
} catch (err) {
// Resolve the actual persisted offset before retrying.
const status = await (await api(op(id))).json();
if (!Number.isSafeInteger(status.next_offset)) throw err;
offset = status.next_offset;
}
progress.value = Math.floor(offset * 100 / file.size);
state.textContent = "IAR Upload: " + progress.value + "%";
detail.textContent = offset + " / " + file.size + " Bytes";
}
await api(op(id) + "/start", {method: "POST"});
watch(id);
} catch (err) { fail(err); }
});
return {
destroy() {
stopped = true;
stopPolling();
root.replaceChildren();
}
};
}
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="../../../NexVerse/Core/Archives/OglIarTransferPolicy.cs" Link="OglIarTransferPolicy.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,52 @@
using System;
using NexVerse.Core.Archives;
internal static class Program
{
private static int count;
private static void Check(bool ok, string name)
{
count++;
if (!ok) throw new Exception("IAR self-service test failed: " + name);
}
public static void Main()
{
Guid region = Guid.Parse("11111111-1111-1111-1111-111111111111");
Guid job = Guid.Parse("22222222-2222-2222-2222-222222222222");
string path = OglIarTransferPolicy.Resolve("/srv/ogl-iar", region, job);
Check(path.EndsWith("11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222.iar"),
"server-chosen opaque storage path");
try { OglIarTransferPolicy.Resolve("/", region, job);
throw new Exception("Root accepted"); }
catch (ArgumentException) { count++; }
long max = OglIarTransferPolicy.DefaultMaximumArchiveBytes;
Check(max > 100L * 1024 * 1024, "uploads support >100 MiB");
Check(OglIarTransferPolicy.AcceptChunk(0, 0, 4194304, 200000000, max),
"first 4MiB chunk");
Check(OglIarTransferPolicy.AcceptChunk(4194304, 4194304, 4194304,
200000000, max), "second sequential chunk");
Check(!OglIarTransferPolicy.AcceptChunk(4194304, 0, 4194304,
200000000, max), "concurrent stale offset rejected");
Check(!OglIarTransferPolicy.AcceptChunk(0, 0, 4194305,
200000000, max), "oversized chunks rejected");
Check(!OglIarTransferPolicy.AcceptChunk(0, 0, 0,
200000000, max), "empty chunk rejected");
Check(!OglIarTransferPolicy.AcceptChunk(0, 0, 1,
max + 1, max), "archive quota enforced");
Check(!OglIarTransferPolicy.AcceptChunk(199999999, 199999999, 2,
200000000, max), "cannot exceed claimed archive size");
DateTimeOffset now = new(2026, 10, 29, 18, 0, 0, TimeSpan.Zero);
Check(OglIarTransferPolicy.EtaSeconds(100, 200,
now.AddSeconds(-60), now) == 60, "actual upload ETA");
Check(OglIarTransferPolicy.EtaSeconds(0, 200,
now.AddMinutes(-20), now) == null, "no progress no fake ETA");
Check(OglIarTransferPolicy.EtaSeconds(200, 200,
now.AddMinutes(-20), now) == null, "finished upload no ETA");
Check(OglIarTransferPolicy.EtaFromJob(50,
now.AddMinutes(-2), now) == 120, "job ETA from observed progress");
Check(OglIarTransferPolicy.EtaFromJob(0, null, now) == null,
"no job progress no ETA");
Console.WriteLine("OGL IAR self-service: " + count + " policy checks PASS");
}
}
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Self-service IAR: resident ownership, bounded transfer, safe defaults."""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def text(path): return (ROOT / path).read_text(encoding="utf-8-sig")
api = text("NexVerse/Server/Api/OglIarSelfServiceApi.cs")
core = text("NexVerse/Core/Archives/OglIarTransferPolicy.cs")
connector = text("NexVerse/Server/Api/NexVerseWorldApiConnector.cs")
node = text("NexVerse/RegionModules/NodeAgent/NexVerseNodeAgentModule.cs")
cfgs = [text(p) for p in (
"bin/Robust.HG.ini", "bin/Robust.HG.ini.example",
"bin/Robust.ini.example")]
for marker in (
'"/api/v1/iar/me"', "apiGate.Wrap(iarSelfService.Handle)",
"new OglIarSelfServiceApi(", "jobStore, eventBus, featureControl"
):
assert marker in connector, marker
assert connector.index('"/api/v1/iar/me"') < connector.index('"/api/v1/iar"')
for cfg in cfgs:
assert cfg.count("[OglIarSelfService]") == 1
assert "Enabled = false" in cfg.split("[OglIarSelfService]")[-1]
assert 'SharedStorageRoot = ""' in cfg.split("[OglIarSelfService]")[-1]
for marker in (
'"Enabled", false', '"SharedStorageRoot", ""',
"m_SharedRoot = m_Enabled ?", "maximumTotal",
"NexScopes.InventoryRead", "NexScopes.InventoryWrite",
"resident_token_required", "principal.Subject",
"user.PrincipalID", "OwnJob(user, id)", "self_service",
'Actor(user)', '"region_id"', '"sha256"', '"expected_bytes"',
"OglIarTransferPolicy.AcceptChunk(", "FileMode.CreateNew",
"FileShare.None", "m_Locks.GetOrAdd", "stream.Flush(true)",
'"uploading"', "EtaSeconds(", "EtaFromJob(",
"sha256_mismatch", 'Digest(path, SHA256.Create)',
"m_Bus.Publish(new NexEvent", '"archive.iar.requested"',
"FileFor(job)", "new FileInfo(path).Length",
"res.RawBuffer = data;", '"Content-Range"', "HttpStatusCode.PartialContent",
"OglIarTransferPolicy.MaximumChunkBytes",
"MD5.Create", "SHA256.Create", "download_ready",
"archive_operation_conflict", "NexScopes.InventoryRead",
"ExpireStaleUploads(user)", "private void DeleteArchive(",
"m_Jobs.Fail(job.JobId, \"sha256_mismatch\")", "m_Jobs.Cancel(job.JobId",
"TimeSpan.FromHours(24)"
):
assert marker in api or marker in core, marker
assert "TryReadyExport(job" in api
assert '"user_id"] = user.PrincipalID.ToString()' in api, "Never trust client user IDs"
assert '"user_id"] = job.Metadata["user_id"]' in api
assert "ArchiveInventory(" not in api and "DearchiveInventory(" not in api
assert "Path.GetFileName(" not in api, "Never let upload choose a filesystem name"
assert "new byte[take]" in api and "new byte[65536]" in api
assert "File.ReadAllBytes(" not in api
assert "request.InputStream.Read(" not in api or "remaining" in api
assert "m_Jobs.List(1000).Any(" in api
assert "inventory_path" in api
assert '["self_service"] = "true"' in api
assert '["checkPermissions"] = "CT"' in node, "Self-service export requires copy+transfer"
for marker in (
"MaximumChunkBytes = 4 * 1024 * 1024",
"DefaultMaximumArchiveBytes = 2L * 1024 * 1024 * 1024",
"Path.GetFullPath(sharedRoot)", 'jobId.ToString("D") + ".iar"',
"offset == currentBytes", "bytes <= MaximumChunkBytes",
"now <= createdAt", "return null",
):
assert marker in core, marker
assert "OglIarTransferPolicy.cs" in text(
"tools/ci/OglIarSelfServiceRegression/OglIarSelfServiceRegression.csproj")
workflow = text(".github/workflows/nexjast-ci.yml")
assert "Verify IAR self-service bounded transfer, ownership and ETA" in workflow
assert "dotnet run --configuration Release --project tools/ci/OglIarSelfServiceRegression/OglIarSelfServiceRegression.csproj" in workflow
assert "/api/v1/iar/me/operations/{id}" in text("doc/NexVerse/OGL_IAR_SELF_SERVICE.md")
assert "mountOglIarSelfService" in text("doc/NexVerse/examples/ogl-iar-self-service-widget.js")
assert "setInterval(" in text("doc/NexVerse/examples/ogl-iar-self-service-widget.js")
assert "showSaveFilePicker" in text("doc/NexVerse/examples/ogl-iar-self-service-widget.js")
print("OGL IAR resident self-service static contracts PASS")