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
@@ -4,6 +4,9 @@
|
|||||||
# The process is the guard (SPEC 9.3, ADR 0012): it starts the engine, watches it and passes the stop on to it.
|
# The process is the guard (SPEC 9.3, ADR 0012): it starts the engine, watches it and passes the stop on to it.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
|
# What the application writes (database, backups, logs) is readable only by its own user.
|
||||||
|
umask 077
|
||||||
|
|
||||||
app="/app/Anubis.Guard.dll"
|
app="/app/Anubis.Guard.dll"
|
||||||
|
|
||||||
# A command ("docker run <immagine> db import ...") runs once and ends: without the guard, which would start it again.
|
# A command ("docker run <immagine> db import ...") runs once and ends: without the guard, which would start it again.
|
||||||
@@ -26,6 +29,14 @@ case "$uid$gid" in
|
|||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
case "$uid" in
|
||||||
|
*[!0]*) ;;
|
||||||
|
*)
|
||||||
|
echo "PUID=0 farebbe girare Anubis come amministratore: usa un utente normale (99 su Unraid)." >&2
|
||||||
|
exit 64
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
mkdir -p /data
|
mkdir -p /data
|
||||||
for folder in db models research import backups logs web-keys guard; do
|
for folder in db models research import backups logs web-keys guard; do
|
||||||
mkdir -p "/data/$folder"
|
mkdir -p "/data/$folder"
|
||||||
@@ -35,4 +46,4 @@ find /data -xdev \( ! -user "$uid" -o ! -group "$gid" \) -exec chown -h "$uid:$g
|
|||||||
chmod 700 /data
|
chmod 700 /data
|
||||||
|
|
||||||
export HOME=/tmp
|
export HOME=/tmp
|
||||||
exec setpriv --reuid="$uid" --regid="$gid" --clear-groups -- dotnet "$app" "$@"
|
exec setpriv --reuid="$uid" --regid="$gid" --clear-groups --no-new-privs -- dotnet "$app" "$@"
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
<Config Name="Soldi veri consentiti" Target="ANUBIS_ALLOW_LIVE" Default="0|1" Mode="" Description="0: il bot non può collegarsi a conti reali, qualunque cosa si faccia dall'interfaccia. 1: la procedura di conferma per i soldi veri diventa disponibile." Type="Variable" Display="advanced" Required="false" Mask="false">0</Config>
|
<Config Name="Soldi veri consentiti" Target="ANUBIS_ALLOW_LIVE" Default="0|1" Mode="" Description="0: il bot non può collegarsi a conti reali, qualunque cosa si faccia dall'interfaccia. 1: la procedura di conferma per i soldi veri diventa disponibile." Type="Variable" Display="advanced" Required="false" Mask="false">0</Config>
|
||||||
<Config Name="Telegram: token del bot" Target="TELEGRAM_BOT_TOKEN" Default="" Mode="" Description="Facoltativo: si può inserire anche dall'interfaccia. Se lo compili qui, l'interfaccia lo mostra in sola lettura." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
<Config Name="Telegram: token del bot" Target="TELEGRAM_BOT_TOKEN" Default="" Mode="" Description="Facoltativo: si può inserire anche dall'interfaccia. Se lo compili qui, l'interfaccia lo mostra in sola lettura." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
||||||
<Config Name="Telegram: chat autorizzata" Target="TELEGRAM_CHAT_ID" Default="" Mode="" Description="Facoltativo: identificativo della chat che riceve gli avvisi e può dare comandi." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
<Config Name="Telegram: chat autorizzata" Target="TELEGRAM_CHAT_ID" Default="" Mode="" Description="Facoltativo: identificativo della chat che riceve gli avvisi e può dare comandi." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
||||||
<Config Name="Segnale di vita" Target="ANUBIS_HEARTBEAT_URL" Default="" Mode="" Description="Facoltativo: indirizzo di un servizio esterno da chiamare ogni minuto, che avvisa quando il bot smette di rispondere." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
|
<Config Name="Segnale di vita" Target="ANUBIS_HEARTBEAT_URL" Default="" Mode="" Description="Facoltativo: indirizzo di un servizio esterno da chiamare ogni minuto, che avvisa quando il bot smette di rispondere." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
||||||
<Config Name="Utente (PUID)" Target="PUID" Default="99" Mode="" Description="Utente a cui va la cartella dei dati e con cui gira l'applicazione. 99 è il valore normale su Unraid." Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
|
<Config Name="Utente (PUID)" Target="PUID" Default="99" Mode="" Description="Utente a cui va la cartella dei dati e con cui gira l'applicazione. 99 è il valore normale su Unraid." Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
|
||||||
<Config Name="Gruppo (PGID)" Target="PGID" Default="100" Mode="" Description="Gruppo a cui va la cartella dei dati. 100 è il valore normale su Unraid." Type="Variable" Display="advanced" Required="false" Mask="false">100</Config>
|
<Config Name="Gruppo (PGID)" Target="PGID" Default="100" Mode="" Description="Gruppo a cui va la cartella dei dati. 100 è il valore normale su Unraid." Type="Variable" Display="advanced" Required="false" Mask="false">100</Config>
|
||||||
<Config Name="Database: indirizzo completo" Target="ANUBIS_DB_URL" Default="" Mode="" Description="Facoltativo, per casi particolari: sostituisce i campi PostgreSQL separati." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
<Config Name="Database: indirizzo completo" Target="ANUBIS_DB_URL" Default="" Mode="" Description="Facoltativo, per casi particolari: sostituisce i campi PostgreSQL separati." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ var environment = Environment.GetEnvironmentVariables().Cast<DictionaryEntry>()
|
|||||||
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
.ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
var paths = new GuardPaths(DataRoot(args, environment));
|
var paths = new GuardPaths(DataRoot(args, environment));
|
||||||
var logger = new LineLogger(Console.Out.WriteLine);
|
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 clock = SystemClock.Instance;
|
||||||
var guardian = new Guardian(paths, clock, new GuardOptions(),
|
var guardian = new Guardian(paths, clock, new GuardOptions(),
|
||||||
start => ChildEngine.Start(GuardLaunch.Dotnet(), [GuardLaunch.Server(), .. args], environment, start),
|
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.
|
// 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 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,
|
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>
|
/// <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);
|
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 TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
|
||||||
private readonly Lock _gate = new();
|
private readonly Lock _gate = new();
|
||||||
|
|
||||||
@@ -303,7 +304,7 @@ internal sealed partial class AnubisHost(
|
|||||||
var key = Config.SecretKey.GetOrCreateKey();
|
var key = Config.SecretKey.GetOrCreateKey();
|
||||||
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
|
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
|
||||||
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
|
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)
|
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
|
||||||
{
|
{
|
||||||
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
@@ -333,7 +333,7 @@
|
|||||||
<AntiforgeryToken />
|
<AntiforgeryToken />
|
||||||
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
|
||||||
<label for="@rule.Key">@definition.Label</label>
|
<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="on" selected="@(rule.Value != "off")">Accesa</option>
|
||||||
<option value="off" selected="@(rule.Value == "off")">Spenta</option>
|
<option value="off" selected="@(rule.Value == "off")">Spenta</option>
|
||||||
</select>
|
</select>
|
||||||
@@ -341,6 +341,14 @@
|
|||||||
{
|
{
|
||||||
<span class="hint">Fissato da @rule.Source: si cambia lì.</span>
|
<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)
|
else if (!Shell.IsDemo)
|
||||||
{
|
{
|
||||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||||
@@ -499,6 +507,8 @@
|
|||||||
</ol>
|
</ol>
|
||||||
<form method="post" action="/azioni/due-fattori/attiva" class="form">
|
<form method="post" action="/azioni/due-fattori/attiva" class="form">
|
||||||
<AntiforgeryToken />
|
<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>
|
<label for="codice">Codice</label>
|
||||||
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
|
<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>
|
<button class="btn" type="submit">Attiva il secondo fattore</button>
|
||||||
@@ -685,6 +695,8 @@
|
|||||||
private string? ErrorText => Errore switch
|
private string? ErrorText => Errore switch
|
||||||
{
|
{
|
||||||
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
|
"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.",
|
"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.",
|
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
|
||||||
"impostazione" => "Questa impostazione non si può cambiare così.",
|
"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 value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null);
|
||||||
var locked = value.ReadOnly || Shell.IsDemo;
|
var locked = value.ReadOnly || Shell.IsDemo;
|
||||||
var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value;
|
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;
|
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">
|
return @<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
|
||||||
<AntiforgeryToken />
|
<AntiforgeryToken />
|
||||||
@@ -737,26 +750,32 @@
|
|||||||
<label for="@id">@label</label>
|
<label for="@id">@label</label>
|
||||||
@if (definition.Allowed is { } choices)
|
@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)
|
@foreach (var choice in choices)
|
||||||
{
|
{
|
||||||
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
|
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
|
||||||
}
|
}
|
||||||
</select>
|
</select>
|
||||||
@if (!locked)
|
|
||||||
{
|
|
||||||
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
<input id="@id" name="valore" inputmode="@(decimals is null ? "text" : "decimal")" autocomplete="off" spellcheck="false" value="@shown"
|
<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)"
|
placeholder="@(key == Anubis.News.NewsModelSettings.Address.Key ? Anubis.News.NewsModelProviders.DefaultAddress(provider).ToString() : null)"
|
||||||
readonly="@locked" required="@(key != Anubis.News.NewsModelSettings.Address.Key)" />
|
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)
|
@if (value.ReadOnly)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -182,7 +182,15 @@
|
|||||||
{
|
{
|
||||||
<div class="row">
|
<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>
|
<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>
|
<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>
|
</div>
|
||||||
}
|
}
|
||||||
@@ -228,6 +236,7 @@
|
|||||||
private DateOnly _to;
|
private DateOnly _to;
|
||||||
private IReadOnlyList<string> _research = [];
|
private IReadOnlyList<string> _research = [];
|
||||||
private IReadOnlyList<CostEstimate> _costs = [];
|
private IReadOnlyList<CostEstimate> _costs = [];
|
||||||
|
private bool _anyLive;
|
||||||
private SlippageTable _table = SlippageTable.Standard;
|
private SlippageTable _table = SlippageTable.Standard;
|
||||||
|
|
||||||
[CascadingParameter]
|
[CascadingParameter]
|
||||||
@@ -248,6 +257,7 @@
|
|||||||
var costs = new CostBook(services.Db, Clock);
|
var costs = new CostBook(services.Db, Clock);
|
||||||
_costs = await costs.ListAsync(ct);
|
_costs = await costs.ListAsync(ct);
|
||||||
_table = await costs.TableAsync(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);
|
_running = _trials.Any(t => !t.IsFinished);
|
||||||
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
_family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0];
|
||||||
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime);
|
||||||
@@ -261,6 +271,9 @@
|
|||||||
_message = Errore switch
|
_message = Errore switch
|
||||||
{
|
{
|
||||||
null => null,
|
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.",
|
"stima" => "Quella stima non aspetta più una conferma.",
|
||||||
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
"motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.",
|
||||||
TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.",
|
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.",
|
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
|
||||||
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
|
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
|
||||||
"attuale" => "La password attuale non è giusta.",
|
"attuale" => "La password attuale non è giusta.",
|
||||||
|
"attesa" => "Troppi tentativi sbagliati: aspetta 15 minuti e riprova.",
|
||||||
"demo" => "Nella modalità dimostrativa la password non si cambia.",
|
"demo" => "Nella modalità dimostrativa la password non si cambia.",
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ internal static class DiagnosticsExport
|
|||||||
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
|
double? hours, DateTimeOffset? from, DateTimeOffset? to, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var end = to ?? now;
|
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)
|
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)
|
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.");
|
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);
|
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -409,6 +415,7 @@ internal static partial class Endpoints
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token);
|
||||||
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
||||||
using var settings = bus.Subscribe<SettingChanged>(16);
|
using var settings = bus.Subscribe<SettingChanged>(16);
|
||||||
using var modes = bus.Subscribe<HostChanged>(16);
|
using var modes = bus.Subscribe<HostChanged>(16);
|
||||||
@@ -418,6 +425,12 @@ internal static partial class Endpoints
|
|||||||
{
|
{
|
||||||
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
|
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 snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
|
||||||
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
|
||||||
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
|
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;
|
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;
|
var services = host.Services;
|
||||||
if (services is null)
|
if (services is null)
|
||||||
@@ -158,12 +158,18 @@ internal static partial class Forms
|
|||||||
if (wait > TimeSpan.Zero)
|
if (wait > TimeSpan.Zero)
|
||||||
{
|
{
|
||||||
var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes));
|
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)));
|
return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||||
}
|
}
|
||||||
|
|
||||||
var code = form["codice"].ToString();
|
var code = form["codice"].ToString();
|
||||||
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
|
var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
if (result is not (LoginResult.Ok or LoginResult.SecondFactorNeeded))
|
||||||
|
{
|
||||||
|
LogSignInRefused(logger, address, result.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
switch (result)
|
switch (result)
|
||||||
{
|
{
|
||||||
case LoginResult.Ok:
|
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)
|
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)
|
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"));
|
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);
|
.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)
|
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");
|
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);
|
var outcome = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["password"].ToString(), form["codice"].ToString(), session, ct)
|
||||||
if (ok)
|
.ConfigureAwait(false);
|
||||||
|
if (outcome is AccessChange.Done or AccessChange.AlreadyOn)
|
||||||
{
|
{
|
||||||
drafts.Remove(session);
|
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)
|
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);
|
var outcome = host.IsDemo ? AccessChange.Wrong : await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(),
|
||||||
return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza");
|
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 back = Back(form, "/impostazioni");
|
||||||
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
|
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"));
|
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);
|
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"));
|
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)
|
if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null)
|
||||||
{
|
{
|
||||||
return Results.Redirect(With(back, "errore", "riunioni"));
|
return Results.Redirect(With(back, "errore", "riunioni"));
|
||||||
@@ -633,9 +677,10 @@ internal static partial class Forms
|
|||||||
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
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(',', '.');
|
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
|
||||||
if (typed.Length == 0)
|
if (typed.Length == 0 || value.ReadOnly)
|
||||||
{
|
{
|
||||||
next[definition.Key] = current[definition.Key];
|
next[definition.Key] = current[definition.Key];
|
||||||
continue;
|
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>
|
/// <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"))
|
if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta"))
|
||||||
{
|
{
|
||||||
return Results.Redirect("/laboratorio?errore=motore#stime");
|
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 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);
|
var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||||
if (done && services.Trading is { } trading)
|
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.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();
|
builder.Logging.ClearProviders();
|
||||||
// Created by the container so it is disposed with the application and releases the log file.
|
// 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));
|
builder.Services.AddSingleton<ILoggerProvider>(_ => new JsonLogProvider(config.Data.Logs, clock, console: true));
|
||||||
@@ -66,12 +72,14 @@ internal static class ServerApp
|
|||||||
|
|
||||||
services.AddAuthentication(SessionAuthentication.SchemeName)
|
services.AddAuthentication(SessionAuthentication.SchemeName)
|
||||||
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(SessionAuthentication.SchemeName, null);
|
.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 =>
|
services.AddAntiforgery(o =>
|
||||||
{
|
{
|
||||||
o.Cookie.Name = "anubis_csrf";
|
o.Cookie.Name = "anubis_csrf";
|
||||||
o.Cookie.SameSite = SameSiteMode.Strict;
|
o.Cookie.SameSite = SameSiteMode.Strict;
|
||||||
o.Cookie.HttpOnly = true;
|
o.Cookie.HttpOnly = true;
|
||||||
|
o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
|
||||||
o.HeaderName = Endpoints.CsrfHeader;
|
o.HeaderName = Endpoints.CsrfHeader;
|
||||||
o.FormFieldName = "__csrf";
|
o.FormFieldName = "__csrf";
|
||||||
});
|
});
|
||||||
@@ -126,6 +134,8 @@ internal static class ServerApp
|
|||||||
private static void RegisterSecrets(StartupConfig config)
|
private static void RegisterSecrets(StartupConfig config)
|
||||||
{
|
{
|
||||||
Redactor.Register(config.Db?.Password);
|
Redactor.Register(config.Db?.Password);
|
||||||
|
Redactor.Register(config.Db?.UrlPassword);
|
||||||
|
Redactor.Register(config.HeartbeatUrl);
|
||||||
Redactor.Register(config.AdminPassword);
|
Redactor.Register(config.AdminPassword);
|
||||||
foreach (var value in config.EnvironmentKeys.Values)
|
foreach (var value in config.EnvironmentKeys.Values)
|
||||||
{
|
{
|
||||||
@@ -141,6 +151,14 @@ internal static class ServerApp
|
|||||||
headers["Referrer-Policy"] = "same-origin";
|
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'; " +
|
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'";
|
"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();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ internal sealed partial class TelegramServices : IDisposable
|
|||||||
_secrets = secrets;
|
_secrets = secrets;
|
||||||
_zone = host.Config.TimeZone;
|
_zone = host.Config.TimeZone;
|
||||||
_logger = logger;
|
_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.
|
// Longer than the wait of the commands' long polling.
|
||||||
_http.Timeout = TimeSpan.FromSeconds(60);
|
_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 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,
|
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)
|
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);
|
_failures.Remove(address);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,31 +142,21 @@ public sealed class LoginLimiter(IClock clock)
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The single user of Anubis and their sessions (SPEC 15.4). Sessions are random tokens in an HttpOnly cookie;
|
/// What stays in memory about re-authentications: the wrong attempts and the last second-factor code used. It lives as
|
||||||
/// only their SHA-256 is stored, so a copy of the database does not let anyone in.
|
/// 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>
|
/// </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";
|
private readonly Lock _gate = new();
|
||||||
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 long _lastStep = long.MinValue;
|
private long _lastStep = long.MinValue;
|
||||||
|
|
||||||
private bool AcceptCode(ReadOnlySpan<byte> secret, string? code)
|
public LoginLimiter Fresh { get; } = new(clock);
|
||||||
{
|
|
||||||
if (Totp.Match(secret, code, clock.UtcNow) is not { } step)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
lock (_stepGate)
|
/// <summary>Each second-factor code works once (RFC 6238, 5.2).</summary>
|
||||||
|
public bool AcceptStep(long step)
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
{
|
{
|
||||||
if (step <= _lastStep)
|
if (step <= _lastStep)
|
||||||
{
|
{
|
||||||
@@ -171,6 +167,39 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
|||||||
return true;
|
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");
|
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 token = Ids.NewToken();
|
||||||
var now = clock.UtcNow;
|
var now = clock.UtcNow;
|
||||||
await db.WriteAsync(s => s.ExecuteAsync(
|
await db.WriteAsync(async s =>
|
||||||
"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)),
|
// Sessions over, with their address and browser, do not pile up.
|
||||||
("t", now), ("e", now + MaxLifetime)), cancellationToken).ConfigureAwait(false);
|
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);
|
return (LoginResult.Ok, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The session behind a cookie token, or null when unknown, idle too long or expired.</summary>
|
public Task<SessionInfo?> ValidateAsync(string? token, CancellationToken cancellationToken = default) => ValidateAsync(token, refresh: true, cancellationToken);
|
||||||
public async Task<SessionInfo?> ValidateAsync(string? token, CancellationToken cancellationToken = default)
|
|
||||||
|
/// <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))
|
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.
|
// 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)
|
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);
|
.ConfigureAwait(false);
|
||||||
@@ -304,45 +343,86 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
|||||||
public Task SignOutAsync(string token, CancellationToken cancellationToken = default) =>
|
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);
|
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>
|
/// <summary>
|
||||||
public async Task<bool> ChangePasswordAsync(Guid userId, string current, string replacement, Guid keepSession, CancellationToken cancellationToken = default)
|
/// 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)
|
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);
|
.ConfigureAwait(false);
|
||||||
if (hash is null || !Passwords.Verify(current, hash))
|
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 replacementHash = Passwords.Hash(replacement, iterations);
|
||||||
var now = clock.UtcNow;
|
var now = clock.UtcNow;
|
||||||
|
var token = Ids.NewToken();
|
||||||
await db.WriteAsync(async s =>
|
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,
|
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);
|
("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);
|
await LogAsync(s, "security.password", "cambiata", cancellationToken).ConfigureAwait(false);
|
||||||
}, 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>
|
private static Task<int> EndOthersAsync(DbSession s, Guid userId, Guid keepSession, CancellationToken cancellationToken) =>
|
||||||
public async Task<bool> EnableSecondFactorAsync(Guid userId, byte[] secret, string code, CancellationToken cancellationToken = default)
|
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);
|
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));
|
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id",
|
||||||
await db.WriteAsync(async s =>
|
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,
|
return AccessChange.Wrong;
|
||||||
("s", sealedSecret), ("t", clock.UtcNow), ("id", userId)).ConfigureAwait(false);
|
}
|
||||||
|
|
||||||
|
_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);
|
await LogAsync(s, "security.second_factor", "attivato", cancellationToken).ConfigureAwait(false);
|
||||||
|
return AccessChange.Done;
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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,
|
/// 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.
|
/// even with the right password, until the window has passed.
|
||||||
/// </summary>
|
/// </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",
|
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);
|
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))
|
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))
|
if (user.Totp is null || AcceptSealedCode(user.Id, user.Totp, code))
|
||||||
{
|
{
|
||||||
_fresh.Succeeded(FreshAttempts);
|
_guards.Fresh.Succeeded(FreshAttempts);
|
||||||
return true;
|
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>
|
/// <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<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
|
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",
|
var outcome = await CheckFreshAsync(password, code, cancellationToken).ConfigureAwait(false);
|
||||||
r => (Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false);
|
if (outcome != AccessChange.Done)
|
||||||
if (user == default || !Passwords.Verify(password, user.Hash))
|
|
||||||
{
|
{
|
||||||
return false;
|
return outcome;
|
||||||
}
|
|
||||||
|
|
||||||
if (user.Totp is not null && !AcceptSealedCode(userId, user.Totp, code))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.WriteAsync(async s =>
|
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 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);
|
await LogAsync(s, "security.second_factor", "disattivato", cancellationToken).ConfigureAwait(false);
|
||||||
}, cancellationToken).ConfigureAwait(false);
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
return true;
|
return AccessChange.Done;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task<int> LogAsync(DbSession s, string key, string what, CancellationToken cancellationToken) =>
|
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)!,
|
int or long => Convert.ToString(cell, CultureInfo.InvariantCulture)!,
|
||||||
DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
DateOnly date => date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||||
DateTimeOffset moment => moment.ToString("dd/MM/yyyy HH:mm", 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) =>
|
private static string CsvField(string value) =>
|
||||||
value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : 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)
|
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
LogFailed(_logger, ex, job.Name);
|
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 SecretStore _secrets;
|
||||||
private readonly DataDirectory? _data;
|
private readonly DataDirectory? _data;
|
||||||
private readonly HttpClient _http;
|
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 Func<IWebSocketTransport>? _sockets;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private readonly MarketCollector _okxCollector;
|
private readonly MarketCollector _okxCollector;
|
||||||
@@ -64,9 +67,14 @@ public sealed partial class MarketDataService : IDisposable
|
|||||||
_sockets = sockets;
|
_sockets = sockets;
|
||||||
_logger = logger ?? NullLogger.Instance;
|
_logger = logger ?? NullLogger.Instance;
|
||||||
Offline = offline;
|
Offline = offline;
|
||||||
_http = Client(handler, offline);
|
_http = Client(handler, offline, signed: false);
|
||||||
_http.Timeout = TimeSpan.FromSeconds(60);
|
_signed = Client(handler, offline, signed: true);
|
||||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
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);
|
Okx = new OkxClient(_http, clock, okx, sockets);
|
||||||
Freshness = new FreshnessMonitor(clock, bus);
|
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"),
|
ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"),
|
||||||
Watcher = new News.NewsWatcher(db, clock, settings) { EarningsActive = References.EarningsFilterActiveAsync },
|
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();
|
_work.Dispose();
|
||||||
News.Dispose();
|
News.Dispose();
|
||||||
_http.Dispose();
|
_http.Dispose();
|
||||||
|
_signed.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
// The connection pool shared by every source; offline, only this computer's own addresses are reached.
|
// 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 owned = handler is null;
|
||||||
var network = handler ?? new SocketsHttpHandler
|
var network = handler ?? (signed ? Outgoing.KeyedHandler() : new SocketsHttpHandler
|
||||||
{
|
{
|
||||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||||
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
AutomaticDecompression = System.Net.DecompressionMethods.All,
|
||||||
};
|
});
|
||||||
if (offline)
|
if (offline)
|
||||||
{
|
{
|
||||||
network = new Supervision.LoopbackOnlyHandler(network, owned);
|
network = new Supervision.LoopbackOnlyHandler(network, owned);
|
||||||
@@ -201,7 +210,7 @@ public sealed partial class MarketDataService : IDisposable
|
|||||||
return cached.Client;
|
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);
|
_alpaca = (key, secret, client);
|
||||||
return 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 stream = new FileStream(Path.Combine(folder, file), FileMode.CreateNew, FileAccess.Write);
|
||||||
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" };
|
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { NewLine = "\n" };
|
||||||
var columns = string.Join(", ", table.Columns.Select(c => c.Name));
|
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);
|
var row = ReadRow(reader, table, s.Engine);
|
||||||
totals.Add(table, row);
|
totals.Add(table, row);
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ public sealed class NotificationSender(Database db, IClock clock, Func<Cancellat
|
|||||||
DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
|
DateTimeOffset? next = ex.Retryable && attempts < MaxAttempts
|
||||||
? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
|
? clock.UtcNow + (ex.RetryAfter is { } wait && wait > Pause(attempts) ? wait : Pause(attempts))
|
||||||
: null;
|
: 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)
|
if (ex.Retryable)
|
||||||
{
|
{
|
||||||
// Telegram unreachable or asking to slow down: the others wait for the next pass.
|
// 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."));
|
"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(secret);
|
||||||
|
Redactor.Register(Get("ANUBIS_HEARTBEAT_URL"));
|
||||||
|
Redactor.Register(db?.UrlPassword);
|
||||||
Redactor.Register(admin);
|
Redactor.Register(admin);
|
||||||
Redactor.Register(db?.Password);
|
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>
|
/// <summary>A full PostgreSQL address (<c>ANUBIS_DB_URL</c>) that replaces the five fields.</summary>
|
||||||
public string? Url { get; init; }
|
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>
|
/// <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;
|
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));
|
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;
|
_clock = clock;
|
||||||
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
||||||
_options = options;
|
_options = options;
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public sealed class OkxTrading : IBrokerAccount
|
|||||||
throw new ArgumentException("Il simulatore interno non passa da OKX.", nameof(options));
|
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;
|
_clock = clock;
|
||||||
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
_credentials = credentials ?? throw new ArgumentNullException(nameof(credentials));
|
||||||
_options = options;
|
_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.
|
// 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)
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
|
|||||||
return RiskReasons.LiveNotConfirmed;
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,12 +11,41 @@ public sealed record HttpAnswer(HttpStatusCode Status, string Body)
|
|||||||
public bool Ok => (int)Status is >= 200 and < 300;
|
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>
|
/// <summary>
|
||||||
/// Requests to a broker's trading API. Reads and cancellations are retried on network errors, 429 and server
|
/// 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
|
/// 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.
|
/// broker before sending again with the same id (SPEC 7.2). Errors never carry headers, so keys stay out of logs.
|
||||||
/// </summary>
|
/// </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;
|
public const int Attempts = 3;
|
||||||
|
|
||||||
@@ -27,6 +56,11 @@ public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName
|
|||||||
ArgumentNullException.ThrowIfNull(method);
|
ArgumentNullException.ThrowIfNull(method);
|
||||||
ArgumentNullException.ThrowIfNull(url);
|
ArgumentNullException.ThrowIfNull(url);
|
||||||
ArgumentNullException.ThrowIfNull(headers);
|
ArgumentNullException.ThrowIfNull(headers);
|
||||||
|
if (!allowed(method, url.AbsolutePath))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"{SourceName}: richiesta non ammessa ({method} {url.AbsolutePath}).");
|
||||||
|
}
|
||||||
|
|
||||||
for (var attempt = 1; ; attempt++)
|
for (var attempt = 1; ; attempt++)
|
||||||
{
|
{
|
||||||
if (limiter is not null)
|
if (limiter is not null)
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ public sealed partial class TradingService : IDisposable
|
|||||||
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
||||||
_sockets = sockets;
|
_sockets = sockets;
|
||||||
_logger = logger ?? NullLogger.Instance;
|
_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.Timeout = TimeSpan.FromSeconds(30);
|
||||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||||
_catalog = new InstrumentCatalog(db, clock);
|
_catalog = new InstrumentCatalog(db, clock);
|
||||||
|
|||||||
@@ -493,14 +493,14 @@ public sealed partial class NewsAnalystTests
|
|||||||
public async Task TheSettingsPageChangesTheModel()
|
public async Task TheSettingsPageChangesTheModel()
|
||||||
{
|
{
|
||||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
await server.SignInFirstTimeAsync();
|
var password = await server.SignInFirstTimeAsync();
|
||||||
var services = server.Host.Services!;
|
var services = server.Host.Services!;
|
||||||
var page = await server.TextAsync("/impostazioni");
|
var page = await server.TextAsync("/impostazioni");
|
||||||
StringAssert.Contains(page, "claude-haiku-5-5");
|
StringAssert.Contains(page, "claude-haiku-5-5");
|
||||||
|
|
||||||
async Task<string> Post(SettingDefinition setting, string value)
|
async Task<string> Post(SettingDefinition setting, string value)
|
||||||
{
|
{
|
||||||
using var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{setting.Key}", ("valore", value), ("ritorno", "/impostazioni#notizie"));
|
using var response = await server.PostFormAsync("/impostazioni", $"/azioni/impostazioni/{setting.Key}", ("valore", value), ("password", password), ("ritorno", "/impostazioni#notizie"));
|
||||||
return ServerHarness.Location(response);
|
return ServerHarness.Location(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -201,7 +201,7 @@ public sealed class RestoreServerTests
|
|||||||
var services = first.Host.Services!;
|
var services = first.Host.Services!;
|
||||||
var secret = Totp.NewSecret();
|
var secret = Totp.NewSecret();
|
||||||
var user = (await services.Access.GetUserAsync())!;
|
var user = (await services.Access.GetUserAsync())!;
|
||||||
Assert.IsTrue(await services.Access.EnableSecondFactorAsync(user.Id, secret, Totp.Compute(secret, DateTimeOffset.UtcNow)));
|
Assert.AreEqual(AccessChange.Done, await services.Access.EnableSecondFactorAsync(user.Id, secret, password, Totp.Compute(secret, DateTimeOffset.UtcNow), Guid.Empty));
|
||||||
await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test");
|
await services.Secrets.SetAsync("FINNHUB_API_KEY", "chiave-di-prova-1", "test");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -173,10 +173,11 @@ public sealed class RiskTests
|
|||||||
public void TheCodeCallsNoWithdrawalOrTransferEndpoint()
|
public void TheCodeCallsNoWithdrawalOrTransferEndpoint()
|
||||||
{
|
{
|
||||||
// SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form.
|
// SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form.
|
||||||
var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw",
|
var endpoint = new System.Text.RegularExpressions.Regex(
|
||||||
|
@"asset/withdrawal|asset/transfer|subaccount|asset/convert|/fiat/|/finance/|set-leverage|/transfers\b|ach_relationships|recipient_banks|/withdraw|/v1/journals|/v2/wallets",
|
||||||
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||||
var offenders = Repo.Files()
|
var offenders = Repo.Files()
|
||||||
.Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal))
|
.Where(f => f.Extension is ".cs" or ".razor" or ".js" && (Repo.Relative(f).StartsWith("src", StringComparison.Ordinal) || Repo.Relative(f).StartsWith("tools", StringComparison.Ordinal)))
|
||||||
.Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName)))
|
.Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName)))
|
||||||
.Select(Repo.Relative)
|
.Select(Repo.Relative)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|||||||
@@ -0,0 +1,396 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Anubis.Access;
|
||||||
|
using Anubis.Brokers;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.News;
|
||||||
|
using Anubis.Platform;
|
||||||
|
using Anubis.Server;
|
||||||
|
using Anubis.Trading;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Routing;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>The security review of Phase 9 as tests (issue #68, SPEC 15.4, 12.4, 9.1).</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed partial class SecurityTests
|
||||||
|
{
|
||||||
|
private static readonly string[] _open =
|
||||||
|
[
|
||||||
|
"/health", "/brand/{file}", "/assets/{file}", "/favicon.ico", "/accesso", "/primo-avvio", "/servizio", "/azioni/accesso", "/azioni/primo-avvio", "/azioni/primo-avvio/prova",
|
||||||
|
"/azioni/servizio/{choice}",
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task EveryRouteAsksForASessionAndEveryFormForItsToken()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
|
var endpoints = server.Services.GetRequiredService<EndpointDataSource>().Endpoints.OfType<RouteEndpoint>().ToList();
|
||||||
|
Assert.IsGreaterThan(60, endpoints.Count);
|
||||||
|
var open = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
var forms = new List<string>();
|
||||||
|
foreach (var e in endpoints)
|
||||||
|
{
|
||||||
|
var path = "/" + e.RoutePattern.RawText!.TrimStart('/');
|
||||||
|
if (e.Metadata.GetMetadata<IAllowAnonymous>() is not null)
|
||||||
|
{
|
||||||
|
open.Add(path);
|
||||||
|
}
|
||||||
|
else if (!path.StartsWith("/_", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
Assert.IsNotNull(e.Metadata.GetMetadata<IAuthorizeData>(), path + " does not ask for a session.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var writes = (e.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods ?? []).Any(m => m is not ("GET" or "HEAD" or "OPTIONS"));
|
||||||
|
if (writes && path.StartsWith("/azioni", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
Assert.IsTrue(e.Metadata.GetMetadata<IAntiforgeryMetadata>()?.RequiresValidation, path + " accepts a form without its token.");
|
||||||
|
forms.Add(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CollectionAssert.AreEquivalent(_open, open.ToList());
|
||||||
|
Assert.IsGreaterThan(30, forms.Count);
|
||||||
|
|
||||||
|
// And really: signed in, without the token, every form is refused.
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
foreach (var form in forms)
|
||||||
|
{
|
||||||
|
var address = Parameter().Replace(form, m => m.Value.Contains("guid", StringComparison.Ordinal) ? Guid.Empty.ToString("D") : "x");
|
||||||
|
using var content = new FormUrlEncodedContent([new("password", "x")]);
|
||||||
|
using var answer = await server.Http.PostAsync(new Uri(address, UriKind.Relative), content);
|
||||||
|
Assert.IsTrue(answer.StatusCode == HttpStatusCode.BadRequest || (answer.StatusCode == HttpStatusCode.ServiceUnavailable && open.Contains(form)) ||
|
||||||
|
(answer.StatusCode == HttpStatusCode.Redirect && form.StartsWith("/azioni/primo-avvio", StringComparison.Ordinal)), form + ": " + answer.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var unknown = await server.GetAsync("/qualcosa-che-non-esiste");
|
||||||
|
Assert.AreEqual(HttpStatusCode.NotFound, unknown.StatusCode);
|
||||||
|
server.Forget();
|
||||||
|
using var stranger = await server.GetAsync("/api/registri.zip");
|
||||||
|
Assert.AreEqual(HttpStatusCode.Unauthorized, stranger.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task PagesAreNotKeptAndLargeBodiesAreRefused()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
foreach (var path in new[] { "/", "/impostazioni", "/api/status", "/api/conti/posizioni.csv" })
|
||||||
|
{
|
||||||
|
using var page = await server.GetAsync(path);
|
||||||
|
StringAssert.Contains(page.Headers.CacheControl?.ToString(), "no-store", path);
|
||||||
|
Assert.AreEqual("", page.Headers.Server.ToString());
|
||||||
|
Assert.AreEqual("same-origin", page.Headers.GetValues("Cross-Origin-Opener-Policy").Single());
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var style = await server.GetAsync("/assets/anubis.css"))
|
||||||
|
{
|
||||||
|
Assert.IsNull(style.Headers.CacheControl);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var content = new ByteArrayContent(new byte[(1024 * 1024) + 1]) { Headers = { { "Content-Type", "application/x-www-form-urlencoded" } } })
|
||||||
|
using (var large = await server.Http.PostAsync(new Uri("/azioni/accesso", UriKind.Relative), content))
|
||||||
|
{
|
||||||
|
Assert.IsTrue(large.StatusCode is HttpStatusCode.RequestEntityTooLarge or HttpStatusCode.BadRequest, large.StatusCode.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
using var odd = await server.GetAsync("/api/diagnostica.md?ore=NaN");
|
||||||
|
Assert.AreEqual(HttpStatusCode.OK, odd.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheLiveStatusEndsWithTheSession()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
var address = new UriBuilder(server.BaseAddress) { Scheme = "ws", Path = "/ws" }.Uri;
|
||||||
|
using (var foreign = new ClientWebSocket())
|
||||||
|
{
|
||||||
|
foreign.Options.Cookies = server.Cookies;
|
||||||
|
foreign.Options.SetRequestHeader("Origin", "http://other.example");
|
||||||
|
await Assert.ThrowsAsync<WebSocketException>(() => foreign.ConnectAsync(address, CancellationToken.None));
|
||||||
|
}
|
||||||
|
|
||||||
|
using var socket = new ClientWebSocket();
|
||||||
|
socket.Options.Cookies = new CookieContainer();
|
||||||
|
socket.Options.Cookies.Add(server.Cookies.GetCookies(server.BaseAddress));
|
||||||
|
await socket.ConnectAsync(address, CancellationToken.None);
|
||||||
|
var buffer = new byte[8192];
|
||||||
|
Assert.AreEqual(WebSocketMessageType.Text, (await socket.ReceiveAsync(buffer, CancellationToken.None)).MessageType);
|
||||||
|
using (var bye = await server.PostFormAsync("/impostazioni", "/azioni/esci"))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/accesso", ServerHarness.Location(bye));
|
||||||
|
}
|
||||||
|
|
||||||
|
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||||
|
while ((await socket.ReceiveAsync(buffer, limit.Token)).MessageType != WebSocketMessageType.Close)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task WhereTheKeyOfTheModelGoesIsDecidedWithThePassword()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||||
|
var password = await server.SignInFirstTimeAsync();
|
||||||
|
var settings = server.Host.Services!.Settings;
|
||||||
|
await server.Host.Services.Secrets.SetAsync(NewsModelSettings.KeySecret, "chiave-del-modello-1", "test");
|
||||||
|
const string action = "/azioni/impostazioni/";
|
||||||
|
async Task<string> Save(string key, string value, string? with)
|
||||||
|
{
|
||||||
|
using var answer = await server.PostFormAsync("/impostazioni", action + key, ("ritorno", "/impostazioni"), ("valore", value), ("password", with ?? ""));
|
||||||
|
return ServerHarness.Location(answer);
|
||||||
|
}
|
||||||
|
|
||||||
|
StringAssert.Contains(await Save(NewsModelSettings.Address.Key, "https://collector.example/", null), "errore=password-rischio");
|
||||||
|
StringAssert.Contains(await Save(NewsModelSettings.Provider.Key, NewsModelProviders.OpenAi, "wrong-password-1"), "errore=password-rischio");
|
||||||
|
Assert.AreEqual("", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value);
|
||||||
|
Assert.AreEqual(NewsModelProviders.Anthropic, (await settings.GetAsync(NewsModelSettings.Provider.Key)).Value);
|
||||||
|
Assert.AreEqual("/impostazioni", await Save(NewsModelSettings.Address.Key, "https://models.example/", password));
|
||||||
|
Assert.AreEqual("https://models.example/", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value);
|
||||||
|
|
||||||
|
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
|
||||||
|
foreach (var key in NewsModelSettings.All.Concat(NewsRuleSettings.All).Select(d => d.Key))
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "off" }) };
|
||||||
|
request.Headers.Add(csrf!["header"], csrf["token"]);
|
||||||
|
using var put = await server.Http.SendAsync(request);
|
||||||
|
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode, key);
|
||||||
|
StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task WithRealMoneyARuleGoesOffOnlyWithThePhraseAndThePassword()
|
||||||
|
{
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
|
||||||
|
var password = await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
async Task<string> Switch(SettingDefinition rule, string value, params (string, string)[] more)
|
||||||
|
{
|
||||||
|
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + rule.Key, [("ritorno", "/impostazioni"), ("valore", value), .. more]);
|
||||||
|
return ServerHarness.Location(answer);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Macro, "off"), "Without real money a switch is a switch.");
|
||||||
|
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'"));
|
||||||
|
Assert.IsTrue(await new StageBook(services.Db, server.Host.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)).AnyLiveAsync(null, CancellationToken.None));
|
||||||
|
StringAssert.Contains(await server.TextAsync("/impostazioni"), "per spegnere la regola servono la frase e la password");
|
||||||
|
StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off"), "errore=frase-rischio");
|
||||||
|
StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio");
|
||||||
|
Assert.AreEqual("on", (await services.Settings.GetAsync(NewsRuleSettings.Severe.Key)).Value);
|
||||||
|
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", password)));
|
||||||
|
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "on"), "Back on is always free.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task NoPageAndNoDownloadShowsASecret()
|
||||||
|
{
|
||||||
|
const string heartbeat = "http://192.168.0.9/ping/segreto-del-segnale-1";
|
||||||
|
var env = ServerHarness.DockerSqlite();
|
||||||
|
env["FRED_API_KEY"] = "segreto-fred-ambiente-1";
|
||||||
|
env["ANUBIS_HEARTBEAT_URL"] = heartbeat;
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", env, trading: true);
|
||||||
|
var password = await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
var values = new List<string> { "segreto-fred-ambiente-1", heartbeat, ServerHarness.SecretKey, ServerHarness.AdminPassword, password };
|
||||||
|
foreach (var (name, i) in TradingService.KeyFields(Venues.Okx).Concat(TradingService.KeyFields(Venues.Alpaca)).Select(k => k.Name)
|
||||||
|
.Concat([NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "TELEGRAM_BOT_TOKEN"]).Select((n, i) => (n, i)))
|
||||||
|
{
|
||||||
|
values.Add("segreto-salvato-" + i);
|
||||||
|
await services.Secrets.SetAsync(name, "segreto-salvato-" + i, "test");
|
||||||
|
}
|
||||||
|
|
||||||
|
var hash = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users", r => r.Text("password_hash")));
|
||||||
|
values.Add(hash!);
|
||||||
|
var paths = server.Services.GetRequiredService<EndpointDataSource>().Endpoints.OfType<RouteEndpoint>()
|
||||||
|
.Where(e => e.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods.Contains("GET") != false)
|
||||||
|
.Select(e => "/" + e.RoutePattern.RawText!.TrimStart('/'))
|
||||||
|
.Where(p => !p.Contains('{', StringComparison.Ordinal) && !p.StartsWith("/_", StringComparison.Ordinal) && p != "/ws")
|
||||||
|
.Concat(["/api/secrets/OKX_API_KEY_DEMO", "/api/secrets/FRED_API_KEY", "/operazioni?pagina=1", "/api/data/quality?format=md&days=30"])
|
||||||
|
.Distinct().ToList();
|
||||||
|
Assert.IsGreaterThan(25, paths.Count);
|
||||||
|
foreach (var path in paths)
|
||||||
|
{
|
||||||
|
using var answer = await server.GetAsync(path);
|
||||||
|
var text = path.EndsWith(".zip", StringComparison.Ordinal) ? await UnzipAsync(answer) : WebUtility.HtmlDecode(await answer.Content.ReadAsStringAsync());
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), path + " shows " + value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The archive carries the keys encrypted, and nobody's session.
|
||||||
|
var folder = TempFolder.Create("archive-secrets");
|
||||||
|
var archive = Path.Combine(folder, "a");
|
||||||
|
await Archive.ExportAsync(services.Db, archive, server.Host.Clock);
|
||||||
|
foreach (var file in Directory.EnumerateFiles(archive))
|
||||||
|
{
|
||||||
|
var text = await File.ReadAllTextAsync(file);
|
||||||
|
foreach (var value in values.Where(v => v != hash))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(0L, new FileInfo(Path.Combine(archive, "sessions.jsonl")).Length);
|
||||||
|
TempFolder.Delete(folder);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<string> UnzipAsync(HttpResponseMessage answer)
|
||||||
|
{
|
||||||
|
using var zip = new System.IO.Compression.ZipArchive(await answer.Content.ReadAsStreamAsync());
|
||||||
|
var text = new StringBuilder();
|
||||||
|
foreach (var entry in zip.Entries)
|
||||||
|
{
|
||||||
|
using var reader = new StreamReader(await entry.OpenAsync());
|
||||||
|
text.Append(await reader.ReadToEndAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
return text.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AKeyNeverFollowsARedirect()
|
||||||
|
{
|
||||||
|
var builder = WebApplication.CreateSlimBuilder();
|
||||||
|
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||||
|
await using var other = builder.Build();
|
||||||
|
var reached = 0;
|
||||||
|
other.MapFallback(() => Interlocked.Increment(ref reached));
|
||||||
|
await other.StartAsync();
|
||||||
|
var target = other.Urls.Single();
|
||||||
|
|
||||||
|
builder = WebApplication.CreateSlimBuilder();
|
||||||
|
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||||
|
await using var broker = builder.Build();
|
||||||
|
broker.MapFallback((HttpContext c) => Results.Redirect(target + c.Request.Path, permanent: false, preserveMethod: true));
|
||||||
|
await broker.StartAsync();
|
||||||
|
var address = new Uri(broker.Urls.Single());
|
||||||
|
|
||||||
|
using var http = Outgoing.KeyedClient();
|
||||||
|
var trading = new TradingHttp(http, SystemClock.Instance, "prova", (_, _) => true);
|
||||||
|
Dictionary<string, string> headers = new() { ["APCA-API-SECRET-KEY"] = "segreto", ["OK-ACCESS-KEY"] = "chiave" };
|
||||||
|
var answer = await trading.SendAsync(HttpMethod.Post, new Uri(address, "/v2/orders"), "{}", _ => headers, null, retry: false, CancellationToken.None);
|
||||||
|
Assert.IsFalse(answer.Ok);
|
||||||
|
await Assert.ThrowsAsync<MarketDataException>(() => new ApiHttp(http, SystemClock.Instance, "prova").GetBytesAsync(new Uri(address, "/v2/bars"), null, headers, CancellationToken.None));
|
||||||
|
var reply = await new LanguageModel(http, new NewsModelConfig(NewsModelProviders.Anthropic, "m", address, 0m, 0m, 0m), "segreto")
|
||||||
|
.AskAsync(new ModelRequest("i", "m", [], 10), CancellationToken.None);
|
||||||
|
Assert.IsNull(reply.Text);
|
||||||
|
Assert.AreEqual(0, reached, "The other host must never be reached.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
|
||||||
|
[DataRow("POST", "/api/v5/asset/trans" + "fer")]
|
||||||
|
[DataRow("POST", "/api/v5/account/set-" + "leverage")]
|
||||||
|
[DataRow("POST", "/api/v5/trade/amend-order")]
|
||||||
|
[DataRow("GET", "/api/v5/asset/balances")]
|
||||||
|
[DataRow("POST", "/v2/wal" + "lets/transfers")]
|
||||||
|
[DataRow("POST", "/v1/journals")]
|
||||||
|
[DataRow("DELETE", "/v2/positions")]
|
||||||
|
[DataRow("DELETE", "/v2/orders")]
|
||||||
|
[DataRow("DELETE", "/v2/orders/")]
|
||||||
|
[DataRow("DELETE", "/v2/orders/a/../../positions")]
|
||||||
|
[DataRow("PATCH", "/v2/account/configurations")]
|
||||||
|
public async Task WhatIsNotInTheListIsNeverSent(string method, string path)
|
||||||
|
{
|
||||||
|
var verb = new HttpMethod(method);
|
||||||
|
Assert.IsFalse(BrokerRequests.Okx(verb, path));
|
||||||
|
Assert.IsFalse(BrokerRequests.Alpaca(verb, path));
|
||||||
|
using var http = new FakeHttp();
|
||||||
|
var trading = new TradingHttp(http.Client(), SystemClock.Instance, "prova", BrokerRequests.Alpaca);
|
||||||
|
await Assert.ThrowsAsync<InvalidOperationException>(() => trading.SendAsync(verb, new Uri("https://example.test" + path), null, _ => new Dictionary<string, string>(), null,
|
||||||
|
retry: false, CancellationToken.None));
|
||||||
|
Assert.IsEmpty(http.Requests);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheAccountsAreOpenedInTwoPlacesOnlyAndBothAskForTheConsent()
|
||||||
|
{
|
||||||
|
var code = Repo.Files().Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)).ToList();
|
||||||
|
var openers = code.Where(f => Opener().IsMatch(File.ReadAllText(f.FullName))).Select(f => f.Name).ToList();
|
||||||
|
CollectionAssert.AreEquivalent(new[] { "TradingService.cs", "GuardBrokers.cs" }, openers);
|
||||||
|
foreach (var name in new[] { "OkxTrading.cs", "AlpacaTrading.cs" })
|
||||||
|
{
|
||||||
|
StringAssert.Contains(File.ReadAllText(code.Single(f => f.Name == name).FullName), "LiveGuard.Ensure(options.Environment, consent);");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheContainerIsHardened()
|
||||||
|
{
|
||||||
|
var entry = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "docker", "entrypoint.sh"));
|
||||||
|
StringAssert.Contains(entry, "umask 077");
|
||||||
|
StringAssert.Contains(entry, "--no-new-privs");
|
||||||
|
StringAssert.Contains(entry, "PUID=0");
|
||||||
|
var template = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis.xml"));
|
||||||
|
foreach (var name in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_HEARTBEAT_URL", "ANUBIS_DB_URL" })
|
||||||
|
{
|
||||||
|
StringAssert.Matches(template, new Regex("Target=\"" + name + "\"[^>]*Mask=\"true\""), name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AShortFirstPasswordIsAProblemOfTheConfiguration()
|
||||||
|
{
|
||||||
|
var env = ServerHarness.DockerSqlite();
|
||||||
|
env["ANUBIS_ADMIN_PASSWORD"] = "corta-1";
|
||||||
|
var config = DockerPlatform.Load(env);
|
||||||
|
Assert.AreEqual("ANUBIS_ADMIN_PASSWORD", config.Problems.Single().Setting);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ThePasswordInsideTheAddressIsMasked()
|
||||||
|
{
|
||||||
|
Assert.AreEqual("se:gre/to", new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis:se%3Agre%2Fto@db:5432/anubis" }.UrlPassword);
|
||||||
|
Assert.IsNull(new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis@db/anubis" }.UrlPassword);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ACellOfACsvIsNeverAFormula()
|
||||||
|
{
|
||||||
|
Assert.AreEqual("'=1+1", Format.CsvText("=1+1"));
|
||||||
|
Assert.AreEqual("'+cmd", Format.CsvText("+cmd"));
|
||||||
|
Assert.AreEqual("'-x", Format.CsvText("-x"));
|
||||||
|
Assert.AreEqual("'@y", Format.CsvText("@y"));
|
||||||
|
Assert.AreEqual("'\tz", Format.CsvText("\tz"));
|
||||||
|
Assert.AreEqual("\"a;b\"", Format.CsvText("a;b"));
|
||||||
|
Assert.AreEqual("\"a \"\"b\"\"\"", Format.CsvText("a \"b\""));
|
||||||
|
Assert.AreEqual("\"'\rx\"", Format.CsvText("\rx"));
|
||||||
|
Assert.AreEqual("-", Format.CsvText("-"));
|
||||||
|
Assert.AreEqual("", Format.CsvText(null));
|
||||||
|
var csv = Encoding.UTF8.GetString(Format.Csv(["a", "b"], [["=1", -5.3m]]));
|
||||||
|
StringAssert.Contains(csv, "'=1;-5,3");
|
||||||
|
}
|
||||||
|
|
||||||
|
[GeneratedRegex(@"\{[^}]*\}")]
|
||||||
|
private static partial Regex Parameter();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"new (OkxTrading|AlpacaTrading)\(")]
|
||||||
|
private static partial Regex Opener();
|
||||||
|
}
|
||||||
@@ -35,6 +35,17 @@ internal sealed partial class ServerHarness : IAsyncDisposable
|
|||||||
|
|
||||||
public Uri BaseAddress => Http.BaseAddress!;
|
public Uri BaseAddress => Http.BaseAddress!;
|
||||||
|
|
||||||
|
internal IServiceProvider Services => _app.Services;
|
||||||
|
|
||||||
|
/// <summary>The browser loses its cookies.</summary>
|
||||||
|
public void Forget()
|
||||||
|
{
|
||||||
|
foreach (Cookie cookie in Cookies.GetAllCookies())
|
||||||
|
{
|
||||||
|
cookie.Expired = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal AnubisHost Host => _app.Services.GetRequiredService<AnubisHost>();
|
internal AnubisHost Host => _app.Services.GetRequiredService<AnubisHost>();
|
||||||
|
|
||||||
/// <summary>Docker configuration with SQLite in the data folder: what most tests need.</summary>
|
/// <summary>Docker configuration with SQLite in the data folder: what most tests need.</summary>
|
||||||
|
|||||||
@@ -265,15 +265,26 @@ public sealed class AccessTests
|
|||||||
|
|
||||||
// Second session, then a password change ends every other session.
|
// Second session, then a password change ends every other session.
|
||||||
var (_, other) = await access.SignInAsync("initial-pass-1", null, null, null).ConfigureAwait(false);
|
var (_, other) = await access.SignInAsync("initial-pass-1", null, null, null).ConfigureAwait(false);
|
||||||
Assert.IsTrue(await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false));
|
var stolen = token;
|
||||||
|
(var changed, token) = await access.ChangePasswordAsync(session.User.Id, "initial-pass-1", "una password nuova", session.Id).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(AccessChange.Done, changed);
|
||||||
|
Assert.IsNull(await access.ValidateAsync(stolen).ConfigureAwait(false), "A copy of the cookie stops working too.");
|
||||||
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
|
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
|
||||||
Assert.IsNull(await access.ValidateAsync(other).ConfigureAwait(false));
|
Assert.IsNull(await access.ValidateAsync(other).ConfigureAwait(false));
|
||||||
Assert.IsFalse((await access.ValidateAsync(token).ConfigureAwait(false))!.User.MustChangePassword);
|
Assert.IsFalse((await access.ValidateAsync(token).ConfigureAwait(false))!.User.MustChangePassword);
|
||||||
|
|
||||||
// Second factor.
|
// Second factor.
|
||||||
var secret = Totp.NewSecret();
|
var secret = Totp.NewSecret();
|
||||||
Assert.IsFalse(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false));
|
var (_, elsewhere) = await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false);
|
||||||
Assert.IsTrue(await access.EnableSecondFactorAsync(session.User.Id, secret, Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
Task<AccessChange> EnableAsync(byte[] with, string password, string number) => access.EnableSecondFactorAsync(session.User.Id, with, password, number, session.Id);
|
||||||
|
Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow.AddMinutes(10))).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(AccessChange.Wrong, await EnableAsync(secret, "not the password", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false), "A session alone is not enough.");
|
||||||
|
Assert.IsNotNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(AccessChange.Done, await EnableAsync(secret, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
||||||
|
Assert.IsNull(await access.ValidateAsync(elsewhere).ConfigureAwait(false), "The other sessions signed in without the factor: they end.");
|
||||||
|
Assert.IsNotNull(await access.ValidateAsync(token).ConfigureAwait(false));
|
||||||
|
var draft = Totp.NewSecret();
|
||||||
|
Assert.AreEqual(AccessChange.AlreadyOn, await EnableAsync(draft, "una password nuova", Totp.Compute(draft, clock.UtcNow)).ConfigureAwait(false), "Never over an active one.");
|
||||||
Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result);
|
Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result);
|
||||||
var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10));
|
var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10));
|
||||||
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result);
|
Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result);
|
||||||
@@ -287,8 +298,8 @@ public sealed class AccessTests
|
|||||||
|
|
||||||
// Switching it off asks for the password and a fresh code.
|
// Switching it off asks for the password and a fresh code.
|
||||||
clock.Advance(TimeSpan.FromSeconds(30));
|
clock.Advance(TimeSpan.FromSeconds(30));
|
||||||
Assert.IsFalse(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null).ConfigureAwait(false));
|
Assert.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null, session.Id).ConfigureAwait(false));
|
||||||
Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false));
|
Assert.AreEqual(AccessChange.Done, await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow), session.Id).ConfigureAwait(false));
|
||||||
|
|
||||||
// Idle and absolute timeouts.
|
// Idle and absolute timeouts.
|
||||||
clock.Advance(AccessStore.IdleTimeout);
|
clock.Advance(AccessStore.IdleTimeout);
|
||||||
@@ -318,4 +329,73 @@ public sealed class AccessTests
|
|||||||
clock.Advance(LoginLimiter.Window);
|
clock.Advance(LoginLimiter.Window);
|
||||||
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task EveryCheckOfThePasswordSharesOneLimitThatTheServicesCannotClear()
|
||||||
|
{
|
||||||
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
||||||
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||||
|
var guards = new AccessGuards(clock);
|
||||||
|
AccessStore Started() => new(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000, guards);
|
||||||
|
var access = Started();
|
||||||
|
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
||||||
|
var user = (await access.GetUserAsync().ConfigureAwait(false))!.Id;
|
||||||
|
var secret = Totp.NewSecret();
|
||||||
|
|
||||||
|
Assert.AreEqual(AccessChange.Wrong, (await access.ChangePasswordAsync(user, "sbagliata-1", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
||||||
|
Assert.AreEqual(AccessChange.Wrong, await access.DisableSecondFactorAsync(user, "sbagliata-2", null, Guid.Empty).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(AccessChange.Wrong, await access.EnableSecondFactorAsync(user, secret, "sbagliata-3", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
||||||
|
Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-4", null).ConfigureAwait(false), "The services start again, the count goes on.");
|
||||||
|
Assert.IsFalse(await Started().ReauthenticateAsync("sbagliata-5", null).ConfigureAwait(false));
|
||||||
|
|
||||||
|
access = Started();
|
||||||
|
Assert.AreEqual(AccessChange.Locked, (await access.ChangePasswordAsync(user, "password-giusta", "una password nuova", Guid.Empty).ConfigureAwait(false)).Outcome);
|
||||||
|
Assert.AreEqual(AccessChange.Locked, await access.DisableSecondFactorAsync(user, "password-giusta", null, Guid.Empty).ConfigureAwait(false));
|
||||||
|
Assert.AreEqual(AccessChange.Locked, await access.EnableSecondFactorAsync(user, secret, "password-giusta", Totp.Compute(secret, clock.UtcNow), Guid.Empty).ConfigureAwait(false));
|
||||||
|
clock.Advance(LoginLimiter.Window);
|
||||||
|
var code = Totp.Compute(secret, clock.UtcNow);
|
||||||
|
Assert.AreEqual(AccessChange.Done, await access.EnableSecondFactorAsync(user, secret, "password-giusta", code, Guid.Empty).ConfigureAwait(false));
|
||||||
|
Assert.IsFalse(await Started().ReauthenticateAsync("password-giusta", code).ConfigureAwait(false), "A code used once stays used after the services start again.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task EndedSessionsAreRemovedAtTheNextSignIn()
|
||||||
|
{
|
||||||
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
||||||
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||||
|
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
|
||||||
|
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
||||||
|
var (_, listening) = await access.SignInAsync("password-giusta", null, "browser", "10.0.0.1").ConfigureAwait(false);
|
||||||
|
for (var i = 0; i < 12; i++)
|
||||||
|
{
|
||||||
|
Assert.IsNotNull(await access.ValidateAsync(listening, refresh: false).ConfigureAwait(false));
|
||||||
|
clock.Advance(TimeSpan.FromHours(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsNull(await access.ValidateAsync(listening).ConfigureAwait(false), "Listening does not keep a session alive.");
|
||||||
|
await access.SignInAsync("password-giusta", null, null, null).ConfigureAwait(false);
|
||||||
|
Assert.AreEqual(1L, await test.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions")).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void SuccessfulSignInsDoNotFillTheOverallCount()
|
||||||
|
{
|
||||||
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 30, 9, 0, 0, TimeSpan.Zero));
|
||||||
|
var limiter = new LoginLimiter(clock);
|
||||||
|
for (var i = 0; i < 3 * LoginLimiter.Overall; i++)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.1"));
|
||||||
|
limiter.Succeeded("10.0.0.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < LoginLimiter.Overall; i++)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.1." + i));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsGreaterThan(TimeSpan.Zero, limiter.Begin("10.0.0.9"), "Twenty failures, from anywhere, still stop everyone.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user