Develop a secrets scanning bot scanning repos, artifacts, and runtime envs with…
- User
Develop a secrets scanning bot scanning repos, artifacts, and runtime envs with auto-revocation.
- Assistant
Develop a secrets scanning bot scanning repos, artifacts, and runtime envs with auto-revocation.
We are going to design a secrets scanning bot that can:
However, note that automatic revocation might be risky and should be done with caution. We must:
Given the complexity and the potential for breaking systems, we might break the process into: a. Detection (scanning) b. Validation (confirming it's a real secret and in use) c. Remediation (revocation and rotation)
Steps for the bot:
Scanning:
gitleaks, truffleHog, or custom rules).Validation:
Remediation:
Given the above, we must design the bot to be modular and pluggable for different secret types and different environments.
Architecture:
We can have:
However, note that automatic revocation and rotation might require integration with the secret management system (like AWS IAM, GitHub OAuth, etc.) and the applications that use them.
Given the complexity and the fact that we cannot automatically update every application, we might limit the scope to:
Steps in the bot:
Configuration: We need to know what to scan, where to scan, and for what types of secrets. Also, we need credentials for the providers to revoke/rotate.
Scanning:
For each found secret:
If we decide to revoke (based on policy, e.g., if the secret is found in a public repo, we revoke immediately), then:
Notify the appropriate team (e.g., via Slack, email) about the revocation and the need to update the applications.
Given the above, we might break the bot into two modes:
Implementation plan:
We'll create a bot that can be run periodically (cron) or triggered by events (e.g., new commit, new artifact built).
Steps:
Set up configuration file (YAML/JSON) that lists:
For each source, run the appropriate scanner.
Collect all findings and group by secret type and value.
For each unique secret (by value):
After revoking, we must also update the places where the secret is used? But we might not know all the places. So we might just revoke and let the applications fail, then the developers will have to update. Alternatively, we can try to update the configuration in the repository (by creating a PR) if the secret was found in a repo? But that might be dangerous if we don't know the context.
Given the risks, we might start with:
We must also consider that the same secret might be used in multiple places. We want to revoke it only once, but we might find it in multiple places. So we should de-duplicate by the secret value.
We must be careful not to revoke a secret that is still in use and we haven't rotated. So the process should be:
We should have a way to exclude certain findings (false positives) by pattern or by location.
Given the complexity, we might start with a simpler version:
But the requirement says repos, artifacts, and runtime. So we need to design for all.
Let's break down:
A. Repository scanning:
1. For each repo (git):
- Clone the repo (if not already present) and scan with gitleaks (or similar). We can use the gitleaks JSON output.
- Also, if the repo is on GitHub, we can use the GitHub API to list the repository secrets (for Actions, Dependabot, etc.) and then scan the code for the same secret values? But note: the repo secrets are encrypted and we cannot read them. So we cannot compare. Instead, we can scan the code for patterns that look like GitHub tokens and then use the GitHub API to check if the token is valid? But again, we cannot read the secret from GitHub to compare.
Alternatively, we can:
- Scan the code for patterns that are known to be secrets (like GitHub token pattern). Then, for each found token, we can try to use the GitHub API to check if it's valid (by making an API call with the token). But that would require the token to have at least public_repo access? And we would be using the token, which might be a secret. That could be dangerous because we are exfiltrating the token? Actually, we are just using it to check, but we are logging the token? We must be very careful.
So for GitHub tokens found in code, we can:
- Try to use the token to make a simple API call (like getting the user associated with the token). If it works, then it's a valid token. Then we can revoke it via the GitHub API (if we have admin rights on the token? We need the token owner to revoke). Actually, we can revoke a GitHub token via the API only if we have the token? Or if we are the owner? We can use the token to revoke itself? There's an endpoint to revoke a token: `POST /applications/{client_id}/grant`? Not exactly. Actually, for a personal access token, you can revoke it via the user's settings or via the API if you have the token and the user's password? Not straightforward.
Given the complexity, maybe we should focus on scanning and alerting for now, and then for specific providers that we can safely rotate (like AWS, where we can create a new key and delete the old one via API) we do automatic rotation.
B. Artifact scanning:
- We can scan Docker images by pulling and then running gitleaks on the filesystem? Or use a tool that can scan Docker images (like `docker scan` with a secret scanning plugin?).
- For JARs, we can unzip and scan the files.
C. Runtime scanning:
- For Kubernetes, we can list all pods and then get the environment variables and mounted volumes (configmaps, secrets) and then scan the values? But note: the secrets in Kubernetes are base64 encoded, but still we can scan the decoded values? Actually, the k8s secrets are stored as base64, but when mounted, they are decoded. We can get the environment variables and the files in the mounted volumes and scan them.
However, we must have permissions to list pods and get their environment and volumes.
Given the time, we might design a modular system with:
We can start by implementing:
And for remediation, we can implement:
But note: if we delete an AWS key, the application will break until we update the key. So we must update the code and redeploy? That's a big step.
Given the complexity and the risk, we might decide that the bot will only:
For private repositories and runtime, we just alert.
Steps for the bot:
Phase 1: Scanning and reporting.
Phase 2: Automatic revocation for high-risk (public exposure) and for secret types that we can safely rotate (like AWS keys) and then update the code? But updating code automatically is risky.
Alternatively, we can:
Given the above, I think we should design the bot to be:
But the requirement says "auto-revocation", so we must have an automatic way.
Let's define:
We can have a mapping:
source: public git repo -> action: revoke and rotate (if possible) and then block the commit? (via pre-receive hook?) but that's a different story.
Given the time, I'll outline a simple bot that:
Scans repositories (git) and artifacts (docker) using gitleaks.
For each finding, it checks the secret type (by regex) and then if it's an AWS key, it will: a. Validate the key (by trying to get the account ID via STS?). b. If valid, then revoke the key (using AWS IAM delete_access_key) and create a new one (if we have permission to create for the same user?). c. Then, we try to update the code? But we don't know the exact location. We can just note in the report that the key was found in file X, line Y, and we have revoked it and created a new key with ARN ... . The user must update.
For other types, we just report.
But note: we might find the same AWS key in multiple places. We should only revoke once.
Implementation:
Steps:
How do we know the key belongs to us? We can check the account ID? For AWS, we can get the account ID from the key? Actually, the access key is tied to an IAM user. We can get the user name by iam.get_access_key_last_used? But we need the key. Then we can get the user and then the account? Actually, the account is in the ARN of the user.
So for AWS:
- We have the key (access key id and secret). We can use boto3 to create a session with these credentials? That would try to use the key. But if the key is not valid, it will fail. We can then get the caller identity? But that requires sts:GetCallerIdentity.
Alternatively, we can use iam.get_access_key_last_used(AccessKeyId=access_key_id) to get the user name and then get the user? But that requires iam:GetAccessKeyLastUsed permission, which we might not have with the key we are checking? Actually, we are using our own admin credentials to check? No, we are using the found key? That would be using the found key to check itself? That might be allowed if the key has iam:GetAccessKeyLastUsed? But that's unlikely.
So we might not be able to validate the key without having additional permissions. So we might rely on the fact that if it's in our code, it's ours? But it could be a key from another account that was accidentally committed? That's a risk.
Given the above, we might only auto-revoke keys that are found in public repositories, because then we know they are exposed and we want to rotate. For private repositories, we might just alert.
So:
- If the source is a public repository (or if the repository is public on GitHub, GitLab, etc.), then we auto-revoke for certain secret types (like AWS, GitHub, etc.).
How do we know if the repo is public? We can query the GitHub API (if it's a GitHub repo) or check the local clone? Actually, we are cloning, so we might not know if it's public? But we can check the remote URL? If it's a GitHub URL and the repo is public, then we can know by the API.
Alternatively, we can have a configuration that says which repos are public.
Given the complexity, let's simplify:
We'll design the bot to:
Scan a list of repositories (local paths or URLs). We assume the user provides a list of repos and marks which are public.
For each repo, if it's marked as public, then for each found secret of a type that we support auto-revocation (like AWS), we revoke and rotate.
For private repos, we just report.
Steps for AWS:
We have the access key id and secret? Actually, gitleaks will give us the secret value. For AWS, it's the access key id and the secret access key? Usually, the pattern for AWS is:
access_key_id = 'AKIA...' secret_access_key = '...'
But gitleaks might find them separately? Actually, gitleaks has rules for AWS keys that match the pattern of the access key id and then the secret key? It might find both in the same line? We have to check.
We can have a rule that for AWS, we expect to find both? But gitleaks might find the access key id and then later the secret? We have to combine? Or we can look for the pattern of the access key id and then the secret key in the same line? Actually, the AWS keys are often found together.
Let's assume gitleaks finds the access key id and the secret key as two separate findings? Or as one? We have to check the gitleaks rule.
According to gitleaks rule for AWS:
[
{
"id": "aws-access-token",
"description": "AWS Access Token",
"regex": "(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}",
"entropy": 3
}
]
This matches the access key id. The secret key is a string of 40 characters? Actually, the secret access key is 40 characters (base64). There's a separate rule for that? Actually, the secret access key is not in a fixed format? It's a random string.
So we might find the access key id and then later in the code the secret key? We have to correlate? That's complex.
Alternatively, we can look for both in the same line? But they might be in different lines.
Given the complexity, we might rely on the fact that gitleaks can be configured to detect both and then we can have a post-processor that if we find an access key id and then within a certain number of lines a secret key, we combine? Or we can look for the pattern of the AWS credentials in the code (like in the AWS SDK configuration) where they are set together.
But note: the code might have:
AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=...
So they are in two separate lines? But in the same file? We can try to match by file and then by proximity? That's complex.
Given the time, we might decide to only handle the case where both are found in the same line? Or we can have a rule that matches the entire credential string? Actually, the AWS SDKs expect two separate variables.
Alternatively, we can have a separate rule that matches the entire block? But that's not reliable.
Given the above, we might limit our auto-revocation to secrets that are found as a single string (like a GitHub token) and for AWS we might not auto-revoke because we cannot reliably extract both keys? Unless we find a line that has both? But that's unlikely.
Actually, the AWS keys are often stored in environment variables or in configuration files (like ~/.aws/credentials) which have:
[default]
aws_access_key_id = AKIA...
aws_secret_access_key = ...
So we can have a rule that matches the entire file? Or we can have a rule that matches the pattern of the access key id and then the secret key in the same file? We can do:
For each file, if we find an access key id and a secret access key (by their patterns) then we combine them? But we don't know which secret access key goes with which access key id? We assume the first access key id with the first secret key? That's not reliable.
Given the complexity, we might decide to not auto-revoke AWS keys until we have a reliable way to extract both.
Alternatively, we can use the fact that the access key id is unique and then we can use the AWS API to list the access keys for the user? But we don't know the user? We can use the access key id to get the user? Actually, we can use iam.get_access_key_last_used(AccessKeyId=access_key_id) to get the user name? But that requires iam:GetAccessKeyLastUsed permission. We can use our admin credentials to do that? Then we can revoke that key.
So:
Step for AWS:
1. We find an access key id (AKIA...) in the code.
2. We use our admin AWS credentials (configured in the bot) to call `iam.get_access_key_last_used(AccessKeyId=access_key_id)`.
3. This returns the user name and other details. Then we can revoke that key for that user? Actually, we can delete the access key for the user.
4. Then we create a new access key for that user and then we have to update the code? But we don't know the secret key? We get it when we create.
5. Then we have to update the code with the new key? We can do that by creating a PR? But we must know the exact file and line? We have the file and line of the old access key id, but we don't have the secret key? We found the access key id, but the secret key might be in a different file? We might have to search for the secret key? That's complex.
Given the above, we might just revoke the key and then notify that the code must be updated with a new key (and provide the new key? That would be storing the new key in the bot? That's not safe).
So we might:
1. Revoke the old key.
2. Create a new key and store it in a secure way (like in a vault) and then notify the user to update the code with the new key from the vault.
But that requires integration with a vault.
Given the time, we might just revoke and then create a new key and then output the new key in the report? That's dangerous because the report might be stored in an insecure way.
So we might not create a new key automatically, but just revoke and let the user create a new one.
Alternatively, we can have a configuration that says:
For AWS:
- If found in public repo, then revoke and create a new key and then update the code in the repo (by creating a PR) with the new key? But we must have write access to the repo.
Steps for updating the code:
We have the file and line of the access key id. We can replace the access key id with the new one? But we also need the secret key? And we don't have the secret key in the same place? Actually, the code might have:
export AWS_ACCESS_KEY_ID=AKIA...
export AWS_SECRET_ACCESS_KEY=...
We found the AKIA... in the first line. We can then look for the secret key in the same block? We can assume that the secret key is in the next line? Or we can search in the same file for the pattern of the secret key? Then we replace both?
This is getting very complex.
Given the time and complexity, I propose:
Phase 1: Only scan and report. No auto-revocation.
Phase 2: For public repositories and for secret types that are single-string (like GitHub tokens, Slack tokens, etc.) we can auto-revoke by:
- Using the provider's API to revoke the token (if we have the necessary permissions and the token is valid).
For AWS, we might not do auto-revocation in phase 2.
So the bot will:
How to revoke a GitHub token?
We can use the GitHub API to revoke a token? Actually, for a personal access token, we can revoke it via the user's settings. But via API? We can use the OAuth application to revoke? There's an endpoint: `DELETE /applications/{client_id}/grant`? But that's for OAuth apps.
For a personal access token, we can use the token itself to revoke? There's no direct API. We can use the token to delete itself? Not possible.
So we might not be able to revoke GitHub tokens automatically.
For Slack tokens, we can revoke via the Slack API? Yes, we can revoke a token by calling auth.revoke? But that revokes the token we are using? Actually, auth.revoke revokes the token passed as the token parameter? So if we have the token, we can revoke it.
So for Slack, we can:
- Use the found token to call `https://slack.com/api/auth.revoke` and that will revoke the token.
But note: we are using the token to revoke itself, which is allowed.
However, we must be careful because we are making an API call with a secret that we found in the code. That might be against the policy? But we are revoking it, so it's okay.
Given the above, we can implement:
For AWS, we cannot revoke by providing the key? We need the admin credentials to revoke a key for a user. So we cannot use the found key to revoke itself? Actually, we can use the found key to delete itself? No, because the key doesn't have permission to delete itself? It might have iam:DeleteAccessKey? But that would be a bad practice to give that permission.
So for AWS, we might need admin credentials to revoke the key. We can have a separate set of credentials (with iam:DeleteAccessKey) and then use the access key id to delete that key for the user? But we don't know the user? We can get the user by the access key id? We can use our admin credentials to call iam.get_access_key_last_used to get the user name? Then delete the key for that user.
Steps for AWS:
1. We have the access key id (AKIA...).
2. Use our admin AWS credentials (configured in the bot) to call `iam.get_access_key_last_used(AccessKeyId=access_key_id)`. This returns the user name.
3. Then call `iam.delete_access_key(UserName=user_name, AccessKeyId=access_key_id)`.
But note: if the key is not found, then it's already deleted? We can ignore.
Then, we can create a new key for that user? But we must have the permission to create access keys for that user? And we must know which user to create for? We have the user name from step 2.
Then we can:
4. Call `iam.create_access_key(UserName=user_name)` to get a new key pair.
5. Then we have to update the code? But we don't know where the old key was? We have the file and line of the access key id, but we don't have the secret key? And the secret key might be in a different file.
Given the complexity, we might just revoke and then notify the user to create a new key and update the code.
So for AWS, we might not rotate automatically.
Given the above, we will implement:
auth.revoke with the found token.We can look for other providers that allow revoking by the token itself.
Alternatively, we can have a revoker that uses the provider's API with admin credentials (like for AWS) to revoke the key without needing the key itself? But we need the key id. We have the key id (for AWS) and we have admin credentials, so we can revoke.
So for AWS, we can revoke without using the found key? Yes, with admin credentials.
Then we can do:
1. For AWS, we have the access key id.
2. Use admin credentials to get the user (by describing the access key? `iam.get_access_key_last_used`).
3. Then revoke the key.
But we don't have the secret key? We don't need it to revoke. We only need the access key id and admin permissions.
So for AWS, we can revoke without the secret key.
Then we can create a new key for the same user? Yes, with admin credentials.
Then we have to update the code? We don't know the secret key? We have the new secret key from the create operation. But we don't know where to put it? We have the file and line of the access key id, but the secret key might be elsewhere.
Given the complexity, we might just revoke and then create a new key and then output the new key in the report? That's dangerous.
Alternatively, we can store the new key in a vault (like HashiCorp Vault) and then in the report, we tell the user to retrieve the new key from the vault.
So:
1. Revoke the old key.
2. Create a new key and store it in the vault (with a known secret path, like `secret/aws/<user_name>/<access_key_id>`?).
3. In the report, we say: "The AWS key with access key id AKIA... has been revoked. A new key has been generated and stored in the vault at path ... . Please update your code with the new key from the vault."
But then the user must have access to the vault.
Given the time, we might just revoke and then create a new key and then print the new key in the report (with a warning that the report is sensitive). That's not ideal.
Given the above, I think we should:
Start with scanning and reporting only.
Then, for a limited set of secret types (like Slack tokens) that can be revoked by the token itself, we can auto-revoke.
For AWS, we can revoke with admin credentials, but we won't rotate (create new) automatically because we don't want to handle the new secret.
So the bot will have:
For each finding:
if source is public and secret type in auto-revoke list:
try to revoke (using the revoker for that type)
if revoke succeeds, mark as revoked and do not report? Or report that it was revoked.
else:
report the finding.
We must be careful: if we revoke a token that is in use, the application will break. So we should only revoke if we are sure it's exposed (public repo) and we have a way to rotate? But we are not rotating for AWS? Then the application will break.
So we might only revoke for tokens that are not in use? But we don't know.
Given the risk, we might only revoke for tokens that are in public repos and that are of a type that we can rotate and update the code? That's a very limited set.
Alternatively, we can have a policy that:
- For public repos, we revoke and then we also update the code (if we can) and then create a PR.
But updating the code automatically is very risky.
Given the time, I think we should:
Phase 1: Scan and report only.
Phase 2: For public repos and for secret types that are single-string and can be revoked by the token itself (like Slack) and that are not used in production? But we don't know.
We might have to accept that auto-revocation is a risky operation and should be done only after careful consideration.
Given the above, I will design the bot to:
Scan and report all findings.
Have an optional flag (--auto-revoke) that will only auto-revoke for:
For AWS, we might have a revoker that uses admin credentials to revoke, but we will not enable it by default? We can have a configuration that says:
auto_revoke: enabled: true types: - slack - aws # but for aws we use admin credentials? and we don't rotate? we just revoke.
We must be cautious: if we revoke an AWS key that is in use, the application breaks. So we should only revoke if we are sure it's exposed and we have a way to rotate? But we are not rotating? Then it breaks.
So for AWS, we might not want to auto-revoke unless we also rotate? So we might not include AWS in the auto-revoke list until we have rotation.
Given the above, I think we should start with:
Scan and report.
Auto-revoke only for Slack tokens in public repos (because we can revoke and then the user must update, but at least the token is exposed and we can revoke it to prevent misuse).
Implementation:
We'll use:
- gitleaks for scanning.
- For Slack: we can revoke by calling `https://slack.com/api/auth.revoke` with the token.
- For GitHub: we cannot revoke via API with the token? We can try to use the token to delete itself? No. We can use the GitHub API with admin credentials? We can revoke a token by deleting the OAuth token? But we don't have the token id? We have the token string. We can list the OAuth tokens for the user? But we don't know the user? We can use the token to get the user? Then we can delete the token? Actually, we can use the token to get the user and then delete the token? There's an endpoint: `DELETE /applications/{client_id}/grants/{access_token}`? But that's for OAuth apps.
Given the complexity, we might skip GitHub for now.
Steps:
Configure the bot with:
For each source:
a. If it's a git repo, clone and run gitleaks (or other scanner) and parse the output (JSON).
b. If it's a docker image, pull and extract to a temporary directory and run gitleaks.
c. If it's k8s, get pods and then get environment variables and mounted files and scan.
For each finding:
Determine the secret type (from the gitleaks rule id or by regex?).
Check if the source is public (from configuration, or by checking the remote if it's a git repo?).
If auto-revoke is enabled and the source is public and the secret type is in the auto-revoke list, then:
i. Get the revoker for that type.
ii. Revoke the secret.
iii. Mark as revoked.
Else, add to report.
Generate a report (with findings and revocation status).
Given the time, we'll implement:
And leave the rest for future.
Code structure:
main.go: reads config, runs scanners, processes findings, outputs report.
scanners/ git_scanner.go docker_scanner.go k8s_scanner.go
revokers/ slack_revoker.go aws_revoker.go (for future)
config.yaml:
sources: - type: git url: https://github.com/example/repo.git public: true creds: ... # optional, for private repos - type: docker image: ubuntu:latest public: true # is the registry public? We might not know, so we assume if the registry is public then the image is public? Not exactly. - type: k8s cluster: https://k8s.example.com namespace: default public: false # runtime is not public? But the secrets might be exposed if the pod is public? We don't know.
auto_revoke:
enabled: true
types:
- slack
credentials:
slack:
token: xoxp-... # bot token? We need a bot token that can revoke? Actually, the auth.revoke endpoint requires a user token? We can use a user token to revoke any token? No, we can only revoke the token we are using? Actually, the auth.revoke endpoint revokes the token passed as the token parameter? So we need the token we found to revoke it? Then we don't need a separate credential? We use the found token to revoke itself.
So for Slack, we don't need a separate credential, we use the found token.
But for AWS, we need admin credentials.
So the configuration for auto-revoke might be:
auto_revoke:
enabled: true
types:
- slack
- aws
credentials:
aws:
access_key_id: ...
secret_access_key: ...
Then, for slack, we don't need credentials in the config because we use the found token.
But for AWS, we use the admin credentials to revoke the found key.
Implementation of slack revoker:
func (r *SlackRevoker) Revoke(secret string) error {
// secret is the token found.
resp, err := http.PostForm("https://slack.com/api/auth.revoke", url.Values{
"token": {secret},
})
// check resp
}
But note: the Slack token might be a bot token (xoxb) or user token (xoxp). The auth.revoke endpoint works for both? According to the Slack API, auth.revoke revokes the token passed. So it should work.
However, we are using the token to revoke itself. That means after revocation, the token is invalid. But we are using it to revoke, so the call might succeed and then the token is revoked.
Steps:
1. We have the token.
2. We call `auth.revoke` with that token.
3. The call succeeds and the token is revoked.
But what if the token is already revoked? Then the call might fail? We can ignore.
Given the above, let's code:
We'll have:
type Revoker interface {
Revoke(secret string) error
}
type SlackRevoker struct{}
func (r *SlackRevoker) Revoke(secret string) error {
// ...
}
type AWSRevoker struct {
creds aws.Credentials
}
func (r *AWSRevoker) Revoke(accessKeyID string) error {
// Use r.creds to create an IAM client.
// Then get the user by accessKeyID? We can use iam.GetAccessKeyLastUsed.
// Then delete the access key for that user.
}
But note: for AWS, we are given the access key id (from the finding). We don't have the secret key? We don't need it for revocation because we are using admin credentials.
However, we must be cautious: the access key id might be from a different account? We are using our admin credentials (which are for our account) to delete an access key? That will only work if the access key is in our account? Actually, the access key is tied to an IAM user in an account. We can only delete keys in our own account? Yes, because we are using our admin credentials for our account.
But what if the found key is from a different account? Then we cannot delete it. So we should check that the key is in our account? We can get the user by the access key and then check the account? The user ARN includes the account id. We can compare with our account id.
Steps for AWS revoker:
1. Create an IAM client with admin credentials.
2. Call GetAccessKeyLastUsed with the access key id.
3. This returns the user name and the account id? Actually, the response has `UserName` and `AccountId`? Let's check: https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccessKeyLastUsed.html
The response includes `UserName` and `AccountId`? Actually, the response has `UserName` and `AccessKeyLastUsed` but not AccountId? We can get the user by `UserName` and then get the user's ARN? That would have the account id.
4. Alternatively, we can call `iam.GetUser` with the UserName? That returns the user's ARN.
5. Then we can extract the account id from the ARN.
6. Compare with our account id (which we can get from STS GetCallerIdentity using our admin credentials).
7. If the account id matches, then delete the access key.
But note: the access key might be from a different account? We don't want to delete a key from another account.
So we must check.
Given the complexity, we might skip the account check and just try to delete? If we don't have permission, it will fail. And if the key is not in our account, we cannot delete it.
So we can try to delete and if we get an error, we ignore? But we might get an error for other reasons.
Given the time, we'll implement:
func (r *AWSRevoker) Revoke(accessKeyID string) error {
svc := iam.New(session.New(&aws.Config{
Credentials: r.creds,
}))
// First, get the user associated with the access key.
output, err := svc.GetAccessKeyLastUsed(&iam.GetAccessKeyLastUsedInput{
AccessKeyId: aws.String(accessKeyID),
})
if err != nil {
return err
}
userName := output.UserName
// Now, delete the access key.
_, err = svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
UserName: userName,
AccessKeyId: aws.String(accessKeyID),
})
return err
}
But note: the GetAccessKeyLastUsed might require iam:GetAccessKeyLastUsed permission? We are using admin credentials, so we should have it.
Then, we can also create a new key? We might not do that automatically.
Given the above, we have:
But for AWS, we are not providing the secret key, only the access key id. That's okay because we don't need the secret key to revoke.
However, the finding from gitleaks for AWS might only give us the access key id? Or might it give us the secret key? We have to check.
According to the gitleaks rule for AWS, it only matches the access key id pattern. So we only get the access key id.
So we can revoke by access key id.
But note: the same access key id might appear multiple times? We should de-duplicate by access key id.
So in the bot, we will:
findings = scan(...)
for each finding:
if finding.secret_type == "aws-access-token" and finding.secret_value is an access key id (we can validate with the regex) then:
if we haven't processed this access key id before, then:
if auto_revoke.enabled and finding.source.public and "aws" in auto_revoke.types:
revoker.Revoke(finding.secret_value)
mark as revoked.
We must store the processed access key ids (or hash) to avoid revoking twice.
Given the above, let's code the structure:
We'll have:
type Finding struct {
Source string // e.g., "git:github.com/example/repo"
File string
Line int
SecretType string // e.g., "aws-access-token", "slack-token"
SecretValue string // the actual secret (or for AWS, the access key id)
Public bool // whether the source is public
}
type Scanner interface {
Scan() ([]Finding, error)
}
type Revoker interface {
Revoke(secret string) error
}
type Bot struct {
scanners []Scanner
revokers map[string]Revoker // key: secret type
processed map[string]bool // key: secret value hash? or the secret value? But we don't want to store the secret. We can store a hash (SHA256) of the secret.
config Config
}
func (b *Bot) Run() {
for _, scanner := range b.scanners {
findings, err := scanner.Scan()
if err != nil {
log.Error(err)
continue
}
for _, f := range findings {
// Check if we have already processed this secret (by hash of the secret value)
hash := sha256.Sum256([]byte(f.SecretValue))
if b.processed[hex.EncodeToString(hash[:])] {
continue
}
b.processed[hex.EncodeToString(hash[:])] = true
if b.config.AutoRevoke.Enabled && f.Public {
if revoker, ok := b.revokers[f.SecretType]; ok {
err := revoker.Revoke(f.SecretValue)
if err != nil {
log.Errorf("Failed to revoke secret of type %s: %v", f.SecretType, err)
} else {
log.Infof("Revoked secret of type %s from %s", f.SecretType, f.Source)
}
}
} else {
// Report
b.reportFinding(f)
}
}
}
}
We must be cautious: we are storing the hash of the secret in memory. We might want to store it in a persistent storage to avoid revoking again if the bot restarts? But if we restart, we might revoke again? We can store in a file or database.
Given the time, we'll store in a file (state.json) that maps the hash to the finding and the action taken.
But note: if we revoke a secret, we don't want to try again? We can store that we revoked it.
So the state can be:
{
"revoked": {
"hash1": true,
"hash2": true
},
"reported": {
"hash3": true
}
}
But we might want to re-scan and if the secret is still there, we might want to revoke again? Probably not.
Given the above, we'll store the hash and the action.
However, we might want to re-scan and if the secret is still there, we might want to alert again? But we already revoked? Then it's a false positive? Or the secret was re-added? Then we might want to alert again.
Given the complexity, we might just store the hash and the fact that we processed it, and then skip in future runs? Or we can have a TTL? Not now.
We'll store the processed hashes in a file and load at startup.
Steps:
- Load state from file (if exists) into b.processed.
- Run scans.
- For each new finding, if hash not in b.processed, then process and add to b.processed.
- Save state to file.
But note: we might have false positives? We might want to allow whitelisting? We can have a config for whitelisted patterns? Not now.
Given the time, I'll outline the code structure and implement a simple version:
Let's code:
main.go:
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"os"
)
type Config struct {
Sources []SourceConfig `yaml:"sources"`
AutoRevoke AutoRevokeConfig `yaml:"auto_revoke"`
}
type SourceConfig struct {
Type string `yaml:"type"`
URL string `yaml:"url"`
Public bool `yaml:"public"`
// ... other fields
}
type AutoRevokeConfig struct {
Enabled bool `yaml:"enabled"`
Types []string `yaml:"types"`
Credentials map[string]interface{} `yaml:"credentials"` // for each type, the credentials needed
}
type Finding struct {
Source string
File string
Line int
SecretType string
SecretValue string
Public bool
}
type Scanner interface {
Scan() ([]Finding, error)
}
type Revoker interface {
Revoke(secret string) error
}
type Bot struct {
config Config
scanners []Scanner
revokers map[string]Revoker
processed map[string]bool
stateFile string
}
func NewBot(config Config, stateFile string) *Bot {
b := &Bot{
config: config,
processed: make(map[string]bool),
stateFile: stateFile,
}
// Load state
data, err := ioutil.ReadFile(stateFile)
if err == nil {
var state map[string]bool
json.Unmarshal(data, &state)
b.processed = state
} else if !os.IsNotExist(err) {
log.Fatalf("Failed to read state file: %v", err)
}
// Initialize scanners
for _, source := range config.Sources {
switch source.Type {
case "git":
b.scanners = append(b.scanners, NewGitScanner(source))
case "docker":
b.scanners = append(b.scanners, NewDockerScanner(source))
case "k8s":
b.scanners = append(b.scanners, NewK8sScanner(source))
}
}
// Initialize revokers
b.revokers = make(map[string]Revoker)
if b.config.AutoRevoke.Enabled {
for _, secretType := range b.config.AutoRevoke.Types {
switch secretType {
case "slack":
b.revokers[secretType] = &SlackRevoker{}
case "aws":
// Create AWS revoker with credentials from config
creds := b.config.AutoRevoke.Credentials["aws"].(map[string]interface{})
accessKeyID := creds["access_key_id"].(string)
secretAccessKey := creds["secret_access_key"].(string)
b.revokers[secretType] = NewAWSRevoker(accessKeyID, secretAccessKey)
}
}
}
return b
}
func (b *Bot) Run() {
for _, scanner := range b.scanners {
findings, err := scanner.Scan()
if err != nil {
log.Printf("Scanner error: %v", err)
continue
}
for _, f := range findings {
hash := sha256.Sum256([]byte(f.SecretValue))
hashStr := hex.EncodeToString(hash[:])
if b.processed[hashStr] {
continue
}
b.processed[hashStr] = true
if b.config.AutoRevoke.Enabled && f.Public {
if revoker, ok := b.revokers[f.SecretType]; ok {
log.Printf("Attempting to revoke secret of type %s from %s", f.SecretType, f.Source)
err := revoker.Revoke(f.SecretValue)
if err != nil {
log.Printf("Failed to revoke: %v", err)
} else {
log.Printf("Revoked secret of type %s from %s", f.SecretType, f.Source)
}
} else {
b.reportFinding(f)
}
} else {
b.reportFinding(f)
}
}
}
// Save state
data, _ := json.Marshal(b.processed)
ioutil.WriteFile(b.stateFile, data, 0644)
}
func (b *Bot) reportFinding(f Finding) {
// Print or send to a channel
log.Printf("Finding: %s in %s:%d", f.SecretType, f.File, f.Line)
}
Then implement:
- GitScanner: runs gitleaks and parses the JSON output.
- SlackRevoker: as above.
- AWSRevoker: as above.
This is a very basic design. We must handle errors, and we must be cautious about the security of the state file (it contains hashes of secrets, but not the secrets themselves).
We must also consider that the same secret might be found in multiple sources? We de-duplicate by the secret value, so we only process once.
Given the time, this is a starting point.
We must also consider:
How to run gitleaks? We can assume it's in the PATH.
The GitScanner:
type GitScanner struct { config SourceConfig }
func NewGitScanner(config SourceConfig) *GitScanner { return &GitScanner{config: config} }
func (s *GitScanner) Scan() ([]Finding, error) { // Clone the repo to a temp dir. // Run gitleaks with JSON output. // Parse the JSON. // For each finding, create a Finding struct. // We need to set Source, File, Line, SecretType, SecretValue, Public. // The gitleaks JSON has: File, Line, Match, Secret, etc. // We can map the RuleID to our secret type? Or use the RuleID as the secret type. }
Given the time, I'll leave the implementation of the scanners as a TODO.
This is a high-level design and a starting point for implementation.
We must also consider:
The bot must run in a secure environment with the necessary credentials.
We must not log the secret values.
The state file must be protected.
Given the above, we can proceed to implement the basic structure and then add more scanners and revokers.
However, note that the requirement includes scanning artifacts and runtime. We have placeholders for Docker and K8s scanners.
For Docker:
We can pull the image, save it to a tar, extract to a temp dir, and then run gitleaks on the extracted filesystem.
For K8s:
We can use the Kubernetes client to list pods and then for each pod, get the environment variables and mounted volumes (configmaps, secrets) and then scan the values.
But note: the secrets in Kubernetes are base64 encoded. We must decode them? Actually, when we get the environment variables and volumes, they are already decoded? In the pod spec, the secrets are referenced and then the kubelet decodes them when mounting? But when we get the pod via the API, the environment variables and volumes are the decoded values? Actually, the pod spec has env and envFrom and volumeMounts. The env can have valueFrom which references a secret. We have to resolve? That's complex.
Alternatively, we can exec into the pod and read the files? That would require the pod to be running and we have permissions to exec.
Given the complexity, we might skip the K8s scanner for now.
Given the time, I think we have a design that can be extended.
Let's write the code for:
We'll leave the AWS revoker and other scanners for future.
Steps to run:
Given the time, I'll provide a skeleton code.
Note: This is a proof of concept and not production-ready. We must handle many edge cases and errors.
Let's code accordingly. I'll design a Secrets Scanning & Auto-Revocation Bot that provides comprehensive coverage across your software supply chain. This is a sophisticated system that requires careful implementation due to the sensitive nature of secrets management.
┌─────────────────────────────────────────────────────────────┐
│ Secrets Scanning Bot │
├─────────────┬─────────────┬──────────────┬─────────────────┤
│ Repos │ Artifacts │ Runtime │ Admin/Config │
├─────────────┼─────────────┼──────────────┼─────────────────┤
│ • Git repos │ • Container │ • Env vars │ • Policy Engine │
│ • PR hooks │ images │ • ConfigMaps │ • Alerting │
│ • CI/CD │ • JARs/WARs │ • Secrets │ • Dashboard │
│ • SCM APIs │ • ISO/NuGet │ • Volumes │ • Audit logs │
└─────────────┴─────────────┴──────────────┴─────────────────┘
│ │ │
└──────────────┼───────────────┘
│
┌──────────────▼───────────────┐
│ Processing & Decision │
│ ┌───────────────────────┐ │
│ │ • Pattern Matching │ │
│ │ • Validation Engine │ │
│ │ • Entropy Analysis │ │
│ │ • Context Awareness │ │
│ └───────────────────────┘ │
└──────────────┬───────────────┘
│
┌──────────────▼───────────────┐
│ Remediation Engine │
│ ┌───────────────────────┐ │
│ │ • Auto-Revocation │ │
│ │ • Rotation (if needed)│ │
│ │ • Secret Injection │ │
│ │ • PR Creation │ │
│ └───────────────────────┘ │
└──────────────┬───────────────┘
│
┌──────────────▼───────────────┐
│ Secret Management System │
│ ┌───────────────────────┐ │
│ │ • Vault Integration │ │
│ │ • Cloud Provider APIs │ │
│ │ • Key Management │ │
│ └───────────────────────┘ │
└──────────────────────────────┘
# Scanner Configuration (YAML)
scanners:
repository_scanners:
- type: git
patterns:
- ${AWS_ACCESS_KEY_ID}
- ${AWS_SECRET_ACCESS_KEY}
- ${GITHUB_TOKEN}
- ${SLACK_WEBHOOK}
- password.*=.*['"]^[A-Za-z0-9]{32}['"]
exclude:
- "*.test.yml"
- "*.mock.*"
- "tests/**"
hooks:
pre-commit: true
pre-receive: true
post-receive: true
- type: github_actions
scan_secrets: true
scan_env_vars: true
scan_workflow_files: true
artifact_scanners:
- type: docker
scan_all_layers: true
scan_entrypoint: true
scan_env: true
exclude_images:
- "nginx:alpine" # Known safe
- type: maven
scan_pom: true
scan_dependencies: true
- type: npm
scan_package_json: true
scan_node_modules: true
runtime_scanners:
- type: kubernetes
scan_pods: true
scan_secrets: true
scan_configmaps: true
scan_env_from: true
exclude_namespaces:
- "kube-system"
- "monitoring"
- type: aws_ecs
scan_task_definitions: true
scan_parameters: true
- type: vm_inventory
scan_env_files: true
scan_application_properties: true
class SecretDetector:
def __init__(self):
self.patterns = self.load_patterns()
self.entropy_threshold = 3.5 # Shannon entropy threshold
self.context_analyzer = ContextAnalyzer()
def detect(self, content, source_type, context):
findings = []
# 1. Pattern matching
for pattern in self.patterns:
matches = pattern.findall(content)
for match in matches:
finding = {
'secret': match,
'pattern': pattern.name,
'source': source_type,
'context': self.context_analyzer.analyze(match, context)
}
findings.append(finding)
# 2. Entropy analysis for high-entropy strings
high_entropy = self.find_high_entropy_strings(content)
for candidate in high_entropy:
if self.is_likely_secret(candidate, context):
findings.append({
'secret': candidate,
'pattern': 'high_entropy',
'source': source_type,
'context': context
})
# 3. Validation against known false positives
findings = self.filter_false_positives(findings)
return findings
def is_likely_secret(self, string, context):
"""Use ML/rule-based classifier"""
score = 0
score += 10 if self.looks_like_key(string)
score += 5 if self.has_secret_keywords(context)
score += 3 if self.is_in_config_file(context)
score -= 8 if self.is_in_test_file(context)
score -= 5 if self.is_in_documentation(context)
return score > 8
class RemediationEngine:
def __init__(self, secret_manager, policy_engine):
self.secret_manager = secret_manager
self.policy_engine = policy_engine
self.rotation_queue = []
def process_finding(self, finding):
"""Main remediation decision flow"""
# 1. Policy evaluation
action = self.policy_engine.evaluate(finding)
if action == 'revoke_only':
self.revoke_secret(finding)
self.create_ticket(finding, 'REVOKED')
elif action == 'rotate':
new_secret = self.rotate_secret(finding)
self.update_dependencies(finding, new_secret)
self.create_pull_request(finding, new_secret)
elif action == 'monitor':
self.add_to_monitoring(finding)
elif action == 'ignore':
self.whitelist(finding)
def rotate_secret(self, finding):
"""Rotate secret through secret manager"""
secret_type = finding['type']
if secret_type == 'aws_key':
# Rotate through AWS IAM
new_key = self.secret_manager.rotate_aws_key(
access_key_id=finding['secret_id']
)
return {
'type': 'aws_key',
'access_key_id': new_key['AccessKeyId'],
'secret_access_key': new_key['SecretAccessKey']
}
elif secret_type == 'github_token':
# Rotate through GitHub App or PAT
new_token = self.secret_manager.create_github_token(
repo=finding['repo'],
permissions=self.get_minimal_permissions(finding)
)
return {'type': 'github_token', 'token': new_token}
elif secret_type == 'database_password':
# Rotate through database API
new_password = self.secret_manager.rotate_database_password(
db_instance=finding['database'],
user=finding['username']
)
return {'type': 'db_password', 'password': new_password}
def update_dependencies(self, finding, new_secret):
"""Update where the secret is used"""
deployment_locations = self.find_deployments(finding)
for location in deployment_locations:
if location['type'] == 'kubernetes_secret':
self.update_k8s_secret(location, new_secret)
elif location['type'] == 'environment_variable':
self.update_env_var(location, new_secret)
elif location['type'] == 'config_file':
self.update_config_file(location, new_secret)
elif location['type'] == 'ci_cd_variable':
self.update_ci_variable(location, new_secret)
class PolicyEngine:
def __init__(self):
self.policies = self.load_policies()
def evaluate(self, finding):
"""Determine action based on policy"""
secret_type = finding['type']
severity = self.classify_severity(finding)
exposure = self.assess_exposure(finding)
context = finding['context']
# Policy matrix
if exposure == 'public_repository':
return 'revoke_only' # Must revoke immediately
if severity == 'critical' and context == 'production':
return 'rotate'
if severity == 'high' and exposure == 'internal':
return 'monitor' # Alert but don't auto-revoke
if context == 'test' or context == 'development':
return 'ignore' # Allow in non-prod
return 'monitor'
def classify_severity(self, finding):
"""Classify secret severity"""
CRITICAL_TYPES = ['aws_root_key', 'github_org_token', 'stripe_secret_key']
HIGH_TYPES = ['aws_iam_key', 'database_password', 'jwt_secret']
MEDIUM_TYPES = ['api_key', 'webhook_url']
if finding['type'] in CRITICAL_TYPES:
return 'critical'
elif finding['type'] in HIGH_TYPES:
return 'high'
else:
return 'medium'
class SecretManager:
def __init__(self):
self.providers = {
'aws': AWSProvider(),
'github': GitHubProvider(),
'gcp': GCPProvider(),
'azure': AzureProvider(),
'vault': VaultProvider(),
'database': DatabaseProvider()
}
def rotate_aws_key(self, access_key_id):
"""Rotate AWS IAM key"""
# 1. Get current key metadata
metadata = self.providers['aws'].get_key_metadata(access_key_id)
# 2. Create new key
new_key = self.providers['aws'].create_access_key(
user_name=metadata['user_name']
)
# 3. Deactivate old key (grace period)
self.providers['aws'].deactivate_key(
access_key_id=access_key_id,
user_name=metadata['user_name']
)
# 4. Schedule deletion (after grace period)
self.schedule_deletion(access_key_id, metadata['user_name'],
delay_hours=24)
return new_key
def create_github_token(self, repo, permissions):
"""Create GitHub token with least privilege"""
# Use GitHub App installation token or PAT
app = self.providers['github'].get_app_installation(repo)
token = app.create_token(
permissions={
'contents': 'read',
'metadata': 'read'
},
expiration_hours=1 # Short-lived tokens
)
return token
# deployment.yaml (Kubernetes)
apiVersion: apps/v1
kind: Deployment
metadata:
name: secrets-scanner
spec:
replicas: 2
template:
spec:
containers:
- name: scanner
image: secrets-scanner:latest
env:
- name: VAULT_ADDR
valueFrom:
secretKeyRef:
name: vault-config
key: vault-addr
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: scanner-credentials
key: aws-access-key-id
- name: GITHUB_TOKEN
valueFrom:
secretKeyRef:
name: scanner-credentials
key: github-token
volumeMounts:
- name: config
mountPath: /etc/scanner
readOnly: true
- name: scans
mountPath: /var/scans
volumes:
- name: config
configMap:
name: scanner-config
- name: scans
persistentVolumeClaim:
claimName: scans-pvc
---
apiVersion: v1
kind: ConfigMap
metadata:
name: scanner-config
data:
config.yaml: |
scanners:
git:
enabled: true
webhook_secret: ${GITHUB_WEBHOOK_SECRET}
docker:
enabled: true
registry_auth: true
---
# Webhook Configuration (GitHub)
# In repository settings:
# - Webhook URL: https://scanner.example.com/webhook/github
# - Content type: application/json
# - Events: push, pull_request, create, delete
.gitlab-ci.yml
secrets_scan:
stage: test
image: registry.example.com/secrets-scanner:latest
script:
- scanner scan --type git --repo $CI_PROJECT_URL
- scanner scan --type docker --image $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
artifacts:
reports:
secrets: scanner-report.json
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual # Manual approval for MRs
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: always
GitHub Actions
name: Secrets Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Run Secrets Scanner
uses: our-org/secrets-scanner-action@v1
with:
scan-type: 'git, docker'
auto-revoke: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
fail-on-critical: true
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v2
if: always()
with:
sarif_file: scanner-results.sarif
class AlertManager:
def __init__(self):
self.channels = {
'critical': ['slack#security', 'pagerduty'],
'high': ['slack#devops', 'email#security-team'],
'medium': ['slack#devops']
}
def send_alert(self, finding):
severity = finding['severity']
channel = self.channels.get(severity, [])
message = self.format_message(finding)
for ch in channel:
if ch.startswith('slack#'):
self.send_slack(ch.split('#')[1], message)
elif ch.startswith('pagerduty'):
self.create_pagerduty_incident(finding)
elif ch.startswith('email#'):
self.send_email(ch.split('#')[1], message)
# Create ticket
self.create_ticket(
title=f"Secret detected: {finding['type']}",
description=message,
severity=severity,
auto_revoke=finding.get('auto_revoked', False)
)
class SecurityController:
def __init__(self):
self.audit_logger = AuditLogger()
self.access_controller = AccessController()
def can_revoke(self, user, finding):
"""Check if user can revoke this secret"""
# Only allow auto-revoke for:
# 1. Secrets in public repositories
# 2. Critical production secrets with documented ownership
# 3. Secrets with confirmed rotation window
if finding['exposure'] == 'public':
return True
if not self.is_owned_by_team(finding, user.team):
return False
if not self.has_rotation_window(finding):
return False
return self.access_controller.has_permission(
user, 'secret:revoke'
)
def audit_log(self, action, finding, user, result):
"""Immutable audit log"""
log_entry = {
'timestamp': datetime.utcnow().isoformat(),
'action': action,
'finding_id': finding['id'],
'secret_type': finding['type'],
'user': user.id,
'source': finding['source'],
'result': result,
'metadata': finding['metadata']
}
self.audit_logger.write(log_entry)
| Phase | Scope | Features | Risk Level |
|---|---|---|---|
| Phase 1 | Repository scanning | • Git scanning (pre-receive hooks)• PR decoration• False positive reduction | Low |
| Phase 2 | Artifact scanning | • Docker image scanning• Dependency scanning• Registry integration | Medium |
| Phase 3 | Runtime scanning | • Kubernetes secrets• Environment variables• Configuration files | Medium-High |
| Phase 4 | Auto-revocation | • AWS/GCP/Azure rotation• GitHub token rotation• Database password rotation | High |
| Phase 5 | Advanced features | • ML-based detection• Secret lineage tracking• Compliance reporting | Medium |
# Docker Compose for quick start
version: '3.8'
services:
scanner:
image: secrets-scanner:latest
environment:
- VAULT_ADDR=http://vault:8200
- VAULT_TOKEN=${VAULT_TOKEN}
- GITHUB_TOKEN=${GITHUB_TOKEN}
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
volumes:
- ./config:/etc/scanner
- ./scans:/var/scans
depends_on:
- vault
- postgres
vault:
image: vault:latest
ports:
- "8200:8200"
postgres:
image: postgres:14
environment:
POSTGRES_PASSWORD: ${DB_PASSWORD}
# config.yaml
general:
scan_interval: 300 # seconds
max_concurrent_scans: 10
retention_days: 90
audit_log_level: detailed
scanners:
git:
max_depth: 3 # Merge commits to check
skip_merge_commits: false
detect_renames: true
docker:
max_image_size: "10GB"
scan_archived: false
exclude_base_images: true
remediation:
auto_revoke:
enabled: false # Start with manual review
require_approval: true
grace_period_hours: 24
allowed_types:
- "github_pat"
- "slack_webhook"
- "aws_key"
blocked_types: # Never auto-revoke
- "production_database_password"
- "payment_gateway_key"
rotation:
create_ticket: true
auto_pr: true
require_test_pass: true
alerting:
slack:
webhook: ${SLACK_WEBHOOK}
channel: "#security-alerts"
pagerduty:
integration_key: ${PD_INTEGRATION_KEY}
severity_mapping:
critical: "P1"
high: "P2"
Never auto-revoke without validation:
Prevent circular dependency:
Gradual rollout:
Week 1: Detection only, no revocation
Week 2: Auto-revoke non-production secrets
Week 3: Auto-revoke public repo secrets
Week 4: Full rollout with monitoring
Rollback capability:
# Prometheus metrics
secrets_scanner_total_scans{source="git"}
secrets_scanner_secrets_found{type="aws_key",severity="critical"}
secrets_scanner_auto_revoked_total
secrets_scanner_false_positives_total
secrets_scanner_scan_duration_seconds
secrets_scanner_policy_violations_total
# Alerting rules
- alert: CriticalSecretFound
expr: secrets_scanner_secrets_found{severity="critical"} > 0
for: 5m
- alert: ScannerDown
expr: up{job="secrets-scanner"} == 0
for: 2m
| Component | Recommended Tools | Alternative |
|---|---|---|
| Scanning | gitleaks, truffleHog, custom regex | Detect-secrets, GitGuardian |
| Container Scanning | Trivy, Hadolint | Grype, Docker Scout |
| Secret Storage | HashiCorp Vault, AWS Secrets Manager | GCP Secret Manager, Azure Key Vault |
| CI/CD | GitHub Actions, GitLab CI | Jenkins, CircleCI |
| Orchestration | Kubernetes Operator | Helm, Terraform |
| Dashboard | Grafana + custom UI | Kibana, Datadog |
⚠️ CRITICAL: Auto-revocation can break production systems!
This system requires cross-team collaboration (Security, DevOps, Engineering) and gradual implementation. Start with detection-only, build trust with engineering teams, then slowly enable auto-revocation for specific low-risk secret types before expanding to critical production secrets.