From e90e1dbd527800ab56fcdbb8e3e918b0846afcdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 18 Oct 2026 10:25:43 +0200 Subject: [PATCH] ci: harden the pull request analysis The mutation tests of a pull request ran the code of that pull request with the Stryker dashboard key and permission to write pull request comments, and Stryker uploaded its report from the same run. Both jobs are disabled, but would expose these secrets to any pull request once they are enabled again. They now only produce their reports, and the new CI-Analysis workflow uploads them and writes the comment, with the pull request and the dashboard version taken from the `workflow_run` event alone, the artifacts checked for symbolic links, the reports validated, comment content defused and only comments of the pipeline updated. The analysis job stays disabled together with the mutation tests. A release tag that is no valid version now fails the build instead of producing an odd package version. Stryker is pinned to 5.0.0 through the build project so that Dependabot updates it, Sonar reads the generic coverage format, which keeps the lines of lambdas in generic classes, GitVersion and ReportGenerator run on .NET 10 like in the other repositories, the mutation targets follow the names of aweXpect, and all actions are pinned to a commit. --- .fallout/build.schema.json | 3 +- .github/workflows/ci-analysis.yml | 43 ++++ .github/workflows/ci.yml | 56 +++-- .github/workflows/notify-docs-site.yml | 2 +- Pipeline/Build.CodeAnalysis.cs | 2 +- Pipeline/Build.CodeCoverage.cs | 6 +- Pipeline/Build.Compile.cs | 12 +- Pipeline/Build.MutationTests.cs | 313 ++++++++++++++++++------- Pipeline/Build.cs | 2 +- Pipeline/Build.csproj | 2 +- Pipeline/BuildExtensions.cs | 165 ++++++++++++- 11 files changed, 483 insertions(+), 123 deletions(-) create mode 100644 .github/workflows/ci-analysis.yml diff --git a/.fallout/build.schema.json b/.fallout/build.schema.json index 64c6dac11..a24bdad35 100644 --- a/.fallout/build.schema.json +++ b/.fallout/build.schema.json @@ -33,9 +33,10 @@ "CodeCoverage", "Compile", "DotNetUnitTests", - "MutationComment", "MutationTestPreparation", "MutationTests", + "MutationTestsComment", + "MutationTestsDashboard", "MutationTestsLinux", "MutationTestsWindows", "Pack", diff --git a/.github/workflows/ci-analysis.yml b/.github/workflows/ci-analysis.yml new file mode 100644 index 000000000..6aed57b39 --- /dev/null +++ b/.github/workflows/ci-analysis.yml @@ -0,0 +1,43 @@ +name: "CI-Analysis" + +on: + workflow_dispatch: + workflow_run: + workflows: [ "CI" ] + types: + - completed + +jobs: + mutation-tests: + name: "Mutation tests" + # The mutation tests in the CI workflow are disabled, so there are no reports to publish. + if: false + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - name: Setup .NET SDKs + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: | + 6.0.x + 8.0.x + 9.0.x + 10.0.x + - name: Upload mutation dashboard and create comment + run: ./build.sh MutationTestsComment + # The artifacts of the workflow run are untrusted, because a pull request controls the code that + # produces them, so the build identifies the pull request by these values of the event alone. + env: + GithubToken: ${{ secrets.GITHUB_TOKEN }} + STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }} + WorkflowRunId: ${{ github.event.workflow_run.id }} + WorkflowRunEvent: ${{ github.event.workflow_run.event }} + WorkflowRunHeadOwner: ${{ github.event.workflow_run.head_repository.owner.login }} + WorkflowRunHeadBranch: ${{ github.event.workflow_run.head_branch }} + WorkflowRunHeadSha: ${{ github.event.workflow_run.head_sha }} \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b36c8fe43..26f39f7d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,11 +14,11 @@ jobs: os: [ ubuntu-latest, windows-latest, macos-latest ] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup .NET SDKs - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: | 6.0.x @@ -33,7 +33,7 @@ jobs: run: ./build.sh CodeCoverage - name: Upload artifacts if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ${{ runner.os }}-artifacts path: | @@ -46,11 +46,11 @@ jobs: env: DOTNET_NOLOGO: true steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup .NET SDKs - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: | 6.0.x @@ -61,7 +61,7 @@ jobs: run: ./build.sh ApiChecks - name: Upload artifacts if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: API-tests path: | @@ -73,16 +73,13 @@ jobs: if: false runs-on: ubuntu-latest env: - STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }} DOTNET_NOLOGO: true - permissions: - pull-requests: write steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup .NET SDKs - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: | 6.0.x @@ -90,25 +87,27 @@ jobs: 9.0.x 10.0.x - name: Run mutation tests - run: ./build.sh MutationTestsLinux MutationComment - env: - GithubToken: ${{ secrets.GITHUB_TOKEN }} + run: ./build.sh MutationTestsLinux + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: MutationTests-Linux + path: | + ./Artifacts/* mutation-tests-windows: name: "Mutation tests (Windows)" if: false runs-on: windows-latest env: - STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }} DOTNET_NOLOGO: true - permissions: - pull-requests: write steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup .NET SDKs - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: | 6.0.x @@ -116,9 +115,14 @@ jobs: 9.0.x 10.0.x - name: Run mutation tests - run: ./build.ps1 MutationTestsWindows MutationComment - env: - GithubToken: ${{ secrets.GITHUB_TOKEN }} + run: ./build.ps1 MutationTestsWindows + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: MutationTests-Windows + path: | + ./Artifacts/* static-code-analysis: name: "Static code analysis" @@ -129,11 +133,11 @@ jobs: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} DOTNET_NOLOGO: true steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup .NET SDKs - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: dotnet-version: | 6.0.x @@ -153,11 +157,11 @@ jobs: if: always() steps: - name: Download Artifacts - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: path: artifacts - name: Publish Test Results - uses: EnricoMi/publish-unit-test-result-action@d0a4676d0e0b938bc201470d88276b7c74c712b3 # v2 + uses: EnricoMi/publish-unit-test-result-action@7622c5bf3d112a72ab4fa3951c2aa5723d8ab92d # v2.25.0 with: comment_mode: always files: "artifacts/**/**/*.trx" diff --git a/.github/workflows/notify-docs-site.yml b/.github/workflows/notify-docs-site.yml index bbe22a24c..a2e773e8c 100644 --- a/.github/workflows/notify-docs-site.yml +++ b/.github/workflows/notify-docs-site.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Dispatch extension-documentation-updated-event to Testably/Testably.Site - uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4 + uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1 with: token: ${{ secrets.SITE_DISPATCH_TOKEN }} repository: Testably/Testably.Site diff --git a/Pipeline/Build.CodeAnalysis.cs b/Pipeline/Build.CodeAnalysis.cs index c4e0fa3de..ade1664b7 100644 --- a/Pipeline/Build.CodeAnalysis.cs +++ b/Pipeline/Build.CodeAnalysis.cs @@ -20,7 +20,7 @@ partial class Build .SetOrganization("testably") .SetProjectKey("Testably_Testably.Abstractions") .AddVSTestReports(TestResultsDirectory / "*.trx") - .AddOpenCoverPaths(TestResultsDirectory / "reports" / "OpenCover.xml") + .AddGenericCoveragePaths(TestResultsDirectory / "reports" / "SonarQube.xml") .SetPullRequestOrBranchName(GitHubActions, BranchName) .SetVersion(SemVer) .SetToken(SonarToken)); diff --git a/Pipeline/Build.CodeCoverage.cs b/Pipeline/Build.CodeCoverage.cs index a20e97b8f..af3c10f3f 100644 --- a/Pipeline/Build.CodeCoverage.cs +++ b/Pipeline/Build.CodeCoverage.cs @@ -16,10 +16,12 @@ partial class Build { ReportGenerator(s => s .SetProcessToolPath(NuGetToolPathResolver.GetPackageExecutable("ReportGenerator", "ReportGenerator.dll", - framework: "net8.0")) + framework: "net10.0")) .SetTargetDirectory(TestResultsDirectory / "reports") .AddReports(TestResultsDirectory / "**/*.cobertura.xml") - .AddReportTypes(ReportTypes.OpenCover) + // The generic format of Sonar lists the lines per file. A format that lists them per method leaves out the + // lines of a lambda in a generic class, because ReportGenerator keeps them in a class without methods. + .AddReportTypes(ReportTypes.SonarQube) .AddFileFilters("-*.g.cs") .SetAssemblyFilters("+Testably*")); }); diff --git a/Pipeline/Build.Compile.cs b/Pipeline/Build.Compile.cs index 5ed42f15f..4c2dab6e4 100644 --- a/Pipeline/Build.Compile.cs +++ b/Pipeline/Build.Compile.cs @@ -12,6 +12,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; +using System.Text.RegularExpressions; using static Fallout.Common.Tools.DotNet.DotNetTasks; // ReSharper disable AllUnderscoreLocalParameterName @@ -53,12 +54,19 @@ partial class Build } else if (GitHubActions.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase) == true) { + if (!Regex.IsMatch(GitHubActions.Ref, + @"\Arefs/tags/(core/)?v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?\z")) + { + Assert.Fail( + $"The tag '{GitHubActions.Ref["refs/tags/".Length..]}' is no valid release tag (expected 'v1.2.3' or 'core/v1.2.3', optionally with a pre-release suffix like '-pre.1')"); + } + int preReleaseIndex = GitHubActions.Ref.IndexOf('-'); preRelease = preReleaseIndex > 0 ? GitHubActions.Ref[preReleaseIndex..] : ""; } CoreVersion = AssemblyVersion.FromGitVersion(GitVersionTasks.GitVersion(s => s - .SetFramework("net8.0") + .SetFramework("net10.0") .SetNoFetch(true) .SetNoCache(true) .DisableProcessOutputLogging() @@ -67,7 +75,7 @@ partial class Build .Result, preRelease); GitVersion gitVersion = GitVersionTasks.GitVersion(s => s - .SetFramework("net8.0") + .SetFramework("net10.0") .SetNoFetch(true) .SetNoCache(true) .DisableProcessOutputLogging() diff --git a/Pipeline/Build.MutationTests.cs b/Pipeline/Build.MutationTests.cs index 5d5116772..762ebf137 100644 --- a/Pipeline/Build.MutationTests.cs +++ b/Pipeline/Build.MutationTests.cs @@ -8,8 +8,15 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Xml.Linq; using static Fallout.Common.Tools.DotNet.DotNetTasks; +using ProductHeaderValue = Octokit.ProductHeaderValue; using Project = Fallout.Solutions.Project; // ReSharper disable AllUnderscoreLocalParameterName @@ -18,67 +25,169 @@ namespace Build; partial class Build { - /// - /// The markdown texts for each project. - /// - static readonly Dictionary MutationCommentBodies = new(); + private const long MaxMutationReportSize = 100 * 1024 * 1024; + + Dictionary LinuxMutationTestProjects => new() + { + { + Solution.Testably_Abstractions_Testing, [ + Solution.Tests.Testably_Abstractions_Testing_Tests, + Solution.Tests.Testably_Abstractions_Tests + ] + }, + }; + + Dictionary WindowsMutationTestProjects => new() + { + { + Solution.Testably_Abstractions_AccessControl, + [Solution.Tests.Testably_Abstractions_AccessControl_Tests] + }, + { + Solution.Testably_Abstractions_Compression, + [Solution.Tests.Testably_Abstractions_Compression_Tests] + }, + { + Solution.Testably_Abstractions_MemoryMappedFiles, + [Solution.Tests.Testably_Abstractions_MemoryMappedFiles_Tests] + }, + { + Solution.Core.Testably_Abstractions, [ + Solution.Tests.Testably_Abstractions_Testing_Tests, + Solution.Tests.Testably_Abstractions_Tests + ] + } + }; + + Target MutationTestsComment => _ => _ + .After(MutationTestsLinux) + .After(MutationTestsWindows) + .DependsOn(MutationTestsDashboard) + .OnlyWhenDynamic(() => BuildScope == BuildScope.Default) + .Executes(async () => + { + // The artifacts are untrusted, because the pull request controls the code that produces them, so the pull + // request to comment on comes from the event of the workflow run. + int? prId = await BuildExtensions.ResolvePullRequestOfWorkflowRun(GithubToken); + if (prId == null) + { + Log.Information( + "The workflow run belongs to no pull request, so there is no mutation comment to write"); + return; + } + + Dictionary mutationCommentBodies = new(); + foreach (AbsolutePath file in ArtifactsDirectory.GetFiles("MutationTest_*.md", 2)) + { + string project = Path.GetFileNameWithoutExtension(file).Substring("MutationTest_".Length); + mutationCommentBodies[project] = (await File.ReadAllTextAsync(file)).AsUntrustedCommentContent(); + } + + if (mutationCommentBodies.Count == 0) + { + Log.Warning("No files matching \"MutationTest_*.md\" found"); + return; + } + + GitHubClient gitHubClient = new(new ProductHeaderValue("Fallout")); + Credentials tokenAuth = new(GithubToken); + gitHubClient.Credentials = tokenAuth; + IReadOnlyList comments = + await gitHubClient.Issue.Comment.GetAllForIssue("Testably", + "Testably.Abstractions", prId.Value); + IssueComment? existingComment = null; + Log.Information($"Found {comments.Count} comments"); + foreach (IssueComment comment in comments) + { + if (comment.IsPipelineComment("## :alien: Mutation Results")) + { + Log.Information($"Found comment: {comment.Body}"); + existingComment = comment; + } + } - Target MutationComment => _ => _ + if (existingComment == null) + { + string body = "## :alien: Mutation Results" + + Environment.NewLine + + $"[![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2FTestably%2FTestably.Abstractions%2Fpull/{prId}/merge)](https://dashboard.stryker-mutator.io/reports/github.com/Testably/Testably.Abstractions/pull/{prId}/merge)" + + Environment.NewLine + + string.Join(Environment.NewLine, mutationCommentBodies.Values); + + Log.Information($"Create comment:\n{body}"); + await gitHubClient.Issue.Comment.Create("Testably", "Testably.Abstractions", + prId.Value, body); + } + else + { + string body = existingComment.Body; + foreach ((string project, string value) in mutationCommentBodies) + { + body = ReplaceProject(body, project, value); + } + + Log.Information($"Update comment:\n{body}"); + await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", + existingComment.Id, body); + } + }); + + Target MutationTestsDashboard => _ => _ .After(MutationTestsLinux) .After(MutationTestsWindows) - .OnlyWhenDynamic(() => GitHubActions.IsPullRequest) .OnlyWhenDynamic(() => BuildScope == BuildScope.Default) .Executes(async () => { - int? prId = GitHubActions.PullRequestNumber; - Log.Debug("Pull request number: {PullRequestId}", prId); - if (MutationCommentBodies.Count == 0) + string? version = await GetMutationDashboardVersion(); + if (version == null) { + Log.Information("The run has no version on the mutation dashboard, so there is nothing to publish"); return; } - if (prId != null) + await "MutationTests-Linux".DownloadArtifactTo(ArtifactsDirectory, GithubToken); + await "MutationTests-Windows".DownloadArtifactTo(ArtifactsDirectory, GithubToken); + + string? apiKey = Environment.GetEnvironmentVariable("STRYKER_DASHBOARD_API_KEY"); + foreach (Project project in LinuxMutationTestProjects.Keys.Concat(WindowsMutationTestProjects.Keys)) { - GitHubClient gitHubClient = new(new ProductHeaderValue("Fallout")); - Credentials tokenAuth = new(GithubToken); - gitHubClient.Credentials = tokenAuth; - IReadOnlyList comments = - await gitHubClient.Issue.Comment.GetAllForIssue("Testably", - "Testably.Abstractions", prId.Value); - IssueComment? existingComment = null; - Log.Information($"Found {comments.Count} comments"); - foreach (IssueComment comment in comments) + AbsolutePath reportFile = StrykerOutputDirectory / project.Name / "reports" / "mutation-report.json"; + if (!File.Exists(reportFile)) { - if (comment.Body.Contains("## :alien: Mutation Results")) - { - Log.Information($"Found comment: {comment.Body}"); - existingComment = comment; - } + Log.Information("Skip uploading the mutation report of {ProjectName}, as there is none", + project.Name); + continue; } - if (existingComment == null) + if (new FileInfo(reportFile).Length > MaxMutationReportSize) { - string body = "## :alien: Mutation Results" - + Environment.NewLine - + $"[![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2FTestably%2FTestably.Abstractions%2Fpull/{prId}/merge)](https://dashboard.stryker-mutator.io/reports/github.com/Testably/Testably.Abstractions/pull/{prId}/merge)" - + Environment.NewLine - + string.Join(Environment.NewLine, MutationCommentBodies.Values); - - Log.Information($"Create comment:\n{body}"); - await gitHubClient.Issue.Comment.Create("Testably", "Testably.Abstractions", - prId.Value, body); + Assert.Fail($"The {project.Name} mutation report is larger than {MaxMutationReportSize} bytes"); + } + + string reportComment = File.ReadAllText(reportFile); + if (JsonNode.Parse(reportComment) is not JsonObject) + { + Assert.Fail($"The {project.Name} mutation report is no JSON object"); + } + + using HttpClient client = new(); + client.DefaultRequestHeaders.Add("X-Api-Key", apiKey); + // https://stryker-mutator.io/docs/General/dashboard/#send-a-report-via-curl + HttpResponseMessage response = await client.PutAsync( + $"https://dashboard.stryker-mutator.io/api/reports/github.com/Testably/Testably.Abstractions/{version}?module={project.Name}", + new StringContent(reportComment, new MediaTypeHeaderValue("application/json"))); + string responseContent = await response.Content.ReadAsStringAsync(); + if (response.IsSuccessStatusCode) + { + Log.Information("Uploaded the {Module} mutation report ({Size} bytes): {Response}", + project.Name, reportComment.Length, responseContent); } else { - string body = existingComment.Body; - foreach ((string project, string value) in MutationCommentBodies) - { - body = ReplaceProject(body, project, value); - } - - Log.Information($"Update comment:\n{body}"); - await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", - existingComment.Id, body); + // Without this the job stays green while the dashboard keeps showing the previous score. + Assert.Fail( + $"Could not upload the {project.Name} mutation report ({reportComment.Length} bytes), " + + $"the dashboard answered {(int)response.StatusCode} {response.ReasonPhrase}: {responseContent}"); } } }); @@ -91,6 +200,7 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", DotNetToolInstall(_ => _ .SetPackageName("dotnet-stryker") + .SetVersion(GetStrykerVersion()) .SetToolInstallationPath(StrykerToolPath)); StrykerOutputDirectory.CreateOrCleanDirectory(); @@ -99,7 +209,6 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", Target MutationTests => _ => _ .DependsOn(MutationTestsWindows) .DependsOn(MutationTestsLinux) - .DependsOn(MutationComment) .OnlyWhenDynamic(() => BuildScope == BuildScope.Default); Target MutationTestsLinux => _ => _ @@ -109,17 +218,7 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", .Executes(() => { AbsolutePath configFile = StrykerToolPath / "Stryker.Config.json"; - Dictionary projects = new() - { - { - Solution.Testably_Abstractions_Testing, [ - Solution.Tests.Testably_Abstractions_Testing_Tests, - Solution.Tests.Testably_Abstractions_Tests - ] - }, - }; - - foreach (KeyValuePair project in projects) + foreach (KeyValuePair project in LinuxMutationTestProjects) { string? branchName = GitVersion?.BranchName; if (GitHubActions?.Ref.StartsWith("refs/tags/", @@ -190,9 +289,8 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", File.WriteAllText(configFile, configText); Log.Debug($"Created '{configFile}':{Environment.NewLine}{configText}"); - string arguments = IsServerBuild - ? $"-f \"{configFile}\" -O \"{StrykerOutputDirectory}\" -r \"Markdown\" -r \"Dashboard\" -r \"cleartext\"" - : $"-f \"{configFile}\" -O \"{StrykerOutputDirectory}\" -r \"Markdown\" -r \"cleartext\""; + string arguments = + $"-f \"{configFile}\" -O \"{StrykerOutputDirectory / project.Key.Name}\" -r \"Markdown\" -r \"json\" -r \"cleartext\""; string executable = EnvironmentInfo.IsWin ? "dotnet-stryker.exe" : "dotnet-stryker"; IProcess process = ProcessTasks.StartProcess( @@ -206,7 +304,13 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", $"Stryker did not execute successfully for {project.Key.Name}: (exit code {process.ExitCode})."); } - MutationCommentBodies.Add(project.Key.Name, + if (!File.Exists(StrykerOutputDirectory / project.Key.Name / "reports" / "mutation-report.md")) + { + Log.Information("Stryker found nothing to mutate in {ProjectName}", project.Key.Name); + continue; + } + + File.WriteAllText(ArtifactsDirectory / $"MutationTest_{project.Key.Name}.md", CreateMutationCommentBody(project.Key.Name)); } }); @@ -218,29 +322,7 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", .Executes(() => { AbsolutePath configFile = StrykerToolPath / "Stryker.Config.json"; - Dictionary projects = new() - { - { - Solution.Testably_Abstractions_AccessControl, - [Solution.Tests.Testably_Abstractions_AccessControl_Tests] - }, - { - Solution.Testably_Abstractions_Compression, - [Solution.Tests.Testably_Abstractions_Compression_Tests] - }, - { - Solution.Testably_Abstractions_MemoryMappedFiles, - [Solution.Tests.Testably_Abstractions_MemoryMappedFiles_Tests] - }, - { - Solution.Core.Testably_Abstractions, [ - Solution.Tests.Testably_Abstractions_Testing_Tests, - Solution.Tests.Testably_Abstractions_Tests - ] - } - }; - - foreach (KeyValuePair project in projects) + foreach (KeyValuePair project in WindowsMutationTestProjects) { string? branchName = GitVersion?.BranchName; if (GitHubActions?.Ref.StartsWith("refs/tags/", @@ -283,9 +365,8 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", File.WriteAllText(configFile, configText); Log.Debug($"Created '{configFile}':{Environment.NewLine}{configText}"); - string arguments = IsServerBuild - ? $"-f \"{configFile}\" -O \"{StrykerOutputDirectory}\" -r \"Markdown\" -r \"Dashboard\" -r \"cleartext\" --test-runner mtp" - : $"-f \"{configFile}\" -O \"{StrykerOutputDirectory}\" -r \"Markdown\" -r \"cleartext\" --test-runner mtp"; + string arguments = + $"-f \"{configFile}\" -O \"{StrykerOutputDirectory / project.Key.Name}\" -r \"Markdown\" -r \"json\" -r \"cleartext\" --test-runner mtp"; string executable = EnvironmentInfo.IsWin ? "dotnet-stryker.exe" : "dotnet-stryker"; IProcess process = ProcessTasks.StartProcess( @@ -299,7 +380,13 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", $"Stryker did not execute successfully for {project.Key.Name}: (exit code {process.ExitCode})."); } - MutationCommentBodies.Add(project.Key.Name, + if (!File.Exists(StrykerOutputDirectory / project.Key.Name / "reports" / "mutation-report.md")) + { + Log.Information("Stryker found nothing to mutate in {ProjectName}", project.Key.Name); + continue; + } + + File.WriteAllText(ArtifactsDirectory / $"MutationTest_{project.Key.Name}.md", CreateMutationCommentBody(project.Key.Name)); } }); @@ -307,10 +394,52 @@ await gitHubClient.Issue.Comment.Update("Testably", "Testably.Abstractions", AbsolutePath StrykerOutputDirectory => ArtifactsDirectory / "Stryker"; AbsolutePath StrykerToolPath => TestResultsDirectory / "dotnet-stryker"; + /// + /// The version under which the dashboard stores the mutation reports of the analysed run, or + /// when it has none. + /// + /// + /// The artifacts are untrusted, because a pull request controls the code that produces them, so the version + /// comes from the event alone, and a run that a pull request triggered can only publish to the version of + /// that pull request. + /// + private async Task GetMutationDashboardVersion() + { + string? version = null; + if (GitHubActions?.EventName != "workflow_run") + { + // The reports come from this very run, so its own ref identifies them. + string gitRef = GitHubActions?.Ref ?? ""; + if (gitRef.StartsWith("refs/tags/", StringComparison.Ordinal)) + { + version = "release/" + gitRef.Substring("refs/tags/".Length); + } + else if (gitRef.StartsWith("refs/heads/", StringComparison.Ordinal)) + { + version = gitRef.Substring("refs/heads/".Length); + } + } + else if (Environment.GetEnvironmentVariable("WorkflowRunEvent") == "pull_request") + { + int? prId = await BuildExtensions.ResolvePullRequestOfWorkflowRun(GithubToken); + return prId == null ? null : $"pull/{prId}/merge"; + } + else + { + version = Environment.GetEnvironmentVariable("WorkflowRunHeadBranch"); + } + + // The version becomes a part of the path that the report is sent to. + return version != null && + Regex.IsMatch(version, @"\A[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)*\z") + ? version + : null; + } + string CreateMutationCommentBody(string projectName) { string[] fileContent = - File.ReadAllLines(ArtifactsDirectory / "Stryker" / "reports" / "mutation-report.md"); + File.ReadAllLines(StrykerOutputDirectory / projectName / "reports" / "mutation-report.md"); StringBuilder sb = new(); sb.AppendLine($""); sb.AppendLine($"### {projectName}"); @@ -353,6 +482,16 @@ string CreateMutationCommentBody(string projectName) return body; } + /// + /// The version of Stryker to install, which is the one that the PackageDownload of the build project + /// pins, so that Dependabot keeps it up to date. + /// + static string GetStrykerVersion() + => XDocument.Load(RootDirectory / "Pipeline" / "Build.csproj") + .Descendants("PackageDownload") + .Single(package => package.Attribute("Include")?.Value == "dotnet-stryker") + .Attribute("Version")!.Value.Trim('[', ']'); + static string PathForJson(Project project) => $"\"{project.Path.ToString().Replace(@"\", @"\\")}\""; diff --git a/Pipeline/Build.cs b/Pipeline/Build.cs index b3dc8a6eb..1b3c4b02d 100644 --- a/Pipeline/Build.cs +++ b/Pipeline/Build.cs @@ -27,7 +27,7 @@ partial class Build : FalloutBuild [Parameter("Github Token")] readonly string? GithubToken; - [Required] [GitVersion(Framework = "net8.0", NoCache = true, NoFetch = true)] readonly GitVersion? GitVersion; + [Required] [GitVersion(Framework = "net10.0", NoCache = true, NoFetch = true)] readonly GitVersion? GitVersion; [Solution(GenerateProjects = true)] readonly Solution Solution = null!; diff --git a/Pipeline/Build.csproj b/Pipeline/Build.csproj index ee22a1346..38fd27482 100644 --- a/Pipeline/Build.csproj +++ b/Pipeline/Build.csproj @@ -30,7 +30,7 @@ - + diff --git a/Pipeline/BuildExtensions.cs b/Pipeline/BuildExtensions.cs index efef25fe9..35cb64df5 100644 --- a/Pipeline/BuildExtensions.cs +++ b/Pipeline/BuildExtensions.cs @@ -1,8 +1,16 @@ using Fallout.Common.CI.GitHubActions; -using Fallout.Common.Tools.GitVersion; using Fallout.Common.Tools.SonarScanner; +using Octokit; using Serilog; using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +using ProductHeaderValue = Octokit.ProductHeaderValue; namespace Build; @@ -33,4 +41,159 @@ public static SonarScannerBeginSettings SetPullRequestOrBranchName( Log.Information("Use branch analysis for '{BranchName}'", branchName); return settings.SetBranchName(branchName); } + + /// + /// Resolves the pull request that triggered the workflow run under analysis, or + /// when there is none. + /// + /// + /// The artifacts of that run are untrusted, because the pull request controls the code that produces them, so + /// the pull request is identified by the workflow_run event alone. The event lists no pull requests for + /// a fork, which is why the number is looked up by the head branch and verified against the head commit. + /// + /// A pull request that was merged or closed while its run was analysed is still found. When the same commit + /// of the same branch belongs to several pull requests, the open one is taken. + /// + public static async Task ResolvePullRequestOfWorkflowRun(string? githubToken) + { + string? workflowRunEvent = Environment.GetEnvironmentVariable("WorkflowRunEvent"); + string? headOwner = Environment.GetEnvironmentVariable("WorkflowRunHeadOwner"); + string? headBranch = Environment.GetEnvironmentVariable("WorkflowRunHeadBranch"); + string? headSha = Environment.GetEnvironmentVariable("WorkflowRunHeadSha"); + if (workflowRunEvent != "pull_request" || + string.IsNullOrEmpty(headOwner) || string.IsNullOrEmpty(headBranch) || string.IsNullOrEmpty(headSha)) + { + Log.Information("The workflow run was not triggered by a pull request"); + return null; + } + + GitHubClient gitHubClient = new(new ProductHeaderValue("Fallout")) + { + Credentials = new Credentials(githubToken), + }; + IReadOnlyList pullRequests = await gitHubClient.PullRequest.GetAllForRepository( + "Testably", "Testably.Abstractions", + new PullRequestRequest + { + State = ItemStateFilter.All, + Head = $"{headOwner}:{headBranch}", + }); + // GitHub ignores a head filter it cannot interpret and then lists every pull request. + PullRequest[] matches = pullRequests + .Where(pullRequest => pullRequest.Head.Sha == headSha && + pullRequest.Head.Ref == headBranch && + string.Equals(pullRequest.Head.User?.Login, headOwner, + StringComparison.OrdinalIgnoreCase)) + .ToArray(); + if (matches.Length > 1) + { + matches = matches.Where(pullRequest => pullRequest.State.Value == ItemState.Open).ToArray(); + } + + int[] numbers = matches.Select(pullRequest => pullRequest.Number).ToArray(); + if (numbers.Length != 1) + { + Log.Information("Found {Count} pull requests for the commit {Sha} of the workflow run", + numbers.Length, headSha); + return null; + } + + Log.Information("The workflow run was triggered by the pull request #{PullRequest}", numbers[0]); + return numbers[0]; + } + + /// + /// Whether the is the one that the pipeline wrote under the + /// . + /// + /// + /// Anyone can write a comment that contains the heading, so the author has to match too. + /// + public static bool IsPipelineComment(this IssueComment comment, string heading) + => comment.User?.Login == "github-actions[bot]" && + comment.Body?.StartsWith(heading, StringComparison.Ordinal) == true; + + /// + /// Prepares the of an artifact for a comment of the pipeline. + /// + /// + /// The artifact is untrusted, so the markdown is bound to what a comment can hold, and a zero-width space + /// after every @ keeps it from notifying users and teams. + /// + public static string AsUntrustedCommentContent(this string markdown) + { + const int maxLength = 60000; + markdown = markdown.Replace("@", "@​"); + if (markdown.Length > maxLength) + { + markdown = markdown.Substring(0, maxLength) + Environment.NewLine + Environment.NewLine + + "_The report was truncated._"; + } + + return markdown; + } + + public static async Task DownloadArtifactTo(this string artifactName, string artifactsDirectory, + string? githubToken) + { + string? runId = Environment.GetEnvironmentVariable("WorkflowRunId"); + if (string.IsNullOrEmpty(runId)) + { + Log.Information("Skip downloading artifacts, because no 'WorkflowRunId' environment variable is set."); + return; + } + + using HttpClient client = new(); + client.DefaultRequestHeaders.UserAgent.ParseAdd("Testably.Abstractions"); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", githubToken); + HttpResponseMessage response = await client.GetAsync( + $"https://api.github.com/repos/Testably/Testably.Abstractions/actions/runs/{runId}/artifacts"); + + string responseContent = await response.Content.ReadAsStringAsync(); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException( + $"Could not find artifacts for run #{runId}': {responseContent}"); + } + + try + { + JsonDocument jsonDocument = JsonDocument.Parse(responseContent); + foreach (JsonElement artifact in jsonDocument.RootElement.GetProperty("artifacts").EnumerateArray()) + { + string name = artifact.GetProperty("name").GetString()!; + if (name.Equals(artifactName, StringComparison.OrdinalIgnoreCase)) + { + long artifactId = artifact.GetProperty("id").GetInt64(); + HttpResponseMessage fileResponse = await client.GetAsync( + $"https://api.github.com/repos/Testably/Testably.Abstractions/actions/artifacts/{artifactId}/zip"); + if (fileResponse.IsSuccessStatusCode) + { + using ZipArchive archive = new(await fileResponse.Content.ReadAsStreamAsync()); + // The artifact can be untrusted, and a link in it could point a later read at any file of + // the runner. The upper half of the attributes is the Unix mode, where 0xA000 marks a link. + if (archive.Entries.Any(entry => ((entry.ExternalAttributes >> 16) & 0xF000) == 0xA000)) + { + throw new InvalidOperationException( + $"The artifact #{artifactId} contains a symbolic link"); + } + + archive.ExtractToDirectory(artifactsDirectory, true); + Log.Information( + $"Extracted artifact #{artifactId} with {archive.Entries.Count} entries to {artifactsDirectory}:\n - {string.Join("\n - ", archive.Entries.Select(entry => $"{entry.Name} ({entry.Length})"))}"); + } + else + { + string fileResponseContent = await fileResponse.Content.ReadAsStringAsync(); + throw new InvalidOperationException( + $"Could not download the artifacts with id #{artifactId}': {fileResponseContent}"); + } + } + } + } + catch (JsonException e) + { + Log.Error($"Could not parse JSON: {e.Message}\n{responseContent}"); + } + } }