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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user