feat(core): platform layer, portable database, archives and access (refs #7 #8 #9 #10 #11)

Phase 1 foundations in the Anubis library:
- Platform: startup configuration from environment variables (Docker) or
  config.toml (desktop, in-house TOML subset), data folder layout, secret key
  custody (ANUBIS_SECRET_KEY, DPAPI on Windows, restricted file elsewhere),
  installation identity and database fingerprint.
- Db: ADO.NET with Npgsql and Microsoft.Data.Sqlite, money as NUMERIC(38,18)
  or canonical text rounded to 18 decimals, UTC moments, UUIDv7 ids; numbered
  SQL migrations with type tokens and a version table; engine-independent
  export/import with count and accounting-total checks; backups keeping 14.
- Core: injectable clock, channel event bus, scheduler with fixed, interval
  and market-relative times, settings with change log, AES-GCM secrets, log
  redaction, Italian formats.
- Access: PBKDF2-SHA512 hashes, RFC 6238 TOTP, hashed session tokens,
  sign-in attempt limit.

SQLitePCLRaw (Apache-2.0) arrives with Microsoft.Data.Sqlite and is declared
in DependencyPolicyTests and API-NOTES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 11:09:42 +01:00
1 parent ffb67c9135
commit 53ca01b7c3
44 files changed
+5644 -12

No files matched your search

+246
View File
@@ -0,0 +1,246 @@
using Anubis.Core;
namespace Anubis.Tests;
[TestClass]
public sealed class CoreTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void IdsAreVersion7AndFollowTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var first = Ids.NewId(clock);
clock.Advance(TimeSpan.FromMilliseconds(5));
var second = Ids.NewId(clock);
Assert.AreEqual(7, first.Version);
Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo");
Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken());
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task ManualClockReleasesWaitersOnlyWhenMoved()
{
var clock = new ManualClock(DateTimeOffset.UnixEpoch);
var waiting = clock.WaitUntilAsync(DateTimeOffset.UnixEpoch.AddMinutes(5), CancellationToken.None);
clock.Advance(TimeSpan.FromMinutes(4));
Assert.IsFalse(waiting.IsCompleted);
clock.Advance(TimeSpan.FromMinutes(1));
await waiting.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task BusDeliversToEachSubscriberAndDropsOldestWhenFull()
{
var bus = new EventBus();
using var all = bus.Subscribe<object>();
using var small = bus.Subscribe<string>(capacity: 2);
bus.Publish("a");
bus.Publish("b");
bus.Publish("c");
bus.Publish(42);
var received = new List<string>();
while (small.TryRead(out var message))
{
received.Add(message!);
}
CollectionAssert.AreEqual(new[] { "b", "c" }, received, "un lettore lento perde i più vecchi, non blocca chi pubblica");
var count = 0;
while (all.TryRead(out _))
{
count++;
}
Assert.AreEqual(4, count);
all.Dispose();
Assert.AreEqual(1, bus.SubscriberCount);
await Task.CompletedTask.ConfigureAwait(false);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RedactorRemovesKeysSignaturesAndHeaders()
{
Redactor.Register("registered-secret-value-123");
var samples = new Dictionary<string, string>
{
["OK-ACCESS-SIGN: " + "abc123signature=="] = "abc123signature",
["APCA-API-SECRET-KEY: " + "Sk1234567890abcdef"] = "Sk1234567890abcdef",
["Authorization: Bearer " + "eyJhbGciOiJIUzI1NiJ9.payload"] = "eyJhbGciOiJIUzI1NiJ9",
["{\"api_key\": \"" + "AK12345678\"}"] = "AK12345678",
["password=" + "hunter2hunter2&x=1"] = "hunter2hunter2",
["postgres://anubis:" + "S3cretPw@db:5432/anubis"] = "S3cretPw",
["bot" + "123456789:" + "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq"] = "AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsawq",
["value registered-secret-value-123 in text"] = "registered-secret-value-123",
};
foreach (var (input, secret) in samples)
{
var output = Redactor.Redact(input);
Assert.IsFalse(output.Contains(secret, StringComparison.Ordinal), $"Segreto rimasto in: {output}");
Assert.Contains(Redactor.Mask, output);
}
Assert.AreEqual("Ordine eseguito: 2 AAPL a 259,80 $", Redactor.Redact("Ordine eseguito: 2 AAPL a 259,80 $"));
}
}
/// <summary>The scheduler with a fake calendar (issue #10): fixed times, intervals, open and close, sleeps.</summary>
[TestClass]
public sealed class SchedulerTests
{
private static readonly TimeZoneInfo _rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
private static readonly TimeZoneInfo _newYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
/// <summary>New York, 09:30–16:00 on weekdays, 13:00 close on the day after Thanksgiving 2026, closed on 3 July.</summary>
private sealed class FakeCalendar : IMarketCalendar
{
public MarketSession? SessionOn(DateOnly day)
{
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || day == new DateOnly(2026, 7, 3))
{
return null;
}
var close = day == new DateOnly(2026, 11, 27) ? new TimeOnly(13, 0) : new TimeOnly(16, 0);
return new MarketSession(day, At(day, new TimeOnly(9, 30)), At(day, close));
}
private static DateTimeOffset At(DateOnly day, TimeOnly time)
{
var local = day.ToDateTime(time);
return new DateTimeOffset(local, _newYork.GetUtcOffset(local)).ToUniversalTime();
}
}
private static DateTimeOffset Rome(int y, int mo, int d, int h, int mi)
{
var local = new DateTime(y, mo, d, h, mi, 0);
return new DateTimeOffset(local, _rome.GetUtcOffset(local));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void MarketTimesFollowTheExchangeNotItalianTime()
{
var calendar = new FakeCalendar();
var afterOpen = Schedule.Market(MarketAnchor.Open, TimeSpan.FromMinutes(5), calendar);
// Normal week: 09:35 in New York is 15:35 in Rome.
Assert.AreEqual(Rome(2026, 10, 9, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 8, 21)));
// 16 March 2026: the USA already moved to summer time, Europe not yet: 09:35 NY is 14:35 in Rome.
Assert.AreEqual(Rome(2026, 3, 16, 14, 35), afterOpen.NextAfter(Rome(2026, 3, 16, 8, 0)));
// Friday after the open: the next run is Monday.
Assert.AreEqual(Rome(2026, 10, 12, 15, 35), afterOpen.NextAfter(Rome(2026, 10, 9, 16, 0)));
// Holiday skipped (Friday 3 July): Monday 6 July.
Assert.AreEqual(Rome(2026, 7, 6, 15, 35), afterOpen.NextAfter(Rome(2026, 7, 2, 16, 0)));
// Early close: 5 minutes before a 13:00 close is 12:55 in New York, 18:55 in Rome.
var beforeClose = Schedule.Market(MarketAnchor.Close, TimeSpan.FromMinutes(-5), calendar);
Assert.AreEqual(Rome(2026, 11, 27, 18, 55), beforeClose.NextAfter(Rome(2026, 11, 27, 9, 0)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DailyAndIntervalSchedules()
{
var backup = Schedule.Daily(new TimeOnly(3, 30), _rome);
Assert.AreEqual(Rome(2026, 10, 10, 3, 30), backup.NextAfter(Rome(2026, 10, 9, 8, 21)));
// The night summer time ends (25 October 2026) 03:30 exists once, in winter time.
Assert.AreEqual(Rome(2026, 10, 25, 3, 30), backup.NextAfter(Rome(2026, 10, 24, 12, 0)));
// 02:30 does not exist on 29 March 2026 in Rome: it moves to 03:00.
var skipped = Schedule.Daily(new TimeOnly(2, 30), _rome);
Assert.AreEqual(new DateTimeOffset(2026, 3, 29, 1, 0, 0, TimeSpan.Zero), skipped.NextAfter(Rome(2026, 3, 28, 12, 0)));
var crypto = Schedule.Daily(new TimeOnly(0, 5), TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 0, 5, 0, TimeSpan.Zero), crypto.NextAfter(Rome(2026, 10, 9, 8, 21)));
var every5 = Schedule.Every(TimeSpan.FromMinutes(5));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero)));
Assert.AreEqual(new DateTimeOffset(2026, 10, 9, 6, 30, 0, TimeSpan.Zero), every5.NextAfter(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task RunsDueJobsOnceAndSkipsRunsMissedDuringASleep()
{
var clock = new ManualClock(Rome(2026, 10, 9, 8, 21));
var bus = new EventBus();
using var runs = bus.Subscribe<JobRun>();
var scheduler = new Scheduler(clock, bus);
var count = 0;
scheduler.Add(new ScheduledJob("backup", "Salvataggio", Schedule.Daily(new TimeOnly(3, 30), _rome), _ =>
{
count++;
return Task.CompletedTask;
}));
scheduler.Add(new ScheduledJob("broken", "Rotto", Schedule.Daily(new TimeOnly(3, 30), _rome), _ => throw new InvalidOperationException("guasto")));
Assert.HasCount(2, scheduler.Upcoming());
clock.Set(Rome(2026, 10, 10, 3, 30));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count, "un lavoro già eseguito non riparte");
// The computer slept two days: the 03:30 run is found late by hours and is skipped, not run blindly.
clock.Set(Rome(2026, 10, 11, 9, 0));
await scheduler.RunDueAsync(CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(1, count);
var outcomes = new List<JobRun>();
while (runs.TryRead(out var run))
{
outcomes.Add(run!);
}
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Completed));
Assert.IsTrue(outcomes.Any(r => r.Name == "backup" && r.Outcome == JobOutcome.Skipped));
Assert.IsTrue(outcomes.Any(r => r.Name == "broken" && r.Outcome == JobOutcome.Failed && r.Error == "guasto"));
Assert.AreEqual(Rome(2026, 10, 12, 3, 30), scheduler.Upcoming().Single(u => u.Name == "backup").DueUtc);
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task LoopWaitsOnTheInjectedClock()
{
var clock = new ManualClock(new DateTimeOffset(2026, 10, 9, 6, 21, 0, TimeSpan.Zero));
var scheduler = new Scheduler(clock, new EventBus());
var ran = new TaskCompletionSource();
scheduler.Add(new ScheduledJob("tick", "Prova", Schedule.Every(TimeSpan.FromMinutes(5)), _ =>
{
ran.TrySetResult();
return Task.CompletedTask;
}));
using var cts = new CancellationTokenSource();
var loop = scheduler.RunAsync(cts.Token);
await WaitUntil(() => clock.Waiting > 0).ConfigureAwait(false);
Assert.IsFalse(ran.Task.IsCompleted, "nessun lavoro prima dell'orario");
clock.Set(new DateTimeOffset(2026, 10, 9, 6, 25, 0, TimeSpan.Zero));
await ran.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
Assert.IsNotNull(scheduler.LastBeatUtc);
await cts.CancelAsync().ConfigureAwait(false);
await Assert.ThrowsAsync<OperationCanceledException>(() => loop).ConfigureAwait(false);
}
internal static async Task WaitUntil(Func<bool> condition)
{
for (var i = 0; i < 500 && !condition(); i++)
{
await Task.Delay(10).ConfigureAwait(false);
}
Assert.IsTrue(condition(), "condizione non raggiunta in tempo");
}
}