How to Use Google Workspace Drive API to Detect External File Sharing

One of the biggest security risks in Google Workspace is the ease with which users can share data. An employee might create a highly confidential Google Sheet containing Q3 financial projections, click the blue “Share” button, and accidentally type the email address of a competitor or a personal Gmail account. Worse, they might accidentally set the link sharing option to “Anyone with the link can view,” effectively making the document public to the entire internet. As an administrator, you cannot manually check the sharing settings of millions of files. You must use the Google Workspace Drive API to programmatically audit your environment for external data exposure.

Understanding Drive Permissions

In the Drive API, every file has a permissions resource attached to it. A permission object defines who has access (the type), their email address (if applicable), and what they can do (the role, such as reader, writer, or owner).

The type field is the key to identifying external sharing. The possible types are:

  • user: A specific person (e.g., [email protected]).
  • group: A Google Group.
  • domain: Anyone inside your specific Google Workspace domain.
  • anyone: The public internet (Anyone with the link).

Step 1: Identifying Public Files (“Anyone with the link”)

The most dangerous sharing setting is type='anyone'. If this is set, the file is essentially a public webpage.

You can use the files().list() method with a specialized query (q) to instantly find all files in the organization that are exposed to the public. (Note: Your API script must be using a Service Account with Domain-Wide Delegation to scan all users’ drives, not just your own).

query = "visibility='anyoneCanFind' or visibility='anyoneWithLink'"

results = service.files().list(
    q=query,
    fields='files(id, name, webViewLink, owners)',
    corpora='allDrives',
    includeItemsFromAllDrives=True,
    supportsAllDrives=True
).execute()

for f in results.get('files', []):
    owner = f['owners'][0]['emailAddress']
    print(f"PUBLIC FILE DETECTED: {f['name']} | Owned by: {owner} | Link: {f['webViewLink']}")

This script will generate a report of every public file, allowing you to contact the owners and ask them to secure their data.

Step 2: Identifying External Users (Specific Gmails)

What if a user didn’t make the file public, but they shared it explicitly with [email protected]? The search query cannot easily filter by “outside my domain.” You must pull the files and inspect the permission objects directly.

First, retrieve a file and explicitly request the permissions field.

file_id = '1aB2c3D4e5F6g7H8i9J0'
my_domain = '@mycompany.com'

response = service.files().get(
    fileId=file_id,
    fields='id, name, permissions'
).execute()

permissions = response.get('permissions', [])

for perm in permissions:
    if perm['type'] == 'user':
        email = perm.get('emailAddress', '')
        
        # Check if the email ends with your corporate domain
        if my_domain not in email:
            print(f"EXTERNAL SHARE DETECTED: File '{response['name']}' shared with {email} (Role: {perm['role']})")

Step 3: Automating Remediation (Revoking Access)

If you detect a severe violation (e.g., an entire folder of HR documents shared with a personal @gmail.com address), you don’t need to wait for the user to fix it. Your script can instantly revoke the access using the permissions().delete() method.

To do this, you need the id of the specific permission object (which you obtained in Step 2).

permission_id_to_revoke = '0987654321' # The ID of the external user's permission

# Instantly remove their access to the file
service.permissions().delete(
    fileId=file_id,
    permissionId=permission_id_to_revoke
).execute()

print("External access successfully revoked.")

By scheduling a Python script to run this audit weekly via a cron job, you create an automated Data Loss Prevention (DLP) system that actively monitors and remediates external sharing violations across your entire Google Workspace environment.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.