Close what the security review found
A session alone could change the password, switch the second factor on or off, send the key of the language model to another address and remove the rules that stop purchases. Each now needs the password and the code, with one limit on wrong attempts that a restart of the services does not clear, and the other sessions end when the password or the factor changes. Requests to the brokers pass a list of allowed calls, never follow a redirect with a key and are signed by one client only. Pages are closed by default, nothing is cached, requests are limited to 1 MB, secrets are masked in logs and notifications, exported tables cannot run as formulas, archives carry no sessions and the container refuses to run as root. refs #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4897594b87
commit
4d92a39fef
35 files changed
+907
-118
No files matched your search
@@ -15,7 +15,8 @@ var environment = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
|
||||
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||
var paths = new GuardPaths(DataRoot(args, environment));
|
||||
var logger = new LineLogger(Console.Out.WriteLine);
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
using var http = Anubis.Brokers.Outgoing.KeyedClient();
|
||||
http.Timeout = TimeSpan.FromSeconds(20);
|
||||
var clock = SystemClock.Instance;
|
||||
var guardian = new Guardian(paths, clock, new GuardOptions(),
|
||||
start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start),
|
||||
|
||||
@@ -167,7 +167,7 @@ internal sealed record AccountsView(
|
||||
// Trailing zeros dropped, so both database engines give the same text.
|
||||
static string Number(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
|
||||
|
||||
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
|
||||
static string Clean(string value) => Format.CsvText(value);
|
||||
}
|
||||
|
||||
private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop,
|
||||
|
||||
@@ -60,6 +60,7 @@ internal sealed partial class AnubisHost(
|
||||
/// <summary>A scheduler silent this long is stuck: the engine stops beating, so the guard steps in.</summary>
|
||||
public static readonly TimeSpan SchedulerSilence = TimeSpan.FromMinutes(30);
|
||||
|
||||
private readonly AccessGuards _accessGuards = new(clock);
|
||||
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
@@ -303,7 +304,7 @@ internal sealed partial class AnubisHost(
|
||||
var key = Config.SecretKey.GetOrCreateKey();
|
||||
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
|
||||
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
|
||||
var access = new AccessStore(_db, clock, secrets, PasswordIterations);
|
||||
var access = new AccessStore(_db, clock, secrets, PasswordIterations, _accessGuards);
|
||||
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
|
||||
{
|
||||
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -333,7 +333,7 @@
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||
<label for="@rule.Key">@definition.Label</label>
|
||||
<select id="@rule.Key" name="valore" disabled="@(rule.ReadOnly || Shell.IsDemo)" data-autosubmit>
|
||||
<select id="@rule.Key" name="valore" disabled="@(rule.ReadOnly || Shell.IsDemo)" data-autosubmit="@(_anyLive && rule.Value != "off" ? null : "")">
|
||||
<option value="on" selected="@(rule.Value != "off")">Accesa</option>
|
||||
<option value="off" selected="@(rule.Value == "off")">Spenta</option>
|
||||
</select>
|
||||
@@ -341,6 +341,14 @@
|
||||
{
|
||||
<span class="hint">Fissato da @rule.Source: si cambia lì.</span>
|
||||
}
|
||||
else if (!Shell.IsDemo && _anyLive && rule.Value != "off")
|
||||
{
|
||||
<p class="note">Una strategia usa soldi veri: per spegnere la regola servono la frase e la password.</p>
|
||||
<label>Scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
}
|
||||
else if (!Shell.IsDemo)
|
||||
{
|
||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||
@@ -499,6 +507,8 @@
|
||||
</ol>
|
||||
<form method="post" action="/azioni/due-fattori/attiva" class="form">
|
||||
<AntiforgeryToken />
|
||||
<label for="password-nuovo-2fa">Password</label>
|
||||
<input id="password-nuovo-2fa" name="password" type="password" autocomplete="current-password" required />
|
||||
<label for="codice">Codice</label>
|
||||
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||
<button class="btn" type="submit">Attiva il secondo fattore</button>
|
||||
@@ -685,6 +695,8 @@
|
||||
private string? ErrorText => Errore switch
|
||||
{
|
||||
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
|
||||
"password-o-codice" => "La password o il codice non sono giusti. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
|
||||
"gia-attivo" => "Il secondo fattore è già attivo: per cambiarlo prima disattivalo.",
|
||||
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
|
||||
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
|
||||
"impostazione" => "Questa impostazione non si può cambiare così.",
|
||||
@@ -730,6 +742,7 @@
|
||||
var value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null);
|
||||
var locked = value.ReadOnly || Shell.IsDemo;
|
||||
var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value;
|
||||
var asksPassword = key == Anubis.News.NewsModelSettings.Address.Key || key == Anubis.News.NewsModelSettings.Provider.Key;
|
||||
var provider = _llm.GetValueOrDefault(Anubis.News.NewsModelSettings.Provider.Key)?.Value ?? Anubis.News.NewsModelProviders.Anthropic;
|
||||
return @<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
@@ -737,26 +750,32 @@
|
||||
<label for="@id">@label</label>
|
||||
@if (definition.Allowed is { } choices)
|
||||
{
|
||||
<select id="@id" name="valore" disabled="@locked" data-autosubmit>
|
||||
<select id="@id" name="valore" disabled="@locked">
|
||||
@foreach (var choice in choices)
|
||||
{
|
||||
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
|
||||
}
|
||||
</select>
|
||||
@if (!locked)
|
||||
{
|
||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<input id="@id" name="valore" inputmode="@(decimals is null ? "text" : "decimal")" autocomplete="off" spellcheck="false" value="@shown"
|
||||
placeholder="@(key == Anubis.News.NewsModelSettings.Address.Key ? Anubis.News.NewsModelProviders.DefaultAddress(provider).ToString() : null)"
|
||||
readonly="@locked" required="@(key != Anubis.News.NewsModelSettings.Address.Key)" />
|
||||
@if (!locked)
|
||||
}
|
||||
@if (!locked)
|
||||
{
|
||||
@if (asksPassword)
|
||||
{
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
<label for="@(id + "-password")">Password</label>
|
||||
<input id="@(id + "-password")" name="password" type="password" autocomplete="current-password" required />
|
||||
@if (_hasSecondFactor)
|
||||
{
|
||||
<label for="@(id + "-codice")">Codice</label>
|
||||
<input id="@(id + "-codice")" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
||||
}
|
||||
}
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
}
|
||||
@if (value.ReadOnly)
|
||||
{
|
||||
|
||||
@@ -182,7 +182,15 @@
|
||||
{
|
||||
<div class="row">
|
||||
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (quasi certamente tra @Bp(c.LowBp) e @Bp(c.HighBp)). Un punto base è un centesimo di punto percentuale.</span></p>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken />
|
||||
@if (_anyLive)
|
||||
{
|
||||
<p class="note">Una strategia usa soldi veri: per contare costi più bassi servono la frase e la password.</p>
|
||||
<label>Scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||
}
|
||||
<button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/rifiuta" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Rifiuta</button></form>
|
||||
</div>
|
||||
}
|
||||
@@ -228,6 +236,7 @@
|
||||
private DateOnly _to;
|
||||
private IReadOnlyList<string> _research = [];
|
||||
private IReadOnlyList<CostEstimate> _costs = [];
|
||||
private bool _anyLive;
|
||||
private SlippageTable _table = SlippageTable.Standard;
|
||||
|
||||
[CascadingParameter]
|
||||
@@ -248,6 +257,7 @@
|
||||
var costs = new CostBook(services.Db, Clock);
|
||||
_costs = await costs.ListAsync(ct);
|
||||
_table = await costs.TableAsync(ct);
|
||||
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
|
||||
_running = _trials.Any(t => !t.IsFinished);
|
||||
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||
@@ -261,6 +271,9 @@
|
||||
_message = Errore switch
|
||||
{
|
||||
null => null,
|
||||
"frase-rischio" => $"Una strategia usa soldi veri: per confermare scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
|
||||
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
|
||||
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
|
||||
"stima" => "Quella stima non aspetta più una conferma.",
|
||||
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
||||
TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.",
|
||||
|
||||
@@ -24,6 +24,7 @@ internal static class PasswordMessages
|
||||
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
|
||||
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
|
||||
"attuale" => "La password attuale non è giusta.",
|
||||
"attesa" => "Troppi tentativi sbagliati: aspetta 15 minuti e riprova.",
|
||||
"demo" => "Nella modalità dimostrativa la password non si cambia.",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ internal static class DiagnosticsExport
|
||||
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
|
||||
{
|
||||
var end = to ?? now;
|
||||
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours ?? MaxHours, 0.25, MaxHours));
|
||||
var start = from ?? end - TimeSpan.FromHours(Math.Clamp(hours is { } h && double.IsFinite(h) ? h : MaxHours, 0.25, MaxHours));
|
||||
if (from is null && hours is null)
|
||||
{
|
||||
var first = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT MIN(taken_at) AS t FROM diagnostic_samples", r => r.MomentOrNull("t")), cancellationToken)
|
||||
|
||||
@@ -146,6 +146,12 @@ internal static partial class Endpoints
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le soglie del modello si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||
}
|
||||
|
||||
// And for the rules of the news, and where the model's key goes: the page asks for the password.
|
||||
if (Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key) || Anubis.News.NewsModelSettings.All.Any(d => d.Key == key))
|
||||
{
|
||||
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "Le regole delle notizie e il modello linguistico si cambiano da Impostazioni, con la password quando serve.");
|
||||
}
|
||||
|
||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
@@ -409,6 +415,7 @@ internal static partial class Endpoints
|
||||
return;
|
||||
}
|
||||
|
||||
context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token);
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
||||
using var settings = bus.Subscribe<SettingChanged>(16);
|
||||
using var modes = bus.Subscribe<HostChanged>(16);
|
||||
@@ -418,6 +425,12 @@ internal static partial class Endpoints
|
||||
{
|
||||
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
|
||||
{
|
||||
// The live status ends with the session: signed out, expired, or closed by a new password.
|
||||
if (!host.IsDemo && (host.Services is not { } services || await services.Access.ValidateAsync(token, refresh: false, aborted).ConfigureAwait(false) is null))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
|
||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
||||
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
|
||||
|
||||
+63
-12
@@ -144,7 +144,7 @@ internal static partial class Forms
|
||||
return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor;
|
||||
}
|
||||
|
||||
private static async Task<IResult> SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, ILogger<AnubisHost> logger, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var services = host.Services;
|
||||
if (services is null)
|
||||
@@ -158,12 +158,18 @@ internal static partial class Forms
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
|
||||
LogSignInRefused(logger, address, "Locked");
|
||||
return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
}
|
||||
|
||||
var code = form["codice"].ToString();
|
||||
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (result is not (LoginResult.Ok or LoginResult.SecondFactorNeeded))
|
||||
{
|
||||
LogSignInRefused(logger, address, result.ToString());
|
||||
}
|
||||
|
||||
switch (result)
|
||||
{
|
||||
case LoginResult.Ok:
|
||||
@@ -182,6 +188,9 @@ internal static partial class Forms
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Sign-in refused from {Address}: {Reason}")]
|
||||
private static partial void LogSignInRefused(ILogger logger, string address, string reason);
|
||||
|
||||
private static async Task<IResult> SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services)
|
||||
@@ -211,9 +220,15 @@ internal static partial class Forms
|
||||
return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale"));
|
||||
}
|
||||
|
||||
var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct)
|
||||
var (outcome, token) = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct)
|
||||
.ConfigureAwait(false);
|
||||
return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale"));
|
||||
if (outcome != AccessChange.Done)
|
||||
{
|
||||
return Results.Redirect(With(page, "errore", outcome == AccessChange.Locked ? "attesa" : "attuale"));
|
||||
}
|
||||
|
||||
SessionAuthentication.WriteCookie(context, token!);
|
||||
return Results.Redirect(With(done, "ok", "password"));
|
||||
}
|
||||
|
||||
private static async Task<IResult> EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct)
|
||||
@@ -225,22 +240,35 @@ internal static partial class Forms
|
||||
return Results.Redirect("/impostazioni?errore=segreto#sicurezza");
|
||||
}
|
||||
|
||||
var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false);
|
||||
if (ok)
|
||||
var outcome = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["password"].ToString(), form["codice"].ToString(), session, ct)
|
||||
.ConfigureAwait(false);
|
||||
if (outcome is AccessChange.Done or AccessChange.AlreadyOn)
|
||||
{
|
||||
drafts.Remove(session);
|
||||
}
|
||||
|
||||
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza");
|
||||
return Results.Redirect(outcome switch
|
||||
{
|
||||
AccessChange.Done => "/impostazioni?ok=due-fattori#sicurezza",
|
||||
AccessChange.Locked => "/impostazioni?errore=attesa#sicurezza",
|
||||
AccessChange.AlreadyOn => "/impostazioni?errore=gia-attivo#sicurezza",
|
||||
_ => "/impostazioni?errore=password-o-codice#sicurezza",
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<IResult> DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false);
|
||||
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza");
|
||||
var outcome = host.IsDemo ? AccessChange.Wrong : await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(),
|
||||
form["codice"].ToString(), CurrentUser.Session(context.User), ct).ConfigureAwait(false);
|
||||
return Results.Redirect(outcome switch
|
||||
{
|
||||
AccessChange.Done => "/impostazioni?ok=due-fattori-tolti#sicurezza",
|
||||
AccessChange.Locked => "/impostazioni?errore=attesa#sicurezza",
|
||||
_ => "/impostazioni?errore=password-o-codice#sicurezza",
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
var back = Back(form, "/impostazioni");
|
||||
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
|
||||
@@ -271,10 +299,26 @@ internal static partial class Forms
|
||||
return Results.Redirect(With(back, "errore", key == Anubis.News.NewsModelSettings.DailyCap.Key ? "tetto" : "modello"));
|
||||
}
|
||||
|
||||
// Who gets the key of the model is decided with the password: with only a session it could be sent anywhere.
|
||||
if ((key == Anubis.News.NewsModelSettings.Address.Key || key == Anubis.News.NewsModelSettings.Provider.Key) && host.Services is { } services &&
|
||||
value != (await services.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value &&
|
||||
!await services.Access.ReauthenticateAsync(form["password"].ToString(), form["codice"].ToString().Trim(), ct).ConfigureAwait(false))
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "password-rischio"));
|
||||
}
|
||||
|
||||
var saved = await Endpoints.SetSettingAsync(host, key, value, context, ct).ConfigureAwait(false);
|
||||
return Results.Redirect(saved is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
|
||||
}
|
||||
|
||||
// Without a rule of SPEC 10.5 purchases pass that it would stop: with real money in play that is more risk (SPEC 12.4).
|
||||
if (news && form["valore"].ToString() == Anubis.News.NewsRuleSettings.Off && host.Services is { } app &&
|
||||
(await app.Settings.GetAsync(key, ct).ConfigureAwait(false)).Value != Anubis.News.NewsRuleSettings.Off &&
|
||||
await RaiseRefusalAsync(app, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", refusal));
|
||||
}
|
||||
|
||||
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
|
||||
{
|
||||
return Results.Redirect(With(back, "errore", "riunioni"));
|
||||
@@ -633,9 +677,10 @@ internal static partial class Forms
|
||||
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||
{
|
||||
current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value;
|
||||
var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false);
|
||||
current[definition.Key] = value.Value;
|
||||
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
|
||||
if (typed.Length == 0)
|
||||
if (typed.Length == 0 || value.ReadOnly)
|
||||
{
|
||||
next[definition.Key] = current[definition.Key];
|
||||
continue;
|
||||
@@ -775,13 +820,19 @@ internal static partial class Forms
|
||||
}
|
||||
|
||||
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6). The form is bound for the antiforgery check.</summary>
|
||||
private static async Task<IResult> DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
private static async Task<IResult> DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta"))
|
||||
{
|
||||
return Results.Redirect("/laboratorio?errore=motore#stime");
|
||||
}
|
||||
|
||||
// A lower cost lets through operations a higher one would stop: with real money in play it asks like more risk (SPEC 12.4).
|
||||
if (choice == "conferma" && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||
{
|
||||
return Results.Redirect("/laboratorio?errore=" + refusal + "#stime");
|
||||
}
|
||||
|
||||
var book = new Anubis.Learning.CostBook(services.Db, host.Clock);
|
||||
var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
if (done && services.Trading is { } trading)
|
||||
|
||||
@@ -37,6 +37,12 @@ internal static class ServerApp
|
||||
builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
// No form of Anubis is larger than a few kilobytes; nothing is uploaded.
|
||||
k.Limits.MaxRequestBodySize = 1024 * 1024;
|
||||
k.AddServerHeader = false;
|
||||
});
|
||||
builder.Logging.ClearProviders();
|
||||
// Created by the container so it is disposed with the application and releases the log file.
|
||||
builder.Services.AddSingleton<ILoggerProvider>(_ => new JsonLogProvider(config.Data.Logs, clock, console: true));
|
||||
@@ -66,12 +72,14 @@ internal static class ServerApp
|
||||
|
||||
services.AddAuthentication(SessionAuthentication.SchemeName)
|
||||
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(SessionAuthentication.SchemeName, null);
|
||||
services.AddAuthorization();
|
||||
// What a new page or route forgets to say stays closed: only those marked anonymous answer without a session.
|
||||
services.AddAuthorization(o => o.FallbackPolicy = o.DefaultPolicy);
|
||||
services.AddAntiforgery(o =>
|
||||
{
|
||||
o.Cookie.Name = "anubis_csrf";
|
||||
o.Cookie.SameSite = SameSiteMode.Strict;
|
||||
o.Cookie.HttpOnly = true;
|
||||
o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||
o.HeaderName = Endpoints.CsrfHeader;
|
||||
o.FormFieldName = "__csrf";
|
||||
});
|
||||
@@ -126,6 +134,8 @@ internal static class ServerApp
|
||||
private static void RegisterSecrets(StartupConfig config)
|
||||
{
|
||||
Redactor.Register(config.Db?.Password);
|
||||
Redactor.Register(config.Db?.UrlPassword);
|
||||
Redactor.Register(config.HeartbeatUrl);
|
||||
Redactor.Register(config.AdminPassword);
|
||||
foreach (var value in config.EnvironmentKeys.Values)
|
||||
{
|
||||
@@ -141,6 +151,14 @@ internal static class ServerApp
|
||||
headers["Referrer-Policy"] = "same-origin";
|
||||
headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " +
|
||||
"font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'";
|
||||
headers["Cross-Origin-Opener-Policy"] = "same-origin";
|
||||
headers["Permissions-Policy"] = "camera=(), geolocation=(), microphone=(), payment=(), usb=()";
|
||||
if (!Gate.IsAlwaysOpen(context.Request.Path))
|
||||
{
|
||||
// Accounts, trades, registers: nothing stays in the browser or in a proxy.
|
||||
headers.CacheControl = "no-cache, no-store";
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ internal sealed partial class TelegramServices : IDisposable
|
||||
_secrets = secrets;
|
||||
_zone = host.Config.TimeZone;
|
||||
_logger = logger;
|
||||
_http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
|
||||
_http = Anubis.Brokers.Outgoing.KeyedClient(handler);
|
||||
|
||||
// Longer than the wait of the commands' long polling.
|
||||
_http.Timeout = TimeSpan.FromSeconds(60);
|
||||
|
||||
@@ -154,7 +154,7 @@ internal sealed record TradesView(
|
||||
|
||||
static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
|
||||
|
||||
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
|
||||
static string Clean(string value) => Format.CsvText(value);
|
||||
}
|
||||
|
||||
private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue,
|
||||
|
||||
@@ -117,6 +117,12 @@ public sealed class LoginLimiter(IClock clock)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
// Begin counts every attempt, also those that end well: a success takes them back from both counts.
|
||||
while (_failures.TryGetValue(address, out var list) && list.Count > 0)
|
||||
{
|
||||
Forgive(address);
|
||||
}
|
||||
|
||||
_failures.Remove(address);
|
||||
}
|
||||
}
|
||||
@@ -136,31 +142,21 @@ public sealed class LoginLimiter(IClock clock)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie;
|
||||
/// only their SHA-256 is stored, so a copy of the database does not let anyone in.
|
||||
/// What stays in memory about re-authentications: the wrong attempts and the last second-factor code used. It lives as
|
||||
/// long as the process, not as long as the services, which the interface can start again (new broker keys): otherwise
|
||||
/// whoever holds a stolen session would clear the count between one attempt and the next.
|
||||
/// </summary>
|
||||
public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, int iterations = Passwords.DefaultIterations)
|
||||
public sealed class AccessGuards(IClock clock)
|
||||
{
|
||||
public const string AdminName = "admin";
|
||||
public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12);
|
||||
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
|
||||
|
||||
// Wrong fresh re-authentications (SPEC 12.4) are limited like sign-ins, so a stolen session cannot try passwords.
|
||||
private const string FreshAttempts = "reauthentication";
|
||||
private readonly LoginLimiter _fresh = new(clock);
|
||||
|
||||
// Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory.
|
||||
private readonly Lock _stepGate = new();
|
||||
private readonly Lock _gate = new();
|
||||
private long _lastStep = long.MinValue;
|
||||
|
||||
private bool AcceptCode(ReadOnlySpan<byte> secret, string? code)
|
||||
{
|
||||
if (Totp.Match(secret, code, clock.UtcNow) is not { } step)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
public LoginLimiter Fresh { get; } = new(clock);
|
||||
|
||||
lock (_stepGate)
|
||||
/// <summary>Each second-factor code works once (RFC 6238, 5.2).</summary>
|
||||
public bool AcceptStep(long step)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (step <= _lastStep)
|
||||
{
|
||||
@@ -171,6 +167,39 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>How a change of password or second factor ended.</summary>
|
||||
public enum AccessChange
|
||||
{
|
||||
Done,
|
||||
|
||||
/// <summary>The password or the code is wrong.</summary>
|
||||
Wrong,
|
||||
|
||||
/// <summary>Too many wrong attempts in 15 minutes: even the right password waits.</summary>
|
||||
Locked,
|
||||
|
||||
/// <summary>The second factor is already on: it must be switched off first, which asks for its code.</summary>
|
||||
AlreadyOn,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie;
|
||||
/// only their SHA-256 is stored, so a copy of the database does not let anyone in.
|
||||
/// </summary>
|
||||
public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, int iterations = Passwords.DefaultIterations, AccessGuards? guards = null)
|
||||
{
|
||||
public const string AdminName = "admin";
|
||||
public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12);
|
||||
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
|
||||
|
||||
// Wrong fresh re-authentications (SPEC 12.4) are limited like sign-ins, so a stolen session cannot try passwords.
|
||||
private const string FreshAttempts = "reauthentication";
|
||||
private readonly AccessGuards _guards = guards ?? new AccessGuards(clock);
|
||||
|
||||
private bool AcceptCode(ReadOnlySpan<byte> secret, string? code) =>
|
||||
Totp.Match(secret, code, clock.UtcNow) is { } step && _guards.AcceptStep(step);
|
||||
|
||||
private static string SecondFactorName(Guid userId) => "totp:" + userId.ToString("D");
|
||||
|
||||
@@ -260,15 +289,25 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
|
||||
var token = Ids.NewToken();
|
||||
var now = clock.UtcNow;
|
||||
await db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO sessions (id, user_id, token_hash, user_agent, address, created_at, last_seen_at, expires_at) VALUES (@id, @u, @h, @ua, @a, @t, @t, @e)",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("u", user.Id), ("h", HashToken(token)), ("ua", Truncate(userAgent, 300)), ("a", Truncate(address, 100)),
|
||||
("t", now), ("e", now + MaxLifetime)), cancellationToken).ConfigureAwait(false);
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
// Sessions over, with their address and browser, do not pile up.
|
||||
await s.ExecuteAsync("DELETE FROM sessions WHERE expires_at <= @t OR last_seen_at <= @idle", cancellationToken, ("t", now), ("idle", now - IdleTimeout)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO sessions (id, user_id, token_hash, user_agent, address, created_at, last_seen_at, expires_at) VALUES (@id, @u, @h, @ua, @a, @t, @t, @e)",
|
||||
cancellationToken, ("id", Ids.NewId(clock)), ("u", user.Id), ("h", HashToken(token)), ("ua", Truncate(userAgent, 300)), ("a", Truncate(address, 100)),
|
||||
("t", now), ("e", now + MaxLifetime)).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return (LoginResult.Ok, token);
|
||||
}
|
||||
|
||||
/// <summary>The session behind a cookie token, or null when unknown, idle too long or expired.</summary>
|
||||
public async Task<SessionInfo?> ValidateAsync(string? token, CancellationToken cancellationToken = default)
|
||||
public Task<SessionInfo?> ValidateAsync(string? token, CancellationToken cancellationToken = default) => ValidateAsync(token, refresh: true, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The session behind a cookie token, or null when unknown, idle too long or expired. Without
|
||||
/// <paramref name="refresh"/> the idle time goes on: an open page that only listens does not keep a session alive.
|
||||
/// </summary>
|
||||
public async Task<SessionInfo?> ValidateAsync(string? token, bool refresh, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
@@ -292,7 +331,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
}
|
||||
|
||||
// Refresh the idle timer at most once a minute, to keep writes rare.
|
||||
if (now - found.Seen > TimeSpan.FromMinutes(1))
|
||||
if (refresh && now - found.Seen > TimeSpan.FromMinutes(1))
|
||||
{
|
||||
await db.WriteAsync(s => s.ExecuteAsync("UPDATE sessions SET last_seen_at = @t WHERE id = @id", cancellationToken, ("t", now), ("id", found.Id)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -304,45 +343,86 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
public Task SignOutAsync(string token, CancellationToken cancellationToken = default) =>
|
||||
db.WriteAsync(s => s.ExecuteAsync("DELETE FROM sessions WHERE token_hash = @h", cancellationToken, ("h", HashToken(token))), cancellationToken);
|
||||
|
||||
/// <summary>Changes the password and ends every other session.</summary>
|
||||
public async Task<bool> ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default)
|
||||
/// <summary>
|
||||
/// A new password: every other session ends and the one that asked goes on with a new token, so a copied cookie stops
|
||||
/// working too. Wrong attempts count like those of a fresh re-authentication.
|
||||
/// </summary>
|
||||
public async Task<(AccessChange Outcome, string? Token)> ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero)
|
||||
{
|
||||
return (AccessChange.Locked, null);
|
||||
}
|
||||
|
||||
var hash = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users WHERE id = @id", r => r.Text("password_hash"), ("id", userId)), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (hash is null || !Passwords.Verify(current, hash))
|
||||
{
|
||||
return false;
|
||||
return (AccessChange.Wrong, null);
|
||||
}
|
||||
|
||||
_guards.Fresh.Succeeded(FreshAttempts);
|
||||
var replacementHash = Passwords.Hash(replacement, iterations);
|
||||
var now = clock.UtcNow;
|
||||
var token = Ids.NewToken();
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET password_hash = @h, must_change_password = @m, updated_at = @t WHERE id = @id", cancellationToken,
|
||||
("h", replacementHash), ("m", false), ("t", now), ("id", userId)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("DELETE FROM sessions WHERE user_id = @u AND id <> @keep", cancellationToken, ("u", userId), ("keep", keepSession)).ConfigureAwait(false);
|
||||
await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE sessions SET token_hash = @h WHERE id = @keep", cancellationToken, ("h", HashToken(token)), ("keep", keepSession)).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.password", "cambiata", cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
return (AccessChange.Done, token);
|
||||
}
|
||||
|
||||
/// <summary>Turns on the second factor after the user proved the app produces valid codes.</summary>
|
||||
public async Task<bool> EnableSecondFactorAsync(Guid userId, byte[] secret, string code, CancellationToken cancellationToken = default)
|
||||
private static Task<int> EndOthersAsync(DbSession s, Guid userId, Guid keepSession, CancellationToken cancellationToken) =>
|
||||
s.ExecuteAsync("DELETE FROM sessions WHERE user_id = @u AND id <> @keep", cancellationToken, ("u", userId), ("keep", keepSession));
|
||||
|
||||
/// <summary>
|
||||
/// Turns on the second factor with the password and a code that proves the app works. Never over an active one: a
|
||||
/// stolen session could put its own in place of the user's. The other sessions end.
|
||||
/// </summary>
|
||||
public async Task<AccessChange> EnableSecondFactorAsync(Guid userId, byte[] secret, string password, string code, Guid keepSession, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(secret);
|
||||
if (!AcceptCode(secret, code))
|
||||
if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero)
|
||||
{
|
||||
return false;
|
||||
return AccessChange.Locked;
|
||||
}
|
||||
|
||||
var sealedSecret = secrets.Seal("totp:" + userId.ToString("D"), Convert.ToBase64String(secret));
|
||||
await db.WriteAsync(async s =>
|
||||
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id",
|
||||
r => (Hash: r.Text("password_hash"), On: !r.IsNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false);
|
||||
if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash))
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET totp_secret = @s, updated_at = @t WHERE id = @id", cancellationToken,
|
||||
("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false);
|
||||
return AccessChange.Wrong;
|
||||
}
|
||||
|
||||
_guards.Fresh.Succeeded(FreshAttempts);
|
||||
if (user.On)
|
||||
{
|
||||
return AccessChange.AlreadyOn;
|
||||
}
|
||||
|
||||
if (!AcceptCode(secret, code))
|
||||
{
|
||||
return AccessChange.Wrong;
|
||||
}
|
||||
|
||||
var sealedSecret = secrets.Seal(SecondFactorName(userId), Convert.ToBase64String(secret));
|
||||
return await db.WriteAsync(async s =>
|
||||
{
|
||||
if (await s.ExecuteAsync("UPDATE users SET totp_secret = @s, updated_at = @t WHERE id = @id AND totp_secret IS NULL", cancellationToken,
|
||||
("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false) == 0)
|
||||
{
|
||||
return AccessChange.AlreadyOn;
|
||||
}
|
||||
|
||||
await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.second_factor", "attivato", cancellationToken).ConfigureAwait(false);
|
||||
return AccessChange.Done;
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -350,50 +430,48 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
||||
/// now whatever the session. Nothing is written. After five wrong attempts in 15 minutes every attempt fails,
|
||||
/// even with the right password, until the window has passed.
|
||||
/// </summary>
|
||||
public async Task<bool> ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default)
|
||||
public async Task<bool> ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default) =>
|
||||
await CheckFreshAsync(password, code, cancellationToken).ConfigureAwait(false) == AccessChange.Done;
|
||||
|
||||
private async Task<AccessChange> CheckFreshAsync(string password, string? code, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_fresh.Begin(FreshAttempts) > TimeSpan.Zero)
|
||||
if (_guards.Fresh.Begin(FreshAttempts) > TimeSpan.Zero)
|
||||
{
|
||||
return false;
|
||||
return AccessChange.Locked;
|
||||
}
|
||||
|
||||
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u",
|
||||
r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false);
|
||||
if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash))
|
||||
{
|
||||
return false;
|
||||
return AccessChange.Wrong;
|
||||
}
|
||||
|
||||
if (user.Totp is null || AcceptSealedCode(user.Id, user.Totp, code))
|
||||
{
|
||||
_fresh.Succeeded(FreshAttempts);
|
||||
return true;
|
||||
_guards.Fresh.Succeeded(FreshAttempts);
|
||||
return AccessChange.Done;
|
||||
}
|
||||
|
||||
return false;
|
||||
return AccessChange.Wrong;
|
||||
}
|
||||
|
||||
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
|
||||
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
|
||||
/// <summary>Turning the second factor off asks for both, the password and a code from the app, and ends the other sessions.</summary>
|
||||
public async Task<AccessChange> DisableSecondFactorAsync(Guid userId, string password, string? code, Guid keepSession, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id",
|
||||
r => (Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false);
|
||||
if (user == default || !Passwords.Verify(password, user.Hash))
|
||||
var outcome = await CheckFreshAsync(password, code, cancellationToken).ConfigureAwait(false);
|
||||
if (outcome != AccessChange.Done)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (user.Totp is not null && !AcceptSealedCode(userId, user.Totp, code))
|
||||
{
|
||||
return false;
|
||||
return outcome;
|
||||
}
|
||||
|
||||
await db.WriteAsync(async s =>
|
||||
{
|
||||
await s.ExecuteAsync("UPDATE users SET totp_secret = NULL, updated_at = @t WHERE id = @id", cancellationToken, ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false);
|
||||
await EndOthersAsync(s, userId, keepSession, cancellationToken).ConfigureAwait(false);
|
||||
await LogAsync(s, "security.second_factor", "disattivato", cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
return true;
|
||||
return AccessChange.Done;
|
||||
}
|
||||
|
||||
private Task<int> LogAsync(DbSession s, string key, string what, CancellationToken cancellationToken) =>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace Anubis.Brokers;
|
||||
|
||||
/// <summary>
|
||||
/// Clients for requests that carry a key. They follow no redirect: .NET drops only the Authorization header on the way
|
||||
/// to another host, and the keys of the brokers travel in headers of their own.
|
||||
/// </summary>
|
||||
public static class Outgoing
|
||||
{
|
||||
public static HttpMessageHandler KeyedHandler() => new SocketsHttpHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||
};
|
||||
|
||||
/// <summary>A client on <paramref name="handler"/> (the tests), or on one of its own.</summary>
|
||||
public static HttpClient KeyedClient(HttpMessageHandler? handler = null) =>
|
||||
handler is null ? new HttpClient(KeyedHandler()) : new HttpClient(handler, disposeHandler: false);
|
||||
}
|
||||
@@ -211,9 +211,17 @@ public static class Format
|
||||
int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!,
|
||||
DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset moment => moment.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture),
|
||||
_ => Convert.ToString(cell, CultureInfo.InvariantCulture) ?? "",
|
||||
_ => Harmless(Convert.ToString(cell, CultureInfo.InvariantCulture) ?? ""),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A text cell of a CSV: quoted when it must be, and never a formula. Names come from brokers and news: one that starts
|
||||
/// with = + - @ would be computed by the spreadsheet that opens the file.
|
||||
/// </summary>
|
||||
public static string CsvText(string? value) => CsvField(Harmless(value ?? ""));
|
||||
|
||||
private static string Harmless(string value) => value.Length > 1 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r' ? "'" + value : value;
|
||||
|
||||
private static string CsvField(string value) =>
|
||||
value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
@@ -387,7 +387,7 @@ public sealed partial class Scheduler(IClock clock, EventBus bus, ILogger<Schedu
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogFailed(_logger, ex, job.Name);
|
||||
Publish(JobOutcome.Failed, ex.Message);
|
||||
Publish(JobOutcome.Failed, Redactor.Redact(ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ public sealed partial class MarketDataService : IDisposable
|
||||
private readonly SecretStore _secrets;
|
||||
private readonly DataDirectory? _data;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
// For what carries a key in a header: Alpaca's data, the language model.
|
||||
private readonly HttpClient _signed;
|
||||
private readonly Func<IWebSocketTransport>? _sockets;
|
||||
private readonly ILogger _logger;
|
||||
private readonly MarketCollector _okxCollector;
|
||||
@@ -64,9 +67,14 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_sockets = sockets;
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
Offline = offline;
|
||||
_http = Client(handler, offline);
|
||||
_http.Timeout = TimeSpan.FromSeconds(60);
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||
_http = Client(handler, offline, signed: false);
|
||||
_signed = Client(handler, offline, signed: true);
|
||||
foreach (var client in new[] { _http, _signed })
|
||||
{
|
||||
client.Timeout = TimeSpan.FromSeconds(60);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||
}
|
||||
|
||||
|
||||
Okx = new OkxClient(_http, clock, okx, sockets);
|
||||
Freshness = new FreshnessMonitor(clock, bus);
|
||||
@@ -81,7 +89,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
{
|
||||
ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"),
|
||||
Watcher = new News.NewsWatcher(db, clock, settings) { EarningsActive = References.EarningsFilterActiveAsync },
|
||||
Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_http, config, key), _logger),
|
||||
Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_signed, config, key), _logger),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -161,17 +169,18 @@ public sealed partial class MarketDataService : IDisposable
|
||||
_work.Dispose();
|
||||
News.Dispose();
|
||||
_http.Dispose();
|
||||
_signed.Dispose();
|
||||
}
|
||||
|
||||
// The connection pool shared by every source; offline, only this computer's own addresses are reached.
|
||||
private static HttpClient Client(HttpMessageHandler? handler, bool offline)
|
||||
private static HttpClient Client(HttpMessageHandler? handler, bool offline, bool signed)
|
||||
{
|
||||
var owned = handler is null;
|
||||
var network = handler ?? new SocketsHttpHandler
|
||||
var network = handler ?? (signed ? Outgoing.KeyedHandler() : new SocketsHttpHandler
|
||||
{
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||
};
|
||||
});
|
||||
if (offline)
|
||||
{
|
||||
network = new Supervision.LoopbackOnlyHandler(network, owned);
|
||||
@@ -201,7 +210,7 @@ public sealed partial class MarketDataService : IDisposable
|
||||
return cached.Client;
|
||||
}
|
||||
|
||||
var client = new AlpacaClient(_http, _clock, new AlpacaCredentials(key, secret), null, _sockets);
|
||||
var client = new AlpacaClient(_signed, _clock, new AlpacaCredentials(key, secret), null, _sockets);
|
||||
_alpaca = (key, secret, client);
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,10 @@ public static class Archive
|
||||
await using var stream = new FileStream(Path.Combine(folder, file), FileMode.CreateNew, FileAccess.Write);
|
||||
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" };
|
||||
var columns = string.Join(", ", table.Columns.Select(c => c.Name));
|
||||
await s.ForEachAsync($"SELECT {columns} FROM {table.Name} ORDER BY id", async reader =>
|
||||
|
||||
// Who was signed in is of no use in another database, which ends every session anyway: it stays out of the files.
|
||||
var rows = table.Name == "sessions" ? "WHERE 1 = 0 " : "";
|
||||
await s.ForEachAsync($"SELECT {columns} FROM {table.Name} {rows}ORDER BY id", async reader =>
|
||||
{
|
||||
var row = ReadRow(reader, table, s.Engine);
|
||||
totals.Add(table, row);
|
||||
|
||||
@@ -98,7 +98,7 @@ public sealed class NotificationSender(Database db, IClock clock, Func<Cancellat
|
||||
DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
|
||||
? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
|
||||
: null;
|
||||
await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, ex.Message, cancellationToken).ConfigureAwait(false);
|
||||
await MarkAsync(item.Id, NotificationStates.Failed, attempts, next, Redactor.Redact(ex.Message), cancellationToken).ConfigureAwait(false);
|
||||
if (ex.Retryable)
|
||||
{
|
||||
// Telegram unreachable or asking to slow down: the others wait for the next pass.
|
||||
|
||||
@@ -49,7 +49,15 @@ public static class DockerPlatform
|
||||
"Imposta ANUBIS_ADMIN_PASSWORD e riavvia il container. Al primo accesso ne sceglierai una nuova; questa resta la chiave delle scelte di questa pagina."));
|
||||
}
|
||||
|
||||
else if (admin.Length < Access.Passwords.MinimumLength)
|
||||
{
|
||||
problems.Add(new("ANUBIS_ADMIN_PASSWORD", "La password iniziale è troppo corta.",
|
||||
$"Usa almeno {Access.Passwords.MinimumLength} caratteri in ANUBIS_ADMIN_PASSWORD e riavvia il container: resta la chiave delle scelte di questa pagina."));
|
||||
}
|
||||
|
||||
Redactor.Register(secret);
|
||||
Redactor.Register(Get("ANUBIS_HEARTBEAT_URL"));
|
||||
Redactor.Register(db?.UrlPassword);
|
||||
Redactor.Register(admin);
|
||||
Redactor.Register(db?.Password);
|
||||
|
||||
|
||||
@@ -33,6 +33,20 @@ public sealed record DbSettings
|
||||
/// <summary>A full PostgreSQL address (<c>ANUBIS_DB_URL</c>) that replaces the five fields.</summary>
|
||||
public string? Url { get; init; }
|
||||
|
||||
/// <summary>The password inside <see cref="Url"/>, so it can be masked; null when there is none.</summary>
|
||||
public string? UrlPassword
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Url is null || !Uri.TryCreate(Url, UriKind.Absolute, out var uri) || uri.UserInfo.IndexOf(':', StringComparison.Ordinal) is not (> 0 and var colon))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Uri.UnescapeDataString(uri.UserInfo[(colon + 1)..]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Seconds to wait for a new PostgreSQL connection. Short, so a lost server shows quickly; tests raise it.</summary>
|
||||
public int ConnectTimeoutSeconds { get; init; } = 5;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ public sealed class AlpacaTrading : IBrokerAccount
|
||||
throw new ArgumentException("Il simulatore interno non passa da Alpaca.", nameof(options));
|
||||
}
|
||||
|
||||
_http = new TradingHttp(http, clock, "Alpaca");
|
||||
_http = new TradingHttp(http, clock, "Alpaca", BrokerRequests.Alpaca);
|
||||
_clock = clock;
|
||||
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
||||
_options = options;
|
||||
|
||||
@@ -46,7 +46,7 @@ public sealed class OkxTrading : IBrokerAccount
|
||||
throw new ArgumentException("Il simulatore interno non passa da OKX.", nameof(options));
|
||||
}
|
||||
|
||||
_http = new TradingHttp(http, clock, "OKX");
|
||||
_http = new TradingHttp(http, clock, "OKX", BrokerRequests.Okx);
|
||||
_clock = clock;
|
||||
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
||||
_options = options;
|
||||
|
||||
@@ -415,7 +415,7 @@ public sealed partial class OrderManager : IDisposable
|
||||
// A real account sends only what the procedure of SPEC 12.4 allows; protection of what the bot holds always goes.
|
||||
private async Task<string?> LiveRefusalAsync(TradeIntent intent, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_account.Environment != TradingEnvironments.Live || intent.Purpose == OrderPurpose.Protective)
|
||||
if (_account.Environment != TradingEnvironments.Live || intent is { Purpose: OrderPurpose.Protective, Side: OrderSide.Sell })
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
|
||||
return RiskReasons.LiveNotConfirmed;
|
||||
}
|
||||
|
||||
if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop)
|
||||
if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop && intent.Side == OrderSide.Sell)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -11,12 +11,41 @@ public sealed record HttpAnswer(HttpStatusCode Status, string Body)
|
||||
public bool Ok => (int)Status is >= 200 and < 300;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The only requests Anubis makes to a broker with the account's keys (SPEC 9.1 point 2): what is not here is never sent,
|
||||
/// withdrawals, transfers and leverage first of all.
|
||||
/// </summary>
|
||||
public static class BrokerRequests
|
||||
{
|
||||
private static readonly HashSet<string> _okx = new(StringComparer.Ordinal)
|
||||
{
|
||||
"GET /api/v5/public/time", "GET /api/v5/account/config", "GET /api/v5/account/balance", "GET /api/v5/trade/orders-pending", "GET /api/v5/trade/orders-algo-pending",
|
||||
"GET /api/v5/trade/order", "GET /api/v5/trade/order-algo", "GET /api/v5/trade/fills", "GET /api/v5/trade/fills-history",
|
||||
"POST /api/v5/trade/order", "POST /api/v5/trade/order-algo", "POST /api/v5/trade/cancel-order", "POST /api/v5/trade/cancel-algos",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> _alpaca = new(StringComparer.Ordinal)
|
||||
{
|
||||
"GET /v2/clock", "GET /v2/account", "GET /v2/positions", "GET /v2/orders", "GET /v2/orders:by_client_order_id", "GET /v2/account/activities", "POST /v2/orders",
|
||||
};
|
||||
|
||||
public static bool Okx(HttpMethod method, string path) => _okx.Contains(method + " " + path);
|
||||
|
||||
public static bool Alpaca(HttpMethod method, string path)
|
||||
{
|
||||
const string OneOrder = "/v2/orders/";
|
||||
return _alpaca.Contains(method + " " + path) ||
|
||||
((method == HttpMethod.Get || method == HttpMethod.Delete) && path.StartsWith(OneOrder, StringComparison.Ordinal) && path.Length > OneOrder.Length &&
|
||||
path.Skip(OneOrder.Length).All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests to a broker's trading API. Reads and cancellations are retried on network errors, 429 and server
|
||||
/// errors; an order is sent once and never retried here: when its answer is lost the order manager asks the
|
||||
/// broker before sending again with the same id (SPEC 7.2). Errors never carry headers, so keys stay out of logs.
|
||||
/// </summary>
|
||||
public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName)
|
||||
public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName, Func<HttpMethod, string, bool> allowed)
|
||||
{
|
||||
public const int Attempts = 3;
|
||||
|
||||
@@ -27,6 +56,11 @@ public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName
|
||||
ArgumentNullException.ThrowIfNull(method);
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
ArgumentNullException.ThrowIfNull(headers);
|
||||
if (!allowed(method, url.AbsolutePath))
|
||||
{
|
||||
throw new InvalidOperationException($"{SourceName}: richiesta non ammessa ({method} {url.AbsolutePath}).");
|
||||
}
|
||||
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
if (limiter is not null)
|
||||
|
||||
@@ -169,7 +169,7 @@ public sealed partial class TradingService : IDisposable
|
||||
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
||||
_sockets = sockets;
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
_http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false);
|
||||
_http = Outgoing.KeyedClient(handler);
|
||||
_http.Timeout = TimeSpan.FromSeconds(30);
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||
_catalog = new InstrumentCatalog(db, clock);
|
||||
|
||||
Reference in new issue
Block a user