DEV Community

omkar
omkar

Posted on

From $50K Reports to AI Automation: Securing Multi-Agent ESG Compliance with Auth0

Auth0 for AI Agents Challenge Submission

This is a submission for the Auth0 for AI Agents Challenge

What I Built

ESG Copilot is an autonomous multi-agent AI system that automates ESG (Environmental, Social, Governance) compliance for small and medium businesses, secured end-to-end with Auth0 for AI Agents.

The Problem

SMBs face a $10K-$50K cost for ESG reports, struggle with complex regulations across jurisdictions, and lack in-house expertise. Manual compliance is time-consuming and error-prone.

The Solution

An autonomous AI agent system that:

  • 🔍 Researches regulations via real-time web search (Google Search grounding)
  • 📊 Collects ESG data from EPA, web scraping, and AI estimation
  • 🌍 Calculates emissions using Climatiq API (Scope 1, 2, 3)
  • 📄 Generates reports in GRI, SASB, TCFD formats with iterative refinement
  • 💬 Answers questions via permission-aware RAG (Retrieval-Augmented Generation)

All secured by Auth0 - every agent action is authenticated, authorized, and audited.


Demo

🔗 GitHub Repository

github.com/omkardongre/ESG-Copilot

🔗 Live Demo

https://esg-copilot.vercel.app/

📸 Screenshots

Homepage

Company Dashboard

Regulation Research Agent

ESG Data Collection Agent

Emissions Calculator Agent

Report Generator Agent

Chat Agent (RAG)

Generated Report

Auth0 Users

Token Vault in Action

Auth0 FGA Store

▶️ Try It Yourself

Test User Accounts (Password: Test@1234):

Email Role Company Agent Access Document Access Chat Context
patagonia@company.com Company Admin Patagonia Inc All 5 agents Own company only Patagonia docs
tesla@company.com Company Admin Tesla Inc All 5 agents Own company only Tesla docs
consultant@esgfirm.com ESG Consultant N/A All 5 agents All companies All docs
auditor@sustainapilot.com Auditor N/A Read-only All companies All docs (read-only)
regulator@epa.gov Regulator N/A Read-only All companies All docs (read-only)

Try Different Scenarios:

  1. Login as Patagonia Admin → Execute agents, see only Patagonia data
  2. Login as Tesla Admin → Execute agents, see only Tesla data (zero data leakage)
  3. Login as ESG Consultant → Execute agents for any company, see all data
  4. Login as Auditor → Read-only access, cannot execute agents
  5. Login as Regulator → Read-only access, view all companies for compliance oversight

📋 Complete Access Rules Matrix

Agent Execution Permissions:

Agent Company Admin ESG Consultant Auditor Regulator
Regulation Research ✅ Own company ✅ Any company
ESG Data Collection ✅ Own company ✅ Any company
Emissions Calculator ✅ Own company ✅ Any company
Report Generator ✅ Own company ✅ Any company
Chat Agent (RAG) ✅ Own docs ✅ All docs ✅ All docs ✅ All docs

Document Access Control:

Document Type Company Admin ESG Consultant Auditor Regulator
Own Company ESG Data ✅ Read/Write ✅ Read/Write ✅ Read-only ✅ Read-only
Other Company ESG Data ❌ No access ✅ Read/Write ✅ Read-only ✅ Read-only
Compliance Reports ✅ Own company ✅ All companies ✅ All companies ✅ All companies
Audit Logs ✅ Own company ✅ All companies ✅ All companies ✅ All companies

Token Vault API Key Distribution:

API Key Company Admin ESG Consultant Auditor Regulator
Climatiq (Emissions)
Pinecone (RAG)
SendGrid (Email)

Example Scenarios:

  1. Cross-Company Privacy:
  • Patagonia Admin asks chat: "Show me Nike's emissions data"
  • AI Response: "No relevant documents found" (FGA blocks access)
  • Audit: Query logged but no Nike documents accessed
  1. Role-Based Agent Restrictions:
  • Auditor tries to execute "Calculate Emissions" agent
  • Result: 403 Forbidden (no execute:agents permission)
  • Audit: Attempt logged with failure reason
  1. Token Vault Security:
    • Auditor tries to access Climatiq API
    • Result: API key not in JWT (Token Vault blocks)
    • Audit: No API key injection for read-only roles

How I Used Auth0 for AI Agents

1. 🔐 Authenticate the User

Challenge Requirement: Secure the human prompting the agents

Implementation:

// frontend/src/app/api/auth/[auth0]/route.ts
import { handleAuth } from "@auth0/nextjs-auth0";

export const GET = handleAuth();
Enter fullscreen mode Exit fullscreen mode

Features:

  • ✅ Auth0 Universal Login (no custom auth code)
  • ✅ JWT tokens with user identity, roles, and permissions
  • ✅ 4 roles: Company Admin, ESG Consultant, Auditor, Regulator
  • ✅ 9 permissions: execute:agents, read:companies, write:reports, etc.
  • ✅ Every agent action tied to authenticated user

Why This Matters: Each AI agent execution is traceable to a specific user with specific permissions. No anonymous agent actions.


2. 🔑 Control the Tools

Challenge Requirement: Manage which APIs your agents can call

Implementation:

// Auth0 Action: Token Vault (Post-Login)
exports.onExecutePostLogin = async (event, api) => {
  const namespace = "https://esg-copilot.com";

  // Add email and roles to custom claims
  api.accessToken.setCustomClaim(`${namespace}/email`, event.user.email);
  api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization?.roles || []);

  // Check if user has agent execution permission
  const permissions = event.authorization?.permissions || [];
  const roles = event.authorization?.roles || [];

  const hasAccess =
    permissions.includes("execute:agents") ||
    roles.includes("ESG Consultant") ||
    roles.includes("Company Admin");

  if (hasAccess) {
    // Inject API keys into JWT from Auth0 Secrets
    const apiKeys = {
      climatiq_api_key: event.secrets.CLIMATIQ_API_KEY,
      sendgrid_api_key: event.secrets.SENDGRID_API_KEY,
      pinecone_api_key: event.secrets.PINECONE_API_KEY,
    };

    api.accessToken.setCustomClaim(`${namespace}/api_keys`, apiKeys);
  }

  // Add company_id for Company Admins
  api.accessToken.setCustomClaim(`${namespace}/company_id`, 
    event.user.user_metadata?.company_id || null);
};
Enter fullscreen mode Exit fullscreen mode

Backend Extraction & Usage:

// src/middleware/auth0.js - Extract from JWT
const extractUserInfo = (req, res, next) => {
  if (req.auth?.payload) {
    const apiKeys = req.auth.payload['https://esg-copilot.com/api_keys'] || {};

    req.user = {
      id: req.auth.payload.sub,
      email: req.auth.payload['https://esg-copilot.com/email'],
      roles: req.auth.payload['https://esg-copilot.com/roles'] || [],
      companyId: req.auth.payload['https://esg-copilot.com/company_id'],
      permissions: req.auth.payload.permissions || [],
      api_keys: apiKeys, // ✅ Available to all agents
    };
  }
  next();
};

// src/routes/chat.js - Agent retrieves keys from Token Vault
const apiKeys = req.user.api_keys || {};
const pineconeApiKey = apiKeys.pinecone_api_key;

if (!pineconeApiKey) {
  return res.status(400).json({
    error: 'Pinecone API key not found in Token Vault'
  });
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • ✅ 3 API keys secured in Token Vault (Climatiq, SendGrid, Pinecone)
  • ✅ Keys only injected for authorized users
  • ✅ No hardcoded credentials anywhere
  • ✅ Agents retrieve keys from JWT at runtime

Why This Matters: Agents can only call APIs if the user has permission. A Company Admin can calculate emissions, but an Auditor cannot.


3. 🎯 Limit Knowledge

Challenge Requirement: Ensure agents only access authorized data

Implementation:

// src/services/fga-store-service.js
const { OpenFgaClient } = require("@openfga/sdk");

class FGAStoreService {
  constructor() {
    this.client = new OpenFgaClient({
      apiUrl: process.env.FGA_API_URL,
      storeId: process.env.FGA_STORE_ID,
      credentials: {
        method: "client_credentials",
        config: {
          apiTokenIssuer: "auth.fga.dev",
          apiAudience: process.env.FGA_API_AUDIENCE,
          clientId: process.env.FGA_CLIENT_ID,
          clientSecret: process.env.FGA_CLIENT_SECRET,
        },
      },
    });
  }

  // Check if user can view a document
  async canViewDocument(userId, documentId) {
    const { allowed } = await this.client.check({
      user: `user:${userId}`,
      relation: "can_view",
      object: `document:${documentId}`,
    });

    return allowed;
  }
}
Enter fullscreen mode Exit fullscreen mode

Authorization Model (FGA Store):

type user

type company
  relations
    define admin: [user]
    define member: [user]
    define viewer: [user] or member or admin

type document
  relations
    define company: [company]
    define owner: [user]
    define viewer: [user] or owner or viewer from company
    define can_view: viewer
Enter fullscreen mode Exit fullscreen mode

RAG Pipeline with FGA:

// src/services/rag-service.js - Two-layer authorization
async queryWithFGAStore({ query, userId, userEmail, companyId, topK = 5 }) {
  // Step 1: Generate embedding
  const queryEmbedding = await this.embeddings.embedQuery(query);

  // Step 2: Query Pinecone with company filter (first layer)
  const results = await this.index.query({
    vector: queryEmbedding,
    topK: topK * 3, // Fetch more, then filter by FGA
    filter: { company_id: { $eq: companyId } },
    includeMetadata: true,
  });

  // Step 3: Filter by FGA Store authorization (second layer)
  const authorizedDocuments = [];

  for (const match of results.matches) {
    const documentId = match.metadata.document_id;

    // Real-time FGA check via Auth0 FGA Store API
    const canView = await fgaStoreService.canViewDocument(userEmail, documentId);

    if (canView) {
      authorizedDocuments.push(match);
    }
  }

  return authorizedDocuments.slice(0, topK);
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • ✅ Auth0 FGA Store for fine-grained authorization
  • ✅ Company-level data isolation (Pinecone filters)
  • ✅ Document-level access control (FGA checks)
  • ✅ Real-time authorization on every query
  • ✅ Zero knowledge leakage between companies

6 Authorization Rules:

  1. Company Admin: See only own company documents
  2. ESG Consultant: See all companies (global viewer)
  3. Auditor: Read-only access to all documents
  4. Regulator: Read-only access to all documents
  5. Document ownership: Creator is owner
  6. Company-document relationship: Documents belong to companies

Why This Matters: A Company Admin for Patagonia cannot see Nike's ESG data. The AI agent respects these boundaries automatically.


Technical Architecture

Tech Stack

Frontend:

  • Next.js 14 (App Router)
  • Auth0 Next.js SDK (@auth0/nextjs-auth0)
  • TailwindCSS

Backend:

  • Node.js + Express
  • Google Gemini 2.5 Flash (with Search grounding)
  • LangChain.js (RAG pipeline)

Data & Storage:

  • BigQuery (agent logs, ESG data, compliance requirements)
  • Pinecone (vector database for RAG)
  • Auth0 FGA Store (external authorization service)

External APIs (via Token Vault):

  • Climatiq API (carbon footprint calculations)
  • SendGrid API (email delivery)
  • Pinecone API (vector search)

Multi-Agent Architecture

5 Core Agents:

  1. Regulation Research Agent (3 sub-agents in parallel)
  • Jurisdiction Analyzer (web search)
  • Framework Mapper (GRI/SASB/TCFD)
  • Deadline Calculator (compliance dates)
  1. ESG Data Collection Agent (3 sub-agents in parallel)
  • EPA Data Collector (government data)
  • Web Scraper (company sustainability pages)
  • AI Estimator (industry benchmarks)
  1. Emissions Calculator Agent
  • Scope 1, 2, 3 emissions via Climatiq API
  • Activity data extraction from ESG metrics
  1. Report Generator Agent (4 sub-agents + iterative refinement)
  • GRI Writer, SASB Writer, TCFD Writer
  • Review & Critique Agent (up to 3 iterations)
  1. Chat Agent (RAG-based)
    • Permission-aware document retrieval
    • Company-scoped knowledge base
    • Real-time FGA authorization

Agentic Patterns:

  • ✅ Parallel fan-out/gather (regulation research)
  • ✅ Iterative refinement (report quality loop)
  • ✅ Multi-agent orchestration (service-level coordination)

Lessons Learned and Takeaways

🎓 Key Insights

1. Auth0 FGA Store is Production-Ready

  • External authorization service (not just role logic)
  • Real-time checks with low latency
  • Scales to millions of tuples
  • No need to build custom RBAC

2. Token Vault Simplifies Agent Security

  • API keys in JWT = no backend secret management
  • Permission-based key injection
  • Agents are stateless and secure

3. Multi-Agent Systems Need Orchestration

  • Service-level coordination > agent-to-agent messaging
  • Parallel execution for independent tasks
  • Sequential execution for dependent tasks

🚧 Challenges Faced

1. FGA Store Learning Curve

  • Understanding tuple relationships took time
  • Authorization model design is critical
  • Testing with FGA Query Tool was essential

2. RAG Authorization Performance

  • Initial approach: Check every document (slow)
  • Solution: Pinecone filters + FGA checks (fast)
  • Result: Smaller query time with 10+ documents

3. Agent Debugging

  • BigQuery audit trail provides complete action history
  • Structured logging helps identify agent execution flow

💡 Key Takeaways

For Developers:

  • Start with Auth0 Universal Login (don't build custom auth)
  • Use FGA Store for document-level permissions
  • Token Vault is perfect for AI agent API keys
  • Audit logging is non-negotiable for production

For AI Agent Builders:

  • Permission-aware RAG prevents data leakage
  • Multi-agent orchestration needs clear patterns
  • Real-time web search > static knowledge bases
  • Iterative refinement improves output quality

🎯 What I'm Proud Of

  • Agent API keys via Token Vault - Climatiq, SendGrid, Pinecone secured in JWT
  • Production-ready security - FGA Store, audit logs, JWT, environment variables
  • Real-world use case - solves actual SMB pain point
  • No dummy data - live web search, real APIs
  • 5 agents + 9 sub-agents - complex multi-agent system

Conclusion

ESG Copilot demonstrates how Auth0 for AI Agents enables production-ready AI systems with:

  • 🔐 User authentication (Universal Login + JWT with roles/permissions)
  • 🔑 Tool control (Token Vault for secure API key management)
  • 🎯 Knowledge limits (FGA Store + two-layer RAG authorization)

The result: An autonomous multi-agent AI system that SMBs can trust with sensitive ESG data, knowing every action is authenticated, authorized, and audited.

Key Numbers:

  • 5 core agents + 9 sub-agents
  • 4 roles with 9 permissions
  • 3 API keys secured via Token Vault
  • 2-layer authorization (Pinecone filters + FGA checks)

Try it yourself: GitHub Repository


🙏 Acknowledgments

Thanks to Auth0 and DEV Community for this challenge! Building with Auth0 for AI Agents transformed how I think about securing multi-agent systems. The combination of Token Vault and FGA Store makes production-ready AI security achievable without building custom infrastructure.

Top comments (0)