AI coding assistants can generate a significant amount of application code from relatively little developer input. A developer might ask an assistant to create an API endpoint, connect an application to a database, add an authentication flow, or integrate a third-party service. The generated code may include configuration files, environment variables, HTTP clients, database access, and deployment settings.
This makes AI-assisted development productive, but it also introduces a security concern that deserves attention: sensitive information can accidentally end up in generated code and eventually reach a pull request.
Consider a developer asking an AI assistant to create an ASP.NET Core API that connects to a SQL Server database. If the prompt includes an actual connection string, the generated configuration might place that value directly in appsettings.json. The code may work perfectly on the developer's machine, but committing it to a shared repository could expose database credentials to everyone who has access to that repository.
The problem is not limited to database passwords. API keys, access tokens, private keys, cloud credentials, signing certificates, webhook secrets, and service account credentials can all appear in generated code or configuration.
Preventing these leaks requires more than asking developers to be careful. Teams need a development workflow in which secrets are kept outside source code, AI tools receive only the information they need, and automated security checks run before changes are merged.
How AI-Generated Code Can Introduce Secret Leaks
AI assistants generate code using the instructions and context available to them. That context may include code from the current project, configuration examples, developer-provided prompts, and other files made available through the development environment.
If a developer provides a real credential as part of a prompt, the generated output may reuse it. The assistant might place the value in a configuration file, create a constant in a service class, or include it in an example request.
For example, a developer might request a database connection implementation and provide the following configuration:
{
"ConnectionStrings": {
"DefaultConnection": "Server=prod-db;Database=Orders;User Id=admin;Password=ActualPassword123;"
}
}
An AI assistant could use this value when generating the application configuration or database registration code. If the developer accepts the generated changes without reviewing the configuration, the credential may become part of the next commit.
Another common situation occurs when developers ask an assistant to debug an authentication or integration problem. They may paste an HTTP request containing an authorization header, a complete configuration file, or an error log with sensitive values. Even if the generated code does not contain the credential, the original prompt may have exposed it to the AI service.
This distinction matters. Preventing secrets in pull requests is only one part of the problem. Developers must also consider what information they share with AI tools and whether the tool is approved for handling that information.
Keep Credentials Outside Source Code
The most effective way to prevent hardcoded secrets is to separate application configuration from sensitive credentials.
An application should know how to retrieve a database password or API key without storing the actual value in its source code. This makes the same application easier to deploy across development, testing, and production environments while reducing the risk of accidental exposure.
In an ASP.NET Core application, developers can use configuration providers to load values from environment variables, user secrets during local development, or a dedicated secret-management service in production.
For example, instead of putting a database password in appsettings.json, keep the configuration file limited to non-sensitive application settings:
{
"ConnectionStrings": {
"DefaultConnection": ""
}
}
The application can continue using the standard configuration system:
var builder = WebApplication.CreateBuilder(args);
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new InvalidOperationException(
"Database connection string is not configured.");
}
The connection string is supplied through the environment rather than committed to the repository.
For example, a deployment environment can define:
ConnectionStrings__DefaultConnection
ASP.NET Core maps the double underscore to the configuration hierarchy separator. This allows the environment variable to override the corresponding configuration value.
For local development, .NET User Secrets provides another option:
dotnet user-secrets init
Then store the local connection string:
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "YOUR_LOCAL_CONNECTION_STRING"
User Secrets keeps development credentials outside the project directory. It is intended for development use, not as a production secret store. Production applications should use an appropriate secret-management solution, such as Azure Key Vault or another approved platform service.
The important point is that AI-generated code should contain the mechanism for retrieving a secret, not the secret itself.
Give AI Assistants Clear Rules for Handling Secrets
Developers often use AI assistants to generate configuration files, service classes, API clients, and deployment scripts. Without clear project-level guidance, the assistant may follow an insecure pattern found in an existing example or provided in a prompt.
A repository can include a .github/copilot-instructions.md file to communicate the team's development and security expectations to GitHub Copilot.
For example:
# Security Instructions
- Never hardcode passwords, API keys, access tokens, or private keys.
- Do not place production credentials in source files.
- Use environment variables or approved secret-management services.
- Do not generate real credentials in sample configuration files.
- Use placeholder values in documentation and examples.
- Never log authorization headers or sensitive configuration values.
- Validate external configuration during application startup.
- Do not disable authentication or authorization checks to simplify implementation.
- Follow the existing authentication and configuration patterns.
These instructions give Copilot useful context when generating code. They also help developers maintain consistent practices across the repository.
However, instructions are not a security boundary. An AI assistant may misunderstand a requirement, produce an insecure suggestion, or generate code that does not follow the instructions. A developer can also accept generated changes without noticing the problem.
Treat repository instructions as guidance for code generation, not as a replacement for secret scanning, code review, or deployment controls.
Detect Secrets Before They Reach the Repository
Code review is useful, but developers should not depend on a reviewer noticing every credential in a large pull request. Secret scanning provides an automated way to inspect repository content for values that resemble sensitive credentials.
GitHub Secret Protection includes secret scanning capabilities that detect supported provider-specific patterns, generic secret patterns, and organization-defined custom patterns. Depending on the repository's configuration and available features, it can also identify less structured secrets using AI-based detection.
For example, a secret scanner may recognize a cloud access key, an API token, or a private key included in a source file. This is especially useful when an AI assistant generates several files and a developer does not notice that a sensitive value has been included.
Push protection adds another preventive layer. Instead of waiting until a secret is committed and then creating an alert, it can block a push when a supported secret is detected.
This changes the developer workflow in an important way: the contributor receives feedback while attempting to push the code and can remove the sensitive value before it reaches the protected repository.
The available secret-scanning and push-protection capabilities depend on repository visibility, licensing, and administrative configuration. Teams should confirm which protections are enabled rather than assuming that every repository has the same coverage.
Use Placeholder Values in Generated Examples
One practical habit can prevent many accidental leaks: never give an AI assistant a real credential when a placeholder is sufficient.
Suppose a developer needs an HTTP client for a payment service. There is no reason to provide the actual production API key in the prompt. The assistant only needs to understand where the key will be configured and how the application will use it.
A safer prompt would be:
Create an ASP.NET Core service that calls a payment provider.
Read the API key from application configuration.
Do not hardcode credentials.
Use a placeholder in configuration examples.
Do not log the authorization header.
Handle unsuccessful HTTP responses appropriately.
The generated service can then retrieve the key through configuration:
public class PaymentService
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
public PaymentService(
HttpClient httpClient,
IConfiguration configuration)
{
_httpClient = httpClient;
_apiKey = configuration["Payment:ApiKey"]
?? throw new InvalidOperationException(
"Payment API key is not configured.");
}
public async Task<HttpResponseMessage> GetPaymentAsync(
CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(
HttpMethod.Get,
"payments");
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(
"Bearer",
_apiKey);
return await _httpClient.SendAsync(
request,
cancellationToken);
}
}
The code demonstrates how to retrieve and use a credential without embedding its value in the source file.
There is another detail worth considering: avoid logging the request object or authorization headers during debugging. A developer may successfully keep the key out of the repository but accidentally expose it through application logs.
The same principle applies to generated documentation, test fixtures, sample requests, and deployment scripts. Use placeholders that communicate the expected configuration without revealing a working credential.
Add Secret Scanning to the Pull Request Workflow
Secret scanning should be part of the repository's security process rather than an occasional manual activity.
For GitHub repositories, administrators can configure secret scanning and push protection through the repository's security settings when the required features are available. Organizations can also apply security configurations across multiple repositories to maintain consistent protection.
For additional coverage, teams can include a dedicated secret-scanning tool in their CI pipeline. For example, Gitleaks can scan a repository for values matching known secret patterns.
A basic GitHub Actions workflow can run Gitleaks against a pull request:
name: Secret Scan
on:
pull_request:
branches:
- main
permissions:
contents: read
jobs:
secret-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run Gitleaks
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
This example uses a GitHub-hosted action to run a secret scan. Before adopting any third-party action in a production workflow, review its source, permissions, maintenance status, and version-pinning requirements. Organizations with stricter supply-chain policies may choose to pin actions to verified commit SHAs.
The scan should be treated as one layer of protection, not a guarantee that every possible secret will be detected. Custom formats, unusual credential structures, and secrets that do not resemble known patterns may require additional detection rules.
A team can also configure branch protection or repository rules so that required security checks must pass before a pull request is merged. This prevents a contributor from treating a failed security check as an optional warning.
What to Do When a Secret Appears in a Pull Request
Finding a credential in a pull request is not simply a matter of deleting the line containing it. Once a secret has been committed or pushed, it should be considered potentially exposed.
For example, removing an API key from the latest version of a file does not necessarily remove it from earlier commits. Git preserves repository history, so the original value may still be accessible to people who can inspect that history.
The correct response depends on the type of credential and where it was exposed.
First, identify the credential and the service that issued it. Revoke or rotate the exposed value as soon as possible. If it is a database password, create a replacement credential and update the application configuration. If it is an API token, revoke the old token and issue a new one with only the permissions the application requires.
Next, remove the credential from the current code and verify that the replacement is being loaded securely. If the secret has already entered Git history, assess whether history rewriting is necessary and coordinate that operation with repository administrators. Rewriting history can affect collaborators' local branches and existing references, so it should be handled carefully.
Finally, investigate how the credential entered the repository. Was it included in an AI prompt? Did the assistant generate it from a configuration example? Was it copied from a local settings file? Did a developer paste it into a debugging log?
Understanding the cause helps the team prevent the same problem from happening again.
Do not assume that deleting the secret from the pull request makes the exposed credential safe to use. Rotation or revocation is the essential response when a real credential has been exposed.
Common Mistakes Teams Should Avoid
One common mistake is relying entirely on .gitignore. Ignoring files such as local environment settings is useful, but it does not protect secrets that are accidentally added through another file, copied into a source file, or committed before the ignore rule is created.
Another mistake is using placeholder-looking values that are actually valid credentials. A developer may copy a working token into a sample configuration file and assume that nobody will use it. Examples should use clearly invalid placeholders rather than credentials from a real environment.
Teams should also avoid giving AI assistants unrestricted access to sensitive configuration simply to make code generation easier. Provide only the context required for the task, and follow the organization's policies for approved AI tools and data handling.
Finally, do not treat a successful secret scan as proof that a pull request is secure. Secret scanning focuses on credential exposure. It does not replace authorization reviews, dependency analysis, input validation, or application security testing.
Best Practices for Secure AI-Assisted Development
A reliable process combines secure code generation, automated detection, and developer accountability. Developers should avoid sharing real credentials with AI assistants, use placeholders in prompts and examples, and retrieve secrets through approved configuration providers.
Repository administrators should enable the available secret-scanning and push-protection features, configure appropriate custom patterns where necessary, and require security checks before merging. Teams should also review generated configuration files and deployment scripts because credentials are not always introduced into application source code.
Most importantly, establish a clear response process for exposed credentials. Developers should know who to notify, how to revoke a credential, how to update dependent applications, and how to investigate the original leak.
AI assistants can generate useful application code, but they do not take responsibility for protecting the credentials used by that application. That responsibility remains with the development team and its security controls.
Summary
AI-generated pull requests can introduce security problems when developers provide real credentials in prompts, accept generated configuration without reviewing it, or copy sensitive values into application code. These mistakes are preventable when teams establish clear rules for secret management and enforce them through automated checks.
Keep credentials outside source code, use environment variables or dedicated secret stores, provide AI assistants with placeholders instead of real values, and configure secret scanning and push protection where available. Add security checks to the pull request workflow and require developers to investigate any detected exposure.
The goal is not to restrict AI-assisted development. It is to make sure that the productivity gained from generated code does not come at the cost of exposing the credentials that keep applications and infrastructure secure.
Join the conversation! Your thoughts help the community grow.