tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
fix(registries): align tazel_registries.txt validation with Modules.md (#52)
- Commit
99b7aa14afead6ff67995d22ac71cbf69b50d1a1- Author
- Leitwolf ·
- Committer
- GitHub
- Parents
45538a239b4b
Changes
.../Dsl/Registries/TazelRegistries.cs | 199 +++++++++++++++++++-- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 7 +- tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs | 2 +- tests/Progmasoft.Tazel.Tests/RegistriesTests.cs | 87 ++++++++- 4 files changed, 271 insertions(+), 24 deletions(-) diff --git a/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs b/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs index 6a15451..647e4f4 100644 --- a/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs +++ b/src/Progmasoft.Tazel/Dsl/Registries/TazelRegistries.cs @@ -6,6 +6,8 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text; using Progmasoft.Tazel.Dsl.Configuration; using Progmasoft.Tazel.Dsl.Custom; using Progmasoft.Tazel.Project; @@ -14,7 +16,7 @@ namespace Progmasoft.Tazel.Dsl.Registries; /// <summary>One module registry entry from <c>tazel_registries.txt</c>, ordered by <see cref="Priority"/>.</summary> /// <param name="Priority">The positive integer priority (1 first).</param> -/// <param name="Name">The registry name, or <c>portal-modules</c> for the built-in Tazel Portal Modules registry.</param> +/// <param name="Name">The NFC-normalized registry name, or <c>portal-modules</c> for the built-in Tazel Portal Modules registry.</param> /// <param name="Address">The base repository URI without a trailing slash.</param> /// <param name="IsBuiltIn">Whether this entry refers to the built-in <c>portal-modules</c> registry.</param> /// <param name="Line">The 1-based line number in the source file, or 0 for the implicit built-in default.</param> @@ -22,6 +24,12 @@ public sealed record RegistryEntry(int Priority, string Name, Uri Address, bool { /// <summary>The index document URI (<c><address>/index.json</c>).</summary> public Uri IndexUri => new($"{Address.AbsoluteUri.TrimEnd('/')}/index.json"); + + /// <summary>The normalized environment variable name (<c>TAZEL_REGISTRY_<NORM>_TOKEN</c>), or <see langword="null"/> if the name has no ASCII alphanumerics.</summary> + public string? TokenEnvironmentVariable => TazelRegistriesFile.TokenEnvironmentVariableFor(Name); + + /// <summary>Filesystem-safe SHA-256 hex cache key derived from normalized name and address (never uses raw name as a path).</summary> + public string CacheKey => TazelRegistriesFile.CacheKeyFor(Name, Address); } /// <summary>The effective registry list and where it came from.</summary> @@ -29,12 +37,13 @@ public sealed record RegistryEntry(int Priority, string Name, Uri Address, bool /// <param name="Entries">The registries ordered by ascending <see cref="RegistryEntry.Priority"/>.</param> public sealed record ResolvedRegistries(string? Source, IReadOnlyList<RegistryEntry> Entries) { - /// <summary>Finds a registry by name, or <see langword="null"/> when no entry has that name.</summary> + /// <summary>Finds a registry by name (NFC, case-insensitive), or <see langword="null"/> when no entry matches.</summary> /// <param name="name">The registry name.</param> public RegistryEntry? FindByName(string name) { ArgumentNullException.ThrowIfNull(name); - return Entries.FirstOrDefault(entry => string.Equals(entry.Name, name, StringComparison.Ordinal)); + var normalized = name.Normalize(NormalizationForm.FormC); + return Entries.FirstOrDefault(entry => string.Equals(entry.Name, normalized, StringComparison.OrdinalIgnoreCase)); } } @@ -52,10 +61,53 @@ public static class TazelRegistriesFile /// <summary>The default base URI of Tazel Portal Modules.</summary> public static Uri PortalModulesUri { get; } = new("https://modules.tazel.net"); + /// <summary>The maximum length of a registry name in Unicode scalar values (Runes).</summary> + public static int MaxNameLength { get; } = 128; + /// <summary>The default registry list used when no <c>tazel_registries.txt</c> exists.</summary> public static IReadOnlyList<RegistryEntry> BuiltInDefault { get; } = [new RegistryEntry(1, PortalModulesKeyword, PortalModulesUri, IsBuiltIn: true, Line: 0)]; + /// <summary> + /// Computes the token environment variable name (<c>TAZEL_REGISTRY_<NORM>_TOKEN</c>) for <paramref name="name"/>, + /// or <see langword="null"/> when <paramref name="name"/> contains no ASCII alphanumeric characters. + /// </summary> + /// <param name="name">The registry name.</param> + public static string? TokenEnvironmentVariableFor(string name) + { + ArgumentNullException.ThrowIfNull(name); + var normalized = name.Normalize(NormalizationForm.FormC); + var sb = new StringBuilder(); + var prevUnderscore = true; + foreach (var ch in normalized) + { + if (char.IsAsciiLetterOrDigit(ch)) + { + sb.Append(char.ToUpperInvariant(ch)); + prevUnderscore = false; + } + else if (!prevUnderscore) + { + sb.Append('_'); + prevUnderscore = true; + } + } + + var token = sb.ToString().TrimEnd('_'); + return token.Length == 0 ? null : $"TAZEL_REGISTRY_{token}_TOKEN"; + } + + /// <summary>Computes a filesystem-safe lowercase SHA-256 hex cache key from normalized registry name and address.</summary> + /// <param name="name">The registry name.</param> + /// <param name="address">The normalized repository base URI.</param> + public static string CacheKeyFor(string name, Uri address) + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(address); + var key = $"{name.Normalize(NormalizationForm.FormC).ToLowerInvariant()}\0{address.AbsoluteUri.TrimEnd('/')}"; + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))).ToLowerInvariant(); + } + /// <summary>Parses <paramref name="text"/> as <c>tazel_registries.txt</c>, sorted by ascending priority.</summary> /// <param name="text">The file contents.</param> public static IReadOnlyList<RegistryEntry> Parse(string text) => Parse(text, FileName); @@ -399,7 +451,8 @@ internal static class RegistryParser { var entries = new List<RegistryEntry>(); var seenPriorities = new Dictionary<int, int>(); - var seenNames = new Dictionary<string, int>(StringComparer.Ordinal); + var seenNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); + var seenEnvVars = new Dictionary<string, (string Name, int Line)>(StringComparer.Ordinal); var index = 0; while (index < lines.Count) @@ -414,7 +467,7 @@ internal static class RegistryParser } var (priority, name) = ParseHeader(header, text, file); - CheckDuplicates(priority, name, header.Line, seenPriorities, seenNames, text, file); + CheckDuplicates(priority, name, header.Line, seenPriorities, seenNames, seenEnvVars, text, file); index++; var entry = ParseEntryBody(priority, name, header.Line, lines, ref index, text, file); @@ -428,13 +481,13 @@ internal static class RegistryParser private static (int Priority, string Name) ParseHeader(RegistryLogicalLine line, string text, string file) { var tokens = line.Tokens; - if (tokens.Count != 3 || tokens[0].Kind != RegistryTokenKind.Number || tokens[1].Kind != RegistryTokenKind.Dot || - tokens[2].Kind != RegistryTokenKind.Name) + var validNameToken = tokens.Count == 3 && (tokens[2].Kind == RegistryTokenKind.Name || tokens[2].Kind == RegistryTokenKind.String); + if (!validNameToken || tokens[0].Kind != RegistryTokenKind.Number || tokens[1].Kind != RegistryTokenKind.Dot) { var tok = tokens[0]; throw RegistryLexer.Fail(text, file, tok.Line, tok.Column, "invalid registry entry header", - "write each entry as '<priority>. <name>', for example '1. portal-modules'"); + "write each entry as '<priority>. <name>', for example '1. portal-modules' or '2. \"Title Case\"'"); } if (!int.TryParse(tokens[0].Text, NumberStyles.None, CultureInfo.InvariantCulture, out var priority) || priority < 1) @@ -444,12 +497,85 @@ internal static class RegistryParser "use 1, 2, 3, ..."); } - return (priority, tokens[2].Text); + var normalizedName = ValidateRegistryName(tokens[2], text, file); + return (priority, normalizedName); + } + + private static string ValidateRegistryName(RegistryToken token, string text, string file) + { + var normalized = token.Text.Normalize(NormalizationForm.FormC); + if (string.IsNullOrWhiteSpace(normalized)) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + "registry name cannot be empty or whitespace", + "provide a non-empty registry name"); + } + + if (char.IsWhiteSpace(normalized[0]) || char.IsWhiteSpace(normalized[^1])) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"registry name '{normalized}' cannot have leading or trailing whitespace", + "trim leading and trailing spaces from the registry name"); + } + + if (normalized.EnumerateRunes().Count() > TazelRegistriesFile.MaxNameLength) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"registry name exceeds maximum length of {TazelRegistriesFile.MaxNameLength} Unicode scalar values", + "use a shorter registry name"); + } + + if (HasControlCharacter(normalized)) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + "registry name cannot contain control characters", + "use printable characters only"); + } + + ValidateReservedKeyword(token, normalized, text, file); + return normalized; + } + + private static void ValidateReservedKeyword(RegistryToken token, string normalized, string text, string file) + { + if (!string.Equals(normalized, TazelRegistriesFile.PortalModulesKeyword, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (token.Kind == RegistryTokenKind.String) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"'{normalized}' is reserved for the built-in '{TazelRegistriesFile.PortalModulesKeyword}' keyword", + "use unquoted 'portal-modules' for the built-in registry or choose a different name"); + } + + if (!string.Equals(normalized, TazelRegistriesFile.PortalModulesKeyword, StringComparison.Ordinal)) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"'{normalized}' conflicts with reserved keyword '{TazelRegistriesFile.PortalModulesKeyword}'", + "write 'portal-modules' in lower-case for the built-in registry or choose a different name"); + } + } + + private static bool HasControlCharacter(string value) + { + foreach (var ch in value) + { + if (ch < 0x20 || ch == 0x7F) + { + return true; + } + } + + return false; } private static void CheckDuplicates( int priority, string name, int line, - Dictionary<int, int> seenPriorities, Dictionary<string, int> seenNames, + Dictionary<int, int> seenPriorities, + Dictionary<string, int> seenNames, + Dictionary<string, (string Name, int Line)> seenEnvVars, string text, string file) { if (seenPriorities.TryGetValue(priority, out var prevPriorityLine)) @@ -462,12 +588,24 @@ internal static class RegistryParser if (seenNames.TryGetValue(name, out var prevNameLine)) { throw RegistryLexer.Fail(text, file, line, 1, - $"duplicate registry name '{name}' (already defined on line {prevNameLine})", + $"duplicate registry name '{name}' (conflicts case-insensitively with line {prevNameLine})", "give each registry entry a unique name"); } + var envVar = TazelRegistriesFile.TokenEnvironmentVariableFor(name); + if (envVar is not null && seenEnvVars.TryGetValue(envVar, out var prevEnv)) + { + throw RegistryLexer.Fail(text, file, line, 1, + $"registry name '{name}' collides with '{prevEnv.Name}' (line {prevEnv.Line}) on token variable '{envVar}'", + "rename one registry so they map to distinct TAZEL_REGISTRY_*_TOKEN environment variables"); + } + seenPriorities[priority] = line; seenNames[name] = line; + if (envVar is not null) + { + seenEnvVars[envVar] = (name, line); + } } private static RegistryEntry ParseEntryBody( @@ -512,6 +650,14 @@ internal static class RegistryParser return new RegistryEntry(priority, name, address, IsBuiltIn: false, headerLine); } + private static readonly HashSet<string> AllowedSchemes = new(StringComparer.OrdinalIgnoreCase) + { + "https", + "tazel+https", + "tazel+ssh", + "tazel", + }; + private static Uri ParseAddress(RegistryLogicalLine line, string name, string text, string file) { if (line.Tokens.Count != 1 || line.Tokens[0].Kind != RegistryTokenKind.String) @@ -523,14 +669,33 @@ internal static class RegistryParser } var raw = line.Tokens[0].Text.Trim(); - if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) || - (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + var uri = ParseAndValidateUri(raw, line.Tokens[0], text, file); + return new Uri(uri.AbsoluteUri.TrimEnd('/')); + } + + private static Uri ParseAndValidateUri(string raw, RegistryToken token, string text, string file) + { + if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri) || !AllowedSchemes.Contains(uri.Scheme)) { - throw RegistryLexer.Fail(text, file, line.Tokens[0].Line, line.Tokens[0].Column, - $"invalid registry address '{raw}'", - "provide an absolute http:// or https:// repository base URL"); + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"invalid or unsupported registry address '{raw}'", + "use https://, tazel+https://, tazel+ssh://, or tazel:// (http:// is refused)"); } - return new Uri(uri.AbsoluteUri.TrimEnd('/')); + if (!string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment)) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + $"registry address '{raw}' must not contain a query or fragment", + "provide only the base repository URI without '?' or '#'"); + } + + if (!string.IsNullOrEmpty(uri.UserInfo)) + { + throw RegistryLexer.Fail(text, file, token.Line, token.Column, + "registry address must not contain embedded credentials", + "supply credentials via TAZEL_REGISTRY_<NAME>_TOKEN or tazel login instead"); + } + + return uri; } } diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index b34ab07..7131741 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -347,9 +347,10 @@ internal static partial class ErrorCodes "ML-DSA-65 and a PKCS #8 key for RSA. tazel cache keygen makes a pair.", "PublicKey = \"AAECAwQF...\"", "PublicKey = \"ed25519:AAECAwQF...\"", "MODULE.csx"), new(RegistriesInvalid, "a tazel_registries.txt file Tazel cannot read", - "tazel_registries.txt lists numbered module registries in priority order with indented quoted HTTP/HTTPS URLs; " + - "'portal-modules' is a built-in keyword with no address line.", - "1. custom\n not-a-url", "1. portal-modules\n2. custom\n \"https://tazel.example.com\"", "tazel_registries.txt"), + "tazel_registries.txt lists numbered module registries in priority order (names may use any casing, or be quoted " + + "when containing spaces) with indented quoted https://, tazel+https://, tazel+ssh://, or tazel:// URLs (no http://, " + + "query, fragment, or embedded credentials); 'portal-modules' is a built-in keyword with no address line.", + "1. custom\n \"http://tazel.example.com\"", "1. portal-modules\n2. \"Title Case\"\n \"https://tazel.example.com\"", "tazel_registries.txt"), 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/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs b/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs index 4be44b2..d99df6d 100644 --- a/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs +++ b/tests/Progmasoft.Tazel.Tests/LogCommandsTests.cs @@ -66,7 +66,7 @@ public sealed class LogCommandsTests "using Progmasoft.Tazel.Dsl.Module.Prelude;\nmodule = Module.Define(new() { Group = \"com.example\", Name = \"logdemo\", Version = \"0.1.0\", License = \"MIT\" });\n", TestContext.Current.CancellationToken); await File.WriteAllTextAsync(Path.Combine(dir, "tazel_registries.txt"), - "1. portal-modules\n2. corp\n \"https://user:super-secret-value@tazel.example.com\"\n", + "1. portal-modules\n2. corp\n \"https://tazel.example.com\"\n", TestContext.Current.CancellationToken); var logsDir = Path.Combine(dir, ".tazel", "testlogs"); Directory.CreateDirectory(logsDir); diff --git a/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs b/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs index 8732c3d..c4da6cb 100644 --- a/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs +++ b/tests/Progmasoft.Tazel.Tests/RegistriesTests.cs @@ -56,15 +56,97 @@ public sealed class RegistriesTests Assert.Equal("https://tazel.example.com/a/b", entries[0].Address.AbsoluteUri); } + [Fact] + public void AcceptsTazelProtocolSchemes() + { + var text = """ + 1. proto-https + "tazel+https://reg.example.com/modules" + 2. proto-ssh + "tazel+ssh://reg.example.com/modules" + 3. proto-plain + "tazel://reg.example.com/modules" + """; + + var entries = TazelRegistriesFile.Parse(text); + Assert.Equal(3, entries.Count); + Assert.Equal("tazel+https", entries[0].Address.Scheme); + Assert.Equal("tazel+ssh", entries[1].Address.Scheme); + Assert.Equal("tazel", entries[2].Address.Scheme); + } + + [Fact] + public void AcceptsAnyCaseAndQuotedSpacedRegistryNames() + { + var text = """ + 1. "Title Case" + "https://title.example.com" + 2. Corp_Internal + "https://corp.example.com" + 3. 'My Team Registry' + "https://team.example.com" + """; + + var entries = TazelRegistriesFile.Parse(text); + Assert.Equal(3, entries.Count); + Assert.Equal("Title Case", entries[0].Name); + Assert.Equal("TAZEL_REGISTRY_TITLE_CASE_TOKEN", entries[0].TokenEnvironmentVariable); + Assert.Equal(64, entries[0].CacheKey.Length); + Assert.DoesNotContain('/', entries[0].CacheKey); + Assert.Equal("Corp_Internal", entries[1].Name); + Assert.Equal("TAZEL_REGISTRY_CORP_INTERNAL_TOKEN", entries[1].TokenEnvironmentVariable); + Assert.Equal("My Team Registry", entries[2].Name); + Assert.Equal("TAZEL_REGISTRY_MY_TEAM_REGISTRY_TOKEN", entries[2].TokenEnvironmentVariable); + } + + [Fact] + public void RejectsOversizedRegistryName() + { + var longName = new string('a', TazelRegistriesFile.MaxNameLength + 1); + var ex = Assert.Throws<CustomCommandsException>(() => + TazelRegistriesFile.Parse($"1. {longName}\n \"https://a.example\"")); + Assert.Contains("maximum length", ex.Diagnostic!.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void HandlesNonAsciiEmptyEnvVarAndFilesystemUnsafeNamesSafely() + { + var text = """ + 1. "日本語" + "https://jp.example.com" + 2. "../CON" + "https://win.example.com" + """; + + var entries = TazelRegistriesFile.Parse(text); + Assert.Equal(2, entries.Count); + Assert.Null(entries[0].TokenEnvironmentVariable); + Assert.Matches("^[0-9a-f]{64}$", entries[0].CacheKey); + Assert.Equal("TAZEL_REGISTRY_CON_TOKEN", entries[1].TokenEnvironmentVariable); + Assert.Matches("^[0-9a-f]{64}$", entries[1].CacheKey); + Assert.NotEqual(entries[0].CacheKey, entries[1].CacheKey); + } + [Theory] [InlineData("1. custom\n \"https://tazel.example.com\"", "multiple of 2")] [InlineData("1. custom\n \"https://tazel.example.com\"", "multiple of 2")] [InlineData("1. custom\n \t\"https://tazel.example.com\"", "mixed tabs and spaces")] [InlineData("1. portal-modules\n \"https://tazel.example.com\"", "cannot declare a custom address")] + [InlineData("1. Portal-Modules\n \"https://tazel.example.com\"", "reserved keyword")] + [InlineData("1. \"portal-modules\"\n \"https://tazel.example.com\"", "reserved")] + [InlineData("1. \" Title \"\n \"https://tazel.example.com\"", "leading or trailing whitespace")] + [InlineData("1. Corp\n \"https://a.example\"\n2. corp\n \"https://b.example\"", "duplicate registry name")] + [InlineData("1. \"Title Case\"\n \"https://a.example\"\n2. \"Title-Case\"\n \"https://b.example\"", "collides")] [InlineData("1. custom\n", "missing its indented address")] [InlineData("1. custom\n \"https://a.example\"\n \"https://b.example\"", "more than one indented line")] [InlineData("1. custom\n https://a.example", "unexpected character")] - [InlineData("1. custom\n \"ftp://a.example\"", "invalid registry address")] + [InlineData("1. custom\n \"http://a.example\"", "invalid or unsupported registry address")] + [InlineData("1. custom\n \"ftp://a.example\"", "invalid or unsupported registry address")] + [InlineData("1. custom\n \"https://a.example?x=1\"", "must not contain a query or fragment")] + [InlineData("1. custom\n \"https://a.example#frag\"", "must not contain a query or fragment")] + [InlineData("1. custom\n \"https://user:pass@a.example\"", "must not contain embedded credentials")] + [InlineData("1. \"\"\n \"https://a.example\"", "cannot be empty or whitespace")] + [InlineData("1. \" \"\n \"https://a.example\"", "cannot be empty or whitespace")] [InlineData("0. portal-modules", "positive integer")] [InlineData("1. portal-modules\n1. custom\n \"https://a.example\"", "duplicate registry priority")] [InlineData("1. custom\n \"https://a.example\"\n2. custom\n \"https://b.example\"", "duplicate registry name")] @@ -111,7 +193,7 @@ public sealed class RegistriesTests """, TestContext.Current.CancellationToken); await File.WriteAllTextAsync(Path.Combine(dir, "tazel_registries.txt"), """ 2. corp - "https://user:secret@tazel.example.com/reg" + "https://tazel.example.com/reg" 1. portal-modules """, TestContext.Current.CancellationToken); @@ -122,7 +204,6 @@ public sealed class RegistriesTests var text = output.ToString(); Assert.Contains("1. portal-modules (built-in) https://modules.tazel.net", text, StringComparison.Ordinal); Assert.Contains("2. corp https://tazel.example.com/reg", text, StringComparison.Ordinal); - Assert.DoesNotContain("secret", text, StringComparison.Ordinal); } finally {