Module 03 · Lesson 3.4
Authentication, Secrets and Least-Privilege Access
On this page
- What you will learn
- Authentication vs authorisation: who you are and what you may do
- What API keys and access tokens are
- Where secrets should live: .env files and secret managers
- Where secrets must never go
- Least privilege: one small key for each tool
- Read a secret safely and mask it in logs with Python
- A quick map: secret, home and who can see it
- What to do if an API key leaks
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think of a hotel key card. The card proves you are a guest, so the door opens. But it only opens your room, not the manager's office. If you lose it, the hotel switches it off and prints a new one. Nobody writes your room number and door code on the hotel's front sign.
An AI agent's tools need keys too. A tool that reads orders needs one. A tool that creates returns needs another. This lesson shows how those keys work, where to keep them, where never to put them, and what to do when one leaks. Most of it needs no coding. One short Python example shows how to read a key safely and hide it in logs.
What you will learn
- Explain the difference between authentication and authorisation in plain words.
- Choose a safe home for each secret, and name the places a secret must never go.
- Give each tool its own key with the smallest permission it needs.
- Write a small Python helper that reads a secret from the environment and masks it in logs.
Before you start
- The previous lesson, Connecting REST APIs and Internal Services.
- The Module 2 lab, where you saved
GEMINI_API_KEYin a.envfile. See Practical Lab: Build and Test Your First AI Agent, Step by Step. - No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What API keys and access tokens are
An API key is a long secret text, like a password made for programs. You send it with each request. The service reads it and knows which account is calling.
An access token is similar, but usually short-lived. Think of a day pass at a theme park. It works for a few hours, then it stops. If someone steals it, the damage ends soon. Many services hand out tokens that expire after minutes or hours.
Both are secrets: values that must stay private. Anyone who holds the key can act as you, and the service cannot tell the difference. That is why this lesson is about keeping them in the right place.
- Model
Asks for lookup_order("QF-1042")
- Tool code
Reads the key from the environment
- Orders service
Checks the key, then answers
- Tool result
Order data only, no key
The key stays on your side of the line. Only the order data comes back to the model.
Where secrets should live: .env files and secret managers
A secret needs a home outside your code. The usual home is an environment variable. That is a named value that the operating system hands to a program when it starts. The program asks for it by name, for example QUILLFEATHER_ORDERS_READ_KEY.
On your own computer: a git-ignored .env file
In the Module 2 lab you saved GEMINI_API_KEY in a .env file and listed that file in .gitignore. That is still the right habit. The .env file holds one name and value per line. Git (opens in a new tab) skips any file named in .gitignore, so the key never reaches your repository. Our guide Managing API Keys Locally covers the setup step by step.
In production: a secret manager
A secret manager is a locked safe for keys, run as a service. Your app asks it for a key when it starts. Only approved people and programs can open the safe. It also records who opened it, and it makes changing a key easy.
Why not just copy the .env file to the server? Files get copied, emailed and forgotten. A safe with a guest list and a log is easier to control. Your cloud or hosting provider usually offers one. The general idea is described in the OWASP Secrets Management Cheat Sheet (opens in a new tab).
Where secrets must never go
A secret is only as safe as the most open place it has been copied to. Keep it out of every one of these:
| Never put a secret in | Why it is dangerous |
|---|---|
| Source code | Code is shared, copied and kept in history forever. |
| The system instructions | The model can repeat its instructions, and a tricky user can ask for them. |
| The model's context | Whatever the model reads, it may write back out. |
| Tool results | Results go straight into the context. A service that echoes a key back leaks it. |
| Logs | Many people and tools can read logs, and logs are often kept for months. |
| Screenshots and chat messages | A pasted picture or message can be seen by anyone with access. |
| Frontend or browser code | Anything sent to a browser can be read by the user in seconds. |
The first rows are the usual accidents. The model rows matter most for agents. Our Context Design lesson explains that everything in the context can influence the answer. Add the risk of prompt injection, where a hidden message tricks a model into revealing things. If the key was never in the context, there is nothing to reveal.
Least privilege: one small key for each tool
Least privilege means giving each part of a system only the access it needs and nothing more. Think of a cafe. The cashier has a key to the till, not to the safe in the back. The cleaner has a key to the building, not to the till.
For agents, this means one credential per tool. Quillfeather Cycles has two tools. lookup_order only reads. request_return creates a return request that staff must approve. They should not share one master key.
| Tool | Environment variable | Permission |
|---|---|---|
lookup_order | QUILLFEATHER_ORDERS_READ_KEY | Read orders. Nothing else. |
request_return | QUILLFEATHER_RETURNS_WRITE_KEY | Create return requests only. Cannot approve them or read other data. |
| Model call | GEMINI_API_KEY | Call the model. Cannot reach the shop's data. |
Why bother? If the read-only key leaks, an attacker can look at orders but cannot create anything. If the agent is tricked into a wrong action, the damage is limited to what that one key allows. The OWASP page on Excessive Agency (opens in a new tab) names too much access as a real risk for AI systems.
Keys that expire, rotate and revoke
- Expire: a key with an end date stops working by itself. Prefer short lives where the service allows it.
- Rotate: replace a key with a new one on a schedule, then switch the old one off. It is like changing your locks every year.
- Revoke: switch a key off right now, for example when it leaks. Check that you know where this button is before you need it.
Read a secret safely and mask it in logs with Python
A log is a written record of what a program did. Logs help you find bugs, but they get shared. To stay safe, log a masked key: most of it hidden, with only the last four characters shown. That is enough to tell two keys apart.
The script below has two small helpers. It uses only Python's standard library, so it runs offline. The key is never written in the code. It comes from the environment.
import os
def get_secret(name):
value = os.environ.get(name)
if not value:
raise RuntimeError(f"Missing secret: set the {name} environment variable.")
return value
def mask(value):
if len(value) <= 4:
return "****"
return "*" * (len(value) - 4) + value[-4:]
try:
key = get_secret("QUILLFEATHER_ORDERS_READ_KEY")
print("Key loaded:", mask(key))
except RuntimeError as error:
print("Error:", error)Standard library only. The secret value is supplied from outside the file.
What each part does
import osloads Python's built-in tools for talking to the operating system.def get_secret(name):creates a function, a named recipe you can reuse. You give it the name of a variable.os.environ.get(name)looks up that variable. It gives backNoneif the variable does not exist, instead of crashing. See the os module docs (opens in a new tab).if not value:is true when the value is missing or empty. Then the function stops withraise RuntimeError(...)and a clear message.- The error message contains the variable name, never a value. A name is safe to print.
def mask(value):hides a key."*" * (len(value) - 4)makes one star for every character except the last four, andvalue[-4:]keeps those last four.- The
tryandexceptlines run the code and catch the error, so you see a friendly message instead of a long crash report.
Run it with a fake key
Use a clearly fake value so nothing real is at risk. On macOS or Linux, the variable is set for that one command only. In PowerShell, it stays set until you close that terminal window.
$env:QUILLFEATHER_ORDERS_READ_KEY = "demo-key-1234abcd"
python secrets_demo.pyQUILLFEATHER_ORDERS_READ_KEY=demo-key-1234abcd python3 secrets_demo.pyKey loaded: *************abcdNow run it again in a fresh terminal where the variable is not set. In PowerShell, you can also clear it with Remove-Item Env:QUILLFEATHER_ORDERS_READ_KEY.
Error: Missing secret: set the QUILLFEATHER_ORDERS_READ_KEY environment variable.A quick map: secret, home and who can see it
| Secret | Where it lives | Who can see it |
|---|---|---|
GEMINI_API_KEY on your laptop | Git-ignored .env file | You, and anyone who uses your computer |
QUILLFEATHER_ORDERS_READ_KEY in production | Secret manager, passed to the tool as an environment variable | The tool code and the few admins who may open the safe |
QUILLFEATHER_RETURNS_WRITE_KEY in production | Secret manager, passed to the tool as an environment variable | The request_return tool code and its admins |
| The same keys in a log line | Nowhere. Log only the masked form, such as *************abcd | Anyone with log access, so they must see only the mask |
| Any key in the model's context | Nowhere. It must never be there | The model, and possibly the user |
What to do if an API key leaks
Step 1: Revoke the key
Switch it off in the provider's dashboard or in your secret manager. This is the step that stops the harm. Do it first.
Step 2: Create a replacement
Make a new key with the same small permission. Store it in the secret manager or
.env, and restart the tool so it picks the key up.Step 3: Check what happened
Read the provider's usage or access logs for the time the key was exposed. Look for requests you do not recognise.
Step 4: Remove the key from where it leaked
Delete the message, file or log line. Remember that deleting does not undo the leak, which is why step 1 comes first.
Step 5: Find the cause and fix it
Ask how it happened. Add
.envto.gitignore, mask the logs, or move the key out of the code. Tell your team what you learned.
Before launch, run through the Agent Launch Safety Checklist to confirm no secret sits in code, logs or the repository.
Conclusion and your next step
Authentication proves who is calling. Authorisation limits what they may do. The tool code holds the key, the model never sees it, and each tool gets its own small key. Keep secrets in the environment or a secret manager, mask them in logs, and revoke fast if one leaks.
Your next step: list the secrets your agent needs, give each tool its own key, and fill in a table like the one above. Then continue to Tool Errors, Retries, Timeouts and Idempotency, where you learn what the agent should do when a call fails.
Want more practice? Try Practical Lab: Build an Agent That Uses Two Tools, or look up any unfamiliar word in the Glossary of AI Engineering and Agent Terms.
Common errors and how to fix them
A real key appears in the code or in a Git commit.
Why it happens: The key was pasted into a file for a quick test, or .env was not listed in .gitignore.
Fix: Revoke the key and make a new one. Move the new key into the environment, and add .env to .gitignore before the next commit.
One master key is shared by every tool.
Why it happens: It was faster to create only one key.
Fix: Make one key per tool with the smallest permission. A read-only tool should hold a read-only key.
A full key shows up in a log file or an error message.
Why it happens: The code printed the whole request, headers or settings while debugging.
Fix: Log only masked values, and never print headers or settings objects whole.
The program fails with a vague error instead of saying a key is missing.
Why it happens: The code used the variable without checking that it was set.
Fix: Read secrets with a helper like get_secret that stops early and names the missing variable.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Plan the keys for a delivery-tracking agent
A bakery agent has two tools. check_delivery(order_id) reads the status of a delivery. reschedule_delivery(order_id, new_time) asks the driver team to move a delivery. Write a one-page key plan.
You will need
- The bakery uses a delivery service with API keys that can be set to read or write.
- The agent also needs a key for the AI model.
- Logs are shared with a support contractor.
- A tester wants a copy of the setup on their laptop.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Start with a table: tool, variable name, permission.
- Ask who can read the logs. Then decide what a log line may show.
- The tester only needs a test key, not the production one.
Show a model answer
A strong answer has three keys. BAKERY_DELIVERY_READ_KEY (read status only) for check_delivery, BAKERY_DELIVERY_WRITE_KEY (change delivery times only) for reschedule_delivery, and GEMINI_API_KEY (or another model key) for the model. On the laptop, they live in a git-ignored .env file and the tester gets separate test keys. In production, they live in a secret manager and reach the tool code as environment variables. Logs show only the masked form, for example the last four characters, because a contractor can read them. No key goes in code, instructions, the model's context, tool results, screenshots or browser code. If the write key leaks: first revoke it, then create a new one with the same small permission and check the delivery service's access log for changes nobody asked for.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. Accepting the key shows who is calling, which is authentication. The first option is tempting because a key often carries permissions, but deciding what the caller may do is a separate check that comes after. Programs can be authenticated too, so the third option is wrong.
Show the answer and explanation
Answer: B. The model only picks a tool and arguments, and the tool code adds the key. The first option feels convenient, but anything in the instructions can be repeated back to a user. The third option puts the secret in the context, which is exactly where it must not be.
Show the answer and explanation
Answer: B. Each tool holds only the permission it needs, so a leak or a mistake stays small. The first option is simple but gives every tool too much power. The third option cannot work, because
request_returnneeds to create something, and a note in the instructions is not a real limit.
Frequently asked questions
What is the difference between authentication and authorisation?
Authentication proves who is calling. Authorisation decides what that caller may do. At a cinema, your ticket proves you paid. Where it lets you sit is the second check. A service does both for each request.
Where should I store API keys?
On your computer, use environment variables, usually loaded from a .env file that is listed in .gitignore. In production, use a secret manager or your hosting provider's secret settings. Never store keys in source code, logs or browser code.
What should I do if I accidentally committed an API key to GitHub?
Revoke the key first and create a new one. Deleting the file or the commit is not enough, because the old version may already be copied. Then check the service's access log for use you do not recognise, and fix the cause so it cannot happen again.
Does an AI model need my API key to call a tool?
No. The model only names the tool and its arguments. Your own code runs the tool and adds the key. Keeping the key out of the model's context means the model cannot repeat it, even if someone tricks it.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Secrets Management Cheat Sheet(opens in a new tab)
OWASP · Official documentation · General guidance on storing, controlling and rotating secrets.
- The Twelve-Factor App: Config(opens in a new tab)
The Twelve-Factor App · Why settings that change between machines belong in the environment, not in code.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Why an AI system should get only the access its job needs.
- OWASP Top 10 for LLM Applications(opens in a new tab)
OWASP Foundation · Official documentation · The wider list of risks for applications built on language models.
- os module (os.environ)(opens in a new tab)
Python Software Foundation · Official documentation · Background for reading environment variables in the example.
- gitignore documentation(opens in a new tab)
Git · Official documentation · How Git is told to skip files such as `.env`.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.