Files
Chronos/src/Titano.Server/Api/UserEndpoints.cs
T
Claude c78747053e 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
2026-10-02 11:32:19 +00:00

158 lines
8.6 KiB
C#

using System.Globalization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Security;
namespace Titano.Server.Api;
/// <summary><c>/api/v1/users</c> (admin): accounts, roles, quotas, render-node right, temporary passwords.</summary>
public static class UserEndpoints
{
private const int MaxDisplayName = 100;
public static void Map(RouteGroupBuilder api)
{
var users = api.MapGroup("/users").Requires(Permissions.ManageUsers);
users.MapGet("", ListAsync);
users.MapPost("", CreateAsync);
users.MapGet("/{id:guid}", GetAsync);
users.MapPatch("/{id:guid}", UpdateAsync);
users.MapDelete("/{id:guid}", DeleteAsync);
users.MapPost("/{id:guid}/reset-password", ResetPasswordAsync);
}
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, TimeProvider time)
{
var ct = context.RequestAborted;
var users = await db.Users.ListAsync(ct);
var latest = await db.Tokens.LatestByUserAsync(ct);
var uploads = await db.Uploads.CommittedCountByUserAsync(time.GetUtcNow().AddDays(-30), ct);
var rows = users.Select(u =>
{
var token = latest.GetValueOrDefault(u.Id);
return new UserSummaryDto(Dto.User(u), token?.LastUsed ?? u.LastLogin, token?.ClientName, uploads.GetValueOrDefault(u.Id));
}).ToList();
return Results.Json(rows, ProtocolJson.Default.ListUserSummaryDto);
}
private static async Task<IResult> GetAsync(HttpContext context, Guid id, TitanoDatabase db) =>
await db.Users.GetAsync(id, context.RequestAborted) is { } user
? Results.Json(Dto.User(user), ProtocolJson.Default.UserDto)
: ApiErrors.NotFound(context, "user");
private static async Task<IResult> CreateAsync(HttpContext context, Caller caller, CreateUserRequest request, TitanoDatabase db, AuditLog audit, TimeProvider time)
{
var username = request.Username?.Trim();
if (!Accounts.IsValidUsername(username)) return ApiErrors.BadRequest(context, "invalid_username");
if (!Accounts.TryParseRole(request.Role, out var role)) return ApiErrors.BadRequest(context, "invalid_role");
if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes");
var password = string.IsNullOrEmpty(request.Password) ? TemporaryPassword.Generate() : request.Password;
if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context);
var user = new User
{
Id = Guid.CreateVersion7(),
Username = username!,
DisplayName = Clean(request.DisplayName),
PasswordHash = PasswordHasher.Hash(password),
Role = role,
Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode),
QuotaBytes = request.QuotaBytes,
MustChangePassword = true,
Created = time.GetUtcNow(),
};
try
{
await db.Users.CreateAsync(user, context.RequestAborted);
}
catch (DatabaseException ex) when (ex.IsUniqueViolation)
{
return ApiErrors.Conflict(context, "username_taken");
}
await audit.WriteAsync(caller, context, "user_created", "user", user.Id.ToString(), $"{user.Username} · {Dto.Role(role)}");
return Results.Json(new TemporaryPasswordResponse(Dto.User(user), password), ProtocolJson.Default.TemporaryPasswordResponse, statusCode: StatusCodes.Status201Created);
}
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, Guid id, UpdateUserRequest request, TitanoDatabase db, AuditLog audit)
{
var ct = context.RequestAborted;
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
var role = user.Role;
if (request.Role is not null && !Accounts.TryParseRole(request.Role, out role)) return ApiErrors.BadRequest(context, "invalid_role");
if (request.QuotaBytes < 0) return ApiErrors.BadRequest(context, "bad_request", "quotaBytes");
var updated = user with
{
DisplayName = request.DisplayName is null ? user.DisplayName : Clean(request.DisplayName),
Role = role,
Permissions = Accounts.PermissionsFor(role, request.AllowRenderNode ?? user.Permissions.HasFlag(Permissions.RenderNode)),
QuotaBytes = request.QuotaBytes ?? user.QuotaBytes,
Disabled = request.Disabled ?? user.Disabled,
};
var losesAdmin = IsActiveAdmin(user) && !IsActiveAdmin(updated);
if (losesAdmin && user.Id == caller.Id) return ApiErrors.Conflict(context, "self");
if (losesAdmin && !await HasOtherActiveAdminAsync(db, user.Id, ct)) return ApiErrors.Conflict(context, "last_admin");
await db.Users.UpdateAsync(updated, ct);
if (updated.Disabled && !user.Disabled) await db.Tokens.RevokeAllAsync(id, ct);
await audit.WriteAsync(caller, context, "user_updated", "user", id.ToString(), Changes(user, updated));
return Results.Json(Dto.User(updated), ProtocolJson.Default.UserDto);
}
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, Guid id, TitanoDatabase db, AuditLog audit)
{
var ct = context.RequestAborted;
if (id == caller.Id) return ApiErrors.Conflict(context, "self");
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
if (IsActiveAdmin(user) && !await HasOtherActiveAdminAsync(db, id, ct)) return ApiErrors.Conflict(context, "last_admin");
// Render jobs of the user's nodes go back to the queue before the nodes disappear with the account.
foreach (var node in (await db.RenderNodes.ListAsync(ct)).Where(n => n.UserId == id))
await db.Jobs.RequeueRunningAsync(node.Id.ToString(), ct);
var reassigned = await db.Sequences.ReassignOwnerAsync(id, caller.Id, ct);
await db.Users.DeleteAsync(id, ct);
await audit.WriteAsync(caller, context, "user_deleted", "user", id.ToString(),
$"{user.Username} · {reassigned.ToString(CultureInfo.InvariantCulture)}");
return Results.NoContent();
}
private static async Task<IResult> ResetPasswordAsync(HttpContext context, Caller caller, Guid id, ResetPasswordRequest? request, TitanoDatabase db, AuditLog audit)
{
var ct = context.RequestAborted;
if (await db.Users.GetAsync(id, ct) is not { } user) return ApiErrors.NotFound(context, "user");
var password = string.IsNullOrEmpty(request?.Password) ? TemporaryPassword.Generate() : request.Password;
if (!PasswordHasher.IsAcceptable(password)) return WeakPassword(context);
var updated = user with { PasswordHash = PasswordHasher.Hash(password), MustChangePassword = true };
await db.Users.UpdateAsync(updated, ct);
await db.Tokens.RevokeAllAsync(id, ct);
await audit.WriteAsync(caller, context, "password_reset", "user", id.ToString(), user.Username);
return Results.Json(new TemporaryPasswordResponse(Dto.User(updated), password), ProtocolJson.Default.TemporaryPasswordResponse);
}
private static bool IsActiveAdmin(User user) => user.Role == UserRole.Admin && !user.Disabled;
private static async Task<bool> HasOtherActiveAdminAsync(TitanoDatabase db, Guid except, CancellationToken ct) =>
(await db.Users.ListAsync(ct)).Any(u => u.Id != except && IsActiveAdmin(u));
private static IResult WeakPassword(HttpContext context) =>
ApiErrors.BadRequest(context, "weak_password", PasswordHasher.MinimumLength.ToString(CultureInfo.InvariantCulture), PasswordHasher.MinimumLength);
private static string? Clean(string? displayName)
{
var trimmed = displayName?.Trim();
return string.IsNullOrEmpty(trimmed) ? null : trimmed[..Math.Min(trimmed.Length, MaxDisplayName)];
}
/// <summary>Audit detail listing the fields an edit changed (never secrets).</summary>
private static string Changes(User before, User after)
{
var changes = new List<string>();
if (before.DisplayName != after.DisplayName) changes.Add("displayName");
if (before.Role != after.Role) changes.Add("role=" + Dto.Role(after.Role));
if (before.Permissions != after.Permissions) changes.Add("permissions");
if (before.QuotaBytes != after.QuotaBytes) changes.Add("quota=" + after.QuotaBytes.ToString(CultureInfo.InvariantCulture));
if (before.Disabled != after.Disabled) changes.Add(after.Disabled ? "disabled" : "enabled");
return string.Join(", ", changes);
}
}