diff --git a/addons/OGLStorageS3/OglS3ObjectMirror.cs b/addons/OGLStorageS3/OglS3ObjectMirror.cs new file mode 100644 index 00000000..d580610a --- /dev/null +++ b/addons/OGLStorageS3/OglS3ObjectMirror.cs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: MPL-2.0 +using System.Security.Cryptography; +using Amazon.Runtime; +using Amazon.S3; +using Amazon.S3.Model; + +namespace OpenGenesisLINK.Storage.S3; + +/// +/// Opt-in immutable content-addressed S3 mirror. FSAssets remains authoritative. +/// This component does not change asset metadata, delete objects or migrate assets. +/// +public sealed class OglS3ObjectMirror : IDisposable +{ + private readonly AmazonS3Client client; + private readonly string bucket; + + public OglS3ObjectMirror(Uri endpoint, string bucket, string accessKey, string secretKey) + { + if (endpoint == null || !endpoint.IsAbsoluteUri || + (endpoint.Scheme != Uri.UriSchemeHttps && endpoint.Scheme != Uri.UriSchemeHttp)) + throw new ArgumentException("An absolute S3 HTTP(S) endpoint is required.", nameof(endpoint)); + if (endpoint.Scheme == Uri.UriSchemeHttp && + !string.Equals(Environment.GetEnvironmentVariable("OGL_S3_ALLOW_PRIVATE_HTTP"), "true", + StringComparison.Ordinal)) + throw new InvalidOperationException("Plain HTTP requires explicit private-network test opt-in."); + if (string.IsNullOrWhiteSpace(bucket) || string.IsNullOrWhiteSpace(accessKey) || + string.IsNullOrWhiteSpace(secretKey)) + throw new ArgumentException("Bucket and credentials must be configured."); + this.bucket = bucket; + var config = new AmazonS3Config + { + ServiceURL = endpoint.ToString().TrimEnd('/'), + ForcePathStyle = true, + AuthenticationRegion = "garage", + Timeout = TimeSpan.FromSeconds(20), + MaxErrorRetry = 1 + }; + client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey), config); + } + + public static OglS3ObjectMirror FromEnvironment() + { + string? endpoint = Environment.GetEnvironmentVariable("OGL_S3_ENDPOINT"); + string? bucket = Environment.GetEnvironmentVariable("OGL_S3_BUCKET"); + string? key = Environment.GetEnvironmentVariable("OGL_S3_ACCESS_KEY"); + string? secret = Environment.GetEnvironmentVariable("OGL_S3_SECRET_KEY"); + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri)) + throw new InvalidOperationException("OGL_S3_ENDPOINT is missing or invalid."); + return new OglS3ObjectMirror(uri, bucket ?? "", key ?? "", secret ?? ""); + } + + private static string KeyFor(string hash) + { + if (hash.Length != 64 || !hash.All(Uri.IsHexDigit)) + throw new ArgumentException("Expected a SHA-256 hex digest.", nameof(hash)); + string lower = hash.ToLowerInvariant(); + return "sha256/" + lower[..2] + "/" + lower; + } + + public async Task MirrorAsync(byte[] payload, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(payload); + string hash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant(); + using var stream = new MemoryStream(payload, writable: false); + await client.PutObjectAsync(new PutObjectRequest + { + BucketName = bucket, + Key = KeyFor(hash), + InputStream = stream, + AutoCloseStream = false + }, cancellationToken).ConfigureAwait(false); + return hash; + } + + /// Returns null on missing objects; all other S3 failures propagate. + public async Task TryReadAsync(string hash, CancellationToken cancellationToken = default) + { + string key = KeyFor(hash); + GetObjectResponse response; + try + { + response = await client.GetObjectAsync(bucket, key, cancellationToken).ConfigureAwait(false); + } + catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) + { + return null; + } + using (response) + using (var memory = new MemoryStream()) + { + await response.ResponseStream.CopyToAsync(memory, cancellationToken).ConfigureAwait(false); + byte[] payload = memory.ToArray(); + string actual = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant(); + if (!string.Equals(actual, hash, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("S3 object digest mismatch."); + return payload; + } + } + + public void Dispose() => client.Dispose(); +}