These resources are written by Freedom Lab members. Join our Freedom Lab server to be a part of the community and receive support directly.

ResourcesScoped Google Drive Access for AI Agents

Scoped Google Drive Access for AI Agents

Tutorial Open-source AI Privacy Security

Give your AI agent read/write access to Google Drive — scoped to only the files it creates or you explicitly share with it. No blanket access to your entire Drive.

Your AI agent becomes dramatically more useful when it can create documents, spreadsheets, and presentations on your behalf. But handing over full Drive access is a privacy nightmare — especially if you're running open-source tools where you control the keys.

The drive.file scope is the sweet spot: your agent can create new files and access files you deliberately share with it, but it can't browse or read anything else in your Drive. Least privilege, maximum utility.

Architecture

The setup uses two credentials with two purposes:

AI Agent (your machine)
    │
    ├── OAuth Token (~/.your-agent/google-oauth-token.json)
    │     └── Scope: drive.file (only files agent creates or you share)
    │
    ├── Service Account (read-only fallback)
    │     └── Can read shared folder contents, zero storage quota
    │
    └── Shared Folder ("AI Agent" on Google Drive)
          └── Agent creates files here, you share existing files here

Why Not Just Use a Service Account?

Service accounts seem simpler — no browser auth, no token refresh. But they have a fatal limitation: zero Drive storage quota. They can read files shared with them, but they can't create anything. For an agent that needs to generate documents, you need OAuth.

Scope Comparison

Scope What it can access
drive Every file in your entire Google Drive
drive.file Only files the app created + files you explicitly opened/shared with it

If your agent's OAuth token ever leaks, drive.file means the attacker can only see files your agent made — not your tax returns, medical records, or anything else. This is the principle of least privilege in practice.

Step 1 — Create a Google Cloud Project

  1. Go to Google Cloud Console
  2. Create a new project (e.g., "ai-agent")
  3. Enable these APIs:
    • Google Drive API
    • Google Docs API
    • Google Sheets API
    • Google Slides API (optional, for presentation support)

Step 2 — Create OAuth Credentials

  1. Go to APIs & Services → Credentials
  2. Click Create Credentials → OAuth client ID
  3. Application type: Desktop app
  4. Name it something descriptive (e.g., "AI Agent Desktop")
  5. Download the client secret JSON — you'll need the client_id and client_secret

Step 4 — Run the Auth Flow (On a Separate Device)

This is the security-conscious part. If your AI agent runs on a machine you don't want logged into your Google account (shared server, always-on box), do the auth on a different device.

First, install the required Python libraries:

pip install google-api-python-client google-auth-oauthlib

Then run this script:

#!/usr/bin/env python3
"""Generate OAuth token for Google Drive (drive.file scope)."""

from google_auth_oauthlib.flow import InstalledAppFlow

CLIENT_CONFIG = {
    "installed": {
        "client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
        "client_secret": "YOUR_CLIENT_SECRET",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"]
    }
}

SCOPES = ["https://www.googleapis.com/auth/drive.file"]

flow = InstalledAppFlow.from_client_config(CLIENT_CONFIG, SCOPES)
auth_url, _ = flow.authorization_url(prompt="consent")
print(f"\nOpen this URL in a browser:\n{auth_url}\n")
code = input("Paste the authorization code here: ")

flow.fetch_token(code=code)
creds = flow.credentials

print(f"\nAccess token: {creds.token}")
print(f"Refresh token: {creds.refresh_token}")

The key trick: using urn:ietf:wg:oauth:2.0:oob as the redirect URI means Google shows you an auth code instead of redirecting to localhost. You can open the auth URL on your phone, sign in there, and paste the code back to your agent's machine. Your Google password never touches the agent's machine.

Step 5 — Store the Token

Save the credentials as JSON for your agent to use:

{
    "access_token": "ya29...",
    "refresh_token": "1//0e...",
    "client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
    "client_secret": "YOUR_CLIENT_SECRET"
}

Store this at a known path (e.g., ~/.your-agent/google-oauth-token.json). Your agent reads this file when it needs to call Google APIs.

Set permissions to owner-only:

chmod 600 ~/.your-agent/google-oauth-token.json

Security note: This file contains your refresh token — treat it like a password. Anyone with it can create and access files as your app.

Step 6 — Create a Shared Folder

Create a single dedicated folder in Google Drive (e.g., "AI Agent"). Your agent will create all new files inside this folder, keeping things organized and easy to find.

Security recommendation: Only give your agent access to one folder. Even though drive.file already limits scope, funneling everything through a single folder gives you a clear boundary — you can see exactly what your agent has touched, revoke access by unsharing one folder, and avoid files scattering across your Drive. If the agent needs to read existing files, share them into this folder rather than granting broader access. One folder = one kill switch.

To get the folder ID: open the folder in Drive, look at the URL — the ID is the long string after /folders/:

https://drive.google.com/drive/folders/1gKS5aeDY5vjjS...
                                        ^^^^^^^^^^^^^^^ this part

Save this folder ID in your agent's config — it'll use this as the default parent for new files.

Step 7 — Use It

Here's a minimal example of creating a Google Doc in your shared folder:

import json
from pathlib import Path
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

TOKEN_PATH = Path.home() / ".your-agent" / "google-oauth-token.json"

def get_credentials():
    with open(TOKEN_PATH) as f:
        token_data = json.load(f)
    return Credentials(
        token=token_data.get("access_token") or token_data.get("token"),
        refresh_token=token_data["refresh_token"],
        token_uri="https://oauth2.googleapis.com/token",
        client_id=token_data["client_id"],
        client_secret=token_data["client_secret"],
        scopes=["https://www.googleapis.com/auth/drive.file"],
    )

creds = get_credentials()
drive = build("drive", "v3", credentials=creds)
docs = build("docs", "v1", credentials=creds)

# Create a new doc in your shared folder
file_metadata = {
    "name": "Meeting Notes - 2026-02-25",
    "mimeType": "application/vnd.google-apps.document",
    "parents": ["YOUR_FOLDER_ID"]
}

file = drive.files().create(body=file_metadata, fields="id").execute()
doc_id = file["id"]
print(f"Created doc: https://docs.google.com/document/d/{doc_id}")

# Write to it
docs.documents().batchUpdate(
    documentId=doc_id,
    body={"requests": [{
        "insertText": {
            "location": {"index": 1},
            "text": "Hello from your AI agent!\n"
        }
    }]}
).execute()

Step 8 — (Optional) Add a Service Account for Read-Only

If you also want your agent to read files you didn't create through the agent:

  1. In Google Cloud Console: IAM & Admin → Service Accounts → Create
  2. Download the JSON key file
  3. Save it (e.g., ~/.your-agent/google-service-account.json)
  4. Share your Drive folder with the service account's email address (it looks like name@project.iam.gserviceaccount.com)

The service account can now list and read files in that folder. Use OAuth for creating, service account for reading — belt and suspenders.

Token Refresh

The access token expires after ~1 hour. The Google Python client handles refresh automatically using the refresh token — you don't need to manage this manually. Just make sure the refresh token is in your stored JSON.

The refresh token itself lasts until you revoke it — unless your app is in "Testing" mode on Google Cloud, in which case it expires after 7 days. When that happens, re-run the auth flow from Step 4.

Gotchas

Privacy Model

Your Google Drive
├── Personal files       ← Agent CANNOT see these
├── Work files           ← Agent CANNOT see these
└── Shared "AI Agent" folder
    ├── Files you share here  ← Agent CAN read (via service account)
    └── Files agent creates   ← Agent CAN read/write (via OAuth)

This is the same principle as giving someone a key to one room in your house instead of the master key. The agent is powerful where you need it, blind everywhere else.