Skip to content

Module 03 · Lesson 3.4

Authentication, Secrets and Least-Privilege Access

40 minUpdated 18 Nov 2026Part of Tools, APIs and Function Calling · AI Agent Development
On this page
  1. What you will learn
  2. Authentication vs authorisation: who you are and what you may do
  3. What API keys and access tokens are
  4. Where secrets should live: .env files and secret managers
  5. Where secrets must never go
  6. Least privilege: one small key for each tool
  7. Read a secret safely and mask it in logs with Python
  8. A quick map: secret, home and who can see it
  9. What to do if an API key leaks
  10. Conclusion and your next step
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. 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

Authentication vs authorisation: who you are and what you may do

These two words sound alike, but they answer two different questions. Mixing them up is a common beginner mistake.

Authentication
Proving who you are. The question is: "Who is calling?"
Authorisation
Deciding what that caller is allowed to do. The question is: "What may they do?"
Credential
Anything you show to prove who you are, such as a password, a key or a token.

Now picture a library. At the desk you show your member card. That is authentication. The librarian sees you are a real member. Next comes your card type. A child card lets you borrow picture books but not the rare-book room. That is authorisation.

Your agent's tools live in the same world. The orders service first asks, "Who are you?" Then it asks, "Is this caller allowed to read orders? To change them?" A caller can pass the first test and still fail the second.

AuthenticationAuthorisation
QuestionWho is calling?What may they do?
Library exampleShowing your member cardChild card: no rare-book room
Agent exampleThe tool sends its key to the orders serviceThe key may read orders but not change them
ComesFirstSecond
Both checks happen on every request, and both are done by the service, not by the model.

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.

Where the key travels
  1. Model

    Asks for lookup_order("QF-1042")

  2. Tool code

    Reads the key from the environment

  3. Orders service

    Checks the key, then answers

  4. 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 inWhy it is dangerous
Source codeCode is shared, copied and kept in history forever.
The system instructionsThe model can repeat its instructions, and a tricky user can ask for them.
The model's contextWhatever the model reads, it may write back out.
Tool resultsResults go straight into the context. A service that echoes a key back leaks it.
LogsMany people and tools can read logs, and logs are often kept for months.
Screenshots and chat messagesA pasted picture or message can be seen by anyone with access.
Frontend or browser codeAnything sent to a browser can be read by the user in seconds.
If a place can be read by someone who should not hold the key, the key does not belong there.

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.

ToolEnvironment variablePermission
lookup_orderQUILLFEATHER_ORDERS_READ_KEYRead orders. Nothing else.
request_returnQUILLFEATHER_RETURNS_WRITE_KEYCreate return requests only. Cannot approve them or read other data.
Model callGEMINI_API_KEYCall the model. Cannot reach the shop's data.
Three jobs, three keys. If one leaks, the other two stay safe.

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.

Pythonsecrets_demo.py
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 os loads 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 back None if 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 with raise 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, and value[-4:] keeps those last four.
  • The try and except lines 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.

PowerShellrun in PowerShell (Windows)
$env:QUILLFEATHER_ORDERS_READ_KEY = "demo-key-1234abcd"
python secrets_demo.py
Bashrun in macOS or Linux
QUILLFEATHER_ORDERS_READ_KEY=demo-key-1234abcd python3 secrets_demo.py
Output with the variable setCaptured from a real run
Key loaded: *************abcd

Now 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.

Output with the variable missingCaptured from a real run
Error: Missing secret: set the QUILLFEATHER_ORDERS_READ_KEY environment variable.

A quick map: secret, home and who can see it

SecretWhere it livesWho can see it
GEMINI_API_KEY on your laptopGit-ignored .env fileYou, and anyone who uses your computer
QUILLFEATHER_ORDERS_READ_KEY in productionSecret manager, passed to the tool as an environment variableThe tool code and the few admins who may open the safe
QUILLFEATHER_RETURNS_WRITE_KEY in productionSecret manager, passed to the tool as an environment variableThe request_return tool code and its admins
The same keys in a log lineNowhere. Log only the masked form, such as *************abcdAnyone with log access, so they must see only the mask
Any key in the model's contextNowhere. It must never be thereThe model, and possibly the user
Use this table as a template for your own agent. Add one row per secret.

What to do if an API key leaks

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. Step 5: Find the cause and fix it

    Ask how it happened. Add .env to .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.

  1. 1.A tool sends its key to a service, and the service accepts it. Which step is that?
    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.

  2. 2.Where should the agent's order-service key be kept so the model can use it?
    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.

  3. 3.Which setup follows least privilege?
    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_return needs 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.

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.