From e8f59e05914461ca76dff18970634f958154d9a7 Mon Sep 17 00:00:00 2001 From: Marcus Kimpenhaus Date: Wed, 9 Sep 2026 21:43:35 +0200 Subject: [PATCH] fix(cli): prevent CLI assembly inspection - Skip inspecting assemblies loaded from the CLI directory to avoid runtime errors. - Add `AssemblyLoaderTest` to validate CLI assembly handling logic. - Document CLI exit codes for enhanced error handling in scripts and CI pipelines. --- docs/docs/operator/cli.mdx | 12 +++ src/KubeOps.Cli/Program.cs | 2 +- .../Transpilation/AssemblyLoader.cs | 14 ++++ .../Transpilation/AssemblyLoader.Test.cs | 79 +++++++++++++++++++ 4 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 test/KubeOps.Cli.Test/Transpilation/AssemblyLoader.Test.cs diff --git a/docs/docs/operator/cli.mdx b/docs/docs/operator/cli.mdx index 0756d37b5..12d48cf4c 100644 --- a/docs/docs/operator/cli.mdx +++ b/docs/docs/operator/cli.mdx @@ -154,6 +154,18 @@ All commands support these options: - `--project`: Regex pattern to filter projects in a solution - `--target-framework`: Specify target framework for solution projects +### Exit Codes + +The CLI returns the exit code of the executed command, so failures can be detected in scripts, +MSBuild `Exec` tasks or CI pipelines: + +| Code | Meaning | +| ---- | --------------------------------------------- | +| `0` | Success | +| `1` | Error (an unhandled exception occurred) | +| `2` | Aborted by the user (confirmation prompt) | +| `99` | Usage error (invalid arguments or options) | + ### Common Use Cases 1. **Development Setup**: diff --git a/src/KubeOps.Cli/Program.cs b/src/KubeOps.Cli/Program.cs index d4f1dfa50..cd96760b5 100644 --- a/src/KubeOps.Cli/Program.cs +++ b/src/KubeOps.Cli/Program.cs @@ -21,4 +21,4 @@ errorAction.ShowTypoCorrections = true; } -await parseResult.InvokeAsync(); +return await parseResult.InvokeAsync(); diff --git a/src/KubeOps.Cli/Transpilation/AssemblyLoader.cs b/src/KubeOps.Cli/Transpilation/AssemblyLoader.cs index 2a649904c..e1147977e 100644 --- a/src/KubeOps.Cli/Transpilation/AssemblyLoader.cs +++ b/src/KubeOps.Cli/Transpilation/AssemblyLoader.cs @@ -40,6 +40,9 @@ private static readonly ConditionalWeakTable OperatorWatchScopes = new(); + private static readonly string CliDirectory = + AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar); + static AssemblyLoader() { MSBuildLocator.RegisterDefaults(); @@ -229,10 +232,21 @@ public static IEnumerable GetConvertedEntities(this MetadataLoad private static IEnumerable GetTypesToInspect(this MetadataLoadContext context) => context .GetAssemblies() + .Where(a => !IsCliAssembly(a)) .SelectMany(a => a.DefinedTypes) .Where(t => t is { IsInterface: false, IsAbstract: false, IsGenericType: false }) .OrderBy(t => t.FullName, StringComparer.Ordinal); + // Assemblies next to the CLI only end up in the context because Utilities.GetContextType falls back to + // LoadFromAssemblyPath. Their references (e.g. Microsoft.CodeAnalysis) are not part of the + // PathAssemblyResolver, so inspecting them throws FileNotFoundException. + private static bool IsCliAssembly(Assembly assembly) => + !string.IsNullOrEmpty(assembly.Location) && + string.Equals( + Path.GetDirectoryName(assembly.Location)?.TrimEnd(Path.DirectorySeparatorChar), + CliDirectory, + StringComparison.OrdinalIgnoreCase); + [GeneratedRegex(".*")] private static partial Regex DefaultRegex(); } diff --git a/test/KubeOps.Cli.Test/Transpilation/AssemblyLoader.Test.cs b/test/KubeOps.Cli.Test/Transpilation/AssemblyLoader.Test.cs new file mode 100644 index 000000000..cd759a2fe --- /dev/null +++ b/test/KubeOps.Cli.Test/Transpilation/AssemblyLoader.Test.cs @@ -0,0 +1,79 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System.Reflection; + +using FluentAssertions; + +using k8s.Models; + +using KubeOps.Cli.Generators; +using KubeOps.Cli.Transpilation; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace KubeOps.Cli.Test.Transpilation; + +[Trait("Area", "Transpilation")] +public sealed class AssemblyLoaderTest +{ + [Fact] + public void Should_Not_Inspect_Assemblies_Loaded_From_The_Cli_Directory() + { + using var parser = CreateParser(); + + // Utilities.GetContextType falls back to LoadFromAssemblyPath for types that only exist in the CLI. + parser.LoadFromAssemblyPath(typeof(RbacGenerator).Assembly.Location); + + var inspect = () => + { + parser.GetRbacAttributes().ToList(); + parser.GetValidatedEntities().ToList(); + parser.GetMutatedEntities().ToList(); + parser.GetConvertedEntities().ToList(); + }; + + inspect.Should().NotThrow(); + parser.GetEntities().Should().ContainSingle().Which.Name.Should().Be("AssemblyLoaderTestEntity"); + } + + private static MetadataLoadContext CreateParser() + { + const string source = """ + using k8s.Models; + + [KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "AssemblyLoaderTestEntity")] + internal sealed class AssemblyLoaderTestEntity; + """; + var syntaxTree = CSharpSyntaxTree.ParseText(source, path: "AssemblyLoaderTestEntity.cs"); + var referencePaths = GetReferencePaths().ToList(); + var compilation = CSharpCompilation.Create( + $"AssemblyLoaderTestAssembly-{Guid.NewGuid():N}", + [syntaxTree], + referencePaths.Select(path => MetadataReference.CreateFromFile(path)), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var assemblyStream = new MemoryStream(); + compilation.Emit(assemblyStream).Diagnostics + .Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error) + .Should().BeEmpty(); + + // The resolver mirrors production: it only knows the inspected project's references, so resolving + // anything the CLI itself is compiled against fails. + var parser = new MetadataLoadContext(new PathAssemblyResolver(referencePaths + .Where(path => !Path.GetFileName(path).StartsWith("Microsoft.CodeAnalysis", StringComparison.Ordinal)))); + parser.LoadFromByteArray(assemblyStream.ToArray()); + return parser; + } + + private static IEnumerable GetReferencePaths() + { + var trustedPlatformAssemblies = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") + ?? throw new InvalidOperationException("Trusted platform assemblies are unavailable."); + + return trustedPlatformAssemblies.Split(Path.PathSeparator) + .Concat([typeof(V1Namespace).Assembly.Location]) + .Distinct(StringComparer.OrdinalIgnoreCase); + } +}