Skip to content

feat: Implement Comprehensive Audit Logging System for B2B Compliance #217

Closed

Description

@larryro

Problem Statement

As a B2B commercial project, Tale needs comprehensive audit logging for:

  • SOC 2 Compliance: User activity tracking, access logs, change logs
  • GDPR Compliance: Right to access audit, data subject requests
  • Security: Detection of unauthorized changes, suspicious patterns
  • Operational: Troubleshooting who made what change when

Current State

  • NO dedicated audit logging exists in the codebase
  • TODO comments in member.ts:432 and member.ts:604: "Add audit log entry in a dedicated audit table"
  • Existing infrastructure available:
    • RLS system with user/organization context
    • Better Auth for authentication
    • Multi-tenancy (organization + team model)

Proposed Solution

Create a comprehensive audit logging system with:

  1. Dedicated auditLogs Convex table with proper indexing
  2. Reusable audit logging helper functions
  3. Integration with all critical mutations (92 total identified)
  4. Query/export API for compliance reporting
  5. Retention policy with archival strategy

Affected Components

  • convex/schema.ts - Add auditLogs table definition
  • convex/lib/audit/ - New audit logging helpers
  • convex/model/audit_logs/ - Validators and model functions
  • convex/audit_logs.ts - Public query/mutation API
  • convex/member.ts - Add audit logging to member mutations
  • convex/team_members.ts - Add audit logging
  • convex/integrations.ts - Add audit logging
  • convex/email_providers.ts - Add audit logging
  • convex/products.ts - Add audit logging
  • convex/customers.ts - Add audit logging
  • convex/documents.ts - Add audit logging
  • convex/vendors.ts - Add audit logging
  • convex/wf_definitions.ts - Add audit logging
  • convex/approvals.ts - Add audit logging
  • convex/crons.ts - Add retention job
  • Admin UI for viewing audit logs

Acceptance Criteria

  • auditLogs table created with proper schema and indexes
  • Audit logging helpers created with sensitive field redaction
  • All Priority 1 mutations (member management) have audit logging
  • All Priority 2 mutations (integrations) have audit logging
  • All Priority 3 mutations (business data CRUD) have audit logging
  • All Priority 4 mutations (workflows/approvals) have audit logging
  • Query API supports filtering by category, resourceType, actor, date range
  • Export functionality for CSV/JSON format
  • Admin UI for viewing audit logs
  • Retention policy implemented (90 days hot, 7 years archived)
  • SOC 2 compliance requirements met
  • GDPR compliance requirements met

🤖 Generated with Claude Code

Activity

  1. larryro commented on Jan 15, 2026

    @larryro
    ContributorAuthor

    Implementation Plan

    Phase 1: Foundation - Schema & Core Helpers

    1.1 Add auditLogs table to schema

    File: services/platform/convex/schema.ts

    auditLogs: defineTable({
      // Organization scope
      organizationId: v.string(),
    
      // Actor information
      actorId: v.string(),
      actorEmail: v.optional(v.string()),
      actorRole: v.optional(v.string()),
      actorType: v.union(
        v.literal('user'),
        v.literal('system'),
        v.literal('api'),
        v.literal('workflow'),
      ),
    
      // Action details
      action: v.string(),
      category: v.union(
        v.literal('auth'),
        v.literal('member'),
        v.literal('data'),
        v.literal('integration'),
        v.literal('workflow'),
        v.literal('security'),
        v.literal('admin'),
      ),
    
      // Resource identification
      resourceType: v.string(),
      resourceId: v.optional(v.string()),
      resourceName: v.optional(v.string()),
    
      // Change tracking
      previousState: v.optional(v.any()),
      newState: v.optional(v.any()),
      changedFields: v.optional(v.array(v.string())),
    
      // Context
      sessionId: v.optional(v.string()),
      ipAddress: v.optional(v.string()),
      userAgent: v.optional(v.string()),
      requestId: v.optional(v.string()),
    
      // Timestamp & status
      timestamp: v.number(),
      status: v.union(v.literal('success'), v.literal('failure'), v.literal('denied')),
      errorMessage: v.optional(v.string()),
      metadata: v.optional(v.any()),
    })
      .index('by_organizationId', ['organizationId'])
      .index('by_organizationId_and_timestamp', ['organizationId', 'timestamp'])
      .index('by_organizationId_and_category', ['organizationId', 'category'])
      .index('by_organizationId_and_actorId', ['organizationId', 'actorId'])
      .index('by_organizationId_and_resourceType', ['organizationId', 'resourceType'])
      .index('by_org_category_timestamp', ['organizationId', 'category', 'timestamp'])
      .index('by_org_resourceType_timestamp', ['organizationId', 'resourceType', 'timestamp'])
      .index('by_resourceType_and_resourceId', ['resourceType', 'resourceId']),

    1.2 Create audit logging helpers

    New files:

    • convex/lib/audit/create_audit_log.ts - Core logging function with sensitive field redaction
    • convex/lib/audit/audit_helpers.ts - Convenient wrappers for different operation types
    • convex/lib/audit/index.ts - Barrel export
    • convex/model/audit_logs/validators.ts - Validators for audit log types

    Key features:

    • Automatic sensitive field redaction (passwords, API keys, tokens)
    • Change detection (compute changedFields automatically)
    • Actor context extraction from RLS

    Phase 2: Add Audit Logging to Critical Mutations

    Priority 1: Member & Access Control (Most Critical)

    File Mutation Audit Action
    member.ts addMember add_member
    member.ts removeMember remove_member
    member.ts updateMemberRole update_role
    member.ts updateMemberDisplayName update_name
    team_members.ts addMember add_team_member
    team_members.ts removeMember remove_team_member

    Priority 2: Integration & Security Operations

    File Mutation Audit Action
    integrations.ts create create_integration
    integrations.ts update update_integration
    integrations.ts deleteIntegration delete_integration
    email_providers.ts create create_email_provider
    email_providers.ts deleteProvider delete_email_provider
    email_providers.ts storeOAuth2Tokens update_oauth_tokens

    Priority 3: Business Data CRUD

    File Mutation Audit Action
    products.ts createProductPublic, updateProduct, deleteProduct create, update, delete
    customers.ts updateCustomer, deleteCustomer, bulkCreateCustomers update, delete, bulk_create
    documents.ts createDocumentFromUpload, updateDocument, deleteDocument create, update, delete
    vendors.ts updateVendor, deleteVendor, bulkCreateVendors update, delete, bulk_create

    Priority 4: Workflow & Approvals

    File Mutation Audit Action
    wf_definitions.ts publishDraftPublic, deleteWorkflowPublic publish_workflow, delete_workflow
    approvals.ts updateApprovalStatusPublic, executeApprovedIntegrationOperation approve/reject, execute_integration_operation

    Phase 3: Query & Export API

    New file: convex/audit_logs.ts

    • getAuditLogs - Paginated logs with filtering (category, resourceType, actor, date range)
    • getResourceAuditTrail - Audit history for a specific resource
    • getActivitySummary - Dashboard statistics
    • exportAuditLogs - CSV/JSON export for compliance reporting

    Phase 4: Admin UI

    New files in: src/app/[locale]/(default)/settings/audit-logs/

    • page.tsx - Audit logs list page with filters
    • components/audit-log-table.tsx - Data table component
    • components/audit-log-filters.tsx - Filter controls
    • components/audit-log-detail-dialog.tsx - Detail view

    Phase 5: Retention & Archival

    Add scheduled job to crons.ts:

    • Archive logs older than 90 days to Convex file storage
    • Delete archived logs after successful export
    • Maintain 7-year retention for compliance

    Files to Modify

    File Changes
    convex/schema.ts Add auditLogs table definition
    convex/lib/audit/*.ts New audit logging helpers (3 files)
    convex/model/audit_logs/*.ts Validators and model functions (2 files)
    convex/audit_logs.ts Public query/mutation API
    convex/member.ts Add audit logging to 4 mutations
    convex/team_members.ts Add audit logging to 2 mutations
    convex/integrations.ts Add audit logging to 3 mutations
    convex/email_providers.ts Add audit logging to 3 mutations
    convex/products.ts Add audit logging to 3 mutations
    convex/customers.ts Add audit logging to 3 mutations
    convex/documents.ts Add audit logging to 3 mutations
    convex/vendors.ts Add audit logging to 3 mutations
    convex/wf_definitions.ts Add audit logging to 2 mutations
    convex/approvals.ts Add audit logging to 2 mutations
    convex/crons.ts Add retention scheduled job
    src/app/.../settings/audit-logs/*.tsx Admin UI (4 files)
    messages/en.json, messages/zh.json Add translations

    Potential Risks

    • Performance: High-frequency mutations could create many audit logs → Mitigation: Use async logging for bulk operations
    • Storage: Audit logs can grow large → Mitigation: Implement retention/archival policy
    • Sensitive data leakage: Accidentally logging passwords/tokens → Mitigation: Built-in sensitive field redaction

    Testing Strategy

    • Unit tests for audit log creation and sensitive field redaction
    • Integration tests for logging in member/integration mutations
    • Manual testing of query filters and pagination
    • Manual testing of CSV/JSON export
    • Build verification: turbo run build --filter=platform
    • Type check: turbo run typecheck --filter=platform

    Compliance Features

    Requirement Implementation
    SOC 2 Immutability No update/delete on auditLogs table
    SOC 2 Completeness Log both success AND failure
    SOC 2 Actor ID User ID, email, role captured
    SOC 2 Retention 7-year retention via archival
    GDPR Minimization Sensitive fields redacted
    GDPR Right to Access Export API for data subject requests
    GDPR Purpose Limitation Category field documents purpose

    🤖 Generated with Claude Code

  2. larryro commented on Jan 15, 2026

    @larryro
    ContributorAuthor

    Related to #190 (Add example on how to export audit logs) - This issue implements the comprehensive audit logging system that #190 will document export examples for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions