From 0fdee4c92d72c23a08f0250756981b1f02374fec Mon Sep 17 00:00:00 2001 From: "OpenGenesis (MPL 2.0)" <153564363+opengenesislink@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:31:57 +0100 Subject: [PATCH] feat(worldapi): complete Media API with secure uploads, inventory and marketplace (#311) * feat(media): durable MariaDB publication registry for owned images and marketplace listings * feat(media): managed uploads, marketplace publication, inventory image and profile/group binding * feat(media): route managed assets, marketplace, inventory and mutations through central image codec * feat(media): allow dedicated machine-only marketplace publication scope * feat(media): allow dedicated machine-only marketplace publication scope * feat(media): connect permanent publication catalog to existing ROBUST MariaDB and providers * fix(media): encode uploads as real OpenSim JPEG2000 texture assets for Firestorm compatibility * fix(media): keep owner-inventory images on explicit /inventory/{itemId}/image path * feat(media): publish complete asset/upload/inventory/marketplace contracts in OpenAPI * docs(media): include all secure media endpoints in citizen/portal instruction catalog * docs(media): full end-to-end managed uploads, marketplace, binding and portal handoff * test(media): cover complete upload, publication, ownership and MariaDB contract in CI * test(media): initialize real MariaDB media catalog and assert owner/public/marketplace HTTP flows --- NexVerse/Core/Security/NexApiKeyStore.cs | 1 + NexVerse/Core/Security/NexSecurity.cs | 3 + .../Api/NexChatGptInstructionDownloads.cs | 8 +- NexVerse/Server/Api/NexManagedMediaApi.cs | 567 ++++++++++++++++++ NexVerse/Server/Api/NexMediaApi.cs | 19 + NexVerse/Server/Api/NexMediaCatalogStore.cs | 166 +++++ .../Server/Api/NexVerseWorldApiConnector.cs | 25 + .../Server/Api/NexVerseWorldApiHandlers.cs | 144 ++++- doc/NexVerse/WORLD_API_MEDIA_1_0.md | 113 ++-- tools/ci/NexGroupsHttpRegression/Program.cs | 66 +- tools/ci/verify_media_api.py | 40 +- 11 files changed, 1106 insertions(+), 46 deletions(-) create mode 100644 NexVerse/Server/Api/NexManagedMediaApi.cs create mode 100644 NexVerse/Server/Api/NexMediaCatalogStore.cs diff --git a/NexVerse/Core/Security/NexApiKeyStore.cs b/NexVerse/Core/Security/NexApiKeyStore.cs index 9e1e39d2..bc60d6aa 100644 --- a/NexVerse/Core/Security/NexApiKeyStore.cs +++ b/NexVerse/Core/Security/NexApiKeyStore.cs @@ -69,6 +69,7 @@ namespace NexVerse.Core.Security NexScopes.UsersRegister, NexScopes.PasswordRecoveryIssue, NexScopes.PasswordRecoveryComplete, + NexScopes.MediaPublish, NexScopes.InventoryRead, NexScopes.InventoryWrite, NexScopes.FriendsManage, diff --git a/NexVerse/Core/Security/NexSecurity.cs b/NexVerse/Core/Security/NexSecurity.cs index 00f2e551..7d6500db 100644 --- a/NexVerse/Core/Security/NexSecurity.cs +++ b/NexVerse/Core/Security/NexSecurity.cs @@ -25,6 +25,9 @@ namespace NexVerse.Core.Security // user role and self-service grant lists. public const string PasswordRecoveryIssue = "password-recovery:issue"; public const string PasswordRecoveryComplete = "password-recovery:complete"; + // Dedicated portal/marketplace publisher; machine API-key only. + // Never add to resident/role-computed scopes. + public const string MediaPublish = "media:publish"; public const string InventoryRead = "inventory:read"; public const string InventoryWrite = "inventory:write"; public const string FriendsManage = "friends:manage"; diff --git a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs index 374d96a5..58fe579c 100644 --- a/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs +++ b/NexVerse/Server/Api/NexChatGptInstructionDownloads.cs @@ -633,10 +633,14 @@ namespace NexVerse.Server.Api AppendCatalogGroup(md, requestedAudience, "shared", "Avatarprofile und Bildbytes", "/api/v1/profiles/{principalId}", "/api/v1/profiles/{principalId}/image"); - AppendCatalogGroup(md, requestedAudience, "shared", "OpenGenesisLINK Media API 1.0: autorisierte Gruppen- und Avatarbilder", + AppendCatalogGroup(md, requestedAudience, "shared", "OpenGenesisLINK Media API: Bilder, sichere Uploads, Medienkatalog und Marketplace", "/api/v1/media/groups/{groupId}/image", "/api/v1/media/profiles/{principalId}/image", - "/api/v1/media/profiles/{principalId}/first-life"); + "/api/v1/media/profiles/{principalId}/first-life", + "/api/v1/media/uploads", + "/api/v1/media/assets/{assetId}", + "/api/v1/media/inventory/{itemId}/image", + "/api/v1/media/marketplace/{listingId}/image"); AppendCatalogGroup(md, requestedAudience, "shared", "Regionen", "/api/v1/regions", "/api/v1/regions/{regionId}"); diff --git a/NexVerse/Server/Api/NexManagedMediaApi.cs b/NexVerse/Server/Api/NexManagedMediaApi.cs new file mode 100644 index 00000000..16e164e9 --- /dev/null +++ b/NexVerse/Server/Api/NexManagedMediaApi.cs @@ -0,0 +1,567 @@ +// SPDX-License-Identifier: MPL-2.0 +// Media uploads, publication and owner-bound inventory images. +using System; +using System.IO; +using System.Net; +using System.Drawing; +using OpenMetaverse.Imaging; +using System.Text.Json; +using log4net; +using NexVerse.Core.Security; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Groups; +using OpenSim.Services.Interfaces; + +namespace NexVerse.Server.Api +{ + internal sealed class NexManagedMediaApi + { + private static readonly ILog s_Log = LogManager.GetLogger(typeof(NexManagedMediaApi)); + private const int MaxUploadBytes = 4 * 1024 * 1024; + private const int MaxJsonBytes = 6 * 1024 * 1024; + private readonly NexApiAuthenticator m_Auth; + private readonly IUserAccountService m_Accounts; + private readonly IInventoryService m_Inventory; + private readonly IProfilesData m_Profiles; + private readonly GroupsService m_Groups; + private readonly Func m_Assets; + private readonly NexMediaCatalogStore m_Catalog; + private readonly Action m_Render; + + internal NexManagedMediaApi(NexApiAuthenticator auth, + IUserAccountService accounts, IInventoryService inventory, + IProfilesData profiles, GroupsService groups, + Func assets, NexMediaCatalogStore catalog, + Action render) + { + m_Auth = auth ?? throw new ArgumentNullException(nameof(auth)); + m_Accounts = accounts ?? throw new ArgumentNullException(nameof(accounts)); + m_Inventory = inventory; + m_Profiles = profiles; + m_Groups = groups; + m_Assets = assets ?? throw new ArgumentNullException(nameof(assets)); + m_Catalog = catalog; + m_Render = render ?? throw new ArgumentNullException(nameof(render)); + } + + internal static bool CanHandle(string path, string method) => + path.StartsWith("/api/v1/media/uploads", StringComparison.Ordinal) || + path.StartsWith("/api/v1/media/assets/", StringComparison.Ordinal) || + path.StartsWith("/api/v1/media/marketplace/", StringComparison.Ordinal) || + path.StartsWith("/api/v1/media/inventory/", StringComparison.Ordinal) || + ((method == "PUT") && + (path.StartsWith("/api/v1/media/groups/", StringComparison.Ordinal) || + path.StartsWith("/api/v1/media/profiles/", StringComparison.Ordinal))); + + internal void Handle(IOSHttpRequest request, IOSHttpResponse response) + { + response.AddHeader("Cache-Control", "private, no-store"); + response.AddHeader("X-Content-Type-Options", "nosniff"); + string path = (request.UriPath ?? "").TrimEnd('/'); + string method = request.HttpMethod ?? ""; + string[] parts = path.Trim('/').Split('/'); + try + { + if (path == "/api/v1/media/uploads" && method == "POST") + { + Upload(request, response); + return; + } + + // Strict segment matching; never expose an arbitrary legacy asset. + if (parts.Length == 5 && + parts[0] == "api" && parts[1] == "v1" && parts[2] == "media" && + UUID.TryParse(parts[4], out UUID id) && !id.IsZero()) + { + if (parts[3] == "assets") + { + if (method == "GET") ReadAsset(request, response, id); + else if (method == "PATCH") ChangeVisibility(request, response, id); + else Error(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed"); + return; + } + // Inventory entries include an explicit /image suffix; + // do not broaden the asset-UUID namespace. + + } + if (parts.Length == 6 && parts[0] == "api" && + parts[1] == "v1" && parts[2] == "media" && + UUID.TryParse(parts[4], out UUID entity) && !entity.IsZero() && + parts[5] == "image") + + { + if (parts[3] == "inventory" && method == "GET") + { + ReadInventory(request, response, entity); + return; + } + if (parts[3] == "marketplace") + { + if (method == "GET") ReadListing(request, response, entity); + else if (method == "PUT") PublishListing(request, response, entity); + else if (method == "DELETE") UnpublishListing(request, response, entity); + else Error(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed"); + return; + } + if (method == "PUT" && parts[3] == "groups") + { + UpdateGroupImage(request, response, entity); + return; + } + if (method == "PUT" && parts[3] == "profiles") + { + UpdateProfileImage(request, response, entity, false); + return; + } + } + if (parts.Length == 6 && method == "PUT" && + parts[0] == "api" && parts[1] == "v1" && parts[2] == "media" && + parts[3] == "profiles" && parts[5] == "first-life" && + UUID.TryParse(parts[4], out UUID avatar) && !avatar.IsZero()) + { + UpdateProfileImage(request, response, avatar, true); + return; + } + Error(response, HttpStatusCode.NotFound, "media_not_found"); + } + catch (JsonException) { Error(response, HttpStatusCode.BadRequest, "invalid_json"); } + catch (FormatException) { Error(response, HttpStatusCode.BadRequest, "invalid_media_format"); } + catch (MySql.Data.MySqlClient.MySqlException e) + { + s_Log.Error("[OGL-MEDIA]: MariaDB publication failure", e); + Error(response, HttpStatusCode.ServiceUnavailable, "media_catalog_unavailable"); + } + catch (Exception e) + { + s_Log.Error("[OGL-MEDIA]: managed media request failed", e); + Error(response, HttpStatusCode.ServiceUnavailable, "media_service_unavailable"); + } + } + + private bool Ready(IOSHttpResponse response) + { + if (m_Catalog != null) return true; + Error(response, HttpStatusCode.ServiceUnavailable, "media_catalog_unavailable"); + return false; + } + + private bool Authorize(IOSHttpRequest request, IOSHttpResponse response, + string scope, out NexPrincipal principal, out UserAccount account) + { + if (m_Auth.TryAuthenticate(request, scope, out principal, out account, + out int status, out string code)) return true; + Error(response, (HttpStatusCode)status, code); + return false; + } + + private bool Machine(IOSHttpRequest request, IOSHttpResponse response) + { + if (!Authorize(request, response, NexScopes.MediaPublish, + out NexPrincipal principal, out _)) return false; + if (!principal.Subject.StartsWith("api-key:", StringComparison.Ordinal)) + { + Error(response, HttpStatusCode.Forbidden, "machine_key_required"); + return false; + } + return true; + } + + private static JsonElement Body(IOSHttpRequest request) + { + using var buffer = new MemoryStream(); + byte[] chunk = new byte[16384]; + int count; + while ((count = request.InputStream.Read(chunk, 0, chunk.Length)) > 0) + { + if (buffer.Length + count > MaxJsonBytes) + throw new FormatException("Oversized media JSON body"); + buffer.Write(chunk, 0, count); + } + buffer.Position = 0; + using JsonDocument json = JsonDocument.Parse(buffer); + if (json.RootElement.ValueKind != JsonValueKind.Object) + throw new FormatException("Object expected"); + return json.RootElement.Clone(); + } + + private static bool TryUuid(JsonElement obj, string name, out UUID value) + { + value = UUID.Zero; + return obj.TryGetProperty(name, out JsonElement part) && + part.ValueKind == JsonValueKind.String && + UUID.TryParse(part.GetString(), out value) && !value.IsZero(); + } + + private static bool TryImageBytes(string mime, byte[] data) + { + if (data.Length < 32 || data.Length > MaxUploadBytes) + return false; + if (mime == "image/png") + { + if (data[0] != 0x89 || data[1] != 0x50 || data[2] != 0x4e || + data[3] != 0x47 || data[12] != (byte)'I' || + data[13] != (byte)'H' || data[14] != (byte)'D' || data[15] != (byte)'R') + return false; + int w = (data[16] << 24) | (data[17] << 16) | (data[18] << 8) | data[19]; + int h = (data[20] << 24) | (data[21] << 16) | (data[22] << 8) | data[23]; + return w > 0 && w <= 2048 && h > 0 && h <= 2048; + } + if (mime != "image/jpeg" || data[0] != 0xff || data[1] != 0xd8) + return false; + // Scan JPEG SOF for bounded dimensions. Do not trust MIME alone. + int p = 2; + while (p + 9 < data.Length) + { + if (data[p++] != 0xff) return false; + while (p < data.Length && data[p] == 0xff) ++p; + if (p >= data.Length) return false; + byte marker = data[p++]; + if (marker == 0xda || marker == 0xd9) return false; + if (p + 1 >= data.Length) return false; + int length = (data[p] << 8) | data[p + 1]; + if (length < 2 || p + length > data.Length) return false; + if ((marker >= 0xc0 && marker <= 0xcf) && + marker != 0xc4 && marker != 0xc8 && marker != 0xcc) + { + if (length < 7) return false; + int h = (data[p + 3] << 8) | data[p + 4]; + int w = (data[p + 5] << 8) | data[p + 6]; + return w > 0 && w <= 2048 && h > 0 && h <= 2048; + } + p += length; + } + return false; + } + + private void Upload(IOSHttpRequest request, IOSHttpResponse response) + { + if (!Ready(response)) return; + // Residents upload for themselves; dedicated publisher machine + // keys may upload for a local account explicitly named by the portal. + bool resident = m_Auth.TryAuthenticate(request, NexScopes.ProfileWrite, + out NexPrincipal actor, out UserAccount user, out _, out _) && + user != null && user.LocalToGrid; + if (!resident && !Machine(request, response)) return; + + JsonElement body = Body(request); + UUID owner = resident ? user.PrincipalID : UUID.Zero; + if (resident) + { + if (body.TryGetProperty("owner_id", out JsonElement raw) && + (!UUID.TryParse(raw.GetString(), out UUID supplied) || supplied != owner)) + { + Error(response, HttpStatusCode.Forbidden, "owner_mismatch"); + return; + } + } + else if (!TryUuid(body, "owner_id", out owner) || + m_Accounts.GetUserAccount(UUID.Zero, owner) is not UserAccount existing || + !existing.LocalToGrid) + { + Error(response, HttpStatusCode.BadRequest, "invalid_owner"); + return; + } + if (!body.TryGetProperty("content_type", out JsonElement contentType) || + contentType.ValueKind != JsonValueKind.String || + !body.TryGetProperty("data_base64", out JsonElement encoded) || + encoded.ValueKind != JsonValueKind.String) + { + Error(response, HttpStatusCode.BadRequest, "missing_image_data"); + return; + } + string mime = contentType.GetString(); + byte[] data; + try { data = Convert.FromBase64String(encoded.GetString()); } + catch (FormatException) { Error(response, HttpStatusCode.BadRequest, "invalid_base64"); return; } + if (!TryImageBytes(mime, data)) + { + Error(response, HttpStatusCode.UnsupportedMediaType, "invalid_image"); + return; + } + + IAssetService assets = m_Assets(); + if (assets == null) + { + Error(response, HttpStatusCode.ServiceUnavailable, "media_asset_service_unavailable"); + return; + } + // Avatar/group/Viewer textures MUST be JPEG2000, not PNG/JPEG + // bytes mislabeled as OpenSim AssetType.Texture. + byte[] texture; + try + { + using MemoryStream source = new MemoryStream(data, false); + using Image original = Image.FromStream(source, false, true); + if (original.Width <= 0 || original.Height <= 0 || + original.Width > 2048 || original.Height > 2048) + { + Error(response, HttpStatusCode.RequestEntityTooLarge, "media_dimensions_exceeded"); + return; + } + using Bitmap bitmap = new Bitmap(original); + texture = OpenJPEG.EncodeFromImage(bitmap, false); + if (texture == null || texture.Length < 8 || texture.Length > MaxUploadBytes) + { + Error(response, HttpStatusCode.UnsupportedMediaType, "media_transcode_failed"); + return; + } + } + catch (Exception e) when (e is ArgumentException || + e is PlatformNotSupportedException || + e is TypeInitializationException || + e is DllNotFoundException) + { + // Never store corrupt non-JPEG2000 bytes for the Viewer. + s_Log.Warn("[OGL-MEDIA]: PNG/JPEG to JPEG2000 encoder unavailable or invalid (" + + e.GetType().Name + ")"); + Error(response, HttpStatusCode.ServiceUnavailable, "media_encoder_unavailable"); + return; + } + UUID id = UUID.Random(); + AssetBase asset = new AssetBase(id, "OpenGenesisLINK Media", + (sbyte)AssetType.Texture, owner.ToString()) { Data = texture }; + string storedId = assets.Store(asset); + if (!UUID.TryParse(storedId, out UUID committed) || committed.IsZero()) + { + Error(response, HttpStatusCode.ServiceUnavailable, "media_asset_store_failed"); + return; + } + // On transient SQL errors an unreferenced immutable asset remains + // in AssetService; never expose it via a free UUID route. + m_Catalog.RecordUpload(committed, owner, mime); + Reply(response, HttpStatusCode.Created, new + { + asset_id = committed.ToString(), + owner_id = owner.ToString(), + content_type = mime, + image_url = "/api/v1/media/assets/" + committed, + visibility = "private" + }); + } + + private bool OwnerOrPublisher(IOSHttpRequest request, IOSHttpResponse response, + NexMediaCatalogStore.MediaRecord media, out bool trustedPublisher) + { + trustedPublisher = false; + if (m_Auth.TryAuthenticate(request, NexScopes.ProfileWrite, + out NexPrincipal _, out UserAccount account, out _, out _) && + account != null && account.PrincipalID == media.Owner) + return true; + if (m_Auth.TryAuthenticate(request, NexScopes.MediaPublish, + out NexPrincipal publisher, out _, out _, out _) && + publisher.Subject.StartsWith("api-key:", StringComparison.Ordinal)) + { + trustedPublisher = true; + return true; + } + Error(response, HttpStatusCode.Forbidden, "media_owner_required"); + return false; + } + + private void ReadAsset(IOSHttpRequest request, IOSHttpResponse response, UUID assetId) + { + if (!Ready(response)) return; + NexMediaCatalogStore.MediaRecord? item = m_Catalog.FindUpload(assetId); + if (!item.HasValue) + { + Error(response, HttpStatusCode.NotFound, "media_not_found"); + return; + } + if (!item.Value.Public) + { + if (!Authorize(request, response, NexScopes.ProfileRead, + out NexPrincipal actor, out UserAccount account)) return; + if ((account == null || account.PrincipalID != item.Value.Owner) && + !actor.HasScope(NexScopes.AdminAll)) + { + Error(response, HttpStatusCode.NotFound, "media_not_found"); + return; + } + } + Render(request, response, assetId); + } + + private void ReadInventory(IOSHttpRequest request, IOSHttpResponse response, UUID itemId) + { + if (!Authorize(request, response, NexScopes.InventoryRead, + out _, out UserAccount user)) return; + if (user == null || !user.LocalToGrid || m_Inventory == null) + { + Error(response, HttpStatusCode.NotFound, "media_not_found"); + return; + } + InventoryItemBase item = m_Inventory.GetItem(user.PrincipalID, itemId); + if (item == null || item.Owner != user.PrincipalID || + (item.AssetType != (int)AssetType.Texture && + item.AssetType != (int)AssetType.ImageJPEG && + item.AssetType != (int)AssetType.TextureTGA && + item.AssetType != (int)AssetType.ImageTGA)) + { + Error(response, HttpStatusCode.NotFound, "media_not_found"); + return; + } + Render(request, response, item.AssetID); + } + + private void ChangeVisibility(IOSHttpRequest request, IOSHttpResponse response, UUID assetId) + { + if (!Ready(response)) return; + NexMediaCatalogStore.MediaRecord? item = m_Catalog.FindUpload(assetId); + if (!item.HasValue) { Error(response, HttpStatusCode.NotFound, "media_not_found"); return; } + if (!OwnerOrPublisher(request, response, item.Value, out _)) return; + JsonElement body = Body(request); + if (!body.TryGetProperty("public", out JsonElement mode) || + (mode.ValueKind != JsonValueKind.True && mode.ValueKind != JsonValueKind.False)) + { + Error(response, HttpStatusCode.BadRequest, "invalid_visibility"); + return; + } + m_Catalog.ChangeVisibility(assetId, item.Value.Owner, mode.GetBoolean()); + Reply(response, HttpStatusCode.OK, new { asset_id = assetId.ToString(), + visibility = mode.GetBoolean() ? "public" : "private" }); + } + + private void ReadListing(IOSHttpRequest request, IOSHttpResponse response, UUID listing) + { + if (!Ready(response)) return; + UUID? asset = m_Catalog.FindListingImage(listing); + if (!asset.HasValue) { Error(response, HttpStatusCode.NotFound, "media_not_found"); return; } + Render(request, response, asset.Value); + } + + private void PublishListing(IOSHttpRequest request, IOSHttpResponse response, UUID listing) + { + if (!Ready(response) || !Machine(request, response)) return; + JsonElement body = Body(request); + if (!TryUuid(body, "asset_id", out UUID asset) || + !TryUuid(body, "owner_id", out UUID owner)) + { + Error(response, HttpStatusCode.BadRequest, "invalid_listing_binding"); + return; + } + if (!m_Catalog.PublishListing(listing, asset, owner)) + { + Error(response, HttpStatusCode.NotFound, "media_owner_asset_mismatch"); + return; + } + Reply(response, HttpStatusCode.OK, new { + listing_id = listing.ToString(), asset_id = asset.ToString(), + image_url = "/api/v1/media/marketplace/" + listing + "/image" + }); + } + + private void UnpublishListing(IOSHttpRequest request, IOSHttpResponse response, UUID listing) + { + if (!Ready(response) || !Machine(request, response)) return; + if (!m_Catalog.UnpublishListing(listing)) + { + Error(response, HttpStatusCode.NotFound, "media_not_found"); + return; + } + Reply(response, HttpStatusCode.OK, new { unpublished = true }); + } + + private void UpdateProfileImage(IOSHttpRequest request, IOSHttpResponse response, + UUID avatar, bool firstLife) + { + if (!Ready(response)) return; + if (!Authorize(request, response, NexScopes.ProfileWrite, out _, out UserAccount user)) + return; + if (user == null || user.PrincipalID != avatar || m_Profiles == null) + { + Error(response, HttpStatusCode.Forbidden, "profile_owner_required"); + return; + } + JsonElement body = Body(request); + if (!TryUuid(body, "asset_id", out UUID assetId) || + m_Catalog.FindUpload(assetId) is not NexMediaCatalogStore.MediaRecord upload || + upload.Owner != avatar) + { + Error(response, HttpStatusCode.NotFound, "media_owner_asset_mismatch"); + return; + } + UserProfileProperties profile = new UserProfileProperties { UserId = avatar }; + string error = ""; + if (!m_Profiles.GetAvatarProperties(ref profile, ref error)) + { + Error(response, HttpStatusCode.ServiceUnavailable, "profiles_service_unavailable"); + return; + } + if (firstLife) profile.FirstLifeImageId = assetId; + else profile.ImageId = assetId; + if (!m_Profiles.UpdateAvatarProperties(ref profile, ref error)) + { + Error(response, HttpStatusCode.ServiceUnavailable, "profile_image_update_failed"); + return; + } + Reply(response, HttpStatusCode.OK, new { asset_id = assetId.ToString(), + image_url = "/api/v1/media/profiles/" + avatar + + (firstLife ? "/first-life" : "/image") }); + } + + private void UpdateGroupImage(IOSHttpRequest request, IOSHttpResponse response, UUID groupId) + { + if (!Ready(response)) return; + if (!Authorize(request, response, NexScopes.GroupsManage, + out _, out UserAccount user)) return; + if (m_Groups == null || user == null || !user.LocalToGrid) + { + Error(response, HttpStatusCode.Forbidden, "group_resident_required"); + return; + } + JsonElement body = Body(request); + if (!TryUuid(body, "asset_id", out UUID assetId) || + m_Catalog.FindUpload(assetId) is not NexMediaCatalogStore.MediaRecord upload || + upload.Owner != user.PrincipalID) + { + Error(response, HttpStatusCode.NotFound, "media_owner_asset_mismatch"); + return; + } + ExtendedGroupRecord record = m_Groups.GetGroupRecord(user.PrincipalID.ToString(), groupId); + ExtendedGroupMembershipData membership = m_Groups.GetAgentGroupMembership( + user.PrincipalID.ToString(), user.PrincipalID.ToString(), groupId); + if (record == null || membership == null || + (((GroupPowers)membership.GroupPowers & GroupPowers.ChangeActions) == 0 && + record.FounderID != user.PrincipalID)) + { + Error(response, HttpStatusCode.Forbidden, "group_change_identity_required"); + return; + } + m_Groups.UpdateGroup(user.PrincipalID.ToString(), groupId, record.Charter, + record.ShowInList, assetId, record.MembershipFee, record.OpenEnrollment, + record.AllowPublish, record.MaturePublish); + ExtendedGroupRecord changed = m_Groups.GetGroupRecord(user.PrincipalID.ToString(), groupId); + if (changed == null || changed.GroupPicture != assetId) + { + Error(response, HttpStatusCode.ServiceUnavailable, "group_image_update_failed"); + return; + } + Reply(response, HttpStatusCode.OK, new { asset_id = assetId.ToString(), + image_url = "/api/v1/media/groups/" + groupId + "/image" }); + } + + private void Render(IOSHttpRequest request, IOSHttpResponse response, UUID asset) + { + if (!NexMediaApi.TryParseSize(request.QueryString?["size"], out int size)) + { + Error(response, HttpStatusCode.BadRequest, "invalid_image_size"); + return; + } + m_Render(asset, response, size); + } + + private static void Error(IOSHttpResponse response, HttpStatusCode status, string code) => + Reply(response, status, new { error = code }); + + private static void Reply(IOSHttpResponse response, HttpStatusCode status, object body) + { + response.StatusCode = (int)status; + response.ContentType = "application/json; charset=utf-8"; + response.KeepAlive = false; + response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(body); + } + } +} diff --git a/NexVerse/Server/Api/NexMediaApi.cs b/NexVerse/Server/Api/NexMediaApi.cs index b5f3d8e5..9b01e65c 100644 --- a/NexVerse/Server/Api/NexMediaApi.cs +++ b/NexVerse/Server/Api/NexMediaApi.cs @@ -35,6 +35,14 @@ namespace NexVerse.Server.Api private readonly GroupsService m_Groups; private readonly Func m_ResolveAssets; private readonly NexApiAuthenticator m_Authenticator; + private NexManagedMediaApi m_Managed; + + internal void ConfigureManaged(NexManagedMediaApi managed) => m_Managed = managed; + + // Reuse the same bounds, type checks and codec for every authorized + // entity, inventory item or media publication. + internal void ServeLinkedImage(UUID assetId, IOSHttpResponse response, int size) => + Serve(assetId, response, size); internal NexMediaApi(IUserAccountService accounts, IProfilesData profiles, GroupsService groups, Func resolveAssets, @@ -56,6 +64,17 @@ namespace NexVerse.Server.Api Error(response, HttpStatusCode.BadRequest, "invalid_request"); return; } + string rawPath = (request.UriPath ?? "").TrimEnd('/'); + if (NexManagedMediaApi.CanHandle(rawPath, request.HttpMethod ?? "")) + { + if (m_Managed == null) + { + Error(response, HttpStatusCode.ServiceUnavailable, "media_catalog_unavailable"); + return; + } + m_Managed.Handle(request, response); + return; + } if (!string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { response.AddHeader("Allow", "GET"); diff --git a/NexVerse/Server/Api/NexMediaCatalogStore.cs b/NexVerse/Server/Api/NexMediaCatalogStore.cs new file mode 100644 index 00000000..45583e11 --- /dev/null +++ b/NexVerse/Server/Api/NexMediaCatalogStore.cs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: MPL-2.0 +// Durable, server-owned publication registry; never scans or publishes +// arbitrary FSAsset/OpenSim inventory contents. +using System; +using MySql.Data.MySqlClient; +using OpenMetaverse; + +namespace NexVerse.Server.Api +{ + internal sealed class NexMediaCatalogStore + { + internal readonly struct MediaRecord + { + internal readonly UUID Asset; + internal readonly UUID Owner; + internal readonly bool Public; + internal readonly string Mime; + + internal MediaRecord(UUID asset, UUID owner, bool isPublic, string mime) + { + Asset = asset; + Owner = owner; + Public = isPublic; + Mime = mime; + } + } + + private readonly string m_Connection; + + internal NexMediaCatalogStore(string connectionString) + { + if (string.IsNullOrWhiteSpace(connectionString)) + throw new ArgumentException("Existing ROBUST MariaDB connection required."); + m_Connection = connectionString; + using MySqlConnection db = Open(); + using MySqlCommand schema = db.CreateCommand(); + schema.CommandText = @"CREATE TABLE IF NOT EXISTS ogl_media_uploads ( + asset_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + owner_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + mime VARCHAR(24) NOT NULL, + is_public TINYINT(1) NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + INDEX ix_ogl_media_owner (owner_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; + schema.ExecuteNonQuery(); + schema.CommandText = @"CREATE TABLE IF NOT EXISTS ogl_media_marketplace ( + listing_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + asset_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + owner_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + updated_at BIGINT NOT NULL, + INDEX ix_ogl_media_listing_asset (asset_id), + CONSTRAINT fk_ogl_media_uploaded_asset FOREIGN KEY(asset_id) + REFERENCES ogl_media_uploads(asset_id) ON DELETE RESTRICT + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; + schema.ExecuteNonQuery(); + } + + private MySqlConnection Open() + { + var db = new MySqlConnection(m_Connection); + db.Open(); + return db; + } + + internal void RecordUpload(UUID assetId, UUID ownerId, string mime) + { + if (assetId.IsZero() || ownerId.IsZero() || + (mime != "image/png" && mime != "image/jpeg")) + throw new ArgumentException("Invalid owned media upload."); + using MySqlConnection db = Open(); + using MySqlCommand command = db.CreateCommand(); + command.CommandText = @"INSERT INTO ogl_media_uploads + (asset_id,owner_id,mime,is_public,created_at) + VALUES(@asset,@owner,@mime,0,@now)"; + command.Parameters.AddWithValue("@asset", assetId.ToString()); + command.Parameters.AddWithValue("@owner", ownerId.ToString()); + command.Parameters.AddWithValue("@mime", mime); + command.Parameters.AddWithValue("@now", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + command.ExecuteNonQuery(); + } + + internal MediaRecord? FindUpload(UUID assetId) + { + if (assetId.IsZero()) return null; + using MySqlConnection db = Open(); + using MySqlCommand command = db.CreateCommand(); + command.CommandText = @"SELECT owner_id,is_public,mime FROM ogl_media_uploads + WHERE asset_id=@asset LIMIT 1"; + command.Parameters.AddWithValue("@asset", assetId.ToString()); + using MySqlDataReader reader = command.ExecuteReader(); + if (!reader.Read() || !UUID.TryParse(reader.GetString(0), out UUID owner)) + return null; + return new MediaRecord(assetId, owner, reader.GetBoolean(1), reader.GetString(2)); + } + + internal bool ChangeVisibility(UUID assetId, UUID ownerId, bool publicAccess) + { + if (assetId.IsZero() || ownerId.IsZero()) return false; + using MySqlConnection db = Open(); + using MySqlCommand command = db.CreateCommand(); + command.CommandText = @"UPDATE ogl_media_uploads SET is_public=@visible + WHERE asset_id=@asset AND owner_id=@owner"; + command.Parameters.AddWithValue("@asset", assetId.ToString()); + command.Parameters.AddWithValue("@owner", ownerId.ToString()); + command.Parameters.AddWithValue("@visible", publicAccess); + return command.ExecuteNonQuery() == 1; + } + + internal bool PublishListing(UUID listingId, UUID assetId, UUID ownerId) + { + if (listingId.IsZero() || assetId.IsZero() || ownerId.IsZero()) return false; + using MySqlConnection db = Open(); + using MySqlTransaction tx = db.BeginTransaction(); + using (MySqlCommand check = db.CreateCommand()) + { + check.Transaction = tx; + check.CommandText = @"SELECT COUNT(*) FROM ogl_media_uploads + WHERE asset_id=@asset AND owner_id=@owner FOR UPDATE"; + check.Parameters.AddWithValue("@asset", assetId.ToString()); + check.Parameters.AddWithValue("@owner", ownerId.ToString()); + if (Convert.ToInt32(check.ExecuteScalar()) != 1) + return false; + } + using (MySqlCommand cmd = db.CreateCommand()) + { + cmd.Transaction = tx; + cmd.CommandText = @"INSERT INTO ogl_media_marketplace + (listing_id,asset_id,owner_id,updated_at) + VALUES(@listing,@asset,@owner,@now) + ON DUPLICATE KEY UPDATE asset_id=VALUES(asset_id), + owner_id=VALUES(owner_id),updated_at=VALUES(updated_at)"; + cmd.Parameters.AddWithValue("@listing", listingId.ToString()); + cmd.Parameters.AddWithValue("@asset", assetId.ToString()); + cmd.Parameters.AddWithValue("@owner", ownerId.ToString()); + cmd.Parameters.AddWithValue("@now", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); + cmd.ExecuteNonQuery(); + } + tx.Commit(); + return true; + } + + internal UUID? FindListingImage(UUID listingId) + { + if (listingId.IsZero()) return null; + using MySqlConnection db = Open(); + using MySqlCommand cmd = db.CreateCommand(); + cmd.CommandText = @"SELECT m.asset_id FROM ogl_media_marketplace m + INNER JOIN ogl_media_uploads u ON m.asset_id=u.asset_id + WHERE m.listing_id=@listing LIMIT 1"; + cmd.Parameters.AddWithValue("@listing", listingId.ToString()); + object result = cmd.ExecuteScalar(); + return result != null && UUID.TryParse(Convert.ToString(result), out UUID id) + && !id.IsZero() ? id : null; + } + + internal bool UnpublishListing(UUID listingId) + { + if (listingId.IsZero()) return false; + using MySqlConnection db = Open(); + using MySqlCommand cmd = db.CreateCommand(); + cmd.CommandText = @"DELETE FROM ogl_media_marketplace WHERE listing_id=@listing"; + cmd.Parameters.AddWithValue("@listing", listingId.ToString()); + return cmd.ExecuteNonQuery() > 0; + } + } +} diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index ae02c62a..21c2230a 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -1219,6 +1219,31 @@ namespace NexVerse.Server.Api userAccounts, mediaProfilesData, nexGroupsService, () => AssetServiceConnector.GetLocalService(config, "AssetService"), authenticator); + NexMediaCatalogStore mediaCatalog = null; + if (apiConfig.GetBoolean("EnableManagedMedia", true)) + { + if (!string.IsNullOrWhiteSpace(databaseConnectionString) && + (databaseStorageProvider.IndexOf("MySQL", StringComparison.OrdinalIgnoreCase) >= 0 || + databaseStorageProvider.IndexOf("MariaDB", StringComparison.OrdinalIgnoreCase) >= 0)) + { + try + { + mediaCatalog = new NexMediaCatalogStore(databaseConnectionString); + } + catch (Exception e) + { + m_Log.Error("[OGL-MEDIA]: Managed media unavailable: MariaDB initialization failed.", e); + } + } + else + m_Log.Warn("[OGL-MEDIA]: Managed uploads require the existing ROBUST MariaDB provider."); + } + NexManagedMediaApi managedMedia = new NexManagedMediaApi( + authenticator, userAccounts, inventory, mediaProfilesData, + nexGroupsService, + () => AssetServiceConnector.GetLocalService(config, "AssetService"), + mediaCatalog, mediaApi.ServeLinkedImage); + mediaApi.ConfigureManaged(managedMedia); server.AddSimpleStreamHandler( new SimpleStreamHandler("/api/v1/media", apiGate.Wrap(mediaApi.Handle), diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 4cd9915f..568a2910 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -273,12 +273,27 @@ namespace NexVerse.Server.Api AuthenticatedOperations(("patch", "Eigene 11 editierbare userprofile-Spalten ändern; useruuid, profileImage und profileFirstImage bleiben gesperrt", "profile:write", "200"))), ["/api/v1/profiles/{principalId}/image"] = GetOperation( "Browserfähige Profilbild-Bytes der aktuell verknüpften Avatar-Textur; privat nur Owner/Admin"), - ["/api/v1/media/profiles/{principalId}/image"] = GetOperation( - "Browserfähiges Avatar-Profilbild über die gemeinsame Media API; privat nur Owner/Admin"), + ["/api/v1/media/profiles/{principalId}/image"] = MergeOperations( + GetOperation("Avatarbild, öffentlich nur für veröffentlichte Profile"), + AuthenticatedOperations(("put", "Eigenes hochgeladenes JPEG2000-Asset als aktuelles Profilbild setzen", "profile:write", "200"))), ["/api/v1/media/profiles/{principalId}/first-life"] = AuthenticatedOperations( - ("get", "First-Life-Bild nur für Avatar-Owner oder Administrator; kein öffentlicher Assetzugriff", "profile:read", "200")), + ("get", "First-Life-Bild nur für Avatar-Owner oder Administrator", "profile:read", "200"), + ("put", "Eigenes hochgeladenes JPEG2000-Asset als First-Life-Bild setzen", "profile:write", "200")), ["/api/v1/media/groups/{groupId}/image"] = AuthenticatedOperations( - ("get", "Gruppeninsignie aus der aktuellen Gruppenreferenz als PNG/JPEG; nur autorisiert", "groups:read", "200")), + ("get", "Gruppeninsignie aus der aktuellen Gruppenreferenz als PNG/JPEG; nur autorisiert", "groups:read", "200"), + ("put", "Eigene hochgeladene Bildtextur als Gruppeninsignie setzen; Gruppenpower zusätzlich geprüft", "groups:manage", "200")), + ["/api/v1/media/uploads"] = AuthenticatedOperations( + ("post", "PNG/JPEG sicher als JPEG2000-Asset in bestehenden AssetService hochladen, Owner oder Publisher", "profile:write", "201")), + ["/api/v1/media/assets/{assetId}"] = MergeOperations( + GetOperation("Nur in der Medienverwaltung registrierte Assets; private nur mit Owner-Rechten"), + AuthenticatedOperations(("patch", "Eigene hochgeladene Bildtextur veröffentlichen/zurückziehen", "profile:write", "200"))), + ["/api/v1/media/inventory/{itemId}/image"] = AuthenticatedOperations( + ("get", "Bildtextur aus dem eigenen Inventar, kein fremder Asset-Zugriff", "inventory:read", "200")), + ["/api/v1/media/marketplace/{listingId}/image"] = MergeOperations( + GetOperation("Öffentliches Marketplace-Vorschaubild einer explizit veröffentlichten Listing-ID"), + AuthenticatedOperations( + ("put", "Marketplace-Bild veröffentlichen, dedizierter Maschinenkey nötig", "media:publish", "200"), + ("delete", "Marketplace-Bild zurückziehen, dedizierter Maschinenkey nötig", "media:publish", "200"))), ["/api/v1/relationships/{principalId}"] = AuthenticatedOperations( ("get", "Eigene Freundesliste mit Anfragezustand, Online-Sichtbarkeit und Rechten lesen", "relationships:read", "200")), ["/api/v1/relationships/{principalId}/{targetId}"] = AuthenticatedOperations( @@ -770,6 +785,64 @@ namespace NexVerse.Server.Api } } + // Managed Media API: publication and upload operations are JSON; + // read operations serve binary PNG/JPEG after entitlement checks. + ApplyJsonContract(paths, "/api/v1/media/uploads", "post", + "MediaUploadRequest", "MediaUploadResponse", "201"); + ApplyJsonContract(paths, "/api/v1/media/assets/{assetId}", "patch", + "MediaVisibilityRequest", "MediaObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/media/marketplace/{listingId}/image", "put", + "MediaListingRequest", "MediaObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/media/marketplace/{listingId}/image", "delete", + null, "MediaObjectResponse", "200"); + foreach (string route in new[] { + "/api/v1/media/groups/{groupId}/image", + "/api/v1/media/profiles/{principalId}/image", + "/api/v1/media/profiles/{principalId}/first-life" }) + ApplyJsonContract(paths, route, "put", "MediaBindRequest", + "MediaObjectResponse", "200"); + AddOperationParameters(paths, "/api/v1/media/assets/{assetId}", "get", + PathParameter("assetId", "Registrierte Medien-Asset-UUID")); + AddOperationParameters(paths, "/api/v1/media/assets/{assetId}", "patch", + PathParameter("assetId", "Registrierte Medien-Asset-UUID")); + AddOperationParameters(paths, "/api/v1/media/inventory/{itemId}/image", "get", + PathParameter("itemId", "Eigenes Inventar-Item")); + foreach (string op in new[] { "get", "put", "delete" }) + AddOperationParameters(paths, "/api/v1/media/marketplace/{listingId}/image", op, + PathParameter("listingId", "Marketplace-Listing-ID")); + foreach (string route in new[] { + "/api/v1/media/groups/{groupId}/image", + "/api/v1/media/profiles/{principalId}/image", + "/api/v1/media/profiles/{principalId}/first-life" }) + AddOperationParameters(paths, route, "put", + PathParameter(route.Contains("/groups/") ? "groupId" : "principalId", + route.Contains("/groups/") ? "Gruppen-UUID" : "Avatar-UUID")); + foreach (string route in new[] { + "/api/v1/media/assets/{assetId}", + "/api/v1/media/inventory/{itemId}/image", + "/api/v1/media/marketplace/{listingId}/image" }) + { + AddOperationParameters(paths, route, "get", + QueryParameter("size", false, "Vorschaubild: 64, 128, 256 oder 512 Pixel")); + if (paths[route] is Dictionary page && + page["get"] is Dictionary op) + { + op["responses"] = new Dictionary + { + ["200"] = new { + description = "PNG-/JPEG-Bildbytes; kein JSON", + content = new Dictionary { + ["image/png"] = new { schema = new { type = "string", format = "binary" } }, + ["image/jpeg"] = new { schema = new { type = "string", format = "binary" } } + } + }, + ["401"] = new { description = "Authentifizierung nötig" }, + ["403"] = new { description = "Zugriff verweigert" }, + ["404"] = new { description = "Bildreferenz nicht vorhanden" }, + ["503"] = new { description = "Mediendatenspeicher nicht verfügbar" } + }; + } + } ApplyJsonContract(paths, "/api/v1/experiences", "get", null, "ExperienceSearchResponse", "200"); ApplyJsonContract(paths, "/api/v1/experiences", "post", "NexExperienceCreateRequest", "ExperienceDetailsResponse", "201"); ApplyJsonContract(paths, "/api/v1/experiences/{experienceId}", "get", null, "ExperienceDetailsResponse", "200"); @@ -5734,6 +5807,69 @@ namespace NexVerse.Server.Api ["correlation_id"] = new { type = "string" } } }, + ["MediaUploadRequest"] = new + { + type = "object", + required = new[] { "content_type", "data_base64" }, + properties = new Dictionary + { + ["content_type"] = new { type = "string", @enum = new[] { "image/png", "image/jpeg" } }, + ["data_base64"] = new { type = "string", format = "byte", writeOnly = true }, + ["owner_id"] = new { type = "string", format = "uuid", description = "Nur mit media:publish-Maschinenkey" } + } + }, + ["MediaBindRequest"] = new + { + type = "object", + required = new[] { "asset_id" }, + properties = new Dictionary + { + ["asset_id"] = new { type = "string", format = "uuid" } + } + }, + ["MediaVisibilityRequest"] = new + { + type = "object", + required = new[] { "public" }, + properties = new Dictionary + { + ["public"] = new { type = "boolean" } + } + }, + ["MediaListingRequest"] = new + { + type = "object", + required = new[] { "asset_id", "owner_id" }, + properties = new Dictionary + { + ["asset_id"] = new { type = "string", format = "uuid" }, + ["owner_id"] = new { type = "string", format = "uuid" } + } + }, + ["MediaUploadResponse"] = new + { + type = "object", + properties = new Dictionary + { + ["asset_id"] = new { type = "string", format = "uuid" }, + ["owner_id"] = new { type = "string", format = "uuid" }, + ["content_type"] = new { type = "string" }, + ["image_url"] = new { type = "string" }, + ["visibility"] = new { type = "string" } + } + }, + ["MediaObjectResponse"] = new + { + type = "object", + properties = new Dictionary + { + ["asset_id"] = new { type = "string", format = "uuid" }, + ["image_url"] = new { type = "string" }, + ["visibility"] = new { type = "string" }, + ["listing_id"] = new { type = "string", format = "uuid" }, + ["unpublished"] = new { type = "boolean" } + } + }, ["PasswordRecoveryIssueRequest"] = new { type = "object", diff --git a/doc/NexVerse/WORLD_API_MEDIA_1_0.md b/doc/NexVerse/WORLD_API_MEDIA_1_0.md index ea27a29c..d9e4150c 100644 --- a/doc/NexVerse/WORLD_API_MEDIA_1_0.md +++ b/doc/NexVerse/WORLD_API_MEDIA_1_0.md @@ -1,61 +1,106 @@ -# OpenGenesisLINK Media API 1.0 – Gruppen-/Profilbilder +# OpenGenesisLINK Media API – vollständige World-API-Integration -Stand: 25.10.2026. Phase 1: **read-only** und durch Entitätszuordnung abgesichert. Für World-/ROBUST-Versionen mit diesem Feature-Commit; vor einem Deployment als nicht verfügbar behandeln. +Stand: 25.10.2026. Der Medienkatalog ergänzt die bereits existierenden Avatar- und Gruppenservices, ohne eine zweite Asset-Datenbank oder einen zweiten AssetService zu starten. **Produktiv nutzbar erst nach Deployment und Staging-Abnahme des integrierten Builds.** -## HTTP-Endpunkte +## 1. Endpunkte -| Methode | Endpunkt | Schutz | +Basis: `https://world.stadt-nexverse.de`. + +| Methode | URL | Zugriffsregeln | |---|---|---| -| GET | `/api/v1/media/groups/{groupId}/image` | `groups:read` (inkl. serverseitiger Gruppenreferenzprüfung) | -| GET | `/api/v1/media/profiles/{principalId}/image` | öffentlich nur bei `profileAllowPublish`; sonst `profile:read` und Owner/Admin | -| GET | `/api/v1/media/profiles/{principalId}/first-life` | **immer** `profile:read` und Avatar-Owner/Admin | +| GET | `/api/v1/media/groups/{groupId}/image` | `groups:read`, maßgebliche Gruppeninsignie | +| PUT | `/api/v1/media/groups/{groupId}/image` | Resident `groups:manage` **und** gruppeninterne `ChangeActions`-Berechtigung oder Founder, plus eigenes Upload | +| GET | `/api/v1/media/profiles/{principalId}/image` | öffentlich bei `PublishProfile`, privat nur Owner/Admin | +| PUT | `/api/v1/media/profiles/{principalId}/image` | `profile:write`, eigener Avatar und eigenes Upload | +| GET | `/api/v1/media/profiles/{principalId}/first-life` | `profile:read`, immer Owner/Admin | +| PUT | `/api/v1/media/profiles/{principalId}/first-life` | `profile:write`, eigener Avatar und eigenes Upload | +| POST | `/api/v1/media/uploads` | Resident `profile:write` für sich selbst; vertrauenswürdiger Publisher mit `media:publish`-Maschinenkey für lokalen Avatar | +| GET | `/api/v1/media/assets/{assetId}` | **Nur im Medienkatalog registrierte** Uploads; öffentlich nur bei expliziter Veröffentlichung, sonst Owner/Admin | +| PATCH | `/api/v1/media/assets/{assetId}` | Owner mit `profile:write` oder dedizierter `media:publish`-Publisher | +| GET | `/api/v1/media/inventory/{itemId}/image` | `inventory:read`, **nur wirklich eigenes Inventaritem** mit erlaubtem Bildtyp | +| GET | `/api/v1/media/marketplace/{listingId}/image` | öffentlich, wenn vertrauenswürdiger Publisher eine Bildbindung für diese Listing-ID registriert hat | +| PUT | `/api/v1/media/marketplace/{listingId}/image` | dedizierter `media:publish`-Maschinenkey, verifiziertes registriertes Eigentümer-Upload | +| DELETE | `/api/v1/media/marketplace/{listingId}/image` | `media:publish`-Maschinenkey | -Die vorhandene Route `GET /api/v1/profiles/{principalId}/image` bleibt unverändert. +Die URL-Muster sind **nur** nach Deployment der entsprechenden World-Version erreichbar. Die bestehende `GET /api/v1/profiles/{principalId}/image`-Route bleibt kompatibel. -Alle drei Media-Endpunkte akzeptieren `?size=64|128|256|512` als optionale maximale Pixelkante. Ohne `size` wird das Original (PNG/JPEG) oder die JPEG2000→PNG-Konvertierung ausgegeben; mit `size` wird nur verkleinert, nicht vergrößert. Antwort ist ein **echtes Bild** (`image/png` oder `image/jpeg`), **kein JSON**. Es gilt `Cache-Control: private, no-store`; keine Freigabe an geteilte CDNs. Eine optionale Größe garantiert nicht automatisch Zugriff. +`GET`-Bildantworten liefern `image/png`/`image/jpeg`, nicht JSON. Für die gewünschte Vorschaubildgröße kann `?size=64|128|256|512` verwendet werden. Die bestehende Media API limitiert Ausgangs-/Eingangsbilder (bis 2048 Pixel Kantenlänge, 8 MiB) und liefert ausschließlich aktuell autorisierte Referenzen. -### Beispiele +## 2. Upload (Portal-Backend oder eingeloggter Bewohner) ```http -GET /api/v1/media/groups/00000000-0000-0000-0000-000000000001/image?size=256 -Authorization: Bearer +POST /api/v1/media/uploads +Content-Type: application/json +Authorization: Bearer + +{ + "content_type": "image/png", + "data_base64": "", +} ``` +In gültigem JSON das letzte Komma weglassen. Unterstützt sind PNG/JPEG bis 4 MiB; der Server prüft Signatur und Abmessungen (max. 2048×2048), **transkodiert für OpenSim/Firestorm nach JPEG2000** und schreibt das Texture-Asset über den **bereits gestarteten ROBUST AssetService**. So bleibt das Bild inworld nutzbar. Antwort HTTP 201 enthält `asset_id`, `owner_id`, `content_type`, `image_url` und `visibility=private`. + +Ein Maschinen-Client verwendet statt Bearer den Header `X-NexVerse-Api-Key` mit explizit eingeräumtem `media:publish`; bei solchen Uploads ist im JSON zusätzlich die überprüfte lokale `owner_id` erforderlich. Dieser Key darf nur auf dem Portal-Backend stehen, nicht in Browser oder URLs. + +## 3. Aktivieren, Zuordnen, Veröffentlichen + +**Eigene Profil-/Gruppenbilder ändern:** + ```http -GET /api/v1/media/profiles/00000000-0000-0000-0000-000000000002/image?size=128 +PUT /api/v1/media/profiles/{principalId}/image +Authorization: Bearer +Content-Type: application/json + +{"asset_id":""} ``` +Entsprechende `PUT`-Routen gibt es für `/first-life` und `/groups/{groupId}/image`; Gruppenänderungen prüfen zusätzlich die tatsächlichen Gruppenrechte. + +**Eigenes Upload explizit öffentlich/privat schalten:** + ```http -GET /api/v1/media/profiles/00000000-0000-0000-0000-000000000002/first-life -Authorization: Bearer +PATCH /api/v1/media/assets/{assetId} +Authorization: Bearer +Content-Type: application/json + +{"public":true} ``` -**Die Beispiel-UUIDs sind Platzhalter**, keine gültigen Konten oder Gruppen. Öffentliche Profilbilder dürfen ohne Bearer gelesen werden; Gruppen- und First-Life-Bilder benötigen Credentials. +Eine private Media-Asset-ID darf nicht von anderen Einwohnern allein per UUID abgerufen werden. Umgekehrt macht ein Medien-Upload nicht pauschal andere Inventarobjekte öffentlich. -### Referenzen in Entitäts-JSON +**Marketplace-Bild veröffentlichen (NUR Backend):** -`GET /api/v1/groups/{groupId}` liefert künftig zusätzlich im `group`-Objekt `insignia_id` und die **relative** `image_url`. Beim Avatarprofil bleiben `profile_image_url` und `first_life_image` bestehen; neu: `media_image_url` und `first_life_image_url`. Ein nicht gesetztes Bild ergibt `null`. URLs sind nur Referenzen: Zugriffsrechte werden beim Abruf erneut geprüft. +```http +PUT /api/v1/media/marketplace/{listingId}/image +X-NexVerse-Api-Key: +Content-Type: application/json -Die Gruppe kann weiterhin eine nicht veröffentlichte Insignie besitzen. Der Media-Endpunkt benötigt daher ausdrücklich `groups:read`; **Browser ohne Resident-Session erhalten 401**, auch wenn die Gruppe im Viewer angezeigt wird. Das Portal muss autorisierte Anfragen über seine Backend-/Session-Infrastruktur leiten. Ein öffentlicher Bildzugriff wäre eine gesondert abzusichernde Produktentscheidung. +{"asset_id":"","owner_id":""} +``` -### Fehlercodes +Die World API validiert die Zuordnung des Bilds zum registrierten Owner. **Die eigentliche Listing-ID und deren Besitzer/Berechtigung muss das Marketplace-Backend autoritativ prüfen, bevor es den signierten Publisher-Key benutzt.** Der World-Server stellt absichtlich kein eigenes zweites Marketplace-Verkaufs-/Kaufverzeichnis bereit; stattdessen hält er die sichere **Publikationsbindung Listing → Bild** in einer separaten Tabelle. `DELETE` entfernt sie wieder und der öffentliche URL-Abruf liefert 404. -- 200 Bilddaten; 400 ungültige Größe. -- 401/403 nicht authentifiziert bzw. erforderlicher Scope fehlt. -- 404 ungültige Entität, nicht freigegebene oder fehlende Bildreferenz. -- 405 nur GET erlaubt; 413 Bilddaten bzw. Dimensionen überschreiten Grenzwerte. -- 415 Bildtyp/Bilddaten nicht dekodierbar; 503 Profil-, Gruppen- oder AssetService nicht erreichbar. +## 4. Persistenz & Privatsphäre -### Speicher-/Sicherheitsarchitektur +Zwei neue Tabellen im bestehenden ROBUST-MariaDB-Schema werden automatisch angelegt: -- Referenzauflösung ausschließlich über `GroupsService.GetGroupRecord(...).GroupPicture` bzw. `IProfilesData.GetAvatarProperties(...).ImageId/FirstLifeImageId`, **niemals** aus URL-Asset-ID, Browser-Headern oder nicht verifizierten Clientparametern. -- Derselbe von ROBUST registrierte `AssetServiceConnector.GetLocalService(...)` wie die bestehende World API; **kein neuer AssetService, keine Datenbank und keine Asset-Kopie**. -- Nur bildfähige Assettypen; maximal 8 MiB vor der Decodierung; gerenderte maximale Kante 2048 Pixel. JPEG2000-Konvertierung nutzt den OpenJPEG-Dekoder. -- First-Life-Bilder sind selbst bei öffentlichem Avatarprofil nur für Owner/Admin auslieferbar. Keine Secrets in Querystrings. Keine Bearer/API-Keys an fremde Bild-CDNs weitergeben. -- Kein `GET /api/v1/media/assets/{assetId}`: Eine Asset-UUID ist **kein** Leseberechtigungsnachweis. Marketplace, Inventar und freie Asset-IDs bleiben für eine später explizit geprüfte Autorisierung/Veröffentlichung zurückgestellt. +- `ogl_media_uploads`: Texture-UUID, Avatar-Eigentümer, Original-MIME, Sichtbarkeit, Erstellungszeit +- `ogl_media_marketplace`: Listing-ID, zugeordneter Upload, Eigentümer und Aktualisierungszeit (FK für nur zuvor registrierte Uploads) -### Deployment-/Akzeptanzgrenzen +`[NexVerseWorldApi] EnableManagedMedia = true` (Standard bei MariaDB). Ist MariaDB oder der bereits aktive AssetService nicht verfügbar, verweigern die schreibenden Media-Endpunkte ihren Dienst mit 503; **World-Login und ältere Bildrouten bleiben nutzbar**. MariaDB-DB-Benutzer benötigt CREATE TABLE/SELECT/INSERT/UPDATE/DELETE. Für andere Datenbankanbieter gibt es keinen stillen SQLite-Fallback. -Funktioniert nur, wenn World API und die bereits konfigurierten `UserProfilesService`-/`NexGroups`-Module sowie ROBUST AssetService bereit sind. Gruppenbilder benötigen den eingeschalteten NexGroups-Dienst. Kompatibilitäts- und Sicherheitsregressionen werden im GitHub-Actions-Workflow ausgeführt; danach Bildabrufe, fehlende Assets, Fehlerfälle und Berechtigungswechsel im Staging-Portal/Firestorm verifizieren. +`media:publish` ist **maschinenkey-only**; es gehört nicht zu den automatisch zugewiesenen Einwohner-/Rollenrechten. Alle Browser- und Besitzerrechte werden bei jedem Request erneut geprüft. Gruppen- und First-Life-Bilder sind niemals allein wegen ihrer UUID öffentlich. Private Bilder werden nicht in öffentlichen CDN-Caches geteilt (`Cache-Control: private, no-store`). Die AssetService-Daten bleiben unverändert; **bestehende beliebige Texture-UUIDs können nicht unkontrolliert publiziert werden**. -**Nicht implementiert in Phase 1:** Asset-Rohdownloads, Marketplace-Produktbilder, Upload neuer Bilder, Public-Gruppenbilder ohne Authentifizierung, persistenter Thumbnail-Cache oder CDN-Publication. +Für JPEG2000-Encoding/Decoding muss die OpenJPEG-/Grafiklaufzeit auf ROBUST vorhanden sein. Ein fehlender nativer Encoder soll einen klaren 503 auslösen; kein korruptes PNG darf als OpenSim-Texture-Asset gespeichert werden. + +## 5. Stadtportal-Arbeitsauftrag und Abnahme + +1. Das Portal-Backend nutzt Einwohner-OAuth/Bearer für persönliche Bilder, einen dedizierten `media:publish`-Maschinenkey ausschließlich für autorisierte Marketplace-Uploads/Bildbindungen. Die **Marketplace-Konto-/Listing-Owner-Prüfung passiert im Portal**, bevor dieser privilegierte Key verwendet wird. +2. Hochladen als PNG/JPEG; neue `asset_id` aus 201 übernehmen. Profilsichtbarkeit respektieren. Gruppen- und Profil-JSON führen bereits `image_url` und `media_image_url`. +3. Listen-/Kachelübersichten nutzen die Media-URLs; Gruppendarstellung braucht `groups:read` und einen authentifizierten Kontext. **Keine geheimen Bearer-Tokens in img-src-Queryparametern**. +4. Einen frisch angelegten Testbewohner verwenden: Upload → Profil- und Gruppenbindung → Firestorm-Anzeige → GET PNG → private/public-Umschaltung. +5. Marketplace: eigenen Test-Listing-Eigentümer verifizieren → mit Maschinenkey hochladen/veröffentlichen → anonym GET 200 → DELETE → GET 404. URL-Manipulation, fremde Asset-UUIDs, falscher Owner, fremdes Inventaritem und fehlende Scopes müssen abgelehnt werden. +6. Nachträgliche Rechte-/Sichtbarkeitsänderungen, fehlende Assets und große/dekodierfehlerhafte Bilder testen. Backup/Restore der beiden Tabellen vorbereiten. + +**Die GitHub-CI ersetzt diese Realitätsabnahme nicht. Kein produktives Aktivieren, bevor die End-to-End-Prüfungen erfolgreich sind.** diff --git a/tools/ci/NexGroupsHttpRegression/Program.cs b/tools/ci/NexGroupsHttpRegression/Program.cs index 57f646af..8162353a 100644 --- a/tools/ci/NexGroupsHttpRegression/Program.cs +++ b/tools/ci/NexGroupsHttpRegression/Program.cs @@ -103,16 +103,32 @@ internal static class Program private static SimpleStreamMethod MediaRoute( GroupsService groups, UserAccountService users, HmacNexAccessTokenService tokens, INexApiKeyStore keys, - IAssetService assetService) + IAssetService assetService, string connection, UUID assetId, UUID ownerId) { Assembly assembly = Assembly.Load("NexVerse.Server.Api"); Type authType = assembly.GetType("NexVerse.Server.Api.NexApiAuthenticator", true); Type mediaType = assembly.GetType("NexVerse.Server.Api.NexMediaApi", true); + Type catalogType = assembly.GetType("NexVerse.Server.Api.NexMediaCatalogStore", true); + Type managedType = assembly.GetType("NexVerse.Server.Api.NexManagedMediaApi", true); object auth = Construct(authType, users, new NexAuthorizationService(), tokens, null, keys, 200); object api = Construct(mediaType, users, null, groups, new Func(() => assetService), auth); - MethodInfo handle = mediaType.GetMethod("Handle", BindingFlags.Instance | BindingFlags.Public); + object catalog = Construct(catalogType, connection); + catalogType.GetMethod("RecordUpload", + BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(catalog, new object[] { assetId, ownerId, "image/png" }); + var renderer = (Action)Delegate.CreateDelegate( + typeof(Action), api, + mediaType.GetMethod("ServeLinkedImage", + BindingFlags.Instance | BindingFlags.NonPublic)!); + object managed = Construct(managedType, auth, users, null, null, groups, + new Func(() => assetService), catalog, renderer); + mediaType.GetMethod("ConfigureManaged", + BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(api, new[] { managed }); + MethodInfo handle = mediaType.GetMethod("Handle", + BindingFlags.Instance | BindingFlags.Public); Check(handle != null, "NexMediaApi.Handle missing"); return (SimpleStreamMethod)Delegate.CreateDelegate( typeof(SimpleStreamMethod), api, handle); @@ -184,6 +200,8 @@ internal static class Program tokens.Issue(account.PrincipalID.ToString(), scopes, account.NexVerseStateChanged); string ownerToken = Jwt(owner, NexScopes.GroupsRead, NexScopes.GroupsManage); + string ownerMediaToken = Jwt(owner, NexScopes.GroupsRead, NexScopes.GroupsManage, + NexScopes.ProfileRead, NexScopes.ProfileWrite); string memberToken = Jwt(member, NexScopes.GroupsRead, NexScopes.GroupsManage); string strangerToken = Jwt(stranger, NexScopes.GroupsRead, NexScopes.GroupsManage); string inviteeReadToken = Jwt(invitee, NexScopes.GroupsRead); @@ -214,6 +232,8 @@ internal static class Program new[] { NexScopes.GroupsRead, NexScopes.EconomyRead }); var groupsOnlyKey = keyStore.Create("Group Land Service", new[] { NexScopes.GroupsRead }); + var publisherKey = keyStore.Create("Media Publisher", + new[] { NexScopes.MediaPublish }); var handler = Route(groups, users, tokens, () => activeEconomy, keyStore); UUID insignia = UUID.Random(); IAssetService mediaAssetService = DispatchProxy.Create(); @@ -225,7 +245,8 @@ internal static class Program "iVBORw0KGgoAAAANSUhEUgAAABAAAAAMCAIAAADkharW" + "AAAAF0lEQVR4nGMUMQpgIAUwkaR6VMMI0gAAdQsArnr0MVEAAAAASUVORK5CYII=") }; - var mediaHandler = MediaRoute(groups, users, tokens, keyStore, mediaAssetService); + var mediaHandler = MediaRoute(groups, users, tokens, keyStore, + mediaAssetService, connection, insignia, owner.PrincipalID); int port = FindPort(); server = new BaseHttpServer((uint)port) { ListenIPAddress = IPAddress.Loopback }; server.AddSimpleStreamHandler( @@ -289,8 +310,45 @@ internal static class Program await Verify(http, mediaPath, narrowToken, HttpStatusCode.Forbidden, "error"); await Verify(http, mediaPath + "?size=999", ownerToken, HttpStatusCode.BadRequest, "error"); - await Verify(http, "/api/v1/media/assets/" + insignia, + await Verify(http, "/api/v1/media/assets/" + UUID.Random(), ownerToken, HttpStatusCode.NotFound, "error"); + await Verify(http, "/api/v1/media/assets/" + insignia, + null, HttpStatusCode.Unauthorized, "error"); + await Verify(http, "/api/v1/media/assets/" + insignia, + ownerMediaToken, HttpStatusCode.OK); + await Verify(http, "/api/v1/media/assets/" + insignia, + ownerMediaToken, HttpStatusCode.OK, "visibility", + HttpMethod.Patch, "{\"public\":true}"); + await Verify(http, "/api/v1/media/assets/" + insignia, + null, HttpStatusCode.OK); + + UUID listingImage = UUID.Random(); + string listingUrl = "/api/v1/media/marketplace/" + listingImage + "/image"; + using (var pub = new HttpRequestMessage(HttpMethod.Put, listingUrl)) + { + pub.Headers.TryAddWithoutValidation("X-NexVerse-Api-Key", publisherKey.ApiKey); + pub.Content = new StringContent(JsonSerializer.Serialize(new { + asset_id = insignia.ToString(), owner_id = owner.PrincipalID.ToString() + }), Encoding.UTF8, "application/json"); + using var published = await http.SendAsync(pub); + Check(published.StatusCode == HttpStatusCode.OK, + "marketplace publisher rejected binding: " + + await published.Content.ReadAsStringAsync()); + } + await Verify(http, listingUrl, null, HttpStatusCode.OK); + await Verify(http, listingUrl, ownerMediaToken, HttpStatusCode.Forbidden, + "error", HttpMethod.Delete); + using (var del = new HttpRequestMessage(HttpMethod.Delete, listingUrl)) + { + del.Headers.TryAddWithoutValidation("X-NexVerse-Api-Key", publisherKey.ApiKey); + using var unpublished = await http.SendAsync(del); + Check(unpublished.StatusCode == HttpStatusCode.OK, + "marketplace unpublish failed"); + } + await Verify(http, listingUrl, null, HttpStatusCode.NotFound, "error"); + await Verify(http, "/api/v1/media/assets/" + insignia, + ownerMediaToken, HttpStatusCode.OK, "visibility", + HttpMethod.Patch, "{\"public\":false}"); using (var mediaRequest = new HttpRequestMessage(HttpMethod.Get, mediaPath)) { mediaRequest.Headers.Authorization = diff --git a/tools/ci/verify_media_api.py b/tools/ci/verify_media_api.py index 3a50908b..ce166abc 100644 --- a/tools/ci/verify_media_api.py +++ b/tools/ci/verify_media_api.py @@ -36,8 +36,44 @@ for marker in ( ): assert marker in media, f"Media API missing safety constraint: {marker}" -assert '"/api/v1/media/assets"' not in connector -assert '"/api/v1/media/assets' not in openapi +# /media/assets/{assetId} is now intentionally available ONLY to uploads +# recorded in the authoritative MariaDB publication catalog. +assert '"/api/v1/media/assets/{assetId}"' in openapi +managed = Path("NexVerse/Server/Api/NexManagedMediaApi.cs").read_text() +store = Path("NexVerse/Server/Api/NexMediaCatalogStore.cs").read_text() +keys = Path("NexVerse/Core/Security/NexApiKeyStore.cs").read_text() +security = Path("NexVerse/Core/Security/NexSecurity.cs").read_text() +for route in ( + "/api/v1/media/uploads", + "/api/v1/media/assets/{assetId}", + "/api/v1/media/inventory/{itemId}/image", + "/api/v1/media/marketplace/{listingId}/image", +): + assert route in openapi, f"missing managed route: {route}" +for marker in ( + 'm_Catalog.FindUpload(assetId)', + 'item.Owner != user.PrincipalID', + 'm_Auth.TryAuthenticate(request, NexScopes.MediaPublish', + 'principal.Subject.StartsWith("api-key:"', + 'm_Catalog.PublishListing(', + 'm_Catalog.UnpublishListing(', + 'm_Groups.UpdateGroup(', + 'm_Profiles.UpdateAvatarProperties(', + 'OpenJPEG.EncodeFromImage(', + 'AssetType.Texture', + 'MaxUploadBytes = 4 * 1024 * 1024', + 'record.FounderID != user.PrincipalID', +): + assert marker in managed, f"missing managed-media ownership/codec validation: {marker}" +assert 'CREATE TABLE IF NOT EXISTS ogl_media_uploads' in store +assert 'CREATE TABLE IF NOT EXISTS ogl_media_marketplace' in store +assert 'FOREIGN KEY(asset_id)' in store +assert 'NexScopes.MediaPublish' in keys +assert 'public const string MediaPublish' in security +role_scopes = security.split('private static readonly HashSet s_AssignableScopes', 1)[1] +assert 'NexScopes.MediaPublish' not in role_scopes +assert 'ConfigureManaged(managedMedia)' in connector +assert 'new NexMediaCatalogStore(databaseConnectionString)' in connector assert '"/api/v1/media"' in connector assert 'apiGate.Wrap(mediaApi.Handle)' in connector assert 'AssetServiceConnector.GetLocalService(config, "AssetService")' in connector