Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 1 · BASICS

Safe Use of AI Coding Assistants (Secrets, Licences, Data)

AI coding tools are useful. They can also leak secrets, suggest code you cannot use, or run a dangerous command. This lesson shows the simple rules that keep you and your company safe.

In short: never paste secrets or .env files, check the licence of suggested code, know what leaves your machine (cloud vs local), follow company policy, and never auto-approve dangerous shell commands.

Why safe use matters

WHY

One pasted API key in a cloud chat can bill your cloud account overnight. One copy-pasted snippet under a strict open-source licence can create a legal problem for your company. One agent command like rm -rf can wipe a folder. Safety is part of the skill, not an extra.

What the risks are

WHAT
  • Secrets: API keys, passwords, .env files, private keys, customer data, production connection strings.
  • Licences: code the AI suggests may match open-source projects. Some licences force you to open your whole product (copyleft). Others are fine for commercial use (MIT, Apache-2.0).
  • Data leaving your PC: cloud assistants send prompts and often parts of your files to a company server. Local tools like Ollama keep the model on your machine.
  • Dangerous actions: agent mode can run shell commands, edit many files, install packages, or push to git if you allow it.
  • Company policy: many Indian IT companies ban pasting client code into public AI tools, or allow only approved tools.

How a safe session flows

1 · Check company policy approved tools only 2 · Block secrets deny .env, keys 3 · Prefer local or private when data is sensitive 4 · Small, clear prompts no customer data 5 · Read every diff + command never blind auto-approve

Rule 1 — do not paste secrets

HOW
  1. Never put .env, credentials.json, PEM keys, or database passwords in a prompt.
  2. In Claude Code, deny those paths in .claude/settings.json (example below).
  3. In Copilot / Cursor / Continue, keep secrets out of the workspace the tool indexes, or add them to ignore lists.
  4. If you pasted a key by mistake: rotate it now (create a new key, delete the old one) in AWS, GitHub, Stripe, etc.
.claude/settings.json
{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)",
      "Read(**/*.pem)",
      "Bash(rm -rf:*)",
      "Bash(git push --force:*)"
    ]
  }
}

Rule 2 — check licences of suggested code

  1. If the AI pastes a large block that looks copied from a library, ask: “Is this from an open-source project? Which licence?”
  2. Search a unique line on GitHub. If it matches a GPL or AGPL file and your product is closed-source, do not use it as-is.
  3. Prefer asking the AI to write a small function from a clear spec, not “copy how library X does it”.
  4. When you use a real library, add it through your package manager (pip, npm, Maven) so the licence is tracked.

Rule 3 — know what leaves your machine

SetupWhere code/prompts goGood for
Cloud chat (ChatGPT, Claude web, Gemini)provider serverslearning, public practice code
IDE cloud assistants (Copilot, Claude Code, Cursor cloud models)provider servers + your project contextday-to-day coding under company rules
Local Ollama + Continuestays on your PC (no cloud model call)client code, personal data, offline work
Company private model / VPCyour company's serversenterprise policy
Local does not mean “no risk”. A local agent can still delete files on your disk if you approve bad commands. Privacy and safety are different.

Rule 4 — company policy first

  1. Ask your lead: which AI tools are allowed? Is client code allowed in any cloud tool?
  2. Use only the approved account (often a company Copilot or Claude seat), not your personal free account for office work.
  3. Do not paste customer names, phone numbers, Aadhaar, PAN, bank data, or medical records into any AI.
  4. If policy is unclear, use a local model or write the code yourself until someone confirms.

Rule 5 — never auto-approve dangerous shell

HOW
  1. Keep permission prompts on in Claude Code, Copilot Agent, Cursor Agent, Devin Local, Kiro.
  2. Read every command before Yes. Refuse: rm -rf, mkfs, dd, force-push to main, curl-piped-to-bash from unknown URLs, disabling firewalls.
  3. Prefer Plan mode first for big tasks: the tool lists steps; you approve; then it runs.
  4. On a production server or a shared machine, do not run agent mode at all unless your team has a written process.
Rule: turning off all permission checks on your real laptop or a production server is never worth the speed. One bad command can cost more than a month of AI subscription.

A one-page safe checklist

  • Before: approved tool? secrets out of the folder? policy OK?
  • During: no .env in prompts; Plan mode for big jobs; read every diff and shell line.
  • After: run tests yourself; rotate any key you may have exposed; commit only what you understand.

Practice: hide secrets in a log line, then review the AI's diff and run the tests

Hello friends. The chapter above gave you the rules for safe use. Now you practise them on a real task. The practice is a fictional coaching class called Neem Tree Tuition Centre. Its log lines contain fake passwords, keys and tokens, and you will ask an AI tool to hide those values before a log is shared. You keep secrets out of the prompt, read every line of the AI's diff, and run the tests yourself. The starter file fails 4 tests and passes 2, and a correct fix passes all 6.

Ravindra Bagale's Tip

Every value in this practice is a fake placeholder. Never put a real password, key or token in a prompt, a test file or a screenshot. If a real one ever leaks, create a new one and turn off the old one in the service where it was made.

Practice label: Neem Tree Tuition Centre and every password, key and token in these files are fictional teaching data. None of them is a real secret, and no real student data is used. Passing these tests proves only the listed cases.
Environment (tested): on 16 November 2026 the starter and fixed files below were run on this course's Linux build machine with Python 3.13.5 and pytest 9.1.1. Starter: 4 failed, 2 passed. Fixed file: 6 passed. The AI tool itself runs on your own computer, so its words will differ from any example here.
Checked against official docs: every menu name, command and setting in this practice was checked on 16 November 2026 against the Claude Code security, permissions and settings pages on code.claude.com and the VS Code agent security and review agent changes pages on code.visualstudio.com. These tools update often. If a menu name looks different on your screen, search for the same words in the official docs or the Command Palette, and do not guess.

Your task: ask your AI coding tool to make redact_line hide the value after password=, api_key= and token= with ***, match those names in any mix of capital and small letters, hide every match on the line, and leave other text unchanged.

Setup (practice folder neem-tree-redact)

HOW
  1. Create the practice folder with the name shown below, and save the two files from this section inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Starter redact.py (it hides only the first password= value and only in small letters):

redact.py
"""Practice data: Neem Tree Tuition Centre is a fictional coaching class made up for this exercise.
Every value below is a fake placeholder, not a real password, key or token."""

SECRET_KEYS = ("password",)


def redact_line(line):
    """Hide secret values in one log line before anyone shares it."""
    for key in SECRET_KEYS:
        marker = key + "="
        if marker in line:
            start = line.index(marker) + len(marker)
            end = line.find(" ", start)
            if end == -1:
                end = len(line)
            line = line[:start] + "***" + line[end:]
    return line

Simple tests test_redact.py:

test_redact.py
from redact import redact_line


def test_password_is_hidden():
    assert redact_line("user=student01 password=practice123") == "user=student01 password=***"


def test_normal_line_is_unchanged():
    assert redact_line("course=python batch=evening") == "course=python batch=evening"


def test_api_key_is_hidden():
    assert redact_line("api_key=practice-not-real-001 status=ok") == "api_key=*** status=ok"


def test_token_is_hidden():
    assert redact_line("token=demo-token-xyz") == "token=***"


def test_capital_letters_are_hidden_too():
    assert redact_line("PASSWORD=Fake#Pass9") == "PASSWORD=***"


def test_every_secret_on_the_line_is_hidden():
    assert redact_line("password=one password=two") == "password=*** password=***"

Before you ask the AI, run python -m pytest -q in the folder. You should see 4 failed, 2 passed. That proves Python and pytest work before the AI tool is involved.

The exact prompt to try (copy it as it is):

safe-prompt.txt
Read redact.py and test_redact.py. They are practice files for the fictional Neem Tree Tuition Centre, and every secret value in them is a fake placeholder. Fix redact_line so it replaces the value after password=, api_key= and token= with ***, in any mix of capital and small letters, for every match on the line. Keep the key name as written and leave other text unchanged. Do not change test_redact.py, do not read any other file, and do not add any real-looking keys. Show me the diff before you save it.

HOW to work safely with the AI on this task

HOW
  1. Check the folder first: the folder should contain only redact.py, test_redact.py and your .venv. If you copied it inside a real project, make sure no .env file or real key file is in the same folder.
  2. Optional, for Claude Code users: stop Claude's file tools from reading .env files with a deny rule in ~/.claude/settings.json, for example {"permissions": {"deny": ["Read(./.env)", "Read(./.env.*)"]}}. The file must be strict JSON, so do not add comments or a trailing comma.
  3. Use an approval mode: in Claude Code choose Manual. In VS Code with Copilot, keep the permission level at Manual permissions, and remember that it does not ask before every file edit, so you still review each edit. Do not use a mode that approves everything for this practice.
  4. Paste the prompt above and read the answer before you approve anything.
  5. Review the diff line by line: the change should touch only redact.py. Check that it does not print, log or send the secret values anywhere, does not add new keys, and does not edit test_redact.py.
  6. Check what changed on disk: if the folder uses git, run git status and git diff. Only redact.py should be listed.
  7. Run the tests yourself: python -m pytest -q. Expect 6 passed. Then run python -c "from redact import redact_line; print(redact_line('api_key=practice-not-real-001 status=ok'))". It prints api_key=*** status=ok.

What a correct result looks like: The AI explains that the starter searches only for small-letter password= and stops after the first match. A good fix uses one regular expression with a case-insensitive flag, or a loop that checks every word on the line. The exact code changes from run to run, which is fine. The result is correct only when pytest shows 6 passed, git diff shows only redact.py, and no real secret appeared anywhere in the conversation.

Real pytest output after the fixed file:

pytest-after.txt
......                                                                   [100%]
6 passed in 0.01s
Optional completed redact.py (try it yourself first)

The AI may split the line into words instead of using a regular expression. Any version is fine if all 6 tests pass, the test file is unchanged, and nothing prints the secret values.

redact.py
"""Practice data: Neem Tree Tuition Centre is a fictional coaching class made up for this exercise.
Every value below is a fake placeholder, not a real password, key or token."""

import re

SECRET_KEYS = ("password", "api_key", "token")
SECRET_PATTERN = re.compile(r"\b(" + "|".join(SECRET_KEYS) + r")=\S+", re.IGNORECASE)


def redact_line(line):
    """Hide secret values in one log line before anyone shares it."""
    return SECRET_PATTERN.sub(lambda match: match.group(1) + "=***", line)

Troubleshooting: common safety mistakes

HOW
  1. Problem: the AI wants to open .env to understand your settings. Fix: refuse that request. In Claude Code, add a Read deny rule such as Read(./.env). A .claudeignore file has no effect, so move its entries into Read deny rules.
  2. Problem: an agent might edit .env in VS Code without asking. Fix: use the chat.tools.edits.autoApprove setting with "**/.env": false, so VS Code shows a diff and asks for approval before it saves an edit to that file.
  3. Problem: the tests pass, but the AI also changed the test file. Fix: that hides the bug instead of fixing it. Undo the change to test_redact.py, then ask the AI to fix only redact.py.
  4. Problem: the tests ran on code you have not reviewed yet. Fix: in VS Code, agent edits are saved to disk before you review them. Review each change and choose Keep or Undo before you trust any test result.
  5. Problem: a change made through a terminal command is missing from the review list. Fix: the review list tracks only edits from the agent's edit tools. Use the Source Control view or git status to see every changed file.
  6. Problem: you are not sure whether a command the AI suggests is safe. Fix: do not approve it. Claude Code's security guide says you are responsible for reviewing proposed code and commands before approval, so ask the AI to explain the command first.
  7. Problem: you pasted a real key into a chat by mistake. Fix: deleting the message is not enough. Create a new key and turn off the old one in the service where it was made, and then update your own code to use the new key.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Fake data only in AI prompts

Practice files should use clearly fake placeholders such as practice-not-real-001.
A real password, key or token must never appear in a prompt, a test file or a screenshot.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Three checks before you keep AI code

Read the diff line by line, and confirm that the test file did not change.
Run git diff to see every changed file, and then run the tests yourself.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

AI prompts मध्ये फक्त खोटा data

सरावाच्या files मध्ये practice-not-real-001 सारखे स्पष्टपणे खोटे placeholders वापरा.
खरा password, key किंवा token कधीही prompt, test file किंवा screenshot मध्ये येऊ नये.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

AI चा code ठेवण्याआधी तीन तपासण्या

Diff ओळ न ओळ वाचा, आणि test file बदलली नाही याची खात्री करा.
प्रत्येक बदललेली file पाहण्यासाठी git diff चालवा, आणि मग tests स्वतः चालवा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Should you paste a .env file into ChatGPT to “debug the config”?

No. Redact secrets or describe the keys without values. Rotate any key you already pasted.

2. Cloud vs local Ollama — what is the privacy difference?

Cloud sends prompts/context to a provider. Ollama runs the model on your PC.

3. What should you do before allowing an agent to run a shell command?

Read the full command. Refuse deletes, force-pushes and unknown install scripts.

4. Why check the licence of a big pasted snippet?

It may come from a copyleft project you cannot ship inside closed-source software.

Save tokens and money

SMART AI USE

Safety also saves money: smaller prompts without secrets and logs mean fewer tokens. Put standing deny rules in one short settings file instead of repeating “do not read .env” in every chat.

Save these cards

INTERVIEW CARDAI Coding

How do you use AI coding tools safely?

Never paste secrets or customer data; deny .env in tool settings.
Follow company policy; prefer local models for sensitive code.
Keep shell approval on; read every command.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Cloud AI vs local Ollama

Cloud: strong models, code leaves your PC.
Local Ollama: weaker or slower on small PCs, data stays with you.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Safe use in 5

No secrets / .env in prompts.
Check licences of big snippets.
Know cloud vs local.
Company policy first.
Never blind auto-approve shell.
Ravindra Bagale · ravindrabagale.com/ai-coding