tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Sign the results of the remote cache
- Commit
1f15223395527a9004f82e495654e6564dc89bad- Author
- Leitwolf11 ·
- Parents
31c075e71177
Changes
.github/workflows/ci.yml | 7 + CHANGELOG.md | 5 + Directory.Packages.props | 1 + THIRD-PARTY-NOTICES.md | 1 + docs/commands.md | 1 + docs/project-files.md | 4 +- docs/remote-cache.md | 40 +++- src/Progmasoft.Tazel/Cache/CacheKeys.cs | 238 ++++++++++++++++++++++ src/Progmasoft.Tazel/Cache/RemoteActions.cs | 118 ++++++++++- src/Progmasoft.Tazel/Cache/RemoteCache.cs | 3 + src/Progmasoft.Tazel/Cli/CommandLine.cs | 23 ++- src/Progmasoft.Tazel/Cli/Commands.cs | 45 +++- src/Progmasoft.Tazel/Cli/Help.cs | 9 + src/Progmasoft.Tazel/Output/ErrorCodes.cs | 7 + src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 1 + src/Progmasoft.Tazel/Program.cs | 6 + tests/Progmasoft.Tazel.Tests/CacheSigningTests.cs | 161 +++++++++++++++ 17 files changed, 643 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 171e4cb..df7383b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,6 +121,13 @@ jobs: dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed --filter-class Progmasoft.Tazel.Tests.BuildCommandTests + - name: Test CacheSigningTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.CacheSigningTests + - name: Test CommandLineTests (macOS) if: runner.os == 'macOS' timeout-minutes: 10 diff --git a/CHANGELOG.md b/CHANGELOG.md index 89a0d15..fd53866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ ## Unreleased +- Signed remote cache results: `PublicKey` and `SigningKey` of `Remote.From`, written as `ed25519:`, `rsa-4096:` or + `ml-dsa-65:` and the key in base64. Writers sign each result; readers take only results signed with their key's + algorithm and verified by it. `tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa]` makes a pair; a key Tazel + cannot read is `error[E0505]`. + - A remote cache: `Cache.Remote` takes results of actions from a cache that speaks Bazel's HTTP protocol, such as bazel-remote, and gives it the results of actions run here. Keys do not depend on where the module is; headers a compiler found are checked by digest before a result is taken, and every file by its SHA-256. A cache that cannot diff --git a/Directory.Packages.props b/Directory.Packages.props index c015251..b6a5579 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,6 +7,7 @@ </PropertyGroup> <ItemGroup> <PackageVersion Include="Spectre.Console" Version="0.57.2" /> + <PackageVersion Include="BouncyCastle.Cryptography" Version="2.7.0" /> <PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.12.0" /> <PackageVersion Include="NuGet.Versioning" Version="8.0.0" /> <PackageVersion Include="Microsoft.Z3" Version="4.12.2" /> diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 9560b09..946fda9 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -12,6 +12,7 @@ Tazel ships with the libraries below. Their licenses are in [LICENSES/](LICENSES | [Roslyn](https://github.com/dotnet/roslyn): Microsoft.CodeAnalysis.CSharp.Scripting and its assemblies | MIT | Copyright (c) .NET Foundation and Contributors | | [NuGet.Versioning](https://github.com/NuGet/NuGet.Client) | Apache-2.0 | Copyright (c) .NET Foundation and Contributors | | [Lzma.Net](https://github.com/zcsizmadia/Lzma.Net) | 0BSD | Copyright (c) 2026 Zoltan Csizmadia | +| [BouncyCastle.Cryptography](https://github.com/bcgit/bc-csharp) | MIT | Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. | The libraries that only build and test Tazel (xUnit, CsCheck, Snapshooter, Coverlet, BenchmarkDotNet, SharpFuzz, DocFX) are not part of what is shipped. diff --git a/docs/commands.md b/docs/commands.md index ba72db0..09bdbcf 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -16,6 +16,7 @@ | `tazel vendor` | copies the modules of Tazel Portal Modules and their indexes into `vendor/` | | `tazel portal-modules search\|info [-e] [--] <module\|group:module>` | searches Tazel Portal Modules, or shows one module | | `tazel clean [--expunge]` | removes the outputs, the test logs and zig's cache; `--expunge` removes all of `.tazel` | +| `tazel cache keygen [--algorithm ed25519\|rsa-4096\|ml-dsa]` | prints a key pair for signing the results of a remote cache ([Remote cache](remote-cache.md)) | | `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` | | `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory | | `tazel version`, `tazel help [command] [--long]` | print the version, or what Tazel or one command does | diff --git a/docs/project-files.md b/docs/project-files.md index 146d9ff..692cfc1 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -54,8 +54,8 @@ toolchains = Toolchains.Define("//toolchains:clang"); Its public targets are `@name//dir:x`. `Module.From`, a module of Tazel Portal Modules, is refused by this Tazel, which fetches nothing. - `plugins` loads local plugin archives ([Plugins](plugins.md)). -- `Cache.Remote` is a remote cache ([Remote cache](remote-cache.md)). This Tazel reads the `PublicKey` and - `SigningKey` of it, `Execution.Remote` and `Execution.Memory` and says, as a warning, that it does not act on them. +- `Cache.Remote` is a remote cache, with its `PublicKey` and `SigningKey` ([Remote cache](remote-cache.md)). This + Tazel reads `Execution.Remote` and `Execution.Memory` and says, as a warning, that it does not act on them. ## BUILD.csx diff --git a/docs/remote-cache.md b/docs/remote-cache.md index eace3ec..e61d39f 100644 --- a/docs/remote-cache.md +++ b/docs/remote-cache.md @@ -46,8 +46,40 @@ outside the module is refused. Steps of plugins run in Tazel itself and are neve A cache that cannot be reached, or answers with an error, is said once as a warning, and the build goes on without it. A build never fails because of its remote cache. -## What it does not do +## Signed results -The results are not signed: whoever may write to the cache decides what readers take. Give `Write` and its token only -to machines you trust, such as the builds of the default branch. `PublicKey` and `SigningKey` are read and not acted -on. +Without keys, whoever may write to the cache decides what readers take. With keys, readers take only what the holder +of the signing key wrote: + +```text +tazel cache keygen # ed25519 +tazel cache keygen --algorithm=rsa-4096 +tazel cache keygen --algorithm=ml-dsa # ML-DSA-65, FIPS 204 +``` + +```cs +using System; + +cache = Cache.Define(new() { + Remote = Remote.From("https://cache.example.com", new() { + Write = Environment.GetEnvironmentVariable("CI") == "true", + Token = Environment.GetEnvironmentVariable("TAZEL_CACHE_TOKEN"), + PublicKey = "ed25519:…", // every reader + SigningKey = Environment.GetEnvironmentVariable("TAZEL_CACHE_SIGNING_KEY") // the writers only + }) +}); +``` + +- A key says its algorithm: `ed25519:`, `rsa-4096:` or `ml-dsa-65:`, then the key in base64. Nothing else chooses + it. A key Tazel cannot read stops the build with `error[E0505]`. +- With a `SigningKey`, each result written gets one more file, its signature record: the algorithm and the signature + of the action's key and of the result's other files. Ed25519 and ML-DSA-65 come from BouncyCastle, RSA-4096 is + RSA-PSS with SHA-256 from .NET. +- With a `PublicKey`, a result is taken only when its record names the algorithm of that key and the key verifies + its signature. An unsigned result, one signed by another key, and one signed with another algorithm are not taken; + that is said once as a warning, and the actions run here. +- Writing with a `PublicKey` and no `SigningKey` is said as a warning: no reader that trusts the key takes what such a + build writes. + +The public key belongs in `MODULE.csx`. Keep the signing key as a secret of the machines that write, such as the CI of +the default branch. diff --git a/src/Progmasoft.Tazel/Cache/CacheKeys.cs b/src/Progmasoft.Tazel/Cache/CacheKeys.cs new file mode 100644 index 0000000..a051f82 --- /dev/null +++ b/src/Progmasoft.Tazel/Cache/CacheKeys.cs @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Security.Cryptography; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Signers; +using Org.BouncyCastle.Security; + +namespace Progmasoft.Tazel.Cache; + +/// <summary>The algorithms that sign the results of a remote cache.</summary> +internal enum SigningAlgorithm +{ + /// <summary>Ed25519 (RFC 8032).</summary> + Ed25519, + + /// <summary>RSA with a 4096-bit modulus, RSA-PSS with SHA-256.</summary> + Rsa4096, + + /// <summary>ML-DSA-65 (FIPS 204).</summary> + MlDsa65, +} + +/// <summary> +/// A key of a remote cache, written as <c>algorithm:base64</c>: <c>ed25519:</c>, <c>rsa-4096:</c> or <c>ml-dsa-65:</c>. +/// </summary> +/// <remarks> +/// A public key is the raw 32 bytes for Ed25519, the SubjectPublicKeyInfo for RSA and the encoded key for ML-DSA-65; a +/// signing key is the 32-byte seed for Ed25519 and ML-DSA-65 and the PKCS #8 key for RSA. Ed25519 and ML-DSA come +/// from BouncyCastle, the same on every host; RSA from the base class library. +/// </remarks> +internal sealed class CacheKey +{ + private CacheKey(SigningAlgorithm algorithm, byte[] bytes, bool isSigning) + { + Algorithm = algorithm; + Bytes = bytes; + IsSigning = isSigning; + } + + public SigningAlgorithm Algorithm { get; } + + public bool IsSigning { get; } + + private byte[] Bytes { get; } + + /// <summary>The name of <paramref name="algorithm"/> as keys and signatures write it.</summary> + public static string NameOf(SigningAlgorithm algorithm) => algorithm switch + { + SigningAlgorithm.Ed25519 => "ed25519", + SigningAlgorithm.Rsa4096 => "rsa-4096", + _ => "ml-dsa-65", + }; + + /// <summary>The algorithm named <paramref name="name"/>, or null.</summary> + public static SigningAlgorithm? AlgorithmNamed(string name) => name switch + { + "ed25519" => SigningAlgorithm.Ed25519, + "rsa-4096" => SigningAlgorithm.Rsa4096, + "ml-dsa-65" => SigningAlgorithm.MlDsa65, + _ => null, + }; + + /// <summary>Reads a public key; <paramref name="what"/> names it in an error.</summary> + public static CacheKey ParsePublic(string text, string what) => Parse(text, what, isSigning: false); + + /// <summary>Reads a signing key; <paramref name="what"/> names it in an error.</summary> + public static CacheKey ParseSigning(string text, string what) => Parse(text, what, isSigning: true); + + /// <summary>A new key pair of <paramref name="algorithm"/>, as text.</summary> + public static (string PublicKey, string SigningKey) Generate(SigningAlgorithm algorithm) + { + var name = NameOf(algorithm) + ":"; + switch (algorithm) + { + case SigningAlgorithm.Ed25519: + { + var signing = new Ed25519PrivateKeyParameters(new SecureRandom()); + return (name + Convert.ToBase64String(signing.GeneratePublicKey().GetEncoded()), + name + Convert.ToBase64String(signing.GetEncoded())); + } + case SigningAlgorithm.Rsa4096: + { + using var rsa = RSA.Create(4096); + return (name + Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo()), + name + Convert.ToBase64String(rsa.ExportPkcs8PrivateKey())); + } + default: + { + var generator = new MLDsaKeyPairGenerator(); + generator.Init(new MLDsaKeyGenerationParameters(new SecureRandom(), MLDsaParameters.ml_dsa_65)); + var pair = generator.GenerateKeyPair(); + return (name + Convert.ToBase64String(((MLDsaPublicKeyParameters)pair.Public).GetEncoded()), + name + Convert.ToBase64String(((MLDsaPrivateKeyParameters)pair.Private).GetSeed())); + } + } + } + + /// <summary>The signature of <paramref name="message"/>; this must be a signing key.</summary> + public byte[] Sign(byte[] message) + { + ArgumentNullException.ThrowIfNull(message); + if (!IsSigning) + { + throw new InvalidOperationException("a public key does not sign"); + } + + switch (Algorithm) + { + case SigningAlgorithm.Ed25519: + { + var signer = new Ed25519Signer(); + signer.Init(true, new Ed25519PrivateKeyParameters(Bytes)); + signer.BlockUpdate(message, 0, message.Length); + return signer.GenerateSignature(); + } + case SigningAlgorithm.Rsa4096: + { + using var rsa = RSA.Create(); + rsa.ImportPkcs8PrivateKey(Bytes, out _); + return rsa.SignData(message, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + default: + { + var signer = new MLDsaSigner(MLDsaParameters.ml_dsa_65, deterministic: false); + signer.Init(true, MLDsaPrivateKeyParameters.FromSeed(MLDsaParameters.ml_dsa_65, Bytes)); + signer.BlockUpdate(message, 0, message.Length); + return signer.GenerateSignature(); + } + } + } + + /// <summary>Whether <paramref name="signature"/> is this public key's signature of <paramref name="message"/>.</summary> + public bool Verify(byte[] message, byte[] signature) + { + ArgumentNullException.ThrowIfNull(message); + ArgumentNullException.ThrowIfNull(signature); + try + { + return Algorithm switch + { + SigningAlgorithm.Ed25519 => VerifyEd25519(message, signature), + SigningAlgorithm.Rsa4096 => VerifyRsa(message, signature), + _ => VerifyMlDsa(message, signature), + }; + } + catch (CryptographicException) + { + return false; + } + } + + private bool VerifyEd25519(byte[] message, byte[] signature) + { + var verifier = new Ed25519Signer(); + verifier.Init(false, new Ed25519PublicKeyParameters(Bytes)); + verifier.BlockUpdate(message, 0, message.Length); + return verifier.VerifySignature(signature); + } + + private bool VerifyRsa(byte[] message, byte[] signature) + { + using var rsa = RSA.Create(); + rsa.ImportSubjectPublicKeyInfo(Bytes, out _); + return rsa.VerifyData(message, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); + } + + private bool VerifyMlDsa(byte[] message, byte[] signature) + { + var verifier = new MLDsaSigner(MLDsaParameters.ml_dsa_65, deterministic: false); + verifier.Init(false, MLDsaPublicKeyParameters.FromEncoding(MLDsaParameters.ml_dsa_65, Bytes)); + verifier.BlockUpdate(message, 0, message.Length); + return verifier.VerifySignature(signature); + } + + private static CacheKey Parse(string text, string what, bool isSigning) + { + ArgumentNullException.ThrowIfNull(text); + var colon = text.IndexOf(':', StringComparison.Ordinal); + if (colon < 0 || AlgorithmNamed(text[..colon]) is not { } algorithm) + { + throw new FormatException($"{what} does not start with ed25519:, rsa-4096: or ml-dsa-65:"); + } + + byte[] bytes; + try + { + bytes = Convert.FromBase64String(text[(colon + 1)..].Trim()); + } + catch (FormatException) + { + throw new FormatException($"{what} is not base64 after {text[..colon]}:"); + } + + var key = new CacheKey(algorithm, bytes, isSigning); + if (!key.HasItsLength()) + { + throw new FormatException($"{what} is not a {(isSigning ? "signing" : "public")} key of {text[..colon]}"); + } + + return key; + } + + /// <summary>Whether the bytes can be a key of this kind: the sizes of Ed25519 and ML-DSA-65, and a 4096-bit RSA key.</summary> + private bool HasItsLength() + { + try + { + switch (Algorithm) + { + case SigningAlgorithm.Ed25519: + return Bytes.Length == 32; + case SigningAlgorithm.MlDsa65: + return IsSigning ? Bytes.Length == 32 : Bytes.Length == 1952; + default: + { + using var rsa = RSA.Create(); + if (IsSigning) + { + rsa.ImportPkcs8PrivateKey(Bytes, out _); + } + else + { + rsa.ImportSubjectPublicKeyInfo(Bytes, out _); + } + + return rsa.KeySize == 4096; + } + } + } + catch (CryptographicException) + { + return false; + } + } +} diff --git a/src/Progmasoft.Tazel/Cache/RemoteActions.cs b/src/Progmasoft.Tazel/Cache/RemoteActions.cs index df48bfb..586e46f 100644 --- a/src/Progmasoft.Tazel/Cache/RemoteActions.cs +++ b/src/Progmasoft.Tazel/Cache/RemoteActions.cs @@ -32,14 +32,26 @@ namespace Progmasoft.Tazel.Cache; /// is put in place, and a result whose paths would leave the action's directory is refused. /// </para> /// <para> +/// With a <c>SigningKey</c>, each result written carries a signature, as one more file named <see cref="Signature"/>: +/// its algorithm and the signature of the action's key and the result's other files. With a <c>PublicKey</c>, only a +/// result signed with the algorithm of that key, and verified by it, is taken. +/// </para> +/// <para> /// A cache that cannot be reached or answers with an error is said once, and the build goes on without it. /// </para> /// </remarks> -internal sealed class RemoteActions(RemoteCache cache, bool read, bool write, Digests digests, Action<string> warn) +internal sealed class RemoteActions( + RemoteCache cache, bool read, bool write, Digests digests, Action<string> warn, CacheKey? trusted = null, + CacheKey? signing = null) { /// <summary>The name, in a result, of the list of the inputs the action found by itself.</summary> public const string DiscoveredInputs = "@tazel/discovered-inputs"; + /// <summary>The name, in a result, of its signature.</summary> + public const string Signature = "@tazel/signature"; + + private int _unsigned; + private static readonly HashSet<string> UserDirectories = new(StringComparer.Ordinal) { "HOME", "TMPDIR", "TMP", "TEMP" }; private int _broken; @@ -133,19 +145,15 @@ internal sealed class RemoteActions(RemoteCache cache, bool read, bool write, Di return false; } - var byPath = new Dictionary<string, OutputFile>(StringComparer.Ordinal); - foreach (var file in files) + if (!await IsTrustedAsync(key, files, cancel).ConfigureAwait(false)) { - if (file.Path != DiscoveredInputs && !IsInside(file.Path)) - { - return false; - } - - byPath[file.Path] = file; + SayUntrusted(); + return false; } var wanted = Wanted(action).Select(Portable).ToList(); - if (!wanted.All(byPath.ContainsKey) || !byPath.TryGetValue(DiscoveredInputs, out var list) || + if (ByPath(files) is not { } byPath || !wanted.All(byPath.ContainsKey) || + !byPath.TryGetValue(DiscoveredInputs, out var list) || !await DiscoveredInputsHoldAsync(action, list, cancel).ConfigureAwait(false)) { return false; @@ -162,6 +170,33 @@ internal sealed class RemoteActions(RemoteCache cache, bool read, bool write, Di return true; } + /// <summary>The files of a result by their paths; null when one of them would leave the action's directory.</summary> + private static Dictionary<string, OutputFile>? ByPath(List<OutputFile> files) + { + var byPath = new Dictionary<string, OutputFile>(StringComparer.Ordinal); + foreach (var file in files) + { + if (file.Path is not (DiscoveredInputs or Signature) && !IsInside(file.Path)) + { + return null; + } + + byPath[file.Path] = file; + } + + return byPath; + } + + /// <summary>Says once that results not signed with the trusted key are left in the cache.</summary> + private void SayUntrusted() + { + if (Interlocked.Exchange(ref _unsigned, 1) == 0) + { + warn($"the remote cache at {cache.Address.Host} holds results that are not signed with the PublicKey " + + $"({CacheKey.NameOf(trusted!.Algorithm)}); they are not taken"); + } + } + /// <summary>Whether every input the action found by itself there has here the digest it had there.</summary> private async Task<bool> DiscoveredInputsHoldAsync(BuildAction action, OutputFile list, CancellationToken cancel) { @@ -260,9 +295,72 @@ internal sealed class RemoteActions(RemoteCache cache, bool read, bool write, Di var listHash = Digests.Sha256(bytes); await cache.PutContentAsync(listHash, bytes, cancel).ConfigureAwait(false); files.Add(new OutputFile(DiscoveredInputs, listHash, bytes.Length, IsExecutable: false)); + if (signing is not null) + { + var record = Encoding.UTF8.GetBytes( + $"tazel signature 1\nalgorithm {CacheKey.NameOf(signing.Algorithm)}\n" + + $"signature {Convert.ToBase64String(signing.Sign(SignedMessage(key, files)))}\n"); + var recordHash = Digests.Sha256(record); + await cache.PutContentAsync(recordHash, record, cancel).ConfigureAwait(false); + files.Add(new OutputFile(Signature, recordHash, record.Length, IsExecutable: false)); + } + await cache.PutActionAsync(key, ActionResultMessage.Encode(files), cancel).ConfigureAwait(false); } + /// <summary> + /// Whether a result may be taken: any result when no PublicKey is trusted; otherwise one whose signature record + /// names the algorithm of the trusted key and whose signature that key verifies. + /// </summary> + private async Task<bool> IsTrustedAsync(string key, List<OutputFile> files, CancellationToken cancel) + { + if (trusted is null) + { + return true; + } + + var signed = files.Where(file => file.Path != Signature).ToList(); + if (files.Count - signed.Count != 1 || files[^1].Path != Signature || + await SignatureOfAsync(files[^1], cancel).ConfigureAwait(false) is not { } record) + { + return false; + } + + return record.Algorithm == trusted.Algorithm && trusted.Verify(SignedMessage(key, signed), record.Signature); + } + + /// <summary>The algorithm and signature of a signature record; null when it is not one.</summary> + private async Task<(SigningAlgorithm Algorithm, byte[] Signature)?> SignatureOfAsync(OutputFile file, CancellationToken cancel) + { + if (file.Size > 64 * 1024 || await cache.GetContentAsync(file.Hash, cancel).ConfigureAwait(false) is not { } record || + Digests.Sha256(record) != file.Hash) + { + return null; + } + + var lines = Encoding.UTF8.GetString(record).Split('\n', StringSplitOptions.RemoveEmptyEntries); + if (lines is not ["tazel signature 1", var algorithm, var signature] || + !algorithm.StartsWith("algorithm ", StringComparison.Ordinal) || + CacheKey.AlgorithmNamed(algorithm["algorithm ".Length..]) is not { } named || + !signature.StartsWith("signature ", StringComparison.Ordinal)) + { + return null; + } + + try + { + return (named, Convert.FromBase64String(signature["signature ".Length..])); + } + catch (FormatException) + { + return null; + } + } + + /// <summary>What a signature covers: the action's key, and the result's files but the signature, in their order.</summary> + private static byte[] SignedMessage(string key, IEnumerable<OutputFile> files) => + [.. Encoding.UTF8.GetBytes($"tazel signed result 1\n{key}\n"), .. ActionResultMessage.Encode(files)]; + /// <summary>The files of a result: the outputs, and the depfile, which the local cache reads after a hit.</summary> private static IEnumerable<string> Wanted(BuildAction action) => action.Depfile is { } depfile ? action.Outputs.Append(depfile).Distinct(StringComparer.Ordinal) : action.Outputs; diff --git a/src/Progmasoft.Tazel/Cache/RemoteCache.cs b/src/Progmasoft.Tazel/Cache/RemoteCache.cs index 6072606..1916984 100644 --- a/src/Progmasoft.Tazel/Cache/RemoteCache.cs +++ b/src/Progmasoft.Tazel/Cache/RemoteCache.cs @@ -137,5 +137,8 @@ internal sealed class RemoteCache : IDisposable } } +/// <summary>A key of the remote cache in MODULE.csx cannot be read.</summary> +public sealed class CacheKeyException(string message) : Exception(message); + /// <summary>A remote cache answered with an error or could not be reached.</summary> public sealed class RemoteCacheException(string message) : Exception(message); diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index f846da6..e9097ad 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -112,6 +112,9 @@ internal sealed record PortalModulesCommand(OutputOptions Output, PortalAction A internal sealed record DaemonCommand(OutputOptions Output, string Action) : Command(Output); +/// <summary><c>tazel cache keygen</c>: a key pair for signing the results of a remote cache.</summary> +internal sealed record CacheKeygenCommand(OutputOptions Output, Cache.SigningAlgorithm Algorithm) : Command(Output); + /// <summary> /// Reads command lines by hand, into typed values. Long options take their value after whitespace, <c>=</c> or /// <c>:</c>; short options also joined (<c>-hbuild</c> is not an option, as <c>-h</c> takes none). A list is @@ -123,7 +126,7 @@ internal static class CommandLine /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", - "portal-modules", "explain", "version", "help", "dotnet"]; + "portal-modules", "cache", "explain", "version", "help", "dotnet"]; private enum Kind { @@ -156,6 +159,7 @@ internal static class CommandLine new("expunge", Kind.Flag, null, "clean"), new("long", Kind.Flag, null, "help", "explain"), new("exact", Kind.Flag, null, "portal-modules"), + new("algorithm", Kind.Value, ["ed25519", "rsa-4096", "ml-dsa"], "cache"), new("output", Kind.Value, ["label", "label_kind"], "query", "cquery", "aquery"), ]; @@ -274,6 +278,7 @@ internal static class CommandLine : new CustomCommandLine(output, scanned.Positional), ["version"] = (scanned, output) => Bare(scanned, new VersionCommand(output)), ["dotnet"] = MakeDaemon, + ["cache"] = MakeCache, }; private static Command Bare(Scanned scanned, Command command) @@ -310,6 +315,22 @@ internal static class CommandLine $"tazel dotnet takes start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); } + private static Command MakeCache(Scanned scanned, OutputOptions output) + { + if (scanned.Positional is not ["keygen"]) + { + throw new CommandLineException("tazel cache takes keygen: tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa]"); + } + + var algorithm = Last(scanned.Seen, "algorithm") switch + { + "rsa-4096" => Cache.SigningAlgorithm.Rsa4096, + "ml-dsa" => Cache.SigningAlgorithm.MlDsa65, + _ => Cache.SigningAlgorithm.Ed25519, + }; + return new CacheKeygenCommand(output, algorithm); + } + private static Command MakeHelp(Scanned scanned, OutputOptions output) => scanned.Positional.Count > 1 ? throw new CommandLineException("tazel help takes one command") diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 9fff720..510c735 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -63,6 +63,15 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; case CleanCommand clean: return Clean(clean.Expunge); + case CacheKeygenCommand keygen: + { + var (publicKey, signingKey) = Cache.CacheKey.Generate(keygen.Algorithm); + reporter.Plain($"PublicKey: {publicKey}"); + reporter.Plain($"SigningKey: {signingKey}"); + reporter.Status("give the PublicKey to every machine that reads; keep the SigningKey secret, for the machines that write"); + return 0; + } + case DaemonCommand daemon: reporter.Error(ErrorCodes.NoDaemon, $"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon", null, @@ -99,12 +108,6 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector /// <summary>Says which settings of MODULE.csx this Tazel reads but does not act on, so none is taken for granted.</summary> private void WarnAboutWhatThisTazelDoesNotDo(Dsl.Module.Prelude.ModuleGlobals globals) { - if (globals.cache?.Settings.Remote?.Settings is { } cache && (cache.PublicKey is not null || cache.SigningKey is not null)) - { - reporter.Warning("MODULE.csx gives the remote cache a PublicKey or a SigningKey; this Tazel neither signs " + - "the results it writes nor checks the ones it reads with them"); - } - if (globals.execution?.Settings.Remote is { } remote) { reporter.Warning($"MODULE.csx names the remote execution {remote.Url}; this Tazel runs every action on this machine"); @@ -291,16 +294,38 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector using var remoteCache = cacheSettings?.Remote is { } remote ? new Cache.RemoteCache(remote.Url, remote.Settings.Token) : null; - var remoteActions = remoteCache is null - ? null - : new Cache.RemoteActions(remoteCache, cacheSettings!.Remote!.Settings.Read, cacheSettings.Remote.Settings.Write, - digests, reporter.Warning); + var remoteActions = remoteCache is null ? null : RemoteActionsOf(remoteCache, cacheSettings!.Remote!.Settings, digests); var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter, remoteActions); var succeeded = await executor.RunAsync(goals, cancel).ConfigureAwait(false); return new Built(buildOptions, planner, chooser, executor, succeeded, planned); } + /// <summary>The remote cache as MODULE.csx sets it up, with its keys read.</summary> + private Cache.RemoteActions RemoteActionsOf(Cache.RemoteCache cache, Dsl.Module.Prelude.RemoteSettings settings, Digests digests) + { + Cache.CacheKey? trusted, signing; + try + { + trusted = settings.PublicKey is { Length: > 0 } text ? Cache.CacheKey.ParsePublic(text, "the PublicKey of the remote cache") : null; + signing = settings.SigningKey is { Length: > 0 } secret + ? Cache.CacheKey.ParseSigning(secret, "the SigningKey of the remote cache") + : null; + } + catch (FormatException error) + { + throw new Cache.CacheKeyException(error.Message); + } + + if (settings.Write && trusted is not null && signing is null) + { + reporter.Warning("MODULE.csx trusts a PublicKey for the remote cache and writes to it without a SigningKey; " + + "no one who trusts that key takes what this build writes"); + } + + return new Cache.RemoteActions(cache, settings.Read, settings.Write, digests, reporter.Warning, trusted, signing); + } + private async Task<int> FinishTestsAsync(Built built, BuildKind kind, CancellationToken cancel) { var tests = built.Planned.Select(entry => (entry.Target, entry.Products, diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 19a89a0..a47b352 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -192,6 +192,15 @@ internal static class Help Prints what Tazel can do, or what one command does; --long says more. """), + ["cache"] = new("tazel cache keygen: a key pair that signs and checks the results of a remote cache.", """ + tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa] + + Prints a PublicKey and a SigningKey for Remote.From in MODULE.csx, each written as its algorithm and the key + in base64. The machines that write to the cache sign with the SigningKey; every machine that reads checks with + the PublicKey and takes only results signed by it. Keep the SigningKey secret, as a secret of your CI. + + --algorithm ed25519|rsa-4096|ml-dsa the algorithm; default: ed25519. ml-dsa is ML-DSA-65 (FIPS 204). + """), ["dotnet"] = new("tazel dotnet start-daemon|restart-daemon|stop-daemon: the daemon of Tazel.", """ tazel dotnet start-daemon|restart-daemon|stop-daemon diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 5f0277f..8453641 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -76,6 +76,7 @@ internal static partial class ErrorCodes public const string NoDaemon = "E0502"; public const string Stopped = "E0503"; public const string MicroVM = "E0504"; + public const string CacheKey = "E0505"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -247,6 +248,12 @@ internal static partial class ErrorCodes "dotnet run microvm/build.cs. The message says which of these failed. The MicroVM has no network, so " + "microvm-network: true is refused, and builds, tests and plugins do not run in it, so a sandbox stops them.", "microvm-network: true;", "microvm-network: false;", "MODULE.csx, BUILD.csx and builds"), + new(CacheKey, "a key of the remote cache Tazel cannot read", + "The PublicKey and the SigningKey of Remote.From in MODULE.csx name their algorithm: ed25519:, rsa-4096: or " + + "ml-dsa-65:, then the key in base64. A public key is 32 bytes for Ed25519, the SubjectPublicKeyInfo of a " + + "4096-bit key for RSA and 1952 bytes for ML-DSA-65; a signing key is a 32-byte seed for Ed25519 and " + + "ML-DSA-65 and a PKCS #8 key for RSA. tazel cache keygen makes a pair.", + "PublicKey = \"AAECAwQF...\"", "PublicKey = \"ed25519:AAECAwQF...\"", "MODULE.csx"), new(Label, "a label Tazel cannot read", "A label names a target: //dir:name, //:name, :name in the current package, @dependency//dir:name; //dir/... " + "and //... are patterns of packages. Names hold letters, digits and _ + . -.", diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index e38dee0..7b3a5a8 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -21,6 +21,7 @@ <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" /> <PackageReference Include="NuGet.Versioning" /> <PackageReference Include="Lzma.Net" /> + <PackageReference Include="BouncyCastle.Cryptography" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 3d75b00..5b75e23 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -62,6 +62,12 @@ internal static class Program reporter.Diagnostic(diagnostic); return 1; } + catch (Cache.CacheKeyException error) + { + reporter.Error(ErrorCodes.CacheKey, error.Message, "make a key pair with tazel cache keygen", + "A key with no name on it opens nothing, least of all a cache."); + return 1; + } catch (MicroVM.MicroVMException error) { reporter.Error(ErrorCodes.MicroVM, error.Message, null, diff --git a/tests/Progmasoft.Tazel.Tests/CacheSigningTests.cs b/tests/Progmasoft.Tazel.Tests/CacheSigningTests.cs new file mode 100644 index 0000000..d342168 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/CacheSigningTests.cs @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cache; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Driver; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class CacheSigningTests +{ + private static void SkipWithoutCompiler() + { + Assert.SkipWhen(Host.Which("clang") is null && Host.Which("gcc") is null, "no C compiler on PATH"); + Assert.SkipWhen(OperatingSystem.IsWindows() && Environment.GetEnvironmentVariable("INCLUDE") is null, + "no MSVC environment (INCLUDE) for the headers of clang on Windows"); + } + + /// <summary>A module that uses the cache at <paramref name="url"/>, with the keys given.</summary> + private static TemporaryModule Module(string url, bool write, string? publicKey, string? signingKey) + { + static string Text(string? value) => value is null ? "null" : $"\"{value}\""; + return new TemporaryModule() + .Write("MODULE.csx", $$""" + using Progmasoft.Tazel.Dsl.Module.Prelude; + module = Module.Define(new() { Group = "com.example", Name = "sample", Version = "0.1.0" }); + cache = Cache.Define(new() { + Remote = Remote.From("{{url}}", new() { + Read = true, Write = {{(write ? "true" : "false")}}, + PublicKey = {{Text(publicKey)}}, SigningKey = {{Text(signingKey)}} + }) + }); + """) + .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.Executable(\"app\", new() { Sources = [\"main.c\"] });\n") + .Write("main.c", "int main(void) { return 0; }\n"); + } + + [Theory] + [InlineData("ed25519")] + [InlineData("rsa-4096")] + [InlineData("ml-dsa-65")] + public void EachAlgorithmSignsAndChecks(string name) + { + var algorithm = CacheKey.AlgorithmNamed(name)!.Value; + var (publicText, signingText) = CacheKey.Generate(algorithm); + Assert.StartsWith(name + ":", publicText, StringComparison.Ordinal); + Assert.StartsWith(name + ":", signingText, StringComparison.Ordinal); + + var publicKey = CacheKey.ParsePublic(publicText, "the key"); + var signingKey = CacheKey.ParseSigning(signingText, "the key"); + var message = Encoding.UTF8.GetBytes("tazel signed result 1\nkey\n"); + var signature = signingKey.Sign(message); + + Assert.True(publicKey.Verify(message, signature)); + Assert.False(publicKey.Verify([.. message, 0x0A], signature)); + signature[^1] ^= 0x01; + Assert.False(publicKey.Verify(message, signature)); + var other = CacheKey.ParsePublic(CacheKey.Generate(algorithm).PublicKey, "the other key"); + Assert.False(other.Verify(message, signingKey.Sign(message))); + } + + [Theory] + [InlineData("AAAA", "does not start with")] + [InlineData("ed448:AAAA", "does not start with")] + [InlineData("ed25519:not base64!", "is not base64")] + [InlineData("ed25519:AAAA", "is not a public key of ed25519")] + [InlineData("ml-dsa-65:AAAA", "is not a public key of ml-dsa-65")] + [InlineData("rsa-4096:AAAA", "is not a public key of rsa-4096")] + public void AKeyThatDoesNotSayItsAlgorithmOrHasTheWrongSizeIsRefused(string text, string said) + { + var error = Assert.Throws<FormatException>(() => CacheKey.ParsePublic(text, "the PublicKey")); + Assert.Contains(said, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void KeygenTakesTheAlgorithmAndNothingElse() + { + Assert.Equal(SigningAlgorithm.Ed25519, Assert.IsType<CacheKeygenCommand>(CommandLine.Parse(["cache", "keygen"])).Algorithm); + Assert.Equal(SigningAlgorithm.MlDsa65, + Assert.IsType<CacheKeygenCommand>(CommandLine.Parse(["cache", "keygen", "--algorithm=ml-dsa"])).Algorithm); + Assert.Equal(SigningAlgorithm.Rsa4096, + Assert.IsType<CacheKeygenCommand>(CommandLine.Parse(["cache", "keygen", "--algorithm", "rsa-4096"])).Algorithm); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["cache"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["cache", "keygen", "--algorithm=dsa"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["build", "--algorithm=ed25519"])); + } + + [Fact] + public async Task AKeyTazelCannotReadStopsTheBuildWithItsCode() + { + using var module = Module("https://cache.example.com", write: false, publicKey: "AAAA", signingKey: null); + var (status, output) = await module.TazelAsync(".", "build", "//:app"); + Assert.Equal(1, status); + Assert.Contains("error[E0505]", output, StringComparison.Ordinal); + Assert.Contains("does not start with ed25519:, rsa-4096: or ml-dsa-65:", output, StringComparison.Ordinal); + } + + [Fact] + public async Task OnlyResultsSignedByTheTrustedKeyAreTaken() + { + SkipWithoutCompiler(); + using var server = new FakeRemoteCache(); + var (publicKey, signingKey) = CacheKey.Generate(SigningAlgorithm.Ed25519); + using (var writer = Module(server.Address, write: true, publicKey, signingKey)) + { + var (status, output) = await writer.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + } + + using (var reader = Module(server.Address, write: false, publicKey, signingKey: null)) + { + var (status, output) = await reader.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.Contains("main.c (remote cache)", output, StringComparison.Ordinal); + } + + // Another key of the same algorithm, and a key of another algorithm: nothing is taken, and that is said once. + foreach (var algorithm in new[] { SigningAlgorithm.Ed25519, SigningAlgorithm.MlDsa65 }) + { + using var stranger = Module(server.Address, write: false, CacheKey.Generate(algorithm).PublicKey, signingKey: null); + var (status, output) = await stranger.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.DoesNotContain("(remote cache)", output, StringComparison.Ordinal); + Assert.Single(output.Split('\n'), line => line.Contains("not signed with the PublicKey", StringComparison.Ordinal)); + } + } + + [Fact] + public async Task AnUnsignedResultIsNotTakenByAReaderThatTrustsAKey() + { + SkipWithoutCompiler(); + using var server = new FakeRemoteCache(); + using (var writer = Module(server.Address, write: true, publicKey: null, signingKey: null)) + { + Assert.Equal(0, (await writer.TazelAsync(".", "build", "//:app")).Status); + } + + Assert.DoesNotContain(server.Actions.Values, bytes => + ActionResultMessage.Decode(bytes)!.Any(file => file.Path == RemoteActions.Signature)); + using var reader = Module(server.Address, write: false, CacheKey.Generate(SigningAlgorithm.Rsa4096).PublicKey, signingKey: null); + var (status, output) = await reader.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.DoesNotContain("(remote cache)", output, StringComparison.Ordinal); + } + + [Fact] + public async Task WritingWithAPublicKeyAndNoSigningKeyIsSaid() + { + SkipWithoutCompiler(); + using var server = new FakeRemoteCache(); + using var writer = Module(server.Address, write: true, CacheKey.Generate(SigningAlgorithm.Ed25519).PublicKey, signingKey: null); + var (status, output) = await writer.TazelAsync(".", "build", "//:app"); + Assert.True(status == 0, output); + Assert.Contains("without a SigningKey", output, StringComparison.Ordinal); + } +}