Sub topic 10
Protecting confidential code and prompts
This chapter covers what happens to the code, prompts and files you send to an AI coding assistant, and how to keep confidential material from leaking. It assumes you can use an AI coding assistant, work with Git and code review, and know roughly what an open-source license is. It is general education, not legal advice. Contracts and laws differ by country and change over time.
Why prompts are a disclosure channel
Earlier chapters asked who owns the code that comes out of a tool. This chapter looks at the other direction: what goes in.
Every prompt is a transfer of data to a third party. A prompt can include more than the text you type. Depending on the tool, it can also carry:
- The file you have open and nearby files the tool decides are relevant.
- Snippets from search results over your repository.
- Terminal output, error logs and stack traces you paste or the tool captures.
- Contents of configuration files, including environment files.
- Conversation history from earlier turns.
Once data leaves your machine, three questions matter. Who can read it? How long is it kept? Can it be used to train a model? The answers come from the tool's terms and your own agreements, which is why this chapter builds on the previous chapter's discussion of tool terms.
Each arrow after the editor is a place where a contract term, a setting or a security control decides what happens next.
Kinds of confidential material
Not everything confidential is a secret key. Sort material into categories, because each category has different rules.
| Category | Examples | Typical source of the duty |
|---|---|---|
| Credentials | API keys, tokens, passwords, private keys | Security policy, cloud provider terms |
| Trade secrets | Proprietary algorithms, unreleased product logic | Trade secret law, employment agreement |
| Client material | A customer's code, schemas, internal URLs | Client contract, non-disclosure agreement (NDA) |
| Personal data | Customer records, user emails in test fixtures | Privacy law such as the GDPR, internal policy |
| Regulated data | Health, payment or export-controlled information | Sector regulation, certification rules |
| Unreleased work | Embargoed features, security fixes before disclosure | Company policy, coordinated disclosure norms |
A non-disclosure agreement is a contract in which one party promises not to reveal information it receives from another. Many NDAs say nothing about AI tools, but they usually prohibit disclosure to any third party without permission. Sending a client's code to a vendor's service can count as that disclosure.
Trade secrets can be lost by careless disclosure
A trade secret is information that has value because it is not generally known and that its owner takes reasonable steps to keep secret. The "reasonable steps" part matters here. If you paste proprietary code into a service that has no confidentiality commitment, a court could later find that the owner did not protect it well enough. Disclosure under a contract that restricts use and retention is much easier to defend than disclosure to a consumer service with broad rights to the data.
This differs from copyright. Copyright protection of your code does not disappear because you sent it to a tool. A trade secret can.
Reading the data terms of a tool
Look for the data-handling terms in the vendor's documentation and agreement. Four questions cover most of the risk.
- Training use. Does the vendor train models on your prompts and code? Many vendors offer different answers for consumer plans and business plans. Check which plan your account is on, not what the marketing page says.
- Retention. How long are prompts and outputs stored? Is there a zero-retention option? Are logs kept for abuse monitoring even if training is off?
- Human access. Can vendor staff or contractors read your data, for example for safety review?
- Subprocessors and location. Which other companies handle the data, and in which regions? This matters for privacy law and for client contracts that restrict where data can go.
Also check how the tool is connected. A tool that calls a model through a cloud provider you already have an agreement with has different terms from the same tool calling a separate vendor directly.
Controlling what the tool can see
Contract terms reduce risk after data leaves your machine. Technical controls reduce what leaves in the first place.
Exclude files from context
Most assistants support an ignore file or an exclusion setting that keeps listed paths out of the context they send. The file name and syntax vary by tool, so check the documentation. A typical exclusion list covers:
.envfiles and other secret stores.- Private keys and certificates.
- Customer data samples and database dumps.
- Directories that hold client code or third-party code under restrictive licenses.
Treat an ignore file as a guard rail, not a guarantee. A tool can still receive content you paste by hand, and some agent modes run commands whose output enters the context.
Keep secrets out of the repository
The most reliable control is not having secrets in files at all. Load them from environment variables or a secrets manager at run time. Then even a tool with full read access to the repository sees no credentials.
Scan before commit and before prompt
A secret scanner checks files for patterns that look like credentials. Running it as a pre-commit hook catches secrets before they reach the repository. The following script is a small, runnable example of the idea. It is a teaching sketch, and a maintained scanner will detect far more patterns.
import re
import sys
from pathlib import Path
PATTERNS = {
"AWS access key ID": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
"Private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
"Generic secret assignment": re.compile(
r"(?i)\b(api[_-]?key|secret|token|password)\b\s*[:=]\s*['\"][^'\"]{8,}['\"]"
),
}
def scan(path: Path) -> list[str]:
findings = []
try:
text = path.read_text(encoding="utf-8", errors="ignore")
except OSError:
return findings
for number, line in enumerate(text.splitlines(), start=1):
for name, pattern in PATTERNS.items():
if pattern.search(line):
findings.append(f"{path}:{number}: possible {name}")
return findings
def main(paths: list[str]) -> int:
findings = []
for p in paths:
findings.extend(scan(Path(p)))
for item in findings:
print(item)
return 1 if findings else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))Save it as scan_secrets.py and run python scan_secrets.py src/app.py. A non-zero exit code means it found something. Pre-commit hooks pass the staged file names as arguments in the same way.
Redact before pasting
When you need help with an error, strip identifying material first. Replace real hostnames, customer names, account IDs and tokens with placeholders. Reduce the code to the smallest example that reproduces the problem. A minimal example is both safer and usually gets a better answer.
Secrets that have already leaked
If a credential has been sent to a tool or committed to a repository, assume it is exposed. Deleting the line afterward does not undo the disclosure, because the data may sit in the vendor's logs and in Git history.
- Revoke or rotate the credential immediately.
- Check access logs for use of the old credential.
- Report the incident under your organization's process. Some contracts require notice to the client within a set time.
- Remove the secret from the repository history only after rotation. Rotation is the fix. History rewriting is cleanup.
Output can also be confidential
Responses are not always safe to share either. A model that was given your private code in the context can echo it back, including in a shared chat, a pull request description or a public issue. Check generated text before you post it outside your organization.
A related risk is injected instructions. An agent that reads untrusted content, such as a web page, an issue comment or a dependency's README, may treat text inside it as a command. A malicious comment could tell the agent to read a credentials file and include it in a request. Limit what agents can read, restrict their network access, and require approval for actions that send data out.
Client contracts and regulated work
A client contract can be stricter than your own company's policy. Look for clauses about:
- Use of subcontractors or third-party services.
- Data location and transfer restrictions.
- Required written consent before using new tools.
- Ownership and deletion of client materials at the end of the engagement.
If the contract is silent on AI tools, do not assume permission. Ask the client or your legal contact. For regulated data, such as health records, using a tool without a suitable agreement can be a compliance violation regardless of how good the vendor's security is.
Local and self-hosted options
Some teams run a model on their own hardware or inside their own cloud account. This keeps prompts inside a boundary you control. It does not remove every obligation. You still need access controls, log retention rules and a license review of the model itself, since model weights have their own terms. It also usually costs more effort to operate and may give weaker results than a hosted model.
| Option | Confidentiality benefit | Trade-off |
|---|---|---|
| Consumer hosted tool | Low unless terms say otherwise | Cheapest, least control |
| Business hosted plan | Contractual limits on training and retention | Still sends data to a third party |
| Cloud-provider hosted model in your account | Data stays under your cloud agreement | Setup and cost |
| Self-hosted model | Data stays inside your network | Operations burden, model quality, model license |
A practical routine
- Classify the repository: public, internal, client-confidential or regulated.
- Match the classification to an approved tool and plan.
- Configure exclusions and confirm the signed-in account.
- Keep secrets out of files, and run a scanner on commits.
- Redact and minimize what you paste.
- Review outputs before sharing them outside the team.
- Know the incident steps for a leaked credential.
Exercise
A contractor pastes a failing test, a stack trace and a .env file into a consumer-plan AI chat to get debugging help on a client project. The client NDA does not mention AI tools. Name at least three problems and the first action the contractor should take about the credentials.
Show answer
Problems: (1) credentials were sent to a third party, so they must be treated as exposed; (2) the client's code and trace may be disclosed in breach of the NDA, which usually bars disclosure to third parties without consent, even if AI is not named; (3) a consumer plan may allow training use, longer retention or human review, and gives weaker confidentiality, which can also weaken any trade secret claim; (4) the client has not agreed to this subprocessor. The first action on the credentials is to revoke or rotate them immediately, then check logs for misuse, report the incident under the contract and company process, and ask the client about permitted tools.
Exercise
Why is an ignore file for an AI assistant not enough on its own to protect secrets, and what is the most reliable control?
Show answer
An ignore file only filters what the tool collects automatically. Secrets can still enter the context through manual pasting, terminal output captured by an agent, or files outside the listed patterns. The most reliable control is to keep secrets out of repository files entirely by using environment variables or a secrets manager, backed by a secret scanner in pre-commit or CI.