DEV Community

Cover image for SecureDoc AI Assistant - Intelligent Document Management with Auth0 for AI Agents
depa panjie purnama
depa panjie purnama Subscriber

Posted on

SecureDoc AI Assistant - Intelligent Document Management with Auth0 for AI Agents

This is a submission for the Auth0 for AI Agents Challenge

What I Built

SecureDoc AI Assistant is an intelligent document management system that demonstrates how Auth0 for AI Agents can secure AI-powered applications with fine-grained access control.

The Problem

Organizations struggle with a critical challenge: How do you let AI agents help employees find information while ensuring they only access documents they're authorized to see?

Traditional solutions either:

  • Give AI agents too much access (security risk)
  • Restrict AI too heavily (poor user experience)
  • Lack proper audit trails (compliance issues)

The Solution

SecureDoc AI Assistant solves this by implementing permission-aware AI agents that:

  • โœ… Authenticate users with Auth0
  • โœ… Filter documents based on role and department
  • โœ… Only retrieve authorized content for AI context
  • โœ… Track every action in a comprehensive audit trail

Demo

Live Demo

GitHub

๐Ÿ“ธ Screenshots

Landing Page - Clean, Professional Design
Landing Page

AI Chat with Source Citations
Ask questions and get answers from authorized documents only

  • Manager from Engineering department accessing Engineering-related information AI Chat with Source Citations 1
  • Employee from Marketing department accessing Engineering-related information AI Chat with Source Citations 2
  • Guest accessing Engineering-related information AI Chat with Source Citations 3

Role-Based Document Access
Different users see different documents based on their role

  • Role: Employee Role-Based Document Access 1
  • Role: Guest Role-Based Document Access 2

Department-Filtered Audit Trail
Track all AI agent actions with department-level filtering

  • Role: Admin Department-Filtered Audit Trail 1
  • Role: Manager Department-Filtered Audit Trail 3
  • Role: Employee Department-Filtered Audit Trail 2

Auth0 Users Configuration

  • User configuration Auth0 Users Configuration 1
  • Roles configuration Auth0 Users Configuration 2

๐ŸŽฎ Try It Yourself

Test Users (Password: Test1234!):

Email Role Department Documents Audit Chat
admin@company.com Admin All 7 (all) All logs Full access
john.smith@company.com Manager Engineering 3 Engineering logs Engineering docs
sarah.johnson@company.com Manager Marketing 2 Marketing logs Marketing docs
emily.wong@company.com Employee Engineering 3 โŒ Engineering docs
lisa.anderson@company.com Employee Marketing 2 โŒ Marketing docs
guest@company.com Guest - 0 โŒ No context

Try Different Scenarios:

  1. Login as Admin โ†’ See all 7 documents, all audit logs
  2. Login as Engineering Manager โ†’ See only engineering docs, only engineering audit logs
  3. Login as Marketing Manager โ†’ See only marketing docs, only marketing audit logs
  4. Login as Employee โ†’ See limited docs, no audit access
  5. Login as Guest โ†’ See no documents, no audit access

๐Ÿ“‹ Complete Access Rules Matrix

Document Access by Role & Department:

Document Department Admin Eng Manager Mkt Manager Eng Employee Mkt Employee Guest
Q4 Engineering Roadmap Engineering โœ… โœ… โŒ โœ… โŒ โŒ
API Documentation Engineering โœ… โœ… โŒ โœ… โŒ โŒ
Security Incident Plan Engineering โœ… โŒ โŒ โŒ โŒ โŒ
Marketing Campaign Strategy Marketing โœ… โŒ โœ… โŒ โœ… โŒ
Employee Handbook HR โœ… โœ… โœ… โœ… โœ… โŒ
Sales Playbook Sales โœ… โŒ โŒ โŒ โŒ โŒ
Financial Report Q3 Finance โœ… โŒ โŒ โŒ โŒ โŒ

Feature Access by Role:

Feature Admin Manager Employee Guest
View Documents All (7) Department (2-4) Limited (1-3) None (0)
AI Chat Full context Department context Limited context No context
Search Documents All docs Department docs Limited docs None
View Audit Logs All logs Department logs โŒ โŒ
Document Details โœ… โœ… โœ… โŒ

Audit Log Visibility:

Viewer Role Can See Logs From
Admin All users, all departments
Engineering Manager Only Engineering department users
Marketing Manager Only Marketing department users
Employee No access (403 Forbidden)
Guest No access (403 Forbidden)

Example Scenarios:

  1. Cross-Department Privacy:

    • Engineering Manager asks about "marketing budget"
    • AI Response: "No relevant documents found" (no access to Marketing docs)
    • Audit: Engineering Manager's query logged in Engineering logs only
  2. Role-Based Restrictions:

    • Employee asks about "financial report"
    • AI Response: "No access" (Finance docs are Manager+ only)
    • Audit: Employee's attempt logged but document not accessed
  3. Department Isolation:

    • Marketing Manager views audit logs
    • Sees: Marketing team activities only
    • Does NOT see: Engineering, Finance, or other department activities
  4. Guest Lockdown:

    • Guest user tries to access documents
    • Result: "No documents found"
    • Audit: Guest cannot view audit logs (403)

How I Used Auth0 for AI Agents

1. ๐Ÿ” User Authentication

Challenge Requirement: Authenticate the user - Secure the human who is prompting the agent

Implementation:

// Auth0 SDK integration with Next.js
import { getSession } from '@auth0/nextjs-auth0';

export async function getCurrentUser(): Promise<User | null> {
  const session = await getSession();
  if (!session?.user) return null;

  // Map Auth0 user to our role system
  return mapAuth0User(session.user);
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • โœ… Secure session management with encrypted cookies
  • โœ… Protected routes via middleware
  • โœ… Role-Based Access Control (RBAC) with 4 levels:
    • Admin: Full access to all documents
    • Manager: Department-level access + audit logs
    • Employee: Limited document access
    • Guest: No document access

Why This Matters:
Every AI query is tied to an authenticated user with specific permissions. The AI can only access what the user is authorized to see.


2. ๐Ÿ”‘ Token Vault

Challenge Requirement: Control the tools - Manage which APIs your agent can call

Implementation:

// Secure API key management
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;

export async function generateChatResponse(messages, context) {
  const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
    headers: {
      'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'meta-llama/llama-3.2-3b-instruct:free',
      messages: apiMessages
    })
  });
  return response.json();
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • โœ… Environment-based API key storage
  • โœ… No hardcoded credentials
  • โœ… Secure token management for AI service (OpenRouter)
  • โœ… Proper secret handling with .env.local

Why This Matters:
The AI agent's API credentials are managed securely, preventing unauthorized access to the AI service while enabling legitimate use.


3. ๐ŸŽฏ Fine-Grained RAG Authorization

Challenge Requirement: Limit knowledge - Apply fine-grained authorization to RAG pipelines

Implementation:

// Permission-aware RAG pipeline
export class RAGService {
  async initialize(user: User): Promise<void> {
    // Get ONLY documents the user can access
    const documents = this.documentService.getAll(user);

    // Generate embeddings only for authorized documents
    for (const doc of documents) {
      const chunks = this.chunkDocument(doc);
      for (const chunk of chunks) {
        const embedding = await this.generateEmbedding(chunk.content);
        this.chunks.set(chunk.id, { ...chunk, embedding });
      }
    }
  }

  async query(userQuery: string, user: User): Promise<DocumentReference[]> {
    // Search only through user's accessible documents
    const accessibleChunks = Array.from(this.chunks.values())
      .filter(chunk => {
        const document = this.documentService.getById(chunk.documentId, user);
        return document !== null; // Permission check!
      });

    return this.findSimilar(queryEmbedding, accessibleChunks);
  }
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • โœ… Documents filtered BEFORE embedding generation
  • โœ… RAG retrieval respects user permissions
  • โœ… Department-based document filtering
  • โœ… Role-based access levels
  • โœ… No data leakage between departments

Why This Matters:
The AI never sees documents the user isn't authorized to access. The RAG pipeline is permission-aware at every step, ensuring zero-knowledge of restricted content.


4. ๐Ÿ“Š Complete Audit Trail

Bonus Feature: Track all AI agent actions for compliance

Implementation:

// Audit logging with deduplication
export class AuditService {
  log(entry: AuditEntry): void {
    // Deduplicate identical actions within 2 seconds
    const dedupeKey = `${entry.userId}-${entry.action}-${entry.resourceType}`;
    if (this.recentEntries.get(dedupeKey) > Date.now() - 2000) {
      return; // Skip duplicate
    }

    this.logs.push({
      ...entry,
      id: generateId(),
      timestamp: new Date()
    });
  }
}

// Department-filtered audit access
if (user.role === UserRole.MANAGER) {
  logs = logs.filter(log => 
    log.metadata?.userDepartment === user.department
  );
}
Enter fullscreen mode Exit fullscreen mode

Features:

  • โœ… Logs every AI query with document sources
  • โœ… Tracks document access with user details
  • โœ… Department-filtered for managers
  • โœ… Deduplication prevents spam
  • โœ… User-friendly display (names, not IDs)

Technical Architecture

Tech Stack

  • Framework: Next.js 14 with TypeScript (App Router)
  • Authentication: Auth0 for AI Agents
  • AI Model: OpenRouter (Llama 3.2 3B Instruct - Free Tier)
  • Styling: Tailwind CSS with custom components

Key Features

1. Role-Based Access Control (RBAC)

export function canAccessDocument(user: User, document: Document): boolean {
  if (user.role === UserRole.ADMIN) return true;
  if (user.role === UserRole.GUEST) return false;

  if (!document.accessLevel.includes(user.role)) return false;
  if (document.department === Department.ALL) return true;

  return user.department === document.department;
}
Enter fullscreen mode Exit fullscreen mode

2. Permission-Aware RAG Pipeline

  • Documents chunked into 500-character segments
  • Hash-based embeddings (no API quota limits)
  • Cosine similarity search
  • Title matching boost for better relevance

3. Smart Audit Logging

  • Deduplication (no duplicate entries)
  • Department filtering for managers
  • User-friendly error messages
  • Metadata includes user names and departments

Lessons Learned and Takeaways

๐ŸŽ“ Key Insights

1. Security-First AI Design
The biggest lesson: AI agents need permission-aware data pipelines, not just API authentication.

It's not enough to authenticate the user - you must filter the AI's knowledge base based on user permissions. This required:

  • Implementing RBAC at the RAG level
  • Filtering documents before embedding generation
  • Permission checks at every data access point

2. The Power of Auth0 for AI Agents
Auth0's approach to AI agent security is brilliant:

  • User Authentication: Establishes who is prompting the agent
  • Token Vault: Manages AI service credentials securely
  • Fine-Grained Authorization: Enables permission-aware RAG

This three-layer approach ensures both the user AND the AI agent are properly secured.

3. RAG Authorization is Critical
Traditional RAG implementations often overlook permissions. I learned that:

  • Documents must be filtered BEFORE embedding
  • Query results must respect user access levels
  • Audit trails must track what the AI accessed

4. UX Matters for Security
Security features need good UX:

  • Clear error messages ("Access Restricted" vs "Error 403")
  • Visual feedback (clickable examples, hover states)
  • Intuitive navigation (bubble-style menu)
  • Markdown rendering for better readability

๐Ÿšง Challenges Faced

Challenge 1: Gemini API Quota Limits

  • Problem: Google Gemini free tier has strict embedding quotas
  • Solution: Switched to OpenRouter (Llama 3.2) with hash-based embeddings
  • Learning: Always have a fallback AI provider

Challenge 2: Guest Role Permissions

  • Problem: Guest users with department: ALL bypassed filters
  • Solution: Explicit role checks before department checks
  • Learning: Permission logic order matters!

Challenge 3: Duplicate Audit Entries

  • Problem: React's double-render caused duplicate logs
  • Solution: Deduplication with time-based tracking
  • Learning: In-memory state needs careful management

Challenge 4: Manager Audit Visibility

  • Problem: Managers couldn't see team activity
  • Solution: Department-filtered logs (not user-filtered)
  • Learning: Audit requirements vary by role

๐Ÿ’ก Key Takeaways

For Developers Building AI Agents:

  1. Implement Permission-Aware RAG

    • Filter data before AI sees it
    • Never trust the AI to enforce permissions
    • Audit what the AI accesses
  2. Use Auth0 for AI Agents Properly

    • Authenticate the human user
    • Manage AI service credentials securely
    • Apply fine-grained authorization to data
  3. Design for Compliance

    • Audit trails are not optional
    • Department filtering enables privacy
    • User-friendly logs aid investigations
  4. Test with Multiple Roles

    • Create test users for each role
    • Verify different access levels
    • Ensure no data leakage

๐ŸŽฏ What I'm Proud Of

  • Zero Data Leakage: Guests see 0 documents, employees see limited docs, managers see department docs
  • Smart Audit Trail: Deduplication, department filtering, user names (not IDs)
  • Professional UI: Minimalism design with perfect UX
  • Production-Ready: Proper error handling, markdown rendering, clickable examples

Conclusion

SecureDoc AI Assistant demonstrates that AI agents can be both powerful and secure.

By implementing Auth0 for AI Agents with permission-aware RAG, we created a system where:

  • Users get intelligent answers from AI
  • AI only accesses authorized documents
  • Every action is audited for compliance
  • Different roles have appropriate access levels

The future of AI agents is secure, permission-aware, and auditable.


๐Ÿ™ Acknowledgments

Built for the Auth0 AI Agents Challenge. Special thanks to the Auth0 team for creating such a comprehensive framework for securing AI agents!


Have questions about the implementation?
Drop a comment below!

Top comments (0)