feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events

- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens
  stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/
  SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate
  limit and lockout, role/permission metadata on every endpoint, audit log,
  first-run administrator bootstrap.
- Sequences with keyset paging, ETags and settings_version conflicts; sync
  manifest; frames, proxies, thumbnails and exports streamed with Range.
- Chunked resumable uploads with hash short-circuit, quota and disk checks,
  staging on the archive volume, SHA-256 verification and IArchiveIngest.
- Job engine host, jobs API, render nodes with heartbeat timeout and
  reassignment, WebSocket events, LAN discovery beacon, upload cleanup.
- Windows service host over advapi32 (--service, --install-service,
  --uninstall-service); fails fast without the archive module services.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 11:32:19 +00:00
1 parent 7353c17d7b
commit c78747053e
56 files changed
+4726 -108

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
using System.Collections.Concurrent;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Server.Storage;
namespace Titano.Server.Tests;
/// <summary>
/// Stand-in for the archive module's ingest: files staged uploads as <c>&lt;folder&gt;/originals/&lt;name&gt;</c>, one
/// sequence per session key, and records every request it received.
/// </summary>
public sealed class FakeArchiveIngest(TitanoDatabase db) : IArchiveIngest
{
private readonly ConcurrentDictionary<string, Guid> _sessions = new(StringComparer.Ordinal);
private readonly SemaphoreSlim _gate = new(1, 1);
public ConcurrentQueue<IngestRequest> Requests { get; } = new();
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
Requests.Enqueue(request);
await _gate.WaitAsync(cancellationToken);
try
{
var archive = (await db.Archives.GetAsync(request.ArchiveId, cancellationToken))!;
var sequence = await SequenceForAsync(request, archive, cancellationToken);
var existing = (await db.Frames.FindBySha256Async(request.Sha256, cancellationToken)).FirstOrDefault(f => f.SequenceId == sequence.Id);
if (existing is not null)
{
File.Delete(request.StagedPath);
return new IngestResult(sequence.Id, existing.Id, existing.Index, existing.RelativePath, Duplicate: true);
}
var index = sequence.FrameCount;
var relative = $"{sequence.Folder}/originals/{index:D4}_{request.OriginalFileName}";
var target = Path.Combine(archive.RootPath, relative);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
File.Move(request.StagedPath, target);
var frame = new Frame
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
Index = index,
RelativePath = relative,
FileName = Path.GetFileName(relative),
OriginalFileName = request.OriginalFileName,
Size = request.Size,
Sha256 = request.Sha256,
CapturedAt = request.ClientCapturedAt,
};
await db.Frames.InsertAsync(frame, cancellationToken);
await db.Sequences.RefreshStatsAsync(sequence.Id, cancellationToken);
return new IngestResult(sequence.Id, frame.Id, index, relative, Duplicate: false);
}
finally
{
_gate.Release();
}
}
private async Task<Sequence> SequenceForAsync(IngestRequest request, Archive archive, CancellationToken cancellationToken)
{
Sequence? sequence = null;
if (request.SequenceId is { } id) sequence = await db.Sequences.GetAsync(id, cancellationToken);
else if (request.SessionKey is { } key && _sessions.TryGetValue(key, out var known)) sequence = await db.Sequences.GetAsync(known, cancellationToken);
if (sequence is null)
{
sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = archive.Id, Folder = string.Empty, Title = request.NewSequenceTitle, OwnerUserId = request.UserId };
if (request.SessionKey is { } key) _sessions[key] = sequence.Id;
}
if (string.IsNullOrEmpty(sequence.Folder))
{
sequence = sequence with { Folder = $"2026/{sequence.Id:N}", UpdatedAt = DateTimeOffset.UtcNow };
await db.Sequences.UpsertAsync(sequence, cancellationToken);
}
return sequence;
}
}
/// <summary>Proxies at <c>&lt;folder&gt;/proxies/NNNN.jpg</c>; thumbnails as 64-byte slots of <c>&lt;folder&gt;/.titano/thumbs.pack</c>.</summary>
public sealed class FakeAssetLocator : IFrameAssetLocator
{
public const int ThumbnailSize = 64;
/// <summary>When set, every lookup answers this location (path traversal tests).</summary>
public AssetLocation? Override { get; set; }
public ValueTask<AssetLocation?> LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken)
{
if (Override is not null) return ValueTask.FromResult<AssetLocation?>(Override);
var folder = Path.Combine(archive.RootPath, sequence.Folder);
AssetLocation? location = asset == FrameAsset.Proxy
? new AssetLocation(Path.Combine(folder, "proxies", $"{frame.Index:D4}.jpg"), 0, -1, "image/jpeg")
: new AssetLocation(Path.Combine(folder, ".titano", "thumbs.pack"), (long)frame.Index * ThumbnailSize, ThumbnailSize, "image/jpeg");
if (!File.Exists(location.Path)) return ValueTask.FromResult<AssetLocation?>(null);
if (location.Length < 0) location = location with { Length = new FileInfo(location.Path).Length };
return ValueTask.FromResult<AssetLocation?>(location);
}
}
/// <summary>A clock tests move by hand (token expiry, heartbeat timeouts).</summary>
public sealed class ManualTimeProvider : TimeProvider
{
private long _ticks = DateTimeOffset.UtcNow.UtcTicks;
public override DateTimeOffset GetUtcNow() => new(Interlocked.Read(ref _ticks), TimeSpan.Zero);
public void Advance(TimeSpan by) => Interlocked.Add(ref _ticks, by.Ticks);
}
/// <summary>
/// A job handler that reports progress and then waits until <see cref="Release"/> (or cancellation), so tests can
/// observe running, paused and cancelled states.
/// </summary>
public sealed class BlockingJobHandler(JobKind kind) : IJobHandler
{
private TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
public JobKind Kind => kind;
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>When set, the next run fails with this message.</summary>
public string? FailWith { get; set; }
public void Release() => _release.TrySetResult();
public async Task RunAsync(JobContext context)
{
await context.ReportAsync(1, 4, "started");
Started.TrySetResult();
if (FailWith is { } message)
{
FailWith = null;
throw new InvalidOperationException(message);
}
for (var i = 2; i <= 3; i++)
{
await Task.Delay(50, context.Cancellation);
await context.ReportAsync(i, 4);
}
await _release.Task.WaitAsync(context.Cancellation);
_release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await context.ReportAsync(4, 4);
}
}
+93 -5
View File
@@ -1,17 +1,33 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Hosting;
using Titano.Server.Storage;
using Titano.Testing;
namespace Titano.Server.Tests;
/// <summary>In-process Kestrel on ephemeral ports with temporary archive/data folders (BRIEF §20.1).</summary>
/// <summary>
/// In-process Kestrel on ephemeral ports with temporary archive/data folders and a SQLite database (BRIEF §20.1).
/// The archive module is replaced by <see cref="FakeArchiveIngest"/> and <see cref="FakeAssetLocator"/>.
/// </summary>
public sealed class TestServer : IAsyncDisposable
{
public const string AdminPassword = "first-admin-pass";
public const string Password = "a-good-password-1";
private readonly WebApplication _app;
private readonly List<HttpClient> _clients = [];
private string _adminPassword = AdminPassword;
private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https)
{
@@ -19,16 +35,21 @@ public sealed class TestServer : IAsyncDisposable
Options = options;
HttpBase = http;
HttpsBase = https;
Client = new HttpClient { BaseAddress = http, Timeout = TimeSpan.FromSeconds(30) };
Client = NewClient();
}
public ServerOptions Options { get; }
public Uri HttpBase { get; }
public Uri? HttpsBase { get; }
/// <summary>An anonymous client.</summary>
public HttpClient Client { get; }
public IServiceProvider Services => _app.Services;
public static async Task<TestServer> StartAsync(TestContext context, Action<ServerOptions>? configure = null)
public TitanoDatabase Database => Services.GetRequiredService<TitanoDatabase>();
public static async Task<TestServer> StartAsync(TestContext context, Action<ServerOptions>? configure = null, Action<IServiceCollection>? services = null)
{
var root = context.CreateTempDirectory("server");
var options = new ServerOptions
@@ -39,10 +60,21 @@ public sealed class TestServer : IAsyncDisposable
HttpsPort = 0,
TlsMode = TlsMode.Auto,
Database = DatabaseKind.Sqlite,
Discovery = false,
Workers = 2,
AdminUser = "admin",
AdminPassword = AdminPassword,
};
Directory.CreateDirectory(options.ArchivePath);
configure?.Invoke(options);
var app = ServerHost.Build(options, []);
var app = ServerHost.Build(options, [], s =>
{
s.AddSingleton<FakeArchiveIngest>();
s.TryAddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<FakeArchiveIngest>());
s.AddSingleton<FakeAssetLocator>();
s.TryAddSingleton<IFrameAssetLocator>(sp => sp.GetRequiredService<FakeAssetLocator>());
services?.Invoke(s);
});
await app.StartAsync(context.Cancellation);
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses
.Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal)))
@@ -52,9 +84,65 @@ public sealed class TestServer : IAsyncDisposable
return new TestServer(app, options, http, https);
}
/// <summary>A plain HTTP client (owned by the server, disposed with it).</summary>
public HttpClient NewClient(string? token = null)
{
var client = new HttpClient { BaseAddress = HttpBase, Timeout = TimeSpan.FromSeconds(60) };
if (token is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
_clients.Add(client);
return client;
}
/// <summary>An HTTPS client with a cookie jar that trusts the self-signed certificate (admin panel sessions).</summary>
public HttpClient NewCookieClient(CookieContainer cookies)
{
var handler = new HttpClientHandler { CookieContainer = cookies, ServerCertificateCustomValidationCallback = (_, _, _, _) => true };
var client = new HttpClient(handler) { BaseAddress = HttpsBase, Timeout = TimeSpan.FromSeconds(60) };
_clients.Add(client);
return client;
}
public async Task<LoginResponse> LoginAsync(string username, string password, string clientName = "tests")
{
using var response = await Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, password, clientName), ProtocolJson.Default.LoginRequest);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Login of {username} failed: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
return (await response.Content.ReadFromJsonAsync(ProtocolJson.Default.LoginResponse))!;
}
/// <summary>The bootstrap administrator, signed in; its first sign-in replaces the bootstrap password with <see cref="Password"/>.</summary>
public async Task<HttpClient> AdminAsync()
{
var login = await LoginAsync("admin", _adminPassword);
var client = NewClient(login.Token);
if (login.MustChangePassword)
{
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(_adminPassword, Password),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
_adminPassword = Password;
}
return client;
}
/// <summary>Creates a user (through the admin API) who has set <see cref="Password"/>, and returns a client signed in as them.</summary>
public async Task<(HttpClient Client, UserDto User, string Token)> UserAsync(string username, string role, long quotaBytes = 0, bool renderNode = false)
{
var admin = await AdminAsync();
using var created = await admin.PostAsJsonAsync("/api/v1/users", new CreateUserRequest(username, null, role, quotaBytes, null, renderNode),
ProtocolJson.Default.CreateUserRequest);
created.EnsureSuccessStatusCode();
var temporary = (await created.Content.ReadFromJsonAsync(ProtocolJson.Default.TemporaryPasswordResponse))!;
var first = await LoginAsync(username, temporary.TemporaryPassword);
var client = NewClient(first.Token);
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(temporary.TemporaryPassword, Password),
ProtocolJson.Default.ChangePasswordRequest);
changed.EnsureSuccessStatusCode();
return (client, temporary.User, first.Token!);
}
public async ValueTask DisposeAsync()
{
Client.Dispose();
foreach (var client in _clients) client.Dispose();
await _app.StopAsync();
await _app.DisposeAsync();
}