Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 63 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,70 @@
# gha-security-scanner

Generates and uploads SARIF files to GitHub Advanced Security.
A GitHub Action that runs static code analysis using [Semgrep](https://semgrep.dev/) and uploads the results (SARIF) to [GitHub Advanced Security](https://docs.github.com/en/get-started/learning-about-github/about-github-advanced-security) (Code Scanning).

## Rebuilding `dist`
## Features

If [check-dist.yaml](.github/workflows/check-dist.yml) fails, it probably means
that a transient dependency has changed. To fix it, rebuild `dist` like this and
commit it.
- Installs and runs Semgrep automatically — no setup required
- Uploads SARIF results to GitHub Code Scanning
- Automatically dismisses suppressed finding alerts
- Supports `.semgrepignore` generation from an `aviary.yaml` exclude list
- Excludes common false-positive rules out of the box

## Usage

```yaml
name: Security Scan

on:
push:
branches: [main]
pull_request:
branches: [main]

permissions:
security-events: write

jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: Workiva/gha-security-scanner@v1.0.0
```
$ rm -rf dist node-modules
$ npm install
$ npm run bundle

## Inputs

| Name | Description | Required | Default |
| -------------- | --------------------------------------------------------------------------- | -------- | --------------------- |
| `scanner` | Static code analysis tool to use. Currently only `semgrep` is supported. | No | `semgrep` |
| `github-token` | GitHub token with `security-events: write` permission. | No | `${{ github.token }}` |

## Outputs

| Name | Description |
| ---------- | ---------------------------------------------------- |
| `sarif-id` | The ID of the SARIF upload to GitHub Code Scanning. |

## Excluding Files from Scanning

If your repository does not already have a `.semgrepignore` file, the action will look for an `aviary.yaml` (or `aviary.yml`) file in the repository root and generate a `.semgrepignore` from its `exclude` patterns.

Example `aviary.yaml`:

```yaml
version: 1

exclude:
- ^__tests__/
- ^docs/
```

Each entry is a regular expression matched against file paths. Matching files and directories are excluded from the scan.

If you already have a `.semgrepignore` file, the action will use it as-is.

## Requirements

- The workflow must have `security-events: write` permission.
- GitHub Advanced Security must be enabled on the repository.
- Runs on `ubuntu-latest` (Linux runners). Python 3 must be available in the runner tool cache.
4 changes: 4 additions & 0 deletions __fixtures__/advancedSecurity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import type { uploadVulnScansToGHAS as uploadFn } from '../src/internal/advancedSecurity.js'
import { jest } from '@jest/globals'

export const uploadVulnScansToGHAS = jest.fn<typeof uploadFn>()
108 changes: 108 additions & 0 deletions __tests__/internal/advancedSecurity.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import {
jest,
describe,
it,
expect,
beforeEach,
afterEach
} from '@jest/globals'

import * as core from '../../__fixtures__/core.js'

const mockUploadSarif = jest.fn<() => Promise<{ data: { id: string } }>>()

jest.unstable_mockModule('@actions/core', () => core)
jest.unstable_mockModule('@actions/github', () => ({
getOctokit: () => ({
rest: {
codeScanning: {
uploadSarif: mockUploadSarif
}
}
})
}))
jest.unstable_mockModule('fs', () => ({
promises: {
readFile: jest.fn<() => Promise<string>>().mockResolvedValue('{"runs":[]}')
}
}))

const { uploadVulnScansToGHAS } =
await import('../../src/internal/advancedSecurity.js')

describe('uploadVulnScansToGHAS', () => {
beforeEach(() => {
jest.clearAllMocks()
process.env.GITHUB_REPOSITORY = 'owner/repo'
process.env.GITHUB_REF = 'refs/heads/main'
process.env.GITHUB_SHA = 'abc123'
mockUploadSarif.mockResolvedValue({ data: { id: 'sarif-id-123' } })
})

afterEach(() => {
delete process.env.GITHUB_REPOSITORY
delete process.env.GITHUB_REF
delete process.env.GITHUB_SHA
})

it('should upload a valid SARIF file', async () => {
const result = await uploadVulnScansToGHAS(
'/tmp/results.sarif',
'trivy',
'fake-token'
)

expect(result).toBe('sarif-id-123')
expect(mockUploadSarif).toHaveBeenCalledWith(
expect.objectContaining({
owner: 'owner',
repo: 'repo',
tool_name: 'trivy',
ref: 'refs/heads/main',
commit_sha: 'abc123'
})
)

expect(core.info).toHaveBeenCalledWith(
'✅ Successfully uploaded SARIF file /tmp/results.sarif.\n' +
' API endpoint: https://api.github.com/repos/owner/repo/code-scanning/analyses?sarif_id=sarif-id-123'
)
})

it('should reject non-SARIF files with a warning and error', async () => {
await expect(
uploadVulnScansToGHAS('/tmp/results.json', 'trivy', 'fake-token')
).rejects.toThrow(
'Failed to upload SARIF file: /tmp/results.json is not a SARIF file'
)

expect(mockUploadSarif).not.toHaveBeenCalled()
expect(core.warning).toHaveBeenCalledWith(
'Skipping non-SARIF file: /tmp/results.json'
)
})

it('should throw when SARIF upload returns no ID', async () => {
mockUploadSarif.mockResolvedValue({ data: { id: '' } } as {
data: { id: string }
})

await expect(
uploadVulnScansToGHAS('/tmp/results.sarif', 'trivy', 'fake-token')
).rejects.toThrow(
'SARIF upload succeeded but no ID was returned for /tmp/results.sarif'
)
})

it('does not retry on 403 errors', async () => {
const error = new Error('Forbidden') as Error & { status?: number }
error.status = 403
mockUploadSarif.mockRejectedValue(error)

await expect(
uploadVulnScansToGHAS('/tmp/results.sarif', 'trivy', 'fake-token')
).rejects.toThrow('Forbidden')

expect(mockUploadSarif).toHaveBeenCalledTimes(1)
})
})
95 changes: 95 additions & 0 deletions __tests__/internal/retry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { jest, describe, it, expect, beforeEach } from '@jest/globals'

import * as core from '../../__fixtures__/core.js'

jest.unstable_mockModule('@actions/core', () => core)

const { promiseRetry } = await import('../../src/internal/retry.js')

describe('promiseRetry', () => {
beforeEach(() => {
jest.clearAllMocks()
jest.useFakeTimers()
})

it('resolves on first attempt if fn succeeds', async () => {
const fn = jest.fn<() => Promise<string>>().mockResolvedValue('ok')
const result = await promiseRetry(fn)
expect(result).toBe('ok')
expect(fn).toHaveBeenCalledTimes(1)
})

it('retries on failure and resolves on subsequent success', async () => {
const fn = jest
.fn<() => Promise<string>>()
.mockRejectedValueOnce(new Error('fail'))
.mockResolvedValue('ok')

const promise = promiseRetry(fn, { delay: 100 })
await jest.runAllTimersAsync()
const result = await promise

expect(result).toBe('ok')
expect(fn).toHaveBeenCalledTimes(2)
expect(core.info).toHaveBeenCalledWith('fail')
})

it('throws after exhausting all retries', async () => {
jest.useRealTimers()
const error = new Error('always fails')
const fn = jest.fn<() => Promise<string>>().mockRejectedValue(error)

await expect(promiseRetry(fn, { maxRetries: 2, delay: 1 })).rejects.toThrow(
'always fails'
)
expect(fn).toHaveBeenCalledTimes(3)
})

it('should call refreshCreds before retrying', async () => {
const refreshCreds = jest
.fn<() => Promise<void>>()
.mockResolvedValue(undefined)
const fn = jest
.fn<() => Promise<string>>()
.mockRejectedValueOnce(new Error('fail'))
.mockResolvedValue('ok')

const promise = promiseRetry(fn, { delay: 100, refreshCreds })
await jest.runAllTimersAsync()
await promise

expect(refreshCreds).toHaveBeenCalledTimes(1)
})

it('stops retrying when shouldRetry returns false', async () => {
const error = new Error('do not retry')
const fn = jest.fn<() => Promise<string>>().mockRejectedValue(error)
const shouldRetry = jest.fn<(e: Error) => boolean>().mockReturnValue(false)

const promise = promiseRetry(fn, { maxRetries: 3, delay: 100, shouldRetry })

await expect(promise).rejects.toThrow('do not retry')
expect(fn).toHaveBeenCalledTimes(1)
expect(shouldRetry).toHaveBeenCalledWith(error)
})

it('should uses exponential backoff for delays', async () => {
const fn = jest
.fn<() => Promise<string>>()
.mockRejectedValueOnce(new Error('1'))
.mockRejectedValueOnce(new Error('2'))
.mockResolvedValue('ok')

const spy = jest.spyOn(global, 'setTimeout')

const promise = promiseRetry(fn, { delay: 1000 })
await jest.runAllTimersAsync()
await promise

const delays = spy.mock.calls.map(c => c[1]).filter(d => d !== undefined)
expect(delays).toContain(1000)
expect(delays).toContain(4000)

spy.mockRestore()
})
})
16 changes: 16 additions & 0 deletions __tests__/scanner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import * as core from '../__fixtures__/core.js'
import * as exec from '../__fixtures__/exec.js'
import * as io from '../__fixtures__/io.js'
import * as tc from '../__fixtures__/tool-cache.js'
import * as advancedSecurity from '../__fixtures__/advancedSecurity.js'

jest.unstable_mockModule('@actions/core', () => core)
jest.unstable_mockModule('@actions/exec', () => exec)
jest.unstable_mockModule('@actions/io', () => io)
jest.unstable_mockModule('@actions/tool-cache', () => tc)
jest.unstable_mockModule(
'../src/internal/advancedSecurity.js',
() => advancedSecurity
)

// Module under test.
const scanner = await import('../src/scanner.js')
Expand Down Expand Up @@ -306,6 +311,8 @@ describe('run', () => {
it('should run the scanner successfully', async () => {
io.which.mockResolvedValue(`/usr/local/bin/${semgrep.command}`)
exec.exec.mockResolvedValue(0)
core.getInput.mockReturnValue('fake-token')
advancedSecurity.uploadVulnScansToGHAS.mockResolvedValue('sarif-id-123')

await scanner.run(semgrep)

Expand All @@ -314,6 +321,15 @@ describe('run', () => {
`${semgrep.command} ${semgrep.args.join(' ')}`
)
expect(exec.exec).toHaveBeenCalledWith(semgrep.command, semgrep.args)
expect(core.getInput).toHaveBeenCalledWith('github-token', {
required: true
})
expect(advancedSecurity.uploadVulnScansToGHAS).toHaveBeenCalledWith(
'semgrep.sarif',
'semgrep',
'fake-token'
)
expect(core.setOutput).toHaveBeenCalledWith('sarif-id', 'sarif-id-123')
})

it('should throw an error if the scanner command returns a non-zero exit code', async () => {
Expand Down
12 changes: 2 additions & 10 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,12 @@ runs:
node-version: '24.13.0'
package-manager-cache: false
- name: 'Generate SARIF file'
id: upload
run: node '${{ github.action_path }}/dist/index.js'
env:
INPUT_SCANNER: '${{ inputs.scanner }}'
INPUT_GITHUB-TOKEN: ${{ github.token }}
shell: bash
- name: 'Upload SARIF file as artifact'
uses: actions/upload-artifact@v7
with:
name: semgrep.sarif
path: semgrep.sarif
- name: 'Upload SARIF file to GitHub Advanced Security'
id: upload
uses: github/codeql-action/upload-sarif@v4
with:
sarif_file: semgrep.sarif
- name: 'Dismiss suppressed finding alerts'
uses: advanced-security/dismiss-alerts@v2.0.2
with:
Expand Down
Loading
Loading