CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
228 lines
14 KiB
C#
228 lines
14 KiB
C#
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Chronos.Protocol;
|
|
using Chronos.Testing;
|
|
|
|
namespace Chronos.Server.Tests.Security;
|
|
|
|
[Category("server")]
|
|
public sealed class AuthTests(TestContext context)
|
|
{
|
|
[Test]
|
|
public async Task BootstrapAdminMustChangePasswordBeforeAnythingElse()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var login = await server.LoginAsync("admin", TestServer.AdminPassword);
|
|
Assert.True(login.MustChangePassword);
|
|
Assert.Equal("admin", login.User.Role);
|
|
var client = server.NewClient(login.Token);
|
|
|
|
using (var blocked = await client.GetAsync("/api/v1/users")) await blocked.ExpectErrorAsync(HttpStatusCode.Forbidden, "password_change_required");
|
|
using (var me = await client.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
|
|
using (var weak = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(TestServer.AdminPassword, "short"),
|
|
ProtocolJson.Default.ChangePasswordRequest))
|
|
await weak.ExpectErrorAsync(HttpStatusCode.BadRequest, "weak_password");
|
|
using (var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(TestServer.AdminPassword, TestServer.Password),
|
|
ProtocolJson.Default.ChangePasswordRequest))
|
|
await changed.ExpectAsync(HttpStatusCode.NoContent);
|
|
using var users = await client.GetAsync("/api/v1/users");
|
|
await users.ExpectAsync(HttpStatusCode.OK);
|
|
Assert.Count(1, await users.ReadAsync(ProtocolJson.Default.ListUserSummaryDto));
|
|
}
|
|
|
|
[Test]
|
|
public async Task BootstrapWithoutPasswordWritesItToAFileNeverToTheLog()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null);
|
|
var file = Path.Combine(server.Options.DataPath, "initial-admin-password.txt");
|
|
Assert.FileExists(file);
|
|
var password = File.ReadAllText(file).Trim();
|
|
if (!OperatingSystem.IsWindows()) Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(file));
|
|
var login = await server.LoginAsync("admin", password);
|
|
Assert.True(login.MustChangePassword);
|
|
foreach (var log in Directory.EnumerateFiles(server.Options.LogPath))
|
|
{
|
|
using var reader = new StreamReader(new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
|
|
Assert.False((await reader.ReadToEndAsync()).Contains(password, StringComparison.Ordinal), "the password reached the log");
|
|
}
|
|
|
|
var client = server.NewClient(login.Token);
|
|
using var changed = await client.PostAsJsonAsync("/api/v1/auth/password", new ChangePasswordRequest(password, TestServer.Password),
|
|
ProtocolJson.Default.ChangePasswordRequest);
|
|
await changed.ExpectAsync(HttpStatusCode.NoContent);
|
|
Assert.FileMissing(file);
|
|
}
|
|
|
|
[Test]
|
|
public async Task WrongPasswordAndUnknownUserFailAlike()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
using var wrong = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", "not-the-password", "tests"), ProtocolJson.Default.LoginRequest);
|
|
var a = await wrong.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
|
using var unknown = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("nobody", "not-the-password", "tests"), ProtocolJson.Default.LoginRequest);
|
|
var b = await unknown.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
|
Assert.Equal(a.Message, b.Message);
|
|
}
|
|
|
|
[Test]
|
|
public async Task RepeatedFailuresLockTheAccountNameEvenWithTheRightPassword()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, o =>
|
|
{
|
|
o.LoginAttemptsPerMinute = 100;
|
|
o.LockoutThreshold = 3;
|
|
});
|
|
for (var i = 0; i < 3; i++)
|
|
{
|
|
using var failed = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest);
|
|
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
|
}
|
|
using var locked = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.AdminPassword, "tests"), ProtocolJson.Default.LoginRequest);
|
|
await locked.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "account_locked");
|
|
Assert.True(locked.Headers.RetryAfter?.Delta > TimeSpan.Zero);
|
|
|
|
for (var i = 0; i < 3; i++)
|
|
(await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("ghost", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest)).Dispose();
|
|
using var ghost = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("ghost", "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest);
|
|
await ghost.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "account_locked");
|
|
}
|
|
|
|
[Test]
|
|
public async Task SignInsAreRateLimitedPerAddress()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context, o => o.LoginAttemptsPerMinute = 5);
|
|
for (var i = 0; i < 5; i++)
|
|
(await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("user" + i, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest)).Dispose();
|
|
using var limited = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.AdminPassword, "tests"), ProtocolJson.Default.LoginRequest);
|
|
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
|
|
}
|
|
|
|
[Test]
|
|
public async Task LogoutRevokesTheToken()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var admin = await server.AdminAsync();
|
|
using (var me = await admin.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
|
|
using (var logout = await admin.PostAsync("/api/v1/auth/logout", null)) await logout.ExpectAsync(HttpStatusCode.NoContent);
|
|
using var after = await admin.GetAsync("/api/v1/auth/me");
|
|
await after.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
Assert.Equal("Bearer", after.Headers.WwwAuthenticate.Single().Scheme);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TokensExpireUnlessUsedWithinTheirLifetime()
|
|
{
|
|
var clock = new ManualTimeProvider();
|
|
await using var server = await TestServer.StartAsync(context, o => o.TokenLifetimeDays = 30, s => s.AddSingleton<TimeProvider>(clock));
|
|
var admin = await server.AdminAsync();
|
|
clock.Advance(TimeSpan.FromDays(20));
|
|
using (var used = await admin.GetAsync("/api/v1/auth/me")) await used.ExpectAsync(HttpStatusCode.OK);
|
|
clock.Advance(TimeSpan.FromDays(20));
|
|
using (var slid = await admin.GetAsync("/api/v1/auth/me")) await slid.ExpectAsync(HttpStatusCode.OK);
|
|
clock.Advance(TimeSpan.FromDays(31));
|
|
using var expired = await admin.GetAsync("/api/v1/auth/me");
|
|
await expired.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
}
|
|
|
|
[Test]
|
|
public async Task TokensAreStoredOnlyAsHashes()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var login = await server.LoginAsync("admin", TestServer.AdminPassword);
|
|
await using var session = await server.Database.Database.OpenAsync(context.Cancellation);
|
|
var hashes = new List<string>();
|
|
await foreach (var row in session.QueryAsync("SELECT token_hash FROM tokens", [], context.Cancellation)) hashes.Add(row.GetString(0));
|
|
Assert.Contains(Chronos.Server.Security.TokenService.HashOf(login.Token!), hashes);
|
|
Assert.DoesNotContain(login.Token!, hashes);
|
|
}
|
|
|
|
[Test]
|
|
public async Task DisablingAUserEndsTheirSessions()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var (editor, user, _) = await server.UserAsync("giulia", "editor");
|
|
var admin = await server.AdminAsync();
|
|
using (var disable = await admin.PatchAsJsonAsync($"/api/v1/users/{user.Id}", new UpdateUserRequest(null, null, null, true, null), ProtocolJson.Default.UpdateUserRequest))
|
|
await disable.ExpectAsync(HttpStatusCode.OK);
|
|
using var me = await editor.GetAsync("/api/v1/auth/me");
|
|
await me.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
using var login = await server.Client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("giulia", TestServer.Password, "tests"), ProtocolJson.Default.LoginRequest);
|
|
await login.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
|
}
|
|
|
|
[Test]
|
|
public async Task PermissionsSeparateMissingSignInFromMissingRights()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
using (var anonymous = await server.Client.GetAsync("/api/v1/users")) await anonymous.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
using (var anonymousSequences = await server.Client.GetAsync("/api/v1/sequences")) await anonymousSequences.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
|
|
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
|
|
using (var users = await viewer.GetAsync("/api/v1/users")) await users.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
|
using (var sequences = await viewer.GetAsync("/api/v1/sequences")) await sequences.ExpectAsync(HttpStatusCode.OK);
|
|
using (var upload = await viewer.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "a.jpg", 10, new string('a', 64), null, null),
|
|
ProtocolJson.Default.StartUploadRequest))
|
|
await upload.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
|
using (var settings = await viewer.GetAsync("/api/v1/server/settings")) await settings.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
|
|
|
var (uploader, _, _) = await server.UserAsync("roof-cam", "uploader");
|
|
using (var start = await uploader.PostAsJsonAsync("/api/v1/uploads", new StartUploadRequest(null, "a.jpg", 10, new string('a', 64), null, null),
|
|
ProtocolJson.Default.StartUploadRequest))
|
|
await start.ExpectAsync(HttpStatusCode.Created);
|
|
using var edit = await uploader.PatchAsJsonAsync($"/api/v1/sequences/{Guid.NewGuid()}", new UpdateSequenceRequest("x", null, null, null, null, null),
|
|
ProtocolJson.Default.UpdateSequenceRequest);
|
|
await edit.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
|
}
|
|
|
|
[Test]
|
|
public async Task CookieSessionsNeedTheCsrfHeaderForChanges()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
await server.AdminAsync();
|
|
var cookies = new CookieContainer();
|
|
var browser = server.NewCookieClient(cookies);
|
|
using (var login = await browser.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
|
|
ProtocolJson.Default.LoginRequest))
|
|
{
|
|
await login.ExpectAsync(HttpStatusCode.OK);
|
|
Assert.Null((await login.ReadAsync(ProtocolJson.Default.LoginResponse)).Token);
|
|
var session = login.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("chronos_session=", StringComparison.Ordinal));
|
|
Assert.Contains("httponly", session.ToLowerInvariant());
|
|
Assert.Contains("secure", session.ToLowerInvariant());
|
|
Assert.Contains("samesite=strict", session.ToLowerInvariant());
|
|
}
|
|
using (var me = await browser.GetAsync("/api/v1/auth/me")) await me.ExpectAsync(HttpStatusCode.OK);
|
|
using (var forged = await browser.PostAsJsonAsync("/api/v1/sequences", new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest))
|
|
await forged.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
|
|
using (var wrong = new HttpRequestMessage(HttpMethod.Post, "/api/v1/sequences") { Content = JsonContent.Create(new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest) })
|
|
{
|
|
wrong.Headers.Add("X-CSRF-Token", "not-the-token");
|
|
using var response = await browser.SendAsync(wrong);
|
|
await response.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
|
|
}
|
|
var csrf = cookies.GetCookies(server.HttpsBase!)["chronos_csrf"]!.Value;
|
|
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/sequences") { Content = JsonContent.Create(new CreateSequenceRequest("x", null), ProtocolJson.Default.CreateSequenceRequest) };
|
|
request.Headers.Add("X-CSRF-Token", csrf);
|
|
using var created = await browser.SendAsync(request);
|
|
await created.ExpectAsync(HttpStatusCode.Created);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ErrorsHaveTheApiShapeAndHeader()
|
|
{
|
|
await using var server = await TestServer.StartAsync(context);
|
|
var admin = await server.AdminAsync();
|
|
using (var missing = await server.Client.GetAsync("/api/v1/nothing-here")) await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
|
using (var badJson = await admin.PostAsync("/api/v1/sequences", new StringContent("{ not json", MediaTypeHeaderValue.Parse("application/json"))))
|
|
await badJson.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request");
|
|
using (var badGuid = await admin.GetAsync($"/api/v1/sequences/{Guid.NewGuid()}")) await badGuid.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found");
|
|
using var italian = new HttpRequestMessage(HttpMethod.Get, "/api/v1/users");
|
|
italian.Headers.AcceptLanguage.ParseAdd("it-IT");
|
|
using var response = await server.Client.SendAsync(italian);
|
|
var error = await response.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
|
|
Assert.Equal("Accedi per continuare.", error.Message);
|
|
}
|
|
}
|