Progmasoft Git

progmaweb

The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.

Clonegit clone https://git.progmasoft.com/progmaweb

Provision the reserved accounts on the server

Registration refuses the reserved names Progmasoft and Leitwolf, which are
meant to be created by trusted operations tooling only, and that tooling did
not exist: the Progmasoft account, the publisher of Progmasoft's Tazel
plugins on ViGet, could not be created at all.

- 'accounts provision-reserved <Name> <email>' runs with the configuration
  of the service, like the viget commands. It accepts only the reserved
  names, applies the rules of registration to the email address and the
  password, never replaces an existing account, and brings the account
  tables to the current schema first.
- The password is read from the terminal without echo, twice, or from one
  line of standard input when it is not a terminal; it never appears on a
  command line or in the output.
- AccountNamePolicy.TryNormalizeReserved checks a reserved name;
  TryNormalize, which registration uses, still refuses it.

Tests cover a reserved account created and signing in with its password,
a name that is not reserved, two different passwords, a weak password, an
existing account and the usage line. ops/README.md shows the command with
systemd-run --pty; docs/ACCOUNT-API.md points to it.
Commit
21b515565b73f86477afe436bb3588f3e5929443
Author
Leitwolf11 ·
Parents
44d14a8ad8cb

Files · Download .tar.gz

Changes

 apps/api-tests/AccountCommandTests.cs  | 123 +++++++++++++++++++++++++++++++++
 apps/api/Accounts/AccountCommand.cs    | 118 +++++++++++++++++++++++++++++++
 apps/api/Accounts/AccountNamePolicy.cs |  27 ++++++++
 apps/api/Accounts/AccountService.cs    |  49 +++++++++++++
 apps/api/Program.cs                    |  11 ++-
 docs/ACCOUNT-API.md                    |   2 +-
 ops/README.md                          |  18 +++++
 7 files changed, 346 insertions(+), 2 deletions(-)

diff --git a/apps/api-tests/AccountCommandTests.cs b/apps/api-tests/AccountCommandTests.cs
new file mode 100644
index 0000000..46c8e31
--- /dev/null
+++ b/apps/api-tests/AccountCommandTests.cs
@@ -0,0 +1,123 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using Microsoft.Extensions.DependencyInjection;
+using Progmasoft.Progmaweb.Api.Accounts;
+
+namespace Progmasoft.Progmaweb.Api.Tests;
+
+/// <summary>The operations command that provisions the reserved accounts.</summary>
+public sealed class AccountCommandTests
+{
+    private const string Password = "a long test passphrase";
+
+    private sealed class Input(bool terminal, params string?[] lines) : IPasswordInput
+    {
+        private readonly Queue<string?> remaining = new(lines);
+
+        public bool IsTerminal { get; } = terminal;
+
+        public List<string> Prompts { get; } = [];
+
+        public string? Read(string prompt)
+        {
+            Prompts.Add(prompt);
+            return remaining.Count > 0 ? remaining.Dequeue() : null;
+        }
+    }
+
+    private static (ServiceProvider Services, InMemoryAccountStore Store) Services()
+    {
+        InMemoryAccountStore store = new();
+        ServiceProvider services = new ServiceCollection()
+            .AddSingleton<IAccountStore>(store)
+            .AddSingleton(TimeProvider.System)
+            .AddSingleton<AccountService>()
+            .BuildServiceProvider();
+        return (services, store);
+    }
+
+    private static async Task<(int Code, string Output, string Errors)> RunAsync(
+        IServiceProvider services,
+        IPasswordInput input,
+        params string[] args)
+    {
+        StringWriter output = new();
+        StringWriter errors = new();
+        int code = await AccountCommand.RunAsync(
+            services, args, input, output, errors, TestContext.Current.CancellationToken);
+        return (code, output.ToString(), errors.ToString());
+    }
+
+    [Fact]
+    public async Task AReservedAccountIsCreatedWithThePasswordTypedTwice()
+    {
+        (ServiceProvider services, InMemoryAccountStore store) = Services();
+        Input input = new(terminal: true, Password, Password);
+
+        (int code, string output, _) = await RunAsync(
+            services, input, "provision-reserved", "Progmasoft", "support@progmasoft.com");
+
+        Assert.Equal(0, code);
+        Assert.Contains("Created the reserved account Progmasoft", output, StringComparison.Ordinal);
+        Assert.DoesNotContain(Password, output, StringComparison.Ordinal);
+        Assert.Equal(["Password: ", "Password again: "], input.Prompts);
+        AccountRecord? account = await store.FindByAccountNameAsync("PROGMASOFT", TestContext.Current.CancellationToken);
+        Assert.NotNull(account);
+        Assert.Equal("Progmasoft", account.AccountName);
+        // The password works for signing in.
+        AccountRecord? verified = await services.GetRequiredService<AccountService>().VerifyPasswordAsync(
+            "support@progmasoft.com", Password, TestContext.Current.CancellationToken);
+        Assert.Equal(account.Id, verified?.Id);
+    }
+
+    [Fact]
+    public async Task OnlyReservedNamesAreProvisioned()
+    {
+        (ServiceProvider services, _) = Services();
+        (int code, _, string errors) = await RunAsync(
+            services, new Input(terminal: false, Password), "provision-reserved", "Somebody1", "a@example.com");
+        Assert.Equal(1, code);
+        Assert.Contains("is not a reserved name", errors, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task DifferentPasswordsCreateNothing()
+    {
+        (ServiceProvider services, InMemoryAccountStore store) = Services();
+        (int code, _, string errors) = await RunAsync(
+            services, new Input(terminal: true, Password, Password + "!"), "provision-reserved", "Leitwolf",
+            "owner@example.com");
+        Assert.Equal(1, code);
+        Assert.Contains("differ", errors, StringComparison.Ordinal);
+        Assert.Null(await store.FindByAccountNameAsync("LEITWOLF", TestContext.Current.CancellationToken));
+    }
+
+    [Fact]
+    public async Task AWeakPasswordOrAnExistingAccountIsRefused()
+    {
+        (ServiceProvider services, _) = Services();
+        (int weak, _, string weakErrors) = await RunAsync(
+            services, new Input(terminal: false, "short"), "provision-reserved", "Progmasoft", "support@progmasoft.com");
+        Assert.Equal(1, weak);
+        Assert.Contains("at least 12 characters", weakErrors, StringComparison.Ordinal);
+
+        Assert.Equal(0, (await RunAsync(
+            services, new Input(terminal: false, Password), "provision-reserved", "Progmasoft",
+            "support@progmasoft.com")).Code);
+        (int again, _, string againErrors) = await RunAsync(
+            services, new Input(terminal: false, Password), "provision-reserved", "PROGMASOFT", "other@progmasoft.com");
+        Assert.Equal(1, again);
+        Assert.Contains("exists already", againErrors, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task PublicRegistrationStillRefusesReservedNames()
+    {
+        Assert.False(AccountNamePolicy.TryNormalize("Progmasoft", out _, out string error));
+        Assert.Equal("That account name is reserved.", error);
+        (int code, _, string errors) = await RunAsync(Services().Services, new Input(terminal: false), "provision");
+        Assert.Equal(2, code);
+        Assert.Contains("usage", errors, StringComparison.Ordinal);
+    }
+}
diff --git a/apps/api/Accounts/AccountCommand.cs b/apps/api/Accounts/AccountCommand.cs
new file mode 100644
index 0000000..ae75564
--- /dev/null
+++ b/apps/api/Accounts/AccountCommand.cs
@@ -0,0 +1,118 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1
+
+using System.Text;
+
+namespace Progmasoft.Progmaweb.Api.Accounts;
+
+/// <summary>
+/// The command that provisions a reserved account on the server: <c>accounts provision-reserved &lt;Name&gt;
+/// &lt;email&gt;</c>. Public registration refuses the reserved names (Progmasoft, Leitwolf); this is the trusted
+/// operations tooling that creates them. The password is read from the terminal without echo, twice, or from one line
+/// of standard input when it is not a terminal; it never appears on a command line.
+/// </summary>
+internal static class AccountCommand
+{
+    /// <summary>Runs an account command.</summary>
+    /// <param name="services">The services of the API, not started.</param>
+    /// <param name="args">The arguments after <c>accounts</c>.</param>
+    /// <param name="input">Where the password comes from.</param>
+    /// <param name="output">Where results go.</param>
+    /// <param name="errors">Where errors go.</param>
+    /// <param name="cancellationToken">Cancels the command.</param>
+    /// <returns>The exit code: 0 on success, 1 when refused, 2 for a wrong command line.</returns>
+    public static async Task<int> RunAsync(
+        IServiceProvider services,
+        string[] args,
+        IPasswordInput input,
+        TextWriter output,
+        TextWriter errors,
+        CancellationToken cancellationToken)
+    {
+        if (args is not ["provision-reserved", string name, string email])
+        {
+            await errors.WriteLineAsync("usage: accounts provision-reserved <Name> <email>");
+            return 2;
+        }
+
+        // The service brings the account tables to the current schema when it starts; a command may run before.
+        if (services.GetService<Npgsql.NpgsqlDataSource>() is { } dataSource)
+        {
+            await AccountSchema.ApplyAsync(dataSource, cancellationToken);
+        }
+
+        string? password = input.Read("Password: ");
+        if (input.IsTerminal && password != input.Read("Password again: "))
+        {
+            await errors.WriteLineAsync("The two passwords differ; nothing was created.");
+            return 1;
+        }
+
+        AccountService accounts = services.GetRequiredService<AccountService>();
+        (AccountRecord? account, string? error) =
+            await accounts.ProvisionReservedAsync(name, email, password, cancellationToken);
+        if (account is null)
+        {
+            await errors.WriteLineAsync(error);
+            return 1;
+        }
+
+        await output.WriteLineAsync($"Created the reserved account {account.AccountName} ({account.Email}).");
+        return 0;
+    }
+}
+
+/// <summary>Where <see cref="AccountCommand"/> reads a password from.</summary>
+internal interface IPasswordInput
+{
+    /// <summary>Whether the input is a terminal, which asks twice and does not echo.</summary>
+    bool IsTerminal { get; }
+
+    /// <summary>Reads one password.</summary>
+    /// <param name="prompt">What to show before it, on a terminal.</param>
+    /// <returns>The password, or <see langword="null"/> at the end of the input.</returns>
+    string? Read(string prompt);
+}
+
+/// <summary>The console: a terminal without echo, or one line of redirected standard input.</summary>
+internal sealed class ConsolePasswordInput : IPasswordInput
+{
+    /// <inheritdoc/>
+    public bool IsTerminal => !Console.IsInputRedirected;
+
+    /// <inheritdoc/>
+    public string? Read(string prompt)
+    {
+        if (!IsTerminal)
+        {
+            return Console.In.ReadLine();
+        }
+
+        Console.Error.Write(prompt);
+        StringBuilder password = new();
+        while (true)
+        {
+            ConsoleKeyInfo key = Console.ReadKey(intercept: true);
+            if (key.Key == ConsoleKey.Enter)
+            {
+                Console.Error.WriteLine();
+                return password.ToString();
+            }
+
+            if (key.Key == ConsoleKey.Backspace)
+            {
+                if (password.Length > 0)
+                {
+                    password.Length--;
+                }
+
+                continue;
+            }
+
+            if (!char.IsControl(key.KeyChar))
+            {
+                password.Append(key.KeyChar);
+            }
+        }
+    }
+}
diff --git a/apps/api/Accounts/AccountNamePolicy.cs b/apps/api/Accounts/AccountNamePolicy.cs
index 3b2328d..7dce6c5 100644
--- a/apps/api/Accounts/AccountNamePolicy.cs
+++ b/apps/api/Accounts/AccountNamePolicy.cs
@@ -61,6 +61,33 @@ internal static partial class AccountNamePolicy
         return true;
     }
 
+    /// <summary>
+    /// Validates a reserved name for the operations command that provisions it: the same rules as
+    /// <see cref="TryNormalize"/>, except that the name must be one of the reserved names.
+    /// </summary>
+    /// <param name="value">The name as entered; surrounding white space is ignored.</param>
+    /// <param name="canonical">The trimmed name. It is meaningful only when the method returns <see langword="true"/>.</param>
+    /// <param name="error">Message for the operator when the name is refused; empty otherwise.</param>
+    /// <returns><see langword="true"/> when the name is a well-formed reserved name.</returns>
+    public static bool TryNormalizeReserved(string? value, out string canonical, out string error)
+    {
+        canonical = value?.Trim() ?? string.Empty;
+        if (!CanonicalPattern().IsMatch(canonical))
+        {
+            error = "Account names must begin with an uppercase ASCII letter and contain only ASCII letters or digits.";
+            return false;
+        }
+
+        if (!ReservedNames.Contains(NormalizeForLookup(canonical)))
+        {
+            error = $"'{canonical}' is not a reserved name; it is registered through the account site.";
+            return false;
+        }
+
+        error = string.Empty;
+        return true;
+    }
+
     /// <summary>Returns the key under which a name is compared for uniqueness.</summary>
     /// <param name="canonical">A name that <see cref="TryNormalize"/> accepted.</param>
     /// <returns>The name in upper case.</returns>
diff --git a/apps/api/Accounts/AccountService.cs b/apps/api/Accounts/AccountService.cs
index 0deadb5..40e971d 100644
--- a/apps/api/Accounts/AccountService.cs
+++ b/apps/api/Accounts/AccountService.cs
@@ -224,6 +224,55 @@ internal sealed class AccountService(
         return (await sessions.CreateAsync(result.Account ?? account, cancellationToken), GoogleAccountFailure.None);
     }
 
+    /// <summary>
+    /// Creates the account of a reserved name, which public registration refuses. Only trusted operations tooling
+    /// calls this; see <see cref="AccountCommand"/>.
+    /// </summary>
+    /// <param name="accountName">The reserved name, as it is to be spelled.</param>
+    /// <param name="email">The email address of the account.</param>
+    /// <param name="password">The password, which the operator typed.</param>
+    /// <param name="cancellationToken">Cancels the operation.</param>
+    /// <returns>The created account, or the message that says why it was refused.</returns>
+    public async ValueTask<(AccountRecord? Account, string? Error)> ProvisionReservedAsync(
+        string? accountName,
+        string? email,
+        string? password,
+        CancellationToken cancellationToken)
+    {
+        if (!AccountNamePolicy.TryNormalizeReserved(accountName, out string name, out string nameError))
+        {
+            return (null, nameError);
+        }
+
+        if (!EmailAddressPolicy.TryNormalize(email, out string address, out string normalizedEmail, out string emailError))
+        {
+            return (null, emailError);
+        }
+
+        if (!PasswordPolicy.TryValidate(password, out string passwordError))
+        {
+            return (null, passwordError);
+        }
+
+        AccountRecord provisional = new(
+            Guid.NewGuid(),
+            name,
+            AccountNamePolicy.NormalizeForLookup(name),
+            address,
+            normalizedEmail,
+            null,
+            string.Empty,
+            timeProvider.GetUtcNow());
+        AccountRecord account = provisional with { PasswordHash = passwordHasher.HashPassword(provisional, password!) };
+        CreateAccountResult result = await store.CreateAsync(account, cancellationToken);
+        return result.Status switch
+        {
+            CreateAccountStatus.AccountNameUnavailable => (null, $"The account '{name}' exists already."),
+            CreateAccountStatus.EmailUnavailable => (null, "That email address is already registered."),
+            _ => (result.Account ?? account, null)
+        };
+    }
+
     /// <summary>Validates every field of a registration and collects the messages of the refused ones.</summary>
     /// <param name="request">The registration body.</param>
     /// <param name="accountName">The canonical account name.</param>
diff --git a/apps/api/Program.cs b/apps/api/Program.cs
index 873c120..6208b30 100644
--- a/apps/api/Program.cs
+++ b/apps/api/Program.cs
@@ -13,8 +13,10 @@ using Progmasoft.Progmaweb.Api.ViGet;
 
 // `viget ...` runs a command of ViGet with the configuration of the service instead of the service itself; its
 // arguments are not configuration.
+// `accounts ...` provisions a reserved account the same way.
 bool vigetCommand = ViGetCommand.IsCommand(args);
-WebApplicationBuilder builder = WebApplication.CreateBuilder(vigetCommand ? [] : args);
+bool accountCommand = args is ["accounts", ..];
+WebApplicationBuilder builder = WebApplication.CreateBuilder(vigetCommand || accountCommand ? [] : args);
 
 builder.Services.Configure<AccountSessionOptions>(builder.Configuration.GetSection(AccountSessionOptions.SectionName));
 builder.Services.AddSingleton(TimeProvider.System);
@@ -109,6 +111,13 @@ builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize =
 
 WebApplication app = builder.Build();
 
+if (accountCommand)
+{
+    Environment.ExitCode = await AccountCommand.RunAsync(
+        app.Services, args[1..], new ConsolePasswordInput(), Console.Out, Console.Error, CancellationToken.None);
+    return;
+}
+
 if (vigetCommand)
 {
     Environment.ExitCode = await ViGetCommand.RunAsync(
diff --git a/docs/ACCOUNT-API.md b/docs/ACCOUNT-API.md
index 51648a3..9288c0f 100644
--- a/docs/ACCOUNT-API.md
+++ b/docs/ACCOUNT-API.md
@@ -26,7 +26,7 @@ Every response carries `Cache-Control: no-store`.
 
 | Field | Rule |
 | --- | --- |
-| `accountName` | 8 to 128 ASCII letters or digits, beginning with an upper-case letter. Unique without regard to case; the spelling the owner chose is kept. `Progmasoft` and `Leitwolf` are reserved in every case. |
+| `accountName` | 8 to 128 ASCII letters or digits, beginning with an upper-case letter. Unique without regard to case; the spelling the owner chose is kept. `Progmasoft` and `Leitwolf` are reserved in every case; operations tooling creates them on the server (`accounts provision-reserved`, see ops/README.md). |
 | `email` | a single mailbox without a display name, at most 254 characters. Unique without regard to case. Ownership is not verified. |
 | `password` | 12 to 256 characters, without a null character. No composition rule; long passphrases are welcome. |
 
diff --git a/ops/README.md b/ops/README.md
index dd1ee9d..2015fbb 100644
--- a/ops/README.md
+++ b/ops/README.md
@@ -153,6 +153,24 @@ The certificate of `progmasoft.com` must name `credentials.progmasoft.com`, `aut
 it with certbot's webroot plugin before the vhosts are enabled, then check
 `/.well-known/openid-configuration`, the sign-in page and the console from outside.
 
+## Reserved accounts
+
+Public registration refuses the reserved names, `Progmasoft` and `Leitwolf`, which identify Progmasoft itself and its
+administrator. They are created on the server by the person who will use them, in an interactive terminal; the
+command asks for the password twice without showing it, so it never reaches a command line or a log:
+
+```sh
+systemd-run --quiet --wait --pty --uid=progmaweb --gid=progmaweb \
+  -p EnvironmentFile=/etc/progmaweb/account.env -p Environment=ASPNETCORE_ENVIRONMENT=Production \
+  -p WorkingDirectory=/srv/progmaweb/current/api \
+  /usr/bin/dotnet /srv/progmaweb/current/api/Progmaweb.Api.dll \
+  accounts provision-reserved Progmasoft support@progmasoft.com
+```
+
+The name, the email address and the password follow the rules of registration; only the reserved names are accepted,
+and an existing account is never replaced. The account then signs in on `account.progmasoft.com` like any other, and
+is the ViGet publisher of the same name.
+
 ## ViGet: Tazel plugins
 
 ViGet opens in stages. Now only the accounts that `ViGet__TazelPublishers` names (Progmasoft by default) publish Tazel