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