Zum Inhalt springen

A quality gate in .NET CI with GitHub Actions and SARIF

A CodeCharter gate in GitHub Actions has to tell findings from failed runs. The article shows exit codes, SARIF upload and a required check on an example.

by CodeCharter
  • continuous-integration
  • code-quality
  • testing

A tech lead has settled the gate for the solution Shop.slnx: every pull request runs against a baseline and fails with --fail-on info on any new finding. How he got there is described in the article on the baseline quality gate. Now he writes the GitHub workflow, uploads the results to code scanning and makes the check required. The solution and its Git history are constructed for this article. The output comes from real local runs of CodeCharter v1.7.0, and the statements about the GitHub Action come from the code of its version v1.11.0 from October. No workflow ran on GitHub, and nothing was uploaded. Statements about what GitHub does with the results rest on its documentation.

A pipeline run

A runner starts from a fresh clone. It has no bin, no obj and no rule cache .codecharter/cache, because codecharter config init adds the cache to .gitignore. In the example a local bare repository stands in for GitHub:

$ git clone --branch pr/find-or-default origin.git run1
$ ls .codecharter
baseline.json
codecharter.lock.json
config.yml
$ dotnet restore Shop.slnx
…
$ codecharter restore
  codeguard/csharp-all@1.3.0: restored (248 rules)
Restored 1 profiles, 248 rules cached.

codecharter restore downloads the rule bundle pinned in codecharter.lock.json from the portal. If the portal is unreachable, this step already ends with exit 2. The next run shows which outputs a single call writes: annotations for GitHub, JSON and SARIF. It uses --git-ref without a baseline and is not the chosen gate:

$ codecharter analyze Shop.slnx --fail-on error --git-ref origin/main..HEAD --output github-annotations --output json:codecharter.json --output sarif:codecharter.sarif
::error file=C%3A/Users/…/run1/src/Shop/Infrastructure/SqlOrderRepository.cs,line=42,col=9,title=Empty catch block::catch (System.Collections.Generic.KeyNotFoundException) - …
::notice file=C%3A/Users/…/run1/src/Shop/Infrastructure/SqlOrderRepository.cs,line=36,title=Public member missing XML documentation::Shop.Infrastructure.SqlOrderRepository.FindOrDefault - …
Rules: 248 from codeguard/csharp-all@1.3.0
Note: 6 finding(s) in diff-touched files fall outside the changed lines (e.g. class- or namespace-level findings) and were NOT gated. Re-run with --diff-context to report them.
CodeCharter: 2 violation(s) - 1 error(s), 0 warning(s), 1 info(s) in 6,7s

The run ends with exit 1 because the PR introduces an empty catch with severity error. The note on the six other findings is the v1.7.0 behaviour. In versions after v1.7.1, --git-ref without --diff-context no longer only counts these findings: those at or above --fail-on (every one when --fail-on is not given) fail the run and are named on stderr by severity and rule; --diff-context still reports all of them, and --no-diff-context-gate restores the count-only behaviour (analyze documentation). The local bare repository provides origin/main. On GitHub, actions/checkout fetches a single commit unless told otherwise. In such a clone the same call ended with exit 2 and "Diff analysis failed: error: git diff failed" in the example. A workflow that uses --git-ref therefore sets fetch-depth: 0, as the article on coverage gates also describes for codecharter coverage.

A CI run does not need the --no-host option. The CLI recognizes CI by variables such as CI, GITHUB_ACTIONS or TF_BUILD and then works without the local host it uses on developer machines. Only a CI system that sets none of these variables needs the option.

Exit codes in the step

For analyze, exit 1 means that findings reach the --fail-on threshold. The higher codes mean that the run says nothing reliable. Runs in fresh clones produced these codes in the example, each from a different starting point:

Starting point Message on stderr Exit SARIF file
PR with an empty catch 2 violation(s) - 1 error(s) 1 yes, 2 results
main against the baseline 0 violation(s) 0 yes, 0 results
lockfile missing No lockfile found. 2 no
declared rules directory missing Inconclusive run with [source-unresolved] 2 yes
a project fails to load Inconclusive run with [project-load-failed] 2 yes
codecharter restore without portal error: failed to download bundle 2 not applicable
no rule cache, portal unreachable Profile cache is incomplete and the portal cannot be reached. 3 no
no license License error: No codecharter.license file found. 6 not checked

In the case with the project that does not load, a project Billing is added whose SDK is missing. Its class InvoiceWriter also contains an empty catch. Against the baseline with --fail-on info, the run still reports no finding:

…
CodeCharter: 0 violation(s) - 0 error(s), 0 warning(s), 0 info(s) in 13,8s
Inconclusive run: 248 rules evaluated, 248 resolved. This is NOT a clean result.
  [core-library-unresolved] 1 project(s) could not resolve their own core library reference (Billing), so every fact extracted from them may be wrong; run 'dotnet restore'.
  [project-load-failed] 1 project(s) of the analysis unit failed to load, so their code is not part of this run: Billing (…).

The run ends with exit 2 because the code of Billing was not part of the analysis. A step that only looks at the number of findings would take this for a green result. A step that passes the exit code on turns red. All codes are listed in the exit code documentation.

A pipe is a common place to lose the code. Without shell:, GitHub Actions starts bash -e {0} on Linux runners, with shell: bash it starts bash --noprofile --norc -eo pipefail {0} (GitHub documentation). If the step pipes the output into tee, the exit code of tee decides without pipefail:

$ bash -e -c 'codecharter analyze Shop.slnx --fail-on error --git-ref origin/main..HEAD --no-color | tee codecharter.log >/dev/null'
EXIT=0
$ bash --noprofile --norc -eo pipefail -c 'codecharter analyze Shop.slnx --fail-on error --git-ref origin/main..HEAD --no-color | tee codecharter.log >/dev/null'
EXIT=1

The same PR with the same empty catch is green in the first call. A step with a pipe therefore sets shell: bash.

The GitHub Action

In November 2026 the tag v1 of the action bochmann-software/codecharter points to v1.11.0 from October 5. The action downloads the CLI from the portal with the API key and caches the binary between runs. With the same key the CLI obtains a license that is valid for 24 hours. The action then calls analyze with --severity info, --output github-annotations, a JSON file and optionally --output sarif:. Without further inputs fail-on: error applies, so the gate of the example needs an explicit fail-on: info. The following workflow was written for the example and has not run on GitHub:

permissions:
  contents: read
  security-events: write

jobs:
  codecharter:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-dotnet@v6
        with:
          dotnet-version: '10.0.x'
      - uses: bochmann-software/codecharter@v1
        id: codecharter
        with:
          solution: Shop.slnx
          api-key: ${{ secrets.CODECHARTER_API_KEY }}
          version: v1.7.0
          baseline: .codecharter/baseline.json
          fail-on: info
          sarif-output: codecharter.sarif
      - uses: github/codeql-action/upload-sarif@v4
        if: always() && steps.codecharter.outputs.sarif-path != ''
        with:
          sarif_file: ${{ steps.codecharter.outputs.sarif-path }}
          category: codecharter

The example replayed the call the action builds from these inputs with the CLI. For the PR it ended with exit 1 and two annotations, for main with exit 0. version: v1.7.0 pins the CLI; besides latest the action accepts exact versions. NuGet.org meanwhile has v1.7.1.

The action handles an inconclusive run itself. On exit 2 the step fails, even with fail-on: never, and the action deletes the SARIF file. The sarif-path output then stays empty. Its code gives the reason: uploaded, the file would close every open alert the run could not re-evaluate.

With diff: true the action passes the PR's diff as a file with --diff. It never passes --diff-context and has no input for it. Which findings slipped through without that option in v1.7.0 is shown in the baseline article on a god class. From the CLI version after v1.7.1, the diff run gates those at the action's fail-on threshold without the option. The gate of the example runs without a diff and is not affected.

Two things the action does not do. The CLI refills the rule cache from the portal in every fresh checkout; only the CLI binary is cached. And without the secret the CLI gets no license. GitHub gives workflows from fork PRs no secrets and only a read-only GITHUB_TOKEN (GitHub documentation). In the example a run without a license ended with exit 6. If the job is a required check, a fork PR therefore stays red and cannot be merged.

A custom CLI step

Without the action, the workflow handles installation, cache and exit code itself. The following excerpt was written for the example and has not run on GitHub. The commands of the analysis step ran locally in the example, without the line for $GITHUB_OUTPUT:

- run: |
    dotnet tool install CodeCharter.Cli --version 1.7.0 --tool-path "$RUNNER_TEMP/cc"
    echo "$RUNNER_TEMP/cc" >> "$GITHUB_PATH"
- uses: actions/cache@v6
  with:
    path: .codecharter/cache
    key: codecharter-${{ hashFiles('.codecharter/codecharter.lock.json') }}
- run: dotnet restore Shop.slnx
- name: CodeCharter
  id: codecharter
  shell: bash
  env:
    CODECHARTER_API_KEY: ${{ secrets.CODECHARTER_API_KEY }}
    CODECHARTER_SKIP_UPDATE: '1'
  run: |
    set +e
    codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --fail-on info \
      --output github-annotations --output sarif:codecharter.sarif
    code=$?
    if [ "$code" -ge 2 ]; then rm -f codecharter.sarif; else echo "upload=true" >> "$GITHUB_OUTPUT"; fi
    exit $code

set +e keeps the shell alive after exit 1 so that the step can evaluate the code. From exit 2 on, it deletes the SARIF file, because the CLI writes it for an inconclusive run as well. In the example the PR run ended with 1 and kept the file. The run with the unloadable Billing ended with 2 and lost it, and main ended with 0.

The cache key is the hash of the lockfile, so a new rule bundle after codecharter update gets a new entry. The cache saves little time: codecharter restore took 1.9 to 5.4 seconds in the example. It does make loading the rules independent of the portal. Without cache and portal the run ended with exit 3; with the cache of an earlier run it completed. The license still needs the portal unless the runner gets a license file. That route is described in the article on confidential customer projects.

A custom step pays off when the gate needs --git-ref with --diff-context, or when the action's summary must not go through the portal. Loading the rules without the portal also takes the cache and therefore a custom step. There is no task for Azure Pipelines. The Azure DevOps documentation shows a Bash step, and the same exit code handling applies to it.

Without a SARIF upload and without a pipe, a single run: codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --fail-on info is enough. Any exit code other than 0 turns the step red, and the difference between 1 and 2 only matters when someone looks for the cause.

SARIF and code scanning

The SARIF file of the PR run holds rule, severity, message, location and fingerprints for each finding:

"results": [
  {
    "ruleId": "empty-catch-block",
    "ruleIndex": 0,
    "level": "error",
    "message": {
      "text": "Empty catch block: catch (System.Collections.Generic.KeyNotFoundException)"
    },
    "locations": [
      {
        "physicalLocation": {
          "artifactLocation": {
            "uri": "C:/Users/…/run1/src/Shop/Infrastructure/SqlOrderRepository.cs"
          },
          "region": {
            "startLine": 42,
            "startColumn": 9
          }
        }
      }
    ],
    "partialFingerprints": {
      "codecharter/v1": "024ac5984311f72974f14a68bbdc2539",
      "codecharter/v3": "3d6f3d3016200a4c785316c0d005768b"
    }
  },
  …

A Python script using jsonschema checked five SARIF files from the example. They included the PR run, the full run on main, the baseline run and the run with Billing. Each passed the OASIS SARIF 2.1.0 schema and the schema in GitHub's CodeQL Action without an error. The script then compared the full run on main with the requirements GitHub lists in SARIF support for code scanning. The table summarizes its output:

GitHub requirement Full run on main
at most 10 MB after gzip 11,327 bytes
at most 25,000 results per run 145 results
at least one location for code scanning to display a result 2 results without a location (namespace-distance)
fullDescription.text and help.text per rule present for none of the 17 rules
paths preferably relative to the repository all 143 paths absolute
primaryLocationLineHash for tracking missing, only own keys codecharter/v1 to v3

--workspace-root only shortens the paths of the annotations; the SARIF file keeps absolute paths. According to the code of upload-sarif v4, the CodeQL Action computes primaryLocationLineHash itself when an absolute path lies below checkout_path. For paths under /home/runner/work/… on a Linux runner this follows from the code; the example has no Linux run. The same code treats a Windows path such as C:/… as relative and does not find the file. The job with the upload therefore runs on ubuntu-latest. Whether GitHub accepts results without a location and without help, and how it displays them, has not been checked without an upload.

The SARIF file has the same scope as the gate. The full run on main writes 145 results, the same run with --baseline none. According to GitHub, a later upload with the same tool and the same category overwrites the earlier results. If the workflow uploads the baseline result, code scanning therefore shows only findings that are not in the baseline. If the existing findings should appear in the security tab, main needs a separate run without the baseline and with its own category. Locally this run ended with exit 1. Its step would have to treat exit 1 as success; the example does not demonstrate that.

For the upload, GitHub requires security-events: write, and in private repositories also actions: read (GitHub documentation). The action's README suggests the condition if: steps.codecharter.outputs.sarif-path != ''. Without a status function, however, GitHub applies success() (GitHub documentation). If the gate fails on a finding, the upload would then not run. The workflow above therefore adds always(). With a custom CLI step, the condition and the file change; this excerpt has not run on GitHub either:

- uses: github/codeql-action/upload-sarif@v4
  if: always() && steps.codecharter.outputs.upload == 'true'
  with:
    sarif_file: codecharter.sarif
    category: codecharter

In private repositories, according to GitHub, code scanning also requires GitHub Code Security to be enabled.

The required check

For a red check to block the merge, the repository adds the job to branch protection or to a ruleset. GitHub describes two cases in Troubleshooting required status checks. If a path or branch filter skips the workflow, the check stays "Pending" and blocks the merge. If a condition skips the job, it reports "Success". A required workflow therefore runs without a paths: filter, and the job has no condition that passes over a PR.

Code scanning offers a second route. The ruleset rule "Require code scanning results" blocks a PR when a required tool reports an alert at or above a threshold. The choices are "None", "Errors", "Errors and Warnings" and "All". An alert counts when all of its lines are in the PR's diff. The rule also blocks while a required tool's analysis is still running or is not configured for the repository (GitHub documentation). Whether a tool that only uploads SARIF can be selected there, the page does not say. The exit code of the CodeCharter job therefore remains the check the requirement relies on.

The decision in the example

For Shop.slnx this means: the gate needs neither --git-ref nor --diff-context, and the runner reaches the portal. The tech lead therefore uses the action with version: v1.7.0, baseline and fail-on: info. It holds back the SARIF of an inconclusive run itself. The job codecharter becomes a required check, without a path filter. The upload runs with always() and only when sarif-path is set. Code scanning then shows the new findings of a PR. If the summary must not go through the portal, a custom CLI step with the exit code switch replaces the action.

The coverage gate follows the same rules. codecharter coverage ends with exit 2 on a red test or a missing coverage file, so the switch applies there too. With --git-ref it needs fetch-depth: 0, otherwise it ends with exit 64. Thresholds and diff coverage are described in the article on coverage gates.