### Recommended Workflow Configuration Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md A complete workflow example demonstrating recommended environment variable placement at the workflow level for the Lacework Code Security Action. ```yaml name: Lacework Code Security on: [pull_request, push] env: LW_ACCOUNT: ${{ secrets.LW_ACCOUNT }} LW_API_KEY: ${{ secrets.LW_API_KEY }} LW_API_SECRET: ${{ secrets.LW_API_SECRET }} jobs: # All jobs inherit these env vars ``` -------------------------------- ### Complete GitHub Permissions Example Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Includes permissions for pull request analysis, code scanning, and check status updates. ```yaml permissions: contents: read pull-requests: write security-events: write checks: write ``` -------------------------------- ### List Existing PR Comments Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Example of a GET request to list comments on a GitHub pull request. Includes pagination parameters and authorization header. ```bash GET /repos/owner/repo/issues/123/comments?per_page=100&page=1 Authorization: Bearer ghp_xxxxxxxxxxxxx ``` -------------------------------- ### GitHub Actions Error Log Example Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/errors.md An example of how errors are logged in GitHub Actions, showing timestamps, error messages, and stack traces. ```log 2024-01-15T10:30:45.123Z ℹ️ Analyzing new 2024-01-15T10:30:50.456Z ✗ Error: Missing required environment variable LW_ACCOUNT 2024-01-15T10:30:50.457Z Error: Missing required environment variable LW_ACCOUNT at getRequiredEnvVariable (index.js:123:45) at runCodesecScan (index.js:234:12) at runAnalysis (index.js:89:23) ... ``` -------------------------------- ### Example GitHub Actions Workflow Invocation Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/index.md This example shows how to invoke the Lacework Code Security Action in a GitHub Actions workflow. It demonstrates setting the token and accessing output parameters. ```yaml - id: code-analysis uses: lacework/code-security-action@v1 with: token: ${{ secrets.GITHUB_TOKEN }} - name: Check results run: | if [[ -n "${{ steps.code-analysis.outputs.posted-comment }}" ]]; then echo "Issues found: ${{ steps.code-analysis.outputs.posted-comment }}" fi ``` -------------------------------- ### Child Process Spawn Example Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Demonstrates importing and using the 'spawn' function from Node.js's 'child_process' module to create a child process. Includes an interface for handling the 'close' event. ```typescript import { spawn } from 'child_process' interface ChildProcess { on(event: 'close', listener: (code: number | null) => void): this // other properties/methods } const child: ChildProcess = spawn(command, args, options) interface SpawnOptions { stdio?: 'inherit' | 'ignore' | string[] | undefined } ``` -------------------------------- ### Configure Action to Use Private Image Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md This is an example of how you might configure the action to use a private image. This would typically require forking the action. ```yaml uses: lacework/code-security-action@v1 with: target: new env: # Modify action to use private image (would require forking) ``` -------------------------------- ### getMsSinceStart Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Calculates and returns the elapsed milliseconds since the action started. It uses the LACEWORK_START_TIME environment variable, which must be RFC-3339 formatted. Throws an error if the environment variable is not set or invalid. ```APIDOC ## getMsSinceStart ### Description Get the milliseconds elapsed since action start time. ### Returns string - Milliseconds elapsed as a string ### Behavior Calculates the difference between current time and `LACEWORK_START_TIME` environment variable (expected to be RFC-3339 formatted). ### Throws - Error if `LACEWORK_START_TIME` is not set or invalid ``` -------------------------------- ### Get Milliseconds Since Action Start Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Calculates the milliseconds elapsed since the action started, based on the `LACEWORK_START_TIME` environment variable. Throws an error if the environment variable is not set or invalid. ```typescript export function getMsSinceStart(): string ``` -------------------------------- ### Type Annotation and Usage Example Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Demonstrates how to use type annotations and type guards for handling potentially undefined string values returned from a function. ```typescript // Comment explains what the string represents const modifiedFiles: string | undefined = await getModifiedFiles() // Returns comma-separated list or undefined // Type guard clarifies usage if (modifiedFiles) { // Now known to be non-undefined string const files = modifiedFiles.split(',') } ``` -------------------------------- ### GitHub Actions Core Functions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Demonstrates the usage of core functions from '@actions/core' for reading input parameters, writing output parameters, and logging messages. Ensure '@actions/core' is installed. ```typescript import { getInput, setOutput, info, error, startGroup, endGroup } from '@actions/core' // Read input parameters const target: string = getInput('target') // Write output parameters setOutput('new-completed', true) // Logging info('Message') error('Error message') startGroup('Group name') endGroup() ``` -------------------------------- ### Get GitHub Action Reference Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Retrieves the current GitHub Action reference. Returns 'unknown' if the reference is not available. ```typescript export function getActionRef(): string ``` ```typescript import { getActionRef } from './util' const actionRef = getActionRef() console.log(`Running action: ${actionRef}`) ``` -------------------------------- ### Post Scan Results with Custom Footer Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md This example demonstrates how to include a custom footer in the pull request comments generated by the action. The `token` input is required for posting comments. ```yaml - uses: lacework/code-security-action@v1 with: target: new token: ${{ secrets.GITHUB_TOKEN }} footer: | For more details, see the [Lacework Dashboard](https://myaccount.lacework.net) ``` -------------------------------- ### getActionsApi Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Get the GitHub Actions API client. This client is configured with a retry plugin and a 30-second request timeout. ```APIDOC ## getActionsApi ### Description Get the GitHub Actions API client. This client is configured with a retry plugin and a 30-second request timeout. ### Returns Octokit actions API object. ``` -------------------------------- ### getUsersApi Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Get the GitHub Users API client. This client is configured with a retry plugin and a 30-second request timeout. ```APIDOC ## getUsersApi ### Description Get the GitHub Users API client. This client is configured with a retry plugin and a 30-second request timeout. ### Returns Octokit users API object. ``` -------------------------------- ### Exported Functions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/MANIFEST.txt Documentation for over 25 exported functions, including full signatures, parameter tables, return types, behavior descriptions, error conditions, code examples, and source file references. ```APIDOC ## Exported Functions This section details the 25+ exported functions available in the Lacework Code Security GitHub Action. Each function is documented with its full signature, including types, parameter tables with defaults and descriptions, return type documentation, behavior descriptions, error conditions, code examples, and source file references. ``` -------------------------------- ### Usage Example for Scan Target Type Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Illustrates how to assign and conditionally update a ScanTarget variable. Note that 'push' is handled as a special case mapping to 'scan'. ```typescript let targetScan: ScanTarget = target if (target == 'push') { targetScan = 'scan' } ``` -------------------------------- ### Promise Type Inference Examples Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Illustrates type inference for various asynchronous operations returning Promises. This includes Promises resolving to `void`, `string`, `boolean`, or `undefined`. ```typescript const promise: Promise = runAnalysis() const promise: Promise = downloadArtifact('results-old') const promise: Promise = tryCallCommand('docker', 'ps') const promise: Promise = getModifiedFiles() const promise: Promise = runCodesecCompare() const promise: Promise = generateCacheKey('old') ``` -------------------------------- ### Type Predicate for Error Handling Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Use type predicates to check for the existence of a value before proceeding. This example demonstrates checking if a download path is undefined and throwing an error if it is. ```typescript if (downloadResponse.downloadPath === undefined) { throw new Error('Failed to download artifact') } ``` -------------------------------- ### HTTP Endpoints Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/MANIFEST.txt Information on 20+ HTTP endpoints, including Lacework API, GitHub REST API, and artifact/cache APIs, with request/response examples, status codes, and authentication details. ```APIDOC ## HTTP Endpoints This section documents over 20 HTTP endpoints that the Lacework Code Security GitHub Action interacts with. This includes Lacework API endpoints, GitHub REST API endpoints, and artifact and cache APIs. Each endpoint is described with request/response examples, status codes, and authentication requirements. ``` -------------------------------- ### Octokit API Types for GitHub Actions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Defines types for interacting with GitHub APIs like Issues, Pull Requests, Actions, Organizations, and Users via Octokit. Requires setup with '@actions/github'. ```typescript import { getOctokit } from '@actions/github' type OctokitInstance = ReturnType // Issues API (for PR comments) interface IssuesApi { listComments(options: { owner: string repo: string issue_number: number per_page?: number page?: number }): Promise<{ data: IssueComment[] }> createComment(options: { owner: string repo: string issue_number: number body: string }): Promise<{ data: IssueComment }> updateComment(options: { owner: string repo: string comment_id: number body: string }): Promise<{ data: IssueComment }> } interface IssueComment { id: number url: string html_url: string body?: string user: { login: string } created_at: string updated_at: string } // Pull Requests API type PullRequestsApi = OctokitInstance['rest']['pulls'] // Actions API type ActionsApi = OctokitInstance['rest']['actions'] // Organizations API type OrganizationsApi = OctokitInstance['rest']['orgs'] // Users API type UsersApi = OctokitInstance['rest']['users'] ``` -------------------------------- ### Create New PR Comment Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Example of a POST request to create a new comment on a GitHub pull request. Specifies JSON content type and includes the comment body with a custom marker. ```bash POST /repos/owner/repo/issues/123/comments Authorization: Bearer ghp_xxxxxxxxxxxxx Content-Type: application/json { "body": "## Lacework Code Security Results\nFound 2 new violations\n\n" } ``` -------------------------------- ### GitHub Action Usage for Analysis Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/index.md Examples of how to invoke the Lacework code security action for different analysis targets. Specify the 'target' input to control whether to analyze new code, old code, or perform a push analysis. ```yaml # PR analysis on new code uses: lacework/code-security-action@v1 with: target: new ``` ```yaml # PR analysis on old code uses: lacework/code-security-action@v1 with: target: old ``` ```yaml # Push analysis (uploads to Lacework UI) uses: lacework/code-security-action@v1 with: target: push ``` -------------------------------- ### Recommended Checkout Settings for Actions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Configure the checkout action with fetch-depth 2 for PR comparisons. Ensure GITHUB_TOKEN is provided. ```yaml - uses: actions/checkout@v6 with: fetch-depth: 2 # Required for PR comparisons (HEAD and HEAD^1) token: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Get GitHub Users API Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Use this function to get an Octokit users API object. It is configured with a retry plugin and a 30-second request timeout. ```typescript export function getUsersApi(): Octokit['rest']['users'] ``` -------------------------------- ### Get GitHub Organizations API Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Use this function to get an Octokit orgs API object. It is configured with a retry plugin and a 30-second request timeout. ```typescript export function getOrgsApi(): Octokit['rest']['orgs'] ``` -------------------------------- ### Path Module Key Methods Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Illustrates importing the 'path' module and lists key methods for working with file and directory paths, such as 'join' and 'resolve'. ```typescript import * as path from 'path' // Key methods: // path.join(...segments: string[]): string // path.resolve(...segments: string[]): string ``` -------------------------------- ### Get GitHub Actions API Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Use this function to get an Octokit actions API object. It is configured with a retry plugin and a 30-second request timeout. ```typescript export function getActionsApi(): Octokit['rest']['actions'] ``` -------------------------------- ### Configuration Options Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/MANIFEST.txt Details on 16+ configuration options, including GitHub Action inputs and outputs, required and optional environment variables, GitHub permissions, and network configuration. ```APIDOC ## Configuration Options This section covers 16+ configuration options for the Lacework Code Security GitHub Action. It includes documentation for 5 GitHub Action inputs, 5 GitHub Action outputs, 7+ required environment variables, optional environment variables, GitHub permissions, and network configuration details. ``` -------------------------------- ### Get GitHub Issues API Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Use this function to get an Octokit issues API object. It is configured with a retry plugin and a 30-second request timeout. ```typescript export function getIssuesApi(): Octokit['rest']['issues'] ``` ```typescript import { getIssuesApi } from './actions' const api = getIssuesApi() const comments = await api.listComments({ owner: 'myorg', repo: 'myrepo', issue_number: 123, per_page: 100, page: 1 }) ``` -------------------------------- ### Get GitHub Pull Requests API Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Use this function to get an Octokit pulls API object. It is configured with a retry plugin and a 30-second request timeout. ```typescript export function getPrApi(): Octokit['rest']['pulls'] ``` -------------------------------- ### Artifact Client Initialization and Type Definitions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Shows how to instantiate the 'DefaultArtifactClient' from '@actions/artifact' and defines interfaces for the responses expected from artifact upload and download operations. Requires '@actions/artifact'. ```typescript import { DefaultArtifactClient } from '@actions/artifact' const artifact = new DefaultArtifactClient() // Upload artifact interface UploadArtifactResponse { artifactName: string artifactId: number size: number } // Download artifact interface GetArtifactResponse { artifact: { id: number name: string size_in_bytes: number created_at: string expires_at: string updated_at: string } } interface DownloadArtifactResponse { downloadPath: string | undefined } ``` -------------------------------- ### OS Module Key Method Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Shows the import statement for the 'os' module and highlights the 'tmpdir' method for retrieving the default directory for temporary files. ```typescript import * as os from 'os' // Key methods: // os.tmpdir(): string ``` -------------------------------- ### Get Artifact Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Retrieves artifact metadata. This is a private endpoint used internally by the action. ```APIDOC ## GET Get Artifact ### Description Retrieves metadata for a specific artifact. ### Method GET ### Endpoint Private (via DefaultArtifactClient from @actions/artifact) ### Parameters #### Path Parameters - **artifactName** (string) - Required - The name of the artifact to retrieve. ### Response #### Success Response (200) - **artifact** (object) - Metadata of the artifact including id, name, size_in_bytes, created_at, expires_at, updated_at. ``` -------------------------------- ### Get Artifact Metadata Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Retrieve metadata for a specific artifact. Requires the artifact name. ```typescript const response = await artifact.getArtifact(artifactName) // response.artifact = { id, name, size_in_bytes, created_at, expires_at, updated_at } ``` -------------------------------- ### Configure HTTP Proxy for Action Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Set environment variables to configure the action to use an HTTP proxy. This is necessary if your network environment requires a proxy for internet access. ```yaml env: HTTP_PROXY: http://proxy.example.com:8080 HTTPS_PROXY: http://proxy.example.com:8080 NO_PROXY: localhost,127.0.0.1 LW_ACCOUNT: ${{ secrets.LW_ACCOUNT }} LW_API_KEY: ${{ secrets.LW_API_KEY }} LW_API_SECRET: ${{ secrets.LW_API_SECRET }} ``` -------------------------------- ### Prepare Scanner Files Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/index.md Helper function to prepare SCA or IAC files for comparison. Determines file extension, checks for existence, logs status, and copies files to the scan-results directory. Returns false if essential files are missing. ```typescript async function prepareScannerFiles( scanner: 'sca' | 'iac', artifactOld: string, artifactNew: string ): Promise ``` -------------------------------- ### Checkout Settings for Push/Scheduled Analysis Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md For push or scheduled analysis, a fetch-depth of 0 is recommended for full history, though it's optional for push scans. ```yaml - uses: actions/checkout@v6 with: fetch-depth: 0 # Full history optional for push scans ``` -------------------------------- ### getOrgsApi Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Get the GitHub Organizations API client. This client is configured with a retry plugin and a 30-second request timeout. ```APIDOC ## getOrgsApi ### Description Get the GitHub Organizations API client. This client is configured with a retry plugin and a 30-second request timeout. ### Returns Octokit orgs API object. ``` -------------------------------- ### GitHub Actions Context and Octokit Client Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Illustrates how to import and use the 'context' object for accessing GitHub event payload and repository information, and how to initialize the 'getOctokit' client for interacting with the GitHub API. Requires '@actions/github' and a valid token. ```typescript import { context, getOctokit } from '@actions/github' // GitHub context object const context: typeof context = { payload: { pull_request?: { number: number // ... other PR fields } }, repo: { owner: string // e.g., 'lacework' repo: string // e.g., 'code-security-action' }, workflow: string // Workflow filename action: string // Action step name // ... other context fields } // Octokit REST API client const octokit = getOctokit(token, options, retry) ``` -------------------------------- ### getIssuesApi Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Get the GitHub Issues API client. This client is configured with a retry plugin and a 30-second request timeout. ```APIDOC ## getIssuesApi ### Description Get the GitHub Issues API client. This client is configured with a retry plugin and a 30-second request timeout. ### Returns Octokit issues API object with methods like `createComment`, `updateComment`, `listComments`. ### Example ```typescript import { getIssuesApi } from './actions' const api = getIssuesApi() const comments = await api.listComments({ owner: 'myorg', repo: 'myrepo', issue_number: 123, per_page: 100, page: 1 }) ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/architecture.md Illustrates the directory and file organization for the Code Security Action project, including source, compiled output, and workflow definitions. ```yaml / ├── action.yaml # GitHub Action definition ├── package.json # Node.js dependencies ├── tsconfig.json # TypeScript configuration ├── src/ │ ├── index.ts # Main entry point │ ├── actions.ts # GitHub API functions │ └── util.ts # System integration functions ├── dist/ # Compiled JavaScript (generated) │ └── src/ │ ├── index.js │ ├── actions.js │ └── util.js └── .github/workflows/ # Test workflows ├── unit-tests.yml ├── integration-test.yml └── update-tag.yml ``` -------------------------------- ### getPrApi Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/actions.md Get the GitHub Pull Requests API client. This client is configured with a retry plugin and a 30-second request timeout. ```APIDOC ## getPrApi ### Description Get the GitHub Pull Requests API client. This client is configured with a retry plugin and a 30-second request timeout. ### Returns Octokit pulls API object. ``` -------------------------------- ### Log Failed to Get Modified Files Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/errors.md Logs an error if retrieving modified files fails, allowing the action to proceed without interruption. ```typescript catch (e) { info(`Failed to get modified files: ${e}`) } ``` -------------------------------- ### Utility Functions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/MANIFEST.txt Helper functions for executing commands, managing environment variables, and interacting with the file system. ```APIDOC ## callCommand() ### Description Executes shell commands with error checking. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` callCommand() ``` ### Response None specified ``` ```APIDOC ## tryCallCommand() ### Description Executes shell commands without throwing errors. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` tryCallCommand() ``` ### Response None specified ``` ```APIDOC ## getRequiredEnvVariable() ### Description Retrieves a required environment variable. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getRequiredEnvVariable() ``` ### Response None specified ``` ```APIDOC ## getOptionalEnvVariable() ### Description Retrieves an optional environment variable with a default value. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getOptionalEnvVariable() ``` ### Response None specified ``` ```APIDOC ## getOrDefault() ### Description Retrieves a GitHub Actions input or a default value. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getOrDefault() ``` ### Response None specified ``` ```APIDOC ## getActionRef() ### Description Retrieves the reference for the current GitHub Action. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getActionRef() ``` ### Response None specified ``` ```APIDOC ## getRunUrl() ### Description Constructs the URL for a GitHub Actions run. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getRunUrl() ``` ### Response None specified ``` ```APIDOC ## getMsSinceStart() ### Description Gets the elapsed milliseconds since the action started. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getMsSinceStart() ``` ### Response None specified ``` ```APIDOC ## getModifiedFiles() ### Description Gets a list of modified files from a git diff. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` getModifiedFiles() ``` ### Response None specified ``` ```APIDOC ## runCodesecScan() ### Description Executes a Docker-based Lacework scanner. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` runCodesecScan() ``` ### Response None specified ``` ```APIDOC ## runCodesecCompare() ### Description Executes a Docker-based result comparison. ### Method Not specified (SDK function) ### Endpoint Not applicable ### Parameters None specified ### Request Example ``` runCodesecCompare() ``` ### Response None specified ``` -------------------------------- ### Construct GitHub Actions Run URL Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Constructs the full URL to the current GitHub Actions run using environment variables. Throws an error if required environment variables are missing. ```typescript export function getRunUrl(): string ``` ```typescript import { getRunUrl } from './util' const runUrl = getRunUrl() // Returns: https://github.com/owner/repo/actions/runs/12345 ``` -------------------------------- ### Login to Docker Registry Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Use this command to log in to a private Docker registry. Ensure you have the necessary credentials. ```yaml - name: Login to Docker registry run: docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PASS }} private-registry.example.com ``` -------------------------------- ### Main Entry Point Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/index.md The main function that dispatches to the appropriate workflow based on the 'target' input. It calls runAnalysis if target is provided, otherwise displayResults. Errors are caught and logged without failing the action. ```typescript async function main(): Promise ``` ```typescript // Automatically called at module load time main() .catch((e) => { error(e.message) }) .finally(async () => {}) ``` -------------------------------- ### Get Optional Environment Variable with Default Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Retrieve an environment variable, returning a specified default value if the variable is not found. This is useful for non-critical configurations. ```typescript export function getOptionalEnvVariable(name: string, defaultValue: string): string ``` ```typescript import { getOptionalEnvVariable } from './util' const branch = getOptionalEnvVariable('GITHUB_HEAD_REF', '') const workspace = getOptionalEnvVariable('WORKSPACE', '.') ``` -------------------------------- ### Type Definitions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/MANIFEST.txt Details on 15+ type definitions, including GitHub Actions types, Octokit API types, module-specific types, and type inference patterns. ```APIDOC ## Type Definitions This section provides documentation for over 15 type definitions used within the Lacework Code Security GitHub Action. This includes GitHub Actions types, Octokit API types, module-specific types, and explanations of type inference patterns. ``` -------------------------------- ### Enable Debug Logging via GitHub Actions Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Enable debug logging for the action by setting the ACTIONS_STEP_DEBUG environment variable to true. ```bash # Via GitHub Actions ACTIONS_STEP_DEBUG=true ``` -------------------------------- ### getRunUrl Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Constructs the full URL to the current GitHub Actions run using environment variables like GITHUB_SERVER_URL, GITHUB_REPOSITORY, and GITHUB_RUN_ID. Throws an error if required environment variables are missing. ```APIDOC ## getRunUrl ### Description Construct the GitHub Actions run URL from environment variables. ### Returns string - Full URL to the current GitHub Actions run ### Behavior Constructs URL from: - `GITHUB_SERVER_URL` (e.g., https://github.com) - `GITHUB_REPOSITORY` (e.g., owner/repo) - `GITHUB_RUN_ID` (numeric run ID) ### Throws - Error if required environment variables are missing ### Example ```typescript import { getRunUrl } from './util' const runUrl = getRunUrl() // Returns: https://github.com/owner/repo/actions/runs/12345 ``` ``` -------------------------------- ### Get Required Environment Variable Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Use this function to retrieve a mandatory environment variable. It throws an error if the variable is not set or is empty, ensuring critical configurations are present. ```typescript export function getRequiredEnvVariable(name: string): string ``` ```typescript import { getRequiredEnvVariable } from './util' const lwAccount = getRequiredEnvVariable('LW_ACCOUNT') const apiKey = getRequiredEnvVariable('LW_API_KEY') ``` -------------------------------- ### Get Modified Files for PR Scan Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/INDEX.md Retrieves modified files using `git diff` for PR 'new' target scans. Pass the output to `runCodesecScan` as `MODIFIED_FILES`. ```bash getModifiedFiles() → git diff HEAD^1...HEAD → Pass to runCodesecScan() as MODIFIED_FILES ``` -------------------------------- ### Handle Missing SCA Files for Comparison Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/errors.md Ensures that necessary SCA files are available for comparison. If files are not found or cannot be prepared, an error is logged, and the comparison process is aborted. ```typescript if (!(await prepareScannerFiles('sca', artifactOld, artifactNew))) { error('SCA files not found. Cannot perform compare.') return } ``` -------------------------------- ### Download Artifact Files Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Download all files from a specified artifact to a local directory. Requires the artifact ID and a download path. ```typescript const response = await artifact.downloadArtifact(artifactId, { path: downloadPath }) // response.downloadPath = '/path/to/artifact' ``` -------------------------------- ### getOptionalEnvVariable Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Retrieves an environment variable, returning a default value if it's not set. ```APIDOC ## getOptionalEnvVariable ### Description Get an environment variable or return a default value if not present. ### Signature ```typescript export function getOptionalEnvVariable(name: string, defaultValue: string): string ``` ### Parameters #### Path Parameters - **name** (string) - Required - Environment variable name - **defaultValue** (string) - Required - Value to return if variable is not set ### Returns string - The environment variable value or the default value ### Example ```typescript import { getOptionalEnvVariable } from './util' const branch = getOptionalEnvVariable('GITHUB_HEAD_REF', '') const workspace = getOptionalEnvVariable('WORKSPACE', '.') ``` ``` -------------------------------- ### Optional Type Inference Examples Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Shows type inference for variables that can hold a value or be `undefined`. This is common for optional environment variables, function return values, or potentially missing data. ```typescript const branch: string = getOptionalEnvVariable('GITHUB_HEAD_REF', '') const files: string | undefined = await getModifiedFiles() const cacheKey: string | undefined = await generateCacheKey('old') const commentUrl: string | undefined = await postCommentIfInPr(message) const foundComment: number | undefined = await findExistingComment(hash) ``` -------------------------------- ### Configure PR Analysis Workflow Source: https://github.com/lacework/code-security-action/blob/main/README.md Set up a GitHub Actions workflow to analyze pull requests. This workflow checks for new alerts and requires repository secrets for authentication. ```yaml on: - pull_request permissions: contents: read pull-requests: write env: LW_ACCOUNT: ${{ secrets.LW_ACCOUNT }} LW_SUBACCOUNT: ${{ secrets.LW_SUBACCOUNT }} LW_API_KEY: ${{ secrets.LW_API_KEY }} LW_API_SECRET: ${{ secrets.LW_API_SECRET }} name: Lacework Code Security (PR) jobs: run-analysis: runs-on: ubuntu-latest name: Run analysis strategy: matrix: target: [new, old] steps: - name: Checkout repository uses: actions/checkout@v6 with: fetch-depth: 2 - name: Checkout old if: ${{ matrix.target == 'old' }} run: git checkout HEAD^1 - name: Analyze uses: lacework/code-security-action@v1 with: target: ${{ matrix.target }} display-results: runs-on: ubuntu-latest name: Display results needs: - run-analysis steps: - name: Results id: code-analysis uses: lacework/code-security-action@v1 with: token: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Get GitHub Actions Input or Default Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Retrieve a GitHub Actions input parameter, providing a default value if the input is not set or is empty. This simplifies handling optional inputs in workflows. ```typescript export function getOrDefault(name: string, defaultValue: string): string ``` ```typescript import { getOrDefault } from './util' const sources = getOrDefault('sources', '.') const codeScanPath = getOrDefault('code-scanning-path', 'code-scanning.sarif') ``` -------------------------------- ### Parallel Execution Strategy Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/INDEX.md Utilizes GitHub Actions matrix jobs for concurrent analysis. 'analyze' jobs run in parallel, while 'display' depends on their completion. ```yaml Job 1: analyze (target: new) Job 2: analyze (target: old) ← Parallel Job 3: display (needs: analyze) ← Sequential after jobs 1-2 ``` -------------------------------- ### Checkout Settings for PR Analysis Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md For PR analysis, fetch-depth 2 is needed to access both the PR branch and the base branch. A separate step checks out the base branch for 'old' targets. ```yaml - uses: actions/checkout@v6 with: fetch-depth: 2 # Need both PR branch and base branch # For 'old' target, checkout the base branch - name: Checkout old if: ${{ matrix.target == 'old' }} run: git checkout HEAD^1 ``` -------------------------------- ### Diagnose Docker Issues Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/errors.md Commands to help diagnose common Docker-related problems that might cause scan failures. ```bash # Check Docker daemon docker ps # Check image availability docker images lacework/codesec # Check free disk space df -h ``` -------------------------------- ### Configure Push/Scheduled Analysis Workflow Source: https://github.com/lacework/code-security-action/blob/main/README.md Configure a GitHub Actions workflow to perform code security analysis on pushes to the main branch or on a schedule. Findings are uploaded to the Lacework UI. Requires repository secrets for authentication. ```yaml on: push: # Run the scan on evey push in main branches: [main] # Run the scan evey day at 7:00am schedule: - cron: '0 7 * * *' # To manually trigger scans from the GitHub UI workflow_dispatch: env: LW_ACCOUNT: ${{ secrets.LW_ACCOUNT }} LW_API_KEY: ${{ secrets.LW_API_KEY }} LW_API_SECRET: ${{ secrets.LW_API_SECRET }} name: Lacework Code Security (Push) jobs: run-analysis: runs-on: ubuntu-latest name: Run analysis steps: - name: Checkout repository uses: actions/checkout@v6 - name: Analyze uses: lacework/code-security-action@v1 with: target: push ``` -------------------------------- ### Download Old Scan Artifacts Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Use the 'actions/download-artifact' action to download specific artifacts, such as 'results-old', into a local directory for inspection. ```yaml - name: Download old results uses: actions/download-artifact@v3 with: name: results-old path: ./old-results - name: Inspect results run: | ls -la ./old-results/ jq . ./old-results/scan-results/iac/iac-old.json ``` -------------------------------- ### Get Modified Files in Commit Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/util.md Retrieves a comma-separated list of files modified in the current commit by comparing HEAD with its parent. Returns undefined if the git command fails. Errors are logged internally. ```typescript export async function getModifiedFiles(): Promise ``` ```typescript import { getModifiedFiles } from './util' const files = await getModifiedFiles() if (files) { console.log(`Modified files: ${files}`) // Output: src/main.ts,src/util.ts,README.md } ``` -------------------------------- ### MD5 Type Definition and Usage Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Defines and demonstrates the usage of the `Md5` class from the `ts-md5` library for hashing strings. It shows how to append strings and end the hashing process. ```typescript import { Md5 } from 'ts-md5' class Md5 { appendStr(input: string): Md5 end(): string | undefined } // Usage: const md5 = new Md5() md5.appendStr('lacework-code-security') md5.appendStr(context.workflow) const result: string | undefined = md5.end() ``` -------------------------------- ### Example Update Pull Request Comment JSON Request Body Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Demonstrates the JSON payload required to update an existing pull request comment. The 'body' field is used to provide the new content for the comment. ```json { "body": "Updated: All issues previously detected have been resolved!\n\n" } ``` -------------------------------- ### Configure Firewall Rules for Code Security Action Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/INDEX.md These `iptables` commands configure outbound firewall rules to allow the action to communicate with GitHub, Docker Hub, and the Lacework API over HTTPS. ```bash # Allow GitHub iptables -A OUTPUT -p tcp --dport 443 -d api.github.com -j ACCEPT iptables -A OUTPUT -p tcp --dport 443 -d github.com -j ACCEPT # Allow Docker Hub iptables -A OUTPUT -p tcp --dport 443 -d docker.io -j ACCEPT # Allow Lacework iptables -A OUTPUT -p tcp --dport 443 -d "*.lacework.net" -j ACCEPT ``` -------------------------------- ### Example Pull Request Comment JSON Response Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Illustrates the structure of a comment object returned by the GitHub API when listing pull request comments. Includes fields like ID, URL, author, and content. ```json [ { "id": 1, "url": "https://api.github.com/repos/owner/repo/issues/comments/1", "html_url": "https://github.com/owner/repo/issues/123#issuecomment-1", "body": "Comment text with footer", "user": { "login": "github-actions[bot]" }, "created_at": "2024-01-15T10:30:00Z", "updated_at": "2024-01-15T10:35:00Z" } ] ``` -------------------------------- ### Explicit Function Parameter Types Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Explicitly define the types for all function parameters to enhance readability and prevent type-related errors. This example shows a function with a string literal union type, string types, and a Promise return type. ```typescript function prepareScannerFiles( scanner: 'sca' | 'iac', artifactOld: string, artifactNew: string ): Promise ``` -------------------------------- ### Scan New PR Code with Lacework Action Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/configuration.md Use this configuration to scan newly committed code in a pull request. Ensure the `sources` parameter is set to '.' for the current directory. ```yaml - uses: lacework/code-security-action@v1 with: target: new sources: . ``` -------------------------------- ### Upload Artifact Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Upload specified files as an artifact. Requires a name for the artifact, an array of file paths, and a root directory for relative paths. ```typescript await artifact.uploadArtifact(artifactName, files, rootDirectory) ``` -------------------------------- ### Example Create Pull Request Comment JSON Request Body Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Shows the expected JSON payload for creating a new pull request comment. The 'body' field contains the comment text, which can include Markdown and a tracking hash. ```json { "body": "## Lacework Code Security Results\n\nFound 3 new potential violations\n\n...\n\n" } ``` -------------------------------- ### Restore and Save Cache with @actions/cache Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/types.md Use these generic Promise-based APIs to restore or save caches. Ensure paths and keys are correctly defined. ```typescript import * as cache from '@actions/cache' // Restore cache const restored: string | undefined = await cache.restoreCache( paths: string[], primaryKey: string ) // Save cache const cacheId: number = await cache.saveCache( paths: string[], key: string ) ``` -------------------------------- ### Download Artifact Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/endpoints.md Downloads all files from a specified artifact to a given directory. This is a private endpoint. ```APIDOC ## GET Download Artifact ### Description Downloads all files from a specified artifact to a designated directory. ### Method GET ### Endpoint Private (via DefaultArtifactClient) ### Parameters #### Path Parameters - **artifactId** (string) - Required - The ID of the artifact to download. #### Query Parameters - **path** (string) - Required - The directory path where the artifact files should be downloaded. ### Response #### Success Response (200) - **downloadPath** (string) - The path to the directory where the artifact was downloaded. ``` -------------------------------- ### Run Code Security Analysis Source: https://github.com/lacework/code-security-action/blob/main/_autodocs/api-reference/index.md This function executes code security scans on a specified target. It handles context determination, Git branch setup, PR optimization, caching, scanner execution, result collection, and artifact uploading. Reads inputs from GitHub Actions context. ```typescript async function runAnalysis(): Promise ```