jactionlint

package module
v2.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 56 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README Âķ

jactionlint

Catch broken and insecure GitHub Actions workflows before they run.

CI status Latest release Go reference

Documentation · Playground · Rules · Changelog

jactionlint is a static checker for GitHub Actions. It reads your workflows, composite actions and dependabot.yml and reports two kinds of problems: the mistakes that make a run fail or misbehave, and the patterns that let an outsider run code in your repository or steal its token. It started as a fork of actionlint and covers its checks, and its security rules follow the audits of zizmor.

  • Correctness. Unknown keys and events, type errors in ${{ }} expressions, wrong inputs of actions and reusable workflows, and broken needs:, cron and glob patterns. shellcheck and pyflakes check the scripts of run: steps.
  • Security. Script injection, excessive token permissions, dangerous triggers such as pull_request_target, cache poisoning, credentials left in the checkout and AI agent actions that outsiders can steer.
  • Policy. Actions used by a tag instead of a commit, and workflows without permissions:, a job timeout or a concurrency group.
  • Fixes. jactionlint --fix repairs what has a mechanical fix, and --diff shows the change first.
  • Gradual adoption. Profiles choose how much is checked, and a baseline fails the build only on new findings.
  • Local runs. jactionlint run ci runs the jobs of a workflow on your machine, every step in an OS sandbox, with a local actions cache and no container engine unless the workflow asks for one. See Run workflows locally.
  • Updates. jactionlint update finds the latest release of each action that your cooldown, tag and immutability policy allows, and shows, previews (--diff) or writes (--apply) the new references, pinned to a commit SHA with a version comment if you like. See Update actions.
  • No network unless you ask. The online checks, which ask GitHub about archived repositories, impostor commits and published advisories, run only with --online.

Try it without installing anything in the playground, which runs jactionlint in your browser.

Quick start

Install jactionlint with mise and run it at the root of a repository:

mise use -g jactionlint
jactionlint

With no arguments, jactionlint checks the workflows, composite actions, dependabot.yml and Actions lock file of the repository. Pass file names to check only those, or - to read standard input. It exits with status 1 when a finding of level error is left.

Other ways to install it:

  • Homebrew: brew tap jdx/jactionlint https://github.com/jdx/jactionlint, then brew install --cask jdx/jactionlint/jactionlint.
  • PyPI: uvx jactionlint runs it without installing it, and pipx install jactionlint or uv tool install jactionlint installs it.
  • Docker: the image ghcr.io/jdx/jactionlint also holds shellcheck and pyflakes. Run the image shows the command.
  • Go: go install github.com/jdx/jactionlint/v2/cmd/jactionlint@latest.
  • Release archives: download the archive for your platform from the releases and verify it.

Packages named actionlint, as in Homebrew core, install the original project, not this fork. Installation covers every method.

Example

This workflow has a typo in a trigger, untrusted input in a script and an undefined matrix property. It also uses an action by tag and sets no permissions, timeout or concurrency group. Save it as test.yaml:

on:
  push:
    branch: main
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: echo "${{ github.event.head_commit.message }}"
      - run: echo "${{ matrix.os }}"

jactionlint test.yaml prints each finding with its position, a message, the line it points at and, in brackets, the ID of its rule:

test.yaml:1:1: workflow has no "concurrency:", so every run of it executes at the same time even when a newer run supersedes the older ones. add a top-level "concurrency:" with a "group:" and "cancel-in-progress: true" [concurrency-limits]
  |
1 | on:
  | ^~~
test.yaml:3:5: unexpected key "branch" for "push" section. expected one of "branches", "branches-ignore", "paths", "paths-ignore", "tags", "tags-ignore", "types", "workflows" [workflow-syntax]
  |
3 |     branch: main
  |     ^~~~~~~
test.yaml:5:3: "timeout-minutes" is not set at this job. Set it to avoid wasting runner minutes when the job hangs. Set "default-minutes" in the "missing-timeout" rule options of the configuration to turn on the --fix fix [missing-timeout]
  |
5 |   test:
  |   ^~~~~
test.yaml:5:3: neither the workflow nor this job sets "permissions:" so the GITHUB_TOKEN gets the default permissions of the repository. set "permissions:" at workflow-level or job-level (use "permissions: {}" for no permissions) because the "missing-permissions" rule is enabled [missing-permissions]
  |
5 |   test:
  |   ^~~~~
test.yaml:8:15: action "actions/checkout@v4" must be pinned to a full-length commit SHA like "{owner}/{repo}@{sha}" because the "unpinned-uses" rule is enabled [unpinned-uses]
  |
8 |       - uses: actions/checkout@v4
  |               ^~~~~~~~~~~~~~~~~~~
test.yaml:8:15: actions/checkout leaves the GITHUB_TOKEN in the git config of the workspace, where a later step such as an artifact upload can publish it. set "persist-credentials: false" under "with:" unless a later step needs to push [artipacked]
  |
8 |       - uses: actions/checkout@v4
  |               ^~~~~~~~~~~~~~~~~~~
test.yaml:9:24: "github.event.head_commit.message" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. see https://docs.github.com/en/actions/reference/security/secure-use#good-practices-for-mitigating-script-injection-attacks for more details [template-injection]
  |
9 |       - run: echo "${{ github.event.head_commit.message }}"
  |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test.yaml:10:24: property "os" is not defined in object type {} [undefined-property]
   |
10 |       - run: echo "${{ matrix.os }}"
   |                        ^~~~~~~~~

jactionlint --explain template-injection prints what a rule checks, why it matters and how to fix it. With --profile correctness, jactionlint reports only workflow-syntax, template-injection and undefined-property. The other five findings come from the security and policy rules of the default profile, which applies when you configure nothing.

jactionlint --diff test.yaml previews the safe fixes, and jactionlint --fix test.yaml applies them. Here they stop actions/checkout from persisting the token, give the token read-only permissions and pass the untrusted message through an environment variable:

--- a/test.yaml
+++ b/test.yaml
@@ -1,10 +1,17 @@
 on:
   push:
     branch: main
+
+permissions:
+  contents: read
 jobs:
   test:
     runs-on: ubuntu-latest
     steps:
       - uses: actions/checkout@v4
-      - run: echo "${{ github.event.head_commit.message }}"
+        with:
+          persist-credentials: false
+      - run: echo "${HEAD_COMMIT_MESSAGE}"
+        env:
+          HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
       - run: echo "${{ matrix.os }}"

Run it in CI

The jactionlint action installs jactionlint, checks the repository and annotates the pull request with the findings. This workflow passes the default profile itself:

name: jactionlint
on:
  push:
    branches: [main]
  pull_request:
permissions: {}
concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true
jobs:
  jactionlint:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
        with:
          persist-credentials: false
      - uses: jdx/jactionlint@9e87e8f34edfc00b849a27807e26eff9d00b936d # v2.5.0

Set advanced-security: true under with: to upload the findings to code scanning instead, which needs security-events: write. Run jactionlint in CI also covers mise, which verifies the download, the Docker image and problem matchers. Git hooks and editors covers hk and pre-commit.

Adopt it on an existing repository

The default profile can fail the first run on a repository that never followed it. Choose how much is checked with --profile, or with profile: in .github/jactionlint.yaml:

Profile What it checks
correctness The checks of actionlint and the bug detectors of jactionlint.
default correctness, plus the security and policy rules worth failing a build on. It applies when you configure nothing.
pedantic default, plus the noisier and opinionated rules.

Fix what the correctness profile reports first, because those findings are mistakes, not debt. Then record what the default profile still finds, and let the build fail only on new findings:

jactionlint --profile correctness   # fix these first
jactionlint --baseline-write        # record the findings that are left
jactionlint --baseline              # fail only on new findings

Silence a finding that you accept with a comment such as # jactionlint ignore=unpinned-uses on the line above it. jactionlint --init-config writes a config file to start from. See Profiles, Adopt new checks with a baseline and Ignore findings.

Coming from actionlint or zizmor

  • From actionlint. jactionlint reads the config file of actionlint. --profile correctness keeps the checks that you have, and the default profile adds the security and policy rules when you are ready for them. Coming from actionlint lists the renamed options and the differences.
  • From zizmor. Each audit of zizmor 1.30.1 has a rule, under the same ID in every case but one, and # zizmor: ignore[...] comments keep working. jactionlint and zizmor maps the audits, the personas and the settings of zizmor.yml.

Documentation

jactionlint.jdx.dev has the full documentation, and the release archives hold the same pages. These are the ones to start with:

The site documents the main branch. jactionlint --help lists what your installed version supports.

Contributing

To report a bug, a false positive or an idea for a check, open an issue with a minimal workflow that shows it. CONTRIBUTING.md explains how to build and test jactionlint and how to propose a change.

License and acknowledgments

jactionlint is distributed under the MIT license. It is a fork of actionlint by rhysd, and its security rules follow the audits of zizmor. NOTICE.md names every project that it builds on.

Documentation Âķ

Overview Âķ

Package jactionlint is the implementation of jactionlint linter. It's a static checker for GitHub Actions workflow files.

https://github.com/jdx/jactionlint

jactionlint is a command line tool but it also provides Go API for Go programs. It includes a workflow file parser built on top of yaml/go-yaml, lexer/parser/checker for expressions embedded by ${{ }} placeholder, popular actions data, available contexts information, etc.

To run the linter, Linter is the struct which manages the entire linter lifecycle. Please see the first example.

jactionlint also provides the flexibility to add your own rules by implementing Rule interface. Please read the YourOwnRule example.

Library versioning Âķ

The version is for the command line tool. So it does not represent the version of the library. It means that the library does not follow semantic versioning and any patch version bump may introduce some breaking changes.

Go version compatibility Âķ

Minimum supported Go version is written in go.mod file in this library. That said, older Go versions are actually not tested on CI. CI tests with one Go version, the toolchain which go.mod names, so that version or a newer one is recommended.

https://github.com/jdx/jactionlint/blob/main/go.mod

Other documentations Âķ

All documentations for jactionlint can be found in the following page.

https://jactionlint.jdx.dev/

License Âķ

This library is provided under the MIT license.

> Copyright (c) 2021 rhysd > > Copyright (c) 2026 jdx

Full text can be found in the following page.

https://github.com/jdx/jactionlint/blob/main/LICENSE.txt

Package jactionlint provides linting functionality for GitHub Actions workflows.

Index Âķ

Examples Âķ

Constants Âķ

View Source
const (
	// RawYAMLValueKindObject is kind for an object value of raw YAML value.
	RawYAMLValueKindObject = RawYAMLValueKind(yaml.MappingNode)
	// RawYAMLValueKindArray is kind for an array value of raw YAML value.
	RawYAMLValueKindArray = RawYAMLValueKind(yaml.SequenceNode)
	// RawYAMLValueKindString is kind for a string value of raw YAML value.
	RawYAMLValueKindString = RawYAMLValueKind(yaml.ScalarNode)
)
View Source
const (
	// ExitStatusSuccessNoProblem is the exit status when the command ran successfully with no problem found.
	ExitStatusSuccessNoProblem = 0
	// ExitStatusSuccessProblemFound is the exit status when the command ran successfully with some problem found.
	ExitStatusSuccessProblemFound = 1
	// ExitStatusInvalidCommandOption is the exit status when parsing command line options failed or the value of
	// an option is invalid (an unknown --profile, --format or --min-severity, a broken --ignore regular expression).
	ExitStatusInvalidCommandOption = 2
	// ExitStatusFailure is the exit status when the command stopped due to some fatal error while checking workflows
	// (no project, an unreadable file or config).
	ExitStatusFailure = 3
)
View Source
const (
	// PlatformGitHub is the default value of the "platform" key of the config file.
	PlatformGitHub = "github"
	// PlatformForgejo is the value for Forgejo, which accepts `uses: https://host/owner/repo@ref`.
	PlatformForgejo = "forgejo"
	// PlatformGitea is the value for Gitea, which accepts the same.
	PlatformGitea = "gitea"
)
View Source
const (
	// ConfigSchemaURL is where the JSON Schema of the config file is published. The comment which --init-config
	// writes at the top of the file points editors to it.
	ConfigSchemaURL = "https://raw.githubusercontent.com/jdx/jactionlint/main/schema/jactionlint-config.json"
	// OutputSchemaURL is where the JSON Schema of --format json is published.
	OutputSchemaURL = "https://raw.githubusercontent.com/jdx/jactionlint/main/schema/jactionlint-output.json"
)
View Source
const (
	// ExternalToolRan is the status of an external linter that was found and used for the scripts of the run.
	ExternalToolRan = "ran"
	// ExternalToolNotFound is the status of an external linter that was not found, so its scripts were not checked.
	ExternalToolNotFound = "not found"
	// ExternalToolDisabled is the status of an external linter that was turned off with an empty command. It is not
	// part of ExternalTools.
	ExternalToolDisabled = "disabled"
)
View Source
const (
	// FormatText is the default format. Each error is printed with its source snippet and an indicator.
	FormatText = "text"
	// FormatOneline prints one error per line without the source snippet.
	FormatOneline = "oneline"
	// FormatJSON prints a JSON array of the errors. It is the same as the "{{json .}}" template.
	FormatJSON = "json"
	// FormatJSONL prints one JSON object per error per line (JSON Lines).
	FormatJSONL = "jsonl"
	// FormatSARIF prints a SARIF 2.1.0 log.
	FormatSARIF = "sarif"
	// FormatGCC prints "file:line:col: severity: message [id]" like GCC does.
	FormatGCC = "gcc"
	// FormatSummary prints counts of the findings per rule and per file, new and baselined ones apart.
	FormatSummary = "summary"
	// FormatGitHub prints GitHub Actions workflow commands which annotate the files in the pull request.
	FormatGitHub = "github"
)

Output formats which --format and LinterOptions.Format accept besides Go templates.

View Source
const (
	// GeneratedFilesReport reports a generated file like any other file.
	GeneratedFilesReport = "report"
	// GeneratedFilesSkipPolicy does not report the rules of the policy and style groups in a generated file. It is the
	// default. The rules of the correctness and security groups still report.
	GeneratedFilesSkipPolicy = "skip-policy"
	// GeneratedFilesSkip reports nothing in a generated file.
	GeneratedFilesSkip = "skip"
)

Values of the "generated-files" key of the configuration.

View Source
const (
	// LogLevelNone does not output any log output.
	LogLevelNone LogLevel = 0
	// LogLevelVerbose shows verbose log output. This is equivalent to specifying --verbose option
	// to jactionlint command.
	LogLevelVerbose = 1
	// LogLevelDebug shows all log output including debug information.
	LogLevelDebug = 2
)
View Source
const (
	// DefaultTimeoutHistoryRuns is how many of the latest successful runs of each workflow are read.
	DefaultTimeoutHistoryRuns = 20
	// DefaultTimeoutBuffer is the factor by which the longest duration on record is multiplied.
	DefaultTimeoutBuffer = 2.0
)
View Source
const (
	// UpdateAvailableID is a reference that has a newer eligible release, or that the policy wants pinned.
	UpdateAvailableID = "update-available"
	// UpdateUnverifiedID is a reference whose version could not be verified or whose update could not be looked up.
	UpdateUnverifiedID = "update-unverified"
	// UpdatePolicyID is a reference that violates the update policy (its release is in the cooldown, is a prerelease,
	// or is not immutable) and for which no eligible replacement exists.
	UpdatePolicyID = "update-policy"
	// UpdateHeldID is a newer release that exists but that the policy does not allow yet. It is informational.
	UpdateHeldID = "update-held"
)

Rule IDs of the findings of `jactionlint update`. They are not rules of the linter: they name what the update found in the SARIF, JSON and text output.

View Source
const AssumeDefaultPermissionsPermissive = "permissive"

AssumeDefaultPermissionsPermissive is the config value enabling the permissive-default assumption.

View Source
const AssumeDefaultPermissionsRestricted = "restricted"

AssumeDefaultPermissionsRestricted is the config value enabling the restricted-default assumption.

View Source
const DefaultBaselineFile = ".github/jactionlint-baseline.json"

DefaultBaselineFile is the path of the baseline file relative to the root of the repository.

View Source
const DefaultImpostorMaxBranches = 1000

DefaultImpostorMaxBranches is how many branches of an action repository the impostor-commit rule compares a pinned commit with before it gives up without a verdict.

View Source
const DefaultMaxRunLines = 100

DefaultMaxRunLines is the maximum number of lines of a run: script which the max-run-lines rule allows when it is enabled by a profile without the "max" option.

View Source
const FactsSchemaURL = "https://raw.githubusercontent.com/jdx/jactionlint/main/schema/jactionlint-facts.json"

FactsSchemaURL is where the JSON Schema of --export-facts is published.

View Source
const FactsVersion = 1

FactsVersion is the version of the facts document. A field is not removed and does not change its meaning within a version; fields can be added, so a reader ignores the ones it does not know. The version changes only when a field changes meaning.

View Source
const TimeoutReportVersion = 1

TimeoutReportVersion is the version of the document of --suggest-timeouts with --format json.

Variables Âķ

View Source
var AllContexts = map[string][]string{"env": []string{"jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.defaults.run", "jobs.<job_id>.environment.url", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory"}, "github": []string{"concurrency", "env", "jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.if", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.strategy", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>", "on.workflow_call.inputs.<inputs_id>.default", "on.workflow_call.outputs.<output_id>.value", "run-name"}, "inputs": []string{"concurrency", "env", "jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.if", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.strategy", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>", "on.workflow_call.inputs.<inputs_id>.default", "on.workflow_call.outputs.<output_id>.value", "run-name"}, "job": []string{"jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.environment.url", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory"}, "jobs": []string{"on.workflow_call.outputs.<output_id>.value"}, "matrix": []string{"jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>"}, "needs": []string{"jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.if", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.strategy", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>"}, "runner": []string{"jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.environment.url", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory"}, "secrets": []string{"env", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.env", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory"}, "steps": []string{"jobs.<job_id>.environment.url", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory"}, "strategy": []string{"jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>"}, "vars": []string{"concurrency", "env", "jobs.<job_id>.concurrency", "jobs.<job_id>.container", "jobs.<job_id>.container.credentials", "jobs.<job_id>.container.env.<env_id>", "jobs.<job_id>.container.image", "jobs.<job_id>.continue-on-error", "jobs.<job_id>.defaults.run", "jobs.<job_id>.env", "jobs.<job_id>.environment", "jobs.<job_id>.environment.url", "jobs.<job_id>.if", "jobs.<job_id>.name", "jobs.<job_id>.outputs.<output_id>", "jobs.<job_id>.runs-on", "jobs.<job_id>.secrets.<secrets_id>", "jobs.<job_id>.services", "jobs.<job_id>.services.<service_id>.credentials", "jobs.<job_id>.services.<service_id>.env.<env_id>", "jobs.<job_id>.snapshot.if", "jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.strategy", "jobs.<job_id>.timeout-minutes", "jobs.<job_id>.with.<with_id>", "on.workflow_call.inputs.<inputs_id>.default", "on.workflow_call.outputs.<output_id>.value", "run-name"}}

AllContexts is a map from context name to workflow key which allows the context. This variable was generated by scraping https://docs.github.com/en/actions/reference/workflows-and-actions/contexts See the script for more details: https://github.com/jdx/jactionlint/blob/main/scripts/generate-availability/

View Source
var AllWebhookTypes = map[string][]string{
	"branch_protection_rule":      {"created", "edited", "deleted"},
	"check_run":                   {"created", "rerequested", "completed", "requested_action"},
	"check_suite":                 {"completed"},
	"create":                      {},
	"delete":                      {},
	"deployment":                  {},
	"deployment_status":           {},
	"discussion":                  {"created", "edited", "deleted", "transferred", "pinned", "unpinned", "labeled", "unlabeled", "locked", "unlocked", "category_changed", "answered", "unanswered"},
	"discussion_comment":          {"created", "edited", "deleted"},
	"fork":                        {},
	"gollum":                      {},
	"image_version":               {"created", "ready", "deleted"},
	"issue_comment":               {"created", "edited", "deleted"},
	"issues":                      {"opened", "edited", "deleted", "transferred", "pinned", "unpinned", "closed", "reopened", "assigned", "unassigned", "labeled", "unlabeled", "locked", "unlocked", "milestoned", "demilestoned", "typed", "untyped", "field_added", "field_removed"},
	"label":                       {"created", "edited", "deleted"},
	"merge_group":                 {"checks_requested"},
	"milestone":                   {"created", "closed", "opened", "edited", "deleted"},
	"page_build":                  {},
	"public":                      {},
	"pull_request":                {"assigned", "unassigned", "labeled", "unlabeled", "opened", "edited", "closed", "reopened", "synchronize", "converted_to_draft", "locked", "unlocked", "enqueued", "dequeued", "milestoned", "demilestoned", "ready_for_review", "review_requested", "review_request_removed", "auto_merge_enabled", "auto_merge_disabled", "stacked"},
	"pull_request_review":         {"submitted", "edited", "dismissed"},
	"pull_request_review_comment": {"created", "edited", "deleted"},
	"pull_request_target":         {"assigned", "unassigned", "labeled", "unlabeled", "opened", "edited", "closed", "reopened", "synchronize", "converted_to_draft", "locked", "unlocked", "enqueued", "dequeued", "milestoned", "demilestoned", "ready_for_review", "review_requested", "review_request_removed", "auto_merge_enabled", "auto_merge_disabled", "stacked"},
	"push":                        {},
	"registry_package":            {"published", "updated"},
	"release":                     {"published", "unpublished", "created", "edited", "deleted", "prereleased", "released"},
	"repository_dispatch":         nil,
	"schedule":                    {},
	"status":                      {},
	"watch":                       {"started"},
	"workflow_call":               {},
	"workflow_dispatch":           {},
	"workflow_run":                {"completed", "requested", "in_progress"},
}

AllWebhookTypes is a table of all webhooks with their types. This variable was generated by script at ./scripts/generate-webhook-events based on https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows The value is nil when the activity types cannot be determined from the document. For example repository_dispatch event can contain arbitrary types that are customized by user.

View Source
var BrandingColors = map[string]struct{}{
	"white":     {},
	"black":     {},
	"yellow":    {},
	"blue":      {},
	"green":     {},
	"orange":    {},
	"red":       {},
	"purple":    {},
	"gray-dark": {},
}

BrandingColors is a set of colors allowed at branding.color in action.yaml. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#brandingcolor

View Source
var BrandingIcons = map[string]struct{}{}/* 257 elements not displayed */

BrandingIcons is a set of icon names allowed at branding.icon in action.yaml. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#brandingicon

View Source
var BuiltinFuncSignatures = map[string][]*FuncSignature{
	"contains": {
		{
			Name: "contains",
			Ret:  BoolType{},
			Params: []ExprType{
				StringType{},
				StringType{},
			},
			IsConstFunc: true,
		},
		{
			Name: "contains",
			Ret:  BoolType{},
			Params: []ExprType{
				&ArrayType{Elem: AnyType{}},
				AnyType{},
			},
			IsConstFunc: true,
		},
	},
	"startswith": {{
		Name: "startsWith",
		Ret:  BoolType{},
		Params: []ExprType{
			StringType{},
			StringType{},
		},
		IsConstFunc: true,
	}},
	"endswith": {{
		Name: "endsWith",
		Ret:  BoolType{},
		Params: []ExprType{
			StringType{},
			StringType{},
		},
		IsConstFunc: true,
	}},
	"format": {{
		Name: "format",
		Ret:  StringType{},
		Params: []ExprType{
			StringType{},
			AnyType{},
		},
		VariableLengthParams: true,
		IsConstFunc:          true,
	}},
	"join": {
		{
			Name: "join",
			Ret:  StringType{},
			Params: []ExprType{
				&ArrayType{Elem: StringType{}},
				StringType{},
			},
			IsConstFunc: true,
		},

		{
			Name: "join",
			Ret:  StringType{},
			Params: []ExprType{
				&ArrayType{Elem: StringType{}},
			},
			IsConstFunc: true,
		},
	},
	"tojson": {{
		Name: "toJSON",
		Ret:  StringType{},
		Params: []ExprType{
			AnyType{},
		},
		IsConstFunc: true,
	}},
	"fromjson": {{
		Name: "fromJSON",
		Ret:  AnyType{},
		Params: []ExprType{
			StringType{},
		},
	}},
	"hashfiles": {{
		Name: "hashFiles",
		Ret:  StringType{},
		Params: []ExprType{
			StringType{},
		},
		VariableLengthParams: true,
	}},
	"success": {{
		Name:   "success",
		Ret:    BoolType{},
		Params: []ExprType{},
	}},
	"always": {{
		Name:   "always",
		Ret:    BoolType{},
		Params: []ExprType{},
	}},
	"cancelled": {{
		Name:   "cancelled",
		Ret:    BoolType{},
		Params: []ExprType{},
	}},
	"failure": {{
		Name:   "failure",
		Ret:    BoolType{},
		Params: []ExprType{},
	}},
	"case": {{
		Name: "case",
		Ret:  AnyType{},
		Params: []ExprType{
			BoolType{},
			AnyType{},
			AnyType{},
		},
		VariableLengthParams: true,
		IsConstFunc:          true,
	}},
}

BuiltinFuncSignatures is a set of all builtin function signatures. All function names are in lower case because function names are compared in case insensitive. https://docs.github.com/en/actions/learn-github-actions/expressions#functions

View Source
var BuiltinGlobalVariableTypes = map[string]ExprType{

	"github": NewStrictObjectType(map[string]ExprType{
		"action":                    StringType{},
		"action_path":               StringType{},
		"action_ref":                StringType{},
		"action_repository":         StringType{},
		"action_status":             StringType{},
		"actor":                     StringType{},
		"actor_id":                  StringType{},
		"api_url":                   StringType{},
		"artifact_cache_size_limit": NumberType{},
		"artifacts":                 StringType{},
		"artifacts_list":            StringType{},
		"base_ref":                  StringType{},
		"env":                       StringType{},
		"event":                     NewEmptyObjectType(),
		"event_name":                StringType{},
		"event_path":                StringType{},
		"graphql_url":               StringType{},
		"head_ref":                  StringType{},
		"job":                       StringType{},
		"job_workflow_sha":          StringType{},
		"output":                    StringType{},
		"path":                      StringType{},
		"ref":                       StringType{},
		"ref_name":                  StringType{},
		"ref_protected":             BoolType{},
		"ref_type":                  StringType{},
		"repository":                StringType{},
		"repository_id":             StringType{},
		"repository_owner":          StringType{},
		"repository_owner_id":       StringType{},
		"repository_visibility":     StringType{},
		"repositoryurl":             StringType{},
		"retention_days":            NumberType{},
		"run_attempt":               StringType{},
		"run_id":                    StringType{},
		"run_number":                StringType{},
		"secret_source":             StringType{},
		"server_url":                StringType{},
		"sha":                       StringType{},
		"state":                     StringType{},
		"step_summary":              StringType{},
		"token":                     StringType{},
		"triggering_actor":          StringType{},
		"workflow":                  StringType{},
		"workflow_ref":              StringType{},
		"workflow_sha":              StringType{},
		"workspace":                 StringType{},
	}),

	"env": NewMapObjectType(StringType{}),

	"job": NewStrictObjectType(map[string]ExprType{
		"check_run_id": NumberType{},
		"container": NewStrictObjectType(map[string]ExprType{
			"id":      StringType{},
			"network": StringType{},
		}),
		"services": NewMapObjectType(
			NewStrictObjectType(map[string]ExprType{
				"id":      StringType{},
				"network": StringType{},
				"ports":   NewMapObjectType(StringType{}),
			}),
		),
		"status":              StringType{},
		"workflow_file_path":  StringType{},
		"workflow_ref":        StringType{},
		"workflow_repository": StringType{},
		"workflow_sha":        StringType{},
	}),

	"steps": NewEmptyStrictObjectType(),

	"runner": NewStrictObjectType(map[string]ExprType{
		"name":        StringType{},
		"os":          StringType{},
		"arch":        StringType{},
		"temp":        StringType{},
		"tool_cache":  StringType{},
		"debug":       StringType{},
		"environment": StringType{},
	}),

	"secrets": NewMapObjectType(StringType{}),

	"strategy": NewObjectType(map[string]ExprType{
		"fail-fast":    BoolType{},
		"job-index":    NumberType{},
		"job-total":    NumberType{},
		"max-parallel": NumberType{},
	}),

	"matrix": NewEmptyStrictObjectType(),

	"needs": NewEmptyStrictObjectType(),

	"inputs": NewEmptyStrictObjectType(),

	"vars": NewMapObjectType(StringType{}),
}

BuiltinGlobalVariableTypes defines types of all global variables. All context variables are documented at https://docs.github.com/en/actions/learn-github-actions/contexts

View Source
var BuiltinUntrustedInputs = UntrustedInputSearchRoots{
	"github": NewUntrustedInputMap("github",
		NewUntrustedInputMap("event",
			NewUntrustedInputMap("issue",
				NewUntrustedInputMap("title"),
				NewUntrustedInputMap("body"),
			),
			NewUntrustedInputMap("pull_request",
				NewUntrustedInputMap("title"),
				NewUntrustedInputMap("body"),
				NewUntrustedInputMap("head",
					NewUntrustedInputMap("ref"),
					NewUntrustedInputMap("label"),
					NewUntrustedInputMap("repo",
						NewUntrustedInputMap("default_branch"),
						NewUntrustedInputMap("description"),
					),
				),
			),
			NewUntrustedInputMap("comment",
				NewUntrustedInputMap("body"),
			),
			NewUntrustedInputMap("review",
				NewUntrustedInputMap("body"),
			),
			NewUntrustedInputMap("review_comment",
				NewUntrustedInputMap("body"),
			),
			NewUntrustedInputMap("pages",
				NewUntrustedInputMap("*",
					NewUntrustedInputMap("page_name"),
				),
			),
			NewUntrustedInputMap("commits",
				NewUntrustedInputMap("*",
					NewUntrustedInputMap("message"),
					NewUntrustedInputMap("author",
						NewUntrustedInputMap("email"),
						NewUntrustedInputMap("name"),
					),
					NewUntrustedInputMap("committer",
						NewUntrustedInputMap("email"),
						NewUntrustedInputMap("name"),
					),
				),
			),
			NewUntrustedInputMap("head_commit",
				NewUntrustedInputMap("message"),
				NewUntrustedInputMap("author",
					NewUntrustedInputMap("email"),
					NewUntrustedInputMap("name"),
				),
				NewUntrustedInputMap("committer",
					NewUntrustedInputMap("email"),
					NewUntrustedInputMap("name"),
				),
			),
			NewUntrustedInputMap("discussion",
				NewUntrustedInputMap("title"),
				NewUntrustedInputMap("body"),
			),
			NewUntrustedInputMap("workflow_run",
				NewUntrustedInputMap("head_branch"),
				NewUntrustedInputMap("display_title"),
				NewUntrustedInputMap("head_commit",
					NewUntrustedInputMap("message"),
					NewUntrustedInputMap("author",
						NewUntrustedInputMap("email"),
						NewUntrustedInputMap("name"),
					),
					NewUntrustedInputMap("committer",
						NewUntrustedInputMap("email"),
						NewUntrustedInputMap("name"),
					),
				),
				NewUntrustedInputMap("pull_requests",
					NewUntrustedInputMap("*",
						NewUntrustedInputMap("head",
							NewUntrustedInputMap("ref"),
						),
					),
				),
				NewUntrustedInputMap("head_repository",
					NewUntrustedInputMap("description"),
					NewUntrustedInputMap("owner",
						NewUntrustedInputMap("login"),
					),
				),
			),
		),
		NewUntrustedInputMap("head_ref"),
	),
}

BuiltinUntrustedInputs is list of untrusted inputs. These inputs are detected as untrusted in `run:` scripts. See the URL for more details. - https://securitylab.github.com/research/github-actions-untrusted-input/ - https://docs.github.com/en/actions/reference/security/secure-use#good-practices-for-mitigating-script-injection-attacks - https://github.com/github/codeql/blob/main/javascript/ql/src/experimental/Security/CWE-094/ExpressionInjection.ql

View Source
var ErrGitHubBranchScanUnavailable = errors.New("branch scan unavailable")

ErrGitHubBranchScanUnavailable is returned by GitHubBranchScanner when the scan cannot be done and the caller should compare the branches one by one.

View Source
var ErrGitHubListTruncated = errors.New("the list has more pages than are read")

ErrGitHubListTruncated is returned by GitHubAdvisoryListClient.ActionAdvisories when the list is longer than the client reads. The caller must not use the part it has: it asks about each action instead.

View Source
var ErrGitHubNotCached = errors.New("not in the cache of GitHub answers")

ErrGitHubNotCached is returned (wrapped) by the built-in client in the offline mode (--online=cache) when the disk cache has no answer for a request. Nothing is sent to the network in that mode.

View Source
var ErrGitHubNotFound = errors.New("not found on GitHub")

ErrGitHubNotFound is returned (wrapped) by a GitHubClient when something does not exist or is not visible to the client.

View Source
var ErrGitHubRateLimited = errors.New("GitHub API rate limit exceeded")

ErrGitHubRateLimited is matched by errors.Is for an error returned by a GitHubClient because the API rate limit was reached. The client does not retry: the online rules stop for the run.

View Source
var ErrImageNotFound = errors.New("image not found in the registry")

ErrImageNotFound is returned (wrapped) by an ImageDigestClient when the registry has no such image, or the image is not visible without credentials.

View Source
var OutdatedPopularActionSpecs = map[string]struct{}{}/* 154 elements not displayed */

OutdatedPopularActionSpecs is a spec set of known outdated popular actions. The word 'outdated' means that the runner used by the action is no longer available such as "node12", "node16".

View Source
var PopularActionRuntimes = map[string]string{}/* 210 elements not displayed */

PopularActionRuntimes is the Node.js runtime ("runs.using") of the popular actions that run JavaScript, by spec. An action of another kind ("composite", "docker") is not in it, and neither is an outdated action (see OutdatedPopularActionSpecs). A runtime older than the one the runners have, such as "node20", means that the action declares a runtime which GitHub Actions removed.

View Source
var PopularActions = map[string]*ActionMetadata{}/* 258 elements not displayed */

PopularActions is data set of known popular actions. Keys are specs (owner/repo@ref) of actions and values are their metadata.

View Source
var SpecialFunctionNames = map[string][]string{"always": []string{"jobs.<job_id>.if", "jobs.<job_id>.steps.if", "jobs.<job_id>.snapshot.if"}, "cancelled": []string{"jobs.<job_id>.if", "jobs.<job_id>.steps.if", "jobs.<job_id>.snapshot.if"}, "failure": []string{"jobs.<job_id>.if", "jobs.<job_id>.steps.if", "jobs.<job_id>.snapshot.if"}, "hashfiles": []string{"jobs.<job_id>.steps.continue-on-error", "jobs.<job_id>.steps.env", "jobs.<job_id>.steps.if", "jobs.<job_id>.steps.name", "jobs.<job_id>.steps.run", "jobs.<job_id>.steps.timeout-minutes", "jobs.<job_id>.steps.with", "jobs.<job_id>.steps.working-directory", "jobs.<job_id>.snapshot.if"}, "success": []string{"jobs.<job_id>.if", "jobs.<job_id>.steps.if", "jobs.<job_id>.snapshot.if"}}

SpecialFunctionNames is a map from special function name to available workflow keys. Some functions are only available at specific positions. This variable is useful when you want to know which functions are special and what workflow keys support them.

This variable was generated from https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability. See the script for more details: https://github.com/jdx/jactionlint/blob/main/scripts/generate-availability/

Functions Âķ

func ConfigSchema Âķ added in v2.2.0

func ConfigSchema() []byte

ConfigSchema returns the JSON Schema (draft-07) of the config file as indented JSON. Rule IDs are an enum and each rule lists its options, so editors complete and check them.

func ContainsExpression Âķ

func ContainsExpression(s string) bool

ContainsExpression checks if the given string contains a ${{ }} placeholder or not. This function is identical to String.ContainsExpression method except for taking a standard string value.

func EqualTypes Âķ

func EqualTypes(l, r ExprType) bool

EqualTypes returns if the two types are equal.

func FactsSchema Âķ added in v2.2.0

func FactsSchema() []byte

FactsSchema returns the JSON Schema (draft-07) of the document of --export-facts as indented JSON. Like the schema of the findings it does not set additionalProperties: fields are added within a version, so a reader ignores the ones it does not know. TestFactsSchemaMatchesTypes keeps it in step with the types of facts.go.

func HintsDisabledByEnv Âķ

func HintsDisabledByEnv() bool

HintsDisabledByEnv reports whether JACTIONLINT_NO_HINTS asks for no hints about the run.

func IsActionPath Âķ

func IsActionPath(p string) bool

IsActionPath reports whether the path is the metadata file of an action: a file named action.yml or action.yaml that is not directly in ".github/workflows" (where every YAML file is a workflow). GitHub loads only the files directly in that directory as workflows, so the file of a subdirectory is the action which a `uses: ./.github/workflows/dir` refers to.

func LexExpression Âķ

func LexExpression(src string) ([]*Token, int, *ExprError)

LexExpression lexes the given string as expression syntax. The parameter must contain '}}' which represents end of expression. Otherwise this function will report an error that it encountered unexpected EOF.

func MigrateConfig Âķ

func MigrateConfig(src []byte) ([]byte, []string, error)

MigrateConfig rewrites the deprecated keys of the content of a config file ("require-shell: true", "timeout-minutes: {...}" and so on) into the "rules" mapping. Rules which are already listed in "rules" are not changed. Comments and the other keys are kept. It returns the rewritten content and the deprecated keys which were migrated. When the config has no deprecated key, the returned content is the input and the list is empty.

func MigrateConfigFile Âķ

func MigrateConfigFile(path string) ([]string, error)

MigrateConfigFile rewrites the deprecated keys of the config file at the path in place. See MigrateConfig. The file is not touched when it has no deprecated key.

func MigrateZizmorIgnoreFiles Âķ

func MigrateZizmorIgnoreFiles(paths []string) (map[string][]string, error)

MigrateZizmorIgnoreFiles runs MigrateZizmorIgnores on the files and writes the files which changed. It returns the migrated audit names by file path, only for the files which changed.

func MigrateZizmorIgnores Âķ

func MigrateZizmorIgnores(src []byte) ([]byte, []string)

MigrateZizmorIgnores rewrites the trailing `# zizmor: ignore[...]` comments of a workflow into `# jactionlint ignore=...` comments on the line above, with the same indentation, and returns the new content and the audit names which were migrated. The reason after the brackets moves to a plain comment line above. An audit without a counterpart in jactionlint, or whose findings are only a part of a jactionlint diagnostic (unpinned-images), stays in the zizmor comment, which jactionlint keeps honoring. Comments which are not trailing are left alone. The result is unchanged when nothing can be migrated, so running it twice changes nothing. When the rewritten file would not have the same YAML data as the original, the source is returned unchanged. A comment on a line which starts a sequence item stays when the item has more lines, because the comment above would cover them too.

func OutputSchema Âķ added in v2.2.0

func OutputSchema() []byte

OutputSchema returns the JSON Schema (draft-07) of the findings of --format json (an array of findings) and --format jsonl (one finding per line, which is validated by #/definitions/finding). It is the contract for the programs which read them: a field is never removed or renamed within a major version, and fields can be added, so a reader must ignore the fields it does not know.

func Parse Âķ

func Parse(b []byte) (*Workflow, []*Error)

Parse parses given source as byte sequence into workflow syntax tree. It returns all errors detected while parsing the input. It means that detecting one error does not stop parsing. Even if one or more errors are detected, parser will try to continue parsing and finding more errors.

func ParseAction Âķ

func ParseAction(b []byte) (*Workflow, []*Error)

ParseAction parses the content of an action metadata file (action.yml). It returns all errors detected while parsing the input. Like Parse, detecting one error does not stop parsing. The returned workflow is nil only when the input is not valid YAML.

func ParseDependabot Âķ

func ParseDependabot(b []byte) (*Dependabot, []*Error)

ParseDependabot parses given source as the Dependabot configuration (.github/dependabot.yml). It returns all errors detected while parsing the input. Like Parse, detecting one error does not stop parsing.

func RenderYAMLValue Âķ

func RenderYAMLValue(s string) string

RenderYAMLValue returns the string as a whole YAML scalar for the value of a mapping entry in the block style: plain when that reads back as the same string, or else in double quotes. It checks with the YAML parser, so "true", "1.0", "null", "a: b", "# x" and the like are quoted.

func RuleDocURL Âķ

func RuleDocURL(id string) string

RuleDocURL returns the URL of the documentation of the rule with the given ID.

func VisitExprNode Âķ

func VisitExprNode(n ExprNode, f VisitExprNodeFunc)

VisitExprNode visits the given expression syntax tree with given function f.

func WorkflowKeyAvailability Âķ

func WorkflowKeyAvailability(key string) ([]string, []string)

WorkflowKeyAvailability returns contexts and special functions availability of the given workflow key. 1st return value indicates what contexts are available. Empty slice means no contexts are available. 2nd return value indicates what special functions are available. Empty slice means no special functions are available. The 'key' parameter should represents a workflow key like "jobs.<job_id>.concurrency".

This function was generated from https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability. See the script for more details: https://github.com/jdx/jactionlint/blob/main/scripts/generate-availability/

Types Âķ

type ActionCalledByFacts Âķ added in v2.2.0

type ActionCalledByFacts struct {
	// Known is false when no workflow of the repository runs the action: it may be published for other repositories, and
	// its events are unknown.
	Known   bool                 `json:"known"`
	Callers []*ActionCallerFacts `json:"callers"`
}

ActionCalledByFacts are the local workflows that run an action.

type ActionCaller Âķ

type ActionCaller struct {
	// Workflow is the path of the workflow file, relative to the root of the repository with "/" as the
	// separator.
	Workflow string
	// Via lists the local actions and reusable workflows between the workflow and the action, outermost
	// first, as paths relative to the root of the repository. It is empty when the workflow runs the
	// action in one of its own steps.
	Via []string
	// Events are the events which trigger the workflow, without workflow_call. They are empty when the
	// workflow is only called by other workflows, which is not known.
	Events []Event
	// contains filtered or unexported fields
}

ActionCaller is one local workflow which (directly or through other local actions and reusable workflows) runs an action.

type ActionCallerFacts Âķ added in v2.2.0

type ActionCallerFacts struct {
	Workflow string `json:"workflow"`
	// Via are the local actions and reusable workflows between the workflow and the action, outermost first. It is
	// empty when a step of the workflow runs the action.
	Via []string `json:"via,omitempty"`
	// Events are the events of the workflow, without workflow_call. Empty means they are not known.
	Events []string `json:"events"`
	// Inputs are what the steps of the workflow pass in "with:". They are given only when a step of the workflow runs the
	// action itself (Via is empty).
	Inputs []InputFact `json:"inputs,omitempty"`
}

ActionCallerFacts is one workflow that runs an action.

type ActionCallers Âķ

type ActionCallers struct {
	// Dir is the directory of the action relative to the root of the repository with "/" as the
	// separator. It is "." for an action.yml in the root.
	Dir string
	// Callers are sorted by the path of the workflow.
	Callers []*ActionCaller
}

ActionCallers are the local workflows which run an action. It lets the rules which depend on the context of the run (the trigger) judge the steps of a composite action.

The context is the most dangerous one among the callers: an action called by a "pull_request" workflow and by a "pull_request_target" workflow is checked as if it ran in the second one. When no local workflow calls the action (it is published for other repositories, or only used by workflows which are not in the repository), Callers is empty and the rules assume nothing about the trigger: they judge the action by its own steps.

func (*ActionCallers) Dangerous Âķ

func (c *ActionCallers) Dangerous() (*ActionCaller, string)

Dangerous returns the caller whose trigger is the most dangerous, and the name of the trigger. It returns nil when no caller has an event.

func (*ActionCallers) Describe Âķ

func (c *ActionCallers) Describe() string

Describe tells in a message where the context comes from, for example "called from .github/workflows/release.yml, which runs on pull_request_target". When no workflow calls the action it says so. It is "" when the action is not a composite action.

func (*ActionCallers) Events Âķ

func (c *ActionCallers) Events() []Event

Events returns the events of all callers.

func (*ActionCallers) Known Âķ

func (c *ActionCallers) Known() bool

Known reports whether a local workflow runs the action.

func (*ActionCallers) RunsOn Âķ

func (c *ActionCallers) RunsOn(event string) (*ActionCaller, bool)

RunsOn reports whether any caller runs on the event.

type ActionFacts Âķ added in v2.2.0

type ActionFacts struct {
	// Path is the file, relative to the root of the repository with "/" as the separator.
	Path   string `json:"path"`
	Parsed bool   `json:"parsed"`
	// SyntaxErrors counts the syntax errors of the file.
	SyntaxErrors int         `json:"syntax_errors,omitempty"`
	Name         *StringFact `json:"name,omitempty"`
	// Using is the runtime: "composite", "docker" or "node20" and the like.
	Using  string   `json:"using,omitempty"`
	Inputs []string `json:"inputs,omitempty"`
	// CalledBy says which workflows of the repository run it. It is absent when the file belongs to no repository.
	CalledBy *ActionCalledByFacts `json:"called_by,omitempty"`
	// Steps are the steps of a composite action.
	Steps []*StepFacts `json:"steps,omitempty"`
}

ActionFacts are the facts of an action.yml.

type ActionFile Âķ

type ActionFile struct {
	// Name is the "name" of the action. It can be nil.
	Name *String
	// Author is the "author" of the action. It can be nil.
	Author *String
	// Description is the "description" of the action. It can be nil.
	Description *String
	// Inputs are the "inputs" of the action in the order of the source. Their IDs are case-insensitive.
	Inputs []*ActionFileInput
	// Outputs are the "outputs" of the action in the order of the source.
	Outputs []*ActionFileOutput
	// Runs is the "runs" section. It is nil only when the section is missing.
	Runs *ActionFileRuns
	// Pos is the position of the file.
	Pos *Pos
	// Callers tells which local workflows run the action. The linter sets it when it knows the
	// repository; it is nil when it does not (for example when linting standard input) and then
	// the rules which depend on the caller assume nothing about it. See ActionCallers.
	Callers *ActionCallers
}

ActionFile is the syntax tree of the metadata file of an action (action.yml or action.yaml). It is not the same as ActionMetadata, which only has what is needed to check the inputs of a step which uses the action. ActionFile keeps positions and the steps of a composite action so that the rules which check steps can check them too.

ParseAction returns a Workflow with ActionFile in its Action field. The steps of a composite action are in one synthetic job of the workflow (see Job.Composite), so the rules which visit steps visit them like the steps of a workflow job. Actions of other kinds ("node" and "docker") have no job.

https://docs.github.com/en/actions/reference/workflows-and-actions/metadata-syntax

type ActionFileInput Âķ

type ActionFileInput struct {
	// ID is the name of the input.
	ID *String
	// Description is the "description" of the input.
	Description *String
	// Required is the "required" of the input.
	Required *Bool
	// Default is the "default" of the input. It is nil when the input has no default.
	Default *String
	// DeprecationMessage is the "deprecationMessage" of the input.
	DeprecationMessage *String
}

ActionFileInput is one input in the "inputs" section of an action.

type ActionFileOutput Âķ

type ActionFileOutput struct {
	// ID is the name of the output.
	ID *String
	// Description is the "description" of the output.
	Description *String
	// Value is the "value" of the output of a composite action. It is nil for other actions.
	Value *String
}

ActionFileOutput is one output in the "outputs" section of an action.

type ActionFileRuns Âķ

type ActionFileRuns struct {
	// Using is the "using" key: "composite", "docker" or "node20" and the like.
	Using *String
	// Pos is the position of the "runs" key.
	Pos *Pos
	// Steps are the "steps" of a composite action.
	Steps []*Step
	// Main is the "main" script of a JavaScript action.
	Main *String
	// Image is the "image" of a Docker action: "Dockerfile" or "docker://image:tag".
	Image *String
	// PreIf and PostIf are the "pre-if" and "post-if" conditions of a JavaScript or Docker action. They are
	// nil when the key is missing.
	PreIf, PostIf *String
}

ActionFileRuns is the "runs" section of an action.

func (*ActionFileRuns) IsComposite Âķ

func (r *ActionFileRuns) IsComposite() bool

IsComposite reports whether the action runs steps like a job: "runs.using" is "composite".

type ActionMetadata Âķ

type ActionMetadata struct {

	// Name is "name" field of action.yaml.
	Name string `yaml:"name" json:"name"`
	// Description is "description" field of action.yaml.
	Description string `yaml:"description" json:"-"`
	// Inputs is "inputs" field of action.yaml.
	Inputs ActionMetadataInputs `yaml:"inputs" json:"inputs"`
	// Outputs is "outputs" field of action.yaml. Key is name of output. Description is omitted
	// since jactionlint does not use it.
	Outputs ActionMetadataOutputs `yaml:"outputs" json:"outputs"`
	// SkipInputs is flag to specify behavior of inputs check. When it is true, inputs for this
	// action will not be checked.
	SkipInputs bool `yaml:"-" json:"skip_inputs"`
	// SkipOutputs is flag to specify a bit loose typing to outputs object. If it is set to
	// true, the outputs object accepts any properties along with strictly typed props.
	SkipOutputs bool `yaml:"-" json:"skip_outputs"`
	// Runs is "runs" field of action.yaml.
	Runs ActionMetadataRuns `yaml:"runs" json:"runs"`
	// Branding is "branding" field of action.yaml.
	Branding ActionMetadataBranding `yaml:"branding" json:"-"`
	// contains filtered or unexported fields
}

ActionMetadata represents structure of action.yaml. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions

func (*ActionMetadata) Dir Âķ

func (md *ActionMetadata) Dir() string

Dir returns a directory path of the action.

func (*ActionMetadata) Path Âķ

func (md *ActionMetadata) Path() string

Path returns a file path of the action's metadata file.

type ActionMetadataBranding Âķ

type ActionMetadataBranding struct {
	Icon  string `yaml:"icon"`
	Color string `yaml:"color"`
}

ActionMetadataBranding is "branding" section of action.yaml. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#branding

type ActionMetadataInput Âķ

type ActionMetadataInput struct {
	// Name is a name of this input.
	Name string `json:"name"`
	// Required is true when this input is mandatory to run the action.
	Required bool `json:"required"`
	// Deprecated is true when this input is marked as deprecated.
	Deprecated bool `json:"deprecated"`
	// DeprecationMessage is a deprecation message for the deprecated input.
	DeprecationMessage string `json:"deprecation-message"`
}

ActionMetadataInput is input metadata in "inputs" section in action.yml metadata file. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#inputs

type ActionMetadataInputs Âķ

type ActionMetadataInputs map[string]*ActionMetadataInput

ActionMetadataInputs is a map from input ID to its metadata. Keys are in lower case since input names are case-insensitive. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#inputs

func (*ActionMetadataInputs) UnmarshalYAML Âķ

func (inputs *ActionMetadataInputs) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ActionMetadataOutput Âķ

type ActionMetadataOutput struct {
	Name string `json:"name"`
}

ActionMetadataOutput is output metadata in "outputs" section in action.yml metadata file. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#outputs-for-composite-actions

type ActionMetadataOutputs Âķ

type ActionMetadataOutputs map[string]*ActionMetadataOutput

ActionMetadataOutputs is a map from output ID to its metadata. Keys are in lower case since output names are case-insensitive. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#outputs-for-composite-actions

func (*ActionMetadataOutputs) UnmarshalYAML Âķ

func (inputs *ActionMetadataOutputs) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ActionMetadataRuns Âķ

type ActionMetadataRuns struct {
	// Using is `using` configuration of action.yaml. It defines what runner is used for the action.
	Using string `yaml:"using" json:"using"`
	// Main is `main` configuration of action.yaml for JavaScript action.
	Main string `yaml:"main" json:"main"`
	// Pre is `pre` configuration of action.yaml for JavaScript action.
	Pre string `yaml:"pre" json:"pre"`
	// PreIf is `pre-if` configuration of action.yaml for JavaScript action.
	PreIf string `yaml:"pre-if" json:"pre-if"`
	// Post is `post` configuration of action.yaml for JavaScript action.
	Post string `yaml:"post" json:"post"`
	// PostIf is `post-if` configuration of action.yaml for JavaScript action.
	PostIf string `yaml:"post-if" json:"post-if"`
	// Steps is `steps` configuration of action.yaml for Composite action.
	Steps []any `yaml:"steps" json:"steps"`
	// Image is `image` of action.yaml for Docker action.
	Image string `yaml:"image" json:"image"`
	// PreEntrypoint is `pre-entrypoint` of action.yaml for Docker action.
	PreEntrypoint string `yaml:"pre-entrypoint" json:"pre-entrypoint"`
	// Entrypoint is `entrypoint` of action.yaml for Docker action.
	Entrypoint string `yaml:"entrypoint" json:"entrypoint"`
	// PostEntrypoint is `post-entrypoint` of action.yaml for Docker action.
	PostEntrypoint string `yaml:"post-entrypoint" json:"post-entrypoint"`
	// Args is `args` of action.yaml for Docker action.
	Args []any `yaml:"args" json:"args"`
	// Env is `env` of action.yaml for Docker action.
	Env map[string]any `yaml:"env" json:"env"`
}

ActionMetadataRuns is "runs" section of action.yaml. It defines how the action is run. https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#runs

type AnyType Âķ

type AnyType struct{}

AnyType represents type which can be any type. It also indicates that a value of the type cannot be type-checked since it's type cannot be known statically.

func (AnyType) Assignable Âķ

func (ty AnyType) Assignable(_ ExprType) bool

Assignable returns if other type can be assignable to the type.

func (AnyType) DeepCopy Âķ

func (ty AnyType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (AnyType) Merge Âķ

func (ty AnyType) Merge(other ExprType) ExprType

Merge merges other type into this type. When other type conflicts with this type, the merged result is any type as fallback.

func (AnyType) String Âķ

func (ty AnyType) String() string

type ArrayDerefNode Âķ

type ArrayDerefNode struct {
	// Receiver is an expression at receiver of array element dereference.
	Receiver ExprNode
}

ArrayDerefNode represents elements dereference of arrays like '*' in 'foo.bar.*.piyo'.

func (ArrayDerefNode) Token Âķ

func (n ArrayDerefNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type ArrayType Âķ

type ArrayType struct {
	// Elem is type of element of the array.
	Elem ExprType
	// Deref is true when this type was derived from object filtering syntax (foo.*).
	Deref bool
}

ArrayType is type for arrays.

func (*ArrayType) Assignable Âķ

func (ty *ArrayType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type.

func (*ArrayType) DeepCopy Âķ

func (ty *ArrayType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (*ArrayType) Merge Âķ

func (ty *ArrayType) Merge(other ExprType) ExprType

Merge merges two object types into one. When other object has unknown props, they are merged into current object. When both have same property, when they are assignable, it remains as-is. Otherwise, the property falls back to any type.

func (*ArrayType) String Âķ

func (ty *ArrayType) String() string

type Baseline Âķ

type Baseline struct {
	// Version is the format version of the file.
	Version int `json:"version"`
	// Entries are the accepted findings in the order of the file.
	Entries []*BaselineEntry `json:"entries"`
}

Baseline is a set of accepted findings. See ReadBaselineFile.

func ParseBaseline Âķ

func ParseBaseline(b []byte) (*Baseline, error)

ParseBaseline parses the content of a baseline file.

func ReadBaselineFile Âķ

func ReadBaselineFile(path string) (*Baseline, error)

ReadBaselineFile reads a baseline file written by "jactionlint --baseline-write".

func (*Baseline) Marshal Âķ

func (bl *Baseline) Marshal() ([]byte, error)

Marshal returns the content of the baseline file. The output is deterministic so writing the same findings twice gives the same bytes.

type BaselineEntry Âķ

type BaselineEntry struct {
	// File is the path of the file relative to the root of the repository, with forward slashes.
	File string `json:"file"`
	// Rule is the ID of the rule which reported the finding.
	Rule string `json:"rule"`
	// Fingerprint is a hash of the rule, the enclosing job or top-level key, the trimmed source line
	// and the normalized message.
	Fingerprint string `json:"fingerprint"`
	// Context is a hash of the same without the message. A finding whose fingerprint changed only
	// because a new release rewords the message still matches the entry through it.
	Context string `json:"context"`
	// Occurrence tells identical findings (same fingerprint in the same file) apart, counting from 0
	// in the order of the file.
	Occurrence int `json:"occurrence"`
	// Message is the message of the finding when the baseline was written. It is for people reading the
	// file; matching does not use it.
	Message string `json:"message"`
	// contains filtered or unexported fields
}

BaselineEntry is one accepted finding of a baseline file. It identifies the finding without its line number so that it survives edits which only move the line: the file, the rule, a fingerprint of the finding and an occurrence index for findings that look identical.

type Bool Âķ

type Bool struct {
	// Value is a raw value of the bool string.
	Value bool
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Bool represents generic boolean value in YAML file with position.

func (*Bool) String Âķ

func (b *Bool) String() string

type BoolNode Âķ

type BoolNode struct {
	// Value is value of the boolean literal.
	Value bool
	// contains filtered or unexported fields
}

BoolNode is node for boolean literal, true or false.

func (*BoolNode) Token Âķ

func (n *BoolNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type BoolType Âķ

type BoolType struct{}

BoolType is type for boolean values.

func (BoolType) Assignable Âķ

func (ty BoolType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type.

func (BoolType) DeepCopy Âķ

func (ty BoolType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (BoolType) Merge Âķ

func (ty BoolType) Merge(other ExprType) ExprType

Merge merges other type into this type. When other type conflicts with this type, the merged result is any type as fallback.

func (BoolType) String Âķ

func (ty BoolType) String() string

type CallFacts Âķ added in v2.2.0

type CallFacts struct {
	// Kind is "reusable-workflow" or "action".
	Kind string `json:"kind"`
	// From is the file with the call, Job the job, and Step the index of the step (absent for a job that calls a workflow).
	From     string    `json:"from"`
	Job      string    `json:"job,omitempty"`
	Step     *int      `json:"step,omitempty"`
	Location *Location `json:"location,omitempty"`
	// To is the file or the directory of the callee, relative to the root of the repository.
	To string `json:"to"`
	// Permissions are the permissions of the token of the calling job: what the callee can have at most.
	Permissions *EffectivePermissions `json:"permissions,omitempty"`
	// Events are the events of the calling workflow (without workflow_call). Empty means that no event of its own is
	// known.
	Events []string `json:"events"`
}

CallFacts is a call of a local reusable workflow or action.

type CalledByFacts Âķ added in v2.2.0

type CalledByFacts struct {
	// Callers are the files that call it directly, sorted: workflows and composite actions of the repository.
	Callers []string `json:"callers"`
	// Events are the events of the workflows that reach it, directly or through other reusable workflows, without
	// workflow_call. Sorted.
	Events []string `json:"events"`
	// Known is true when every chain of calls ends in a workflow of this repository with events of its own. It is false
	// when nothing in the repository calls the workflow, or a caller is itself only called: another repository may then
	// call it on any event, and Events is not all of them.
	Known bool `json:"known"`
}

CalledByFacts are the local callers of a reusable workflow.

type ChangedInfo Âķ added in v2.2.0

type ChangedInfo struct {
	// Since is the revision that was asked for.
	Since string `json:"since"`
	// Scope is "lines" or "files".
	Scope string `json:"scope"`
	// Hidden counts the findings that were not shown because they are outside what changed. Baselined findings are
	// not counted here.
	Hidden int `json:"hidden"`
}

ChangedInfo is what --changed-since did in a run. The SARIF log has it in properties.changedSince, so that a consumer can tell a log with the findings of a diff from a full one.

type ChangedScope Âķ added in v2.2.0

type ChangedScope string

ChangedScope says how much of a changed file is shown.

const (
	// ChangedScopeLines shows the findings on the changed lines (the default).
	ChangedScopeLines ChangedScope = "lines"
	// ChangedScopeFiles shows every finding of a file that changed.
	ChangedScopeFiles ChangedScope = "files"
)

func ParseChangedScope Âķ added in v2.2.0

func ParseChangedScope(s string) (ChangedScope, error)

ParseChangedScope reads the value of --changed-scope.

type ColorOptionKind Âķ

type ColorOptionKind int

ColorOptionKind is kind of colorful output behavior.

const (
	// ColorOptionKindAuto is kind to determine to colorize errors output automatically. It is
	// determined based on pty and $NO_COLOR environment variable. See document of fatih/color
	// for more details.
	ColorOptionKindAuto ColorOptionKind = iota
	// ColorOptionKindAlways is kind to always colorize errors output.
	ColorOptionKindAlways
	// ColorOptionKindNever is kind never to colorize errors output.
	ColorOptionKindNever
)

type Command Âķ

type Command struct {
	// Stdin is a reader to read input from stdin
	Stdin io.Reader
	// Stdout is a writer to write output to stdout
	Stdout io.Writer
	// Stderr is a writer to write output to stderr
	Stderr io.Writer
	// contains filtered or unexported fields
}

Command represents entire jactionlint command. Given stdin/stdout/stderr are used for input/output.

Example Âķ
package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"

	"github.com/jdx/jactionlint/v2"
)

func main() {
	// Write command output to this buffer
	var output bytes.Buffer

	// Create command instance populating stdin/stdout/stderr
	cmd := jactionlint.Command{
		Stdin:  os.Stdin,
		Stdout: &output,
		Stderr: &output,
	}

	// Run the command end-to-end. Note that given args should contain program name
	workflow := filepath.Join(".github", "workflows", "release.yaml")
	status := cmd.Main([]string{"jactionlint", "--shellcheck=", "--pyflakes=", workflow})

	fmt.Println("Exited with status", status)

	if status != 0 {
		panic("jactionlint command failed: " + output.String())
	}
}
Output:
Exited with status 0

func (*Command) Main Âķ

func (cmd *Command) Main(args []string) int

Main is main function of jactionlint. It takes command line arguments as string slice and returns exit status. The args should be entire arguments including the program name, usually given via os.Args.

type Comment Âķ

type Comment struct {
	// Line is the 1-based line of the comment.
	Line int
	// Column is the 1-based column of the '#', counted in characters like the positions of the syntax tree.
	Column int
	// Text is the comment without the leading '#' and the surrounding white space.
	Text string
	// Inline is true for a comment following YAML content on its line ("key: value # comment") and
	// false for a comment which has the line to itself.
	Inline bool
}

Comment is one YAML comment of a source file.

type CommentIndex Âķ

type CommentIndex struct {
	// contains filtered or unexported fields
}

CommentIndex finds the comments of a YAML file by line. The YAML library does not tell where a comment is, only which node it is loosely attached to (and attaches the comment at the end of the file to an unrelated key), so the index is built by scanning the source instead. It understands what is not a comment: '#' inside quoted scalars, block scalars ("|" and ">") and plain scalars ("a#b").

Workflow.Comments is the index of a parsed workflow. A syntax node is located by Pos.Line, so a rule asks about the comments of a node with Inline(n.Pos.Line), Before(n.Pos.Line) or Documented(n.Pos.Line). All methods accept a nil index, which has no comments.

Known limit: a continuation line of a multi-line plain scalar that starts with a quote is read as the start of a quoted scalar.

func NewCommentIndex Âķ

func NewCommentIndex(src []byte) *CommentIndex

NewCommentIndex scans src for comments.

func (*CommentIndex) After Âķ

func (idx *CommentIndex) After(line int) []Comment

After returns the comments which sit on the lines directly below the line, in source order, up to the first blank line or line of content. Those comments are also what Before reports for the node which follows. The syntax tree has no end position, so for a node spanning several lines the caller must pass its last line.

func (*CommentIndex) All Âķ

func (idx *CommentIndex) All() []Comment

All returns every comment in the order of the source.

func (*CommentIndex) At Âķ

func (idx *CommentIndex) At(line int) *Comment

At returns the comment on the line, inline or not, or nil.

func (*CommentIndex) Before Âķ

func (idx *CommentIndex) Before(line int) []Comment

Before returns the comments which sit on the lines directly above the line, in source order. The block ends at the first blank line or line of content going up, so a comment separated by a blank line belongs to nobody.

func (*CommentIndex) Documented Âķ

func (idx *CommentIndex) Documented(line int) bool

Documented reports whether the line is explained by a comment: one trailing the line or a block directly above it.

func (*CommentIndex) Inline Âķ

func (idx *CommentIndex) Inline(line int) *Comment

Inline returns the comment which follows content on the line ("key: value # comment"), or nil. In a flow collection, or after an anchor, it is the comment at the end of the line which holds the node.

type CompareOpNode Âķ

type CompareOpNode struct {
	// Kind is a kind of this expression to show which operator is used.
	Kind CompareOpNodeKind
	// Left is an expression for left hand side of the binary operator.
	Left ExprNode
	// Right is an expression for right hand side of the binary operator.
	Right ExprNode
}

CompareOpNode is node for binary expression to compare values; ==, !=, <, <=, > or >=.

func (*CompareOpNode) Token Âķ

func (n *CompareOpNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type CompareOpNodeKind Âķ

type CompareOpNodeKind int

CompareOpNodeKind is a kind of compare operators; ==, !=, <, <=, >, >=.

const (
	// CompareOpNodeKindInvalid is invalid and initial value of CompareOpNodeKind values.
	CompareOpNodeKindInvalid CompareOpNodeKind = iota
	// CompareOpNodeKindLess is kind for < operator.
	CompareOpNodeKindLess
	// CompareOpNodeKindLessEq is kind for <= operator.
	CompareOpNodeKindLessEq
	// CompareOpNodeKindGreater is kind for > operator.
	CompareOpNodeKindGreater
	// CompareOpNodeKindGreaterEq is kind for >= operator.
	CompareOpNodeKindGreaterEq
	// CompareOpNodeKindEq is kind for == operator.
	CompareOpNodeKindEq
	// CompareOpNodeKindNotEq is kind for != operator.
	CompareOpNodeKindNotEq
)

func (CompareOpNodeKind) IsEqualityOp Âķ

func (kind CompareOpNodeKind) IsEqualityOp() bool

IsEqualityOp returns true when it represents == or != operator.

func (CompareOpNodeKind) String Âķ

func (kind CompareOpNodeKind) String() string

type Concurrency Âķ

type Concurrency struct {
	// Group is name of the concurrency group.
	Group *String
	// CancelInProgress is a flag that shows if canceling this workflow cancels other jobs in progress.
	CancelInProgress *Bool
	// Queue is the queue strategy for pending workflow runs. Valid values are "single" (default) and "max".
	Queue *String
	// Bare is true when the concurrency is written as a plain group name (`concurrency: my-group`)
	// instead of a mapping. This form cannot cancel runs in progress. It is false for `concurrency: ${{ ... }}`
	// (see Expression).
	Bare bool
	// Expression is the expression of a concurrency written as one expression, such as
	// `concurrency: ${{ fromJSON(vars.CONCURRENCY) }}`. It can evaluate to a group name or to a mapping, so the form
	// is not known. Group is the same expression. Otherwise nil.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Concurrency is a configuration of concurrency of the workflow. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#concurrency

type ConcurrencyFacts Âķ added in v2.2.0

type ConcurrencyFacts struct {
	// Form is "mapping" (group and cancel-in-progress), "group" (only a group name, which cannot cancel) or
	// "expression" (the whole key is an expression, so the group and the flag are unknown).
	Form  string      `json:"form"`
	Group *StringFact `json:"group,omitempty"`
	// CancelInProgress is "true", "false", "unset" (not written: nothing is cancelled) or "unknown" (an expression).
	CancelInProgress string `json:"cancel_in_progress"`
	// Queue is the queue strategy, when written.
	Queue    string    `json:"queue,omitempty"`
	Location *Location `json:"location,omitempty"`
}

ConcurrencyFacts is a "concurrency:" of a workflow or a job.

type Config Âķ

type Config struct {
	// Profile selects the set of rules which are enabled by default: "correctness", "default" or
	// "pedantic". The empty value means ProfileDefault. See Rules for which rules each profile enables.
	// The retired names "strict" and "all" are read as "pedantic" with a deprecation warning.
	Profile Profile `yaml:"profile"`
	// Extends is a list of config files to inherit from. Relative paths are resolved from the directory
	// of the config file listing them. Later files win over earlier ones, and the config file itself
	// wins over all of them. ReadConfigFile loads them and merges them into the returned Config.
	Extends []string `yaml:"extends"`
	// Online turns on the online checks (see LinterOptions.Online) for the files this configuration
	// applies to, like the --online flag does for the whole run. They query the GitHub API.
	Online bool `yaml:"online"`
	// Baseline controls the baseline of accepted findings (see "jactionlint --baseline-write"). "auto" (or
	// true) applies the file .github/jactionlint-baseline.json when it exists, false or empty does not
	// apply a baseline, and any other value is the path of the baseline file relative to the root of the
	// repository, which must exist. The --baseline flag overrides it.
	Baseline string `yaml:"baseline"`
	// OnlineOptions tunes the online checks: the mode ("cache" for offline use from the disk cache,
	// "strict" to fail when a lookup is skipped), the API URL of GitHub Enterprise Server, where the
	// token comes from, which repositories may be looked up, and the cache and retry behavior. A mode
	// of "cache" or "strict" turns the online checks on, unless "online: false" is written explicitly. They apply to the whole run: the
	// run uses the configuration of the first file for which the online checks run.
	OnlineOptions OnlineOptions `yaml:"online-options"`
	// Rules sets the level and the options of each rule by rule ID. A rule not listed here follows the
	// profile.
	Rules map[string]RuleConfig `yaml:"rules"`
	// SelfHostedRunner is configuration for self-hosted runner.
	SelfHostedRunner struct {
		// Labels is label names for self-hosted runner.
		Labels []string `yaml:"labels"`
		// StrictLabels makes the runner-label rule accept only the labels listed in Labels. When true, the
		// built-in labels (GitHub-hosted runner labels and the preset self-hosted labels such as "self-hosted"
		// and "linux") are reported as unknown unless they are explicitly listed in Labels.
		StrictLabels bool `yaml:"strict-labels"`
		// Providers names the hosted-runner providers whose labels the runner-label rule accepts (blacksmith,
		// depot, namespace, runson, ubicloud and warpbuild). Nil, which is the default, accepts all of them; an
		// empty list accepts none. Labels of other providers belong in Labels. It has no effect when StrictLabels is
		// true.
		Providers []string `yaml:"providers"`
	} `yaml:"self-hosted-runner"`
	// ConfigVariables is names of configuration variables used in the checked workflows. When this value is nil,
	// property names of `vars` context will not be checked. Otherwise jactionlint will report a name which is not
	// listed here as undefined config variables.
	// https://docs.github.com/en/actions/learn-github-actions/variables
	ConfigVariables []string `yaml:"config-variables"`
	// ConfigSecrets is names of secrets used in the checked workflows. When this value is nil,
	// property names of `secrets` context will not be checked. Otherwise jactionlint will report a name which is not
	// listed here as undefined secrets.
	// https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
	ConfigSecrets []string `yaml:"config-secrets"`
	// Paths is a "paths" mapping in the configuration file. The keys are glob patterns to match file paths.
	// And the values are corresponding configurations applied to the file paths.
	Paths map[string]PathConfig `yaml:"paths"`

	// Ignores is the "ignores" list: findings to accept, matched by rule and by where they are (file,
	// job, step, uses) instead of by line, so that they survive tools rewriting the workflow. See
	// ConfigIgnore. The lists of the files listed in "extends" are concatenated, the extended files first.
	Ignores []ConfigIgnore `yaml:"ignores"`

	// RequiredActions is a "required-actions" list in the configuration file. Each item is an action (or
	// reusable workflow) which must be used at least once in every checked workflow. The check is disabled
	// when the list is empty.
	RequiredActions []RequiredActionRule `yaml:"required-actions"`
	// RequiredChecks is the "required-checks" list: the check names that branch protection or a ruleset requires,
	// and the events they are required for. The unreachable-required-check rule reports a declared check that no job
	// reports, and a trigger filter of a workflow that keeps GitHub from starting the job which reports it. The lists
	// of the files listed in "extends" are replaced, not merged.
	RequiredChecks []RequiredCheck `yaml:"required-checks"`
	// AssumeDefaultPermissions controls how the workflow-call permission check treats a caller that
	// has no `permissions:` block at the workflow level and none on the calling job. Unset, nothing
	// is assumed (the default token is a setting of the repository): only a scope that no default
	// token has (`id-token`) is reported. "restricted" assumes GitHub's restricted default token
	// (contents/packages: read, everything else: none). "permissive" assumes write on every scope
	// except `id-token`, which always requires an explicit opt-in regardless of the repo-level
	// Workflow permissions setting. Only affects callers
	// with no permissions block anywhere; once any permissions block is declared, the check always
	// runs against it.
	AssumeDefaultPermissions *string `yaml:"assume-default-permissions"`

	// Platform is the system which runs the workflows: "github" (the default) or "forgejo" (or "gitea", the same
	// here). On Forgejo and Gitea a step can run an action from any host with `uses: https://host/owner/repo@ref`
	// (actionlint#698), which is a malformed `uses:` on GitHub and stays an error there. Only the syntax and the
	// pinning of such an action are checked: the metadata, the inputs and the online checks are those of GitHub.
	Platform *string `yaml:"platform"`

	// GeneratedFiles tells what to do with a file whose first comment says that a tool wrote it ("DO NOT EDIT",
	// "automatically generated by gh-aw"): "skip-policy" (the default) does not report the rules of the policy and style
	// groups there, since the author cannot act on them without changing the generator, "report" treats the file like any
	// other, and "skip" reports nothing.
	GeneratedFiles *string `yaml:"generated-files"`

	// Fix configures "jactionlint --fix".
	Fix FixConfig `yaml:"fix"`

	// Update configures "jactionlint update", which checks the external actions for newer releases and pins them.
	Update UpdateConfig `yaml:"update"`

	// Shellcheck tunes the shellcheck integration: a shellcheckrc, more arguments and optional checks.
	Shellcheck ShellcheckConfig `yaml:"shellcheck"`

	// Path is the path of the file which the config was read from. It is empty when the config was
	// parsed from bytes.
	Path string `yaml:"-"`
	// Deprecations are messages about deprecated keys the config file uses, for example the old
	// "require-shell: true" which is replaced by the "rules" mapping. The config still works.
	// "jactionlint --migrate-config" rewrites the file.
	Deprecations []string `yaml:"-"`
	// Notices are messages about the config file which are not warnings, for example that a file written
	// for actionlint was read and which profile applies to it.
	Notices []string `yaml:"-"`
	// contains filtered or unexported fields
}

Config is configuration of jactionlint. This struct instance is parsed from "jactionlint.yaml" file usually put in ".github" directory.

func ParseConfig Âķ

func ParseConfig(b []byte) (*Config, error)

ParseConfig parses the given bytes as an jactionlint config file. When deserializing the YAML file or the config validation fails, this function returns an error. Unknown keys are errors too, with a suggestion when the key looks like a typo of a known one. The "extends" key needs the path of the file to find the files to inherit from so it is an error here; use ReadConfigFile.

func ReadConfigFile Âķ

func ReadConfigFile(path string) (*Config, error)

ReadConfigFile reads jactionlint config file (jactionlint.yaml) from the given file path. The files listed in "extends" are read too and merged into the returned config.

func (*Config) PathConfigs Âķ

func (c *Config) PathConfigs(path string) []PathConfig

PathConfigs returns a list of all PathConfig values matching to the given file path. The path must be relative to the root of the project.

func (*Config) RuleEnabled Âķ

func (c *Config) RuleEnabled(id string) bool

RuleEnabled reports whether the rule runs with this configuration. It can be called on a nil Config.

func (*Config) RuleLevel Âķ

func (c *Config) RuleLevel(id string) Severity

RuleLevel returns the severity at which the rule with the given ID runs with this configuration: the level written in "rules", or else the default level of the rule when the profile includes the rule, or else SeverityOff. It can be called on a nil Config, which behaves like an empty one. Unknown IDs (IDs of custom rules) are always enabled as errors.

func (*Config) RuleOption Âķ

func (c *Config) RuleOption(id, name string) (any, bool)

RuleOption returns the value of the option of the rule: the one written in "rules", or else the default of the option. The boolean is false when the option has neither. The value is an int or a float64 according to RuleOption.Kind. It can be called on a nil Config.

func (*Config) RuleOptionStrings Âķ

func (c *Config) RuleOptionStrings(id, name string) ([]string, bool)

RuleOptionStrings returns the value of a list option of the rule: the one written in "rules", or else the default of the option. The boolean is false when the option has neither. It can be called on a nil Config.

func (*Config) RuleRuns Âķ

func (c *Config) RuleRuns(id string, online bool) bool

RuleRuns reports whether the rule runs in a run where the online checks are on or off: an online rule needs online mode as well as a level which is not off. Use it where a consumer asks whether a rule could have reported something (unused-ignore); RuleEnabled only looks at the level.

type ConfigIgnore Âķ

type ConfigIgnore struct {
	// Rules are the rule IDs whose findings are ignored. At least one is required.
	Rules []string
	// File is a glob matched against the path of the file ("**" crosses directories). The path is
	// matched relative to the project root and as the linter prints it. Empty matches every file.
	File string
	// Uses matches the `uses:` value of the step (or the called workflow of a job). It is a pattern
	// as of forbidden-uses ("actions/checkout", "actions/*", "owner/repo/sub@v1", names are
	// case-insensitive and any ref matches when the pattern has none), a glob with `*` for values
	// which are not repository references ("docker://alpine*", "./.github/actions/*"), or a regular
	// expression between slashes ("/^actions\/(checkout|cache)@/") matched against the whole value.
	// Empty matches every step.
	Uses string
	// Job is the ID of the job (its key in "jobs"). It is matched without regard to case, like the IDs in
	// "needs" are.
	Job string
	// Step is the "id" or the "name" of the step.
	Step string
	// Reason says why the finding is accepted. It is for the readers of the config file; it is shown in
	// the messages about the entry.
	Reason string
	// Expires is the last day (YYYY-MM-DD, UTC) the entry suppresses findings. After it the findings
	// come back and the entry is reported by the expired-ignore rule. Empty never expires.
	Expires string
	// AllowUnused accepts that the entry suppresses nothing at times, for a finding which comes and
	// goes: the unused-ignore rule does not report it. Expiry is still checked.
	AllowUnused bool

	// Path is the config file the entry was read from. It is set by ReadConfigFile.
	Path string
	// Line and Column are the position of the entry in the config file. They are 1-based.
	Line, Column int
	// contains filtered or unexported fields
}

ConfigIgnore is one entry of the "ignores" list of the configuration file. Unlike an inline ignore comment, it does not live next to the code, so a tool that rewrites the line (Renovate or Dependabot bumping `uses: actions/checkout@<sha> # v4`) cannot drop it. It matches a finding by the rule and by attributes of the place in the workflow where the finding is: the file, the job, the step and the `uses:` value of the step. All attributes which are set must match.

ignores:
  - rule: unpinned-uses
    uses: actions/checkout        # any ref
    file: .github/workflows/*.yml
    reason: the org pins this through a ruleset
    expires: 2027-01-31

func (ConfigIgnore) Snippet Âķ

func (ig ConfigIgnore) Snippet() string

Snippet returns the entry as YAML text for the "ignores" list of a config file, one item with the attributes which are set. Tools which migrate other kinds of ignore comments (for instance zizmor's) use it to write entries.

func (*ConfigIgnore) UnmarshalYAML Âķ

func (ig *ConfigIgnore) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type Container Âķ

type Container struct {
	// Image is specification of Docker image. When the whole container is written as one expression (Expression),
	// it is that expression.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainerimage
	Image *String
	// Expression is the expression of a container written as a single value that is an image name or a whole
	// configuration, such as `container: ${{ matrix.container }}`. Otherwise nil.
	Expression *String
	// Credentials is credentials configuration of the Docker container.
	Credentials *Credentials
	// Env is environment variables setup in the container.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainerenv
	Env *Env
	// Ports is list of port number mappings of the container.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainerports
	Ports []*String
	// PortsExpression is the expression of a section written as one expression, such as `ports: ${{ fromJSON(vars.P) }}`.
	// Ports is empty then.
	PortsExpression *String
	// Volumes are list of volumes to be mounted to the container.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainervolumes
	Volumes []*String
	// VolumesExpression is the expression of a section written as one expression. Volumes is empty then.
	VolumesExpression *String
	// Options is options string to run the container.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontaineroptions
	Options *String
	// Command overrides Docker image's default command for service containers.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idservicesservice_idcommand
	Command *String
	// Entrypoint overrides Docker image's default entrypoint for service containers.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idservicesservice_identrypoint
	Entrypoint *String
	// Pos is a position in source.
	Pos *Pos
}

Container is configuration of how to run the container. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainer

type Credentials Âķ

type Credentials struct {
	// Username is username for authentication.
	Username *String
	// Password is password for authentication.
	Password *String
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Credentials is credentials configuration. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontainercredentials

type Defaults Âķ

type Defaults struct {
	// Run is configuration of how to run shell.
	Run *DefaultsRun
	// Pos is a position in source.
	Pos *Pos
}

Defaults is set of default configurations to run shell. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#defaults

type DefaultsRun Âķ

type DefaultsRun struct {
	// Shell is shell name to be run. When the section is written as one expression (Expression), it is that
	// expression, so that a rule treats the shell as chosen by an expression and unknown.
	Shell *String
	// WorkingDirectory is a default working directory path. It is the Expression too when that is set.
	WorkingDirectory *String
	// Expression is the expression of a section written as one expression, such as `run: ${{ fromJSON(vars.RUN) }}`.
	// It is allowed in the defaults of a job only. Otherwise nil.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

DefaultsRun is configuration that shell is how to be run. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#defaultsrun

type Dependabot Âķ

type Dependabot struct {
	// Version is the "version" key. Dependabot supports only version 2.
	Version *Int
	// Updates is the "updates" key. Each item configures the updates of one package ecosystem.
	Updates []*DependabotUpdate
	// Registries is the "registries" key in the order of the source.
	Registries []*DependabotRegistry
	// MultiEcosystemGroups is the "multi-ecosystem-groups" key in the order of the source.
	MultiEcosystemGroups []*DependabotMultiEcosystemGroup
	// EnableBetaEcosystems is the "enable-beta-ecosystems" key.
	EnableBetaEcosystems *Bool
	// Pos is the position of the top-level mapping.
	Pos *Pos
}

Dependabot is the root of the syntax tree of a Dependabot configuration file (.github/dependabot.yml). Every node has the position where it starts in the source.

https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference

type DependabotAllow Âķ

type DependabotAllow struct {
	// Pos is the position of the item.
	Pos *Pos
	// DependencyName is the "dependency-name" key.
	DependencyName *String
	// DependencyType is the "dependency-type" key.
	DependencyType *String
}

DependabotAllow is an item of "allow" of an update.

type DependabotBranchName Âķ

type DependabotBranchName struct {
	// Pos is the position of the key.
	Pos *Pos
	// Separator is the "separator" key.
	Separator *String
}

DependabotBranchName is the "pull-request-branch-name" key of an update.

type DependabotCommitMessage Âķ

type DependabotCommitMessage struct {
	// Pos is the position of the "commit-message" key.
	Pos *Pos
	// Prefix is the "prefix" key.
	Prefix *String
	// PrefixDevelopment is the "prefix-development" key.
	PrefixDevelopment *String
	// Include is the "include" key: "scope".
	Include *String
}

DependabotCommitMessage is the "commit-message" key of an update.

type DependabotCooldown Âķ

type DependabotCooldown struct {
	// Pos is the position of the "cooldown" key.
	Pos *Pos
	// DefaultDays is the "default-days" key. It is nil when the key is missing or its value is not a valid integer.
	DefaultDays *Int
	// HasDefaultDays is whether the "default-days" key is written, valid or not.
	HasDefaultDays bool
	// SemverMajorDays is the "semver-major-days" key.
	SemverMajorDays *Int
	// SemverMinorDays is the "semver-minor-days" key.
	SemverMinorDays *Int
	// SemverPatchDays is the "semver-patch-days" key.
	SemverPatchDays *Int
	// Include is the "include" key.
	Include []*String
	// Exclude is the "exclude" key.
	Exclude []*String
}

DependabotCooldown is the "cooldown" key of an update. It delays updating to a version until it is old enough.

type DependabotGroup Âķ

type DependabotGroup struct {
	// Pos is the position of the name of the group.
	Pos *Pos
	// Name is the name of the group.
	Name *String
	// AppliesTo is the "applies-to" key: "version-updates" or "security-updates".
	AppliesTo *String
	// DependencyType is the "dependency-type" key: "development" or "production".
	DependencyType *String
	// GroupBy is the "group-by" key.
	GroupBy *String
	// Patterns is the "patterns" key.
	Patterns []*String
	// ExcludePatterns is the "exclude-patterns" key.
	ExcludePatterns []*String
	// UpdateTypes is the "update-types" key.
	UpdateTypes []*String
}

DependabotGroup is an item of "groups" of an update. The key of the mapping is the Name.

type DependabotIgnore Âķ

type DependabotIgnore struct {
	// Pos is the position of the item.
	Pos *Pos
	// DependencyName is the "dependency-name" key.
	DependencyName *String
	// Versions is the "versions" key.
	Versions []*String
	// UpdateTypes is the "update-types" key.
	UpdateTypes []*String
}

DependabotIgnore is an item of "ignore" of an update.

type DependabotMultiEcosystemGroup Âķ

type DependabotMultiEcosystemGroup struct {
	// Pos is the position of the name of the group.
	Pos *Pos
	// Name is the name which updates refer to with "multi-ecosystem-group".
	Name *String
	// Schedule is the "schedule" key.
	Schedule *DependabotSchedule
	// Assignees is the "assignees" key.
	Assignees []*String
	// Reviewers is the "reviewers" key.
	Reviewers []*String
	// Labels is the "labels" key.
	Labels []*String
	// Milestone is the "milestone" key.
	Milestone *Int
	// TargetBranch is the "target-branch" key.
	TargetBranch *String
	// CommitMessage is the "commit-message" key.
	CommitMessage *DependabotCommitMessage
	// PullRequestBranchName is the "pull-request-branch-name" key.
	PullRequestBranchName *DependabotBranchName
	// OpenPullRequestsLimit is the "open-pull-requests-limit" key.
	OpenPullRequestsLimit *Int
}

DependabotMultiEcosystemGroup is an item of "multi-ecosystem-groups" of the Dependabot configuration. It makes updates of several package ecosystems share one pull request. The key of the mapping is the Name.

type DependabotPass Âķ

type DependabotPass interface {
	// VisitDependabotPre is callback when visiting the root node before visiting its children. It
	// returns internal error when it cannot continue the process.
	VisitDependabotPre(node *Dependabot) error
	// VisitDependabotUpdate is callback when visiting an item of "updates". It returns internal error
	// when it cannot continue the process.
	VisitDependabotUpdate(node *DependabotUpdate) error
	// VisitDependabotPost is callback when visiting the root node after visiting its children. It
	// returns internal error when it cannot continue the process.
	VisitDependabotPost(node *Dependabot) error
}

DependabotPass is an interface to traverse the syntax tree of a Dependabot configuration. It is the counterpart of Pass for .github/dependabot.yml.

type DependabotRegistry Âķ

type DependabotRegistry struct {
	// Pos is the position of the name of the registry.
	Pos *Pos
	// Name is the name which updates refer to.
	Name *String
	// Type is the "type" key such as "npm-registry".
	Type *String
	// URL is the "url" key.
	URL *String
	// Username is the "username" key.
	Username *String
	// Password is the "password" key.
	Password *String
	// Key is the "key" key.
	Key *String
	// Token is the "token" key.
	Token *String
	// ReplacesBase is the "replaces-base" key.
	ReplacesBase *Bool
	// Settings are the other keys. They depend on the type of the registry and new ones are added
	// over time (e.g. for OIDC), so they are not validated.
	Settings []*DependabotSetting
}

DependabotRegistry is an item of "registries" of the Dependabot configuration. The key of the mapping is the Name.

type DependabotRule Âķ

type DependabotRule interface {
	DependabotPass
	Errs() []*Error
	Name() string
	Description() string
	EnableDebug(out io.Writer)
	SetConfig(cfg *Config)
	Config() *Config
}

DependabotRule is an interface which all rules for Dependabot configurations must meet. It is the counterpart of Rule. Embed DependabotRuleBase to implement the methods other than the visiting callbacks you need.

type DependabotRuleBase Âķ

type DependabotRuleBase struct {
	RuleBase
}

DependabotRuleBase is a struct to be a base of rule structs for Dependabot configurations. It has the same reporting methods as RuleBase (Error, ReportID, ...) and visiting callbacks which do nothing.

func NewDependabotRuleBase Âķ

func NewDependabotRuleBase(name string, desc string) DependabotRuleBase

NewDependabotRuleBase creates a new DependabotRuleBase instance. It should be embedded to your own rule instance.

func (*DependabotRuleBase) VisitDependabotPost Âķ

func (r *DependabotRuleBase) VisitDependabotPost(node *Dependabot) error

VisitDependabotPost is callback when visiting the root node after visiting its children.

func (*DependabotRuleBase) VisitDependabotPre Âķ

func (r *DependabotRuleBase) VisitDependabotPre(node *Dependabot) error

VisitDependabotPre is callback when visiting the root node before visiting its children.

func (*DependabotRuleBase) VisitDependabotUpdate Âķ

func (r *DependabotRuleBase) VisitDependabotUpdate(node *DependabotUpdate) error

VisitDependabotUpdate is callback when visiting an item of "updates".

type DependabotSchedule Âķ

type DependabotSchedule struct {
	// Pos is the position of the "schedule" key.
	Pos *Pos
	// Interval is the "interval" key such as "daily" or "weekly".
	Interval *String
	// Day is the "day" key.
	Day *String
	// Time is the "time" key in the format HH:MM.
	Time *String
	// Timezone is the "timezone" key, an IANA timezone name.
	Timezone *String
	// Cronjob is the "cronjob" key which is used with the interval "cron".
	Cronjob *String
}

DependabotSchedule is the "schedule" key of an update or a multi-ecosystem group.

type DependabotSetting Âķ

type DependabotSetting struct {
	// Key is the key of the setting.
	Key *String
	// Value is the value of the setting.
	Value *String
}

DependabotSetting is a key-value pair whose key jactionlint does not know.

type DependabotUpdate Âķ

type DependabotUpdate struct {
	// Pos is the position of the item.
	Pos *Pos
	// PackageEcosystem is the "package-ecosystem" key such as "npm" or "github-actions".
	PackageEcosystem *String
	// Directory is the "directory" key.
	Directory *String
	// Directories is the "directories" key.
	Directories []*String
	// Schedule is the "schedule" key.
	Schedule *DependabotSchedule
	// Allow is the "allow" key.
	Allow []*DependabotAllow
	// Assignees is the "assignees" key.
	Assignees []*String
	// CommitMessage is the "commit-message" key.
	CommitMessage *DependabotCommitMessage
	// Cooldown is the "cooldown" key.
	Cooldown *DependabotCooldown
	// ExcludePaths is the "exclude-paths" key.
	ExcludePaths []*String
	// Groups is the "groups" key in the order of the source.
	Groups []*DependabotGroup
	// Ignore is the "ignore" key.
	Ignore []*DependabotIgnore
	// InsecureExternalCodeExecution is the "insecure-external-code-execution" key: "allow" or "deny".
	InsecureExternalCodeExecution *String
	// Labels is the "labels" key.
	Labels []*String
	// Milestone is the "milestone" key.
	Milestone *Int
	// MultiEcosystemGroup is the "multi-ecosystem-group" key. It is the name of an item of
	// Dependabot.MultiEcosystemGroups.
	MultiEcosystemGroup *String
	// OpenPullRequestsLimit is the "open-pull-requests-limit" key.
	OpenPullRequestsLimit *Int
	// Patterns is the "patterns" key which is used with MultiEcosystemGroup.
	Patterns []*String
	// PullRequestBranchName is the "pull-request-branch-name" key.
	PullRequestBranchName *DependabotBranchName
	// RebaseStrategy is the "rebase-strategy" key: "auto" or "disabled".
	RebaseStrategy *String
	// Registries is the "registries" key. Each item is a name of Dependabot.Registries or "*".
	Registries []*String
	// Reviewers is the "reviewers" key.
	Reviewers []*String
	// TargetBranch is the "target-branch" key.
	TargetBranch *String
	// Vendor is the "vendor" key.
	Vendor *Bool
	// VersioningStrategy is the "versioning-strategy" key.
	VersioningStrategy *String
}

DependabotUpdate is an item of "updates" of the Dependabot configuration.

type DependabotVisitor Âķ

type DependabotVisitor struct {
	// contains filtered or unexported fields
}

DependabotVisitor visits the syntax tree of a Dependabot configuration from the root in depth-first order.

func NewDependabotVisitor Âķ

func NewDependabotVisitor() *DependabotVisitor

NewDependabotVisitor creates DependabotVisitor instance.

func (*DependabotVisitor) AddPass Âķ

func (v *DependabotVisitor) AddPass(p DependabotPass)

AddPass adds new pass which is called on traversing a syntax tree.

func (*DependabotVisitor) EnableDebug Âķ

func (v *DependabotVisitor) EnableDebug(w io.Writer)

EnableDebug enables debug output when non-nil io.Writer value is given. All debug outputs from visitor will be written to the writer.

func (*DependabotVisitor) Visit Âķ

func (v *DependabotVisitor) Visit(n *Dependabot) error

Visit visits given syntax tree in depth-first order.

type DispatchInput Âķ

type DispatchInput struct {
	// Name is a name of input value specified on dispatching workflow manually.
	Name *String
	// Description is a description of input value specified on dispatching workflow manually.
	Description *String
	// Required is a flag to show if this input is mandatory or not on dispatching workflow manually.
	Required *Bool
	// Default is a default value of input value on dispatching workflow manually.
	Default *String
	// Type is a type of the input
	// https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#workflow_dispatch
	Type WorkflowDispatchEventInputType
	// Options is list of options of choice type
	Options []*String
}

DispatchInput is input specified on dispatching workflow manually. https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#workflow_dispatch

type EffectivePermissions Âķ added in v2.2.0

type EffectivePermissions struct {
	// Source is "job" (the job declares them), "workflow" (it inherits those of the workflow) or "repository-setting":
	// neither declares them, so the default token of the repository applies, which the file does not say. Scopes is empty
	// then, and that means unknown, not none.
	Source string            `json:"source"`
	Scopes map[string]string `json:"scopes,omitempty"`
}

EffectivePermissions are the permissions the token of a job has.

type Env Âķ

type Env struct {
	// Vars is mapping from env var name to env var value.
	Vars map[string]*EnvVar
	// Expression is an expression string which contains ${{ ... }}. When this value is not empty,
	// Vars should be nil.
	Expression *String
	// Inserts are the values of the `${{ insert }}` keys, such as `${{ insert }}: ${{ matrix.env }}`. Each is an
	// expression which evaluates to a mapping of more variables.
	Inserts []*String
}

Env represents set of environment variables.

func (*Env) Dynamic Âķ added in v2.2.0

func (e *Env) Dynamic() bool

Dynamic reports whether the variables are not all known from the source because the whole section is an expression or it has a `${{ insert }}` key. A rule which reports that a variable is not set must not report then.

type EnvVar Âķ

type EnvVar struct {
	// Name is name of the environment variable.
	Name *String
	// Value is string value of the environment variable.
	Value *String
}

EnvVar represents key-value of environment variable setup.

type Environment Âķ

type Environment struct {
	// Name is a name of environment which the workflow uses.
	Name *String
	// Expression is the expression of an environment written as one expression, such as `environment: ${{ matrix.env }}`.
	// It can evaluate to a name or to a mapping. Name is the same expression. Otherwise nil.
	Expression *String
	// URL is the URL mapped to 'environment_url' in the deployments API. Empty value means no value was specified.
	URL *String
	// Deployment is whether GitHub should create a deployment for this job. false skips auto-deployment while still applying environment protection rules and secrets.
	Deployment *Bool
	// Pos is a position in source.
	Pos *Pos
}

Environment is a configuration of environment. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idenvironment

type Error Âķ

type Error struct {
	// Message is an error message.
	Message string
	// Filepath is a file path where the error occurred.
	Filepath string
	// Line is a line number where the error occurred. This value is 1-based.
	Line int
	// Column is a column number where the error occurred. This value is 1-based and counts Unicode
	// code points.
	Column int
	// EndLine is the line number of the end of the problematic region. This value is 1-based. It is
	// the same as Line unless the region spans several lines.
	EndLine int
	// EndColumn is the column number just after the end of the problematic region on EndLine. It is
	// 1-based and counts Unicode code points, so a region of one character at column 5 has EndColumn
	// 6. When a rule did not report where the region ends, the linter fills it with the end of the
	// token which starts at Line and Column.
	EndColumn int
	// Kind is a string to represent kind of the error. Usually rule name which found the error. It is
	// the legacy way to group errors. Use ID to tell which diagnostic was reported.
	Kind string
	// ID is the stable identifier of the diagnostic such as "unpinned-uses". See Rules for all IDs of
	// jactionlint. Errors reported by custom rules through RuleBase.Error have the Kind as their ID.
	ID string
	// Severity is how serious the error is. It is determined by the configuration: the level of the
	// rule or the default level of the rule.
	Severity Severity
	// DocURL is a URL of the documentation of the diagnostic. It is empty for custom rules.
	DocURL string
	// Fix is an automatic correction for the error. It is nil when the error cannot be fixed
	// mechanically.
	Fix *Fix
	// NoFix says why the error has no applicable Fix although the rule can fix such findings. It is nil
	// when Fix is set and for the findings which are advice only (the rule never fixes them), so that an
	// unavailable fix can be told from one that does not exist.
	NoFix *NoFix
	// Baselined is true when the baseline file accepts the finding (see Config.Baseline). The linter
	// does not return such errors from its methods or print them, except in the SARIF log (as
	// suppressed results) and the summary format; it is set only on the way there.
	Baselined bool
	// Events are the names of the events which trigger the workflow the finding is in, sorted. It is set only
	// with LinterOptions.FindingContext, and for a workflow.
	Events []string
	// Permissions are the permissions of the token of the job the finding is in (the permissions of the job, or
	// else the ones of the workflow): scope to read, write or none, "*" for read-all and write-all, and "*" at
	// none for an empty mapping. It is empty when the file does not configure them (the default token of the
	// repository applies) and unless LinterOptions.FindingContext is set.
	Permissions map[string]string
	// RetiredID is the rule ID that the finding had before its audit was merged into ID, when it was one of
	// the findings which the pedantic option adds (see RenamedRule). Ignores written with the old ID match it.
	RetiredID string
}

Error represents an error detected by jactionlint rules

func (*Error) Error Âķ

func (e *Error) Error() string

Error returns summary of the error as string. It keeps the form of actionlint, so the name in the brackets is the Kind, which several rules share and which is not always a rule ID ("timeout-check"). Use ID, or PrettyPrint which shows it, for the name that the configuration and --ignore accept.

func (*Error) GetTemplateFields Âķ

func (e *Error) GetTemplateFields(source []byte) *ErrorTemplateFields

GetTemplateFields fields for formatting this error with Go template.

func (*Error) PrettyPrint Âķ

func (e *Error) PrettyPrint(w io.Writer, source []byte)

PrettyPrint prints the error with user-friendly way. It prints file name, source position, error message with colorful output and source snippet with indicator. When nil is set to source, no source snippet is not printed. The name at the end of the first line is the rule ID, like the command prints it. To disable colorful output, set true to fatih/color.NoColor.

func (*Error) String Âķ

func (e *Error) String() string

type ErrorFormatter Âķ

type ErrorFormatter struct {
	// contains filtered or unexported fields
}

ErrorFormatter is a formatter to format a slice of ErrorTemplateFields. It is used for formatting error messages with --format option.

Example Âķ
package main

import (
	"os"

	"github.com/jdx/jactionlint/v2"
)

func main() {
	// Errors returned from Linter methods
	errs := []*jactionlint.Error{
		{
			Message:  "error message 1",
			Filepath: "foo.yaml",
			Line:     1,
			Column:   4,
			Kind:     "rule1",
		},
		{
			Message:  "error message 2",
			Filepath: "foo.yaml",
			Line:     3,
			Column:   1,
			Kind:     "rule2",
		},
	}

	// Create ErrorFormatter instance with template
	f, err := jactionlint.NewErrorFormatter(`{{range $ := .}}{{$.Filepath}}:{{$.Line}}:{{$.Column}}: {{$.Message}}\n{{end}}`)
	if err != nil {
		// Some error happened while creating the formatter (e.g. syntax error)
		panic(err)
	}

	src := `on: push

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: echo
`

	// Prints all errors to stdout following the template
	if err := f.PrintErrors(os.Stdout, errs, []byte(src)); err != nil {
		panic(err)
	}

}
Output:
foo.yaml:1:4: error message 1
foo.yaml:3:1: error message 2

func NewErrorFormatter Âķ

func NewErrorFormatter(format string) (*ErrorFormatter, error)

NewErrorFormatter creates new ErrorFormatter instance. Given format must contain at least one {{ }} placeholder. Escaped characters like \n in the format string are unescaped.

func (*ErrorFormatter) Print Âķ

func (f *ErrorFormatter) Print(out io.Writer, t []*ErrorTemplateFields) error

Print formats the slice of template fields and prints it with given writer.

func (*ErrorFormatter) PrintErrors Âķ

func (f *ErrorFormatter) PrintErrors(out io.Writer, errs []*Error, src []byte) error

PrintErrors prints the errors after formatting them with template.

func (*ErrorFormatter) RegisterRule Âķ

func (f *ErrorFormatter) RegisterRule(r Rule)

RegisterRule registers the rule. Registered rules are used to get description and index of error kinds when you use `kindDescription` or `kindIndex` functions in an error format template. This method can be called multiple times safely in parallel.

type ErrorTemplateFields Âķ

type ErrorTemplateFields struct {
	// Message is error message body.
	Message string `json:"message"`
	// Filepath is the file path as the linter reports it, relative to the working directory when
	// possible. For input read from stdin it is "<stdin>", or the value of LinterOptions.StdinFileName.
	// The linter always sets it, so the JSON has it; omitempty only matters for an Error built by hand.
	Filepath string `json:"filepath,omitempty"`
	// Line is a line number of error position.
	Line int `json:"line"`
	// Column is a column number of error position.
	Column int `json:"column"`
	// Kind is the legacy name of the checker which reported the error. Several rules share one kind, and
	// it is not always a rule ID. Use ID.
	Kind string `json:"kind"`
	// Snippet is a code snippet and indicator to indicate where the error occurred.
	// When encoding into JSON, this field may be omitted when the snippet is empty.
	Snippet string `json:"snippet,omitempty"`
	// EndColumn is a column number where the error indicator (^~~~~~~) ends. When no indicator
	// can be shown, EndColumn is equal to Column. Note that it is the column of the last character
	// of the indicator, counted in Unicode code points like Column (not in display width, so five wide
	// CJK characters from column 11 end at column 15). It differs from Error.EndColumn, which is the
	// exclusive end of the region.
	EndColumn int `json:"end_column"`
	// ID is the stable ID of the rule which found the error such as "unpinned-uses".
	ID string `json:"id"`
	// Severity is "error", "warn" or "info".
	Severity Severity `json:"severity"`
	// DocURL is the URL of the documentation of the rule. When encoding into JSON, this field may be
	// omitted when the error is not from a built-in rule.
	DocURL string `json:"doc_url,omitempty"`
	// EndLine is the line number where the region of the error ends. It is the same as Line unless the
	// region spans several lines.
	EndLine int `json:"end_line"`
	// Fix is the automatic fix for the error. When encoding into JSON, this field is omitted when the
	// error cannot be fixed automatically.
	Fix *Fix `json:"fix,omitempty"`
	// NoFix says why a finding which the rule can fix has none. When encoding into JSON, this field is
	// omitted when the error has a fix or is advice only.
	NoFix *NoFix `json:"no_fix,omitempty"`
	// Events are the events which trigger the workflow. They are in the output only with --finding-context.
	Events []string `json:"events,omitempty"`
	// Permissions are the permissions of the token of the job, scope to level. They are in the output only
	// with --finding-context, and when the file configures them.
	Permissions map[string]string `json:"permissions,omitempty"`
}

ErrorTemplateFields holds all fields to format one error message.

type Event Âķ

type Event interface {
	// EventName returns name of the event to trigger this workflow.
	EventName() string
}

Event interface represents workflow events in 'on' section

type EventFacts Âķ added in v2.2.0

type EventFacts struct {
	Name     string    `json:"name"`
	Location *Location `json:"location,omitempty"`
	// Types are the activity types of the event. Empty means the default types of the event.
	Types []string `json:"types,omitempty"`
	// Filters are the branch, tag and path filters by their key ("branches", "paths-ignore", ...).
	Filters map[string][]string `json:"filters,omitempty"`
	// Schedules are the cron expressions of the event "schedule".
	Schedules []string `json:"schedules,omitempty"`
	// Inputs are the names of the inputs of workflow_dispatch and workflow_call.
	Inputs []string `json:"inputs,omitempty"`
}

EventFacts is an event of "on:".

type Exec Âķ

type Exec interface {
	// Kind returns kind of the step execution.
	Kind() ExecKind
}

Exec is an interface how the step is executed. Step in workflow runs either an action or a script

type ExecAction Âķ

type ExecAction struct {
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepsuses
	Uses *String
	// Inputs represents inputs to the action to execute in 'with' section. Keys are in lower case since they are case-insensitive.
	// It is empty when the whole section is an expression (see InputsExpression).
	Inputs map[string]*Input
	// InputsExpression is the expression of a 'with' section written as one expression, such as
	// `with: ${{ fromJSON(vars.INPUTS) }}`. Nil when the section is a mapping. Inputs is empty then, and the inputs of
	// the step are unknown: a rule which reports an input that is missing or not set must skip the step (see InputsUnknown).
	InputsExpression *String
	// InputInserts are the values of the `${{ insert }}` keys of the 'with' section, such as
	// `${{ insert }}: ${{ matrix.inputs }}`. Each is an expression which evaluates to a mapping of more inputs.
	InputInserts []*String
	// Entrypoint represents optional 'entrypoint' field in 'with' section. Nil field means nothing specified
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepswithentrypoint
	Entrypoint *String
	// Args represents optional 'args' field in 'with' section. Nil field means nothing specified
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepswithargs
	Args *String
}

ExecAction is configuration how to run action at the step. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepsuses

func (*ExecAction) InputsUnknown Âķ added in v2.2.0

func (e *ExecAction) InputsUnknown() bool

InputsUnknown reports whether the inputs of the step are not all known from the source because the 'with' section is an expression, or has a `${{ insert }}` key. The inputs in Inputs are given, but others may be given too. A rule which reports that an input is missing or not set must not report the step.

func (*ExecAction) Kind Âķ

func (e *ExecAction) Kind() ExecKind

Kind returns kind of the step execution.

type ExecCancel Âķ

type ExecCancel struct {
	// Name is the ID of the background step to cancel, given by the 'cancel' field. The 'cancel' step
	// targets a single background step by its ID.
	Name *String
}

ExecCancel is configuration of a step that cancels a running background step. It corresponds to the 'cancel' step. https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/

func (*ExecCancel) Kind Âķ

func (e *ExecCancel) Kind() ExecKind

Kind returns kind of the step execution.

type ExecKind Âķ

type ExecKind uint8

ExecKind is kind of how the step is executed. A step runs some action or runs some shell script.

const (
	// ExecKindAction is kind for step to run action
	ExecKindAction ExecKind = iota
	// ExecKindRun is kind for step to run shell script
	ExecKindRun
	// ExecKindWait is kind for step to wait for background steps ('wait' or 'wait-all')
	ExecKindWait
	// ExecKindCancel is kind for step to cancel background steps ('cancel')
	ExecKindCancel
	// ExecKindParallel is kind for step to run a group of steps in parallel ('parallel')
	ExecKindParallel
)

type ExecParallel Âķ

type ExecParallel struct {
	// Steps is the group of steps to run in parallel, given by the 'parallel' field.
	Steps []*Step
}

ExecParallel is configuration of a step that runs a group of steps in parallel. It corresponds to the 'parallel' step. https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/

func (*ExecParallel) Kind Âķ

func (e *ExecParallel) Kind() ExecKind

Kind returns kind of the step execution.

type ExecRun Âķ

type ExecRun struct {
	// Run is script to run.
	Run *String
	// Shell represents optional 'shell' field. Nil means nothing specified.
	Shell *String
	// WorkingDirectory represents optional 'working-directory' field. Nil means nothing specified.
	WorkingDirectory *String
	// RunPos is position of 'run' section
	RunPos *Pos
}

ExecRun is configuration how to run shell script at the step. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepsrun

func (*ExecRun) Kind Âķ

func (e *ExecRun) Kind() ExecKind

Kind returns kind of the step execution.

type ExecWait Âķ

type ExecWait struct {
	// Names is the list of background step IDs to wait for, given by the 'wait' field. It is nil when
	// 'wait-all' is used instead.
	Names []*String
	// All is true when the step waits for all preceding background steps via the 'wait-all' field.
	All bool
	// AllPos is the position of the 'wait-all' field. It is nil when 'wait' is used instead.
	AllPos *Pos
}

ExecWait is configuration of a step that waits for background steps to complete. It corresponds to the 'wait' and 'wait-all' steps. https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/

func (*ExecWait) Kind Âķ

func (e *ExecWait) Kind() ExecKind

Kind returns kind of the step execution.

type ExprError Âķ

type ExprError struct {
	// Message is an error message
	Message string
	// Offset is byte offset position which caused the error
	Offset int
	// Offset is line number position which caused the error. Note that this value is 1-based.
	Line int
	// Column is column number position which caused the error. Note that this value is 1-based.
	Column int
	// ID is the stable ID of the diagnostic such as "expression-syntax" or "undefined-property".
	ID string
}

ExprError is an error type caused by lexing/parsing expression syntax. For more details, see https://docs.github.com/en/actions/learn-github-actions/expressions

func (*ExprError) Error Âķ

func (e *ExprError) Error() string

func (*ExprError) String Âķ

func (e *ExprError) String() string

type ExprLexer Âķ

type ExprLexer struct {
	// contains filtered or unexported fields
}

ExprLexer is a struct to lex expression syntax. To know the syntax, see https://docs.github.com/en/actions/learn-github-actions/expressions

func NewExprLexer Âķ

func NewExprLexer(src string) *ExprLexer

NewExprLexer makes new ExprLexer instance.

func (*ExprLexer) Err Âķ

func (lex *ExprLexer) Err() *ExprError

Err returns an error while lexing. When multiple errors occur, the first one is returned.

func (*ExprLexer) Next Âķ

func (lex *ExprLexer) Next() *Token

Next lexes next token to lex input incrementally. Lexer must be initialized with Init() method before the first call of this method. This method is stateful. Lexer advances offset by lexing token. To get the offset, use Offset() method.

func (*ExprLexer) Offset Âķ

func (lex *ExprLexer) Offset() int

Offset returns the current offset (scanning position).

type ExprNode Âķ

type ExprNode interface {
	// Token returns the first token of the node. This method is useful to get position of this node.
	Token() *Token
}

ExprNode is a node of expression syntax tree. To know the syntax, see https://docs.github.com/en/actions/learn-github-actions/expressions

type ExprParser Âķ

type ExprParser struct {
	// contains filtered or unexported fields
}

ExprParser is a parser for expression syntax. To know the details, see https://docs.github.com/en/actions/learn-github-actions/expressions

func NewExprParser Âķ

func NewExprParser() *ExprParser

NewExprParser creates new ExprParser instance.

func (*ExprParser) Err Âķ

func (p *ExprParser) Err() *ExprError

Err returns an error which was caused while previous parsing.

func (*ExprParser) Parse Âķ

func (p *ExprParser) Parse(l *ExprLexer) (ExprNode, *ExprError)

Parse parses token sequence lexed by a given lexer into syntax tree.

type ExprSemanticsChecker Âķ

type ExprSemanticsChecker struct {
	// contains filtered or unexported fields
}

ExprSemanticsChecker is a semantics checker for expression syntax. It checks types of values in given expression syntax tree. It additionally checks other semantics like arguments of format() built-in function. To know the details of the syntax, see

- https://docs.github.com/en/actions/learn-github-actions/contexts - https://docs.github.com/en/actions/learn-github-actions/expressions

func NewExprSemanticsChecker Âķ

func NewExprSemanticsChecker(checkUntrustedInput bool, configVars []string, configSecrets []string) *ExprSemanticsChecker

NewExprSemanticsChecker creates new ExprSemanticsChecker instance. When checkUntrustedInput is set to true, the checker will make use of possibly untrusted inputs error.

func (*ExprSemanticsChecker) Check Âķ

func (sema *ExprSemanticsChecker) Check(expr ExprNode) (ExprType, []*ExprError)

Check checks semantics of given expression syntax tree. It returns the type of the expression as the first return value when the check was successfully done. And it returns all errors found while checking the expression as the second return value.

func (*ExprSemanticsChecker) IsConstant Âķ

func (sema *ExprSemanticsChecker) IsConstant(expr ExprNode) bool

IsConstant returns the given expression is a constant. For example the following expressions are constants.

  • 1 == 2
  • (!true && 'foo') || 'bar'
  • startsWith('foobar', 'foo')
  • format('{} + {} = {}', 1, 2, 3)

func (*ExprSemanticsChecker) SetContextAvailability Âķ

func (sema *ExprSemanticsChecker) SetContextAvailability(avail []string)

SetContextAvailability sets available context names while semantics checks. Some contexts limit where they can be used. https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability

Elements of 'avail' parameter must be in lower case to check context names in case-insensitive.

If this method is not called before checks, no context is available: ExprSemanticsChecker reports every context it finds as not allowed. An empty slice means the same. Available contexts for workflow keys can be obtained from jactionlint.WorkflowKeyAvailability.

func (*ExprSemanticsChecker) SetSpecialFunctionAvailability Âķ

func (sema *ExprSemanticsChecker) SetSpecialFunctionAvailability(avail []string)

SetSpecialFunctionAvailability sets names of available special functions while semantics checks. Some functions limit where they can be used. https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability

Elements of 'avail' parameter must be in lower case to check function names in case-insensitive.

If this method is not called before checks, ExprSemanticsChecker considers no special function is allowed by default. Allowed functions can be obtained from jactionlint.SpecialFunctionNames global constant.

Available function names for workflow keys can be obtained from jactionlint.WorkflowKeyAvailability.

func (*ExprSemanticsChecker) UpdateDispatchInputs Âķ

func (sema *ExprSemanticsChecker) UpdateDispatchInputs(ty *ObjectType)

UpdateDispatchInputs updates 'github.event.inputs' and 'inputs' objects to given object type. https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows

func (*ExprSemanticsChecker) UpdateInputs Âķ

func (sema *ExprSemanticsChecker) UpdateInputs(ty *ObjectType)

UpdateInputs updates 'inputs' context object to given object type.

func (*ExprSemanticsChecker) UpdateJobs Âķ

func (sema *ExprSemanticsChecker) UpdateJobs(ty *ObjectType)

UpdateJobs updates 'jobs' context object to given object type.

func (*ExprSemanticsChecker) UpdateMatrix Âķ

func (sema *ExprSemanticsChecker) UpdateMatrix(ty *ObjectType)

UpdateMatrix updates matrix object to given object type. Since matrix values change according to 'matrix' section of job configuration, the type needs to be updated.

func (*ExprSemanticsChecker) UpdateNeeds Âķ

func (sema *ExprSemanticsChecker) UpdateNeeds(ty *ObjectType)

UpdateNeeds updates 'needs' context object to given object type.

func (*ExprSemanticsChecker) UpdateSecrets Âķ

func (sema *ExprSemanticsChecker) UpdateSecrets(ty *ObjectType)

UpdateSecrets updates 'secrets' context object to given object type.

func (*ExprSemanticsChecker) UpdateSteps Âķ

func (sema *ExprSemanticsChecker) UpdateSteps(ty *ObjectType)

UpdateSteps updates 'steps' context object to given object type.

type ExprType Âķ

type ExprType interface {
	// String returns string representation of the type.
	String() string
	// Assignable returns if other type can be assignable to the type.
	Assignable(other ExprType) bool
	// Merge merges other type into this type. When other type conflicts with this type, the merged
	// result is any type as fallback.
	Merge(other ExprType) ExprType
	// DeepCopy duplicates itself. All its child types are copied recursively.
	DeepCopy() ExprType
}

ExprType is interface for types of values in expression.

type ExternalToolStatus Âķ added in v2.2.0

type ExternalToolStatus struct {
	// Status is "ran", "not found" or "disabled".
	Status string `json:"status"`
	// Command is the command the run was configured with (the default is the name of the tool).
	Command string `json:"command,omitempty"`
	// Scripts is the number of scripts the tool checked.
	Scripts int `json:"scripts"`
	// SkippedScripts is the number of scripts that the tool would have checked if it had run. It is omitted when
	// it is zero.
	SkippedScripts int `json:"skippedScripts,omitempty"`
}

ExternalToolStatus says what happened to one external linter during a run. It is in the run properties of the SARIF log, next to the coverage of the online checks, so a consumer can tell "checked and nothing found" from "not checked".

type Facts Âķ added in v2.2.0

type Facts struct {
	Version     int    `json:"version"`
	Tool        string `json:"tool"`
	ToolVersion string `json:"tool_version"`
	// Workflows are the workflow files that were exported, in the order of their paths.
	Workflows []*WorkflowFacts `json:"workflows"`
	// Actions are the action.yml files that were exported.
	Actions []*ActionFacts `json:"actions"`
	// Calls are the local calls of the exported files: a job that calls a reusable workflow of the repository, and a
	// step that runs a local action. The callee need not be in Workflows or Actions.
	Calls []*CallFacts `json:"calls"`
}

Facts is the document of --export-facts.

func (*Facts) Marshal Âķ added in v2.2.0

func (f *Facts) Marshal() ([]byte, error)

Marshal returns the document as indented JSON with a final newline.

type Fix Âķ

type Fix struct {
	// Description describes what applying the fix does, e.g. "Add timeout-minutes".
	Description string `json:"description"`
	// Unsafe marks a fix which may change the behavior of the workflow. Unsafe fixes are applied
	// only when requested explicitly and are not put in SARIF output.
	Unsafe bool `json:"unsafe,omitempty"`
	// Edits are the replacements to apply.
	Edits []TextEdit `json:"edits"`
}

Fix is an automatic correction for an Error. It is a list of edits to a single file. The edits must not overlap each other.

type FixConfig Âķ

type FixConfig struct {
	// Rules restricts --fix to the fixes of the rules with these IDs. The --fix-rules flag overrides it. When
	// the list is empty, the fixes of all rules are applied.
	Rules []string `yaml:"rules"`
}

FixConfig is the "fix" mapping of the config file.

type FixFailure Âķ

type FixFailure struct {
	// File is the path of the file as it was given to the linter.
	File string
	// Rules are the IDs of the rules whose fixes are to blame, sorted.
	Rules []string
	// Reason says what was wrong.
	Reason string
}

FixFailure reports a fix which was not applied because it would have damaged the file, or fixing which did not converge. The rest of the fixes of the file are still applied, except when fixing did not converge: then the file is left as it was before the fixes which kept repeating.

func (FixFailure) String Âķ

func (f FixFailure) String() string

type FixMode Âķ

type FixMode int

FixMode selects which automatic fixes are applied.

const (
	// FixModeSafe applies the fixes which do not change the behavior of the workflow.
	FixModeSafe FixMode = iota + 1
	// FixModeUnsafe applies the safe fixes and the ones which may change the behavior of the workflow.
	FixModeUnsafe
)

type FixOptions Âķ

type FixOptions struct {
	// Mode selects the fixes to apply. It is required.
	Mode FixMode
	// Rules restricts fixing to the fixes of the errors with these rule IDs. When it is empty, the
	// "fix.rules" of the config file is used, and when that is empty too, the fixes of all rules are applied.
	Rules []string
	// DryRun computes the fixes but does not write the files. FixResult.Diff has the changes.
	DryRun bool
	// MaxPasses overrides the number of passes after which fixing gives up. Zero means the default (10).
	MaxPasses int
}

FixOptions are the options of fixing files.

type FixResult Âķ

type FixResult struct {
	// Fixed is the paths of the files which were rewritten (or would be with DryRun), as they were given
	// to the linter.
	Fixed []string
	// Applied is the number of fixes which were applied.
	Applied int
	// ByRule is the number of the applied fixes for each rule ID.
	ByRule map[string]int
	// Errors are the errors which remain after fixing, including the ones without a fix. They were
	// printed with the output format of the linter.
	Errors []*Error
	// Failures are the files a fix was refused for. See FixFailure.
	Failures []FixFailure
	// Diff is the changes of all the fixed files as a unified diff. It is set only with DryRun.
	Diff string
}

FixResult is the result of fixing files.

type FixtureGitHubClient Âķ

type FixtureGitHubClient struct {
	// contains filtered or unexported fields
}

FixtureGitHubClient is a GitHubClient which serves recorded data. A call for data which was not recorded fails, so a test notices when a rule starts asking for something new. Create it with NewFixtureGitHubClient.

func NewFixtureGitHubClient Âķ

func NewFixtureGitHubClient(data []byte) (*FixtureGitHubClient, error)

NewFixtureGitHubClient parses fixtures made by a RecordingGitHubClient (or written by hand) and returns a client which serves them.

func (*FixtureGitHubClient) Advisories Âķ

func (c *FixtureGitHubClient) Advisories(_ context.Context, owner, repo string) ([]GitHubAdvisory, error)

Advisories implements GitHubClient.

func (*FixtureGitHubClient) AdvisoriesForPackages Âķ

func (c *FixtureGitHubClient) AdvisoriesForPackages(ctx context.Context, packages []string) ([]GitHubAdvisory, error)

AdvisoriesForPackages implements GitHubPackageAdvisoryClient.

func (*FixtureGitHubClient) Branches Âķ

func (c *FixtureGitHubClient) Branches(_ context.Context, owner, repo string, limit int) (*GitHubBranchList, error)

Branches implements GitHubClient.

func (*FixtureGitHubClient) Calls Âķ

func (c *FixtureGitHubClient) Calls() int

Calls returns how many calls the client served. Tests use it to check that lookups are deduplicated.

func (*FixtureGitHubClient) Compare Âķ

func (c *FixtureGitHubClient) Compare(_ context.Context, owner, repo, base, head string) (GitHubCompareStatus, error)

Compare implements GitHubClient.

func (*FixtureGitHubClient) Environment Âķ added in v2.2.0

func (c *FixtureGitHubClient) Environment(_ context.Context, owner, repo, name string) (*GitHubEnvironment, error)

Environment implements GitHubEnvironmentClient.

func (*FixtureGitHubClient) FileContent Âķ added in v2.2.0

func (c *FixtureGitHubClient) FileContent(_ context.Context, owner, repo, ref, path string) ([]byte, error)

FileContent implements GitHubContentClient.

func (*FixtureGitHubClient) ImageDigest Âķ added in v2.2.0

func (c *FixtureGitHubClient) ImageDigest(_ context.Context, registry, repository, tag string) (string, error)

ImageDigest implements ImageDigestClient. An image which was not recorded fails, so that a test notices when a rule starts to ask for something new.

func (*FixtureGitHubClient) Owner Âķ added in v2.2.0

func (c *FixtureGitHubClient) Owner(_ context.Context, login string) (*GitHubOwner, error)

Owner implements GitHubOwnerClient.

func (*FixtureGitHubClient) Release Âķ added in v2.2.0

func (c *FixtureGitHubClient) Release(_ context.Context, owner, repo, tag string) (*GitHubRelease, error)

Release implements GitHubReleaseClient.

func (*FixtureGitHubClient) ReleaseDate Âķ added in v2.2.0

func (c *FixtureGitHubClient) ReleaseDate(_ context.Context, owner, repo, tag, sha string) (*GitHubReleaseDate, error)

ReleaseDate implements GitHubReleaseDateClient.

func (*FixtureGitHubClient) Repository Âķ

func (c *FixtureGitHubClient) Repository(_ context.Context, owner, repo string) (*GitHubRepo, error)

Repository implements GitHubClient.

func (*FixtureGitHubClient) ResolveRef Âķ

func (c *FixtureGitHubClient) ResolveRef(_ context.Context, owner, repo string, ns GitHubRefNamespace, name string) (string, bool, error)

ResolveRef implements GitHubClient.

func (*FixtureGitHubClient) RunJobs Âķ added in v2.2.0

func (c *FixtureGitHubClient) RunJobs(_ context.Context, owner, repo string, runID int64) (*GitHubRunJobs, error)

RunJobs implements GitHubRunsClient.

func (*FixtureGitHubClient) Tags Âķ

func (c *FixtureGitHubClient) Tags(_ context.Context, owner, repo string) (*GitHubTagList, error)

Tags implements GitHubClient.

func (*FixtureGitHubClient) WorkflowRuns Âķ added in v2.2.0

func (c *FixtureGitHubClient) WorkflowRuns(_ context.Context, owner, repo, workflowFile string, limit int) ([]GitHubWorkflowRun, error)

WorkflowRuns implements GitHubRunsClient.

type Float Âķ

type Float struct {
	// Value is a raw value of the float string.
	Value float64
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Float represents generic float value in YAML file with position.

type FloatNode Âķ

type FloatNode struct {
	// Value is value of the float literal.
	Value float64
	// contains filtered or unexported fields
}

FloatNode is node for float literal.

func (*FloatNode) Token Âķ

func (n *FloatNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type FuncCallNode Âķ

type FuncCallNode struct {
	// Callee is a name of called function. This is string value because currently only built-in
	// functions can be called.
	Callee string
	// Args is arguments of the function call.
	Args []ExprNode
	// contains filtered or unexported fields
}

FuncCallNode represents function call in expression. Note that currently only calling builtin functions is supported.

func (*FuncCallNode) Token Âķ

func (n *FuncCallNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type FuncSignature Âķ

type FuncSignature struct {
	// Name is a name of the function.
	Name string
	// Ret is a return type of the function.
	Ret ExprType
	// Params is a list of parameter types of the function. The final element of this list might
	// be repeated as variable length arguments.
	Params []ExprType
	// VariableLengthParams is a flag to handle variable length parameters. When this flag is set to
	// true, it means that the last type of params might be specified multiple times (including zero
	// times). Setting true implies length of Params is more than 0.
	VariableLengthParams bool
	// IsConstFunc is true when the function returns a constant when all parameters are constants.
	IsConstFunc bool
}

FuncSignature is a signature of function, which holds return and arguments types.

func (*FuncSignature) String Âķ

func (sig *FuncSignature) String() string

type GitHubAdvisory Âķ

type GitHubAdvisory struct {
	// ID is the GHSA identifier such as "GHSA-mrrh-fwg8-r2c3".
	ID string `json:"id"`
	// CVE is the CVE identifier. It can be empty.
	CVE string `json:"cve,omitempty"`
	// Summary is the one-line description.
	Summary string `json:"summary"`
	// Severity is "low", "medium", "high" or "critical".
	Severity string `json:"severity,omitempty"`
	// URL is the page of the advisory.
	URL string `json:"url,omitempty"`
	// Vulnerabilities are the affected packages.
	Vulnerabilities []GitHubVulnerability `json:"vulnerabilities"`
}

GitHubAdvisory is a published security advisory (GHSA).

type GitHubAdvisoryListClient Âķ added in v2.2.0

type GitHubAdvisoryListClient interface {
	ActionAdvisories(ctx context.Context) ([]GitHubAdvisory, error)
}

GitHubAdvisoryListClient is an optional interface of a GitHubClient. A client which implements it can list every advisory of the GitHub Actions ecosystem in one lookup (a few pages of one list request), which is cheaper than one lookup for each action when a run uses more than a handful of them, and names no repository to GitHub. The online checks use it when they can and ask with GitHubPackageAdvisoryClient or GitHubClient.Advisories for each action when the list fails or is truncated (ErrGitHubListTruncated). Withdrawn advisories are not returned, and only the vulnerabilities of the actions ecosystem are kept, as for the lookups by package.

type GitHubBranch Âķ

type GitHubBranch struct {
	Name string `json:"name"`
	SHA  string `json:"sha"`
}

GitHubBranch is a branch and its head commit.

type GitHubBranchList Âķ

type GitHubBranchList struct {
	Branches []GitHubBranch `json:"branches"`
	// Truncated is true when the repository has more branches than Branches lists.
	Truncated bool `json:"truncated,omitempty"`
}

GitHubBranchList is the branches of a repository.

type GitHubBranchScan Âķ

type GitHubBranchScan struct {
	// Found is true when the commit is the head of a branch or an ancestor of one.
	Found bool
	// Complete is true when every branch of the repository was looked at, so that !Found means the
	// commit is on no branch. It is false when the repository has more branches than the limit.
	Complete bool
}

GitHubBranchScan is the result of GitHubBranchScanner.CommitOnAnyBranch.

type GitHubBranchScanner Âķ

type GitHubBranchScanner interface {
	// CommitOnAnyBranch looks at up to limit branches. It returns ErrGitHubBranchScanUnavailable
	// when the client cannot do it now, for example without a token.
	CommitOnAnyBranch(ctx context.Context, owner, repo, sha string, limit int) (GitHubBranchScan, error)
}

GitHubBranchScanner is an optional interface of a GitHubClient. A client which implements it answers "is the commit on any branch?" in fewer requests than comparing with every branch (the built-in client uses one GraphQL request per 100 branches when it has a token). The online rules use it when it is there, and compare the branches one by one otherwise.

type GitHubClient Âķ

type GitHubClient interface {
	// Repository returns the metadata of a repository.
	Repository(ctx context.Context, owner, repo string) (*GitHubRepo, error)
	// Tags returns the tags of a repository with the commit each one points to. Annotated tags are
	// dereferenced to the commit. The client reads a bounded number of tags: when there are more,
	// the list is marked as truncated.
	Tags(ctx context.Context, owner, repo string) (*GitHubTagList, error)
	// ResolveRef resolves the branch (GitHubRefHeads) or tag (GitHubRefTags) of the name to the SHA of
	// the commit it points to. Annotated tags are dereferenced. The boolean is false when the ref
	// does not exist.
	ResolveRef(ctx context.Context, owner, repo string, ns GitHubRefNamespace, name string) (sha string, found bool, err error)
	// Branches returns up to limit branches with their head commit. The list is marked as truncated when
	// the repository has more branches.
	Branches(ctx context.Context, owner, repo string, limit int) (*GitHubBranchList, error)
	// Compare tells how the head commit relates to the base commit (see GitHubCompareStatus). Both
	// are commit SHAs. It returns ErrGitHubNotFound when GitHub knows no such commit.
	Compare(ctx context.Context, owner, repo, base, head string) (GitHubCompareStatus, error)
	// Advisories returns the published security advisories which affect the GitHub Actions
	// ecosystem package "owner/repo".
	Advisories(ctx context.Context, owner, repo string) ([]GitHubAdvisory, error)
}

GitHubClient is the part of the GitHub API which the online rules (see LinterOptions.Online) use. It is an interface so that tests, and programs embedding jactionlint, can serve the data from fixtures (see NewFixtureGitHubClient) instead of the network. The client built into the jactionlint command talks REST to api.github.com, and caches the answers on disk.

A client must be safe for concurrent use. Methods return ErrGitHubNotFound (possibly wrapped) when the repository or object does not exist or is not visible, and an error satisfying errors.Is(err, ErrGitHubRateLimited) when the API refused the request because of the rate limit. The repository owner and name are used as given; they are not case-normalized.

type GitHubCompareStatus Âķ

type GitHubCompareStatus string

GitHubCompareStatus is how the head commit of a comparison relates to the base commit.

const (
	// GitHubCompareIdentical means that both commits are the same.
	GitHubCompareIdentical GitHubCompareStatus = "identical"
	// GitHubCompareAhead means that the head is a descendant of the base.
	GitHubCompareAhead GitHubCompareStatus = "ahead"
	// GitHubCompareBehind means that the head is an ancestor of the base.
	GitHubCompareBehind GitHubCompareStatus = "behind"
	// GitHubCompareDiverged means that each commit has changes which the other lacks.
	GitHubCompareDiverged GitHubCompareStatus = "diverged"
)

type GitHubContentClient Âķ added in v2.2.0

type GitHubContentClient interface {
	// FileContent returns the content of the file at path (slash separated, relative to the root of the
	// repository) at ref: a commit SHA, a tag or a branch. It returns ErrGitHubNotFound (possibly wrapped)
	// when the repository, the ref or the file does not exist, is not visible, or is not a regular file
	// small enough to be read. A ref which is a full commit SHA names an immutable file, so the built-in
	// client keeps the answer without an age limit.
	FileContent(ctx context.Context, owner, repo, ref, path string) ([]byte, error)
}

GitHubContentClient is an optional interface of a GitHubClient. A client which implements it can read a file of a repository at a ref, which lets the online checks read the metadata (action.yml) of an action or the declaration of a reusable workflow that is not in the data set built into jactionlint. A client without it makes those checks report nothing for such actions, which is what happens when the lookup fails.

type GitHubEnvironment Âķ added in v2.2.0

type GitHubEnvironment struct {
	// Name is the name of the environment.
	Name string `json:"name"`
	// RequiredReviewers is true when the environment has a "required_reviewers" protection rule: a job which uses it
	// waits until one of the reviewers approves. Other rules (a wait timer, the branches which may deploy) do not
	// make anyone look at what the job runs.
	RequiredReviewers bool `json:"required_reviewers"`
}

GitHubEnvironment is an environment of a repository.

type GitHubEnvironmentClient Âķ added in v2.2.0

type GitHubEnvironmentClient interface {
	// Environment returns the environment of the repository. It returns ErrGitHubNotFound when GitHub has no such
	// environment, or does not show it to the client: a repository which is private to the client looks the same.
	Environment(ctx context.Context, owner, repo, name string) (*GitHubEnvironment, error)
}

GitHubEnvironmentClient is an optional interface of a GitHubClient. A client which implements it can tell what protects an environment, which jactionlint asks for when a workflow relies on the reviewers of an environment. Without it the environment is trusted as it is without the online checks.

type GitHubOwner Âķ added in v2.2.0

type GitHubOwner struct {
	// Login is the name of the account as GitHub spells it.
	Login string `json:"login"`
	// Type is "User" or "Organization".
	Type string `json:"type,omitempty"`
}

GitHubOwner is a user or an organization.

type GitHubOwnerClient Âķ added in v2.2.0

type GitHubOwnerClient interface {
	// Owner returns the user or organization of the login. It returns ErrGitHubNotFound when GitHub has no account
	// of that name: anyone can register it.
	Owner(ctx context.Context, login string) (*GitHubOwner, error)
}

GitHubOwnerClient is an optional interface of a GitHubClient. A client which implements it can tell whether a user or an organization exists, which jactionlint asks for when the repository of an action does not exist, or has moved to another owner. Without it the repojacking check does nothing.

type GitHubPackageAdvisoryClient Âķ

type GitHubPackageAdvisoryClient interface {
	AdvisoriesForPackages(ctx context.Context, packages []string) ([]GitHubAdvisory, error)
}

GitHubPackageAdvisoryClient is an optional interface of a GitHubClient. GitHub publishes the advisories of an action in a subdirectory (gradle/actions/setup-gradle) under the full package name, which the "owner/repo" lookup of GitHubClient.Advisories does not find. A client which implements it returns the advisories which affect any of the packages, each written "owner/repo" or "owner/repo/subpath", in one lookup and without duplicates.

type GitHubRateLimitError Âķ

type GitHubRateLimitError struct {
	// Reset is when the limit resets. It is the zero time when unknown.
	Reset time.Time
	// Authenticated is whether the request carried a token. Unauthenticated requests have a much
	// lower limit.
	Authenticated bool
	// TokenHint says where to set the token which raises the limit, when it is not the usual GITHUB_TOKEN and GH_TOKEN
	// (the token for github.com in the fallback of an Enterprise Server). Empty means the usual ones.
	TokenHint string
	// contains filtered or unexported fields
}

GitHubRateLimitError is the error of a GitHubClient when the API refused a request because of its rate limit. errors.Is(err, ErrGitHubRateLimited) is true for it.

func (*GitHubRateLimitError) Error Âķ

func (e *GitHubRateLimitError) Error() string

func (*GitHubRateLimitError) Is Âķ

func (e *GitHubRateLimitError) Is(target error) bool

Is makes errors.Is(err, ErrGitHubRateLimited) true.

type GitHubRefNamespace Âķ

type GitHubRefNamespace string

GitHubRefNamespace tells whether a ref name is a branch or a tag.

const (
	// GitHubRefHeads is the namespace of branches (refs/heads/).
	GitHubRefHeads GitHubRefNamespace = "heads"
	// GitHubRefTags is the namespace of tags (refs/tags/).
	GitHubRefTags GitHubRefNamespace = "tags"
)

type GitHubRelease Âķ added in v2.2.0

type GitHubRelease struct {
	// Tag is the name of the tag of the release.
	Tag string `json:"tag"`
	// Immutable is true when the release is immutable: its tag and its assets cannot be changed any more.
	Immutable bool `json:"immutable"`
	// Prerelease is true when GitHub marks the release as a prerelease, whatever the name of its tag says.
	Prerelease bool `json:"prerelease,omitempty"`
}

GitHubRelease is the release of a tag.

type GitHubReleaseClient Âķ added in v2.2.0

type GitHubReleaseClient interface {
	// Release returns the published release of the tag. It returns ErrGitHubNotFound when the tag has no release (the
	// tags which are not releases, such as the v4 which moves with every v4.x.y, have none).
	Release(ctx context.Context, owner, repo, tag string) (*GitHubRelease, error)
}

GitHubReleaseClient is an optional interface of a GitHubClient. A client which implements it can tell whether the release of a tag is immutable, which the "immutable-release" policy of the unpinned-uses rule needs.

type GitHubReleaseDate Âķ added in v2.2.0

type GitHubReleaseDate struct {
	// PublishedAt is when the release of GitHub named by the tag was published. It is the zero time
	// when the tag has no release.
	PublishedAt time.Time `json:"published_at,omitzero"`
	// CommittedAt is the committer date of the commit. A client sets it when the tag has no release (the
	// date is then the best that is known). A tag which was moved to an older commit carries
	// the date of that commit, so the date can be older than the release it stands for.
	CommittedAt time.Time `json:"committed_at,omitzero"`
}

GitHubReleaseDate says when a version of an action was released. The data is what the check of the release cooldown (the rule action-release-cooldown) needs.

func (GitHubReleaseDate) Time Âķ added in v2.2.0

func (d GitHubReleaseDate) Time() (t time.Time, release, ok bool)

Time returns when the version was released: the publication of the release, else the date of the commit. The boolean is false when neither is known.

type GitHubReleaseDateClient Âķ added in v2.2.0

type GitHubReleaseDateClient interface {
	// ReleaseDate returns when the tag was released. tag can be empty when the commit is not tagged. sha is the
	// commit the tag points to, or the commit itself. When the tag has no release, or tag is empty,
	// the answer has the date of the commit. A tag or a commit which does not exist gives an answer
	// without dates, not an error.
	ReleaseDate(ctx context.Context, owner, repo, tag, sha string) (*GitHubReleaseDate, error)
}

GitHubReleaseDateClient is an optional interface of a GitHubClient. A client which implements it answers the rule action-release-cooldown. Without it the rule has nothing to check and says nothing.

type GitHubRepo Âķ

type GitHubRepo struct {
	// Archived is true when the repository is archived, which makes it read-only and unmaintained.
	Archived bool `json:"archived"`
	// DefaultBranch is the name of the default branch.
	DefaultBranch string `json:"default_branch"`
	// Private is true when the repository is private or internal, or the answer does not say that it is public: what
	// GitHub does not show to a token which cannot read it is then not proof that it does not exist. A client which does
	// not know leaves it false, which means public.
	Private bool `json:"private,omitempty"`
	// FullName is "owner/repo" as GitHub spells it now. It differs from the name that was asked for when the
	// repository was renamed or transferred and GitHub redirected the request. It can be empty (a client which
	// does not know it).
	FullName string `json:"full_name,omitempty"`
	// ID is the numeric ID of the repository, which stays when it is renamed or transferred. It is 0 when unknown.
	ID int64 `json:"id,omitempty"`
	// Owner is the owner of the repository, nil when unknown.
	Owner *GitHubRepoOwner `json:"owner,omitempty"`
}

GitHubRepo is the metadata of a repository.

type GitHubRepoOwner Âķ added in v2.2.0

type GitHubRepoOwner struct {
	// ID is the numeric ID of the user or organization.
	ID int64 `json:"id,omitempty"`
}

GitHubRepoOwner is the owner of a repository.

type GitHubRunJob Âķ added in v2.2.0

type GitHubRunJob struct {
	// Name is the name that GitHub shows: the ID of the job, or its name with the values of the matrix.
	Name string `json:"name"`
	// Conclusion is "success", "failure", "cancelled", "skipped" and the like. It is empty while the job runs.
	Conclusion string `json:"conclusion,omitempty"`
	// StartedAt and CompletedAt are when the job started on a runner and when it ended. The wait for a runner is
	// not in between.
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at"`
}

GitHubRunJob is a job of a run.

type GitHubRunJobs Âķ added in v2.2.0

type GitHubRunJobs struct {
	Jobs []GitHubRunJob `json:"jobs"`
	// Truncated is true when the run has more jobs than Jobs lists (a large matrix).
	Truncated bool `json:"truncated,omitempty"`
}

GitHubRunJobs are the jobs of the latest attempt of a run.

type GitHubRunsClient Âķ added in v2.2.0

type GitHubRunsClient interface {
	// WorkflowRuns returns up to limit of the most recent runs of the workflow file ("ci.yaml", the name of the
	// file in .github/workflows) that ended with success, newest first. ErrGitHubNotFound means the workflow is not
	// known to GitHub (a file that was never pushed, or a repository the token cannot read).
	WorkflowRuns(ctx context.Context, owner, repo, workflowFile string, limit int) ([]GitHubWorkflowRun, error)
	// RunJobs returns the jobs of the latest attempt of the run.
	RunJobs(ctx context.Context, owner, repo string, runID int64) (*GitHubRunJobs, error)
}

GitHubRunsClient is an optional interface of a GitHubClient. A client which implements it can list the runs of a workflow and the jobs of a run, which --suggest-timeouts reads. Without it the report is not available.

type GitHubStatusError Âķ

type GitHubStatusError struct {
	// Status is the HTTP status code.
	Status int
	// Message is what the API said, if anything.
	Message string
}

GitHubStatusError is the error of a GitHubClient when the API answered with a failure status which is neither "not found" nor "rate limited".

func (*GitHubStatusError) Error Âķ

func (e *GitHubStatusError) Error() string

type GitHubTag Âķ

type GitHubTag struct {
	Name string `json:"name"`
	// SHA is the full SHA of the commit. For an annotated tag it is the commit the tag object points to.
	SHA string `json:"sha"`
}

GitHubTag is a tag and the commit it points to.

type GitHubTagList Âķ

type GitHubTagList struct {
	Tags []GitHubTag `json:"tags"`
	// Truncated is true when the repository has more tags than Tags lists. A tag or commit missing
	// from the list may still exist.
	Truncated bool `json:"truncated,omitempty"`
}

GitHubTagList is the tags of a repository.

type GitHubVulnerability Âķ

type GitHubVulnerability struct {
	// Package is the name of the affected action: "owner/repo", optionally with a subdirectory.
	Package string `json:"package"`
	// VulnerableRange is the affected versions, such as ">= 1.0.0, < 1.2.3".
	VulnerableRange string `json:"range"`
	// FirstPatched is the first version which fixes the vulnerability. It is empty when none does.
	FirstPatched string `json:"first_patched,omitempty"`
}

GitHubVulnerability is one affected package of an advisory.

type GitHubWorkflowRun Âķ added in v2.2.0

type GitHubWorkflowRun struct {
	// ID is the ID of the run.
	ID int64 `json:"id"`
	// CreatedAt is when the run was created.
	CreatedAt time.Time `json:"created_at"`
	// Event is the event that triggered the run.
	Event string `json:"event,omitempty"`
}

GitHubWorkflowRun is a run of a workflow.

type IgnorePattern Âķ

type IgnorePattern struct {
	// ID is the rule ID to ignore. It is empty when the pattern is a regular expression.
	ID string
	// Regexp is the regular expression to match error messages. It is nil when the pattern is a rule ID.
	Regexp *regexp.Regexp
	// Retired is the retired rule ID the pattern was written with (see RenamedRule), or empty. ID is then
	// the rule it was merged into, and the pattern matches only the findings which had the retired ID.
	Retired string
}

IgnorePattern is one pattern of an "ignore" list. It is either a rule ID such as "unpinned-uses", which ignores every error with the ID, or a regular expression matched against the error messages.

func ParseIgnorePattern Âķ

func ParseIgnorePattern(s string) (IgnorePattern, error)

ParseIgnorePattern parses a pattern of --ignore, "paths.*.ignore" and inline ignore comments. When the pattern is exactly the ID of a rule listed in Rules, it ignores the errors of that rule. Otherwise it is compiled as a regular expression which is matched against the error messages.

func (IgnorePattern) Match Âķ

func (p IgnorePattern) Match(err *Error) bool

Match returns whether the pattern matches the error.

func (IgnorePattern) String Âķ

func (p IgnorePattern) String() string

String returns the source of the pattern.

type IgnorePatterns Âķ

type IgnorePatterns []IgnorePattern

IgnorePatterns is a list of patterns. These patterns are used for filtering errors by matching the rule IDs or the error messages.

func (IgnorePatterns) Match Âķ

func (pats IgnorePatterns) Match(err *Error) bool

Match returns whether the given error should be ignored due to the "ignore" configuration.

func (*IgnorePatterns) UnmarshalYAML Âķ

func (pats *IgnorePatterns) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ImageDigestClient Âķ added in v2.2.0

type ImageDigestClient interface {
	// ImageDigest returns the digest of the manifest which the tag has in the registry: the digest of the image index
	// of a multi-platform image, the one that `docker pull image:tag` resolves and Renovate writes. registry is
	// "docker.io" or "ghcr.io", repository is the path in it ("library/ubuntu"). It returns ErrImageNotFound
	// (possibly wrapped) when there is no such image or it is not visible.
	ImageDigest(ctx context.Context, registry, repository, tag string) (string, error)
}

ImageDigestClient is an optional interface of a GitHubClient. A client which implements it answers the digest of an image, which `--online --fix` writes after the tag of an image (`image:tag@sha256:...`). The client built into jactionlint asks the registry (Docker Hub and ghcr.io); a custom one can serve recorded answers.

type ImageVersionEvent Âķ

type ImageVersionEvent struct {
	// Types is a list of activity types of the event: created, ready or deleted. They are in the workflow
	// schema of GitHub but not in the documentation of the event.
	Types []*String
	// Names is a list of names which match to the created image names.
	Names []*String
	// Versions is a list of names which match to the created image versions. Glob patterns are available.
	Versions []*String
	// Pos is a position in source.
	Pos *Pos
}

ImageVersionEvent is image_version event configuration. https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#image_version_ready

func (*ImageVersionEvent) EventName Âķ

func (e *ImageVersionEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type IndexAccessNode Âķ

type IndexAccessNode struct {
	// Operand is an expression at operand of index access, which should be array or object.
	Operand ExprNode
	// Index is an expression at index, which should be integer or string.
	Index ExprNode
}

IndexAccessNode is node for index access, which represents dynamic object property access or array index access.

func (*IndexAccessNode) Token Âķ

func (n *IndexAccessNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type Input Âķ

type Input struct {
	// Name is a name of the input.
	Name *String
	// Value is a value of the input.
	Value *String
}

Input is an input field for running an action. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepswith

type InputFact Âķ added in v2.2.0

type InputFact struct {
	Name     string    `json:"name"`
	Value    string    `json:"value"`
	Dynamic  bool      `json:"dynamic,omitempty"`
	Location *Location `json:"location,omitempty"`
}

InputFact is one input of a call: a key of "with:" of a step or of a job that calls a reusable workflow.

type Int Âķ

type Int struct {
	// Value is a raw value of the integer string.
	Value int
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Int represents generic integer value in YAML file with position.

type IntNode Âķ

type IntNode struct {
	// Value is value of the integer literal.
	Value int
	// contains filtered or unexported fields
}

IntNode is node for integer literal.

func (*IntNode) Token Âķ

func (n *IntNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type InvalidGlobPattern Âķ

type InvalidGlobPattern struct {
	// Message is a human readable error message.
	Message string
	// Column is a column number of the error in the glob pattern. This value is 1-based, but zero
	// is valid value. Zero means the error occurred before reading first character. This happens
	// when a given pattern is empty. When the given pattern include a newline and line number
	// increases (invalid pattern), the column number falls back into always 0.
	Column int
}

InvalidGlobPattern is an error on invalid glob pattern.

func ValidatePathGlob Âķ

func ValidatePathGlob(pat string) []InvalidGlobPattern

ValidatePathGlob checks a given input as glob pattern for file paths. It returns list of errors found by the validation. See the following URL for more details of the syntax: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet

func ValidateRefGlob Âķ

func ValidateRefGlob(pat string) []InvalidGlobPattern

ValidateRefGlob checks a given input as glob pattern for Git ref names. It returns list of errors found by the validation. See the following URL for more details of the syntax: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet

func (*InvalidGlobPattern) Error Âķ

func (err *InvalidGlobPattern) Error() string

func (*InvalidGlobPattern) String Âķ

func (err *InvalidGlobPattern) String() string

type Job Âķ

type Job struct {
	// ID is an ID of the job, which is key of job configuration objects.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_id
	ID *String
	// Name is a name of job that user can specify freely.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idname
	Name *String
	// Needs is list of job IDs which should be run before running this job.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idneeds
	Needs []*String
	// RunsOn is runner configuration which run the job.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idruns-on
	RunsOn *Runner
	// Permissions is permission configuration for running the job.
	Permissions *Permissions
	// CacheMode controls cache access for this job.
	// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idcache-mode
	CacheMode *String
	// Environment is environment specification where the job runs.
	Environment *Environment
	// Concurrency is concurrency configuration on running the job.
	Concurrency *Concurrency
	// Outputs is map from output name to output specifications.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idoutputs
	Outputs map[string]*Output
	// Env is environment variables setup while running the job.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idenv
	Env *Env
	// Defaults is default configurations of how to run scripts.
	Defaults *Defaults
	// If is a condition whether this job should be run.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idif
	If *String
	// Steps is list of steps to be run in the job.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idsteps
	Steps []*Step
	// TimeoutMinutes is timeout value of running the job in minutes.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idtimeout-minutes
	TimeoutMinutes *Float
	// CancelTimeoutMinutes is the number of minutes the runner waits for the job to finish after it is
	// cancelled. It is accepted by the workflow schema of the runner but not documented yet.
	// https://github.com/actions/runner/blob/main/src/Sdk/WorkflowParser/workflow-v1.0.json (job-factory)
	CancelTimeoutMinutes *Float
	// Strategy is strategy configuration of running the job.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategy
	Strategy *Strategy
	// ContinueOnError is a flag to show if execution should continue on error.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idcontinue-on-error
	ContinueOnError *Bool
	// Container is container configuration to run the job.
	Container *Container
	// Services is a services configurations.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idservices
	Services *Services
	// WorkflowCall is a workflow call by 'uses:'.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_iduses
	WorkflowCall *WorkflowCall
	// Snapshot is a custom image snapshot.
	// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idsnapshot
	Snapshot *Snapshot
	// Composite is true for the synthetic job which holds the steps of a composite action (see
	// ParseAction). Such a job has no runs-on, needs, permissions or timeout-minutes of its own: they
	// belong to the job of the workflow which calls the action. Unlike in a workflow job, every run
	// step of a composite action must set shell.
	Composite bool
	// Pos is a position in source.
	Pos *Pos
}

Job is configuration of how to run a job. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobs

type JobFacts Âķ added in v2.2.0

type JobFacts struct {
	ID       string      `json:"id"`
	Location *Location   `json:"location,omitempty"`
	Name     *StringFact `json:"name,omitempty"`
	Needs    []string    `json:"needs,omitempty"`
	// RunsOn are the labels of runs-on. DynamicRunsOn is true when an expression decides them.
	RunsOn        []string `json:"runs_on,omitempty"`
	DynamicRunsOn bool     `json:"runs_on_dynamic,omitempty"`
	// Permissions are those the job declares; EffectivePermissions are those its token has.
	Permissions          PermissionFacts      `json:"permissions"`
	EffectivePermissions EffectivePermissions `json:"effective_permissions"`
	Concurrency          *ConcurrencyFacts    `json:"concurrency,omitempty"`
	Environment          *StringFact          `json:"environment,omitempty"`
	TimeoutMinutes       *NumberFact          `json:"timeout_minutes,omitempty"`
	CacheMode            *StringFact          `json:"cache_mode,omitempty"`
	// If is the condition as written, without "${{ }}". It is not evaluated.
	If *string `json:"if,omitempty"`
	// Uses is set when the job calls a reusable workflow.
	Uses  *JobUsesFacts `json:"uses,omitempty"`
	Steps []*StepFacts  `json:"steps,omitempty"`
}

JobFacts are the facts of one job.

type JobUsesFacts Âķ added in v2.2.0

type JobUsesFacts struct {
	UsesFacts
	// SecretsInherit is true for "secrets: inherit".
	SecretsInherit bool `json:"secrets_inherit"`
	// Secrets are the names of the secrets that the call passes by name.
	Secrets []string    `json:"secrets,omitempty"`
	Inputs  []InputFact `json:"inputs,omitempty"`
}

JobUsesFacts is a job that calls a reusable workflow.

type Linter Âķ

type Linter struct {
	// contains filtered or unexported fields
}

Linter is struct to lint workflow files.

Example Âķ
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/jdx/jactionlint/v2"
)

func main() {
	// Specify linter options
	o := &jactionlint.LinterOptions{
		IgnorePatterns: []string{`'label ".+" is unknown'`},
		// Other options...
	}

	// Create Linter instance which outputs errors to stdout
	l, err := jactionlint.NewLinter(os.Stdout, o)
	if err != nil {
		panic(err)
	}

	// File to check
	f := filepath.Join("testdata", "examples", "main.yaml")

	// First return value is an array of lint errors found in the workflow files. The second return
	// value is an error of jactionlint itself. This call outputs the lint errors to stdout. Use
	// io.Discard to prevent the output.
	//
	// There are several methods to run linter.
	// - LintFile: Check the given single file
	// - LintFiles: Check the given multiple files
	// - LintDir: Check all workflow files in the given single directory recursively
	// - LintRepository: Check all workflow files under .github/workflows in the given repository
	// - LintStdin: Check the given workflow content read from STDIN
	// - Lint: Check the given workflow content assuming the given file path
	errs, err := l.LintFile(f, nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(len(errs), "lint errors found by jactionlint")
}
Example (YourOwnRule) Âķ
package main

import (
	"fmt"
	"io"
	"path/filepath"

	"github.com/jdx/jactionlint/v2"
)

// A rule type to check every steps have their names.
type RuleStepName struct {
	// Embedding RuleBase struct implements the minimal Rule interface.
	jactionlint.RuleBase
}

// Reimplement methods in RuleBase. Visit* methods are called on checking workflows.
func (r *RuleStepName) VisitStep(n *jactionlint.Step) error {
	// Implement your own check
	if n.Name == nil {
		// RuleBase provides methods to report errors. See RuleBase.Error and RuleBase.Errorf.
		r.Error(n.Pos, "every step must have its name")
	}
	return nil
}

func NewRuleStepName() *RuleStepName {
	return &RuleStepName{
		RuleBase: jactionlint.NewRuleBase("step-name", "Checks every step has their own name"),
	}
}

func main() {
	// The function set at OnRulesCreated is called after rule instances are created. You can
	// add/remove some rules and return the modified slice. This function is called on linting
	// each workflow files.
	o := &jactionlint.LinterOptions{
		OnRulesCreated: func(rules []jactionlint.Rule) []jactionlint.Rule {
			rules = append(rules, NewRuleStepName())
			return rules
		},
	}

	l, err := jactionlint.NewLinter(io.Discard, o)
	if err != nil {
		panic(err)
	}

	f := filepath.Join("testdata", "ok", "minimal.yaml")

	// First return value is an array of lint errors found in the workflow file.
	errs, err := l.LintFile(f, nil)
	if err != nil {
		panic(err)
	}

	// `errs` includes errors like below:
	//
	// testdata/examples/main.yaml:14:9: every step must have its name [step-name]
	//    |
	// 14 |       - uses: actions/checkout@v4
	//    |         ^~~~~
	fmt.Println(len(errs), "lint errors found by jactionlint")
}
Output:
1 lint errors found by jactionlint

func NewLinter Âķ

func NewLinter(out io.Writer, opts *LinterOptions) (*Linter, error)

NewLinter creates a new Linter instance. The out parameter is used to output errors from Linter instance. Set io.Discard if you don't want the outputs. The opts parameter is LinterOptions instance which configures behavior of linting. Nil means the zero value, the default behavior.

func (*Linter) ExportFacts Âķ added in v2.2.0

func (l *Linter) ExportFacts(files []string, project *Project) (*Facts, error)

ExportFacts reads the workflows and actions of the files, or of the repository when there are none, and returns their facts. The files of the repository that are neither a workflow nor an action.yml (Dependabot configuration, the Actions lock file) are skipped. Nothing is checked and nothing is written. The project may be nil, and then it is found from the first file.

func (*Linter) ExternalTools Âķ added in v2.2.0

func (l *Linter) ExternalTools() map[string]ExternalToolStatus

ExternalTools says whether shellcheck, pyflakes and node ran in this run, keyed by "shellcheck", "pyflakes" and "node". It has an entry for each tool which some checked workflow or action needed, and it is nil when none did. A tool which was not found checked nothing: SkippedScripts is the number of scripts it would have checked.

func (*Linter) FixFiles Âķ

func (l *Linter) FixFiles(filepaths []string, project *Project, mode FixMode) (*FixResult, error)

FixFiles applies the automatic fixes of the errors found in the files and writes the files which changed. See FixFilesWithOptions.

func (*Linter) FixFilesWithOptions Âķ

func (l *Linter) FixFilesWithOptions(filepaths []string, project *Project, opts FixOptions) (*FixResult, error)

FixFilesWithOptions applies the automatic fixes of the errors found in the files and writes the files which changed. The project parameter can be nil. In the case, a project is detected from the file path.

Fixing happens in memory: each pass lints the text, chooses the non-conflicting fixes (see planFixes for how fixes of different rules are ordered), applies them, checks that the result is valid YAML which differs from the text before only where the edits are (see verifyFix), and lints the result again. It stops when no fix is left, so running it again changes nothing. The file is written once at the end, atomically, and not at all when the fixes are unchanged or DryRun is set.

A fix whose edits break the file is refused and its rule is not fixed in that file again; the refusal is in the Failures of the result. If the fixes never settle (the same text comes back, or MaxPasses is exceeded) the file is left as it was before the fixes which kept repeating and the failure names the rules.

Only the fixes allowed by the mode are applied: unsafe fixes need FixModeUnsafe. The errors which have no fix are never changed, so they remain. The errors which remain are printed with the output format of the linter and returned (to the log writer instead of the output with DryRun, as the output has the diff).

func (*Linter) FixRepository Âķ

func (l *Linter) FixRepository(dir string, mode FixMode) (*FixResult, error)

FixRepository fixes the files of the nearest project which LintRepository lints: the workflows and the Dependabot configuration. When the directory path is empty, the current working directory will be used instead.

func (*Linter) FixRepositoryWithOptions Âķ

func (l *Linter) FixRepositoryWithOptions(dir string, opts FixOptions) (*FixResult, error)

FixRepositoryWithOptions is like FixRepository with options.

func (*Linter) GenerateDefaultConfig Âķ

func (l *Linter) GenerateDefaultConfig(dir string) error

GenerateDefaultConfig generates default config file at ".github/jactionlint.yaml" in the project which the given directory path belongs to. When the directory path is empty, the current directory will be used instead.

func (*Linter) Lint Âķ

func (l *Linter) Lint(path string, content []byte, project *Project) ([]*Error, error)

Lint lints YAML workflow file content given as byte slice. The path parameter is used as file path where the content came from. When nil is passed to the project parameter, it tries to find the project from the path parameter.

func (*Linter) LintDir Âķ

func (l *Linter) LintDir(dir string, project *Project) ([]*Error, error)

LintDir lints all YAML workflow files in the given directory recursively.

func (*Linter) LintFile Âķ

func (l *Linter) LintFile(path string, project *Project) ([]*Error, error)

LintFile lints one YAML workflow file and outputs the errors to given writer. The project parameter can be nil. In the case, the project is detected from the given path.

func (*Linter) LintFiles Âķ

func (l *Linter) LintFiles(filepaths []string, project *Project) ([]*Error, error)

LintFiles lints YAML workflow files and outputs the errors to given writer. It applies lint rules to all given files. The project parameter can be nil. In the case, a project is detected from the file path.

func (*Linter) LintRepository Âķ

func (l *Linter) LintRepository(dir string) ([]*Error, error)

LintRepository lints the files of a repository and outputs the errors to given writer. It finds the nearest project based on `dir` and lints the YAML workflow files directly in its `.github/workflows` directory, the composite actions (action.yml files), `.github/dependabot.yml` and the Actions lock file. When the directory path is empty, the current working directory will be used instead.

func (*Linter) LintStdin Âķ

func (l *Linter) LintStdin(stdin io.Reader) ([]*Error, error)

LintStdin lints the content read from STDIN. The stdin parameter is a reader to read from STDIN, which is usually os.Stdin. The file name is determined by LinterOptions.StdinFileName. When the option is empty, "<stdin>" is the default value.

func (*Linter) MigrateConfig Âķ

func (l *Linter) MigrateConfig(dir string) error

MigrateConfig rewrites the deprecated keys of the config file into the "rules" mapping and prints what changed. The file is ConfigFile of the options when given, otherwise the config file of the project which the directory belongs to. When the directory is empty, the current directory is used.

func (*Linter) MigrateIgnores Âķ

func (l *Linter) MigrateIgnores(paths []string) error

MigrateIgnores runs MigrateZizmorIgnoreFiles on the given files, or on the workflow files and the root action.yml of the project when none is given, and reports what changed and which comments were skipped.

func (*Linter) OnlineCoverage Âķ added in v2.1.0

func (l *Linter) OnlineCoverage() *OnlineCoverage

OnlineCoverage returns the coverage of the online checks, or nil when they were not turned on.

func (*Linter) OnlineFailed Âķ

func (l *Linter) OnlineFailed() bool

OnlineFailed reports whether the run was asked to fail (the "strict" online mode) and a lookup was skipped, so that a check which could not run does not pass silently.

func (*Linter) OnlineSkipped Âķ

func (l *Linter) OnlineSkipped() int

OnlineSkipped returns how many GitHub lookups of the online checks were skipped because they failed (rate limit, 404, 403, server error, timeout, no network, nothing cached in the offline mode). The checks which needed them report nothing for those actions. Lookups left out by the allow and deny lists are not counted. It is zero when the online checks did not run.

func (*Linter) SuggestTimeouts Âķ added in v2.2.0

func (l *Linter) SuggestTimeouts(files []string, project *Project, opts TimeoutOptions) (*TimeoutReport, error)

SuggestTimeouts reads the durations of the jobs of the recent successful runs of the workflows and returns the report. The files are workflow files, or the workflows of the repository when there are none. It needs the online checks (LinterOptions.Online): the report is made of what GitHub says. It writes nothing.

func (*Linter) Update Âķ added in v2.6.0

func (l *Linter) Update(paths []string, uo UpdateOptions) (*UpdateResult, error)

Update checks the external actions and reusable workflows of the files (the repository when there are none), reports the updates and, with UpdateApply, writes them. The online checks must be on: the releases come from GitHub.

func (*Linter) WriteBaseline Âķ

func (l *Linter) WriteBaseline(files []string, path string) (*WriteBaselineResult, error)

WriteBaseline records the current findings as the baseline. Without files it lints the whole repository like LintRepository and replaces the baseline. With files it lints only them: the entries of those files are replaced and the entries of the other files that still exist are kept. The baseline is written to path, or to .github/jactionlint-baseline.json in the repository when path is empty. The file is sorted and does not contain line numbers, so writing it again without a change in the findings gives the same bytes. Findings are recorded as they are reported: after the ignores and the minimum severity.

type LinterOptions Âķ

type LinterOptions struct {
	// Verbose is flag if verbose log output is enabled.
	Verbose bool
	// Debug is flag if debug log output is enabled.
	Debug bool
	// LogWriter is io.Writer object to use to print log outputs. Note that error outputs detected
	// by the linter are not included in the log outputs.
	LogWriter io.Writer
	// Color is option for colorizing error outputs. See ColorOptionKind document for each enum values.
	Color ColorOptionKind
	// Oneline is flag if one line output is enabled. When enabling it, one error is output per one
	// line. It is useful when reading outputs from programs. It is the same as setting Format to
	// "oneline" and it only affects the text format.
	Oneline bool
	// ShowRuleIDs is accepted for compatibility. The text format always shows the stable rule ID such as
	// "unpinned-uses" at the end of each error, since that is what the configuration, the ignore
	// comments and ignore patterns accept; the kind such as "action" is shared by several rules.
	ShowRuleIDs bool
	// Shellcheck is executable for running shellcheck external command. It can be command name like
	// "shellcheck" or file path like "/path/to/shellcheck", "path/to/shellcheck". When this value
	// is empty, shellcheck won't run to check scripts in workflow file.
	Shellcheck string
	// Pyflakes is executable for running pyflakes external command. It can be command name like "pyflakes"
	// or file path like "/path/to/pyflakes", "path/to/pyflakes". When this value is empty, pyflakes
	// won't run to check scripts in workflow file.
	Pyflakes string
	// Select makes the run report only the findings of these rule IDs (the option --select). A selected rule which
	// the profile or the configuration turns off is turned on at its default level; the other rules report
	// nothing. An unknown ID is an error from NewLinter. The empty list selects nothing: every rule follows the
	// configuration.
	Select []string
	// NoIgnores makes the run apply none of the ways to accept a finding which the repository carries: the inline
	// ignore comments (also those of zizmor), the "ignores" and "paths" ignores of the config file and the
	// baseline (the option --no-ignores). The IgnorePatterns of the command line still apply. It is for audits and
	// for finding what the ignores hide.
	NoIgnores bool
	// ShellcheckRequired and PyflakesRequired say that the command was asked for explicitly (the command line
	// option --shellcheck or --pyflakes was given). NewLinter then fails when the command cannot be found or is
	// not executable, instead of running without it. A command which is not required and is missing is only
	// noted in the log (see RunHints) and in the SARIF log: its scripts are not checked.
	ShellcheckRequired bool
	PyflakesRequired   bool
	// ShellcheckRCFile is a shellcheckrc file for shellcheck to read instead of --norc (the option
	// --shellcheck-rcfile). A relative path is resolved from the working directory. It wins over the
	// "shellcheck.rcfile" key of the configuration. The file must exist: the run fails when it does not.
	ShellcheckRCFile string
	// ShowDocURLs prints the URL of the documentation of the rule under each finding of the text format (not
	// with Oneline) and in the message of the github format (the option --show-doc-urls). The json and sarif
	// formats have it anyway.
	ShowDocURLs bool
	// ShowFixStatus prints what the fix of each finding is under it in the text format (not with Oneline) and in the
	// message of the github format (the option --show-fix-status): the fix that --fix or --fix=unsafe applies, or the
	// reason why a finding which the rule can fix has none (Error.NoFix). A finding that is advice only has no line. The
	// json and sarif formats have the same data as fix, no_fix and noFixCode anyway.
	ShowFixStatus bool
	// Ruff is the command or the path of ruff (the option --ruff). When it is not empty ruff checks the Python
	// scripts of "run:" instead of Pyflakes, with the rules of pyflakes (F) and without the configuration of
	// the working directory. NewLinter fails when the command cannot be found.
	Ruff string
	// FindingContext adds the events of the workflow and the permissions of the token of the job to each finding
	// (Error.Events and Error.Permissions), which the json, jsonl and sarif formats print (the option
	// --finding-context).
	FindingContext bool
	// ChangedSince reports only the findings on what changed since the revision (the option --changed-since): the lines
	// that differ from the merge base of the revision and HEAD, in the commits, the index and the working tree, and every
	// line of a file that is not tracked. The checks run over every file as always, so the findings that depend on a
	// caller or another file are the ones of a full run; only what is shown is filtered. A revision that is not known
	// fails the run.
	ChangedSince string
	// ChangedScope is how much of a changed file ChangedSince shows: "lines" (the default) or "files" (every finding of
	// a changed file).
	ChangedScope ChangedScope
	// IgnorePatterns is list of regular expression to filter errors. The pattern is applied to error
	// messages. When an error is matched, the error is ignored.
	IgnorePatterns []string
	// ConfigFile is a path to config file. Empty string means no config file path is given. In
	// the case, jactionlint will try to read config from the repository's .github/jactionlint.yaml,
	// then from $XDG_CONFIG_HOME/jactionlint/jactionlint.yaml ($HOME/.config when unset).
	ConfigFile string
	// Config is a configuration to use instead of reading one from a file or the repository. It is for
	// callers which have no file system (the playground) or want fixed rules. ConfigFile takes precedence
	// when both are set.
	Config *Config
	// Format selects the output format. It is one of "text" (the default when empty), "oneline", "json",
	// "jsonl", "sarif", "gcc" and "github", or a custom template to format error messages. A template
	// must follow Go Template format and contain at least one {{ }} placeholder. When the format is
	// not a native one, it is regarded as a template. https://pkg.go.dev/text/template
	Format string
	// StdinFileName is a file name when reading input from stdin. When this value is empty, "<stdin>"
	// is used as the default value.
	StdinFileName string
	// WorkingDir is a file path to the current working directory. When this value is empty, os.Getwd
	// will be used to get a working directory.
	WorkingDir string
	// MinSeverity hides the errors less severe than it. The zero value shows every error. For example
	// SeverityWarning hides the errors of info level.
	MinSeverity Severity
	// Online turns on the rules which query the GitHub API (the ones which Rules marks as Online, such as
	// impostor-commit and known-vulnerable-actions, and the pinning fix of unpinned-uses, see Error.Fix).
	// Nothing reaches the network while the online checks are off. They are off unless this is true, the
	// configuration sets "online: true", or OnlineOptions.Mode (or the "mode" of "online-options") is
	// "cache" or "strict". A mode in the configuration does not turn them on when it also says
	// "online: false"; OnlineOptions.Mode of the options does. The token is
	// read from $GITHUB_TOKEN or $GH_TOKEN; without one the API allows very few requests. When the
	// API cannot be used (rate limit, no network) the online rules stop with one warning. It
	// is an error in builds without network access such as the WebAssembly one, unless
	// GitHubClient is set. The "online" key of the configuration file turns it on for the files it
	// applies to.
	Online bool
	// Profile selects the profile (ProfileCorrectness, ProfileDefault or ProfilePedantic) for every file,
	// whatever the configuration says: it is what --profile asks for. The empty value leaves the choice to
	// the configuration.
	Profile Profile
	// OnlineOff turns the online checks off although the configuration file turns them on: it is what
	// --no-online asks for. It wins over Online and over the configuration.
	OnlineOff bool
	// GitHubClient replaces the built-in client of the GitHub API, which sends REST requests and caches
	// the answers in $XDG_CACHE_HOME/jactionlint. It is used by tests (see NewFixtureGitHubClient)
	// and implies nothing by itself: the online rules need Online or the "online" configuration.
	GitHubClient GitHubClient
	// OnlineCacheTTL is how long the built-in client uses a cached answer without asking GitHub
	// whether it changed. Zero means one hour. A negative value revalidates every answer (which
	// costs no rate limit when nothing changed).
	OnlineCacheTTL time.Duration
	// OnlineOptions tunes the online checks (mode, API URL, token source, allow and deny lists, cache,
	// retries). It wins over the "online-options" of the configuration file. A Mode other than the
	// default turns the online checks on. See OnlineOptions.
	OnlineOptions OnlineOptions
	// Context stops the online lookups when it is canceled, for example on interruption. Nil means
	// context.Background.
	Context context.Context
	// Now returns the current time. It is used to decide whether an entry of "ignores" in the config
	// file has expired. Nil means time.Now. It is for tests.
	Now func() time.Time
	// OnRulesCreated is a hook to add or remove the check rules. This function is called on checking
	// every workflow files. Rules created by Linter instance are passed to the argument and the
	// function should return the modified rules.
	// Note that syntax errors may be reported even if this function returns nil or an empty slice.
	OnRulesCreated func([]Rule) []Rule
	// OnDependabotRulesCreated is like OnRulesCreated but for the rules which check Dependabot
	// configuration files (.github/dependabot.yml).
	OnDependabotRulesCreated func([]DependabotRule) []DependabotRule
	// Baseline applies the baseline file (BaselineFile, or .github/jactionlint-baseline.json in the
	// repository when empty) even if the configuration does not ask for it: the findings it accepts
	// are not returned or printed. The file must exist.
	Baseline bool
	// BaselineFile is the path of the baseline file to apply with Baseline. A relative path is relative
	// to the working directory.
	BaselineFile string
	// NoBaseline ignores the baseline even if the configuration asks for it.
	NoBaseline bool
	// BaselineCheck reports the baseline entries which match no finding as unused-baseline-entry. It
	// implies Baseline unless the configuration selects a baseline.
	BaselineCheck bool
	// SARIFHideBaselined leaves the findings which the baseline accepts out of the SARIF log. By default
	// they are in it as results with a suppression of the kind "external".
	SARIFHideBaselined bool
	// RunHints lets a run of the text format that finds many findings print one line to LogWriter about how
	// to count them, adopt them gradually and get the checks of actionlint only. It is printed only when
	// LogWriter is a terminal or the process runs in CI, and never with another format. The jactionlint
	// command sets it unless --no-hints or JACTIONLINT_NO_HINTS is given.
	RunHints bool
}

LinterOptions is set of options for Linter instance. This struct is used for NewLinter factory function call. The zero value LinterOptions{} represents the default behavior.

type LocalActionsCache Âķ

type LocalActionsCache struct {
	// contains filtered or unexported fields
}

LocalActionsCache is cache for local actions' metadata. It avoids repeating to find/read/parse local action's metadata file (action.yml). This cache is not available across multiple repositories. One LocalActionsCache instance needs to be created per one repository.

func NewLocalActionsCache Âķ

func NewLocalActionsCache(proj *Project, dbg io.Writer) *LocalActionsCache

NewLocalActionsCache creates new LocalActionsCache instance for the given project.

func (*LocalActionsCache) FindMetadata Âķ

func (c *LocalActionsCache) FindMetadata(spec string) (*ActionMetadata, bool, error)

FindMetadata finds metadata for given spec. The spec should indicate for local action hence it should start with "./" or with the self-repository prefix "$/". The first return value can be nil even if error did not occur. LocalActionCache caches that the action was not found. At first search, it returns an error that the action was not found. But at the second search, it does not return an error even if the result is nil. This behavior prevents repeating to report the same error from multiple places. Calling this method is thread-safe.

func (*LocalActionsCache) Lookup Âķ

func (c *LocalActionsCache) Lookup(spec string) (*ActionMetadata, error)

Lookup is like FindMetadata but it returns the error every time the metadata is invalid instead of only at the first search. The rules use it so that every use of a broken action reports the same finding; which use is searched first depends on the order in which the files are linted, and the linter keeps the first finding in the order of the files. The second return value is nil when the action is not found.

type LocalActionsCacheFactory Âķ

type LocalActionsCacheFactory struct {
	// contains filtered or unexported fields
}

LocalActionsCacheFactory is a factory to create LocalActionsCache instances. LocalActionsCache should be created for each repositories. LocalActionsCacheFactory creates new LocalActionsCache instance per repository (project).

func NewLocalActionsCacheFactory Âķ

func NewLocalActionsCacheFactory(dbg io.Writer) *LocalActionsCacheFactory

NewLocalActionsCacheFactory creates a new LocalActionsCacheFactory instance.

func (*LocalActionsCacheFactory) GetCache Âķ

GetCache returns LocalActionsCache instance for the given project. One LocalActionsCache is created per one repository. Created instances are cached and will be used when caches are requested for the same projects. This method is not thread safe.

type LocalReusableWorkflowCache Âķ

type LocalReusableWorkflowCache struct {
	// contains filtered or unexported fields
}

LocalReusableWorkflowCache is a cache for local reusable workflow metadata files. It avoids find/read/parse local reusable workflow YAML files. This cache is dedicated for a single project (repository) indicated by 'proj' field. One LocalReusableWorkflowCache instance needs to be created per one project.

func NewLocalReusableWorkflowCache Âķ

func NewLocalReusableWorkflowCache(proj *Project, cwd string, dbg io.Writer) *LocalReusableWorkflowCache

NewLocalReusableWorkflowCache creates a new LocalReusableWorkflowCache instance for the given project. 'cwd' is a current working directory as an absolute file path. The 'Local' means that the cache instance is project-local. It is not available across multiple projects.

func (*LocalReusableWorkflowCache) FindMetadata Âķ

FindMetadata finds/parses a reusable workflow metadata located by the 'spec' argument. When project is not set to 'proj' field or the spec is not a local reference, this method immediately returns with nil.

An invalid workflow returns its error at every search. The linter keeps only the first of the findings which describe a workflow and not the call of it (see sharedFindings), so the finding is in the first file of the run which calls the workflow, whichever goroutine searched first.

Calling this method is thread-safe.

func (*LocalReusableWorkflowCache) WriteWorkflowCallEvent Âķ

func (c *LocalReusableWorkflowCache) WriteWorkflowCallEvent(wpath string, event *WorkflowCallEvent)

WriteWorkflowCallEvent writes reusable workflow metadata by converting from WorkflowCallEvent AST node. The 'wpath' parameter is a path to the workflow file of the AST, which is a relative to the project root directory or an absolute path. This method does nothing when (1) no project is set, (2) it could not convert the workflow path to workflow call spec, (3) some cache for the workflow is already existing. This method is thread safe.

func (*LocalReusableWorkflowCache) WriteWorkflowCallEventFromWorkflow Âķ

func (c *LocalReusableWorkflowCache) WriteWorkflowCallEventFromWorkflow(wpath string, event *WorkflowCallEvent, w *Workflow)

WriteWorkflowCallEventFromWorkflow is like WriteWorkflowCallEvent but additionally records each job's effective `permissions:` requirement from the full Workflow AST. Passing a non-nil 'w' enables caller/callee permission checks downstream. Same do-nothing conditions and thread-safety guarantees as WriteWorkflowCallEvent apply.

type LocalReusableWorkflowCacheFactory Âķ

type LocalReusableWorkflowCacheFactory struct {
	// contains filtered or unexported fields
}

LocalReusableWorkflowCacheFactory is a factory object to create a LocalReusableWorkflowCache instance per project.

func NewLocalReusableWorkflowCacheFactory Âķ

func NewLocalReusableWorkflowCacheFactory(cwd string, dbg io.Writer) *LocalReusableWorkflowCacheFactory

NewLocalReusableWorkflowCacheFactory creates a new LocalReusableWorkflowCacheFactory instance.

func (*LocalReusableWorkflowCacheFactory) GetCache Âķ

GetCache returns a new or existing LocalReusableWorkflowCache instance per project. When a instance was already created for the project, this method returns the existing instance. Otherwise it creates a new instance and returns it.

type Location Âķ added in v2.2.0

type Location struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

Location is a position in a file: 1-based, the column counted in Unicode code points.

type LogLevel Âķ

type LogLevel int

LogLevel is log level of logger used in Linter instance.

type LogicalOpNode Âķ

type LogicalOpNode struct {
	// Kind is a kind to show which operator is used.
	Kind LogicalOpNodeKind
	// Left is an expression for left hand side of the binary operator.
	Left ExprNode
	// Right is an expression for right hand side of the binary operator.
	Right ExprNode
}

LogicalOpNode is node for logical binary operators; && or ||.

func (*LogicalOpNode) Token Âķ

func (n *LogicalOpNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type LogicalOpNodeKind Âķ

type LogicalOpNodeKind int

LogicalOpNodeKind is a kind of logical operators; && and ||.

const (
	// LogicalOpNodeKindInvalid is an invalid and initial value of LogicalOpNodeKind.
	LogicalOpNodeKindInvalid LogicalOpNodeKind = iota
	// LogicalOpNodeKindAnd is a kind for && operator.
	LogicalOpNodeKindAnd
	// LogicalOpNodeKindOr is a kind for || operator.
	LogicalOpNodeKindOr
)

func (LogicalOpNodeKind) String Âķ

func (k LogicalOpNodeKind) String() string

type Matrix Âķ

type Matrix struct {
	// Values stores mappings from name to values. Keys are in lower case since they are case-insensitive.
	Rows map[string]*MatrixRow
	// Include is list of combinations of matrix values and additional values on running matrix combinations.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#example-including-additional-values-into-combinations
	Include *MatrixCombinations
	// Exclude is list of combinations of matrix values which should not be run. Combinations in
	// this list will be removed from combinations of matrix to run.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#example-excluding-configurations-from-a-matrix
	Exclude *MatrixCombinations
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Matrix is matrix variations configuration of a job. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix

type MatrixAssign Âķ

type MatrixAssign struct {
	// Key is a name of the matrix value.
	Key *String
	// Value is the value selected from values in row.
	Value RawYAMLValue
}

MatrixAssign represents which value should be taken in the row of the matrix. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix

type MatrixCombination Âķ

type MatrixCombination struct {
	Assigns map[string]*MatrixAssign
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
}

MatrixCombination is combination of matrix value assignments to define one of matrix variations. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix

type MatrixCombinations Âķ

type MatrixCombinations struct {
	Combinations []*MatrixCombination
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
}

MatrixCombinations is list of combinations of matrix assignments used for 'include' and 'exclude' sections. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix

func (*MatrixCombinations) ContainsExpression Âķ

func (cs *MatrixCombinations) ContainsExpression() bool

ContainsExpression returns if the combinations section includes at least one expression node.

type MatrixRow Âķ

type MatrixRow struct {
	// Name is a name of matrix value.
	Name *String
	// Values is variations of values which the matrix value can take.
	Values []RawYAMLValue
	// Expression is a string when expression syntax ${{ }} is used for this section.
	Expression *String
}

MatrixRow is one row of matrix. One matrix row can take multiple values. Those variations are stored as row of values in this struct. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix

type NoFix Âķ added in v2.1.0

type NoFix struct {
	// Code is the machine-readable reason.
	Code NoFixCode `json:"code"`
	// Reason is the human-readable explanation, e.g. "set the missing-timeout option default-minutes to enable the fix".
	Reason string `json:"reason"`
	// Option is the rule option to configure as "rule-id.option" when Code is option-required or option-invalid.
	Option string `json:"option,omitempty"`
}

NoFix explains why a finding has no Fix. It is part of the JSON of the template fields and the SARIF log (the text output stays one line per finding, as tools which parse it expect), and never changes what --fix does.

type NoFixCode Âķ added in v2.1.0

type NoFixCode string

NoFixCode is the machine-readable reason why a finding which the rule could fix has no fix.

const (
	// NoFixOptionRequired means a rule option must be configured first. NoFix.Option names it. The fixers
	// never invent a value such as a number of minutes or days.
	NoFixOptionRequired NoFixCode = "option-required"
	// NoFixOptionInvalid means the option is configured with a value the fix cannot use.
	NoFixOptionInvalid NoFixCode = "option-invalid"
	// NoFixOnlineRequired means the fix needs a lookup on GitHub and the online checks are off.
	NoFixOnlineRequired NoFixCode = "online-required"
	// NoFixLookupFailed means the online checks are on but the lookup failed, so what the fix needs is unknown.
	NoFixLookupFailed NoFixCode = "lookup-failed"
	// NoFixUnsupportedShape means the fix cannot edit the source the way it is written.
	NoFixUnsupportedShape NoFixCode = "unsupported-shape"
	// NoFixNeedsJudgment means the right change depends on a decision of a person, or an automatic change
	// would not be safe.
	NoFixNeedsJudgment NoFixCode = "needs-judgment"
	// NoFixUnsafeEdit means a fix exists but may change the behavior of the workflow. The SARIF log (which has
	// no unsafe fixes) says so with this code; the JSON has the fix itself, marked unsafe.
	NoFixUnsafeEdit NoFixCode = "unsafe-edit"
	// NoFixEditConflict means a fix exists but its edit overlaps the fix of another finding of the same SARIF log.
	NoFixEditConflict NoFixCode = "edit-conflict"
	// NoFixInvalidEdit means a fix is attached (by a custom rule, say) but its edits do not fit the source, so no
	// tool can apply it.
	NoFixInvalidEdit NoFixCode = "invalid-edit"
)

type NotOpNode Âķ

type NotOpNode struct {
	// Operand is an expression at operand of ! operator.
	Operand ExprNode
	// contains filtered or unexported fields
}

NotOpNode is node for unary ! operator.

func (*NotOpNode) Token Âķ

func (n *NotOpNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type NullNode Âķ

type NullNode struct {
	// contains filtered or unexported fields
}

NullNode is node for null literal.

func (*NullNode) Token Âķ

func (n *NullNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type NullType Âķ

type NullType struct{}

NullType is type for null value.

func (NullType) Assignable Âķ

func (ty NullType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type.

func (NullType) DeepCopy Âķ

func (ty NullType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (NullType) Merge Âķ

func (ty NullType) Merge(other ExprType) ExprType

Merge merges other type into this type. When other type conflicts with this type, the merged result is any type as fallback.

func (NullType) String Âķ

func (ty NullType) String() string

type NumberFact Âķ added in v2.2.0

type NumberFact struct {
	// Value is the number. It is 0 when Dynamic is true.
	Value    float64   `json:"value"`
	Dynamic  bool      `json:"dynamic,omitempty"`
	Expr     string    `json:"expression,omitempty"`
	Location *Location `json:"location,omitempty"`
}

NumberFact is a number of the file, or an expression (Dynamic) that decides it.

type NumberType Âķ

type NumberType struct{}

NumberType is type for number values such as integer or float.

func (NumberType) Assignable Âķ

func (ty NumberType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type.

func (NumberType) DeepCopy Âķ

func (ty NumberType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (NumberType) Merge Âķ

func (ty NumberType) Merge(other ExprType) ExprType

Merge merges other type into this type. When other type conflicts with this type, the merged result is any type as fallback.

func (NumberType) String Âķ

func (ty NumberType) String() string

type ObjectDerefNode Âķ

type ObjectDerefNode struct {
	// Receiver is an expression at receiver of property dereference.
	Receiver ExprNode
	// Property is a name of property to access.
	Property string
}

ObjectDerefNode represents property dereference of object like 'foo.bar'.

func (ObjectDerefNode) Token Âķ

func (n ObjectDerefNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type ObjectType Âķ

type ObjectType struct {
	// Props is map from properties name to their type.
	Props map[string]ExprType
	// Mapped is an element type of this object. This means all props have the type. For example,
	// The element type of env context is string.
	// AnyType means its property types can be any type so it shapes a loose object. Setting nil
	// means properties are mapped to no type so it shapes a strict object.
	//
	// Invariant: All types in Props field must be assignable to this type.
	Mapped ExprType
}

ObjectType is type for objects, which can hold key-values.

func NewEmptyObjectType Âķ

func NewEmptyObjectType() *ObjectType

NewEmptyObjectType creates new loose ObjectType instance which allows unknown props. When accessing to unknown props, their values will fall back to any.

func NewEmptyStrictObjectType Âķ

func NewEmptyStrictObjectType() *ObjectType

NewEmptyStrictObjectType creates new ObjectType instance which does not allow unknown props.

func NewMapObjectType Âķ

func NewMapObjectType(t ExprType) *ObjectType

NewMapObjectType creates new ObjectType which maps keys to a specific type value.

func NewObjectType Âķ

func NewObjectType(props map[string]ExprType) *ObjectType

NewObjectType creates new loose ObjectType instance which allows unknown props with given props.

func NewStrictObjectType Âķ

func NewStrictObjectType(props map[string]ExprType) *ObjectType

NewStrictObjectType creates new ObjectType instance which does not allow unknown props with given prop types.

func (*ObjectType) Assignable Âķ

func (ty *ObjectType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type. In other words, rhs type is more strict than lhs (receiver) type.

func (*ObjectType) DeepCopy Âķ

func (ty *ObjectType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (*ObjectType) IsLoose Âķ

func (ty *ObjectType) IsLoose() bool

IsLoose returns if the type is a loose object, which allows any unknown props.

func (*ObjectType) IsStrict Âķ

func (ty *ObjectType) IsStrict() bool

IsStrict returns if the type is a strict object, which means no unknown prop is allowed.

func (*ObjectType) Loose Âķ

func (ty *ObjectType) Loose()

Loose sets the object is loose, which means any properties can be set.

func (*ObjectType) Merge Âķ

func (ty *ObjectType) Merge(other ExprType) ExprType

Merge merges two object types into one. When other object has unknown props, they are merged into current object. When both have same property, when they are assignable, it remains as-is. Otherwise, the property falls back to any type.

func (*ObjectType) Strict Âķ

func (ty *ObjectType) Strict()

Strict sets the object is strict, which means only known properties are allowed.

func (*ObjectType) String Âķ

func (ty *ObjectType) String() string

type OnlineAnswers Âķ added in v2.2.0

type OnlineAnswers struct {
	// Network is the number of answers GitHub gave in this run, including a conditional request (304) that
	// confirmed a cached answer.
	Network int `json:"network"`
	// Cache is the number of answers read from the disk cache without asking GitHub: younger than
	// CacheTTLSeconds, or of any age in the cache mode.
	Cache int `json:"cache"`
	// Stale is the number of expired cached answers used because the rate limit left no other.
	Stale int `json:"stale"`
	// Immutable is the number of cached answers older than the TTL which were used without asking because they are
	// about a file at a full commit SHA, which cannot change. They are not in Cache and do not set
	// OldestFetched: the age limit of Cache does not apply to them. It is omitted when there were none.
	Immutable int `json:"immutable,omitempty"`
	// OldestFetched is the oldest time at which a cached answer that was used (Cache and Stale) was received.
	// The timestamp source is the clock of the machine running jactionlint at the moment it last received the
	// answer from GitHub, or confirmed it with a 304. It is not a date from GitHub and says nothing about when
	// the repository, tag or branch last changed: an old commit does not prove that a tag was not repointed
	// recently. RFC 3339, UTC. It is omitted when no cached answer was used.
	OldestFetched string `json:"oldestFetched,omitempty"`
	// CacheTTLSeconds is how long a cached answer is used without asking again, so a Cache answer is at most
	// this old. It is the TTL rounded up to whole seconds, so it is never tighter than the TTL in force. It is omitted in the cache mode, which has no age limit, and with a TTL of zero.
	CacheTTLSeconds int `json:"cacheTtlSeconds,omitempty"`
}

OnlineAnswers counts the answers the online checks used, by where they came from, and bounds how old the cached ones are. It is evidence about the run, not a guarantee about GitHub: an answer says what GitHub said when it was asked, and a ref that resolved to a commit may be moved later.

type OnlineCoverage Âķ added in v2.1.0

type OnlineCoverage struct {
	// Status is "complete" (every lookup the checks made was answered, apart from the excluded
	// repositories) or "incomplete" (SkippedLookups is not zero). The struct is absent when the online
	// checks were not turned on.
	Status string `json:"status"`
	// Mode is "online" (the network was used), "cache" (only the disk cache was used) and
	// "strict" or "cache,strict" for the modes which fail the run on a skipped lookup.
	Mode string `json:"mode,omitempty"`
	// SkippedLookups counts the lookups which failed (see OnlineSkipped). The checks which needed them
	// reported nothing for those actions.
	SkippedLookups int `json:"skippedLookups"`
	// ExcludedRepositories counts the repositories which the allow and deny lists left out. They were
	// not checked, on purpose.
	ExcludedRepositories int `json:"excludedRepositories"`
	// Evidence says where the answers came from. "cache" means that they may be older than the cache
	// TTL of the run allows to tell: the cache has no freshness guarantee in this mode.
	Evidence string `json:"evidence,omitempty"`
	// SkippedBy counts the skipped lookups by the kind of failure ("rate limit", "unauthorized", "forbidden", "not found",
	// "server error", "timeout", "network", "not cached" or "other"). It is omitted when nothing was skipped.
	SkippedBy map[string]int `json:"skippedBy,omitempty"`
	// Answers says where the answers which the checks used came from. It is omitted when the client does not
	// track them (a custom GitHubClient), which means unknown, not "all fresh".
	Answers *OnlineAnswers `json:"answers,omitempty"`
}

OnlineCoverage says how complete the online checks of a run were, so that a consumer can tell "checked and nothing found" from "not checked". It is evidence about the run, not a trust guarantee: a resolved ref or a timestamp says what GitHub (or the cache) answered, not that the ref was never repointed.

type OnlineMode Âķ

type OnlineMode string

OnlineMode selects how the online checks use the network.

const (
	// OnlineModeDefault asks GitHub for what the checks need. A lookup which fails is skipped with one
	// warning per kind of failure, and the exit status does not change.
	OnlineModeDefault OnlineMode = ""
	// OnlineModeCache never uses the network. Only the answers already in the disk cache are used,
	// whatever their age. A lookup with no cached answer is skipped.
	OnlineModeCache OnlineMode = "cache"
	// OnlineModeStrict is like the default mode but a skipped lookup makes the exit status 3: use it
	// where a check that could not run must not pass silently.
	OnlineModeStrict OnlineMode = "strict"
)
const OnlineModeCacheStrict OnlineMode = "cache,strict"

OnlineModeCacheStrict is OnlineModeCache that also fails when a lookup has no cached answer.

func ParseOnlineMode Âķ

func ParseOnlineMode(s string) (OnlineMode, error)

ParseOnlineMode parses the value of --online and of "online-options.mode": "true" (or "on", or empty), "cache", "strict", or "cache,strict" for both. Order does not matter.

func (OnlineMode) Offline Âķ

func (m OnlineMode) Offline() bool

Offline reports whether the mode never uses the network.

func (OnlineMode) Strict Âķ

func (m OnlineMode) Strict() bool

Strict reports whether a skipped lookup fails the run.

type OnlineOptions Âķ

type OnlineOptions struct {
	// Mode selects how the network is used. See OnlineMode. Setting it to "cache" or "strict" in the
	// configuration also turns the online checks on.
	Mode OnlineMode `yaml:"mode"`
	// ModeSet says that Mode was chosen explicitly, also when it is the default mode: a bare --online
	// then replaces the "cache" or "strict" mode of a configuration file instead of leaving it in force.
	ModeSet bool `yaml:"-"`
	// APIURL is the URL of the REST API of a GitHub Enterprise Server such as
	// "https://ghe.example.com/api/v3". The default is $GITHUB_API_URL, else derived from
	// $GITHUB_SERVER_URL or $GH_HOST, else https://api.github.com.
	//
	// A token is sent only to hosts which the user chose: github.com, a host named by the
	// environment, or a host set by --online-api-url, the user-global config file or --config-file. An
	// APIURL in the config file of a repository gets no token, because a pull request could
	// otherwise send your token to any server.
	APIURL string `yaml:"api-url"`
	// TokenEnv names the environment variable which holds the token. It is read before $GITHUB_TOKEN
	// and $GH_TOKEN.
	TokenEnv string `yaml:"token-env"`
	// TokenFile is a file which holds the token (surrounding white space is ignored). It is read
	// before $GITHUB_TOKEN and $GH_TOKEN, after TokenEnv.
	TokenFile string `yaml:"token-file"`
	// Allow limits the lookups to the repositories matching one of the patterns "owner/repo". "*"
	// matches within a part ("owner/*", "*/setup-*"). Case does not matter. Empty allows all.
	Allow []string `yaml:"allow"`
	// Deny skips the lookups for the repositories matching one of the patterns, for private or
	// internal actions GitHub cannot answer for. It wins over Allow.
	Deny []string `yaml:"deny"`
	// CacheTTL is how long a cached answer is used without asking GitHub whether it changed. Zero
	// revalidates every answer (which costs no rate limit when nothing changed). Nil means one hour.
	CacheTTL *time.Duration `yaml:"cache-ttl"`
	// MaxRateLimitWait is the longest the checks wait for a rate limit to reset. A limit which resets
	// later skips the lookups, with a message naming the time. Zero never waits. Nil means 30 seconds.
	MaxRateLimitWait *time.Duration `yaml:"max-rate-limit-wait"`
	// Retries is how often a request is repeated after a server error or a secondary rate limit,
	// with exponential backoff and jitter. Nil means 2.
	Retries *int `yaml:"retries"`
	// Concurrency is how many requests are in flight at most. Zero means 6.
	Concurrency int `yaml:"concurrency"`
	// GitHubCLI is whether "gh auth token" is asked for a token when no variable or file has one.
	// Nil means true.
	GitHubCLI *bool `yaml:"gh-cli"`
	// GitHubComFallback makes the lookups of a GitHub Enterprise Server (or GHE.com) go to api.github.com for the
	// repositories which the Server does not have, which is where the actions come from that GitHub Connect syncs.
	// Nil or false asks the Server only. It has no effect when the API is api.github.com. The names of the
	// repositories which the Server does not have are sent to github.com, so list the internal ones in Deny.
	GitHubComFallback *bool `yaml:"github-com-fallback"`
	// GitHubComTokenEnv names the environment variable which holds the token for api.github.com in the fallback. It
	// is read before $GITHUB_COM_TOKEN. The token for the Server is never sent to github.com: $GITHUB_TOKEN and
	// $GH_TOKEN are not used for it.
	GitHubComTokenEnv string `yaml:"github-com-token-env"`
	// GitHubComTokenFile is a file which holds the token for api.github.com in the fallback, read after
	// GitHubComTokenEnv and before $GITHUB_COM_TOKEN.
	GitHubComTokenFile string `yaml:"github-com-token-file"`
}

OnlineOptions tunes how the online checks reach GitHub. The zero value of every field means "use the default". The same options are read from the "online-options" key of the configuration file; the values of LinterOptions.OnlineOptions win over it.

type OnlineReport Âķ added in v2.2.0

type OnlineReport struct {
	// Version is the version of this document. It changes only when a field changes meaning.
	Version int `json:"version"`
	OnlineCoverage
}

OnlineReport is the document of --online-report: the coverage of the online checks of the run, in a file so that --format json (a bare array) and jsonl (one finding a line) keep their shape. Status is "disabled" when the online checks were off, which is told apart from "complete" (checked, nothing missing).

type Output Âķ

type Output struct {
	// Name is name of output.
	Name *String
	// Value is value of output.
	Value *String
}

Output is output entry of the job. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idoutputs

type Pass Âķ

type Pass interface {
	// VisitStep is callback when visiting Step node. It returns internal error when it cannot continue the process
	VisitStep(node *Step) error
	// VisitJobPre is callback when visiting Job node before visiting its children. It returns internal error when it cannot continue the process
	VisitJobPre(node *Job) error
	// VisitJobPost is callback when visiting Job node after visiting its children. It returns internal error when it cannot continue the process
	VisitJobPost(node *Job) error
	// VisitWorkflowPre is callback when visiting Workflow node before visiting its children. It returns internal error when it cannot continue the process
	VisitWorkflowPre(node *Workflow) error
	// VisitWorkflowPost is callback when visiting Workflow node after visiting its children. It returns internal error when it cannot continue the process
	VisitWorkflowPost(node *Workflow) error
}

Pass is an interface to traverse a workflow syntax tree

type PathConfig Âķ

type PathConfig struct {
	// Ignore is a list of patterns. They are used for ignoring errors by matching to the error messages.
	// It is similar to the "--ignore" command line option.
	Ignore IgnorePatterns `yaml:"ignore"`
}

PathConfig is a configuration for specific file path pattern. This is for values of the "paths" mapping in the configuration file.

type PermissionFacts Âķ added in v2.2.0

type PermissionFacts struct {
	// Declared is false when the file has no "permissions:" at this level.
	Declared bool `json:"declared"`
	// Scopes maps a scope to "read", "write" or "none", or to "unknown" when an expression decides it or the value is
	// not one that GitHub accepts (jactionlint reports it as invalid-permissions). The scope "*"
	// is read-all or write-all, and "none" for an empty mapping.
	Scopes   map[string]string `json:"scopes,omitempty"`
	Location *Location         `json:"location,omitempty"`
}

PermissionFacts are the permissions a file declares for the token.

type PermissionScope Âķ

type PermissionScope struct {
	// Name is name of the scope.
	Name *String
	// Value is permission value of the scope.
	Value *String
}

PermissionScope is struct for respective permission scope like "issues", "checks", ... https://docs.github.com/en/actions/security-for-github-actions/security-guides/automatic-token-authentication#permissions-for-the-github_token

type Permissions Âķ

type Permissions struct {
	// All represents a permission value for all the scopes at once.
	All *String
	// Scopes is mappings from scope name to its permission configuration
	Scopes map[string]*PermissionScope
	// Pos is a position in source.
	Pos *Pos
}

Permissions is set of permission configurations in workflow file. All permissions can be set at once. Or each permission can be configured respectively. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#permissions

type Pos Âķ

type Pos struct {
	// Line is a line number of the position. This value is 1-based.
	Line int
	// Col is a column number of the position. This value is 1-based.
	Col int
}

Pos represents position in the file.

func (*Pos) IsBefore Âķ

func (p *Pos) IsBefore(other *Pos) bool

IsBefore returns if the position is before the other position. If they are equal, this function returns false.

func (*Pos) String Âķ

func (p *Pos) String() string

type Profile Âķ

type Profile string

Profile is a named set of rules which are enabled together. A profile includes every rule of the profiles before it: ProfileCorrectness < ProfileDefault < ProfilePedantic.

const (
	// ProfileCorrectness enables what actionlint checks by default plus the bug detectors of the
	// correctness group. It has no security posture or policy rules, apart from the basic checks
	// actionlint has too (an untrusted input in a script, hard-coded container credentials).
	ProfileCorrectness Profile = "correctness"
	// ProfileDefault adds the security posture and policy rules which are worth failing a build on.
	// It is the profile used when none is configured.
	ProfileDefault Profile = "default"
	// ProfilePedantic adds the noisy and opinionated rules and the pedantic checks of the audits.
	ProfilePedantic Profile = "pedantic"
)

func ParseProfile Âķ

func ParseProfile(s string) (Profile, error)

ParseProfile parses the name of a profile: "correctness", "default" or "pedantic".

func (Profile) Includes Âķ

func (p Profile) Includes(q Profile) bool

Includes reports whether the rules of the profile q are enabled by the profile p.

type Project Âķ

type Project struct {
	// contains filtered or unexported fields
}

Project represents one GitHub project. One Git repository corresponds to one project.

func NewProject Âķ

func NewProject(root string) (*Project, error)

NewProject creates a new instance with a file path to the root directory of the repository. This function returns an error when failing to parse an jactionlint config file in the repository.

func (*Project) ActionFiles Âķ

func (p *Project) ActionFiles() []string

ActionFiles returns the paths of the metadata files (action.yml or action.yaml) of the local actions of the project: the one in the root, the ones under ".github/actions" and the ones which a local `uses: ./path` of a workflow or of another action refers to. The paths are absolute and sorted. It reads the workflows and the actions of the project on every call; the linter keeps what it read.

func (*Project) Config Âķ

func (p *Project) Config() *Config

Config returns config object of the GitHub project repository. The config file was read from ".github/jactionlint.yaml" or ".github/jactionlint.yml" when this Project instance was created. When no config was found, this method returns nil.

func (*Project) DependabotFiles Âķ

func (p *Project) DependabotFiles() []string

DependabotFiles returns the paths of the Dependabot configuration files of the project: ".github/dependabot.yml" and ".github/dependabot.yaml" when they exist.

func (*Project) Knows Âķ

func (p *Project) Knows(path string) bool

Knows returns true when the project knows the given file. When a file is included in the project's directory, the project knows the file.

func (*Project) RootDir Âķ

func (p *Project) RootDir() string

RootDir returns a root directory path of the GitHub project repository.

func (*Project) WorkflowsDir Âķ

func (p *Project) WorkflowsDir() string

WorkflowsDir returns a ".github/workflows" directory path of the GitHub project repository. This method does not check if the directory exists.

type Projects Âķ

type Projects struct {
	// contains filtered or unexported fields
}

Projects represents set of projects. It caches Project instances which was created previously and reuses them.

func NewProjects Âķ

func NewProjects() *Projects

NewProjects creates new Projects instance.

func (*Projects) At Âķ

func (ps *Projects) At(path string) (*Project, error)

At returns the Project instance which the path belongs to. It returns nil if no project is found from the path.

type RawYAMLArray Âķ

type RawYAMLArray struct {
	// Elems is list of elements of the array value.
	Elems []RawYAMLValue
	// contains filtered or unexported fields
}

RawYAMLArray is raw YAML sequence value.

func (*RawYAMLArray) Equals Âķ

func (a *RawYAMLArray) Equals(other RawYAMLValue) bool

Equals returns if the other value is equal to the value.

func (*RawYAMLArray) Kind Âķ

func (a *RawYAMLArray) Kind() RawYAMLValueKind

Kind returns kind of raw YAML value.

func (*RawYAMLArray) Pos Âķ

func (a *RawYAMLArray) Pos() *Pos

Pos returns the start position of the value in the source file

func (*RawYAMLArray) String Âķ

func (a *RawYAMLArray) String() string

type RawYAMLObject Âķ

type RawYAMLObject struct {
	// Props is map from property names to their values. Keys are in lower case since they are case-insensitive.
	Props map[string]RawYAMLValue
	// contains filtered or unexported fields
}

RawYAMLObject is raw YAML mapping value.

func (*RawYAMLObject) Equals Âķ

func (o *RawYAMLObject) Equals(other RawYAMLValue) bool

Equals returns if the other value is equal to the value.

func (*RawYAMLObject) Kind Âķ

func (o *RawYAMLObject) Kind() RawYAMLValueKind

Kind returns kind of raw YAML value.

func (*RawYAMLObject) Pos Âķ

func (o *RawYAMLObject) Pos() *Pos

Pos returns the start position of the value in the source file

func (*RawYAMLObject) String Âķ

func (o *RawYAMLObject) String() string

type RawYAMLString Âķ

type RawYAMLString struct {

	// Value is string representation of the scalar node.
	Value string
	// StringTag is true when the YAML parser resolved the scalar with the `!!str` tag; that is,
	// the value was quoted, written as a block scalar, or explicitly tagged. Such a scalar is a
	// string even when its value looks like a number, a boolean, or null.
	StringTag bool
	// contains filtered or unexported fields
}

RawYAMLString is raw YAML scalar value.

func (*RawYAMLString) Equals Âķ

func (s *RawYAMLString) Equals(other RawYAMLValue) bool

Equals returns if the other value is equal to the value.

func (*RawYAMLString) Kind Âķ

func (s *RawYAMLString) Kind() RawYAMLValueKind

Kind returns kind of raw YAML value.

func (*RawYAMLString) Pos Âķ

func (s *RawYAMLString) Pos() *Pos

Pos returns the start position of the value in the source file

func (*RawYAMLString) String Âķ

func (s *RawYAMLString) String() string

type RawYAMLValue Âķ

type RawYAMLValue interface {
	// Kind returns kind of raw YAML value.
	Kind() RawYAMLValueKind
	// Equals returns if the other value is equal to the value.
	Equals(other RawYAMLValue) bool
	// Pos returns the start position of the value in the source file
	Pos() *Pos
	// String returns string representation of the value
	String() string
}

RawYAMLValue is a value at matrix variation. Any value can be put at matrix variations including mappings and arrays.

type RawYAMLValueKind Âķ

type RawYAMLValueKind int

RawYAMLValueKind is kind of raw YAML values

type RecordingGitHubClient Âķ

type RecordingGitHubClient struct {
	// contains filtered or unexported fields
}

RecordingGitHubClient wraps a GitHubClient and records the answers it gives. Fixtures returns them in the format NewFixtureGitHubClient reads.

func NewRecordingGitHubClient Âķ

func NewRecordingGitHubClient(inner GitHubClient) *RecordingGitHubClient

NewRecordingGitHubClient wraps the client.

func (*RecordingGitHubClient) Advisories Âķ

func (c *RecordingGitHubClient) Advisories(ctx context.Context, owner, repo string) ([]GitHubAdvisory, error)

Advisories implements GitHubClient.

func (*RecordingGitHubClient) AdvisoriesForPackages Âķ

func (c *RecordingGitHubClient) AdvisoriesForPackages(ctx context.Context, packages []string) ([]GitHubAdvisory, error)

AdvisoriesForPackages implements GitHubPackageAdvisoryClient. The answer for a subdirectory is recorded under its package name. The repository itself is recorded by Advisories.

func (*RecordingGitHubClient) Branches Âķ

func (c *RecordingGitHubClient) Branches(ctx context.Context, owner, repo string, limit int) (*GitHubBranchList, error)

Branches implements GitHubClient.

func (*RecordingGitHubClient) Compare Âķ

func (c *RecordingGitHubClient) Compare(ctx context.Context, owner, repo, base, head string) (GitHubCompareStatus, error)

Compare implements GitHubClient.

func (*RecordingGitHubClient) Environment Âķ added in v2.2.0

func (c *RecordingGitHubClient) Environment(ctx context.Context, owner, repo, name string) (*GitHubEnvironment, error)

Environment implements GitHubEnvironmentClient when the wrapped client does.

func (*RecordingGitHubClient) FileContent Âķ added in v2.2.0

func (c *RecordingGitHubClient) FileContent(ctx context.Context, owner, repo, ref, path string) ([]byte, error)

FileContent implements GitHubContentClient.

func (*RecordingGitHubClient) Fixtures Âķ

func (c *RecordingGitHubClient) Fixtures() ([]byte, error)

Fixtures returns the recorded answers as JSON, sorted so that recording twice gives the same file.

func (*RecordingGitHubClient) ImageDigest Âķ added in v2.2.0

func (c *RecordingGitHubClient) ImageDigest(ctx context.Context, registry, repository, tag string) (string, error)

ImageDigest implements ImageDigestClient for a wrapped client which can ask a registry.

func (*RecordingGitHubClient) Owner Âķ added in v2.2.0

func (c *RecordingGitHubClient) Owner(ctx context.Context, login string) (*GitHubOwner, error)

Owner implements GitHubOwnerClient when the wrapped client does.

func (*RecordingGitHubClient) Release Âķ added in v2.2.0

func (c *RecordingGitHubClient) Release(ctx context.Context, owner, repo, tag string) (*GitHubRelease, error)

Release implements GitHubReleaseClient when the wrapped client does.

func (*RecordingGitHubClient) ReleaseDate Âķ added in v2.2.0

func (c *RecordingGitHubClient) ReleaseDate(ctx context.Context, owner, repo, tag, sha string) (*GitHubReleaseDate, error)

ReleaseDate implements GitHubReleaseDateClient.

func (*RecordingGitHubClient) Repository Âķ

func (c *RecordingGitHubClient) Repository(ctx context.Context, owner, repo string) (*GitHubRepo, error)

Repository implements GitHubClient.

func (*RecordingGitHubClient) ResolveRef Âķ

func (c *RecordingGitHubClient) ResolveRef(ctx context.Context, owner, repo string, ns GitHubRefNamespace, name string) (string, bool, error)

ResolveRef implements GitHubClient.

func (*RecordingGitHubClient) Tags Âķ

func (c *RecordingGitHubClient) Tags(ctx context.Context, owner, repo string) (*GitHubTagList, error)

Tags implements GitHubClient.

type RefKind Âķ

type RefKind int

RefKind classifies the `@{ref}` part of a repository `uses:` value.

const (
	// RefNone means the value has no ref at all (local paths, a missing '@', or a Docker image
	// without a digest).
	RefNone RefKind = iota
	// RefFullSHA is a full-length commit SHA: 40 hex digits, or 64 for a repository with the SHA-256 object format
	// (https://github.com/actions/runner/pull/4347).
	RefFullSHA
	// RefShortSHA is an abbreviated commit SHA (7 to 39 hex digits). It is a heuristic: GitHub
	// cannot tell it from a branch or tag that happens to be spelled in hex.
	RefShortSHA
	// RefSemverTag looks like a version: v1, v1.2, 1.2.3, v1.2.3-rc.1.
	RefSemverTag
	// RefOther is any other tag or branch name, or a ref containing an expression.
	RefOther
	// RefDigest is a Docker content digest: sha256:{64 hex digits}.
	RefDigest
)

func (RefKind) String Âķ

func (k RefKind) String() string

String returns the name of the ref kind as used in messages.

type RenamedRule Âķ

type RenamedRule struct {
	// Old is the retired ID.
	Old string
	// ID is the ID of the rule which reports the findings now.
	ID string
	// Option is the option of ID that turns the findings on, or empty when ID reports them always.
	Option string
}

RenamedRule is a rule ID which was merged into the ID of another rule before 2.0 was released, when one audit was split in several IDs. The old ID is not a rule any more: its findings are the ones of ID with the option Option on. Ignores of the old ID (--ignore, "ignore" of "paths" and inline ignore comments) still work, matching only the findings that had the old ID, and print a deprecation warning. Everything else that takes a rule ID (rules, ignores, fix.rules, --fix-rules) refuses it and names the new place.

func RenamedRules Âķ

func RenamedRules() []RenamedRule

RenamedRules returns the retired rule IDs and the rules that report their findings now.

type RepositoryDispatchEvent Âķ

type RepositoryDispatchEvent struct {
	// Types is list of types which can trigger workflow.
	Types []*String
	// Pos is a position in source.
	Pos *Pos
}

RepositoryDispatchEvent is repository_dispatch event configuration. https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#repository_dispatch

func (*RepositoryDispatchEvent) EventName Âķ

func (e *RepositoryDispatchEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type RequiredActionRule Âķ

type RequiredActionRule struct {
	// Action is the name of the required action without version (e.g. "actions/checkout"). Sub-paths
	// are part of the name (e.g. "github/codeql-action/init"). The comparison is case-insensitive.
	Action string `yaml:"action"`
	// Version is the optional required ref (e.g. "v4" or a full commit SHA). It is compared exactly.
	// When empty, any version is accepted.
	Version string `yaml:"version"`
}

RequiredActionRule represents a requirement that a specific GitHub Action (or reusable workflow) is used in workflows, with an optional version constraint.

type RequiredCheck Âķ added in v2.5.0

type RequiredCheck struct {
	// Name is the name of the check as GitHub shows it. The comparison is exact.
	Name string
	// Events are the events the check is required for. Empty means pull_request.
	Events []string
	// Branches are the literal names of the base branches the requirement protects. Empty means that they are not
	// known, and the branch filters of the workflows are not judged.
	Branches []string
	// Path is the config file the item was read from. It is set by ReadConfigFile.
	Path string
	// Line and Column are the position of the name in the config file. They are 1-based.
	Line, Column int
}

RequiredCheck is an item of the "required-checks" list of the config file: a check that branch protection or a ruleset requires, and the events it is required for.

func (*RequiredCheck) UnmarshalYAML Âķ added in v2.5.0

func (rc *RequiredCheck) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ReusableWorkflowMetadata Âķ

type ReusableWorkflowMetadata struct {
	Inputs  ReusableWorkflowMetadataInputs  `yaml:"inputs"`
	Outputs ReusableWorkflowMetadataOutputs `yaml:"outputs"`
	Secrets ReusableWorkflowMetadataSecrets `yaml:"secrets"`
	// JobPermissions is per-job effective permission requirements declared by the callee. Each value
	// is the job's own permissions, or the workflow-level permissions when the job omits them.
	// A value of nil means the callee did not declare any permissions for that job (it inherits
	// from the caller's grant, so nothing to compare).
	JobPermissions map[string]*ReusableWorkflowPermissions
}

ReusableWorkflowMetadata is metadata to validate local reusable workflows. This struct does not contain all metadata from YAML file. It only contains metadata which is necessary to validate reusable workflow files by jactionlint.

type ReusableWorkflowMetadataInput Âķ

type ReusableWorkflowMetadataInput struct {
	// Name is a name of the input defined in the reusable workflow.
	Name string
	// Required is true when 'required' field of the input is set to true and no default value is set.
	Required bool
	// Type is a type of the input. When the input type is unknown, 'any' type is set.
	Type ExprType
}

ReusableWorkflowMetadataInput is an input metadata for validating local reusable workflow file.

func (*ReusableWorkflowMetadataInput) UnmarshalYAML Âķ

func (input *ReusableWorkflowMetadataInput) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ReusableWorkflowMetadataInputs Âķ

type ReusableWorkflowMetadataInputs map[string]*ReusableWorkflowMetadataInput

ReusableWorkflowMetadataInputs is a map from input name to reusable wokflow input metadata. The keys are in lower case since input names of workflow calls are case insensitive.

func (*ReusableWorkflowMetadataInputs) UnmarshalYAML Âķ

func (inputs *ReusableWorkflowMetadataInputs) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ReusableWorkflowMetadataOutput Âķ

type ReusableWorkflowMetadataOutput struct {
	// Name is a name of the output in the reusable workflow.
	Name string
}

ReusableWorkflowMetadataOutput is an output metadata for validating local reusable workflow file.

type ReusableWorkflowMetadataOutputs Âķ

type ReusableWorkflowMetadataOutputs map[string]*ReusableWorkflowMetadataOutput

ReusableWorkflowMetadataOutputs is a map from output name to reusable wokflow output metadata. The keys are in lower case since output names of workflow calls are case insensitive.

func (*ReusableWorkflowMetadataOutputs) UnmarshalYAML Âķ

func (outputs *ReusableWorkflowMetadataOutputs) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ReusableWorkflowMetadataSecret Âķ

type ReusableWorkflowMetadataSecret struct {
	// Name is a name of the secret in the reusable workflow.
	Name string
	// Required indicates whether the secret is required by its reusable workflow. When this value
	// is true, workflow calls must set this secret unless secrets are not inherited.
	Required bool `yaml:"required"`
}

ReusableWorkflowMetadataSecret is a secret metadata for validating local reusable workflow file.

type ReusableWorkflowMetadataSecrets Âķ

type ReusableWorkflowMetadataSecrets map[string]*ReusableWorkflowMetadataSecret

ReusableWorkflowMetadataSecrets is a map from secret name to reusable wokflow secret metadata. The keys are in lower case since secret names of workflow calls are case insensitive.

func (*ReusableWorkflowMetadataSecrets) UnmarshalYAML Âķ

func (secrets *ReusableWorkflowMetadataSecrets) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ReusableWorkflowPermissions Âķ

type ReusableWorkflowPermissions struct {
	// All is the special form: "read-all" or "write-all". Empty when Scopes is used or when the
	// permission was explicitly set to `{}`.
	All string
	// Scopes is the per-scope permission level mapping (scope name → "read"/"write"/"none").
	Scopes map[string]string
}

ReusableWorkflowPermissions represents the effective `permissions:` declared by a callee job. Either All is set (e.g. "read-all", "write-all") or Scopes carries per-scope permission levels. An empty value (All == "" and Scopes empty) is the explicit `permissions: {}` form, meaning all scopes are "none".

type Rule Âķ

type Rule interface {
	Pass
	Errs() []*Error
	Name() string
	Description() string
	EnableDebug(out io.Writer)
	SetConfig(cfg *Config)
	Config() *Config
}

Rule is an interface which all rule structs must meet.

type RuleAction Âķ

type RuleAction struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleAction is a rule to check running action in steps of jobs. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstepsuses

func NewRuleAction Âķ

func NewRuleAction(cache *LocalActionsCache) *RuleAction

NewRuleAction creates new RuleAction instance.

func (*RuleAction) VisitStep Âķ

func (rule *RuleAction) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleAction) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleAction) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleActionInputDependencies Âķ added in v2.2.0

type RuleActionInputDependencies struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleActionInputDependencies reports inputs of well-known actions which only work together, from the table of action_input_dependencies.go: an input that the action ignores without another one (`run-id` of actions/download-artifact needs `github-token`), a group of which exactly one input is needed (`timeout_minutes` or `timeout_seconds` of nick-fields/retry), and inputs which exclude each other.

The first two are reported as missing-action-input, which is what actionlint calls an input the action needs, the third as conflicting-action-inputs. The data set of popular actions does not know these rules, and the rule does not need it: the table has its own versions. A step whose `with:` is an expression or has an `${{ insert }}` key is not judged, and two inputs of a conflict are reported only when both are written out: an expression may be empty at run time, which is how a workflow chooses between two inputs.

func NewRuleActionInputDependencies Âķ added in v2.2.0

func NewRuleActionInputDependencies() *RuleActionInputDependencies

NewRuleActionInputDependencies creates a new RuleActionInputDependencies instance.

func (*RuleActionInputDependencies) VisitStep Âķ added in v2.2.0

func (rule *RuleActionInputDependencies) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleActionInputDependencies) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleActionInputDependencies) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleActionReleaseCooldown Âķ added in v2.2.0

type RuleActionReleaseCooldown struct {
	// contains filtered or unexported fields
}

RuleActionReleaseCooldown reports an action pinned to a version which was released less than a number of days ago. A compromised release of an action is usually found and taken down within days, and a pin that waits for a release to age is not hit by it. It is the check of pinact's --min-age, and the twin of dependabot-cooldown, which asks the same of the updates that Dependabot proposes.

The date is the one of the release of GitHub which the tag names (published_at). A tag without a release has the date of its commit, which is older than the tag when the tag was moved to an older commit, and so can hide a fresh release. It does not report a branch.

func NewRuleActionReleaseCooldown Âķ added in v2.2.0

func NewRuleActionReleaseCooldown(sess *onlineSession, days int, now func() time.Time) *RuleActionReleaseCooldown

NewRuleActionReleaseCooldown creates a new RuleActionReleaseCooldown instance. now returns the current time; nil means releaseNow.

func (*RuleActionReleaseCooldown) VisitJobPre Âķ added in v2.2.0

func (r *RuleActionReleaseCooldown) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleActionReleaseCooldown) VisitStep Âķ added in v2.2.0

func (r *RuleActionReleaseCooldown) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleActionReleaseCooldown) VisitWorkflowPost Âķ added in v2.2.0

func (r *RuleActionReleaseCooldown) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleActionReleaseCooldown) VisitWorkflowPre Âķ added in v2.2.0

func (r *RuleActionReleaseCooldown) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleActionsLock Âķ added in v2.2.0

type RuleActionsLock struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleActionsLock reports the actions of a workflow (or of a local action) which the Actions lock file does not list for the workflows which run it.

func NewRuleActionsLock Âķ added in v2.2.0

func NewRuleActionsLock(scope *lockScope) *RuleActionsLock

NewRuleActionsLock creates a new RuleActionsLock instance. The scope is the lock file with the workflows it is read for, see RuleEnv.lockScope.

func (*RuleActionsLock) VisitStep Âķ added in v2.2.0

func (r *RuleActionsLock) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleActionsLock) VisitWorkflowPre Âķ added in v2.2.0

func (r *RuleActionsLock) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre implements Pass.

type RuleAdhocPackages Âķ

type RuleAdhocPackages struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleAdhocPackages detects `run:` steps which install a package by name with a JavaScript package manager (npm, yarn, pnpm, bun, aube) or a Ruby tool (gem, bundle add), outside of a manifest that produces a lock file.

A package installed this way is usually not pinned, and even when it is, its dependencies are resolved anew on every run. Adding the package to package.json or a Gemfile, committing the lock file and installing with `npm ci` or `bundle install` makes the workflow reproducible.

func NewRuleAdhocPackages Âķ

func NewRuleAdhocPackages() *RuleAdhocPackages

NewRuleAdhocPackages creates a new RuleAdhocPackages instance.

func (*RuleAdhocPackages) VisitJobPost Âķ

func (rule *RuleAdhocPackages) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleAdhocPackages) VisitJobPre Âķ

func (rule *RuleAdhocPackages) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleAdhocPackages) VisitStep Âķ

func (rule *RuleAdhocPackages) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleAdhocPackages) VisitWorkflowPre Âķ

func (rule *RuleAdhocPackages) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleAgenticActions Âķ

type RuleAgenticActions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleAgenticActions finds AI agent actions that outsiders can steer or that run with their safeguards off. An agent reads text that an attacker writes (an issue, a comment, the code of a pull request) as instructions, and then uses its tools with the secrets and the token of the job. It is a risk that template-injection cannot describe: there is no escaping that makes text safe to read for an agent.

func NewRuleAgenticActions Âķ

func NewRuleAgenticActions(anyTrigger bool) *RuleAgenticActions

NewRuleAgenticActions creates a new RuleAgenticActions instance. With anyTrigger the unsafe settings of an agent are also reported in a workflow that outsiders cannot trigger.

func (*RuleAgenticActions) VisitJobPre Âķ

func (rule *RuleAgenticActions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleAgenticActions) VisitWorkflowPre Âķ

func (rule *RuleAgenticActions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleAnonymousDefinition Âķ

type RuleAnonymousDefinition struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleAnonymousDefinition is a rule to detect workflows and jobs without a "name:". GitHub renders such a workflow with its file path in the UI, which makes it hard to tell which definition runs. https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#name

func NewRuleAnonymousDefinition Âķ

func NewRuleAnonymousDefinition(path string, src []byte) *RuleAnonymousDefinition

NewRuleAnonymousDefinition creates a new RuleAnonymousDefinition instance. The path and the source of the file are used to put a fix on the error. They can be empty.

func (*RuleAnonymousDefinition) VisitJobPre Âķ

func (rule *RuleAnonymousDefinition) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleAnonymousDefinition) VisitWorkflowPre Âķ

func (rule *RuleAnonymousDefinition) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleArchivedUses Âķ

type RuleArchivedUses struct {
	// contains filtered or unexported fields
}

RuleArchivedUses reports actions and reusable workflows whose repository is archived. An archived repository is read-only and unmaintained: its vulnerabilities, and those of what it vendors, will not be fixed.

func NewRuleArchivedUses Âķ

func NewRuleArchivedUses(sess *onlineSession) *RuleArchivedUses

NewRuleArchivedUses creates a new RuleArchivedUses instance.

func (*RuleArchivedUses) VisitJobPre Âķ

func (r *RuleArchivedUses) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleArchivedUses) VisitStep Âķ

func (r *RuleArchivedUses) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleArchivedUses) VisitWorkflowPost Âķ

func (r *RuleArchivedUses) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleArchivedUses) VisitWorkflowPre Âķ

func (r *RuleArchivedUses) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleArgumentInjection Âķ added in v2.2.0

type RuleArgumentInjection struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleArgumentInjection detects free text that an outsider writes and that a script puts into the program text or the options of a command that can run code or write files with them.

  • `sed "s/PLACEHOLDER/$BODY/g"`: a value with a slash ends the command and the rest is a program of its own. GNU sed runs a command with the `e` command and the `e` flag of `s`, and `w` and `r` write and read files, so `a/g;1e id;#` runs `id`. The text of an `awk` program is the same (`system()`), and so is the command that `find -exec` runs, and an unquoted value that the shell splits into words can add `-exec` to a `find`.
  • `wget`, `curl` and `git clone` take a quoted value as one word, and a value that starts with a dash is an option: `-o`, `--output`, `--upload-pack`. The value must be the whole word or start it, it must be a word that is not the value of an option, and nothing may end the options with `--` before it. Commands whose options the rule does not know (tar, zip, rsync) are left out: it cannot tell their operands from the values of their options.

Only free text counts: a body, a comment, a title, a commit message, a name an author chose. The name of a branch, of a label or of an account is left out, as in the models of CodeQL (actions/ql/lib/ext/config/argument_injection_sinks.yml has the commands): git refuses a branch that starts with a dash, and the characters of an account name are fixed. The value is judged like in command-injection, with the strictest charset (letters, digits and a dash) as the only safe shape, because a dot and a slash are enough to break a sed program.

func NewRuleArgumentInjection Âķ added in v2.2.0

func NewRuleArgumentInjection() *RuleArgumentInjection

NewRuleArgumentInjection creates a new RuleArgumentInjection instance.

func (*RuleArgumentInjection) VisitJobPost Âķ added in v2.2.0

func (rule *RuleArgumentInjection) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleArgumentInjection) VisitJobPre Âķ added in v2.2.0

func (rule *RuleArgumentInjection) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleArgumentInjection) VisitStep Âķ added in v2.2.0

func (rule *RuleArgumentInjection) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleArgumentInjection) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleArgumentInjection) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleArtipacked Âķ

type RuleArtipacked struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleArtipacked is a rule checker which reports actions/checkout steps that leave the GITHUB_TOKEN in the git config of the workspace. Anything that later copies the workspace, such as an artifact upload, then publishes the credential (the "ArtiPACKED" attack), and even without that the credential is on disk for every later step to read. Setting `persist-credentials: false` removes it.

An explicit `persist-credentials: true` is a decision that the credential is needed, so it is not reported.

The fix adds `persist-credentials: false`. It is safe only when no later step of the job runs git commands that talk to a remote or uses a known pushing action; otherwise the job may be relying on the credential and the fix is unsafe. Scripts which push without showing a git command in the workflow cannot be seen, so run the workflow after applying the fix.

func NewRuleArtipacked Âķ

func NewRuleArtipacked(src []byte) *RuleArtipacked

NewRuleArtipacked creates a new RuleArtipacked instance. The source of the file is needed to attach fixes. It can be nil, in which case findings carry no fix.

func (*RuleArtipacked) VisitJobPre Âķ

func (rule *RuleArtipacked) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleArtipacked) VisitWorkflowPost Âķ

func (rule *RuleArtipacked) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children. It verifies the fixes: the file must still be YAML with persist-credentials: false in the same step.

func (*RuleArtipacked) VisitWorkflowPre Âķ

func (rule *RuleArtipacked) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleBase Âķ

type RuleBase struct {
	// contains filtered or unexported fields
}

RuleBase is a struct to be a base of rule structs. Embed this struct to define default methods automatically

func NewRuleBase Âķ

func NewRuleBase(name string, desc string) RuleBase

NewRuleBase creates a new RuleBase instance. It should be embedded to your own rule instance.

func (*RuleBase) Config Âķ

func (r *RuleBase) Config() *Config

Config returns the user configuration of jactionlint. When no config was set to this rule by SetConfig, this method returns nil.

func (*RuleBase) Debug Âķ

func (r *RuleBase) Debug(format string, args ...interface{})

Debug prints debug log to the output. The output is specified by the argument of EnableDebug method. By default, no output is set so debug log is not printed.

func (*RuleBase) Description Âķ

func (r *RuleBase) Description() string

Description returns the description of the rule.

func (*RuleBase) EnableDebug Âķ

func (r *RuleBase) EnableDebug(out io.Writer)

EnableDebug enables debug output from the rule. Given io.Writer instance is used to print debug information to console. Setting nil means disabling debug output.

func (*RuleBase) Error Âķ

func (r *RuleBase) Error(pos *Pos, msg string)

Error creates a new error from the source position and the error message and stores it in the rule instance. The errors can be accessed by Errs method. The ID of the error is the name of the rule. Rules which should be configurable per diagnostic report with ReportID instead.

func (*RuleBase) Errorf Âķ

func (r *RuleBase) Errorf(pos *Pos, format string, args ...interface{})

Errorf reports a new error with the source position and the formatted error message and stores it in the rule instance. The errors can be accessed by Errs method. The ID of the error is the name of the rule.

func (*RuleBase) Errs Âķ

func (r *RuleBase) Errs() []*Error

Errs returns errors found by the rule.

func (*RuleBase) Name Âķ

func (r *RuleBase) Name() string

Name returns the name of the rule.

func (*RuleBase) ReportID Âķ

func (r *RuleBase) ReportID(id string, pos *Pos, msg string)

ReportID reports a new error with the stable diagnostic ID, the source position and the error message and stores it in the rule instance. One rule can report several IDs. IDs of the built-in rules are listed in Rules. The errors can be accessed by Errs method.

func (*RuleBase) ReportIDf Âķ

func (r *RuleBase) ReportIDf(id string, pos *Pos, format string, args ...interface{})

ReportIDf is like ReportID but takes a format string and its arguments.

func (*RuleBase) ReportRange Âķ

func (r *RuleBase) ReportRange(id string, pos *Pos, end *Pos, msg string)

ReportRange is like ReportID but also tells where the problematic region ends. The end position is exclusive: it is the position just after the last character of the region.

func (*RuleBase) SetConfig Âķ

func (r *RuleBase) SetConfig(cfg *Config)

SetConfig populates user configuration of jactionlint to the rule. When no config is set, rules should behave as if the default configuration is set.

func (*RuleBase) VisitJobPost Âķ

func (r *RuleBase) VisitJobPost(node *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleBase) VisitJobPre Âķ

func (r *RuleBase) VisitJobPre(node *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleBase) VisitStep Âķ

func (r *RuleBase) VisitStep(node *Step) error

VisitStep is callback when visiting Step node.

func (*RuleBase) VisitWorkflowPost Âķ

func (r *RuleBase) VisitWorkflowPost(node *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children.

func (*RuleBase) VisitWorkflowPre Âķ

func (r *RuleBase) VisitWorkflowPre(node *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleBotConditions Âķ

type RuleBotConditions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleBotConditions is a rule to find conditions which trust an account by checking who "the actor" is. github.actor is the account which caused the last event, not the one who created the pull request or the branch, so a condition like github.actor == 'dependabot[bot]' can be satisfied by a change that dependabot never authored.

func NewRuleBotConditions Âķ

func NewRuleBotConditions(src []byte) *RuleBotConditions

NewRuleBotConditions creates a new RuleBotConditions instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleBotConditions) VisitJobPre Âķ

func (rule *RuleBotConditions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleBotConditions) VisitStep Âķ

func (rule *RuleBotConditions) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleBotConditions) VisitWorkflowPre Âķ

func (rule *RuleBotConditions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleCachePoisoning Âķ

type RuleCachePoisoning struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleCachePoisoning is a rule checker for two ways the GitHub Actions cache turns into an attack path:

  • a job that publishes artifacts (a workflow triggered by a release or by pushed tags, or a job using a publishing action or command) restores a cache. Whoever can write that cache can slip code into the release. `cache-mode: none` at the workflow or the job switches caching off.
  • a workflow on a privileged trigger saves a cache with `cache-mode: write` or `write-only`, which lets untrusted code plant the entries that release workflows later restore.

func NewRuleCachePoisoning Âķ

func NewRuleCachePoisoning() *RuleCachePoisoning

NewRuleCachePoisoning creates a new RuleCachePoisoning instance.

func (*RuleCachePoisoning) VisitJobPre Âķ

func (rule *RuleCachePoisoning) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleCachePoisoning) VisitWorkflowPre Âķ

func (rule *RuleCachePoisoning) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleCheckoutStaticCredentials Âķ

type RuleCheckoutStaticCredentials struct {
	RuleBase
}

RuleCheckoutStaticCredentials is a rule checker which reports actions/checkout steps that are given a credential that does not expire: the "ssh-key" input, or a "token" input written in the workflow. With the "secret-tokens" option it also reports a "token" taken from a secret other than GITHUB_TOKEN (a personal access token, in most cases). That is a pedantic check: it is on under the pedantic profile and off under the default one, because workflows that have to push something that triggers other workflows, or reach other repositories, use one on purpose. The default GITHUB_TOKEN lives as long as the job and is limited to the repository, and a token created by a GitHub App lives for an hour at most. A static credential is valid until somebody rotates it, can usually reach much more than the job needs, and checkout writes it to the git config of the workspace (unless "persist-credentials" is false) where every later step can read it.

The rule is conservative: a "token" taken from an expression that is not made only of secrets (the output of a step, "github.token", an input of a reusable workflow, a fallback to GITHUB_TOKEN) is not reported, because what it holds is not known.

func NewRuleCheckoutStaticCredentials Âķ

func NewRuleCheckoutStaticCredentials() *RuleCheckoutStaticCredentials

NewRuleCheckoutStaticCredentials creates a new RuleCheckoutStaticCredentials instance.

func (*RuleCheckoutStaticCredentials) VisitJobPre Âķ

func (rule *RuleCheckoutStaticCredentials) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleCommandInjection Âķ added in v2.2.0

type RuleCommandInjection struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleCommandInjection detects input that an outsider controls and that a script runs as code after it was moved out of the `${{ }}` expression into an environment variable.

The advice for template injection is to pass the input to the script as `env:` and to read it as `"$BODY"`. That is safe as long as the shell only expands the variable. It is not when the script parses the value again:

  • `eval "$BODY"` and `source <(echo "$BODY")` run the value;
  • `bash -c "echo $BODY"` (any shell with -c, also behind docker, sudo or xargs) parses the command string after the variable was expanded into it, so a `;` or `$(...)` in the value runs. `bash -c 'echo "$1"' _ "$BODY"` passes the value as data and is fine;
  • `$CMD` as the name of a command runs the program that the value names;
  • `echo "$BODY" | bash` and `bash <<< "$BODY"` run the value from the input of the shell;
  • `xargs -I{} sh -c 'echo {}'` puts each line of its input into the command string of the shell;
  • `python -c "...$BODY..."`, `node -e` and `perl -e` run an inline program with the value in its text;
  • in the script of actions/github-script, `execSync(`echo ${process.env.BODY}`)`, `exec.exec(process.env.X)` and the other calls of child_process that go through a shell (see command_injection_javascript.go).

A plain `"$BODY"` as an argument of a command is not reported (that is argument injection at most), and neither is a value that the script validated or cut down to harmless characters before, or quoted with `printf %q` or `${v@Q}`. The judgement of the value is the one of github-env (rule_github_env_flow.go, see the invariant in rule_github_env.go): the variable has the value of its last assignment, whatever the step's `env:` gave it, and the source of an untrusted value is the table of untrusted inputs of the expression checks. What differs is the destination. A value is safe for a shell only when it is cut down to a character set (destShell): a value without newlines can still run `$(id)`. An expression written in the script itself is not judged: template-injection reports it. `inputs.*` of a composite action is not judged either, as an action may take a command on purpose.

func NewRuleCommandInjection Âķ added in v2.2.0

func NewRuleCommandInjection() *RuleCommandInjection

NewRuleCommandInjection creates a new RuleCommandInjection instance.

func (*RuleCommandInjection) VisitJobPost Âķ added in v2.2.0

func (rule *RuleCommandInjection) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleCommandInjection) VisitJobPre Âķ added in v2.2.0

func (rule *RuleCommandInjection) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleCommandInjection) VisitStep Âķ added in v2.2.0

func (rule *RuleCommandInjection) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleCommandInjection) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleCommandInjection) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleCommentTriggerAuthorization Âķ added in v2.2.0

type RuleCommentTriggerAuthorization struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleCommentTriggerAuthorization finds the jobs of the comment-triggered workflows that are started by the text of the comment and check nothing about who wrote it (zizmor#459).

A workflow with the trigger `issue_comment` runs on the comment of anyone who can comment, on a public repository that is every user of GitHub, and it runs in the base repository, with the default token and the secrets. The usual shape is a command bot:

if: github.event.issue.pull_request && contains(github.event.comment.body, '/deploy')

which looks like a restriction but only reads what the commenter chose to write. It lets anyone start the job. The job is reported when its condition (or the condition of one of its steps) reads the comment body, and nothing checks the commenter: no condition on the association (`github.event.comment.author_association`), the actor or the user, no step before it that asks for the permission of the actor, no `environment:` and no such check in a job that it needs. That is the same check of the user that agentic-actions makes (jobChecksWhoStarted). It is a heuristic: it cannot tell a condition that is right from one that only mentions the actor.

func NewRuleCommentTriggerAuthorization Âķ added in v2.2.0

func NewRuleCommentTriggerAuthorization() *RuleCommentTriggerAuthorization

NewRuleCommentTriggerAuthorization creates a new RuleCommentTriggerAuthorization instance.

func (*RuleCommentTriggerAuthorization) VisitJobPre Âķ added in v2.2.0

func (rule *RuleCommentTriggerAuthorization) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleCommentTriggerAuthorization) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleCommentTriggerAuthorization) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleConcurrencyCancelsPRs Âķ

type RuleConcurrencyCancelsPRs struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleConcurrencyCancelsPRs reports concurrency groups that are shared by all pull requests while cancel-in-progress can cancel the running workflow: a new run for one pull request then cancels the run of an unrelated pull request.

func NewRuleConcurrencyCancelsPRs Âķ

func NewRuleConcurrencyCancelsPRs() *RuleConcurrencyCancelsPRs

NewRuleConcurrencyCancelsPRs creates a new RuleConcurrencyCancelsPRs instance.

func (*RuleConcurrencyCancelsPRs) VisitJobPre Âķ

func (rule *RuleConcurrencyCancelsPRs) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleConcurrencyCancelsPRs) VisitWorkflowPre Âķ

func (rule *RuleConcurrencyCancelsPRs) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleConcurrencyCancelsRelease Âķ

type RuleConcurrencyCancelsRelease struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleConcurrencyCancelsRelease reports `cancel-in-progress` that cancels a release or a deployment which is still running. A new push must not kill an in-flight release.

func NewRuleConcurrencyCancelsRelease Âķ

func NewRuleConcurrencyCancelsRelease(src []byte) *RuleConcurrencyCancelsRelease

NewRuleConcurrencyCancelsRelease creates a new RuleConcurrencyCancelsRelease instance.

func (*RuleConcurrencyCancelsRelease) VisitJobPre Âķ

func (rule *RuleConcurrencyCancelsRelease) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleConcurrencyCancelsRelease) VisitWorkflowPre Âķ

func (rule *RuleConcurrencyCancelsRelease) VisitWorkflowPre(n *Workflow) error

type RuleConcurrencyDeadlock Âķ added in v2.2.0

type RuleConcurrencyDeadlock struct {
	RuleBase
}

RuleConcurrencyDeadlock reports the group of a workflow which a workflow that it calls has too.

func NewRuleConcurrencyDeadlock Âķ added in v2.2.0

func NewRuleConcurrencyDeadlock() *RuleConcurrencyDeadlock

NewRuleConcurrencyDeadlock creates a new RuleConcurrencyDeadlock instance.

func (*RuleConcurrencyDeadlock) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleConcurrencyDeadlock) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleConcurrencyLimits Âķ

type RuleConcurrencyLimits struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleConcurrencyLimits is a rule to detect workflows without a concurrency limit. By default GitHub runs every instance of a workflow at once even when a newer run supersedes the older ones, which wastes runner minutes and can race on artifacts. https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#concurrency

func NewRuleConcurrencyLimits Âķ

func NewRuleConcurrencyLimits(path string, src []byte) *RuleConcurrencyLimits

NewRuleConcurrencyLimits creates a new RuleConcurrencyLimits instance. The source is used to find where to report a workflow without any concurrency setting. It can be empty.

func (*RuleConcurrencyLimits) VisitWorkflowPre Âķ

func (rule *RuleConcurrencyLimits) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleConfig Âķ

type RuleConfig struct {
	// Level is the severity of the findings of the rule. SeverityOff disables the rule.
	Level Severity
	// Options are the options of the rule. The values are int or float64 depending on RuleOption.Kind.
	Options map[string]any
	// contains filtered or unexported fields
}

RuleConfig is the configuration of one rule in the "rules" mapping of the configuration file. It is either a level (`unpinned-uses: warn`) or a mapping with the level and the options of the rule (`max-run-lines: {level: warn, max: 80}`). A mapping without "level" enables the rule at its default level.

func (*RuleConfig) UnmarshalYAML Âķ

func (rc *RuleConfig) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type RuleContinueOnError Âķ

type RuleContinueOnError struct {
	RuleBase
}

RuleContinueOnError reports jobs with `continue-on-error: true`, which let the workflow pass when the job fails.

func NewRuleContinueOnError Âķ

func NewRuleContinueOnError() *RuleContinueOnError

NewRuleContinueOnError creates a new RuleContinueOnError instance.

func (*RuleContinueOnError) VisitJobPre Âķ

func (rule *RuleContinueOnError) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleContinueOnError) VisitStep Âķ

func (rule *RuleContinueOnError) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleCredentials Âķ

type RuleCredentials struct {
	RuleBase
}

RuleCredentials is a rule to check credentials in workflows

func NewRuleCredentials Âķ

func NewRuleCredentials() *RuleCredentials

NewRuleCredentials creates new RuleCredentials instance

func (*RuleCredentials) VisitJobPre Âķ

func (rule *RuleCredentials) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleDangerousTriggers Âķ

type RuleDangerousTriggers struct {
	RuleBase
}

RuleDangerousTriggers is a rule to detect workflow triggers which are difficult to use securely: "pull_request_target", "workflow_run" and "issue_comment". The message says what the workflow can use (the scopes its token can write, the secrets it reads), and a workflow that can neither write nor read a secret is a pedantic finding. https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/

func NewRuleDangerousTriggers Âķ

func NewRuleDangerousTriggers() *RuleDangerousTriggers

NewRuleDangerousTriggers creates a new RuleDangerousTriggers instance.

func (*RuleDangerousTriggers) VisitWorkflowPre Âķ

func (rule *RuleDangerousTriggers) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleDependabotCooldown Âķ

type RuleDependabotCooldown struct {
	DependabotRuleBase
	// contains filtered or unexported fields
}

RuleDependabotCooldown is a rule to check that the updates of a Dependabot configuration wait for a new version to age before proposing it.

func NewRuleDependabotCooldown Âķ

func NewRuleDependabotCooldown(src []byte) *RuleDependabotCooldown

NewRuleDependabotCooldown creates a new RuleDependabotCooldown instance. src is the content of the file, which is used to build automatic fixes. It can be nil.

func (*RuleDependabotCooldown) VisitDependabotUpdate Âķ

func (r *RuleDependabotCooldown) VisitDependabotUpdate(u *DependabotUpdate) error

VisitDependabotUpdate is callback when visiting an item of "updates".

type RuleDependabotExecution Âķ

type RuleDependabotExecution struct {
	DependabotRuleBase
	// contains filtered or unexported fields
}

RuleDependabotExecution is a rule to check that updates of a Dependabot configuration do not allow the package managers to run code of the dependencies. https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#insecure-external-code-execution--

func NewRuleDependabotExecution Âķ

func NewRuleDependabotExecution(src []byte) *RuleDependabotExecution

NewRuleDependabotExecution creates a new RuleDependabotExecution instance. src is the content of the file, which is used to build the automatic fix. It can be nil.

func (*RuleDependabotExecution) VisitDependabotUpdate Âķ

func (r *RuleDependabotExecution) VisitDependabotUpdate(u *DependabotUpdate) error

VisitDependabotUpdate is callback when visiting an item of "updates".

type RuleDependabotMissingActionsUpdate Âķ

type RuleDependabotMissingActionsUpdate struct {
	DependabotRuleBase
	// contains filtered or unexported fields
}

RuleDependabotMissingActionsUpdate is a rule to check that a repository which has workflows and uses Dependabot also keeps its actions up to date with Dependabot.

It also reports the local composite actions with `uses:` which none of the github-actions updates covers.

func NewRuleDependabotMissingActionsUpdate Âķ

func NewRuleDependabotMissingActionsUpdate(project *Project) *RuleDependabotMissingActionsUpdate

NewRuleDependabotMissingActionsUpdate creates a new RuleDependabotMissingActionsUpdate instance. project is the repository which has the Dependabot configuration. It can be nil, in which case the rule does nothing.

func (*RuleDependabotMissingActionsUpdate) VisitDependabotPost Âķ

func (r *RuleDependabotMissingActionsUpdate) VisitDependabotPost(d *Dependabot) error

VisitDependabotPost is callback when visiting the root node after visiting its children.

type RuleDependabotRegistryCredentials Âķ added in v2.2.0

type RuleDependabotRegistryCredentials struct {
	DependabotRuleBase
}

RuleDependabotRegistryCredentials is a rule to check that the registries of a Dependabot configuration do not hold their credentials in plain text.

Dependabot reads a secret from the "Dependabot secrets" of the repository when a value is written as ${{secrets.NAME}}. A literal "password", "token", "key" or "auth-key" is a credential committed to the repository. It is the counterpart of hardcoded-container-credentials for dependabot.yml (https://github.com/zizmorcore/zizmor/issues/1222, which is not an audit of zizmor yet).

https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#registries--

func NewRuleDependabotRegistryCredentials Âķ added in v2.2.0

func NewRuleDependabotRegistryCredentials() *RuleDependabotRegistryCredentials

NewRuleDependabotRegistryCredentials creates a new RuleDependabotRegistryCredentials instance.

func (*RuleDependabotRegistryCredentials) VisitDependabotPre Âķ added in v2.2.0

func (r *RuleDependabotRegistryCredentials) VisitDependabotPre(d *Dependabot) error

VisitDependabotPre is callback when visiting the root node before visiting its children.

type RuleDeprecatedCommands Âķ

type RuleDeprecatedCommands struct {
	RuleBase
}

RuleDeprecatedCommands is a rule checker to detect deprecated workflow commands. Currently 'set-state', 'set-output', `set-env' and 'add-path' are detected as deprecated.

- https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/ - https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/

func NewRuleDeprecatedCommands Âķ

func NewRuleDeprecatedCommands() *RuleDeprecatedCommands

NewRuleDeprecatedCommands creates a new RuleDeprecatedCommands instance.

func (*RuleDeprecatedCommands) VisitStep Âķ

func (rule *RuleDeprecatedCommands) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleDeprecatedNodeRuntime Âķ added in v2.2.0

type RuleDeprecatedNodeRuntime struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleDeprecatedNodeRuntime reports the settings of GitHub Actions about the Node.js runtime of JavaScript actions that GitHub removed. A JavaScript action declares its runtime in runs.using. The runner no longer has Node.js 20 (or 16, or 12): it runs the action on Node.js 24 whatever it declares. The action still works unless its code breaks on Node.js 24, so this is hygiene and not an error: the author never tested the action on the runtime it runs on, and a runner that is not updated (GitHub Enterprise Server, an old self-hosted runner) behaves differently. It is a policy rule of the pedantic profile.

func NewRuleDeprecatedNodeRuntime Âķ added in v2.2.0

func NewRuleDeprecatedNodeRuntime() *RuleDeprecatedNodeRuntime

NewRuleDeprecatedNodeRuntime creates a new RuleDeprecatedNodeRuntime instance.

func (*RuleDeprecatedNodeRuntime) VisitJobPre Âķ added in v2.2.0

func (rule *RuleDeprecatedNodeRuntime) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleDeprecatedNodeRuntime) VisitStep Âķ added in v2.2.0

func (rule *RuleDeprecatedNodeRuntime) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleDeprecatedNodeRuntime) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleDeprecatedNodeRuntime) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleDeprecatedRunnerLabel Âķ added in v2.2.0

type RuleDeprecatedRunnerLabel struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleDeprecatedRunnerLabel warns ahead of the retirement of a GitHub-hosted runner label (macos-14, ubuntu-22.04). The label still works until its day, so this is not a mistake yet; from that day on unknown-runner-label reports it as an error. The dates are in runnerLabelRetirements.

func NewRuleDeprecatedRunnerLabel Âķ added in v2.2.0

func NewRuleDeprecatedRunnerLabel(now func() time.Time) *RuleDeprecatedRunnerLabel

NewRuleDeprecatedRunnerLabel creates a new RuleDeprecatedRunnerLabel instance. now returns the current time; nil means time.Now.

func (*RuleDeprecatedRunnerLabel) VisitJobPre Âķ added in v2.2.0

func (rule *RuleDeprecatedRunnerLabel) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleDuplicateTriggers Âķ

type RuleDuplicateTriggers struct {
	RuleBase
}

RuleDuplicateTriggers reports workflows that run twice for a commit pushed to a branch with an open pull request: they are triggered by `push` and by `pull_request` and `push` has no branch filter.

func NewRuleDuplicateTriggers Âķ

func NewRuleDuplicateTriggers() *RuleDuplicateTriggers

NewRuleDuplicateTriggers creates a new RuleDuplicateTriggers instance.

func (*RuleDuplicateTriggers) VisitWorkflowPre Âķ

func (rule *RuleDuplicateTriggers) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleEnv Âķ

type RuleEnv struct {
	// contains filtered or unexported fields
}

RuleEnv is what the constructors of the built-in rules need to create rule instances while linting one file. A factory registered with registerRuleFactory receives it.

func (*RuleEnv) Now Âķ added in v2.2.0

func (e *RuleEnv) Now() time.Time

Now returns the current time, which a rule that depends on a date (the retirement of a runner label) reads. It is time.Now unless LinterOptions.Now is set.

func (*RuleEnv) Skip Âķ

func (e *RuleEnv) Skip(reason string)

Skip reports with the debug log that the rule being created is disabled for the reason. A factory calls it and returns nil when the rule cannot be created (e.g. an external command is missing).

func (*RuleEnv) Source Âķ

func (e *RuleEnv) Source() []byte

Source returns the content of the file being linted. A rule which attaches a Fix needs it to turn the positions of the syntax tree into byte offsets. The slice must not be modified.

type RuleEnvVar Âķ

type RuleEnvVar struct {
	RuleBase
}

RuleEnvVar is a rule checker to check environment variables setup.

func NewRuleEnvVar Âķ

func NewRuleEnvVar() *RuleEnvVar

NewRuleEnvVar creates new RuleEnvVar instance.

func (*RuleEnvVar) VisitJobPre Âķ

func (rule *RuleEnvVar) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleEnvVar) VisitStep Âķ

func (rule *RuleEnvVar) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleEnvVar) VisitWorkflowPre Âķ

func (rule *RuleEnvVar) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleEnvironmentFileRedirect Âķ added in v2.2.0

type RuleEnvironmentFileRedirect struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleEnvironmentFileRedirect detects a `run:` script which writes to the environment files of the runner in a way that loses the data. It reports, with the one ID "environment-file-redirect":

  • a redirect or `tee` to the bare word GITHUB_OUTPUT, GITHUB_ENV, GITHUB_PATH, GITHUB_STEP_SUMMARY or GITHUB_STATE (`echo "a=b" >> GITHUB_OUTPUT`). The word is a file name, not the variable, so the shell writes a file of that name in the working directory and the runner never sees it: the output, the variable or the path is silently missing. The fix writes `"$GITHUB_OUTPUT"`.
  • a `>` (or `tee` without `-a`) to the file of one of them after the same script has already written to it: `>` truncates the file, so what the script wrote before is lost. Each step gets new files, so a lone `>` is harmless and is not reported. The fix (unsafe, because the reset may be meant) writes `>>`.

PowerShell (`$env:GITHUB_OUTPUT`) and cmd (`%GITHUB_OUTPUT%`) scripts are not analyzed.

func NewRuleEnvironmentFileRedirect Âķ added in v2.2.0

func NewRuleEnvironmentFileRedirect(src []byte) *RuleEnvironmentFileRedirect

NewRuleEnvironmentFileRedirect creates a new RuleEnvironmentFileRedirect instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleEnvironmentFileRedirect) VisitJobPost Âķ added in v2.2.0

func (rule *RuleEnvironmentFileRedirect) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleEnvironmentFileRedirect) VisitJobPre Âķ added in v2.2.0

func (rule *RuleEnvironmentFileRedirect) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleEnvironmentFileRedirect) VisitStep Âķ added in v2.2.0

func (rule *RuleEnvironmentFileRedirect) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleEnvironmentFileRedirect) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleEnvironmentFileRedirect) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleEventNameNeverReceived Âķ added in v2.2.0

type RuleEventNameNeverReceived struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleEventNameNeverReceived detects a comparison of `github.event_name` with the name of an event that the workflow never receives, which is always false:

on: [push, workflow_dispatch]
jobs:
  deploy:
    if: github.event_name == 'pull_request'   # never true

The job or the step never runs, or the comparison is a dead branch of a larger expression: a wrong trigger, a typo in the name of the event, or code which is left over from a trigger that was removed. It also reports two different events that must both be equal to the event of the run (`github.event_name == 'push' && github.event_name == 'pull_request'`).

Only a workflow whose events are all known is looked at: one with `workflow_call` is skipped (the event is the one of its caller), and so is a composite action and a workflow with the internal event `image_version`. The names are compared without regard to case, as GitHub compares strings. `!=` and the other ways to test the event (`contains`, a `switch` by a matrix) are not looked at.

func NewRuleEventNameNeverReceived Âķ added in v2.2.0

func NewRuleEventNameNeverReceived(src []byte) *RuleEventNameNeverReceived

NewRuleEventNameNeverReceived creates a new RuleEventNameNeverReceived instance. The source of the file makes the positions exact in values that span several lines. It can be nil.

func (*RuleEventNameNeverReceived) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleEventNameNeverReceived) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleEvents Âķ

type RuleEvents struct {
	RuleBase
}

RuleEvents is a rule to check 'on' field in workflow. https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows

func NewRuleEvents Âķ

func NewRuleEvents() *RuleEvents

NewRuleEvents creates new RuleEvents instance.

func (*RuleEvents) VisitWorkflowPre Âķ

func (rule *RuleEvents) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleExcessivePermissions Âķ

type RuleExcessivePermissions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleExcessivePermissions is a rule checker which reports write access that the GITHUB_TOKEN gets without a narrow need: `write-all`, `read-all`, and write scopes set at the workflow level, where every job inherits them. Write scopes on a job are the recommended way to grant access, so they are not reported, except `write-all` and `read-all`. When the workflow runs on a privileged trigger (pull_request_target, workflow_run and issue_comment) the message of a workflow-level write scope says so, since people without write access can start the workflow.

A job without any `permissions:` in a workflow without any is the business of the missing-permissions rule. The "require-workflow-permissions" option also reports a workflow without a top-level `permissions:`, even when its jobs set their own, so that the default permissions of the repository apply to no job added later. Unset, the option is on under the pedantic profile, like the pedantic persona of zizmor, which reports every workflow without a top-level `permissions:`. The finding is reported at the first key of the workflow (zizmor reports the start of the document), not at line 1, which a license header of comments would move away from it.

func NewRuleExcessivePermissions Âķ

func NewRuleExcessivePermissions() *RuleExcessivePermissions

NewRuleExcessivePermissions creates a new RuleExcessivePermissions instance.

func (*RuleExcessivePermissions) VisitJobPre Âķ

func (rule *RuleExcessivePermissions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleExcessivePermissions) VisitWorkflowPre Âķ

func (rule *RuleExcessivePermissions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleExpression Âķ

type RuleExpression struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleExpression is a rule checker to check expression syntax in string values of workflow syntax. It checks syntax and semantics of the expressions including type checks and functions/contexts definitions. For more details see - https://docs.github.com/en/actions/learn-github-actions/contexts - https://docs.github.com/en/actions/learn-github-actions/expressions

func NewRuleExpression Âķ

func NewRuleExpression(actionsCache *LocalActionsCache, workflowCache *LocalReusableWorkflowCache) *RuleExpression

NewRuleExpression creates new RuleExpression instance.

func (*RuleExpression) VisitJobPost Âķ

func (rule *RuleExpression) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children

func (*RuleExpression) VisitJobPre Âķ

func (rule *RuleExpression) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleExpression) VisitStep Âķ

func (rule *RuleExpression) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleExpression) VisitWorkflowPost Âķ

func (rule *RuleExpression) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children

func (*RuleExpression) VisitWorkflowPre Âķ

func (rule *RuleExpression) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleExpressionDelimiters Âķ added in v2.2.0

type RuleExpressionDelimiters struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleExpressionDelimiters detects text which is meant to be an expression but is not one, because its delimiters are wrong. GitHub expands `${{ }}` only. Everything else reaches the action, the environment variable or the condition as written, so the workflow does not do what its author meant and nothing says so.

It reports, with the one ID "malformed-expression-delimiters":

  • `${ github.ref }`: one brace instead of two. The fix writes `${{ github.ref }}`.
  • `$ {{ github.sha }}` and `${ { github.sha }}`: a space between the `$` and the braces. The fix removes it.
  • `{{ github.sha }}`: no `$`. The fix adds it.
  • with the option pedantic, `$HOME` and `${HOME}` in a `with:` value: no shell expands them there.

The first three are reported only when the text inside starts with the name of a context or a function of expressions, so that the templates of Go, Jinja and Helm (`{{ .Values.x }}`) and the shell syntax (`${VAR}`) are never reported. A `run:` script is never looked at: it is shell. The inputs which hold code (`script`, `command`, ...) are not looked at either, because the code may use `${...}` for itself.

func NewRuleExpressionDelimiters Âķ added in v2.2.0

func NewRuleExpressionDelimiters(src []byte) *RuleExpressionDelimiters

NewRuleExpressionDelimiters creates a new RuleExpressionDelimiters instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleExpressionDelimiters) VisitJobPre Âķ added in v2.2.0

func (rule *RuleExpressionDelimiters) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleExpressionDelimiters) VisitStep Âķ added in v2.2.0

func (rule *RuleExpressionDelimiters) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleExpressionDelimiters) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleExpressionDelimiters) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleFailFastActionInputs Âķ added in v2.2.0

type RuleFailFastActionInputs struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleFailFastActionInputs reports a step of an action which does not fail by default when the thing it exists for did not happen: `actions/upload-artifact` only warns when its `path` matches no file, `softprops/action-gh-release` publishes without the `files` that matched nothing, a test report action passes when it found no test result. The build is then green although it is broken, and nobody notices until the artifact or the release is needed. Each action has an input that makes it fail (the table of action_fail_fast.go); the finding asks for it.

It is in the pedantic profile: a missing file is sometimes fine, and nothing says which jobs it is for. A step which sets the input, with any value, has decided; a step (or a job, or a group of parallel steps) that can only run after a failure or a cancellation (`if: failure()`, `if: cancelled()`), which upload logs on a best effort basis, and a step with `continue-on-error` are not reported. A condition which is true after a success too (`always()`, `!cancelled()`, `!failure()`, `success() || failure()`) does not make a step best effort: a missing file would keep the job green.

The fix adds the input to the `with:` of the step, creating it when there is none. It is unsafe: a build that was green without the files fails with it, which is the point, but it changes what the workflow does.

func NewRuleFailFastActionInputs Âķ added in v2.2.0

func NewRuleFailFastActionInputs(src []byte) *RuleFailFastActionInputs

NewRuleFailFastActionInputs creates a new RuleFailFastActionInputs instance. The source of the file is needed to attach fixes. It can be nil, in which case findings carry no fix.

func (*RuleFailFastActionInputs) VisitJobPre Âķ added in v2.2.0

func (rule *RuleFailFastActionInputs) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleFailFastActionInputs) VisitWorkflowPost Âķ added in v2.2.0

func (rule *RuleFailFastActionInputs) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children. It verifies the fixes: the file must still be YAML with the input in the same step.

func (*RuleFailFastActionInputs) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleFailFastActionInputs) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleForbiddenUses Âķ

type RuleForbiddenUses struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleForbiddenUses is a rule to restrict the actions and reusable workflows a repository may use. With an "allow" list only the listed ones are accepted. With a "deny" list the listed ones are rejected. The rule does nothing without one of them.

The lists "images-allow" and "images-deny" do the same for container images: the image of `container:` and `services:`, of `uses: docker://` and of `docker run`, `docker create` and `docker pull` in a script.

func NewRuleForbiddenUses Âķ

func NewRuleForbiddenUses(allow, deny []string) *RuleForbiddenUses

NewRuleForbiddenUses creates a new RuleForbiddenUses instance from the patterns of the allow and deny lists. It returns nil when both lists are empty.

func (*RuleForbiddenUses) VisitJobPost Âķ added in v2.2.0

func (rule *RuleForbiddenUses) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleForbiddenUses) VisitJobPre Âķ

func (rule *RuleForbiddenUses) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleForbiddenUses) VisitStep Âķ added in v2.2.0

func (rule *RuleForbiddenUses) VisitStep(n *Step) error

VisitStep is callback when visiting Step node. It checks the images of `docker run` and the like in a script.

func (*RuleForbiddenUses) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleForbiddenUses) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGateJobSkippedOnFailure Âķ

type RuleGateJobSkippedOnFailure struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleGateJobSkippedOnFailure reports jobs that read the result of the jobs they need but are skipped by GitHub when one of them fails, so the check never sees a failure.

func NewRuleGateJobSkippedOnFailure Âķ

func NewRuleGateJobSkippedOnFailure() *RuleGateJobSkippedOnFailure

NewRuleGateJobSkippedOnFailure creates a new RuleGateJobSkippedOnFailure instance.

func (*RuleGateJobSkippedOnFailure) VisitJobPre Âķ

func (rule *RuleGateJobSkippedOnFailure) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleGateJobSkippedOnFailure) VisitWorkflowPre Âķ

func (rule *RuleGateJobSkippedOnFailure) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGhWithoutToken Âķ added in v2.2.0

type RuleGhWithoutToken struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleGhWithoutToken detects a `run:` script that runs the GitHub CLI when no token reaches the step.

In a workflow, gh refuses to run commands that talk to GitHub unless one of GH_TOKEN, GITHUB_TOKEN, GH_ENTERPRISE_TOKEN or GITHUB_ENTERPRISE_TOKEN is in its environment, and prints "set the GH_TOKEN environment variable". The runner image has gh, but does not set the token: `env: GH_TOKEN: ${{ github.token }}` does.

The rule is silent whenever it cannot be sure: a token variable named anywhere in the script, in the `env:` of the step, the job (and its container) or the workflow, or written to $GITHUB_ENV by an earlier step; an `env:` that is an expression; `gh auth ...`; a runner that is not shown to be GitHub-hosted (a self-hosted runner can be logged in already); a script that is not bash or sh.

func NewRuleGhWithoutToken Âķ added in v2.2.0

func NewRuleGhWithoutToken() *RuleGhWithoutToken

NewRuleGhWithoutToken creates a new RuleGhWithoutToken instance.

func (*RuleGhWithoutToken) VisitJobPost Âķ added in v2.2.0

func (rule *RuleGhWithoutToken) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleGhWithoutToken) VisitJobPre Âķ added in v2.2.0

func (rule *RuleGhWithoutToken) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleGhWithoutToken) VisitStep Âķ added in v2.2.0

func (rule *RuleGhWithoutToken) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleGhWithoutToken) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleGhWithoutToken) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGitHubApp Âķ

type RuleGitHubApp struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleGitHubApp is a rule checker which reports the ways of using actions/create-github-app-token that issue a token which is more powerful or lives longer than the job needs:

  • skip-token-revoke: true keeps the token valid after the job
  • owner without repositories gives the token access to every repository of the owner that has the app installed
  • no permission-* input gives the token every permission the app was granted

The same is checked, with their own inputs, for tibdex/github-app-token and peter-murray/workflow-application-token-action.

func NewRuleGitHubApp Âķ

func NewRuleGitHubApp() *RuleGitHubApp

NewRuleGitHubApp creates a new RuleGitHubApp instance.

func (*RuleGitHubApp) VisitStep Âķ

func (rule *RuleGitHubApp) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleGitHubApp) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleGitHubApp) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGitHubEnv Âķ

type RuleGitHubEnv struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleGitHubEnv detects dangerous writes to the files $GITHUB_ENV and $GITHUB_PATH in `run:` scripts.

What is written to $GITHUB_ENV becomes the environment of every later step of the job, so a value an outsider controls can set LD_PRELOAD or NODE_OPTIONS (a newline in the value is enough to add another variable) and run code. A directory added to $GITHUB_PATH can shadow the executables of the runner. The rule reports

  • "github-env": a write of a value that is not a literal in a workflow started by pull_request_target or workflow_run, which run with secrets and a write token while the event may come from a fork, and
  • a write of a value that is known to come from an outsider (an untrusted context or an environment variable holding one), whatever the trigger.

Scripts of bash and sh are analyzed with the run-script analyzer, scripts of pwsh, powershell and cmd by matching their lines.

The invariant Âķ

A value written to $GITHUB_ENV or $GITHUB_PATH is trusted if and only if, at the write, every variable it uses has a value that is provably harmless, where "the value of a variable" is decided in execution order by rule_github_env_flow.go (judgeVar) and the rest of the analysis stays conservative: whatever it cannot prove is untrusted.

  1. The value of a variable at the write is its LAST assignment (or read, or for-loop item) before the write. Only an unconditional one ends the search; one in a branch, a loop, a function, a pipeline or the right side of && and || may not have happened, so it counts together with what was there before it. `+=` adds to the value, so it counts together with the earlier value as well. A write in a loop also sees the assignments after it. Anything that can set a variable unseen (eval, source, printf -v, mapfile) makes it unknown.
  2. An assignment is trusted when its value is: a literal, a trusted source (the runner, a variable of the workflow that holds no outsider's input, a command with fixed output such as date), or a value made safe by a sanitizer, which means for $GITHUB_ENV that it cannot hold a newline, and for $GITHUB_PATH also that it holds no ".", "/" or ":": `tr -d '\n'`, `head -n 1`, `${v//[^a-z0-9]/}`, `sed 's/[^a-z0-9-]/-/g'`.
  3. A pipeline is trusted only if every stage after its last sanitizer is known to keep it (keepsSanitized): head, tail, sort, uniq, cut, rev, wc, tee, a deletion with tr, a translation or substitution whose parts are plain text. sed, tr, awk, printf, xargs and the like can write a newline back, so they do not count unless proven harmless.
  4. A test counts as validation (runscript.Guard) only when the script cannot go on unless the value passed it: `[[ v =~ ^re$ ]] || exit`, `[[ ! v =~ ^re$ ]] && exit`, `if [[ ! ... ]]; then exit; fi`, a bare `[[ ]]` under the default -e, or a `case` whose last branch is `*) exit`. The polarity must be right (a negated test whose failure is the way on proves nothing), the exit must be the exit of the script (not of a subshell), the test must be at the top level of the script or in the same `if`/`else` branch as the write (before it, and then only for the rest of that branch; not in loops or functions), and no assignment may follow it. The regular expression must be anchored and hold no character the destination cannot have.

Every case of the table in rule_github_env_flow_test.go names the clause it checks.

func NewRuleGitHubEnv Âķ

func NewRuleGitHubEnv() *RuleGitHubEnv

NewRuleGitHubEnv creates a new RuleGitHubEnv instance.

func (*RuleGitHubEnv) VisitJobPost Âķ

func (rule *RuleGitHubEnv) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleGitHubEnv) VisitJobPre Âķ

func (rule *RuleGitHubEnv) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleGitHubEnv) VisitStep Âķ

func (rule *RuleGitHubEnv) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleGitHubEnv) VisitWorkflowPre Âķ

func (rule *RuleGitHubEnv) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGithubScriptSyntax Âķ added in v2.2.0

type RuleGithubScriptSyntax struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleGithubScriptSyntax checks the JavaScript of the `script` input of actions/github-script for syntax errors with `node --check`.

The action runs the script as the body of an async function (`new AsyncFunction(...names, script)`), so `await` and `return` are allowed at the top level and the names of the arguments (`github`, `context`, `core`, ...) are taken: `const exec = require(...)` fails with "Identifier 'exec' has already been declared". The rule checks the script wrapped in the same way, with the arguments of the version of the action when the reference names one (see githubScriptArguments), and reports the first syntax error that node finds, at its place in the workflow.

It is careful not to report what the action would run:

  • An expression `${{ }}` is replaced by underscores of the same length, an identifier, which is valid where a value or a name can be. A script with an expression that spans lines, that follows a number, or that is not closed is not checked.
  • Only the syntax is checked: node does not run anything, so a missing module or an undefined variable is not an error.
  • It needs `node` (version 20 or later, so that newer syntax is not taken for an error) in the PATH. Without it the rule does nothing.

func NewRuleGithubScriptSyntax Âķ added in v2.2.0

func NewRuleGithubScriptSyntax(executable string, proc *concurrentProcess) (*RuleGithubScriptSyntax, error)

NewRuleGithubScriptSyntax creates a new RuleGithubScriptSyntax instance. The executable is node. When it is not found, an error is returned.

func (*RuleGithubScriptSyntax) VisitStep Âķ added in v2.2.0

func (rule *RuleGithubScriptSyntax) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleGithubScriptSyntax) VisitWorkflowPost Âķ added in v2.2.0

func (rule *RuleGithubScriptSyntax) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children.

type RuleGlob Âķ

type RuleGlob struct {
	RuleBase
}

RuleGlob is a rule to check glob syntax. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#filter-pattern-cheat-sheet

func NewRuleGlob Âķ

func NewRuleGlob() *RuleGlob

NewRuleGlob creates new RuleGlob instance.

func (*RuleGlob) VisitJobPre Âķ

func (rule *RuleGlob) VisitJobPre(n *Job) error

func (*RuleGlob) VisitWorkflowPre Âķ

func (rule *RuleGlob) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleGroup Âķ

type RuleGroup string

RuleGroup classifies a rule by what it protects against.

const (
	// RuleGroupCorrectness is for rules detecting mistakes which make a workflow fail or misbehave.
	RuleGroupCorrectness RuleGroup = "correctness"
	// RuleGroupSecurity is for rules detecting insecure constructs.
	RuleGroupSecurity RuleGroup = "security"
	// RuleGroupPolicy is for rules enforcing good practices which are not mistakes by themselves.
	RuleGroupPolicy RuleGroup = "policy"
	// RuleGroupStyle is for rules which only enforce a code style.
	RuleGroupStyle RuleGroup = "style"
)

type RuleID Âķ

type RuleID struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleID is a rule to check step IDs in workflow.

func NewRuleID Âķ

func NewRuleID() *RuleID

NewRuleID creates a new RuleID instance.

func (*RuleID) VisitJobPost Âķ

func (rule *RuleID) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleID) VisitJobPre Âķ

func (rule *RuleID) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleID) VisitStep Âķ

func (rule *RuleID) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleIfCond Âķ

type RuleIfCond struct {
	RuleBase
}

RuleIfCond is a rule to check if: conditions.

func NewRuleIfCond Âķ

func NewRuleIfCond() *RuleIfCond

NewRuleIfCond creates new RuleIfCond instance.

func (*RuleIfCond) VisitJobPre Âķ

func (rule *RuleIfCond) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleIfCond) VisitStep Âķ

func (rule *RuleIfCond) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleImpostorCommit Âķ

type RuleImpostorCommit struct {
	// contains filtered or unexported fields
}

RuleImpostorCommit reports an action pinned to a commit which is not part of the history of the repository itself. GitHub shares the commits of a repository and all its forks, so a commit which exists only in a fork can be addressed with the slug of the parent repository, and looks like any other hash-pinned action.

func NewRuleImpostorCommit Âķ

func NewRuleImpostorCommit(sess *onlineSession) *RuleImpostorCommit

NewRuleImpostorCommit creates a new RuleImpostorCommit instance.

func (*RuleImpostorCommit) VisitJobPre Âķ

func (r *RuleImpostorCommit) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleImpostorCommit) VisitStep Âķ

func (r *RuleImpostorCommit) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleImpostorCommit) VisitWorkflowPost Âķ

func (r *RuleImpostorCommit) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleImpostorCommit) VisitWorkflowPre Âķ

func (r *RuleImpostorCommit) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleInfo Âķ

type RuleInfo struct {
	// ID is the stable kebab-case identifier of the diagnostic, e.g. "unpinned-uses". It appears in
	// Error.ID, in the "rules" mapping of the configuration and in --ignore.
	ID string
	// Group is the category of the rule.
	Group RuleGroup
	// Summary is a one-line description of what the rule reports.
	Summary string
	// DefaultLevel is the severity of the rule when it is enabled without an explicit level.
	DefaultLevel Severity
	// Profile is the first profile which enables the rule. The empty value means that no profile
	// enables the rule; it only runs when the configuration turns it on.
	Profile Profile
	// Online is whether the rule needs the GitHub API. Online rules run only when the online checks are on
	// (--online, "online: true" in the configuration, or an online mode such as "cache" or "strict") and are
	// independent of the profile.
	Online bool
	// OptIn is whether the rule runs only when the "rules" of the configuration has an entry for it, whatever the profile and
	// the online checks are. A rule of a number of days, for example, is a decision of the project.
	OptIn bool
	// Fixable is whether the rule can attach an automatic fix (Error.Fix) to its findings.
	Fixable bool
	// DocsAnchor is the anchor of the section describing the rule in docs/checks.md. It can be empty.
	DocsAnchor string
	// Options are the options the rule accepts in the "rules" mapping of the configuration.
	Options []RuleOption
}

RuleInfo is the metadata of a rule. One rule implementation (a Rule, which is identified by the Kind of its errors) may report several IDs, and each ID has one RuleInfo. IDs are stable: they are never renamed or reused, so they are safe to put in configuration files, ignore comments and CI annotations.

func LookupRule Âķ

func LookupRule(id string) (RuleInfo, bool)

LookupRule returns the metadata of the rule with the given ID.

func Rules Âķ

func Rules() []RuleInfo

Rules returns the metadata of all rules sorted by ID. The returned slice is a copy.

func (*RuleInfo) DocURL Âķ

func (r *RuleInfo) DocURL() string

DocURL returns the URL of the documentation of the rule.

type RuleInsecureCommands Âķ

type RuleInsecureCommands struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleInsecureCommands is a rule to detect workflows which opt in to the deprecated workflow commands "set-env" and "add-path" by setting ACTIONS_ALLOW_UNSECURE_COMMANDS. Any process which can write to the output of a step can then inject environment variables, which leads to code execution. https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/

func NewRuleInsecureCommands Âķ

func NewRuleInsecureCommands(src []byte) *RuleInsecureCommands

NewRuleInsecureCommands creates a new RuleInsecureCommands instance. The source is used to put a fix on the errors. It can be empty.

func (*RuleInsecureCommands) VisitJobPre Âķ

func (rule *RuleInsecureCommands) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleInsecureCommands) VisitStep Âķ

func (rule *RuleInsecureCommands) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleInsecureCommands) VisitWorkflowPre Âķ

func (rule *RuleInsecureCommands) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleInsecureSSHKeyscan Âķ

type RuleInsecureSSHKeyscan struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleInsecureSSHKeyscan is a rule checker which reports `ssh-keyscan` output that a `run:` script writes to a known_hosts file. The scan trusts whatever key the server presents when the job runs (trust on first use), so anyone who can intercept the connection of the runner becomes the host in every later ssh, scp or rsync of the job. The host key has to come from somewhere that does not depend on the connection being scanned: a repository variable or secret with the verified key, or for GitHub the keys published in its documentation.

A script that prints the fingerprints of the scanned keys with `ssh-keygen -l` is assumed to compare them, and is not reported.

func NewRuleInsecureSSHKeyscan Âķ

func NewRuleInsecureSSHKeyscan() *RuleInsecureSSHKeyscan

NewRuleInsecureSSHKeyscan creates a new RuleInsecureSSHKeyscan instance.

func (*RuleInsecureSSHKeyscan) VisitJobPost Âķ

func (rule *RuleInsecureSSHKeyscan) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleInsecureSSHKeyscan) VisitJobPre Âķ

func (rule *RuleInsecureSSHKeyscan) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleInsecureSSHKeyscan) VisitStep Âķ

func (rule *RuleInsecureSSHKeyscan) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleInsecureSSHKeyscan) VisitWorkflowPre Âķ

func (rule *RuleInsecureSSHKeyscan) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleInsecureURLScheme Âķ

type RuleInsecureURLScheme struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleInsecureURLScheme is a rule checker which reports URLs with a scheme that sends data in the clear or without authenticating the server (`http://`, `ftp://` and `git://`) where a workflow fetches something from a remote host: the URLs that `curl`, `wget`, `git` and the package managers are given in a `run:` script, and inputs of actions in `with:` whose whole value is such a URL.

URLs of hosts that cannot be reached over the internet are not reported (loopback and private addresses, `localhost`, names without a dot such as the services of a job, and the reserved local domains), nor are URLs whose host is an expression or a variable. A proxy given to `curl`/`wget` and the XML namespaces of text are out of scope: only the location a command downloads from is checked.

There is no fix: whether the host serves the same content over HTTPS is not known.

func NewRuleInsecureURLScheme Âķ

func NewRuleInsecureURLScheme() *RuleInsecureURLScheme

NewRuleInsecureURLScheme creates a new RuleInsecureURLScheme instance.

func (*RuleInsecureURLScheme) VisitJobPost Âķ

func (rule *RuleInsecureURLScheme) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleInsecureURLScheme) VisitJobPre Âķ

func (rule *RuleInsecureURLScheme) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleInsecureURLScheme) VisitStep Âķ

func (rule *RuleInsecureURLScheme) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleInsecureURLScheme) VisitWorkflowPre Âķ

func (rule *RuleInsecureURLScheme) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleInsufficientPermissions Âķ added in v2.2.0

type RuleInsufficientPermissions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleInsufficientPermissions reports a step whose action (or command) needs a permission of the GITHUB_TOKEN that the explicit `permissions:` of its job do not grant. The step then fails with "Resource not accessible by integration" (an OIDC login: with no token to request), which is the failure of the first run in a repository that has just been locked down with `permissions:`.

It judges only what is certain. The permissions are those of the job, or of the workflow when the job sets none; a workflow without `permissions:` at both levels has the default of the repository, which is unknown here, so the rule says nothing (workflow-call-permissions makes the same choice for callers). A value that is an expression is not judged either. The needs come from the table of action_permissions.go, which lists only what the documentation of an action says. A step with another token than the GITHUB_TOKEN, `continue-on-error` or an `if: false` is skipped. The commands `gh release create` and `git push` are judged under the same conditions: the token of the command is the GITHUB_TOKEN of the job.

The need of actions/checkout for `contents: read` holds in private repositories only, so it is reported with the option pedantic.

func NewRuleInsufficientPermissions Âķ added in v2.2.0

func NewRuleInsufficientPermissions() *RuleInsufficientPermissions

NewRuleInsufficientPermissions creates a new RuleInsufficientPermissions instance.

func (*RuleInsufficientPermissions) VisitJobPost Âķ added in v2.2.0

func (rule *RuleInsufficientPermissions) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleInsufficientPermissions) VisitJobPre Âķ added in v2.2.0

func (rule *RuleInsufficientPermissions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleInsufficientPermissions) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleInsufficientPermissions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleJobNeeds Âķ

type RuleJobNeeds struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleJobNeeds is a rule to check 'needs' field in each job configuration. For more details, see https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idneeds

func NewRuleJobNeeds Âķ

func NewRuleJobNeeds() *RuleJobNeeds

NewRuleJobNeeds creates new RuleJobNeeds instance.

func (*RuleJobNeeds) VisitJobPre Âķ

func (rule *RuleJobNeeds) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleJobNeeds) VisitWorkflowPost Âķ

func (rule *RuleJobNeeds) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children.

type RuleKnownVulnerableActions Âķ

type RuleKnownVulnerableActions struct {
	// contains filtered or unexported fields
}

RuleKnownVulnerableActions reports actions whose version is affected by a published GitHub security advisory (GHSA) for the GitHub Actions ecosystem.

func NewRuleKnownVulnerableActions Âķ

func NewRuleKnownVulnerableActions(sess *onlineSession, allow []string) *RuleKnownVulnerableActions

NewRuleKnownVulnerableActions creates a new RuleKnownVulnerableActions instance. The advisories whose IDs are in allow are not reported.

func (*RuleKnownVulnerableActions) VisitJobPre Âķ

func (r *RuleKnownVulnerableActions) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleKnownVulnerableActions) VisitStep Âķ

func (r *RuleKnownVulnerableActions) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleKnownVulnerableActions) VisitWorkflowPost Âķ

func (r *RuleKnownVulnerableActions) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleKnownVulnerableActions) VisitWorkflowPre Âķ

func (r *RuleKnownVulnerableActions) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleLocalActionCheckout Âķ

type RuleLocalActionCheckout struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleLocalActionCheckout is a rule to check that a local action (`uses: ./path`) is not used before the repository is checked out in the same job. This rule is opt-in and enabled by the "require-checkout-before-local-action" configuration.

func NewRuleLocalActionCheckout Âķ

func NewRuleLocalActionCheckout() *RuleLocalActionCheckout

NewRuleLocalActionCheckout creates a new RuleLocalActionCheckout instance.

func (*RuleLocalActionCheckout) VisitJobPre Âķ

func (rule *RuleLocalActionCheckout) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleLocalActionCheckout) VisitStep Âķ

func (rule *RuleLocalActionCheckout) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleMacosGnuFlags Âķ added in v2.2.0

type RuleMacosGnuFlags struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleMacosGnuFlags reports options of the commands in `run:` scripts that exist in the GNU version of the command and not in the BSD one that macOS has, in a job that runs on macOS.

The runners of GitHub (and the machines of developers) have the BSD sed, grep, date, stat, find, cp and tee. They are rejected by the macOS command with a message such as `tee: illegal option -- -`, which a workflow tested only on Linux does not show until a macOS job is added to the matrix. Only forms are reported for which the sources of the commands that Apple publishes (apple-oss-distributions: shell_cmds, file_cmds and text_cmds) show that macOS fails:

  • `tee --append` (tee has only -a and -i, and no long option)
  • `sed -i` followed by the script: the option takes the next word as the suffix of the backup, so the script is taken for the suffix and the file for the script. `sed -i ”` or `sed -i.bak` is what BSD understands. Long options (`--in-place`) do not exist
  • `date -d` and `date --date` (date has no such option; BSD date reads a time with -f and -v)
  • `grep -P` and `grep --perl-regexp` (the options of the macOS grep have no P)
  • `stat -c` and `stat --format` (the format of BSD stat is -f)
  • `find -printf`, `-regextype` and `-xtype` (they are not in the table of primaries of find)
  • `cp --parents` (cp has no long options)

Forms that look as GNU-only and work on macOS are not reported: `xargs -r` (a no-op that BSD accepts for compatibility), `sort -V`, and `readlink -f` since macOS 12.3.

The job must run on macOS: a `runs-on` label with `macos`, or a matrix value of `runs-on: ${{ matrix.x }}` that is. A job on a self-hosted runner is not looked at (its owner can have installed the GNU tools), and neither is a command whose failure the script handles (`date -d ... || date -v ...`). A step is skipped when it may be meant for another system: its `if:` reads the runner or the matrix, or its script mentions the system or GNU tools (`RUNNER_OS`, `uname`, `gsed`, `brew`, ...).

func NewRuleMacosGnuFlags Âķ added in v2.2.0

func NewRuleMacosGnuFlags() *RuleMacosGnuFlags

NewRuleMacosGnuFlags creates a new RuleMacosGnuFlags instance.

func (*RuleMacosGnuFlags) VisitJobPost Âķ added in v2.2.0

func (rule *RuleMacosGnuFlags) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleMacosGnuFlags) VisitJobPre Âķ added in v2.2.0

func (rule *RuleMacosGnuFlags) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleMacosGnuFlags) VisitStep Âķ added in v2.2.0

func (rule *RuleMacosGnuFlags) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleMacosGnuFlags) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleMacosGnuFlags) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleMatrix Âķ

type RuleMatrix struct {
	RuleBase
}

RuleMatrix is a rule checker to check 'matrix' field of job.

func NewRuleMatrix Âķ

func NewRuleMatrix() *RuleMatrix

NewRuleMatrix creates new RuleMatrix instance.

func (*RuleMatrix) VisitJobPre Âķ

func (rule *RuleMatrix) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleMisfeature Âķ

type RuleMisfeature struct {
	RuleBase
}

RuleMisfeature is a rule to find usages of features which GitHub Actions has but nobody should rely on: the pip-install input of actions/setup-python, the Windows cmd shell and shells which are not documented by GitHub.

func NewRuleMisfeature Âķ

func NewRuleMisfeature() *RuleMisfeature

NewRuleMisfeature creates a new RuleMisfeature instance.

func (*RuleMisfeature) VisitJobPre Âķ

func (rule *RuleMisfeature) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleMisfeature) VisitStep Âķ

func (rule *RuleMisfeature) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleMisfeature) VisitWorkflowPre Âķ

func (rule *RuleMisfeature) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleMissingVersionComment Âķ added in v2.2.0

type RuleMissingVersionComment struct {
	// contains filtered or unexported fields
}

RuleMissingVersionComment reports an action or reusable workflow pinned to a commit SHA without a comment that names its version ("uses: actions/checkout@<sha> # v4.2.2"). Dependabot and Renovate read the comment to know which release the pin is and to keep it up to date, and a reviewer cannot tell what a bare SHA is. This is the part of the zizmor audit ref-version-mismatch which is about a missing comment; the comment that does not match the commit is reported by the online rule of the same name.

It needs no network. With the online checks on, the finding carries a fix which adds the comment: the most specific version tag that points to the commit. The fix is safe because it only adds a comment.

func NewRuleMissingVersionComment Âķ added in v2.2.0

func NewRuleMissingVersionComment(sess *onlineSession, src []byte) *RuleMissingVersionComment

NewRuleMissingVersionComment creates a new RuleMissingVersionComment instance. sess (nil without the online checks) is used to find the version for the fix, and src (which can be nil) to attach it.

func (*RuleMissingVersionComment) VisitJobPre Âķ added in v2.2.0

func (r *RuleMissingVersionComment) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleMissingVersionComment) VisitStep Âķ added in v2.2.0

func (r *RuleMissingVersionComment) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleMissingVersionComment) VisitWorkflowPost Âķ added in v2.2.0

func (r *RuleMissingVersionComment) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleMissingVersionComment) VisitWorkflowPre Âķ added in v2.2.0

func (r *RuleMissingVersionComment) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleMultilinePlainRun Âķ added in v2.2.0

type RuleMultilinePlainRun struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleMultilinePlainRun detects a `run:` which is written as a plain or quoted scalar over several lines of the file without a block indicator, and whose lines look like separate commands:

  • run: echo "start" npm ci npm test

YAML folds the line breaks of such a scalar into spaces, so the shell runs one command, `echo "start" npm ci npm test`, and the steps after the first never happen. The block indicator `|` keeps the lines.

Wrapping a long single command over several lines is legitimate and common (`docker run --rm \` is not even needed: the fold joins the lines), so the rule reports only when a line starts with the name of a command which is not an argument of the command before it: the previous line does not end with an operator (`&&`, `|`, `\`, ...) and does not leave a quote or a bracket open, the command before it is not one that takes a command as an argument (`docker`, `ssh`, `sudo`, `xargs`, ...), and the line starts with a command of the list below, or with an assignment after a command that takes no assignments (`echo a` then `x=1`). A blank line of the scalar is a real line break in the value, so lines that are separated by one are not looked at.

The fix writes the scalar as a literal block (`run: |`) with one line of the scalar on each line. It is offered only when that is exact: the scalar is the plain value of a `run:` key written on the line of the key, there is no blank line, no comment and no escape in it, and nothing follows it on its last line.

func NewRuleMultilinePlainRun Âķ added in v2.2.0

func NewRuleMultilinePlainRun(src []byte) *RuleMultilinePlainRun

NewRuleMultilinePlainRun creates a new RuleMultilinePlainRun instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleMultilinePlainRun) VisitJobPost Âķ added in v2.2.0

func (rule *RuleMultilinePlainRun) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleMultilinePlainRun) VisitJobPre Âķ added in v2.2.0

func (rule *RuleMultilinePlainRun) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleMultilinePlainRun) VisitStep Âķ added in v2.2.0

func (rule *RuleMultilinePlainRun) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleMultilinePlainRun) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleMultilinePlainRun) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleMutableRunnerLabel Âķ

type RuleMutableRunnerLabel struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleMutableRunnerLabel reports GitHub-hosted runner labels that GitHub moves to newer images ("ubuntu-latest"). A job on such a label can break without any change in the repository.

func NewRuleMutableRunnerLabel Âķ

func NewRuleMutableRunnerLabel(src []byte) *RuleMutableRunnerLabel

NewRuleMutableRunnerLabel creates a new RuleMutableRunnerLabel instance. The source is used to attach a fix; it can be nil.

func (*RuleMutableRunnerLabel) VisitJobPre Âķ

func (rule *RuleMutableRunnerLabel) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleObfuscation Âķ

type RuleObfuscation struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleObfuscation is a rule to find obfuscated usages of GitHub Actions features, which work but are written in a way that makes other tools (and readers) miss what they do. It checks the path of uses: here and the expressions in RuleExpression.checkObfuscation.

func NewRuleObfuscation Âķ

func NewRuleObfuscation(src []byte) *RuleObfuscation

NewRuleObfuscation creates a new RuleObfuscation instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleObfuscation) VisitJobPre Âķ

func (rule *RuleObfuscation) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleObfuscation) VisitStep Âķ

func (rule *RuleObfuscation) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleOption Âķ

type RuleOption struct {
	// Name is the key of the option.
	Name string
	// Kind is the type of the option value.
	Kind RuleOptionKind
	// Default is the value used when the rule is enabled without the option. nil means that the rule
	// does nothing until the option is set.
	Default any
	// Summary describes the option.
	Summary string
	// Min is the smallest value of an int option, when it is not 0. It is checked when the configuration is read and is the
	// "minimum" of the JSON schema.
	Min int
	// Validate checks the value after it was normalized to the type of Kind. It can be nil.
	Validate func(v any) error
}

RuleOption describes one option which can be given to a rule in the "rules" mapping of the configuration file.

type RuleOptionKind Âķ

type RuleOptionKind string

RuleOptionKind is the type of the value of a rule option.

const (
	// RuleOptionInt is an option taking a non-negative integer.
	RuleOptionInt RuleOptionKind = "int"
	// RuleOptionNumber is an option taking a non-negative number.
	RuleOptionNumber RuleOptionKind = "number"
	// RuleOptionBool is an option taking true or false.
	RuleOptionBool RuleOptionKind = "bool"
	// RuleOptionStringMap is an option taking a mapping from strings to strings.
	RuleOptionStringMap RuleOptionKind = "string-map"
	// RuleOptionStrings is an option taking a list of strings.
	RuleOptionStrings RuleOptionKind = "strings"
)

type RuleOutputClobbering Âķ added in v2.2.0

type RuleOutputClobbering struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleOutputClobbering detects input that an outsider controls and that is written to $GITHUB_OUTPUT in a way that lets it end the record and add others.

The file is read line by line. `name=value` sets an output, and a value that holds a newline ends the record: the rest is read as the next one. A comment with `x\napproved=true` writes `approved=true` after the `approved=false` that the step wrote on purpose, and the later `if: steps.check.outputs.approved == 'true'` believes it. The multi-line form `name<<DELIMITER` ... `DELIMITER` has the same flaw when the delimiter is a constant, because the value can hold the delimiter on a line of its own: the one thing that makes the form safe is a delimiter that nobody can guess (`$(uuidgen)`). See CodeQL's actions/output-clobbering/high.

The rule judges what is written with the data flow of github-env (rule_github_env.go): the value of a variable is its last assignment, a value that was validated or cut down to one line is trusted. What differs:

  • only input that can hold a line break counts: the title of an issue, a branch name or the name of an author is one line, a body, a comment or a commit message is not;
  • the step needs an `id` and the job (or, in an action, its outputs) must read an output of the step other than the one that is written, as `steps.id.outputs.approved`: the attacker can only change what is read. A step with one output that nothing else reads is not reported;
  • `inputs.*` of a composite action does not count (an action can pass its input on as an output on purpose).

func NewRuleOutputClobbering Âķ added in v2.2.0

func NewRuleOutputClobbering() *RuleOutputClobbering

NewRuleOutputClobbering creates a new RuleOutputClobbering instance.

func (*RuleOutputClobbering) VisitJobPost Âķ added in v2.2.0

func (rule *RuleOutputClobbering) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleOutputClobbering) VisitJobPre Âķ added in v2.2.0

func (rule *RuleOutputClobbering) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleOutputClobbering) VisitStep Âķ added in v2.2.0

func (rule *RuleOutputClobbering) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleOutputClobbering) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleOutputClobbering) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleOverprovisionedSecrets Âķ

type RuleOverprovisionedSecrets struct {
	RuleBase
}

RuleOverprovisionedSecrets is a rule to detect expressions which expose the whole "secrets" context instead of individual secrets, e.g. toJSON(secrets). Everything in the context is then passed to the runner, whether or not it is needed. https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions

func NewRuleOverprovisionedSecrets Âķ

func NewRuleOverprovisionedSecrets() *RuleOverprovisionedSecrets

NewRuleOverprovisionedSecrets creates a new RuleOverprovisionedSecrets instance.

func (*RuleOverprovisionedSecrets) VisitWorkflowPre Âķ

func (rule *RuleOverprovisionedSecrets) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleParallelSteps Âķ

type RuleParallelSteps struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleParallelSteps is a rule to check parallel steps: a 'wait' or 'cancel' step must refer to the ID of a preceding background step, and a 'parallel' group may only contain 'run' and 'uses' steps ('wait', 'wait-all', 'cancel', and nested 'parallel' steps are not allowed in it; 'background: true' is redundant there but accepted by GitHub, so it is not reported). https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/

func NewRuleParallelSteps Âķ

func NewRuleParallelSteps() *RuleParallelSteps

NewRuleParallelSteps creates a new RuleParallelSteps instance.

func (*RuleParallelSteps) VisitJobPost Âķ

func (rule *RuleParallelSteps) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleParallelSteps) VisitJobPre Âķ

func (rule *RuleParallelSteps) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleParallelSteps) VisitStep Âķ

func (rule *RuleParallelSteps) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RulePermissions Âķ

type RulePermissions struct {
	RuleBase
}

RulePermissions is a rule checker to check permission configurations in a workflow. https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#defining-access-for-the-github_token-scopes

func NewRulePermissions Âķ

func NewRulePermissions() *RulePermissions

NewRulePermissions creates new RulePermissions instance.

func (*RulePermissions) VisitJobPre Âķ

func (rule *RulePermissions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RulePermissions) VisitWorkflowPre Âķ

func (rule *RulePermissions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RulePipelineWithoutPipefail Âķ

type RulePipelineWithoutPipefail struct {
	RuleBase
	// contains filtered or unexported fields
}

RulePipelineWithoutPipefail is a rule to detect pipelines in "run:" scripts whose failures are hidden because the shell does not enable pipefail.

The default shell of Linux and macOS runners is `bash -e {0}`, and `shell: sh` is `sh -e {0}`. Without pipefail the exit status of `cmd1 | cmd2` is the one of `cmd2`, so when `cmd1` fails the step still succeeds. An explicit `shell: bash` runs `bash --noprofile --norc -eo pipefail {0}`, which does not have the problem.

A pipeline is reported when all of the following hold:

  • the shell has no pipefail: the default shell on a runner which is known not to be Windows (the default shell of Windows is pwsh), `shell: sh`, or a custom template for bash or sh without "pipefail" which turns errexit on (a template without errexit does not stop the step at the failure anyway). The shell is the one of the step, of "defaults.run.shell" of the job or of the workflow.
  • the script does not turn pipefail on before the pipeline (`set -o pipefail`, `set -eo pipefail`, `set -euxo pipefail`, `set -o errexit -o pipefail`, an assignment of SHELLOPTS with pipefail) or turns it off again with `set +o pipefail`.
  • a stage in front of the last one is a command whose failure matters. Commands which cannot meaningfully fail do not count (see pipefailNoFail, e.g. echo and printf, cat without a file, true and yes), and neither do filters in the middle of a pipeline (see pipefailFilters, e.g. sed and sort: the failure of what feeds them is reported at that command). Neither do grep, rg and diff anywhere: their non-zero status is an answer ("no match", "files differ"), and pipefail would turn an expected "no match" into a failed step.
  • the script does not handle the status itself: the pipeline is not negated with `!`, not the condition of `if`, `elif`, `while` or `until` and not an operand of `&&` or `||` other than the last one of a list, where `set -e` does not stop the script either. The commands of the first stages are held to the same rule, so `{ git notes show || true; cat note; } | sort` does not blame `git`.
  • no later stage stops reading early: `head`, `grep -q`, `grep -m`, `read`, `sed ...q` or `awk ... exit` make the producer die with SIGPIPE. Pipefail would then make a working pipeline fail, so enabling it is not a fix. Such pipelines are not reported at all.

The fix inserts `set -o pipefail` as the first line of a literal block script. It is unsafe because failures which were hidden now fail the step. There is no fix for `shell: sh` (dash has no pipefail), for custom shells other than bash and for scripts which are not a literal block (`run: cmd1 | cmd2`).

func NewRulePipelineWithoutPipefail Âķ

func NewRulePipelineWithoutPipefail(src []byte) *RulePipelineWithoutPipefail

NewRulePipelineWithoutPipefail creates a new RulePipelineWithoutPipefail instance. src is the content of the file, which is needed to attach fixes. It can be nil, then findings have no fix.

func (*RulePipelineWithoutPipefail) VisitJobPost Âķ

func (rule *RulePipelineWithoutPipefail) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RulePipelineWithoutPipefail) VisitJobPre Âķ

func (rule *RulePipelineWithoutPipefail) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RulePipelineWithoutPipefail) VisitStep Âķ

func (rule *RulePipelineWithoutPipefail) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RulePipelineWithoutPipefail) VisitWorkflowPre Âķ

func (rule *RulePipelineWithoutPipefail) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RulePyflakes Âķ

type RulePyflakes struct {
	RuleBase
	// contains filtered or unexported fields
}

RulePyflakes is a rule to check Python scripts at 'run:' using pyflakes. https://github.com/PyCQA/pyflakes

func NewRulePyflakes Âķ

func NewRulePyflakes(executable string, proc *concurrentProcess) (*RulePyflakes, error)

NewRulePyflakes creates new RulePyflakes instance. Parameter executable can be command name or relative/absolute file path. When the given executable is not found in system, it returns an error.

func NewRuleRuff Âķ added in v2.2.0

func NewRuleRuff(executable string, proc *concurrentProcess) (*RulePyflakes, error)

NewRuleRuff creates the rule for the Python scripts of "run:" which runs ruff (the pyflakes rules F of ruff) instead of pyflakes. It reports the same rule ID "pyflakes". The executable is the command name or the path of ruff.

func (*RulePyflakes) VisitJobPost Âķ

func (rule *RulePyflakes) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RulePyflakes) VisitJobPre Âķ

func (rule *RulePyflakes) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RulePyflakes) VisitStep Âķ

func (rule *RulePyflakes) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RulePyflakes) VisitWorkflowPost Âķ

func (rule *RulePyflakes) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children.

func (*RulePyflakes) VisitWorkflowPre Âķ

func (rule *RulePyflakes) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleRefConfusion Âķ

type RuleRefConfusion struct {
	// contains filtered or unexported fields
}

RuleRefConfusion reports an action pinned to a name which is both a branch and a tag of the repository. GitHub resolves such a name by its own rules, and whoever can create the second ref can change what runs in every workflow which uses the first.

func NewRuleRefConfusion Âķ

func NewRuleRefConfusion(sess *onlineSession) *RuleRefConfusion

NewRuleRefConfusion creates a new RuleRefConfusion instance.

func (*RuleRefConfusion) VisitJobPre Âķ

func (r *RuleRefConfusion) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleRefConfusion) VisitStep Âķ

func (r *RuleRefConfusion) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleRefConfusion) VisitWorkflowPost Âķ

func (r *RuleRefConfusion) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleRefConfusion) VisitWorkflowPre Âķ

func (r *RuleRefConfusion) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleRefVersionMismatch Âķ

type RuleRefVersionMismatch struct {
	// contains filtered or unexported fields
}

RuleRefVersionMismatch reports a hash-pinned action whose version comment names another version than the pinned commit is. Dependabot and Renovate keep the "# v4.2.2" comment of a pinned action up to date; a comment that went stale makes them skip it and misleads the readers.

With the source of the file the finding carries an unsafe fix, which rewrites the version in the comment to the tag of the pinned commit. It is unsafe because what the mismatch means is not known: the comment may be stale, or the SHA may be wrong (replaced by hand, or by an attacker). The commit is what runs, so the fix believes the commit, but a person has to confirm that is the one meant.

func NewRuleRefVersionMismatch Âķ

func NewRuleRefVersionMismatch(sess *onlineSession, src []byte) *RuleRefVersionMismatch

NewRuleRefVersionMismatch creates a new RuleRefVersionMismatch instance. The source of the file is needed to attach the fix, and can be nil.

func (*RuleRefVersionMismatch) VisitJobPre Âķ

func (r *RuleRefVersionMismatch) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleRefVersionMismatch) VisitStep Âķ

func (r *RuleRefVersionMismatch) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleRefVersionMismatch) VisitWorkflowPost Âķ

func (r *RuleRefVersionMismatch) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleRefVersionMismatch) VisitWorkflowPre Âķ

func (r *RuleRefVersionMismatch) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleRepojacking Âķ added in v2.2.0

type RuleRepojacking struct {
	// contains filtered or unexported fields
}

RuleRepojacking reports actions and reusable workflows of an owner whose name anyone can register: the owner does not exist (so the repository cannot either), or the repository has moved to another owner and the old name is free, so that GitHub only redirects until somebody registers the name and creates the repository again. The workflow then runs what that person published, with its token and secrets.

func NewRuleRepojacking Âķ added in v2.2.0

func NewRuleRepojacking(sess *onlineSession) *RuleRepojacking

NewRuleRepojacking creates a new RuleRepojacking instance.

func (*RuleRepojacking) VisitJobPre Âķ added in v2.2.0

func (r *RuleRepojacking) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleRepojacking) VisitStep Âķ added in v2.2.0

func (r *RuleRepojacking) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleRepojacking) VisitWorkflowPost Âķ added in v2.2.0

func (r *RuleRepojacking) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleRepojacking) VisitWorkflowPre Âķ added in v2.2.0

func (r *RuleRepojacking) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleRequirePermissions Âķ

type RuleRequirePermissions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleRequirePermissions is an opt-in rule checker which requires explicit `permissions:` configuration so that the GITHUB_TOKEN does not silently fall back to the repository/organization default (which may be read-write). It does nothing unless "require-permissions" is enabled in the config.

A job is accepted when the workflow has a top-level `permissions:` or the job has its own. Note that `permissions: {}` is an explicit configuration and is accepted. Jobs calling reusable workflows are checked in the same way since the caller determines the maximum permissions of the callee.

A workflow which runs only on workflow_call (a reusable workflow that nothing else triggers) is not checked: the caller decides what the token can do, and a callee that asks for more than its caller grants is rejected, so no value written in the callee is right for every caller. A workflow which has workflow_call and another event is also run directly, so it is still checked, and its finding has a fix which is always unsafe (see fixMissingPermissions) because the callers are not known; the message says so.

func NewRuleRequirePermissions Âķ

func NewRuleRequirePermissions() *RuleRequirePermissions

NewRuleRequirePermissions creates new RuleRequirePermissions instance.

func (*RuleRequirePermissions) VisitJobPre Âķ

func (rule *RuleRequirePermissions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleRequirePermissions) VisitWorkflowPre Âķ

func (rule *RuleRequirePermissions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleRequiredActions Âķ

type RuleRequiredActions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleRequiredActions implements a linting rule that checks for the presence and version of required GitHub Actions within workflows. It is enabled only when "required-actions" is configured in the config file.

func NewRuleRequiredActions Âķ

func NewRuleRequiredActions(required []RequiredActionRule) *RuleRequiredActions

NewRuleRequiredActions creates a new instance of RuleRequiredActions with the specified required actions. Returns nil if no required actions are provided.

func (*RuleRequiredActions) VisitWorkflowPre Âķ

func (rule *RuleRequiredActions) VisitWorkflowPre(workflow *Workflow) error

VisitWorkflowPre analyzes the workflow to ensure all required actions are present with correct versions. It reports errors for missing or mismatched versions.

type RuleRunPolicy Âķ

type RuleRunPolicy struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleRunPolicy is an opt-in rule to enforce style policies on 'run:' steps. It does nothing unless "require-shell" or "max-run-lines" is set in the configuration file.

  • "require-shell": every 'run:' step must have an explicit shell, either by 'shell:' of the step or by 'defaults.run.shell' of the job or the workflow. The default shell differs between 'bash -e {0}' (when the shell is omitted) and 'bash --noprofile --norc -eo pipefail {0}' (when 'shell: bash' is set).
  • "max-run-lines": a 'run:' script must not have more non-blank lines than the configured value.

func NewRuleRunPolicy Âķ

func NewRuleRunPolicy() *RuleRunPolicy

NewRuleRunPolicy creates a new RuleRunPolicy instance.

func (*RuleRunPolicy) VisitJobPost Âķ

func (rule *RuleRunPolicy) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleRunPolicy) VisitJobPre Âķ

func (rule *RuleRunPolicy) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleRunPolicy) VisitStep Âķ

func (rule *RuleRunPolicy) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleRunPolicy) VisitWorkflowPre Âķ

func (rule *RuleRunPolicy) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleRunnerLabel Âķ

type RuleRunnerLabel struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleRunnerLabel is a rule to check runner label like "ubuntu-latest". There are two types of runners, GitHub-hosted runner and Self-hosted runner. GitHub-hosted runner is described at https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners . And Self-hosted runner is described at https://docs.github.com/en/actions/hosting-your-own-runners/using-self-hosted-runners-in-a-workflow .

func NewRuleRunnerLabel Âķ

func NewRuleRunnerLabel() *RuleRunnerLabel

NewRuleRunnerLabel creates new RuleRunnerLabel instance.

func (*RuleRunnerLabel) VisitJobPre Âķ

func (rule *RuleRunnerLabel) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleSecretsInherit Âķ

type RuleSecretsInherit struct {
	RuleBase
}

RuleSecretsInherit is a rule to detect "secrets: inherit" at a job which calls a reusable workflow. It passes every secret of the caller to the called workflow, which breaks the principle of least privilege and makes it impossible to tell which secrets the called workflow receives. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idsecretsinherit

func NewRuleSecretsInherit Âķ

func NewRuleSecretsInherit() *RuleSecretsInherit

NewRuleSecretsInherit creates a new RuleSecretsInherit instance.

func (*RuleSecretsInherit) VisitJobPre Âķ

func (rule *RuleSecretsInherit) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleSecretsOutsideEnv Âķ

type RuleSecretsOutsideEnv struct {
	RuleBase
}

RuleSecretsOutsideEnv is a rule to detect secrets which are used by a job without an "environment:". Secrets of a repository or an organization are exposed to every job that asks for them, while the secrets of an environment are protected by the rules of the environment. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-deployments/managing-environments-for-deployment

func NewRuleSecretsOutsideEnv Âķ

func NewRuleSecretsOutsideEnv() *RuleSecretsOutsideEnv

NewRuleSecretsOutsideEnv creates a new RuleSecretsOutsideEnv instance.

func (*RuleSecretsOutsideEnv) VisitWorkflowPre Âķ

func (rule *RuleSecretsOutsideEnv) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleSelfHostedRunner Âķ

type RuleSelfHostedRunner struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleSelfHostedRunner is a rule to point out jobs which run on self-hosted runners: jobs with the "self-hosted" label, with a label that "self-hosted-runner.labels" of the configuration lists (a runner of an ARC runner set has no "self-hosted" label) and jobs in a runner group. Such runners are hard to secure and GitHub does not recommend them for public repositories. The rule is informational: it cannot tell how a runner is configured, and a custom label alone (for example one of a hosted runner provider) is not reported. https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#self-hosted-runner-security

func NewRuleSelfHostedRunner Âķ

func NewRuleSelfHostedRunner() *RuleSelfHostedRunner

NewRuleSelfHostedRunner creates a new RuleSelfHostedRunner instance.

func (*RuleSelfHostedRunner) VisitJobPre Âķ

func (rule *RuleSelfHostedRunner) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleSelfHostedRunner) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleSelfHostedRunner) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleSelfRepository Âķ

type RuleSelfRepository struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleSelfRepository is a rule checker which reports `uses: ./path` and prefers the self-repository form `uses: $/path`. Both name an action or a reusable workflow of the repository running the workflow. The workspace-relative form is looked up in the workspace at run time, where an earlier step can have put something else (for instance a checkout of another ref or repository), and it cannot be told apart from an arbitrary directory by a policy that requires pinning. The `$/` form always resolves to the commit that runs the workflow.

The fix is unsafe: `$/` is newer syntax which needs runner 2.336.0 or newer and which actionlint 1.7.12 and older reject (the repository then fails the other linter), and when a step replaces the workspace with another checkout `./` and `$/` are not the same code.

func NewRuleSelfRepository Âķ

func NewRuleSelfRepository(src []byte) *RuleSelfRepository

NewRuleSelfRepository creates a new RuleSelfRepository instance. The source of the file is needed to attach fixes. It can be nil, in which case findings carry no fix.

func (*RuleSelfRepository) VisitJobPre Âķ

func (rule *RuleSelfRepository) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleSelfRepository) VisitStep Âķ

func (rule *RuleSelfRepository) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

type RuleShellName Âķ

type RuleShellName struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleShellName is a rule to check 'shell' field. For more details, see https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#using-a-specific-shell

func NewRuleShellName Âķ

func NewRuleShellName() *RuleShellName

NewRuleShellName creates new RuleShellName instance.

func (*RuleShellName) VisitJobPost Âķ

func (rule *RuleShellName) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleShellName) VisitJobPre Âķ

func (rule *RuleShellName) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleShellName) VisitStep Âķ

func (rule *RuleShellName) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleShellName) VisitWorkflowPre Âķ

func (rule *RuleShellName) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleShellSyntax Âķ added in v2.2.0

type RuleShellSyntax struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleShellSyntax reports a syntax error in the script of a "run:" step without running shellcheck. The script is parsed with the bash parser of mvdan.cc/sh, offline, and only a genuine syntax error is reported (an unclosed quote, a missing "fi" or "done", an unexpected token). It is the part of shellcheck that needs no installation (zizmor#2322).

The rule is silent when:

  • shellcheck runs. It reports the same mistakes with its SC1xxx codes, and a second finding for the same line is noise. The rule is for runs where shellcheck was not found, was turned off with an empty command, or where the "shellcheck" rule is switched off in the configuration.
  • the shell is not bash or sh. Only these two names (and a custom template that starts with one of them, such as "bash -el {0}") are read; pwsh, powershell, cmd, python and every other custom shell are not parsed at all. A step without "shell:" is read only when the runner is known to be Linux or macOS: the default shell of a Windows runner is pwsh, and a runner chosen with an expression can be one.
  • the script is not read faithfully: it has a carriage return, or the parser stops at a construct of another shell instead of at a syntax error.

"sh" is read with the bash grammar, too, and reports only what is an error in bash. The /bin/sh of a runner is dash on Ubuntu but bash on macOS and Git Bash, so a script that is only valid in bash ("[[ ]]", arrays, process substitution) is not a syntax error of "shell: sh" on every runner, and the rule does not call it one.

${{ }} expressions are replaced by underscores of the same length before parsing (see sanitizeScriptExpressions: the end of an expression is found by the expression lexer, and a script with an expression that cannot be delimited is not read), so the offset of an error is also an offset of the script in the workflow.

func NewRuleShellSyntax Âķ added in v2.2.0

func NewRuleShellSyntax() *RuleShellSyntax

NewRuleShellSyntax creates a new RuleShellSyntax instance.

func (*RuleShellSyntax) VisitJobPost Âķ added in v2.2.0

func (rule *RuleShellSyntax) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleShellSyntax) VisitJobPre Âķ added in v2.2.0

func (rule *RuleShellSyntax) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleShellSyntax) VisitStep Âķ added in v2.2.0

func (rule *RuleShellSyntax) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleShellSyntax) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleShellSyntax) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleShellcheck Âķ

type RuleShellcheck struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleShellcheck is a rule to check shell scripts at 'run:' using shellcheck. https://github.com/koalaman/shellcheck

func NewRuleShellcheck Âķ

func NewRuleShellcheck(executable string, proc *concurrentProcess) (*RuleShellcheck, error)

NewRuleShellcheck creates new RuleShellcheck instance. The executable argument can be command name or relative/absolute file path. When the given executable is not found in system, it returns an error as 2nd return value.

func (*RuleShellcheck) VisitJobPost Âķ

func (rule *RuleShellcheck) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleShellcheck) VisitJobPre Âķ

func (rule *RuleShellcheck) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleShellcheck) VisitStep Âķ

func (rule *RuleShellcheck) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleShellcheck) VisitWorkflowPost Âķ

func (rule *RuleShellcheck) VisitWorkflowPost(n *Workflow) error

VisitWorkflowPost is callback when visiting Workflow node after visiting its children.

func (*RuleShellcheck) VisitWorkflowPre Âķ

func (rule *RuleShellcheck) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleStaleActionRefs Âķ

type RuleStaleActionRefs struct {
	// contains filtered or unexported fields
}

RuleStaleActionRefs reports an action pinned to a commit SHA that no tag of its repository points to. Such a commit is between releases: it may carry fixes or bugs which no changelog explains.

func NewRuleStaleActionRefs Âķ

func NewRuleStaleActionRefs(sess *onlineSession) *RuleStaleActionRefs

NewRuleStaleActionRefs creates a new RuleStaleActionRefs instance.

func (*RuleStaleActionRefs) VisitJobPre Âķ

func (r *RuleStaleActionRefs) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleStaleActionRefs) VisitStep Âķ

func (r *RuleStaleActionRefs) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleStaleActionRefs) VisitWorkflowPost Âķ

func (r *RuleStaleActionRefs) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleStaleActionRefs) VisitWorkflowPre Âķ

func (r *RuleStaleActionRefs) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleSuperfluousActions Âķ

type RuleSuperfluousActions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleSuperfluousActions detects steps that use an action which is known to do what the runner image can do without it. See superfluousActions for the table.

func NewRuleSuperfluousActions Âķ

func NewRuleSuperfluousActions() *RuleSuperfluousActions

NewRuleSuperfluousActions creates a new RuleSuperfluousActions instance.

func (*RuleSuperfluousActions) VisitJobPost Âķ

func (rule *RuleSuperfluousActions) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleSuperfluousActions) VisitJobPre Âķ

func (rule *RuleSuperfluousActions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleSuperfluousActions) VisitStep Âķ

func (rule *RuleSuperfluousActions) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleSuperfluousActions) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleSuperfluousActions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleTemplateInjection Âķ

type RuleTemplateInjection struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleTemplateInjection finds ${{ }} expansions in scripts which the check of the expression rule does not cover: objects which hold attacker controlled properties, environment variables which are set from attacker controlled properties, and every other expansion. Expansions of the properties which are known to be attacker controlled are reported by RuleExpression because it already checks every expression.

func NewRuleTemplateInjection Âķ

func NewRuleTemplateInjection(src []byte) *RuleTemplateInjection

NewRuleTemplateInjection creates a new RuleTemplateInjection instance. The source of the file lets the rule attach fixes to its findings. It can be nil.

func (*RuleTemplateInjection) VisitJobPost Âķ

func (rule *RuleTemplateInjection) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleTemplateInjection) VisitJobPre Âķ

func (rule *RuleTemplateInjection) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleTemplateInjection) VisitStep Âķ

func (rule *RuleTemplateInjection) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleTemplateInjection) VisitWorkflowPre Âķ

func (rule *RuleTemplateInjection) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleTimeoutCheck Âķ

type RuleTimeoutCheck struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleTimeoutCheck is a rule to check "timeout-minutes" of jobs. It is opt-in and configured by the "timeout-minutes" section of the configuration file. https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idtimeout-minutes

func NewRuleTimeoutCheck Âķ

func NewRuleTimeoutCheck() *RuleTimeoutCheck

NewRuleTimeoutCheck creates a new RuleTimeoutCheck instance.

func (*RuleTimeoutCheck) VisitJobPre Âķ

func (rule *RuleTimeoutCheck) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleTimeoutCheck) VisitWorkflowPre Âķ

func (rule *RuleTimeoutCheck) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleTyposquatUses Âķ

type RuleTyposquatUses struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleTyposquatUses is a rule to detect actions whose "owner/repo" is one typo away from a popular action of another owner, like "action/checkout" instead of "actions/checkout". An attacker can register the misspelled account and serve malicious code to everyone who copied the typo.

func NewRuleTyposquatUses Âķ

func NewRuleTyposquatUses(allow []string) *RuleTyposquatUses

NewRuleTyposquatUses creates a new RuleTyposquatUses instance. The slugs ("owner/repo") in allow are never reported.

func (*RuleTyposquatUses) VisitJobPre Âķ

func (rule *RuleTyposquatUses) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleUbuntuSlimLimits Âķ added in v2.2.0

type RuleUbuntuSlimLimits struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUbuntuSlimLimits reports what a job on ubuntu-slim cannot do. The runner runs the job inside an unprivileged container instead of a VM, which has no Docker daemon ("using Docker-in-Docker ... not supported"), and ends a job after 15 minutes. A job container, services and a Docker container action always fail; a timeout above 15 minutes is reported with the option pedantic only.

func NewRuleUbuntuSlimLimits Âķ added in v2.2.0

func NewRuleUbuntuSlimLimits(localActions *LocalActionsCache) *RuleUbuntuSlimLimits

NewRuleUbuntuSlimLimits creates a new RuleUbuntuSlimLimits instance. The cache of local actions can be nil.

func (*RuleUbuntuSlimLimits) VisitJobPre Âķ added in v2.2.0

func (rule *RuleUbuntuSlimLimits) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

type RuleUndocumentedPermissions Âķ

type RuleUndocumentedPermissions struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUndocumentedPermissions is a rule checker which requires a comment explaining why a permission scope of the GITHUB_TOKEN is granted above `read`. A scope is explained by a comment at the end of its line or by a block of comment lines directly above it. Comments which only configure a tool (such as an ignore comment) do not explain anything.

With the "include-read" option every scope is checked except `contents: read`, which everybody needs to check out the repository. Unset, the option is on under the pedantic profile, like the pedantic persona of zizmor, which asks for a comment on every read scope other than `contents: read`.

func NewRuleUndocumentedPermissions Âķ

func NewRuleUndocumentedPermissions() *RuleUndocumentedPermissions

NewRuleUndocumentedPermissions creates a new RuleUndocumentedPermissions instance.

func (*RuleUndocumentedPermissions) VisitJobPre Âķ

func (rule *RuleUndocumentedPermissions) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUndocumentedPermissions) VisitWorkflowPre Âķ

func (rule *RuleUndocumentedPermissions) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnlockedInstall Âķ

type RuleUnlockedInstall struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnlockedInstall detects installations in `run:` scripts that do not use a lock file. Without one, the dependencies are resolved anew on every run, so a new (or compromised) release of any transitive dependency reaches the workflow.

It reports, with the one ID "unlocked-install":

  • `cargo install` without --locked. The flag is the documented way to use the Cargo.lock that the crate was published with. This is the one finding that has a fix.
  • installs from a manifest that are not bound to the lock file of the repository: `npm install` instead of `npm ci`, `yarn install` without --immutable, `pnpm install --no-frozen-lockfile` and the same flag of `aube install` (pnpm and aube freeze the lock file by default in CI, so they are only reported with the flag). They are reported when the repository has the lock file (the project root, or the working-directory of the step, has package-lock.json, yarn.lock, pnpm-lock.yaml, or for aube any of those or aube-lock.yaml or bun.lock), because only then the lock file is being ignored. Without the lock file there is nothing to bind to.
  • with the option "pedantic", the same installs without a lock file in the repository, `bun install` without a frozen lock file, `pip install -r` without hashes or constraints, and npm, Yarn and bun installs that run the lifecycle scripts of the dependencies (see checkLifecycleScripts; for aube only the installs that allow every build), and installs of packages without a release-age cooldown (see checkReleaseAge).

func NewRuleUnlockedInstall Âķ

func NewRuleUnlockedInstall(src []byte, root string) *RuleUnlockedInstall

NewRuleUnlockedInstall creates a new RuleUnlockedInstall instance. The source is the content of the file; it is needed to build the fix and can be nil, in which case no fix is attached. The root is the root directory of the project, where the lock files are looked up; it can be empty.

func (*RuleUnlockedInstall) VisitJobPost Âķ

func (rule *RuleUnlockedInstall) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUnlockedInstall) VisitJobPre Âķ

func (rule *RuleUnlockedInstall) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnlockedInstall) VisitStep Âķ

func (rule *RuleUnlockedInstall) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleUnlockedInstall) VisitWorkflowPre Âķ

func (rule *RuleUnlockedInstall) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnmatchedPathsFilter Âķ added in v2.2.0

type RuleUnmatchedPathsFilter struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnmatchedPathsFilter reports an entry of `paths` or `paths-ignore` which matches no file of the repository.

GitHub starts a workflow for a push or a pull request only when a changed file matches an entry of `paths`. An entry whose path was renamed, moved or misspelled matches nothing, so the workflow does not start for the files that it was written for, and nothing says so. In `paths-ignore` such an entry ignores nothing.

The entries are matched against the files that git lists in the working tree (tracked, and untracked ones which are not ignored), or, when git cannot say, a walk of the project root (`.git`, node_modules and virtual environments excluded). The rule is conservative in what it calls a mismatch, because a false report would hide a real one:

  • it runs only when the file belongs to a project (not for stdin or a file outside a repository), and not for a generated file (unless the configuration reports them), whose entries come from another file;
  • an entry matches when it matches a file or a directory of the repository, in either case: GitHub does not say whether `docs` alone matches the files in it, so it is not called dead;
  • an entry starting with `!` is skipped (a negation that matches nothing changes nothing), and so is an entry that is invalid, contains `${{`, starts with `/` or `./`, or uses a form this rule cannot evaluate;
  • an entry in a git submodule that is not checked out is skipped, as is any entry that could match inside it;
  • a repository with more than pathsFilterMaxEntries files is not looked at.

func NewRuleUnmatchedPathsFilter Âķ added in v2.2.0

func NewRuleUnmatchedPathsFilter(root string) *RuleUnmatchedPathsFilter

NewRuleUnmatchedPathsFilter creates a new RuleUnmatchedPathsFilter instance for the project at root.

func (*RuleUnmatchedPathsFilter) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleUnmatchedPathsFilter) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnpinnableAction Âķ added in v2.2.0

type RuleUnpinnableAction struct {
	// contains filtered or unexported fields
}

RuleUnpinnableAction reports an action which a workflow pins to a commit SHA but whose own steps use an action by a tag or a branch, or a Docker image by a tag: the pin does not freeze what runs, because the action pulls in something which can change. It is the "unpinnable action" check of poutine.

func NewRuleUnpinnableAction Âķ added in v2.2.0

func NewRuleUnpinnableAction(sess *onlineSession) *RuleUnpinnableAction

NewRuleUnpinnableAction creates a new RuleUnpinnableAction instance.

func (*RuleUnpinnableAction) VisitJobPre Âķ added in v2.2.0

func (r *RuleUnpinnableAction) VisitJobPre(n *Job) error

VisitJobPre implements Pass.

func (*RuleUnpinnableAction) VisitStep Âķ added in v2.2.0

func (r *RuleUnpinnableAction) VisitStep(n *Step) error

VisitStep implements Pass.

func (*RuleUnpinnableAction) VisitWorkflowPost Âķ added in v2.2.0

func (r *RuleUnpinnableAction) VisitWorkflowPost(*Workflow) error

VisitWorkflowPost implements Pass.

func (*RuleUnpinnableAction) VisitWorkflowPre Âķ added in v2.2.0

func (r *RuleUnpinnableAction) VisitWorkflowPre(w *Workflow) error

VisitWorkflowPre implements Pass.

type RuleUnpinnedImages Âķ

type RuleUnpinnedImages struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnpinnedImages is a rule checker which reports container images of `container:` and `services:` that are not pinned by a digest. An image without a tag, or with the tag "latest", is the worst case: the registry decides what runs. A tag other than "latest" is mutable too, so it is reported unless the "require-digest" option is turned off.

An image given as `${{ matrix.name }}` is checked at the values the matrix writes for that name.

Docker images in `uses: docker://...` are checked by the unpinned-uses rule.

func NewRuleUnpinnedImages Âķ

func NewRuleUnpinnedImages() *RuleUnpinnedImages

NewRuleUnpinnedImages creates a new RuleUnpinnedImages instance.

func (*RuleUnpinnedImages) VisitJobPost Âķ added in v2.2.0

func (rule *RuleUnpinnedImages) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUnpinnedImages) VisitJobPre Âķ

func (rule *RuleUnpinnedImages) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnpinnedImages) VisitStep Âķ added in v2.2.0

func (rule *RuleUnpinnedImages) VisitStep(n *Step) error

VisitStep is callback when visiting Step node. It checks the images that `docker run`, `docker create` and `docker pull` (also of podman) use in a script.

func (*RuleUnpinnedImages) VisitWorkflowPre Âķ

func (rule *RuleUnpinnedImages) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children. It checks the "image" of a Docker action (action.yml), which is a registry image when it starts with "docker://" and a Dockerfile otherwise.

type RuleUnpinnedTools Âķ

type RuleUnpinnedTools struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnpinnedTools detects tools that are installed without an exact version.

"unpinned-tools" reports `uses:` steps of the actions in floatingToolActions that install the newest version of their tool because no version is set or the version is "latest". "unpinned-tools-pedantic" reports the further actions of that table that zizmor does not report, and `run:` steps that install or run a tool without an exact version: `pip install`, `pipx`, `uv tool`, `uvx`, `cargo install` and `cargo binstall`, `go install`, global `npm install -g` and `npx --yes`, `pnpm dlx`, `aube dlx` and the like.

func NewRuleUnpinnedTools Âķ

func NewRuleUnpinnedTools() *RuleUnpinnedTools

NewRuleUnpinnedTools creates a new RuleUnpinnedTools instance.

func (*RuleUnpinnedTools) VisitJobPost Âķ

func (rule *RuleUnpinnedTools) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUnpinnedTools) VisitJobPre Âķ

func (rule *RuleUnpinnedTools) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnpinnedTools) VisitStep Âķ

func (rule *RuleUnpinnedTools) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleUnpinnedTools) VisitWorkflowPre Âķ

func (rule *RuleUnpinnedTools) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnreachableRequiredCheck Âķ added in v2.5.0

type RuleUnreachableRequiredCheck struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnreachableRequiredCheck reports the trigger filters of a workflow which keep GitHub from starting the job that reports a check declared in "required-checks", so that the check stays pending (see required_checks.go). A declared name that no job reports is a problem of the declaration: the linter reports it in the config file at the end of the run (Linter.finishRequiredChecksRun).

func (*RuleUnreachableRequiredCheck) VisitWorkflowPre Âķ added in v2.5.0

func (rule *RuleUnreachableRequiredCheck) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnredactedSecrets Âķ

type RuleUnredactedSecrets struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnredactedSecrets is a rule to detect secrets which are parsed as structured data with fromJSON(), e.g. fromJSON(secrets.CREDENTIALS).password. The runner redacts the exact value of a secret from the logs, but not the fields which are extracted from it. https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#redacting-secrets

func NewRuleUnredactedSecrets Âķ

func NewRuleUnredactedSecrets() *RuleUnredactedSecrets

NewRuleUnredactedSecrets creates a new RuleUnredactedSecrets instance.

func (*RuleUnredactedSecrets) VisitJobPost Âķ added in v2.2.0

func (rule *RuleUnredactedSecrets) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUnredactedSecrets) VisitJobPre Âķ added in v2.2.0

func (rule *RuleUnredactedSecrets) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnredactedSecrets) VisitStep Âķ added in v2.2.0

func (rule *RuleUnredactedSecrets) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleUnredactedSecrets) VisitWorkflowPre Âķ

func (rule *RuleUnredactedSecrets) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnsoundContains Âķ

type RuleUnsoundContains struct {
	RuleBase
}

RuleUnsoundContains is a rule to detect conditions which use contains() with a string literal as the haystack. contains('refs/heads/main refs/heads/develop', github.ref) is also true for substrings such as a branch named "mai", so it cannot be used to check membership in a list. https://docs.github.com/en/actions/reference/workflows-and-actions/expressions#example-matching-an-array-of-strings

func NewRuleUnsoundContains Âķ

func NewRuleUnsoundContains() *RuleUnsoundContains

NewRuleUnsoundContains creates a new RuleUnsoundContains instance.

func (*RuleUnsoundContains) VisitWorkflowPre Âķ

func (rule *RuleUnsoundContains) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnsoundPrefixMatch Âķ

type RuleUnsoundPrefixMatch struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnsoundPrefixMatch is a rule to find expressions which identify an account, an organization or a repository by a part of its name. startsWith(github.actor, 'jdx') is also true for "jdx-evil", endsWith(github.repository, '/mise') for a fork of any owner, and contains() for any name which has the text somewhere. Names are chosen by whoever registers them, so a partial match does not identify the owner of the name.

func NewRuleUnsoundPrefixMatch Âķ

func NewRuleUnsoundPrefixMatch(refs, botConditionOn bool) *RuleUnsoundPrefixMatch

NewRuleUnsoundPrefixMatch creates a new RuleUnsoundPrefixMatch instance. refs makes the rule check the names of branches and tags too.

func (*RuleUnsoundPrefixMatch) VisitWorkflowPre Âķ

func (rule *RuleUnsoundPrefixMatch) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUntrustedArtifact Âķ

type RuleUntrustedArtifact struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUntrustedArtifact reports workflow_run workflows that download an artifact of the run that triggered them and then run it, extract it or put its content in the environment of later steps without checking it. The workflow that made the artifact runs the code of a pull request, so the artifact is whatever the author of the pull request wanted it to be.

func NewRuleUntrustedArtifact Âķ

func NewRuleUntrustedArtifact(project *Project) *RuleUntrustedArtifact

NewRuleUntrustedArtifact creates a new RuleUntrustedArtifact instance. The project can be nil.

func (*RuleUntrustedArtifact) VisitJobPre Âķ

func (rule *RuleUntrustedArtifact) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUntrustedArtifact) VisitWorkflowPre Âķ

func (rule *RuleUntrustedArtifact) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUntrustedCheckout Âķ

type RuleUntrustedCheckout struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUntrustedCheckout reports pull_request_target and workflow_run workflows that check out the code of a pull request (or of the run that triggered the workflow) and then run it. Those events run with a write token and with secrets, so whoever opened the pull request can use them.

func NewRuleUntrustedCheckout Âķ

func NewRuleUntrustedCheckout(project *Project) *RuleUntrustedCheckout

NewRuleUntrustedCheckout creates a new RuleUntrustedCheckout instance. The project can be nil.

func (*RuleUntrustedCheckout) VisitJobPre Âķ

func (rule *RuleUntrustedCheckout) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUntrustedCheckout) VisitWorkflowPre Âķ

func (rule *RuleUntrustedCheckout) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnusedJobOutput Âķ

type RuleUnusedJobOutput struct {
	RuleBase
}

RuleUnusedJobOutput reports job outputs that nothing reads: no job reads them through the needs context and no output of a reusable workflow uses them through the jobs context.

func NewRuleUnusedJobOutput Âķ

func NewRuleUnusedJobOutput() *RuleUnusedJobOutput

NewRuleUnusedJobOutput creates a new RuleUnusedJobOutput instance.

func (*RuleUnusedJobOutput) VisitWorkflowPre Âķ

func (rule *RuleUnusedJobOutput) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnusedNeeds Âķ

type RuleUnusedNeeds struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnusedNeeds reports entries of `needs` that do nothing: the job never reads the outputs or the result of the needed job and another needed job already depends on it, so the entry changes neither the order nor whether the job runs.

An entry that is only there for the order is not reported, because the rule cannot tell it from an entry that was forgotten.

func NewRuleUnusedNeeds Âķ

func NewRuleUnusedNeeds() *RuleUnusedNeeds

NewRuleUnusedNeeds creates a new RuleUnusedNeeds instance.

func (*RuleUnusedNeeds) VisitJobPre Âķ

func (rule *RuleUnusedNeeds) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnusedNeeds) VisitWorkflowPre Âķ

func (rule *RuleUnusedNeeds) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnusedWorkflowInput Âķ

type RuleUnusedWorkflowInput struct {
	RuleBase
}

RuleUnusedWorkflowInput reports inputs of workflow_dispatch and workflow_call that the workflow never reads.

func NewRuleUnusedWorkflowInput Âķ

func NewRuleUnusedWorkflowInput() *RuleUnusedWorkflowInput

NewRuleUnusedWorkflowInput creates a new RuleUnusedWorkflowInput instance.

func (*RuleUnusedWorkflowInput) VisitWorkflowPre Âķ

func (rule *RuleUnusedWorkflowInput) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnusedWorkflowSecret Âķ added in v2.2.0

type RuleUnusedWorkflowSecret struct {
	RuleBase
}

RuleUnusedWorkflowSecret reports secrets that a reusable workflow declares in "on.workflow_call.secrets" and never reads: the sibling of unused-workflow-input. Every caller has to pass a required secret, and an optional one is passed for nothing, so an unused one hands a credential to a workflow that does not need it.

func NewRuleUnusedWorkflowSecret Âķ added in v2.2.0

func NewRuleUnusedWorkflowSecret() *RuleUnusedWorkflowSecret

NewRuleUnusedWorkflowSecret creates a new RuleUnusedWorkflowSecret instance.

func (*RuleUnusedWorkflowSecret) VisitWorkflowPre Âķ added in v2.2.0

func (rule *RuleUnusedWorkflowSecret) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUnverifiedDownload Âķ

type RuleUnverifiedDownload struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUnverifiedDownload is a rule checker which reports code that a `run:` script downloads and runs without checking it:

  • a download piped into a shell or an interpreter (`curl ... | sh`, `wget -O- ... | sudo bash`, `bash <(curl ...)`, `sh -c "$(curl ...)"`, `curl ... | python3 -`);
  • a downloaded file that the same script makes executable or runs (or installs with dpkg, rpm or apt) without a checksum or signature check in between;
  • a download made with TLS certificate verification turned off.

A pipe into a program that is not an interpreter (`curl ... | tar -x`, `| jq`) is not reported. Neither is a URL that names a full git commit (`raw.githubusercontent.com/o/r/<sha>/install.sh`), because the URL itself fixes the content, a loopback or private host, or a URL accepted by the "allow" option.

func NewRuleUnverifiedDownload Âķ

func NewRuleUnverifiedDownload() *RuleUnverifiedDownload

NewRuleUnverifiedDownload creates a new RuleUnverifiedDownload instance.

func (*RuleUnverifiedDownload) VisitJobPost Âķ

func (rule *RuleUnverifiedDownload) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUnverifiedDownload) VisitJobPre Âķ

func (rule *RuleUnverifiedDownload) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUnverifiedDownload) VisitStep Âķ

func (rule *RuleUnverifiedDownload) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleUnverifiedDownload) VisitWorkflowPre Âķ

func (rule *RuleUnverifiedDownload) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleUseTrustedPublishing Âķ

type RuleUseTrustedPublishing struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleUseTrustedPublishing detects packaging workflows that publish with a long-lived credential although the registry supports trusted publishing, an OIDC based tokenless authentication.

It reports `run:` steps with a publish command (`twine upload`, `uv publish`, `cargo publish`, `npm publish`, `gem push`, `dotnet nuget push`, ...) in a job that cannot request an OIDC token (`id-token: write`), and the steps of the well known publishing actions that are given a password or token. Publishing to another registry than the public one, and dry runs, are not reported.

func NewRuleUseTrustedPublishing Âķ

func NewRuleUseTrustedPublishing() *RuleUseTrustedPublishing

NewRuleUseTrustedPublishing creates a new RuleUseTrustedPublishing instance.

func (*RuleUseTrustedPublishing) VisitJobPost Âķ

func (rule *RuleUseTrustedPublishing) VisitJobPost(n *Job) error

VisitJobPost is callback when visiting Job node after visiting its children.

func (*RuleUseTrustedPublishing) VisitJobPre Âķ

func (rule *RuleUseTrustedPublishing) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleUseTrustedPublishing) VisitStep Âķ

func (rule *RuleUseTrustedPublishing) VisitStep(n *Step) error

VisitStep is callback when visiting Step node.

func (*RuleUseTrustedPublishing) VisitWorkflowPre Âķ

func (rule *RuleUseTrustedPublishing) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleWorkflowCall Âķ

type RuleWorkflowCall struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleWorkflowCall is a rule checker to check workflow call at jobs.<job_id>.

func NewRuleWorkflowCall Âķ

func NewRuleWorkflowCall(workflowPath string, cache *LocalReusableWorkflowCache) *RuleWorkflowCall

NewRuleWorkflowCall creates a new RuleWorkflowCall instance. 'workflowPath' is a file path to the workflow which is relative to a project root directory or an absolute path.

func (*RuleWorkflowCall) VisitJobPre Âķ

func (rule *RuleWorkflowCall) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children.

func (*RuleWorkflowCall) VisitWorkflowPre Âķ

func (rule *RuleWorkflowCall) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleWorkflowRun Âķ

type RuleWorkflowRun struct {
	RuleBase
	// contains filtered or unexported fields
}

RuleWorkflowRun is a rule to check workflow names specified at 'workflows' of 'workflow_run' event. The names must be the names of workflows existing in the same repository.

func NewRuleWorkflowRun Âķ

func NewRuleWorkflowRun(project *Project) *RuleWorkflowRun

NewRuleWorkflowRun creates a new RuleWorkflowRun instance. This rule is opt-in; it does nothing unless "check-workflow-run-names" is enabled in the config. The project parameter can be nil. In the case, this rule does nothing.

func (*RuleWorkflowRun) VisitWorkflowPre Âķ

func (rule *RuleWorkflowRun) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type RuleWorkflowSecretScope Âķ added in v2.1.0

type RuleWorkflowSecretScope struct {
	RuleBase
}

RuleWorkflowSecretScope is a rule to detect a secret which is assigned to the workflow-level "env:" and so is passed to the steps of every job, although only one job or step needs it. https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions

func NewRuleWorkflowSecretScope Âķ added in v2.1.0

func NewRuleWorkflowSecretScope() *RuleWorkflowSecretScope

NewRuleWorkflowSecretScope creates a new RuleWorkflowSecretScope instance.

func (*RuleWorkflowSecretScope) VisitJobPre Âķ added in v2.2.0

func (rule *RuleWorkflowSecretScope) VisitJobPre(n *Job) error

VisitJobPre is callback when visiting Job node before visiting its children. With the option "job-level" it reports a secret in the "env:" of a job, which every step of the job gets, third-party actions included (ghalint job_secrets, zizmor#1816).

func (*RuleWorkflowSecretScope) VisitWorkflowPre Âķ added in v2.1.0

func (rule *RuleWorkflowSecretScope) VisitWorkflowPre(n *Workflow) error

VisitWorkflowPre is callback when visiting Workflow node before visiting its children.

type Runner Âķ

type Runner struct {
	// Labels is list label names to select a runner to run a job. There are preset labels and user
	// defined labels. Runner matching to the labels is selected.
	Labels []*String
	// LabelsExpr is a string when expression syntax ${{ }} is used for this section. Related issue is #164.
	LabelsExpr *String
	// Group is a group of runners specified in runs-on: section. It is nil when no group is specified.
	// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#choosing-runners-in-a-group
	Group *String
}

Runner is struct for runner configuration. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idruns-on

type ScheduleEntry Âķ

type ScheduleEntry struct {
	// Cron is the cron string for the schedule.
	Cron *String
	// Timezone is the optional IANA timezone for the schedule.
	Timezone *String
}

ScheduleEntry is a single entry in a schedule event. https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#onschedule

type ScheduledEvent Âķ

type ScheduledEvent struct {
	// Schedules is list of schedule entries which schedule the workflow.
	Schedules []*ScheduleEntry
	// Pos is a position in source.
	Pos *Pos
}

ScheduledEvent is event scheduled by workflow. https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#scheduled-events

func (*ScheduledEvent) EventName Âķ

func (e *ScheduledEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type Service Âķ

type Service struct {
	// Name is name of the service.
	Name *String
	// Container is configuration of container which runs the service.
	Container *Container
}

Service is configuration to run a service like database. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idservices

type Services Âķ

type Services struct {
	// Value is a mapping from service ID to its Service instances. Keys are in lower case since
	// they are case-insensitive.
	Value map[string]*Service
	// Expression is an expression assigned to the services mapping by ${{ }} placeholder. Otherwise
	// this field is nil.
	Expression *String
	// Pos is a position in source.
	Pos *Pos
}

Services is a mapping from service ID to its configuration. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idservices

type Severity Âķ

type Severity int

Severity is how serious a finding is. The zero value SeverityOff means a rule is disabled; no reported Error has this severity.

const (
	// SeverityOff disables a rule. It is only meaningful as a configured level.
	SeverityOff Severity = iota
	// SeverityInfo is for findings which are worth knowing but never fail a run.
	SeverityInfo
	// SeverityWarning is for findings which should be fixed but do not fail a run unless --strict-exit
	// is given.
	SeverityWarning
	// SeverityError is for findings which fail a run.
	SeverityError
)

func ParseSeverity Âķ

func ParseSeverity(s string) (Severity, error)

ParseSeverity parses "off", "info", "warn" (or "warning") and "error".

func (Severity) MarshalText Âķ

func (s Severity) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler. JSON output uses the same names as the configuration.

func (Severity) String Âķ

func (s Severity) String() string

String returns the name used in configuration files and on the command line: "off", "info", "warn" or "error".

func (*Severity) UnmarshalText Âķ

func (s *Severity) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler. It accepts the names of ParseSeverity.

func (*Severity) UnmarshalYAML Âķ

func (s *Severity) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type ShellcheckConfig Âķ added in v2.2.0

type ShellcheckConfig struct {
	// RCFile is the shellcheckrc file to use instead of --norc. A relative path is resolved from the root of the
	// repository (the directory which has ".github"); the --shellcheck-rcfile flag, which is resolved from the
	// working directory, overrides it. The file must exist. A config file which is not the user's own (the one of the
	// repository) can name only a file inside the repository.
	RCFile string `yaml:"rcfile"`
	// Args are more arguments for shellcheck, such as "--exclude=SC2129" or "--severity=warning".
	// jactionlint sets the output format, the shell, the external sources and the script on its own, so
	// the options which would change them are errors.
	Args []string `yaml:"args"`
	// Enable lists the optional checks of shellcheck to turn on (shellcheck --enable=NAME,...), for example
	// "avoid-nullary-conditions" or "all".
	Enable []string `yaml:"enable"`
}

ShellcheckConfig is the "shellcheck" mapping of the config file. It tunes how jactionlint runs shellcheck for the scripts of "run:" steps. Without it jactionlint runs shellcheck with --norc, so that the .shellcheckrc of the directory that happens to be the working directory cannot change the results, and with the arguments it needs.

The environment variable SHELLCHECK_OPTS is still read by shellcheck itself. These keys are for the places where it cannot be set, such as pre-commit.ci, and for keeping the settings in the repository.

type Snapshot Âķ

type Snapshot struct {
	// ImageName is a name of the custom image.
	ImageName *String
	// Version is a version of the custom image.
	Version *String
	// If is a condition whether the custom image is used.
	If *String
}

Snapshot is a struct to represent image snapshot at jobs.<job_id>.snapshot. https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idsnapshot https://docs.github.com/en/actions/how-tos/manage-runners/larger-runners/use-custom-images

type StepFacts Âķ added in v2.2.0

type StepFacts struct {
	// Index is the position of the step in the job, from 0.
	Index    int         `json:"index"`
	Location *Location   `json:"location,omitempty"`
	ID       string      `json:"id,omitempty"`
	Name     *StringFact `json:"name,omitempty"`
	// Kind is "run", "action" or "parallel".
	Kind string  `json:"kind"`
	If   *string `json:"if,omitempty"`
	// Shell is the shell of a run step, when written.
	Shell *StringFact `json:"shell,omitempty"`
	Uses  *UsesFacts  `json:"uses,omitempty"`
	// Inputs are the keys of "with:" of an action step. InputsDynamic is true when the whole section is an expression,
	// so the list is not all of them.
	Inputs        []InputFact `json:"inputs,omitempty"`
	InputsDynamic bool        `json:"inputs_dynamic,omitempty"`
}

StepFacts is a step. A step of a "parallel:" group is listed after the group, in the order of the source.

type Strategy Âķ

type Strategy struct {
	// Matrix is matrix of combinations of values. Each combination will run the job once. When the whole strategy is
	// an expression (Expression), it is a matrix with the same Expression, so that a rule treats the matrix as unknown.
	Matrix *Matrix
	// Expression is the expression of a strategy written as one expression, such as
	// `strategy: ${{ fromJSON(needs.setup.outputs.strategy) }}`. Otherwise nil.
	Expression *String
	// FailFast is flag to show if other jobs should stop when one job fails.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategyfail-fast
	FailFast *Bool
	// MaxParallel is how many jobs should be run at once.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategymax-parallel
	MaxParallel *Int
	// Pos is a position in source.
	Pos *Pos
}

Strategy is strategy configuration of how the job is run. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategy

type String Âķ

type String struct {
	// Value is a raw value of the string.
	Value string
	// Quoted represents the string is quoted with ' or " in the YAML source.
	Quoted bool
	// Pos is a position of the string in source.
	Pos *Pos
	// If string is a literal block which preserves newlines and indentation. Helpful for error messages
	Literal bool
	// Indent is the number of spaces which the YAML parser stripped from each content line of a
	// literal block. 0 means unknown (or not a literal block). When set, positions in the value
	// can be mapped back to the source.
	Indent int
	// contains filtered or unexported fields
}

String represents generic string value in YAML file with position.

func (*String) ContainsExpression Âķ

func (s *String) ContainsExpression() bool

ContainsExpression returns whether the string contains at least one ${{ }} expression.

func (*String) IsExpressionAssigned Âķ

func (s *String) IsExpressionAssigned() bool

IsExpressionAssigned returns whether a single expression is assigned to the string.

type StringFact Âķ added in v2.2.0

type StringFact struct {
	Value    string    `json:"value"`
	Dynamic  bool      `json:"dynamic,omitempty"`
	Location *Location `json:"location,omitempty"`
}

StringFact is a string of the file. Dynamic is true when it contains a ${{ }} expression, so its value is known only when the workflow runs: Value is then the text as written.

type StringNode Âķ

type StringNode struct {
	// Value is value of the string literal. Escapes are resolved and quotes at both edges are
	// removed.
	Value string
	// contains filtered or unexported fields
}

StringNode is node for string literal.

func (*StringNode) Token Âķ

func (n *StringNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type StringType Âķ

type StringType struct{}

StringType is type for string values.

func (StringType) Assignable Âķ

func (ty StringType) Assignable(other ExprType) bool

Assignable returns if other type can be assignable to the type.

func (StringType) DeepCopy Âķ

func (ty StringType) DeepCopy() ExprType

DeepCopy duplicates itself. All its child types are copied recursively.

func (StringType) Merge Âķ

func (ty StringType) Merge(other ExprType) ExprType

Merge merges other type into this type. When other type conflicts with this type, the merged result is any type as fallback.

func (StringType) String Âķ

func (ty StringType) String() string

type TagPatterns Âķ added in v2.6.0

type TagPatterns []string

TagPatterns is a list of glob patterns, written in the config file as one string or a list of strings.

func (*TagPatterns) UnmarshalYAML Âķ added in v2.6.0

func (p *TagPatterns) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML implements yaml.Unmarshaler.

type TextEdit Âķ

type TextEdit struct {
	// Start is the byte offset where the replaced range starts.
	Start int `json:"start"`
	// End is the byte offset just after the replaced range.
	End int `json:"end"`
	// NewText is the text to put in place of the range.
	NewText string `json:"new_text"`
}

TextEdit replaces the bytes in [Start, End) of a file with NewText. Offsets are byte offsets from the beginning of the file. Start == End inserts the text, and an empty NewText deletes the range.

type TimeoutJob Âķ added in v2.2.0

type TimeoutJob struct {
	ID string `json:"id"`
	// Line is the line of the job in the file.
	Line int `json:"line,omitempty"`
	// Kind is "job", "matrix" (one job that runs once for each combination of values: the legs share the timeout) or
	// "reusable-workflow" (a call of a workflow, which has the jobs and the timeouts).
	Kind string `json:"kind"`
	// DeclaredMinutes is the timeout-minutes the job sets; DeclaredDynamic is true when an expression decides it.
	DeclaredMinutes *float64 `json:"declared_minutes,omitempty"`
	DeclaredDynamic bool     `json:"declared_dynamic,omitempty"`
	// Legs is how many different names of the runs matched: the combinations of a matrix that ran.
	Legs int `json:"legs"`
	// Samples is how many successful executions of the job (every leg) were measured.
	Samples int `json:"samples"`
	// MinMinutes, MedianMinutes and MaxMinutes are the duration of a job from its start on a runner to its end, in minutes
	// to a tenth. They are absent without samples.
	MinMinutes    *float64 `json:"min_minutes,omitempty"`
	MedianMinutes *float64 `json:"median_minutes,omitempty"`
	MaxMinutes    *float64 `json:"max_minutes,omitempty"`
	// SuggestedMinutes is MaxMinutes times the buffer, rounded up to whole minutes. It is absent when the job has fewer than
	// MinSamples samples (Note says so).
	SuggestedMinutes int `json:"suggested_minutes,omitempty"`
	// Note says why a job has no suggestion.
	Note string `json:"note,omitempty"`
}

TimeoutJob is a job of a workflow file.

type TimeoutOptions Âķ added in v2.2.0

type TimeoutOptions struct {
	// Runs is how many of the latest successful runs of each workflow are read (1 to 100). 0 means DefaultTimeoutHistoryRuns.
	Runs int
	// Buffer is the factor of the suggestion: the longest duration on record times Buffer, rounded up to whole
	// minutes. It must be at least 1. 0 means DefaultTimeoutBuffer.
	Buffer float64
}

TimeoutOptions configure SuggestTimeouts.

type TimeoutReport Âķ added in v2.2.0

type TimeoutReport struct {
	Version int `json:"version"`
	// Repository is "owner/repo".
	Repository string `json:"repository"`
	// Runs is how many successful runs of each workflow were asked for, and Buffer the factor of the suggestions.
	Runs   int     `json:"runs_per_workflow"`
	Buffer float64 `json:"buffer"`
	// MinSamples is how many durations a job needs to get a suggestion.
	MinSamples int `json:"min_samples"`
	// Complete is false when a lookup failed (a rate limit, a 403, a timeout): the numbers are from what could be read.
	Complete bool `json:"complete"`
	// SkippedLookups counts the lookups that failed.
	SkippedLookups int `json:"skipped_lookups"`
	// LargestSuggestedMinutes is the largest suggestion of the report. A single default-minutes of the rule missing-timeout has
	// to be at least this long not to cancel the slowest job on record. It is absent when there is no suggestion.
	LargestSuggestedMinutes int                `json:"largest_suggested_minutes,omitempty"`
	Workflows               []*TimeoutWorkflow `json:"workflows"`
}

TimeoutReport is the document of --suggest-timeouts.

func (*TimeoutReport) JSON Âķ added in v2.2.0

func (r *TimeoutReport) JSON() ([]byte, error)

JSON returns the report as indented JSON with a final newline.

func (*TimeoutReport) WriteText Âķ added in v2.2.0

func (r *TimeoutReport) WriteText(w io.Writer) error

WriteText writes the report for a person.

type TimeoutUnmatched Âķ added in v2.2.0

type TimeoutUnmatched struct {
	Name    string `json:"name"`
	Samples int    `json:"samples"`
}

TimeoutUnmatched is a job of the runs that matches no job of the file.

type TimeoutWorkflow Âķ added in v2.2.0

type TimeoutWorkflow struct {
	// Path is relative to the root of the repository, with "/" as the separator.
	Path string `json:"path"`
	// Runs is how many successful runs were read, and Oldest and Newest the dates (UTC) on which the oldest and the newest
	// were created.
	Runs   int    `json:"runs"`
	Oldest string `json:"oldest,omitempty"`
	Newest string `json:"newest,omitempty"`
	// Error says why the workflow has no numbers: GitHub has no run of it, the runs could not be read.
	Error string `json:"error,omitempty"`
	// TruncatedRuns counts the runs whose jobs are more than the 100 the report reads (a large matrix).
	TruncatedRuns int `json:"truncated_runs,omitempty"`
	// Unmatched are the jobs of the runs that the report could not match to a job of the file.
	Unmatched []TimeoutUnmatched `json:"unmatched,omitempty"`
	Jobs      []*TimeoutJob      `json:"jobs"`
}

TimeoutWorkflow is a workflow file of the report.

type Token Âķ

type Token struct {
	// Kind is kind of the token.
	Kind TokenKind
	// Value is string representation of the token.
	Value string
	// Offset is byte offset of token string starting.
	Offset int
	// Line is line number of start position of the token. Note that this value is 1-based.
	Line int
	// Column is column number of start position of the token. Note that this value is 1-based.
	Column int
}

Token is a token lexed from expression syntax. For more details, see https://docs.github.com/en/actions/learn-github-actions/expressions

func (*Token) String Âķ

func (t *Token) String() string

type TokenKind Âķ

type TokenKind int

TokenKind is kind of token.

const (
	// TokenKindUnknown is a default value of token as unknown token value.
	TokenKindUnknown TokenKind = iota
	// TokenKindEnd is a token for end of token sequence. Sequence without this
	// token means invalid.
	TokenKindEnd
	// TokenKindIdent is a token for identifier.
	TokenKindIdent
	// TokenKindString is a token for string literals.
	TokenKindString
	// TokenKindInt is a token for integers including hex integers.
	TokenKindInt
	// TokenKindFloat is a token for float numbers.
	TokenKindFloat
	// TokenKindLeftParen is a token for '('.
	TokenKindLeftParen
	// TokenKindRightParen is a token for ')'.
	TokenKindRightParen
	// TokenKindLeftBracket is a token for '['.
	TokenKindLeftBracket
	// TokenKindRightBracket is a token for ']'.
	TokenKindRightBracket
	// TokenKindDot is a token for '.'.
	TokenKindDot
	// TokenKindNot is a token for '!'.
	TokenKindNot
	// TokenKindLess is a token for '<'.
	TokenKindLess
	// TokenKindLessEq is a token for '<='.
	TokenKindLessEq
	// TokenKindGreater is a token for '>'.
	TokenKindGreater
	// TokenKindGreaterEq is a token for '>='.
	TokenKindGreaterEq
	// TokenKindEq is a token for '=='.
	TokenKindEq
	// TokenKindNotEq is a token for '!='.
	TokenKindNotEq
	// TokenKindAnd is a token for '&&'.
	TokenKindAnd
	// TokenKindOr is a token for '||'.
	TokenKindOr
	// TokenKindStar is a token for '*'.
	TokenKindStar
	// TokenKindComma is a token for ','.
	TokenKindComma
)

func (TokenKind) String Âķ

func (t TokenKind) String() string

type UntrustedInputChecker Âķ

type UntrustedInputChecker struct {
	// contains filtered or unexported fields
}

UntrustedInputChecker is a checker to detect untrusted inputs in an expression syntax tree. This checker checks object property accesses, array index accesses, and object filters. And detects paths to untrusted inputs. Found errors are stored in this instance and can be get via Errs method.

Note: To avoid breaking the state of checking property accesses on nested property accesses like foo[aaa.bbb].bar, IndexAccessNode.Index must be visited before IndexAccessNode.Operand.

func NewUntrustedInputChecker Âķ

func NewUntrustedInputChecker(roots UntrustedInputSearchRoots) *UntrustedInputChecker

NewUntrustedInputChecker creates a new UntrustedInputChecker instance. The roots argument is a search tree which defines untrusted input paths as trees.

func (*UntrustedInputChecker) Errs Âķ

func (u *UntrustedInputChecker) Errs() []*ExprError

Errs returns errors detected by this checker. This method should be called after visiting all nodes in a syntax tree.

func (*UntrustedInputChecker) Init Âķ

func (u *UntrustedInputChecker) Init()

Init initializes a state of checker.

func (*UntrustedInputChecker) OnVisitEnd Âķ

func (u *UntrustedInputChecker) OnVisitEnd()

OnVisitEnd is a callback which should be called after visiting whole syntax tree. This callback is necessary to handle the case where an untrusted input access is at root of expression.

func (*UntrustedInputChecker) OnVisitNodeEnter Âķ

func (u *UntrustedInputChecker) OnVisitNodeEnter(n ExprNode)

func (*UntrustedInputChecker) OnVisitNodeLeave Âķ

func (u *UntrustedInputChecker) OnVisitNodeLeave(n ExprNode)

OnVisitNodeLeave is a callback which should be called on visiting node after visiting its children.

type UntrustedInputMap Âķ

type UntrustedInputMap struct {
	Name     string
	Parent   *UntrustedInputMap
	Children map[string]*UntrustedInputMap
}

UntrustedInputMap is a recursive map to match context object property dereferences. Root of this map represents each context names and their ancestors represent recursive properties.

func NewUntrustedInputMap Âķ

func NewUntrustedInputMap(name string, children ...*UntrustedInputMap) *UntrustedInputMap

NewUntrustedInputMap creates new instance of UntrustedInputMap. It is used for node of search tree of untrusted input checker.

func (*UntrustedInputMap) String Âķ

func (m *UntrustedInputMap) String() string

type UntrustedInputSearchRoots Âķ

type UntrustedInputSearchRoots map[string]*UntrustedInputMap

UntrustedInputSearchRoots is a list of untrusted inputs. It forms tree structure to detect untrusted inputs in nested object property access, array index access, and object filters efficiently. Each value of this map represents a root of the search so their names are context names.

func (UntrustedInputSearchRoots) AddRoot Âķ

AddRoot adds a new root to search for detecting untrusted input.

type UpdateConfig Âķ added in v2.6.0

type UpdateConfig struct {
	// CooldownDays is how old a release must be to be chosen. Nil and 0 turn the restriction off.
	CooldownDays *int `yaml:"cooldown-days"`
	// Freeze pins the references to the commit SHA of the chosen release, with the version as a comment.
	Freeze *bool `yaml:"freeze"`
	// IncludeTags are the glob patterns a tag must match (any of them) to be chosen. Empty means every tag.
	IncludeTags TagPatterns `yaml:"include-tags"`
	// ExcludeTags are the glob patterns of the tags which are never chosen. They win over IncludeTags.
	ExcludeTags TagPatterns `yaml:"exclude-tags"`
	// ExcludePrereleases leaves out the releases which GitHub marks as prereleases.
	ExcludePrereleases *bool `yaml:"exclude-prereleases"`
	// RequireImmutableReleases accepts only published releases which GitHub marks immutable.
	RequireImmutableReleases *bool `yaml:"require-immutable-releases"`
}

UpdateConfig is the "update" mapping of the config file. It sets the defaults of "jactionlint update"; the options of the command override it.

type UpdateMode Âķ added in v2.6.0

type UpdateMode int

UpdateMode is what `jactionlint update` does with the updates it finds.

const (
	// UpdateReport lists the updates and changes nothing.
	UpdateReport UpdateMode = iota
	// UpdateCheck lists them like UpdateReport. The command exits with status 1 when a reference violates the policy.
	UpdateCheck
	// UpdateDiff prints the changes as a unified diff and writes nothing.
	UpdateDiff
	// UpdateApply writes the changes.
	UpdateApply
)

type UpdateOptions Âķ added in v2.6.0

type UpdateOptions struct {
	Mode UpdateMode
	// MinAge overrides "cooldown-days": the age in days a release must have. 0 turns the cooldown off.
	MinAge *int
	// Freeze overrides "freeze".
	Freeze *bool
	// PinOnly pins the referenced release to its commit without upgrading it. It implies Freeze.
	PinOnly bool
	// BranchToTag are regular expressions: a reference whose ref (a branch name) matches one is converted to the latest
	// eligible release.
	BranchToTag []string
	// IncludeTags and ExcludeTags override "include-tags" and "exclude-tags".
	IncludeTags, ExcludeTags []string
	// IncludeActions and ExcludeActions are regular expressions matched against "owner/repo[/subpath]". An action is
	// updated only when it matches one of the includes (if any) and none of the excludes.
	IncludeActions, ExcludeActions []string
	// ActionRules are "REGEX=ignore" or "REGEX=cooldown:DAYS". The first rule whose regular expression matches the value
	// of `uses:` followed by its comment ("actions/checkout@v4 # v4.1.0") applies.
	ActionRules []string
	// contains filtered or unexported fields
}

UpdateOptions are the options of Linter.Update. A nil or empty field leaves the setting of the "update" mapping of the config file, which is what the command line options override.

type UpdateResult Âķ added in v2.6.0

type UpdateResult struct {
	// Updates is the number of references that have an update (or a pin) to apply.
	Updates int
	// Violations is the number of references that violate the policy, or whose version could not be verified.
	Violations int
	// Files are the files that were changed (or would be changed).
	Files []string
	// Diff is the changes as a unified diff.
	Diff string
	// Errors are the findings, which were printed.
	Errors []*Error
}

UpdateResult is what Linter.Update did.

type UsesFacts Âķ added in v2.2.0

type UsesFacts struct {
	Raw string `json:"uses"`
	// Kind is "action", "reusable-workflow", "docker", "local" or "invalid".
	Kind string `json:"kind"`
	// Dynamic is true when the value has an expression.
	Dynamic bool `json:"dynamic,omitempty"`
	// Repository is "owner/repo" of an action or a reusable workflow of another repository.
	Repository string `json:"repository,omitempty"`
	// Ref and RefKind are what follows "@". RefKind is "full-sha", "short-sha", "semver-tag", "other-tag-or-branch",
	// "digest" or "none".
	Ref     string `json:"ref,omitempty"`
	RefKind string `json:"ref_kind,omitempty"`
	// Path is the canonical "./path" of a local action or workflow.
	Path string `json:"path,omitempty"`
}

UsesFacts is a "uses:" value.

type UsesKind Âķ

type UsesKind int

UsesKind classifies the value of a `uses:` key.

const (
	// UsesInvalid is a value that follows none of the accepted formats. UsesRef.Problem says why.
	UsesInvalid UsesKind = iota
	// UsesAction is a repository action: {owner}/{repo}[/{subpath}]@{ref}.
	UsesAction
	// UsesReusableWorkflow is a repository workflow: {owner}/{repo}/{path}.yml@{ref}.
	UsesReusableWorkflow
	// UsesDocker is a container image: docker://{image}[:{tag}][@{digest}].
	UsesDocker
	// UsesLocal is a path in the workflow's own repository: ./{path} or $/{path}.
	UsesLocal
)

func (UsesKind) String Âķ

func (k UsesKind) String() string

String returns the name of the kind as used in messages.

type UsesPattern Âķ

type UsesPattern struct {
	// contains filtered or unexported fields
}

UsesPattern is a pattern which matches the repository references of `uses:` keys, i.e. actions and reusable workflows. It is the matching logic of the forbidden-uses rule and is meant to be shared by the rules which select actions by name.

A pattern is "{name}" or "{name}@{ref}". Names are compared case-insensitively and refs case-sensitively. In a name:

  • "*" matches every action
  • "owner/*" matches every action of the owner, including the ones in sub-directories
  • "owner/repo/*" matches the repository itself and everything in it
  • "owner/repo" matches only the root action of the repository. "owner/repo/sub" matches only that sub-directory
  • any other '*' matches any run of characters, "/" included

Without "@{ref}" any ref matches.

func ParseUsesPattern Âķ

func ParseUsesPattern(s string) UsesPattern

ParseUsesPattern parses a pattern.

func (UsesPattern) Match Âķ

func (p UsesPattern) Match(u *UsesRef) bool

Match reports whether the reference matches the pattern. Only actions and reusable workflows can match: local paths, Docker images and invalid values never do.

func (UsesPattern) String Âķ

func (p UsesPattern) String() string

String returns the pattern as it was written.

type UsesRef Âķ

type UsesRef struct {
	// Raw is the value exactly as given.
	Raw string
	// Kind is the kind of reference.
	Kind UsesKind
	// Problem says why Kind is UsesInvalid. Empty otherwise.
	Problem string
	// Dynamic is true when the value contains a `${{ }}` expression. The value is still split on a
	// best-effort basis but cannot be judged: IsPinned is false.
	Dynamic bool

	// Owner, Repo and Subpath are set for UsesAction and UsesReusableWorkflow (and best effort for
	// invalid values). Owner and Repo keep the case they were written in; compare them with
	// SameRepo. Subpath is everything after "{owner}/{repo}/" and keeps trailing slashes.
	Owner, Repo, Subpath string
	// Ref is what follows the first '@'. HasRef tells an absent ref from an empty one.
	Ref     string
	HasRef  bool
	RefKind RefKind

	// Path is the canonical "./{path}" form of a UsesLocal value.
	Path string

	// Image, Tag and Digest are set for UsesDocker. Image excludes the "docker://" scheme, the tag
	// and the digest, and keeps a registry host and port ("localhost:5000/img"). HasTag tells an
	// absent tag from an empty one ("docker://img:"). Digest is the part after '@', for instance
	// "sha256:...".
	Image, Tag, Digest string
	HasTag             bool
}

UsesRef is the parsed form of a `uses:` value, for both step-level actions and job-level reusable workflow calls. Obtain it with ParseUses. A UsesRef is never nil, and fields that do not apply to the Kind are empty.

func ParseUses Âķ

func ParseUses(spec string) *UsesRef

ParseUses parses the value of a `uses:` key. It never fails: a value that is not understood comes back as UsesInvalid with Problem set, and as much of it as could be split is filled in.

A value starting with "./" or "$/" is UsesLocal and one starting with "docker://" is UsesDocker. Everything else is read as {owner}/{repo}[/{subpath}]@{ref}; it is a UsesReusableWorkflow when the subpath names a .yml or .yaml file. Whether the value is legal in a given position (a step cannot call a workflow, a job cannot run an action) is for the caller to decide.

func (*UsesRef) CanonicalName Âķ

func (u *UsesRef) CanonicalName() string

CanonicalName returns the reference without its ref, normalised for comparison and lookup: "owner/repo[/subpath]" with owner and repo lowercased and trailing slashes dropped, the image name for Docker images, the "./{path}" form for local paths. Invalid values give "".

func (*UsesRef) IsPinned Âķ

func (u *UsesRef) IsPinned() bool

IsPinned reports whether the reference is immutable: a full commit SHA for repository actions and reusable workflows, a sha256 digest for Docker images. Local references are always pinned since they are resolved at the running commit. Invalid and dynamic values are not.

func (*UsesRef) IsRepo Âķ

func (u *UsesRef) IsRepo() bool

IsRepo reports whether the reference points into a GitHub repository (an action or a reusable workflow, as opposed to a container image or a local path).

func (*UsesRef) SameRepo Âķ

func (u *UsesRef) SameRepo(other *UsesRef) bool

SameRepo reports whether both references point into the same GitHub repository. Owner and repo names are case-insensitive on GitHub, so they are compared that way.

type VariableNode Âķ

type VariableNode struct {
	// Name is name of the variable
	Name string
	// contains filtered or unexported fields
}

VariableNode is node for variable access.

func (*VariableNode) Token Âķ

func (n *VariableNode) Token() *Token

Token returns the first token of the node. This method is useful to get position of this node.

type VisitExprNodeFunc Âķ

type VisitExprNodeFunc func(node, parent ExprNode, entering bool)

VisitExprNodeFunc is a visitor function for VisitExprNode(). The entering argument is set to true when it is called before visiting children. It is set to false when it is called after visiting children. It means that this function is called twice for the same node. The parent argument is the parent of the node. When the node is root, its parent is nil.

type Visitor Âķ

type Visitor struct {
	// contains filtered or unexported fields
}

Visitor visits syntax tree from root in depth-first order

func NewVisitor Âķ

func NewVisitor() *Visitor

NewVisitor creates Visitor instance

func (*Visitor) AddPass Âķ

func (v *Visitor) AddPass(p Pass)

AddPass adds new pass which is called on traversing a syntax tree

func (*Visitor) EnableDebug Âķ

func (v *Visitor) EnableDebug(w io.Writer)

EnableDebug enables debug output when non-nil io.Writer value is given. All debug outputs from visitor will be written to the writer.

func (*Visitor) Visit Âķ

func (v *Visitor) Visit(n *Workflow) error

Visit visits given syntax tree in depth-first order

type WebhookEvent Âķ

type WebhookEvent struct {
	// Hook is a name of the webhook event.
	Hook *String
	// Types is list of types of the webhook event. Only the types enumerated here will trigger
	// the workflow.
	Types []*String
	// Branches is 'branches' filter. This value is nil when it is omitted.
	Branches *WebhookEventFilter
	// BranchesIgnore is 'branches-ignore' filter. This value is nil when it is omitted.
	BranchesIgnore *WebhookEventFilter
	// Tags is 'tags' filter. This value is nil when it is omitted.
	Tags *WebhookEventFilter
	// TagsIgnore is 'tags-ignore' filter. This value is nil when it is omitted.
	TagsIgnore *WebhookEventFilter
	// Paths is 'paths' filter. This value is nil when it is omitted.
	Paths *WebhookEventFilter
	// PathsIgnore is 'paths-ignore' filter. This value is nil when it is omitted.
	PathsIgnore *WebhookEventFilter
	// Workflows is list of workflow names which are triggered by 'workflow_run' event.
	Workflows []*String
	// Pos is a position in source.
	Pos *Pos
}

WebhookEvent represents event type based on webhook events. Some events can't have 'types' field. Only 'push' and 'pull' events can have 'tags', 'tags-ignore', 'paths' and 'paths-ignore' fields. Only 'workflow_run' event can have 'workflows' field. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onevent_nametypes

func (*WebhookEvent) EventName Âķ

func (e *WebhookEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type WebhookEventFilter Âķ

type WebhookEventFilter struct {
	// Name is a name of filter such like 'branches', 'tags'
	Name *String
	// Values is a list of filter values.
	Values []*String
}

WebhookEventFilter is a filter for Webhook events such as 'branches', 'paths-ignore', ... Webhook events are filtered by those filters. Some filters are exclusive. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#using-filters

func (*WebhookEventFilter) IsEmpty Âķ

func (f *WebhookEventFilter) IsEmpty() bool

IsEmpty returns true when it has no value. This may mean the WebhookEventFilter instance itself is nil.

type Workflow Âķ

type Workflow struct {
	// Name is name of the workflow. This field can be nil when user didn't specify the name explicitly.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#name
	Name *String
	// Description is the description of the workflow. It has no effect on a run.
	// https://github.com/actions/runner/blob/main/src/Sdk/WorkflowParser/workflow-v1.0.json (workflow-root)
	Description *String
	// RunName is the name of workflow runs. This field can be set dynamically using ${{ }}.
	// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#run-name
	RunName *String
	// On is list of events which can trigger this workflow.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onpushpull_requestbranchestags
	On []Event
	// Permissions is configuration of permissions of this workflow.
	Permissions *Permissions
	// CacheMode controls cache access for jobs in this workflow.
	// https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#cache-mode
	CacheMode *String
	// Env is a default set of environment variables while running this workflow.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#env
	Env *Env
	// Defaults is default configuration of how to run scripts.
	Defaults *Defaults
	// Concurrency is concurrency configuration of entire workflow. Each jobs also can their own
	// concurrency configurations.
	Concurrency *Concurrency
	// Jobs is mappings from job ID to the job object. Keys are in lower case since they are case-insensitive.
	Jobs map[string]*Job
	// Comments holds the YAML comments of the source file. Look a node up by the line of its Pos.
	// It is never nil for a workflow returned by Parse.
	Comments *CommentIndex
	// Action is set instead of On when the file is the metadata of an action (action.yml) parsed with
	// ParseAction. The workflow then has no events, permissions or other workflow-level
	// configuration. The steps of a composite action are in Jobs as one job with Composite set.
	Action *ActionFile

	// Source is the content of the source file. Rules which offer a fix (Error.Fix) read it to turn
	// positions into byte offsets. It is never nil for a workflow returned by Parse. Do not modify it.
	Source []byte
	// contains filtered or unexported fields
}

Workflow is root of workflow syntax tree, which represents one workflow configuration file. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions

func (*Workflow) FindWorkflowCallEvent Âķ

func (w *Workflow) FindWorkflowCallEvent() (*WorkflowCallEvent, bool)

FindWorkflowCallEvent returns workflow_call event node if exists

func (*Workflow) IsComposite Âķ

func (w *Workflow) IsComposite() bool

IsComposite reports whether the workflow is the metadata of a composite action.

func (*Workflow) TriggerEvents Âķ

func (w *Workflow) TriggerEvents() []Event

TriggerEvents returns the events which decide the context a workflow-level rule judges. They are the events of the workflow, or, for the metadata of an action, those of the workflows which call it (see ActionCallers).

type WorkflowCall Âķ

type WorkflowCall struct {
	// Uses is a workflow specification to be called. This field is mandatory.
	Uses *String
	// Inputs is a map from input name to input value at 'with:'. Keys are in lower case since input names
	// are case-insensitive.
	Inputs map[string]*WorkflowCallInput
	// Secrets is a map from secret name to secret value at 'secrets:'. Keys are in lower case since input
	// names are case-insensitive.
	Secrets map[string]*WorkflowCallSecret
	// InheritSecrets is true when 'secrets: inherit' is specified. In this case, Secrets must be empty.
	// https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onworkflow_callsecretsinherit
	InheritSecrets bool
	// InheritSecretsPos is the position of the 'secrets: inherit' value. It is nil unless
	// InheritSecrets is true.
	InheritSecretsPos *Pos
}

WorkflowCall is a struct to represent workflow call at jobs.<job_id>. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_iduses

type WorkflowCallEvent Âķ

type WorkflowCallEvent struct {
	// Inputs is an array of inputs of the workflow_call event. This value is not a map unlike other fields of this
	// struct since its order is important when checking the default values of inputs.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callinputs
	Inputs []*WorkflowCallEventInput
	// Secrets is a map from name of secret to secret configuration. When 'secrets' is omitted, nil is set to this
	// field. Keys are in lower case since they are case-insensitive.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callsecrets
	Secrets map[string]*WorkflowCallEventSecret
	// Outputs is a map from name of output to output configuration. Keys are in lower case since they are case-insensitive.
	// https://docs.github.com/en/actions/using-workflows/reusing-workflows#using-outputs-from-a-reusable-workflow
	Outputs map[string]*WorkflowCallEventOutput
	// Pos is a position in source.
	Pos *Pos
}

WorkflowCallEvent is workflow_call event configuration. https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#workflow-reuse-events

func (*WorkflowCallEvent) EventName Âķ

func (e *WorkflowCallEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type WorkflowCallEventInput Âķ

type WorkflowCallEventInput struct {
	// Name is a name of the input.
	Name *String
	// Description is a description of the input.
	Description *String
	// Default is a default value of the input. Nil means no default value.
	Default *String
	// Required represents if the input is required or optional. When this value is nil, it was not explicitly specified.
	// In the case the default value is 'not required'.
	Required *Bool
	// Type of the input, which must be one of 'boolean', 'number' or 'string'. This property is required.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callinput_idtype
	Type WorkflowCallEventInputType
	// ID is an ID of the input. Input ID is in lower case because it is case-insensitive.
	ID string
}

WorkflowCallEventInput is an input configuration of workflow_call event. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callinputs

func (*WorkflowCallEventInput) IsRequired Âķ

func (i *WorkflowCallEventInput) IsRequired() bool

IsRequired returns if the input is marked as required or not. require

type WorkflowCallEventInputType Âķ

type WorkflowCallEventInputType uint8

WorkflowCallEventInputType is a type of inputs at workflow_call event. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callinput_idtype

const (
	// WorkflowCallEventInputTypeInvalid represents invalid type input as default value of the type.
	WorkflowCallEventInputTypeInvalid WorkflowCallEventInputType = iota
	// WorkflowCallEventInputTypeBoolean represents boolean type input.
	WorkflowCallEventInputTypeBoolean
	// WorkflowCallEventInputTypeNumber represents number type input.
	WorkflowCallEventInputTypeNumber
	// WorkflowCallEventInputTypeString represents string type input.
	WorkflowCallEventInputTypeString
)

type WorkflowCallEventOutput Âķ

type WorkflowCallEventOutput struct {
	// Name is a name of the output.
	Name *String
	// Description is a description of the output.
	Description *String
	// Value is an expression for the value of the output.
	Value *String
}

WorkflowCallEventOutput is an output configuration of workflow_call event. https://docs.github.com/en/actions/using-workflows/reusing-workflows#using-outputs-from-a-reusable-workflow

type WorkflowCallEventSecret Âķ

type WorkflowCallEventSecret struct {
	// Name is a name of the secret.
	Name *String
	// Description is a description of the secret.
	Description *String
	// Required represents if the secret is required or optional. When this value is nil, it means optional.
	// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callsecretssecret_idrequired
	Required *Bool
}

WorkflowCallEventSecret is a secret configuration of workflow_call event. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onworkflow_callsecrets

type WorkflowCallInput Âķ

type WorkflowCallInput struct {
	// Name is a name of the input.
	Name *String
	// Value is a value of the input.
	Value *String
}

WorkflowCallInput is a normal input for workflow call.

type WorkflowCallSecret Âķ

type WorkflowCallSecret struct {
	// Name is a name of the secret
	Name *String
	// Value is a value of the secret
	Value *String
}

WorkflowCallSecret is a secret input for workflow call. https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idwith

type WorkflowCallers Âķ added in v2.1.0

type WorkflowCallers struct {
	// Events are the events of the workflows which call it, directly or through other reusable workflows, without
	// workflow_call.
	Events []Event
	// Known is true when every chain of calls ends in a local workflow with its own events. It is false when the
	// workflow has no local caller, or a caller which is itself only called (by workflows of other repositories,
	// which are not known).
	Known bool
}

WorkflowCallers are the events of the local workflows which run a reusable workflow. Unlike the callers of an action they are not judged by the most dangerous one: a rule asks which events can reach the workflow.

type WorkflowDispatchEvent Âķ

type WorkflowDispatchEvent struct {
	// Inputs is map from input names to input attributes. Keys are in lower case since they are case insensitive.
	Inputs map[string]*DispatchInput
	// Pos is a position in source.
	Pos *Pos
}

WorkflowDispatchEvent is event on dispatching workflow manually. https://docs.github.com/en/actions/learn-github-actions/events-that-trigger-workflows#workflow_dispatch

func (*WorkflowDispatchEvent) EventName Âķ

func (e *WorkflowDispatchEvent) EventName() string

EventName returns name of the event to trigger this workflow.

type WorkflowDispatchEventInputType Âķ

type WorkflowDispatchEventInputType uint8

WorkflowDispatchEventInputType is a type for input types of workflow_dispatch events. https://github.blog/changelog/2021-11-10-github-actions-input-types-for-manual-workflows/

const (
	// WorkflowDispatchEventInputTypeNone represents no type is specified to the input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeNone WorkflowDispatchEventInputType = iota
	// WorkflowDispatchEventInputTypeString is string type of input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeString
	// WorkflowDispatchEventInputTypeNumber is number type of input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeNumber
	// WorkflowDispatchEventInputTypeBoolean is boolean type of input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeBoolean
	// WorkflowDispatchEventInputTypeChoice is choice type of input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeChoice
	// WorkflowDispatchEventInputTypeEnvironment is environment type of input of workflow_dispatch event.
	WorkflowDispatchEventInputTypeEnvironment
)

type WorkflowFacts Âķ added in v2.2.0

type WorkflowFacts struct {
	// Path is relative to the root of the repository, with "/" as the separator (relative to the working directory when
	// the file belongs to no repository).
	Path string `json:"path"`
	// Parsed is false when the file is not valid YAML. It has no other fact then.
	Parsed bool `json:"parsed"`
	// SyntaxErrors counts the syntax errors of the file. The facts are what could be read.
	SyntaxErrors int           `json:"syntax_errors,omitempty"`
	Name         *StringFact   `json:"name,omitempty"`
	Events       []*EventFacts `json:"events"`
	// Callable is true when the workflow has the event workflow_call.
	Callable bool `json:"callable"`
	// CalledBy says who calls a callable workflow in this repository. It is absent for a workflow that is not callable
	// and when the file belongs to no repository.
	CalledBy    *CalledByFacts    `json:"called_by,omitempty"`
	Permissions PermissionFacts   `json:"permissions"`
	Concurrency *ConcurrencyFacts `json:"concurrency,omitempty"`
	CacheMode   *StringFact       `json:"cache_mode,omitempty"`
	Jobs        []*JobFacts       `json:"jobs"`
}

WorkflowFacts are the facts of one workflow file.

type WriteBaselineResult Âķ

type WriteBaselineResult struct {
	// Path is the baseline file.
	Path string
	// Entries is the number of findings in the file.
	Entries int
	// Files is the number of files which have findings in the file.
	Files int
	// Changed is false when the file already had this content.
	Changed bool
	// Applied is true when the configuration already applies the baseline ("baseline: auto" or the path of
	// a file), so a plain run uses it. Otherwise only --baseline does.
	Applied bool
	// ConfigFile is the configuration file, relative to the repository, in which "baseline: auto" applies the
	// baseline to every run. It is the file the repository has, else the default .github/jactionlint.yaml
	// that --init-config creates.
	ConfigFile string
	// ConfigValue is the value of "baseline" in ConfigFile which applies this baseline: "auto" for the default
	// file, else the path of the file relative to the repository.
	ConfigValue string
}

WriteBaselineResult describes a baseline file which WriteBaseline wrote.

type YAMLContext Âķ

type YAMLContext int

YAMLContext is how a scalar is written in the source.

const (
	// YAMLPlain is a plain scalar of the block style: key: value
	YAMLPlain YAMLContext = iota
	// YAMLFlowPlain is a plain scalar inside a flow collection: [a, b] or {a: b}
	YAMLFlowPlain
	// YAMLSingleQuoted is a scalar written with single quotes.
	YAMLSingleQuoted
	// YAMLDoubleQuoted is a scalar written with double quotes.
	YAMLDoubleQuoted
	// YAMLBlockScalar is a literal (|) or folded (>) block scalar.
	YAMLBlockScalar
)

func (YAMLContext) String Âķ

func (c YAMLContext) String() string

type YAMLSite Âķ

type YAMLSite struct {
	Context YAMLContext
	// Indent is the number of spaces in front of each line of the content of a block scalar. Text
	// which has line breaks gets this indentation after each of them.
	Indent int
	// AtStart tells that the text is inserted at the start of a plain scalar. A plain scalar cannot
	// start with an indicator character such as "-", "&", "*", "!", "|", ">", "%" or "@".
	AtStart bool
	// CRLF tells that the line of the site ends with "\r\n": the lines of an inserted block text then do too.
	CRLF bool
}

YAMLSite is a place inside an existing scalar where a fixer inserts text.

func YAMLSiteAt Âķ

func YAMLSiteAt(src []byte, off int) (YAMLSite, bool)

YAMLSiteAt finds out how the scalar which contains the byte offset is written. It returns false when the offset is not inside a scalar, when the source does not parse, or when the context is not one the helpers handle (for instance, a block scalar whose content is empty).

Every call parses the whole source. Code which asks about many offsets of one source builds a yamlSiteIndex once instead (sourceIndex.sites does it lazily).

func (YAMLSite) Insert Âķ

func (s YAMLSite) Insert(text string) (string, bool)

Insert renders the text so that it reads back as the same text once it is inserted at the site. It returns false when the context cannot hold the text. The caller then offers no fix or writes the whole scalar again with RenderYAMLValue. Text which is not escaped by the rules of the context is never returned in a form which changes the meaning of the line or the document.

Source Files Âķ

Directories Âķ

Path Synopsis
cmd
jactionlint command
internal
exampleconfig
Package exampleconfig has the configuration which the examples of docs/checks.md are linted with, both by scripts/check-checks (which writes the outputs) and by the playground (which the permalinks open).
Package exampleconfig has the configuration which the examples of docs/checks.md are linted with, both by scripts/check-checks (which writes the outputs) and by the playground (which the permalinks open).
runner
Package runner runs the jobs of a GitHub Actions workflow on the local machine.
Package runner runs the jobs of a GitHub Actions workflow on the local machine.
runner/cache
Package cache is the local actions cache: a store of archives with the matching rules of GitHub's cache, and a service that speaks the protocols of @actions/cache so that actions which cache work unmodified.
Package cache is the local actions cache: a store of archives with the matching rules of GitHub's cache, and a service that speaks the protocols of @actions/cache so that actions which cache work unmodified.
runner/eval
Package eval evaluates the expressions of a workflow (the text inside ${{ }}) with the coercion rules of GitHub Actions.
Package eval evaluates the expressions of a workflow (the text inside ${{ }}) with the coercion rules of GitHub Actions.
runscript
Package runscript analyzes the shell scripts of `run:` steps for the security rules of jactionlint.
Package runscript analyzes the shell scripts of `run:` steps for the security rules of jactionlint.
sandbox
Package sandbox runs a command with its access to the machine restricted by the operating system: Landlock and seccomp on Linux, Seatbelt on macOS.
Package sandbox runs a command with its access to the machine restricted by the operating system: Landlock and seccomp on Linux, Seatbelt on macOS.
toolcmd
Package toolcmd resolves project-pinned executables before tools change directories.
Package toolcmd resolves project-pinned executables before tools change directories.
scripts
check-checks command
fix-corpus command
Command fix-corpus checks that --fix is safe on real workflows.
Command fix-corpus checks that --fix is safe on real workflows.
generate-config-schema command
Command generate-config-schema writes the JSON Schemas of jactionlint, schema/jactionlint-config.json (the config file, from the rule registry) and schema/jactionlint-output.json (--format json) and schema/jactionlint-facts.json (--export-facts), from the jactionlint package.
Command generate-config-schema writes the JSON Schemas of jactionlint, schema/jactionlint-config.json (the config file, from the rule registry) and schema/jactionlint-output.json (--format json) and schema/jactionlint-facts.json (--export-facts), from the jactionlint package.
generate-rules-doc command
Command generate-rules-doc generates docs/rules.md, the reference of all rule IDs, from the rule registry of the jactionlint package.
Command generate-rules-doc generates docs/rules.md, the reference of all rule IDs, from the rule registry of the jactionlint package.
zizmor-diff command
Command zizmor-diff runs jactionlint and zizmor over a corpus of repositories and reports which of zizmor's findings jactionlint also reports.
Command zizmor-diff runs jactionlint and zizmor over a corpus of repositories and reports which of zizmor's findings jactionlint also reports.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL