GitHub Actions logs help developers understand what happens during a build, test, deployment, or release. When a workflow fails, developers usually open the job logs, identify the failed step, and investigate the problem.
However, logs can also expose sensitive information. A debugging statement might print an API token, a deployment script might display a connection string, or a third-party tool might include an authentication header in an error message. Once sensitive information appears in a workflow log, everyone with permission to view that run may potentially see it.
GitHub Actions provides automatic secret masking, but masking should not be treated as a complete security solution. It primarily protects values GitHub knows about, and it may not recognize transformed, encoded, or previously unknown credentials.
A safer approach is to combine GitHub's built-in masking with secret detection before application output is forwarded to workflow logs or uploaded as an artifact.
In this article, we will explore how secrets leak into GitHub Actions logs, understand the limitations of automatic masking, and build a practical detection mechanism using Python and GitHub Actions. We will also discuss false positives, generated credentials, third-party tools, and what to do when a secret has already been exposed.
Understanding How Secrets Reach GitHub Actions Logs
A GitHub Actions workflow usually interacts with several external systems. It may restore packages, connect to databases, call APIs, authenticate with cloud services, or deploy an application.
These operations require credentials such as:
- API keys.
- Database connection strings.
- Cloud access keys.
- Personal access tokens.
- Private registry credentials.
- SSH private keys.
- OAuth access tokens.
- Webhook signing secrets.
GitHub Actions allows developers to store sensitive values as repository, environment, or organization secrets.
For example, a workflow can access a repository secret through the secrets context:
name: Deploy Application
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy application
env:
API_TOKEN: ${{ secrets.DEPLOYMENT_API_TOKEN }}
run: |
./deploy.sh
The secret is passed to the deployment process through an environment variable.
This is better than placing the token directly inside the workflow file. However, the application or deployment script can still accidentally print the value.
For example:
echo "Using API token: $API_TOKEN"
A developer may add this statement while troubleshooting an authentication problem. If the token is not masked successfully, the value can appear in the workflow log.
Other tools can also expose credentials without an explicit echo statement. An HTTP client might include request headers in debug output, a database driver might print connection details, or a failed deployment command might display its configuration.
This is why protecting secrets requires more than storing them securely.
How GitHub Actions Automatically Masks Secrets
GitHub Actions automatically attempts to redact configured secrets from workflow logs.
When a value matches a secret known to GitHub, the runner replaces the matching text with a masked representation.
For example, suppose a workflow secret contains:
ghp_example_sensitive_token_value
If a command prints the exact value, the log may display something similar to:
Using token: ***
This behavior is useful, but it has important limitations.
Masking Depends on Recognizing the Secret Value
GitHub cannot automatically recognize every sensitive value generated or discovered during a workflow.
For example, an application might generate a temporary authentication token during deployment. If the token was not registered for masking, it may be printed without redaction.
GitHub provides the add-mask workflow command for registering additional sensitive values:
echo "::add-mask::$GENERATED_TOKEN"
After registering the value, subsequent matching output is treated as sensitive and redacted within that job.
The order is important. Register the value before printing it or using it in a workflow command that might expose it.
Transformed Values May Not Be Masked
Consider an API token stored as a GitHub secret.
The original token might be masked, but the following operations can produce different strings:
- Base64 encoding.
- URL encoding.
- JSON escaping.
- Adding a prefix or suffix.
- Splitting the token into multiple parts.
- Printing only a portion of the token.
These transformed values may not match the original secret value.
For example:
ENCODED_TOKEN=$(printf '%s' "$API_TOKEN" | base64)
echo "Encoded token: $ENCODED_TOKEN"
The encoded token is not the same string as the original secret. Do not assume that masking the original value automatically protects every representation of it.
Structured Data Requires Additional Care
A JSON document can contain credentials alongside ordinary application settings.
For example:
{
"application": "OrderService",
"database": {
"server": "db.internal",
"password": "sensitive-password"
}
}
If the complete JSON document is printed, automatic masking may not recognize every sensitive representation.
GitHub recommends avoiding structured data as secret values because redaction largely relies on matching the exact secret value.
A better approach is to avoid printing sensitive configuration objects altogether.
Building a Secret Detection Script
Automatic masking is useful for values already known to GitHub. A separate detection step can help identify credentials that were not registered as secrets.
For this example, we will build a Python script that examines application output before it is forwarded to GitHub Actions logs.
The script will:
- Execute an application command.
- Capture its standard output and standard error.
- Search the captured output for common credential patterns.
- Replace detected values before displaying the output.
- Return a failure status if a possible secret is found.
This is not a complete secret detection engine. It is a practical first layer that demonstrates how to prevent suspicious output from being printed directly.
Creating the Detection Script
Create a file named detect_secrets.py.
import re
import subprocess
import sys
PATTERNS = [
(
"GitHub token",
re.compile(
r"\b(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9_]{20,}\b"
)
),
(
"AWS access key",
re.compile(r"\bAKIA[0-9A-Z]{16}\b")
),
(
"Private key",
re.compile(
r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"
)
),
(
"Password assignment",
re.compile(
r"(?i)(password|passwd|client_secret)\s*[:=]\s*"
r"['\"]?[^,\s'\"}]+"
)
),
(
"Bearer token",
re.compile(
r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{12,}"
)
)
]
def inspect_output(output):
findings = []
for label, pattern in PATTERNS:
if pattern.search(output):
findings.append(label)
return findings
def redact_output(output):
redacted = output
for _, pattern in PATTERNS:
redacted = pattern.sub("[REDACTED]", redacted)
return redacted
def main():
if len(sys.argv) < 2:
print("Usage: python detect_secrets.py command [arguments]")
return 2
command = sys.argv[1:]
result = subprocess.run(
command,
capture_output=True,
text=True,
errors="replace"
)
combined_output = result.stdout + result.stderr
findings = inspect_output(combined_output)
safe_output = redact_output(combined_output)
if safe_output:
print(safe_output, end="")
if findings:
print("\nPotential sensitive information detected:")
for finding in sorted(set(findings)):
print(f"- {finding}")
print("Review the application output securely.")
return 1
return result.returncode
if __name__ == "__main__":
sys.exit(main())
The script uses regular expressions to identify several common credential patterns.
The important design decision is that the detected value is never printed in the detection summary. The output only identifies the category of the possible secret.
The script also replaces matching values before displaying the captured output.
For example, if the application prints:
Deployment started.
Using token: ghp_example_sensitive_token_value
Deployment failed.
The workflow displays:
Deployment started.
Using token: [REDACTED]
Deployment failed.
Potential sensitive information detected:
- GitHub token
Review the application output securely.
The original output is captured in memory and is not directly forwarded to the GitHub Actions log.
The regular expressions are intentionally limited examples. They will not detect every credential format, and some patterns can match ordinary configuration values. A production implementation should use a maintained secret detection tool with rules appropriate for the credentials used by the organization.
Running the Detection Script Locally
Before integrating the script into GitHub Actions, test it locally.
First, run a command that produces normal output:
python detect_secrets.py python -c "print('Build completed successfully')"
The script displays the output and returns the command's exit code because no potential secret was found.
Now test it with a sample token:
python detect_secrets.py python -c "print('Token: ghp_example_sensitive_token_value')"
The script should replace the matching value and return a nonzero exit code.
You can also test a password assignment:
python detect_secrets.py python -c "print('password=sample-password-value')"
The output should contain the redacted value rather than the original password.
Use clearly artificial test values. Do not test the detector by deliberately printing a real production credential.
Integrating Secret Detection Into GitHub Actions
Once the script works locally, add it to the repository and call it from a workflow.
For example:
name: Secure Build
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Run build with secret detection
run: |
python scripts/detect_secrets.py \
dotnet build MyApplication.sln
The detection script captures the build command's standard output and standard error.
If a supported credential pattern is found, the script prints the sanitized output and returns a failure status. GitHub Actions then marks the step as failed.
This provides a basic safeguard against known credential patterns appearing in the build output.
However, the example captures the complete command output in memory. For commands that produce very large logs, use a streaming implementation that scans output incrementally and writes only sanitized content to the workflow log.
Also, this approach only protects output from commands executed through the wrapper. Other workflow steps and third-party actions can still write directly to the runner log.
Using a Dedicated Secret Scanning Tool
A small custom script is useful for demonstrating the detection process, but maintaining credential patterns manually is difficult.
Different services use different token formats. Some credentials have recognizable prefixes, while others are random strings that require additional detection techniques.
A dedicated scanner such as Gitleaks can provide broader coverage.
Gitleaks is commonly used to detect secrets in source code, configuration files, and other repository content. It can also inspect files generated during a workflow.
For example, a workflow can install a pinned version of Gitleaks and scan a generated log file:
- name: Install Gitleaks
run: |
curl -sSfL \
https://raw.githubusercontent.com/gitleaks/gitleaks/master/scripts/install.sh \
| bash -s -- -b /usr/local/bin
- name: Scan generated log
run: |
gitleaks dir ./build-logs \
--redact \
--exit-code 1
This example assumes that the application output has been redirected into the build-logs directory without first being printed to the workflow log.
The scanner's --redact option helps prevent detected values from appearing in its report, while --exit-code controls the failure status.
For a production workflow, pin the scanner to a reviewed release or verified commit rather than installing whatever version is currently available from a moving branch. Verify the command-line options against the version you deploy.
Gitleaks and similar tools are useful, but they are not perfect. They can produce false positives, and no scanner should be treated as a guarantee that every possible credential will be detected.
Capturing Third-Party Tool Output Safely
Many secret leaks originate from third-party tools rather than application code.
For example, a deployment tool might print HTTP request details when debug mode is enabled. A package manager might display authentication configuration during troubleshooting. A database migration tool might include connection details in an exception.
A common mistake is running these commands directly:
- name: Deploy application
run: |
./deployment-tool --debug
If the tool prints sensitive information, it goes directly to the workflow log.
A safer approach is to capture the output first and process it before displaying anything.
For example:
- name: Run deployment safely
run: |
mkdir -p build-logs
set +e
./deployment-tool \
> build-logs/deployment.log 2>&1
DEPLOY_STATUS=$?
set -e
python scripts/detect_secrets.py \
python -c "print(open('build-logs/deployment.log').read())"
exit "$DEPLOY_STATUS"
This example demonstrates the capture-before-display approach, but the Python wrapper shown earlier is better suited to larger outputs and should be adapted to avoid loading large files entirely into memory.
Also, do not upload the original deployment.log file as an artifact simply because it is not printed to the console. It may still contain credentials.
If logs need to be preserved for troubleshooting, create a sanitized copy and upload only that copy after validation.
Masking Dynamically Generated Secrets
Sometimes a workflow creates a temporary credential during execution.
For example, a deployment process might request a short-lived token from an internal authentication service.
GitHub cannot necessarily recognize this token automatically because it was generated after the workflow started.
Register the value for masking immediately after generating it:
- name: Generate temporary token
id: token
shell: bash
run: |
TOKEN=$(./get-temporary-token.sh)
if [ -z "$TOKEN" ]; then
echo "Token generation failed."
exit 1
fi
echo "::add-mask::$TOKEN"
echo "token=$TOKEN" >> "$GITHUB_OUTPUT"
A later step in the same job can use the output:
- name: Use temporary token
env:
API_TOKEN: ${{ steps.token.outputs.token }}
run: |
./deploy.sh
The token is registered for masking before it is passed to the later step.
Do not print the token while generating it. If the command that creates the token writes the value to standard output, capture that output without forwarding it to the log.
Also remember that masking is a redaction mechanism, not a permission boundary. Any process that receives a secret may be able to use it. Avoid exposing credentials to untrusted code.
Protecting Logs From Pull Requests and Untrusted Code
Secret detection is only one part of GitHub Actions security.
A particularly important risk comes from workflows that execute code submitted by external contributors.
For public repositories, workflows triggered by pull_request events from forks normally do not receive repository secrets, and the GITHUB_TOKEN is restricted. This helps reduce the impact of untrusted pull requests.
However, developers sometimes use pull_request_target because they need access to the base repository's secrets or write permissions.
This event runs in a privileged context. Checking out and executing untrusted pull request code in such a workflow can expose repository secrets and tokens.
For example, an attacker could modify a build script or package installation step to read environment variables and send their contents outside the runner.
A log scanner cannot reliably prevent this type of attack because the credential might be exfiltrated without ever appearing in the logs.
Follow these practices:
- Prefer pull_request when privileged access is not required.
- Do not execute untrusted fork code in a privileged workflow.
- Keep GITHUB_TOKEN permissions as restrictive as possible.
- Avoid passing secrets to build and test processes that do not need them.
- Review third-party actions before using them.
- Pin actions to reviewed commit SHAs where practical.
- Use environment protection rules for sensitive deployments.
- Consider OpenID Connect for supported cloud authentication instead of long-lived cloud credentials.
The strongest protection is preventing untrusted processes from receiving secrets in the first place.
Handling False Positives and Detection Failures
Secret scanners can identify strings that resemble credentials but are not actually sensitive.
For example, a test fixture might contain a sample token, a documentation file might show a fake connection string, or a generated identifier might match a scanner rule.
If every detection automatically blocks a build, developers may become accustomed to ignoring security failures.
A better approach is to classify findings and review them carefully.
| Finding | Recommended action |
|---|
| Confirmed production credential | Stop exposure and rotate the credential |
| Known test credential | Verify that it is artificial and safely scoped |
| False positive | Document the reason and add a narrow exclusion |
| Unknown credential | Treat it as potentially sensitive until verified |
| Repeated detection | Fix the source rather than repeatedly suppressing the finding |
Avoid creating broad exclusions for entire log directories or file types. An exclusion that removes too much coverage can hide real credentials.
Also, do not include the detected value in the failure message. Show the file, line number, or category only when doing so does not expose sensitive information.
What to Do When a Secret Has Already Been Exposed
If a real credential appears in a GitHub Actions log, masking it afterward does not make the original exposure harmless.
Treat the credential as compromised.
The response should include:
- Identify the affected workflow run and the credential involved.
- Revoke or rotate the exposed credential immediately.
- Check the credential's audit history for suspicious activity.
- Remove the exposed workflow log or artifact where possible.
- Review who had access to the affected run.
- Investigate the code or action that printed the credential.
- Add a preventive control to avoid the same problem.
Deleting a workflow log does not invalidate a credential that may already have been copied.
If the credential provides access to cloud resources, databases, package registries, or source repositories, review those systems for unauthorized activity.
The priority should be revoking the credential, not simply hiding the visible log entry.
Best Practices for Protecting GitHub Actions Logs
A reliable log security strategy combines several controls rather than depending on one scanner.
Use GitHub secrets for sensitive configuration and register dynamically generated values with add-mask before they can be printed.
Capture output from tools that might expose credentials, inspect it before displaying it, and upload only sanitized artifacts.
Use dedicated secret scanning tools for broader pattern detection. Keep scanner versions controlled and review findings instead of automatically suppressing them.
Most importantly, limit which processes can access secrets. Do not give deployment credentials to ordinary build steps or untrusted pull request workflows when they are not required.
For high-value credentials, prefer short-lived authentication and supported OpenID Connect integrations over long-lived static secrets.
Summary
GitHub Actions logs are essential for troubleshooting builds and deployments, but they can also expose sensitive information when scripts or third-party tools print credentials.
GitHub's automatic secret masking provides an important first layer of protection. However, it cannot guarantee that every transformed, dynamically generated, or previously unknown credential will be hidden.
A safer workflow combines built-in masking with output capture, secret scanning, and sanitized log publishing. A small Python wrapper can demonstrate this approach, while dedicated tools such as Gitleaks provide broader detection capabilities.
The most important security principle is to prevent unnecessary secret access in the first place. Keep credentials away from untrusted code, restrict workflow permissions, rotate exposed values immediately, and treat log scanning as an additional safeguard rather than a replacement for secure workflow design.
Join the conversation! Your thoughts help the community grow.