using System.Text;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
namespace Chronos.Server.Security;
///
/// First-run administrator (BRIEF ยง14.9): when no admin account exists, one is created from
/// CHRONOS_ADMIN_USER/CHRONOS_ADMIN_PASSWORD and must change its password at first sign-in. Without a
/// configured password a temporary one is generated and written to /data/initial-admin-password.txt (owner-only;
/// on Windows readable by the server's account and Administrators), never to the log; the file is removed once an
/// administrator changes their password.
///
public static class AdminBootstrap
{
public const string DefaultUsername = "admin";
/// The file in the data folder that holds a generated temporary password until an administrator sets their own.
public const string PasswordFileName = "initial-admin-password.txt";
public static async Task RunAsync(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger logger, CancellationToken cancellationToken)
{
var users = await db.Users.ListAsync(cancellationToken).ConfigureAwait(false);
if (users.Any(u => u.Role == UserRole.Admin))
{
if (!string.IsNullOrEmpty(options.AdminPassword))
logger.LogInformation("An administrator exists; CHRONOS_ADMIN_USER and CHRONOS_ADMIN_PASSWORD are ignored");
return;
}
var username = string.IsNullOrWhiteSpace(options.AdminUser) ? DefaultUsername : options.AdminUser.Trim();
if (!Accounts.IsValidUsername(username))
throw new InvalidOperationException("CHRONOS_ADMIN_USER may only contain letters, digits, dot, dash and underscore (up to 64 characters).");
if (users.Any(u => Accounts.Key(u.Username) == Accounts.Key(username)))
throw new InvalidOperationException($"No administrator exists and CHRONOS_ADMIN_USER '{username}' names an existing account; choose another name.");
var password = options.AdminPassword;
string? passwordFile = null;
if (string.IsNullOrEmpty(password))
{
password = TemporaryPassword.Generate();
passwordFile = Path.Combine(options.DataPath, PasswordFileName);
DataFolderAccess.WritePrivateFile(passwordFile, Encoding.UTF8.GetBytes(password + Environment.NewLine));
}
var admin = new User
{
Id = Guid.CreateVersion7(),
Username = username,
DisplayName = null,
PasswordHash = PasswordHasher.Hash(password),
Role = UserRole.Admin,
Permissions = Permissions.All,
MustChangePassword = true,
Created = time.GetUtcNow(),
};
await db.Users.CreateAsync(admin, cancellationToken).ConfigureAwait(false);
await db.Audit.AppendAsync(new AuditEntry
{
Id = Guid.CreateVersion7(),
At = admin.Created,
Action = "user_created",
TargetKind = "user",
TargetId = admin.Id.ToString(),
Details = "admin",
Username = username,
}, cancellationToken).ConfigureAwait(false);
if (passwordFile is null)
logger.LogWarning("Created administrator '{User}' from CHRONOS_ADMIN_USER/CHRONOS_ADMIN_PASSWORD; the password must be changed at first sign-in", username);
else
logger.LogWarning("Created administrator '{User}'; its temporary password is in {File} and must be changed at first sign-in", username, passwordFile);
}
/// Removes the generated password file (called when an administrator sets their own password).
public static void ForgetInitialPassword(ServerOptions options)
{
try
{
File.Delete(Path.Combine(options.DataPath, PasswordFileName));
}
catch (IOException)
{
// Best effort: the file holds a password that no longer works.
}
}
}