Files
Alphaeus Mote 39441eced9 feat(auth): record a generated first-start admin password and add reset-admin
An empty INITIAL_ADMIN_PASSWORD now means generate and record: the one-time
password goes to <data>/initial-admin-password.txt (Administrators, SYSTEM and
the server's own account only; mode 600 elsewhere) and the log only says where.
The file is removed once the password is changed or reset. reset-admin (alias
auth-reset) reads the standalone appsettings.json, so it reaches the same
database with the service running or stopped, takes --user/--password, turns
the account back on and is audited. The compose scripts stop generating the
password into .env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:42:38 -05:00

134 lines
5.8 KiB
C#

using System.Net.Http.Json;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.RegularExpressions;
using Backend.Auth;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Shared.Contracts.Api;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// No admin password in the installer: the first start generates one, records it where only administrators can
/// read it, and requires a new one at the first sign-in; reset-admin recovers a lost or locked-out account.
/// </summary>
public partial class InitialAdminPasswordTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private string RecordPath => Path.Combine(fixture.DataPath, InitialAdminPasswordFile.FileName);
[Fact]
public async Task TheGeneratedPasswordIsRecordedForAdministratorsAndMustBeChangedAtFirstSignIn()
{
using var _ = fixture.CreateClient();
var record = File.ReadAllText(RecordPath);
var password = PasswordLine().Match(record).Groups[1].Value;
Assert.Contains($"User: {BreakGlass.DefaultUserName}", record);
Assert.True(password.Length >= 16, "a strong generated password");
using var client = fixture.CreateClient();
(await client.SignInAsync(BreakGlass.DefaultUserName, password)).EnsureSuccessStatusCode();
var session = await client.GetFromJsonAsync<SessionView>(ApiRoutes.AuthSession, JsonDefaults.Options);
Assert.True(session!.BreakGlass);
Assert.True(session.PasswordChangeRequired);
if (OperatingSystem.IsWindows())
{
AssertAdministratorsOnly(RecordPath);
}
else
{
Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(RecordPath));
}
}
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
private static void AssertAdministratorsOnly(string path)
{
var acl = new FileInfo(path).GetAccessControl();
Assert.True(acl.AreAccessRulesProtected, "inheritance is off");
var allowed = new HashSet<SecurityIdentifier>();
foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
allowed.Add((SecurityIdentifier)rule.IdentityReference);
}
Assert.Contains(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), allowed);
Assert.Contains(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), allowed);
Assert.DoesNotContain(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), allowed);
Assert.DoesNotContain(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), allowed);
Assert.DoesNotContain(new SecurityIdentifier(WellKnownSidType.WorldSid, null), allowed);
allowed.ExceptWith([
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
WindowsIdentity.GetCurrent().User!,
]);
Assert.Empty(allowed);
}
[GeneratedRegex(@"Password: (\S+)")]
private static partial Regex PasswordLine();
}
/// <summary>reset-admin, run on the server with the service running or stopped.</summary>
public class ResetAdminTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private string RecordPath => Path.Combine(fixture.DataPath, InitialAdminPasswordFile.FileName);
[Fact]
public async Task ResetAdminSetsAPasswordReEnablesTheAccountAndAuditsIt()
{
using var _ = fixture.CreateClient();
await fixture.WithDbAsync(db => db.Users.Where(u => u.IsBreakGlass).ExecuteUpdateAsync(set => set.SetProperty(u => u.Enabled, false)));
var password = "Reset-" + Guid.NewGuid().ToString("N");
var exit = await AuthResetCli.RunAsync(["--password", password], CliConfiguration());
Assert.Equal(0, exit);
using var client = fixture.CreateClient();
(await client.SignInAsync(BreakGlass.DefaultUserName, password)).EnsureSuccessStatusCode();
var session = await client.GetFromJsonAsync<SessionView>(ApiRoutes.AuthSession, JsonDefaults.Options);
Assert.True(session!.PasswordChangeRequired);
Assert.True(await fixture.WithDbAsync(db => db.AuditEvents.AnyAsync(a => a.Action == "identity.break-glass.reset" && a.Actor == "reset-admin")));
Assert.False(File.Exists(RecordPath), "the first-start record no longer holds a working password");
}
[Fact]
public async Task ResetAdminRefusesAnAccountThatDoesNotExist()
{
using var _ = fixture.CreateClient();
Assert.Equal(2, await AuthResetCli.RunAsync(["--user", "nobody-here"], CliConfiguration()));
}
[Fact]
public void ResetAdminReadsTheStandaloneSettingsBesideTheBinary()
{
var folder = Path.Combine(Path.GetTempPath(), "executer-reset-admin-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
File.WriteAllText(Path.Combine(folder, "appsettings.json"), """{ "DATABASE_PATH": "C:/ExecuteR/data/db/app.db", "DATA_PATH": "C:/ExecuteR/data" }""");
var configuration = AuthResetCli.LoadConfiguration(folder);
Assert.Equal("C:/ExecuteR/data/db/app.db", configuration["DATABASE_PATH"]);
Assert.Equal("C:/ExecuteR/data", configuration["DATA_PATH"]);
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
private IConfiguration CliConfiguration() => new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["DATABASE_PATH"] = fixture.DatabasePath,
["DATA_PATH"] = fixture.DataPath,
["DATAPROTECTION_PATH"] = Path.Combine(fixture.DataPath, "keys"),
}).Build();
}