Close phase 0 review findings: stricter policy scans, property generator, hook
ci / test (postgres) (push) Successful in 1m24s
ci / test (sqlite) (push) Successful in 1m35s
ci / image (push) Successful in 16s
ci / test (postgres) (pull_request) Successful in 1m11s
ci / test (sqlite) (pull_request) Successful in 1m24s
ci / image (pull_request) Successful in 14s
ci / test (postgres) (push) Successful in 1m24s
ci / test (sqlite) (push) Successful in 1m35s
ci / image (push) Successful in 16s
ci / test (postgres) (pull_request) Successful in 1m11s
ci / test (sqlite) (pull_request) Successful in 1m24s
ci / image (pull_request) Successful in 14s
The independent review found that the policy tests could be bypassed: Microsoft-named direct packages and GlobalPackageReference slipped past the dependency check, the live-money scan missed the JSON, Dockerfile and Unraid template forms, the secret scan missed short project secrets but would have failed on the user's own ignored .env. The scans now read only the files git would commit and cover those cases. Also adds the fixed-seed generator for property tests, the REGISTRY variables reserved for phase 9 in the CI, a git pre-commit hook in place of the pre-commit tool (tasks hooks), the missing SPEC 4 facts in API-NOTES (Fed/ECB/BLS times, USDC depth on OKX) and the full list of today's indirect packages. refs #3 refs #5 refs #6 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b4bf864f74
commit
52550ee6d1
15 files changed
+400
-83
No files matched your search
@@ -1,6 +1,7 @@
|
||||
# Line endings: LF in the repository; shell scripts and the Dockerfile stay LF everywhere.
|
||||
* text=auto
|
||||
*.sh text eol=lf
|
||||
.githooks/* text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
@@ -48,6 +48,11 @@ jobs:
|
||||
image:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
# Registry settings for phase 9 (issue #70): declared here, not used before then.
|
||||
env:
|
||||
REGISTRY: gitea.encke-hake.ts.net
|
||||
REGISTRY_USER: ${{ github.repository_owner }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
# Project pre-commit hook (ADR 0006), in place of the pre-commit tool of SPEC 17.
|
||||
# Enable once per clone with: tasks hooks. Skip only in an emergency with: git commit --no-verify
|
||||
exec sh ./tasks.sh check
|
||||
@@ -17,10 +17,11 @@ Da `tools/Anubis.Tasks`, tramite `./tasks.ps1 <comando>` (Windows) o `sh ./tasks
|
||||
- `dev`: il server con `dotnet watch` su http://localhost:5000 (o `--urls`).
|
||||
- `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`.
|
||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||
- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`.
|
||||
|
||||
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è in `Directory.Packages.props`, nel file di blocco e in `docs/API-NOTES.md` (ADR 0004, 0006).
|
||||
Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006).
|
||||
|
||||
## Regole che, se dimenticate, fanno sbagliare
|
||||
|
||||
|
||||
+32
-9
@@ -7,7 +7,9 @@ Ogni fatto ha uno di questi esiti:
|
||||
- **cambiato**: vale in parte o non vale più; la colonna Dettaglio dice cosa è diverso;
|
||||
- **non verificabile**: le pagine pubbliche non bastano per verificarlo. Il fatto resta dietro una protezione, elencata in fondo alla pagina.
|
||||
|
||||
I fatti che riguardano strumenti abbandonati con l'ADR 0003 (`alpaca-py`, `ccxt`, `ib_async`) sono segnati **non più rilevante**.
|
||||
Sono segnati **non più rilevante**, senza essere ricontrollati, i fatti che non toccano più il progetto:
|
||||
- gli strumenti abbandonati con l'ADR 0003 (`alpaca-py`, `ccxt`, `ib_async`);
|
||||
- le fonti che la specifica esclude e Anubis non usa.
|
||||
|
||||
Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggiorna questa pagina (SPEC 4).
|
||||
|
||||
@@ -62,7 +64,10 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio
|
||||
| O13 | ccxt `myokx` 4.5.85 e le sue commissioni predefinite | non più rilevante | Client scritto in casa (ADR 0003). | — |
|
||||
| O14 | La commissione può essere trattenuta nella moneta comprata | confermato | Ogni esecuzione ha `fee`, negativa quando è un costo, e `feeCcy`. Con l'impostazione di conto `feeType` = 1 si paga nella valuta di quotazione. | https://my.okx.com/docs-v5/en/ · https://www.okx.com/en-eu/help/okx-to-introduce-spot-fee-payment-option-in-quote-currency |
|
||||
| O15 | Limiti di frequenza (dato in più, utile all'adapter) | confermato | `candles` 40 ogni 2 s per IP; `history-candles` 20 ogni 2 s; invio ordine 60 ogni 2 s; `instruments` 20 ogni 2 s; `fills` 60 ogni 2 s. | https://my.okx.com/docs-v5/en/ |
|
||||
| O16 | Alternative: Bitvavo 0,15%/0,25% senza ambiente di prova; Kraken 0,40%/0,80%, candele solo ultime 720, solo `validate=true` | confermato | `validate=true` di Kraken non ricontrollato: conta solo se l'utente cambia exchange. | https://www.bitvavo.com/en/fees · https://docs.kraken.com/api/docs/rest-api/get-ohlc-data |
|
||||
| O16 | Alternative, commissioni: Bitvavo 0,15%/0,25%; Kraken 0,40%/0,80% al livello base | confermato | Kraken applica questa tariffa dal 9/7/2026. | https://www.bitvavo.com/en/fees · https://blog.kraken.com/product/pro/new-kraken-pro-fee-tiers |
|
||||
| O16b | Kraken: candele solo le ultime 720 | confermato | — | https://docs.kraken.com/api/docs/rest-api/get-ohlc-data |
|
||||
| O16c | Bitvavo: libri in EUR più profondi, nessun ambiente di prova; Kraken: nessun ambiente di prova, solo `validate=true` | non più rilevante | Conta solo se l'utente cambia exchange: si ricontrolla in quel momento. | — |
|
||||
| O18 | Per le monete minori le coppie in USDC sono più profonde di quelle in EUR | confermato | Libri degli ordini pubblici del 10/11/2026, controvalore entro lo 0,5% dal prezzo medio. Su 12 monete su 12 (ADA, AVAX, DOGE, DOT, LINK, LTC, NEAR, ONDO, PEPE, SUI, XRP, ZEC) la coppia in USDC è più profonda; per esempio XRP circa 749.000 contro 195.000, DOT circa 11.600 contro 0. Lo spread in USDC è quasi sempre più stretto. | `GET https://eea.okx.com/api/v5/market/books?instId=XRP-USDC&sz=400` |
|
||||
| O17 | Binance non serve più i residenti italiani dal 1/7/2026; archivi pubblici con candele a 1 minuto dal 2017 | confermato | La chiusura risulta solo dalla stampa, non da una nota ufficiale di Binance. L'archivio BTCUSDT a 1 minuto va da agosto 2017 a ottobre 2026. | https://data.binance.vision/?prefix=data/spot/monthly/klines/BTCUSDT/1m/ |
|
||||
|
||||
**Cosa cambia per il codice**
|
||||
@@ -105,7 +110,10 @@ Prima di scrivere ogni adapter, si rilegge la documentazione corrente e si aggio
|
||||
| F8 | SEC EDGAR: 10 richieste al secondo, User-Agent con nome e contatto | confermato | — | https://www.sec.gov/search-filings/edgar-search-assistance/accessing-edgar-data |
|
||||
| F9 | I 14 feed RSS rispondono | confermato | Tutti e 14 rispondono con RSS valido. CoinDesk rinvia all'indirizzo senza la barra finale: si usa `https://www.coindesk.com/arc/outboundfeeds/rss`. | elenco in SPEC 4.4 |
|
||||
| F10a | CryptoPanic non ha più un piano gratuito | confermato | Piano gratuito chiuso dal 1° aprile 2026; il più economico costa 199 $ al mese. Dato da fonti secondarie: la pagina ufficiale non si legge senza JavaScript. | https://cryptopanic.com/developers/api/plans/ |
|
||||
| F10b | `yfinance`, Stooq, GDELT, API di X e Reddit da non usare | non verificabile | Non ricontrollati. Non cambia nulla: restano esclusi. | — |
|
||||
| F10b | `yfinance`, Stooq, GDELT, API di X e Reddit da non usare | non più rilevante | Fonti escluse dalla specifica: Anubis non le usa, quindi non sono state ricontrollate. | — |
|
||||
| F11 | Date FRED: orario predefinito 08:30 di New York, impatto alto | confermato | Le uscite principali del BLS escono alle 8:30 di New York: il CPI il 10/11 e il 10/12/2026, l'Employment Situation il 6/11 e il 4/12/2026. | https://www.bls.gov/schedule/news_release/cpi.htm · https://www.bls.gov/schedule/news_release/empsit.htm |
|
||||
| F12 | Fed alle 14:00 di New York | confermato | Comunicato del 28/10/2026 "for release at 2:00 p.m.". Prossima riunione 8–9 dicembre 2026. | https://www.federalreserve.gov/newsevents/pressreleases/monetary20261028a.htm · https://www.federalreserve.gov/monetarypolicy/fomccalendars.htm |
|
||||
| F13 | BCE alle 14:15, ora dell'Europa centrale | confermato | Comunicato alle 14:15, conferenza stampa alle 14:45. La BCE scrive "CET" anche con l'ora legale: in pratica è l'ora di Francoforte, quindi si usa il fuso `Europe/Berlin`. Prossima riunione 16–17 dicembre 2026. | https://www.ecb.europa.eu/press/govcdec/mopo/html/index.en.html · https://www.ecb.europa.eu/press/press_conference/html/index.en.html |
|
||||
|
||||
**Cosa cambia per il codice**
|
||||
- **F1**: l'importatore riconosce millisecondi e microsecondi.
|
||||
@@ -146,7 +154,6 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio
|
||||
| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo. | 3 |
|
||||
| O7 liquidità | Elenco fisso di coppie ammesse e filtro sullo spread prima di ogni ordine. | 3, 5 |
|
||||
| F3b limite del calendario | Una richiesta all'ora, al massimo una ogni 5 minuti anche ai riavvii; la pagina di blocco conta come errore. | 2 |
|
||||
| F10b fonti escluse | Non usate. | — |
|
||||
| M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 |
|
||||
| V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 |
|
||||
| V3 fiscalità | Esportazione CSV delle operazioni con il cambio BCE. | 3 |
|
||||
@@ -171,9 +178,27 @@ Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già
|
||||
|
||||
Il metapacchetto `MSTest` porterebbe con sé l'estensione di copertura `Microsoft.Testing.Extensions.CodeCoverage`. Quell'estensione ha una licenza Microsoft separata da accettare e dipende da `Mono.Cecil`, di terze parti. Per questo si usano i suoi pacchetti di base (ADR 0006).
|
||||
|
||||
## Dipendenze indirette di terze parti
|
||||
## Dipendenze indirette
|
||||
|
||||
I pacchetti autorizzati se ne portano dietro alcuni non pubblicati da Microsoft. L'ADR 0004 li accetta insieme al pacchetto che li richiede. Il test `DependencyPolicyTests` blocca ogni pacchetto di terze parti che compare nei file di blocco senza essere elencato qui. Quando la fase indicata aggiunge il pacchetto, il nome entra anche nell'elenco del test.
|
||||
**Oggi (Fase 0).** I file di blocco contengono solo pacchetti Microsoft e MSTest. Oltre ai tre diretti (`MSTest.TestFramework`, `MSTest.TestAdapter`, `Microsoft.NET.Test.Sdk`), il progetto dei test si porta dietro:
|
||||
|
||||
| Pacchetto | Versione | Arriva con | Nota |
|
||||
|---|---|---|---|
|
||||
| `MSTest.Analyzers` | 4.5.2 | MSTest.TestFramework | Analizzatori del codice dei test |
|
||||
| `Microsoft.Testing.Platform`, `Microsoft.Testing.Platform.MSBuild` | 2.5.2 | MSTest.TestAdapter | Piattaforma che esegue i test |
|
||||
| `Microsoft.Testing.Extensions.TrxReport.Abstractions` | 2.5.2 | MSTest.TestAdapter | Solo le interfacce del rapporto TRX |
|
||||
| `Microsoft.Testing.Extensions.Telemetry` | 2.5.2 | MSTest.TestAdapter | Telemetria della piattaforma: spenta con `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in `tasks` e nella CI |
|
||||
| `Microsoft.ApplicationInsights` | 2.23.0 | Microsoft.Testing.Extensions.Telemetry | Libreria di telemetria (MIT), non usata con la telemetria spenta |
|
||||
| `Microsoft.TestPlatform.ObjectModel`, `Microsoft.TestPlatform.TestHost` | 18.11.0 | Microsoft.NET.Test.Sdk | Esecutore `dotnet test` |
|
||||
| `Microsoft.CodeCoverage` | 18.11.0 | Microsoft.NET.Test.Sdk | Raccoglitore di copertura classico (MIT, senza dipendenze di terze parti). Arriva sempre con `Microsoft.NET.Test.Sdk`; Anubis non lo attiva |
|
||||
|
||||
Tutti sono di Microsoft, con licenza MIT. Sono solo strumenti di sviluppo e non finiscono nell'immagine né nell'applicazione.
|
||||
|
||||
**Di terze parti, in arrivo con le prossime fasi.** I pacchetti autorizzati se ne portano dietro alcuni non pubblicati da Microsoft; l'ADR 0004 li accetta insieme al pacchetto che li richiede. Il test `DependencyPolicyTests` blocca:
|
||||
- ogni pacchetto diretto fuori dall'elenco dell'ADR 0004, anche con un nome Microsoft;
|
||||
- ogni pacchetto indiretto di terze parti che non sia nel suo elenco.
|
||||
|
||||
Quando la fase indicata aggiunge il pacchetto, il nome entra nell'elenco del test. Un altro test controlla che ogni nome di quell'elenco compaia in questa tabella.
|
||||
|
||||
| Dipendenza | Di chi, licenza | Arriva con | Fase | Nota |
|
||||
|---|---|---|---|---|
|
||||
@@ -181,9 +206,7 @@ I pacchetti autorizzati se ne portano dietro alcuni non pubblicati da Microsoft.
|
||||
| `Newtonsoft.Json` 13.0.3 | James Newton-King, MIT | `Microsoft.ML`, LightGbm, FastTree | 8 | — |
|
||||
| `LightGBM` 4.6.0 | progetto microsoft/LightGBM, pubblicato a nome di Guolin Ke, MIT | `Microsoft.ML.LightGbm` | 8 | Libreria nativa; in Docker serve `libgomp1`. |
|
||||
| `Google.Protobuf` 3.30.2 | Google, BSD-3-Clause | `Microsoft.ML.Tokenizers` | 7 | — |
|
||||
| `Mono.Cecil` 0.11.6 | Jb Evain, MIT | estensione di copertura di MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||
|
||||
Nella Fase 0 i file di blocco contengono solo pacchetti Microsoft e MSTest.
|
||||
| Mono.Cecil 0.11.6 | Jb Evain, MIT | estensione di copertura del metapacchetto MSTest | — | Evitato: non si usa il metapacchetto. |
|
||||
|
||||
## Immagini Docker
|
||||
|
||||
|
||||
+11
-11
@@ -9,7 +9,7 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest
|
||||
|
||||
| Fase | Titolo | Stato |
|
||||
|---|---|---|
|
||||
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Da fare |
|
||||
| 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Completata |
|
||||
| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Da fare |
|
||||
| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Da fare |
|
||||
| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Da fare |
|
||||
@@ -31,19 +31,19 @@ Un progetto vuoto ma completo di toolchain, con i fatti sulle API ricontrollati.
|
||||
|
||||
**Lavori**
|
||||
|
||||
- [ ] [#1](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/1) Ricontrollare i fatti sulle API e scrivere API-NOTES.md
|
||||
- [ ] [#2](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/2) Struttura del repository e file di memoria del progetto
|
||||
- [ ] [#3](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/3) Toolchain .NET: analizzatori, MSTest, controllo dei pacchetti, comandi `tasks`
|
||||
- [ ] [#4](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/4) Applicazione minima con /health, Dockerfile minimo e docker-compose con PostgreSQL
|
||||
- [ ] [#5](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/5) Scheletro della CI su Gitea Actions (backend su SQLite e PostgreSQL)
|
||||
- [ ] [#6](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/6) Chiusura della fase, revisione indipendente e tag `fase-0`
|
||||
- [x] [#1](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/1) Ricontrollare i fatti sulle API e scrivere API-NOTES.md
|
||||
- [x] [#2](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/2) Struttura del repository e file di memoria del progetto
|
||||
- [x] [#3](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/3) Toolchain .NET: analizzatori, MSTest, controllo dei pacchetti, comandi `tasks`
|
||||
- [x] [#4](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/4) Applicazione minima con /health, Dockerfile minimo e docker-compose con PostgreSQL
|
||||
- [x] [#5](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/5) Scheletro della CI su Gitea Actions (backend su SQLite e PostgreSQL)
|
||||
- [x] [#6](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/6) Chiusura della fase, revisione indipendente e tag `fase-0`
|
||||
|
||||
**Criteri di accettazione**
|
||||
|
||||
- [ ] `tasks check` passa su una soluzione vuota ma completa di toolchain
|
||||
- [ ] `docker compose up` avvia l'applicazione minima, che risponde su `/health`
|
||||
- [ ] `docs/API-NOTES.md` elenca per ogni fatto della sezione 4 "confermato", "cambiato" o "non verificabile"
|
||||
- [ ] `docs/STATE.md` dice quali chiavi serviranno e da quale fase (paper Alpaca dalla Fase 2, demo OKX dalla Fase 3)
|
||||
- [x] `tasks check` passa su una soluzione vuota ma completa di toolchain
|
||||
- [x] `docker compose up` avvia l'applicazione minima, che risponde su `/health`
|
||||
- [x] `docs/API-NOTES.md` elenca per ogni fatto della sezione 4 "confermato", "cambiato" o "non verificabile"
|
||||
- [x] `docs/STATE.md` dice quali chiavi serviranno e da quale fase (paper Alpaca dalla Fase 2, demo OKX dalla Fase 3)
|
||||
|
||||
## Fase 1 — Fondamenta
|
||||
|
||||
|
||||
+4
-3
@@ -25,8 +25,9 @@ Aggiornato: 2026-11-10
|
||||
- analizzatori con avvisi trattati come errori;
|
||||
- formattazione controllata;
|
||||
- versioni centralizzate, file di blocco.
|
||||
- Comandi `tasks` (vedi `CLAUDE.md`).
|
||||
- Comandi `tasks` (vedi `CLAUDE.md`) e hook pre-commit, attivo in questa copia.
|
||||
- Test sempre attivi:
|
||||
- generatore casuale a seme fisso per i test di proprietà;
|
||||
- pacchetti ammessi;
|
||||
- nessun `ANUBIS_ALLOW_LIVE=1`;
|
||||
- nessun segreto nei file;
|
||||
@@ -47,7 +48,8 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc
|
||||
- Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006).
|
||||
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
|
||||
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
|
||||
- Esecutore delle Actions su Gitea: ESITO_RUNNER
|
||||
- Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale.
|
||||
- Su questo PC Docker Desktop non partiva: erano rimasti due file di comunicazione di una sessione di ottobre, che Windows non riusciva a cancellare. Le cartelle che li contengono sono state rinominate, non cancellate: `%LOCALAPPDATA%\Docker\run.stale*` e `%LOCALAPPDATA%\docker-secrets-engine.stale*`. Si possono eliminare dopo un riavvio.
|
||||
|
||||
## Serve dall'utente
|
||||
|
||||
@@ -56,7 +58,6 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc
|
||||
| Via libera per la Fase 1 | Subito | Non si parte |
|
||||
| Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa |
|
||||
| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa |
|
||||
| Un esecutore di Gitea Actions (runner), se si vuole la CI remota | Ora | `tasks ci` in locale |
|
||||
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
|
||||
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
|
||||
| Chiavi FRED e Finnhub (facoltative, gratuite) | Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento |
|
||||
|
||||
@@ -13,7 +13,9 @@ La Fase 0 ha preparato il progetto e ricontrollato i fatti della sezione 4 (`doc
|
||||
- `MSTest.TestAdapter`;
|
||||
- `Microsoft.NET.Test.Sdk`.
|
||||
|
||||
Niente copertura del codice per ora. Se servirà, si chiede all'utente (ADR 0004). La telemetria della piattaforma di test è spenta con `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in `tasks` e nella CI.
|
||||
Niente copertura del codice per ora. `Microsoft.NET.Test.Sdk` porta sempre con sé il raccoglitore classico `Microsoft.CodeCoverage` (Microsoft, MIT, nessuna dipendenza di terze parti): resta nel file di blocco ma non si attiva. Se servirà la copertura, si chiede all'utente (ADR 0004).
|
||||
|
||||
La piattaforma di test porta con sé la telemetria (`Microsoft.Testing.Extensions.Telemetry`, che usa `Microsoft.ApplicationInsights`). È spenta con `TESTINGPLATFORM_TELEMETRY_OPTOUT=1` in `tasks` e nella CI. L'elenco completo delle dipendenze indirette di oggi è in `docs/API-NOTES.md`.
|
||||
|
||||
**2. Test dell'applicazione senza host di prova.** `Microsoft.AspNetCore.Mvc.Testing` non è autorizzato. I test avviano il server vero su una porta locale libera (`--urls http://127.0.0.1:0`) e lo interrogano con `HttpClient`.
|
||||
|
||||
@@ -22,14 +24,20 @@ Niente copertura del codice per ora. Se servirà, si chiede all'utente (ADR 0004
|
||||
**4. Dipendenze indirette sotto controllo.**
|
||||
- I file di blocco (`packages.lock.json`) sono nel repository, e `tasks check` ripristina con `--locked-mode`.
|
||||
- `DependencyPolicyTests` fallisce se:
|
||||
- compare un pacchetto fuori dall'elenco dell'ADR 0004;
|
||||
- un progetto fissa una versione propria;
|
||||
- nei file di blocco c'è un pacchetto di terze parti non elencato in `docs/API-NOTES.md`.
|
||||
- `Directory.Packages.props` elenca un pacchetto fuori dall'elenco dell'ADR 0004, anche come `GlobalPackageReference`;
|
||||
- un `.csproj`, `.props` o `.targets` usa un pacchetto non autorizzato, o fissa una versione propria (come attributo o come elemento);
|
||||
- nei file di blocco c'è un pacchetto diretto non autorizzato. Vale anche con un nome Microsoft: EF Core e Identity, per esempio, sono esclusi;
|
||||
- nei file di blocco c'è un pacchetto indiretto di terze parti che non è nell'elenco del test;
|
||||
- un nome dell'elenco del test non compare in `docs/API-NOTES.md`.
|
||||
- I pacchetti indiretti con nome `Microsoft.*`, `System.*` o `MSTest.*` sono riservati a Microsoft su nuget.org e passano senza elenco. Restano comunque riportati in `docs/API-NOTES.md`.
|
||||
- Le dipendenze di terze parti già note (SQLitePCLRaw, Newtonsoft.Json, LightGBM, Google.Protobuf) entrano nell'elenco del test nella fase che aggiunge il pacchetto che le richiede.
|
||||
- I test sui file del repository (pacchetti, segreti, soldi veri) leggono i file che git considera: quelli tracciati e quelli nuovi non esclusi da `.gitignore`. Il `.env` locale con le chiavi dell'utente e la cartella `/data` restano fuori.
|
||||
|
||||
**5. Cartelle dei moduli.** Le cartelle di `src/Anubis` nascono con il primo codice che le riempie, così git non deve tenere cartelle vuote. La tabella in `src/Anubis/README.md` dice per ogni modulo la cartella, il namespace e la fase.
|
||||
|
||||
**6. Cambi delle API che toccano il progetto** (dettagli in `docs/API-NOTES.md`):
|
||||
**6. Hook pre-commit al posto dello strumento `pre-commit`.** La Fase 0 della SPEC 17 nomina `pre-commit`, uno strumento Python. Al suo posto c'è `.githooks/pre-commit`, uno script che esegue `tasks check`. Si attiva una volta per copia del repository con `tasks hooks` (`git config core.hooksPath .githooks`). In emergenza si salta con `git commit --no-verify`, ma la CI ripete lo stesso controllo.
|
||||
|
||||
**7. Cambi delle API che toccano il progetto** (dettagli in `docs/API-NOTES.md`):
|
||||
- **OKX, WebSocket sulla porta 443.** La 8443 è chiusa dal 31/10/2026. Gli URL si scrivono senza porta, in produzione e in demo.
|
||||
- **Alpaca, calendario e orologio.** Si parte con i `/v2` ancora attivi, dietro un'interfaccia. I `/v3` vanno usati appena i `/v2` vengono dismessi.
|
||||
- **Alpaca, conti a margine.** Alpaca non offre più conti senza margine. Il divieto di leva (SPEC 9.1) lo fa rispettare Anubis: compra solo con la liquidità propria e non va mai allo scoperto.
|
||||
@@ -39,6 +47,7 @@ Niente copertura del codice per ora. Se servirà, si chiede all'utente (ADR 0004
|
||||
## Alternative scartate
|
||||
|
||||
- **Tenere il metapacchetto `MSTest` e accettare l'estensione di copertura.** Porta una licenza in più e un pacchetto di terze parti che non serve.
|
||||
- **Lo strumento `pre-commit` di Python.** Richiederebbe Python e pacchetti esterni; uno script git fa lo stesso.
|
||||
- **Chiedere a parte il pacchetto `Microsoft.AspNetCore.Mvc.Testing`.** Il server vero su una porta libera fa la stessa prova senza componenti in più.
|
||||
- **Un'immagine Debian fatta in casa.** Bisognerebbe mantenere un'immagine propria e perdere gli aggiornamenti di sicurezza di Microsoft.
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@ using System.Xml.Linq;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>ADR 0004: only the packages the user authorised, and nothing else sneaking in.</summary>
|
||||
/// <summary>ADR 0004 and 0006: only the packages the user authorised, and nothing else sneaking in.</summary>
|
||||
[TestClass]
|
||||
public sealed class DependencyPolicyTests
|
||||
{
|
||||
/// <summary>The list of ADR 0004. Changing it needs the user's permission and a new ADR.</summary>
|
||||
/// <summary>The list of ADR 0004 as precised by ADR 0006. Changing it needs the user's permission and a new ADR.</summary>
|
||||
private static readonly HashSet<string> _authorised = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Microsoft.Data.Sqlite",
|
||||
@@ -25,17 +25,22 @@ public sealed class DependencyPolicyTests
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Third-party packages pulled in by an authorised one, each listed in docs/API-NOTES.md and
|
||||
/// reported to the user. Microsoft.* and System.* ids are reserved to Microsoft on nuget.org.
|
||||
/// Third-party packages pulled in by an authorised one. Each must also be listed in docs/API-NOTES.md
|
||||
/// and reported to the user (checked below). Microsoft.* and System.* ids are reserved to Microsoft on nuget.org.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> _knownThirdPartyTransitive = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static readonly string[] _packageElements = ["PackageReference", "GlobalPackageReference", "PackageDownload"];
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CentralVersionsListOnlyAuthorisedPackages()
|
||||
{
|
||||
var props = XDocument.Load(Path.Combine(Repo.Root.FullName, "Directory.Packages.props"));
|
||||
var listed = props.Descendants("PackageVersion").Select(e => (string)e.Attribute("Include")!).ToList();
|
||||
var listed = props.Descendants()
|
||||
.Where(e => e.Name.LocalName is "PackageVersion" or "GlobalPackageReference")
|
||||
.Select(e => (string?)e.Attribute("Include") ?? "?")
|
||||
.ToList();
|
||||
|
||||
var notAllowed = listed.Where(id => !_authorised.Contains(id)).ToList();
|
||||
Assert.IsEmpty(notAllowed, "Pacchetti non autorizzati (ADR 0004): " + string.Join(", ", notAllowed));
|
||||
@@ -45,21 +50,26 @@ public sealed class DependencyPolicyTests
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ProjectsDoNotPinVersionsOrBypassTheCentralList()
|
||||
{
|
||||
string[] msbuildExtensions = [".csproj", ".props", ".targets"];
|
||||
var problems = new List<string>();
|
||||
foreach (var project in Repo.Files().Where(f => f.Extension.Equals(".csproj", StringComparison.OrdinalIgnoreCase)))
|
||||
foreach (var file in Repo.Files().Where(f => msbuildExtensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)))
|
||||
{
|
||||
var doc = XDocument.Load(project.FullName);
|
||||
foreach (var reference in doc.Descendants("PackageReference"))
|
||||
var isCentralList = file.Name.Equals("Directory.Packages.props", StringComparison.OrdinalIgnoreCase);
|
||||
var doc = XDocument.Load(file.FullName);
|
||||
foreach (var reference in doc.Descendants().Where(e => _packageElements.Contains(e.Name.LocalName)))
|
||||
{
|
||||
var id = (string?)reference.Attribute("Include") ?? "?";
|
||||
if (reference.Attribute("Version") is not null || reference.Attribute("VersionOverride") is not null)
|
||||
{
|
||||
problems.Add($"{Repo.Relative(project)}: {id} ha una versione propria");
|
||||
}
|
||||
|
||||
var id = (string?)reference.Attribute("Include") ?? (string?)reference.Attribute("Update") ?? "?";
|
||||
if (!_authorised.Contains(id))
|
||||
{
|
||||
problems.Add($"{Repo.Relative(project)}: {id} non è autorizzato");
|
||||
problems.Add($"{Repo.Relative(file)}: {id} non è autorizzato");
|
||||
}
|
||||
|
||||
var ownVersion = reference.Attribute("Version") is not null
|
||||
|| reference.Attribute("VersionOverride") is not null
|
||||
|| reference.Elements().Any(e => e.Name.LocalName is "Version" or "VersionOverride");
|
||||
if (ownVersion && !isCentralList)
|
||||
{
|
||||
problems.Add($"{Repo.Relative(file)}: {id} ha una versione propria");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,12 +79,12 @@ public sealed class DependencyPolicyTests
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void LockFilesContainNoUnknownThirdPartyPackage()
|
||||
public void LockFilesContainOnlyAuthorisedDirectPackagesAndKnownIndirectOnes()
|
||||
{
|
||||
var lockFiles = Repo.Files().Where(f => f.Name.Equals("packages.lock.json", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
Assert.IsNotEmpty(lockFiles, "Nessun packages.lock.json: i file di blocco devono essere nel repository.");
|
||||
|
||||
var unknown = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var problems = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in lockFiles)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file.FullName));
|
||||
@@ -83,21 +93,41 @@ public sealed class DependencyPolicyTests
|
||||
foreach (var package in framework.Value.EnumerateObject())
|
||||
{
|
||||
var type = package.Value.TryGetProperty("type", out var t) ? t.GetString() : null;
|
||||
if (type == "Project")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var id = package.Name;
|
||||
if (!_authorised.Contains(id) && !IsMicrosoftId(id) && !_knownThirdPartyTransitive.Contains(id))
|
||||
switch (type)
|
||||
{
|
||||
unknown.Add($"{id} (in {Repo.Relative(file)})");
|
||||
case "Project":
|
||||
break;
|
||||
case "Direct" or "CentralTransitive":
|
||||
// Whatever a project asks for directly must be on the list, Microsoft or not.
|
||||
if (!_authorised.Contains(id))
|
||||
{
|
||||
problems.Add($"{id} diretto non autorizzato (in {Repo.Relative(file)})");
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
if (!_authorised.Contains(id) && !IsMicrosoftId(id) && !_knownThirdPartyTransitive.Contains(id))
|
||||
{
|
||||
problems.Add($"{id} indiretto di terze parti non dichiarato (in {Repo.Relative(file)})");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsEmpty(unknown, "Dipendenze di terze parti non dichiarate: " + string.Join(", ", unknown));
|
||||
Assert.IsEmpty(problems, string.Join(", ", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void KnownThirdPartyPackagesAreDocumentedInApiNotes()
|
||||
{
|
||||
var notes = File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "API-NOTES.md"));
|
||||
var missing = _knownThirdPartyTransitive.Where(id => !notes.Contains($"`{id}`", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
Assert.IsEmpty(missing, "Dipendenze di terze parti non elencate in docs/API-NOTES.md: " + string.Join(", ", missing));
|
||||
}
|
||||
|
||||
private static bool IsMicrosoftId(string id) =>
|
||||
|
||||
@@ -19,11 +19,15 @@ public sealed partial class LiveSafetyTests
|
||||
public void NoConfigurationFileEnablesRealMoney()
|
||||
{
|
||||
// Configuration-like files only: the documentation quotes the switches to forbid them.
|
||||
string[] extensions = [".toml", ".env", ".yml", ".yaml", ".json", ".xml", ".ps1", ".sh", ".props"];
|
||||
string[] extensions =
|
||||
[
|
||||
".toml", ".env", ".yml", ".yaml", ".json", ".xml", ".ps1", ".sh", ".props", ".targets", ".csproj",
|
||||
".runsettings", ".config", ".ini", ".conf",
|
||||
];
|
||||
var offenders = Repo.Files()
|
||||
.Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)
|
||||
|| f.Name.StartsWith(".env", StringComparison.OrdinalIgnoreCase)
|
||||
|| f.Name.Equals("Dockerfile", StringComparison.OrdinalIgnoreCase))
|
||||
|| f.Name.StartsWith("Dockerfile", StringComparison.OrdinalIgnoreCase))
|
||||
.Where(f => LiveSwitch().IsMatch(File.ReadAllText(f.FullName)))
|
||||
.Select(Repo.Relative)
|
||||
.ToList();
|
||||
@@ -33,15 +37,47 @@ public sealed partial class LiveSafetyTests
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void PatternRecognisesBothSwitches()
|
||||
public void PatternRecognisesBothSwitchesInEveryFormat()
|
||||
{
|
||||
Assert.IsTrue(LiveSwitch().IsMatch("ANUBIS_ALLOW_LIVE=1"));
|
||||
Assert.IsTrue(LiveSwitch().IsMatch(" ANUBIS_ALLOW_LIVE: \"1\""));
|
||||
Assert.IsTrue(LiveSwitch().IsMatch("allow_live = true"));
|
||||
Assert.IsFalse(LiveSwitch().IsMatch("ANUBIS_ALLOW_LIVE=0"));
|
||||
Assert.IsFalse(LiveSwitch().IsMatch("allow_live = false"));
|
||||
string[] active =
|
||||
[
|
||||
"ANUBIS_ALLOW_LIVE=1",
|
||||
" ANUBIS_ALLOW_LIVE: \"1\"",
|
||||
"\"ANUBIS_ALLOW_LIVE\": \"1\"",
|
||||
"\"ANUBIS_ALLOW_LIVE\": 1",
|
||||
"ENV ANUBIS_ALLOW_LIVE 1",
|
||||
"$env:ANUBIS_ALLOW_LIVE = '1'",
|
||||
"<Config Name=\"Soldi veri\" Target=\"ANUBIS_ALLOW_LIVE\" Default=\"0|1\" Type=\"Variable\">1</Config>",
|
||||
"<Config Target=\"ANUBIS_ALLOW_LIVE\" Default=\"1|0\" Type=\"Variable\">0</Config>",
|
||||
"allow_live = true",
|
||||
"\"allow_live\": true",
|
||||
];
|
||||
string[] inactive =
|
||||
[
|
||||
"ANUBIS_ALLOW_LIVE=0",
|
||||
"ANUBIS_ALLOW_LIVE: \"0\"",
|
||||
"ENV ANUBIS_ALLOW_LIVE 10",
|
||||
"<Config Name=\"Soldi veri\" Target=\"ANUBIS_ALLOW_LIVE\" Default=\"0|1\" Description=\"1: abilita\" Type=\"Variable\">0</Config>",
|
||||
"allow_live = false",
|
||||
];
|
||||
|
||||
foreach (var line in active)
|
||||
{
|
||||
Assert.IsTrue(LiveSwitch().IsMatch(line), "Non riconosciuto: " + line);
|
||||
}
|
||||
|
||||
foreach (var line in inactive)
|
||||
{
|
||||
Assert.IsFalse(LiveSwitch().IsMatch(line), "Falso allarme: " + line);
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""ANUBIS_ALLOW_LIVE\s*[:=]\s*["']?1\b|allow_live\s*=\s*true\b""", RegexOptions.IgnoreCase)]
|
||||
// Assignments (=, :, JSON, ENV with a space, PowerShell) and the Unraid template's value or default.
|
||||
[GeneratedRegex(
|
||||
"""ANUBIS_ALLOW_LIVE["']?\s*(?:[:=]|\s)\s*["']?1\b"""
|
||||
+ """|Target=["']ANUBIS_ALLOW_LIVE["'][^>]*>\s*1\s*<"""
|
||||
+ """|Target=["']ANUBIS_ALLOW_LIVE["'][^>]*\bDefault=["']1\b"""
|
||||
+ """|allow_live["']?\s*[:=]\s*["']?true\b""",
|
||||
RegexOptions.IgnoreCase)]
|
||||
private static partial Regex LiveSwitch();
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Property tests without external packages (ADR 0003, 0004): many generated cases from a fixed
|
||||
/// seed, so a failure always repeats, and a message that names the seed and the failing case.
|
||||
/// </summary>
|
||||
internal static class Property
|
||||
{
|
||||
public const int DefaultSeed = 20261110;
|
||||
public const int DefaultCases = 200;
|
||||
|
||||
public static void ForAll<T>(Func<Gen, T> generate, Action<T> property, int cases = DefaultCases, int seed = DefaultSeed)
|
||||
{
|
||||
var gen = new Gen(seed);
|
||||
for (var i = 0; i < cases; i++)
|
||||
{
|
||||
var value = generate(gen);
|
||||
try
|
||||
{
|
||||
property(value);
|
||||
}
|
||||
catch (Exception ex) when (ex is not AssertInconclusiveException)
|
||||
{
|
||||
throw new AssertFailedException(
|
||||
string.Create(CultureInfo.InvariantCulture, $"Proprietà violata al caso {i} (seme {seed}): {value}"), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fixed-seed generator based on SplitMix64. Unlike a seeded <see cref="Random"/>, its sequence is
|
||||
/// fixed by this code, so it stays the same on every platform and .NET version.
|
||||
/// </summary>
|
||||
internal sealed class Gen(int seed)
|
||||
{
|
||||
private ulong _state = unchecked((ulong)(long)seed);
|
||||
|
||||
public ulong NextUInt64()
|
||||
{
|
||||
var z = _state += 0x9E3779B97F4A7C15UL;
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
|
||||
/// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxExclusive"/>).</summary>
|
||||
public long Long(long minInclusive, long maxExclusive)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive);
|
||||
var range = unchecked((ulong)(maxExclusive - minInclusive));
|
||||
var limit = ulong.MaxValue - (ulong.MaxValue % range);
|
||||
ulong x;
|
||||
do
|
||||
{
|
||||
x = NextUInt64();
|
||||
}
|
||||
while (x >= limit);
|
||||
|
||||
return unchecked(minInclusive + (long)(x % range));
|
||||
}
|
||||
|
||||
public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive);
|
||||
|
||||
public bool Bool() => (NextUInt64() & 1UL) == 1UL;
|
||||
|
||||
/// <summary>Uniform value in [0, 1).</summary>
|
||||
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
|
||||
|
||||
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
|
||||
public decimal Decimal(decimal min, decimal max, int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18);
|
||||
|
||||
var unit = 1m;
|
||||
for (var i = 0; i < scale; i++)
|
||||
{
|
||||
unit /= 10m;
|
||||
}
|
||||
|
||||
var low = decimal.Ceiling(min / unit);
|
||||
var high = decimal.Floor(max / unit);
|
||||
if (low > high)
|
||||
{
|
||||
throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale));
|
||||
}
|
||||
|
||||
var steps = high - low;
|
||||
if (steps >= long.MaxValue)
|
||||
{
|
||||
throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale));
|
||||
}
|
||||
|
||||
var k = Long(0, (long)steps + 1);
|
||||
return (low + k) * unit;
|
||||
}
|
||||
|
||||
public T Pick<T>(IReadOnlyList<T> items)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfZero(items.Count);
|
||||
return items[Int(0, items.Count)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace Anubis.Tests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class PropertyTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Golden)]
|
||||
public void SplitMix64MatchesTheReferenceSequence()
|
||||
{
|
||||
// First output of the published SplitMix64 reference for seed 0.
|
||||
Assert.AreEqual(0xE220A8397B1DCDAFUL, new Gen(0).NextUInt64());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void SameSeedGivesTheSameSequence()
|
||||
{
|
||||
var a = new Gen(42);
|
||||
var b = new Gen(42);
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
Assert.AreEqual(a.NextUInt64(), b.NextUInt64());
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void IntegersStayInRange()
|
||||
{
|
||||
Property.ForAll(g => (Value: g.Int(-3, 4), Wide: g.Long(long.MinValue, long.MaxValue)), x =>
|
||||
{
|
||||
Assert.IsTrue(x.Value is >= -3 and < 4, x.ToString());
|
||||
Assert.AreNotEqual(long.MaxValue, x.Wide);
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DecimalsRespectBoundsAndScale()
|
||||
{
|
||||
Property.ForAll(g => g.Decimal(0.00000001m, 70000m, 8), value =>
|
||||
{
|
||||
Assert.IsTrue(value is >= 0.00000001m and <= 70000m);
|
||||
Assert.AreEqual(value, decimal.Round(value, 8));
|
||||
}, cases: 1000);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void DoublesAreInTheUnitInterval()
|
||||
{
|
||||
Property.ForAll(g => g.Double(), value => Assert.IsTrue(value is >= 0.0 and < 1.0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void FailureNamesSeedAndCase()
|
||||
{
|
||||
var error = Assert.ThrowsExactly<AssertFailedException>(() =>
|
||||
Property.ForAll(g => g.Int(0, 10), value => Assert.IsTrue(value < 5), seed: 7));
|
||||
|
||||
Assert.Contains("seme 7", error.Message);
|
||||
}
|
||||
}
|
||||
@@ -41,14 +41,30 @@ public sealed partial class SecretScanTests
|
||||
Assert.IsTrue(LooksLikeSecret("OK-ACCESS-PASSPHRASE=" + "Sup3rS3cretPass"));
|
||||
Assert.IsTrue(LooksLikeSecret("TELEGRAM_BOT_TOKEN=123456789:" + new string('A', 35)));
|
||||
Assert.IsTrue(LooksLikeSecret("api_key = \"" + "AKZXCVBNMASDFGHJKLQWERTY12" + "\""));
|
||||
Assert.IsTrue(LooksLikeSecret("ANUBIS_SECRET_KEY=" + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822c"));
|
||||
Assert.IsTrue(LooksLikeSecret("OKX_API_PASSPHRASE=" + "MyOkx2026Pass"));
|
||||
Assert.IsTrue(LooksLikeSecret("FINNHUB_API_KEY: " + "c1a2b3c4d5e6f7g8h9i0"));
|
||||
Assert.IsTrue(LooksLikeSecret("\"AlpacaSecret\": \"" + "Zx9Kq2Lm7Np4Rs8T" + "\""));
|
||||
|
||||
Assert.IsFalse(LooksLikeSecret("ANUBIS_SECRET_KEY=replace-with-random"));
|
||||
Assert.IsFalse(LooksLikeSecret("APCA-API-SECRET-KEY: <your-secret>"));
|
||||
Assert.IsFalse(LooksLikeSecret("POSTGRES_PASSWORD: anubis-dev"));
|
||||
Assert.IsFalse(LooksLikeSecret("ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev}"));
|
||||
Assert.IsFalse(LooksLikeSecret("REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}"));
|
||||
Assert.IsFalse(LooksLikeSecret("private const string SecretKeyVariable = \"ANUBIS_SECRET_KEY\";"));
|
||||
Assert.IsFalse(LooksLikeSecret("OKX_API_PASSPHRASE=<passphrase-123>"));
|
||||
}
|
||||
|
||||
private static bool LooksLikeSecret(string line) =>
|
||||
PrivateKey().IsMatch(line) || BrokerHeader().IsMatch(line) || TelegramToken().IsMatch(line) || GenericSecret().IsMatch(line);
|
||||
PrivateKey().IsMatch(line) || BrokerHeader().IsMatch(line) || TelegramToken().IsMatch(line) || GenericSecret().IsMatch(line)
|
||||
|| NamedSecret().Matches(line).Any(m => !IsPlaceholder(m.Groups["value"].Value));
|
||||
|
||||
// Example values in .env.example, compose files and the CI are clearly fake.
|
||||
private static bool IsPlaceholder(string value) =>
|
||||
value.StartsWith('$') || value.StartsWith('<')
|
||||
|| _placeholderWords.Any(word => value.Contains(word, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static readonly string[] _placeholderWords = ["replace", "change-me", "example", "your-", "dummy", "fake", "xxxx"];
|
||||
|
||||
[GeneratedRegex("-----BEGIN (RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----")]
|
||||
private static partial Regex PrivateKey();
|
||||
@@ -61,4 +77,9 @@ public sealed partial class SecretScanTests
|
||||
|
||||
[GeneratedRegex("""(?i)(api[_-]?key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?=[A-Za-z0-9/+=_\-]*\d)(?=[A-Za-z0-9/+=_\-]*[A-Za-z])[A-Za-z0-9/+=_\-]{24,}""")]
|
||||
private static partial Regex GenericSecret();
|
||||
|
||||
// Variables named like the project's secrets (…KEY, …SECRET, …TOKEN, …PASSPHRASE, …PASSWORD) with a value
|
||||
// of at least 8 characters that mixes letters and digits, as real keys and passwords do.
|
||||
[GeneratedRegex("""(?i)[A-Za-z0-9_\-]*(key|secret|token|passphrase|password)["']?\s*[:=]\s*["']?(?<value>(?=[^\s"',;#]*\d)(?=[^\s"',;#]*[A-Za-z])[^\s"',;#]{8,})""")]
|
||||
private static partial Regex NamedSecret();
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net.Sockets;
|
||||
|
||||
[assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
|
||||
@@ -32,29 +33,41 @@ internal static class Repo
|
||||
throw new InvalidOperationException("Repository root (Anubis.slnx) not found above " + AppContext.BaseDirectory);
|
||||
}
|
||||
|
||||
private static readonly string[] _skippedDirectories = ["bin", "obj", ".git", ".vs", ".claude", "artifacts", "TestResults", "publish", "screenshots"];
|
||||
private static readonly Lazy<IReadOnlyList<FileInfo>> _files = new(ListFiles);
|
||||
|
||||
/// <summary>All files of the working tree, without build output and tool folders.</summary>
|
||||
public static IEnumerable<FileInfo> Files()
|
||||
/// <summary>
|
||||
/// The files git would commit: tracked ones plus new ones that .gitignore does not exclude.
|
||||
/// The local .env, /data and build output stay out, so a key the user puts there never fails the suite.
|
||||
/// </summary>
|
||||
public static IEnumerable<FileInfo> Files() => _files.Value;
|
||||
|
||||
private static List<FileInfo> ListFiles()
|
||||
{
|
||||
var pending = new Stack<DirectoryInfo>();
|
||||
pending.Push(Root);
|
||||
while (pending.Count > 0)
|
||||
var info = new ProcessStartInfo("git")
|
||||
{
|
||||
var dir = pending.Pop();
|
||||
foreach (var sub in dir.EnumerateDirectories())
|
||||
{
|
||||
if (!_skippedDirectories.Contains(sub.Name, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
pending.Push(sub);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var file in dir.EnumerateFiles())
|
||||
{
|
||||
yield return file;
|
||||
}
|
||||
WorkingDirectory = Root.FullName,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
};
|
||||
foreach (var argument in new[] { "ls-files", "-z", "--cached", "--others", "--exclude-standard" })
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
using var process = Process.Start(info) ?? throw new InvalidOperationException("git could not be started.");
|
||||
var errors = process.StandardError.ReadToEndAsync();
|
||||
var output = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
throw new InvalidOperationException("git ls-files failed: " + errors.Result);
|
||||
}
|
||||
|
||||
return output.Split('\0', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(path => new FileInfo(Path.Combine(Root.FullName, path)))
|
||||
.Where(file => file.Exists)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public static string Relative(FileInfo file) =>
|
||||
|
||||
@@ -15,6 +15,7 @@ return command switch
|
||||
"dev" => Run("dotnet", ["watch", "--project", "src/Anubis.Server", "run", .. rest]),
|
||||
"build" => BuildImage("dev"),
|
||||
"ci" => Ci(),
|
||||
"hooks" => Step("Attivazione dell'hook pre-commit (.githooks)", "git", ["config", "core.hooksPath", ".githooks"]) ?? 0,
|
||||
"seed-demo" => NotYet("seed-demo", 1),
|
||||
"desktop-win" => NotYet("desktop-win", 10),
|
||||
_ => Help(),
|
||||
@@ -90,6 +91,7 @@ int Help()
|
||||
tasks dev avvia il server e lo riavvia a ogni modifica
|
||||
tasks build costruisce l'immagine Docker
|
||||
tasks ci come la CI: check, test su PostgreSQL, immagine
|
||||
tasks hooks attiva l'hook che esegue check prima di ogni commit
|
||||
tasks seed-demo dati dimostrativi (Fase 1)
|
||||
tasks desktop-win installatore Windows (Fase 10)
|
||||
""");
|
||||
|
||||
Reference in new issue
Block a user