# Copper Tone Technologies - Audit Process Guide **Version:** 1.0.0 **Last Updated:** 2025-11-20 **Purpose:** Complete instructions for auditing the Copper Tone Technologies codebase --- ## Table of Contents 1. [Overview](#overview) 2. [Prerequisites](#prerequisites) 3. [Automated Security Scanning](#automated-security-scanning) 4. [Database Audit Process](#database-audit-process) 5. [Backend Services Audit Process](#backend-services-audit-process) 6. [Frontend Application Audit Process](#frontend-application-audit-process) 7. [Infrastructure & DevOps Audit Process](#infrastructure--devops-audit-process) 8. [Security Audit Process (OWASP Top 10)](#security-audit-process-owasp-top-10) 9. [Code Quality Analysis](#code-quality-analysis) 10. [Compliance Verification](#compliance-verification) 11. [Report Generation](#report-generation) 12. [Audit Checklist](#audit-checklist) --- ## Overview This document provides complete, step-by-step instructions for performing a comprehensive security and code quality audit of the Copper Tone Technologies platform. Follow these instructions sequentially to ensure no aspect of the codebase is overlooked. ### Audit Frequency - **Security Audit:** Every 3 months or after major changes - **Dependency Audit:** Monthly - **Code Quality Audit:** Quarterly - **Compliance Audit:** Annually or before major releases ### Time Estimates - **Full Comprehensive Audit:** 4-6 hours - **Security-Only Audit:** 2-3 hours - **Dependency Scan:** 15-30 minutes - **Code Quality Review:** 2-3 hours --- ## Prerequisites ### Required Tools - Podman or Docker (for containerized scans) - Git access to repository - Go 1.25+ (for local testing) - Node.js 20+ (for local testing) - Access to production environment variables (.env file) ### Required Access - Read access to all source code - Access to CI/CD pipelines - Access to production configuration (for comparison) - Database schema access ### Setup ```bash # Clone the repository cd /home/administrator/projects/coppertone.tech # Ensure you're on the latest version git checkout main git pull origin main # Create audit output directory mkdir -p docs/audits/$(date +%Y%m%d-%H%M%S) export AUDIT_DIR=docs/audits/$(date +%Y%m%d-%H%M%S) ``` --- ## Automated Security Scanning ### 1. NPM Dependency Audit (Frontend) **Purpose:** Scan all frontend JavaScript/TypeScript dependencies for known vulnerabilities. **Process:** ```bash # Navigate to frontend directory cd /home/administrator/projects/coppertone.tech/frontend # Run npm audit in container (recommended) podman run --rm -v .:/app:z -w /app node:20-alpine npm audit --json > $AUDIT_DIR/npm-audit.json # Or run locally npm audit --json > $AUDIT_DIR/npm-audit.json npm audit --production --json > $AUDIT_DIR/npm-audit-prod.json # Review results cat $AUDIT_DIR/npm-audit.json | jq '.vulnerabilities' ``` **What to Check:** - ✅ Total vulnerability count (should be 0) - ✅ Critical vulnerabilities (must be 0) - ✅ High vulnerabilities (should be 0) - ✅ Moderate vulnerabilities (review and assess) - ✅ Production vs. dev dependencies (production is priority) **Acceptance Criteria:** - Zero critical vulnerabilities - Zero high vulnerabilities - All moderate vulnerabilities documented with remediation plan **Documentation:** Record in audit report: - Total dependencies scanned - Vulnerability breakdown by severity - Any vulnerabilities found and their status - Upgrade recommendations --- ### 2. Go Module Verification (Backend) **Purpose:** Verify integrity of all Go dependencies and check for known vulnerabilities. **Process:** ```bash cd /home/administrator/projects/coppertone.tech # Verify all backend services for service in auth-service work-management-service payment-service; do echo "=== Auditing $service ===" cd backend/functions/$service # Verify module checksums go mod verify > $AUDIT_DIR/go-verify-$service.txt 2>&1 # Tidy dependencies go mod tidy # Run static analysis go vet ./... > $AUDIT_DIR/go-vet-$service.txt 2>&1 # Check for vulnerabilities (requires govulncheck) go install golang.org/x/vuln/cmd/govulncheck@latest govulncheck ./... > $AUDIT_DIR/govulncheck-$service.txt 2>&1 cd ../../.. done ``` **What to Check:** - ✅ All modules verify successfully - ✅ No modified dependencies - ✅ No known CVEs in dependencies - ✅ go vet reports no issues - ✅ All dependencies are up-to-date **Key Dependencies to Verify:** - `golang.org/x/crypto` - Should be latest patch version - `github.com/golang-jwt/jwt` - Should be v5.2.1+ - `github.com/ethereum/go-ethereum` - Should be v1.14+ - `github.com/stripe/stripe-go` - Should be v81+ - `github.com/lib/pq` - PostgreSQL driver should be latest **Acceptance Criteria:** - All modules verify without errors - Zero known vulnerabilities - go vet passes cleanly **Documentation:** Record in audit report: - Module verification status for each service - Dependency versions - Any vulnerabilities found - Upgrade recommendations --- ### 3. Container Security Scan **Purpose:** Scan container images for vulnerabilities in base images and layers. **Process:** ```bash cd /home/administrator/projects/coppertone.tech # Install trivy if not already installed # See: https://aquasecurity.github.io/trivy/ # Build all container images podman-compose build # Scan each image for image in coppertone-frontend coppertone-auth-service coppertone-work-management-service coppertone-payment-service; do echo "=== Scanning $image ===" trivy image $image:latest --format json > $AUDIT_DIR/trivy-$image.json trivy image $image:latest --severity HIGH,CRITICAL done ``` **What to Check:** - ✅ Base image vulnerabilities - ✅ Installed package vulnerabilities - ✅ Critical CVEs (must be 0) - ✅ High severity issues - ✅ Outdated base images **Acceptance Criteria:** - Zero critical vulnerabilities - All high vulnerabilities documented - Base images are current versions **Documentation:** Record in audit report: - Images scanned - Vulnerabilities by severity - Base image versions - Remediation actions --- ### 4. Static Code Analysis (Optional) **Purpose:** Additional code quality and security analysis. **Process:** ```bash # Go static analysis with golangci-lint (if available) for service in auth-service work-management-service payment-service; do cd backend/functions/$service golangci-lint run --out-format json > $AUDIT_DIR/golangci-$service.json 2>&1 cd ../../.. done # Frontend linting cd frontend npm run lint > $AUDIT_DIR/eslint-report.txt 2>&1 npm run type-check > $AUDIT_DIR/typescript-check.txt 2>&1 ``` **Acceptance Criteria:** - Linter passes or documented exceptions - Type checking passes - No security-related warnings --- ## Database Audit Process ### Purpose Audit database schema, migrations, security, and data integrity. ### Files to Audit ```bash # List all migration files ls -la backend/migrations/ # Files to review: - 001_create_users_and_identities.up.sql - 001_create_users_and_identities.down.sql - 002_create_projects_and_tasks.up.sql - 002_create_projects_and_tasks.down.sql - 003_create_invoices_and_payments.up.sql - 003_create_invoices_and_payments.down.sql ``` ### Audit Checklist #### 1. SQL Injection Protection **Prompt:** Review all backend Go files for SQL queries. Verify EVERY query uses parameterized statements. **Process:** ```bash # Search for all database queries cd /home/administrator/projects/coppertone.tech grep -r "db.Query\|db.Exec\|db.QueryRow" backend/functions/*/main.go --color -A 2 # Check for string concatenation in queries (BAD) grep -r "fmt.Sprintf.*SELECT\|fmt.Sprintf.*INSERT\|fmt.Sprintf.*UPDATE\|fmt.Sprintf.*DELETE" backend/functions/ || echo "✅ No string concatenation in SQL" ``` **What to Look For:** - ❌ BAD: `db.Query("SELECT * FROM users WHERE id = " + userId)` - ❌ BAD: `db.Query(fmt.Sprintf("SELECT * FROM users WHERE id = %s", id))` - ✅ GOOD: `db.Query("SELECT * FROM users WHERE id = $1", userId)` **For Each Query Found:** 1. Verify it uses `$1, $2, $3...` placeholders (PostgreSQL) 2. Verify user input is passed as parameters, not concatenated 3. Check that the query cannot be manipulated by user input **Acceptance Criteria:** - 100% of queries use parameterized statements - Zero string concatenation in SQL queries - All user input properly escaped by database driver **Documentation Template:** ``` ### SQL Injection Audit Results **Files Audited:** - backend/functions/auth-service/main.go - backend/functions/work-management-service/main.go - backend/functions/payment-service/main.go **Total Queries Found:** [NUMBER] **Parameterized Queries:** [NUMBER] (should be 100%) **Vulnerable Queries:** [NUMBER] (should be 0) **Sample Secure Queries:** [Paste 2-3 examples] **Result:** ✅ PASS / ❌ FAIL ``` --- #### 2. Schema Security Review **Prompt:** Audit database schema for security best practices. **Process:** ```bash # Review each migration file for file in backend/migrations/*.up.sql; do echo "=== Auditing $file ===" cat "$file" done ``` **Checklist for Each Table:** **Users Table:** - [ ] Email field is nullable (supports blockchain-only users) - [ ] Email has UNIQUE constraint - [ ] Email index exists for performance - [ ] No plaintext passwords stored - [ ] created_at and updated_at timestamps present - [ ] Proper foreign key constraints **Identities Table:** - [ ] Supports multiple auth methods (email_password, blockchain_address, did) - [ ] credential field is TEXT (stores hashed passwords) - [ ] UNIQUE constraint on (type, identifier) - [ ] Foreign key to users with ON DELETE CASCADE - [ ] Indexes on user_id and (type, identifier) **User Roles Table:** - [ ] Role is ENUM type (prevents invalid roles) - [ ] UNIQUE constraint on (user_id, role) - [ ] Foreign key to users with ON DELETE CASCADE - [ ] Index on user_id **Projects/Tasks Tables:** - [ ] Foreign keys to users and clients - [ ] Status fields use ENUM or VARCHAR with constraints - [ ] IPFS CID fields for document storage - [ ] Proper indexes on frequently queried fields - [ ] ON DELETE rules appropriate (CASCADE, SET NULL, or RESTRICT) **Invoices/Payments Tables:** - [ ] Monetary amounts use NUMERIC(12,2) (not FLOAT) - [ ] Currency field present - [ ] Status tracking via ENUM - [ ] blockchain_tx_hash fields for crypto payments - [ ] ipfs_document_cid for immutable invoice storage - [ ] Proper foreign keys and indexes **General Security:** - [ ] No sensitive data in plain text - [ ] Proper data types (no VARCHAR for everything) - [ ] Constraints prevent invalid data - [ ] Indexes on all foreign keys - [ ] Triggers for automatic timestamp updates - [ ] No default passwords or test data in migrations **Acceptance Criteria:** - All tables follow normalization (3NF minimum) - All foreign keys have indexes - All sensitive data properly protected - Proper use of constraints and data types **Documentation Template:** ``` ### Database Schema Audit Results **Tables Audited:** [NUMBER] **Total Columns:** [NUMBER] **Foreign Keys:** [NUMBER] **Indexes:** [NUMBER] **Constraints:** [NUMBER] **Security Features:** - Password hashing: ✅ bcrypt in credential field - Email privacy: ✅ Nullable for blockchain-only users - Data integrity: ✅ Foreign keys with ON DELETE CASCADE - Financial precision: ✅ NUMERIC(12,2) for amounts - Audit trail: ✅ created_at/updated_at on all tables **Issues Found:** [LIST or "None"] **Result:** ✅ PASS / ❌ FAIL ``` --- #### 3. Database Connection Security **Prompt:** Verify database connections use secure settings. **Process:** ```bash # Check database connection strings in all services grep -r "sslmode" backend/functions/*/main.go grep -r "connStr" backend/functions/*/main.go -A 1 ``` **What to Check:** **Development vs. Production:** - ⚠️ `sslmode=disable` - Acceptable for local development - ✅ `sslmode=require` - Required for production - ✅ `sslmode=verify-full` - Best for production with certificate verification **Connection String Security:** ```go // Check for this pattern: connStr := fmt.Sprintf("user=%s password=%s dbname=%s host=%s sslmode=disable", ...) // For production, should be: connStr := fmt.Sprintf("user=%s password=%s dbname=%s host=%s sslmode=require", ...) ``` **Environment Variables:** - [ ] DB_USER from environment (not hardcoded) - [ ] DB_PASSWORD from environment (not hardcoded) - [ ] DB_NAME from environment - [ ] DB_HOST from environment - [ ] No credentials in source code - [ ] No credentials in git history **Acceptance Criteria:** - Development: sslmode can be disable - Production: Must use sslmode=require or verify-full - All credentials from environment variables - No plaintext passwords in code **Documentation Template:** ``` ### Database Connection Security Audit **Services Audited:** - auth-service: [sslmode setting] - work-management-service: [sslmode setting] - payment-service: [sslmode setting] **Environment Variable Usage:** - DB credentials: ✅ From environment / ❌ Hardcoded - SSL setting: ✅ Configurable / ❌ Fixed **Production Readiness:** - Current setting: sslmode=[VALUE] - Required for production: sslmode=require - Action needed: [YES/NO] **Result:** ✅ PASS / ⚠️ NEEDS CONFIGURATION ``` --- #### 4. Migration Safety Review **Prompt:** Verify migrations can be safely applied and rolled back. **Process:** ```bash # Check that every .up.sql has a corresponding .down.sql cd backend/migrations for up in *.up.sql; do down="${up/up.sql/down.sql}" if [ ! -f "$down" ]; then echo "❌ Missing down migration for $up" else echo "✅ $up has corresponding $down" fi done ``` **What to Check:** **For Each Migration Pair:** 1. `.up.sql` creates tables/columns 2. `.down.sql` drops tables/columns in reverse order 3. Down migration properly handles dependencies (foreign keys first) 4. No data loss in down migrations (or documented) **Migration Naming:** - [ ] Sequential numbering (001, 002, 003) - [ ] Descriptive names - [ ] Timestamp or version included **Migration Content:** - [ ] `CREATE TABLE IF NOT EXISTS` (idempotent) - [ ] Proper DROP order in down migrations - [ ] No DROP CASCADE unless intentional - [ ] Comments explaining complex migrations **Acceptance Criteria:** - Every up migration has a down migration - Migrations are idempotent where possible - Down migrations properly reverse changes - No data loss without documentation **Documentation Template:** ``` ### Database Migration Audit **Total Migrations:** [NUMBER] **Up Migrations:** [NUMBER] **Down Migrations:** [NUMBER] **Migration Pairs Complete:** ✅ YES / ❌ NO **Migration Files:** 1. 001_create_users_and_identities (✅ up/down pair) 2. 002_create_projects_and_tasks (✅ up/down pair) 3. 003_create_invoices_and_payments (✅ up/down pair) **Safety Features:** - IF NOT EXISTS checks: ✅ Present - Proper DROP order: ✅ Verified - Foreign key handling: ✅ Correct - Rollback safety: ✅ Safe **Result:** ✅ PASS / ❌ FAIL ``` --- ## Backend Services Audit Process ### Purpose Audit all Go microservices for security, code quality, and best practices. ### Services to Audit 1. Auth Service (`backend/functions/auth-service/main.go`) 2. Work Management Service (`backend/functions/work-management-service/main.go`) 3. Payment Service (`backend/functions/payment-service/main.go`) 4. IPFS Client (if applicable) --- ### 1. Authentication & Authorization Audit **Prompt:** Verify all authentication mechanisms are secure and properly implemented. **Process:** #### Auth Service Specific Checks ```bash cd /home/administrator/projects/coppertone.tech/backend/functions/auth-service grep -n "bcrypt\|jwt\|ethereum" main.go ``` **Password Hashing:** ```bash # Find password hashing implementation grep -A 10 "GenerateFromPassword\|CompareHashAndPassword" main.go ``` **Check:** - [ ] Uses bcrypt (not MD5, SHA1, or plain) - [ ] bcrypt cost is 10 or higher - [ ] Passwords never logged or returned in responses - [ ] Password comparison uses constant-time comparison (bcrypt.CompareHashAndPassword) **Example Secure Implementation:** ```go // ✅ GOOD passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) // Check cost const cost = 10 // Should be >= 10 ``` **JWT Token Security:** ```bash # Find JWT implementation grep -A 20 "jwt.New\|jwt.Sign\|jwt.Parse" main.go ``` **Check:** - [ ] JWT secret from environment variable (not hardcoded) - [ ] JWT secret is at least 32 characters (preferably 64+) - [ ] Token expiration time set (not indefinite) - [ ] Signing algorithm is HS256, RS256, or ES256 (not "none") - [ ] Claims include user ID, roles, and expiration - [ ] Token validation on protected routes **Example Secure Implementation:** ```go // ✅ GOOD - Secret from environment jwtSecret := []byte(os.Getenv("JWT_SECRET")) if len(jwtSecret) == 0 { log.Fatal("JWT_SECRET must be set") } // ✅ GOOD - Token with expiration token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "user_id": user.ID, "exp": time.Now().Add(24 * time.Hour).Unix(), "roles": roles, }) ``` **Blockchain Authentication:** ```bash # Find Ethereum signature verification grep -A 15 "verifyEthereumSignature\|crypto.Ecrecover" main.go ``` **Check:** - [ ] Uses official go-ethereum library - [ ] Signature verification before authentication - [ ] Address normalization (lowercase) - [ ] Message signing prevents replay attacks - [ ] Nonce or timestamp included in signed message **Acceptance Criteria:** - Passwords hashed with bcrypt cost >= 10 - JWT secret from environment, 64+ characters - Token expiration implemented - Ethereum signatures properly verified - No authentication bypass vulnerabilities **Documentation Template:** ``` ### Authentication Audit Results **Password Security:** - Hashing algorithm: bcrypt - Cost factor: [NUMBER] - Constant-time comparison: ✅ YES / ❌ NO **JWT Security:** - Secret source: ✅ Environment variable / ❌ Hardcoded - Secret length: [NUMBER] characters - Expiration: ✅ Implemented / ❌ Missing - Signing algorithm: [ALGORITHM] **Blockchain Authentication:** - Library: go-ethereum v[VERSION] - Signature verification: ✅ Implemented / ❌ Missing - Replay protection: ✅ YES / ❌ NO **Issues Found:** [LIST or "None"] **Result:** ✅ PASS / ❌ FAIL ``` --- #### RBAC (Role-Based Access Control) Audit **Prompt:** Verify role-based access control is properly enforced. **Process:** ```bash # Find RBAC middleware grep -A 20 "requireRole\|checkRole" backend/functions/*/main.go ``` **What to Check:** **Role Definition:** - [ ] Roles defined as ENUM in database or constants in code - [ ] Valid roles: ADMIN, STAFF, CLIENT (or similar) - [ ] No hardcoded role checks scattered throughout code - [ ] Centralized role validation **Middleware Implementation:** ```go // Example pattern to find: func requireRole(handler http.HandlerFunc, allowedRoles ...string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Extract user from context // Check if user has required role // Allow or deny access } } ``` **Check:** - [ ] Role verification happens in middleware (not in handlers) - [ ] User roles extracted from JWT claims - [ ] Default deny (if no role matches, deny access) - [ ] All protected endpoints use requireRole middleware **Protected Endpoints:** ```bash # Find all protected routes grep -n "http.HandleFunc\|http.Handle" backend/functions/*/main.go ``` **For Each Endpoint, Verify:** - Public endpoints (register, login, healthz): No authentication needed - Protected endpoints: Wrapped with authenticate() middleware - Admin endpoints: Wrapped with requireRole("ADMIN") - Client endpoints: Wrapped with requireRole("CLIENT", "STAFF", "ADMIN") **Example Secure Implementation:** ```go // ✅ GOOD - Protected with RBAC http.HandleFunc("/admin/users", authenticate(requireRole(handleAdminUsers, "ADMIN"))) http.HandleFunc("/projects", authenticate(requireRole(handleProjects, "CLIENT", "STAFF", "ADMIN"))) // ✅ GOOD - Public endpoint http.HandleFunc("/register", handleRegister) http.HandleFunc("/healthz", handleHealth) ``` **Acceptance Criteria:** - All protected endpoints wrapped with authentication - Admin endpoints require ADMIN role - RBAC enforced via middleware (not scattered checks) - Default deny policy **Documentation Template:** ``` ### RBAC Audit Results **Services Audited:** - auth-service: [NUMBER] endpoints - work-management-service: [NUMBER] endpoints - payment-service: [NUMBER] endpoints **Endpoint Classification:** - Public endpoints: [NUMBER] - Authenticated endpoints: [NUMBER] - Role-protected endpoints: [NUMBER] **RBAC Implementation:** - Middleware-based: ✅ YES / ❌ NO - Centralized validation: ✅ YES / ❌ NO - Default deny: ✅ YES / ❌ NO **Sample Protected Endpoints:** [List 3-5 examples with their required roles] **Issues Found:** [LIST or "None"] **Result:** ✅ PASS / ❌ FAIL ``` --- ### 2. Input Validation Audit **Prompt:** Verify all user input is validated before use. **Process:** ```bash # Find all HTTP handlers grep -n "func handle" backend/functions/*/main.go # For each handler, check for input validation ``` **What to Validate:** **Email Addresses:** - [ ] Format validation (regex or library) - [ ] Length limits (max 255 characters) - [ ] Normalization (lowercase) - [ ] No SQL injection characters if used in queries **Passwords:** - [ ] Minimum length (recommend 8+ characters) - [ ] Maximum length (prevent DOS, recommend 100) - [ ] No whitespace-only passwords - [ ] Complexity requirements (optional but recommended) **User Names:** - [ ] Length limits - [ ] Allowed characters (alphanumeric, spaces, hyphens) - [ ] XSS prevention (though Vue handles this) **Numeric IDs:** - [ ] Type validation (int, not string) - [ ] Range validation (positive numbers) - [ ] No negative IDs **Blockchain Addresses:** - [ ] Format validation (0x + 40 hex characters) - [ ] Checksum validation - [ ] Normalization (lowercase) **Amounts/Currency:** - [ ] Positive numbers only (or explicit negative handling) - [ ] Maximum amount limits - [ ] Decimal precision (2 digits for currency) **Example Validation Patterns:** ```go // ✅ GOOD - Email validation if req.Email == "" { http.Error(w, "Email is required", http.StatusBadRequest) return } if len(req.Email) > 255 { http.Error(w, "Email too long", http.StatusBadRequest) return } // ✅ GOOD - Password validation if len(req.Password) < 8 { http.Error(w, "Password must be at least 8 characters", http.StatusBadRequest) return } // ✅ GOOD - Role validation validRoles := map[string]bool{"ADMIN": true, "STAFF": true, "CLIENT": true} if !validRoles[req.Role] { http.Error(w, "Invalid role", http.StatusBadRequest) return } // ✅ GOOD - Amount validation if req.Amount <= 0 { http.Error(w, "Amount must be positive", http.StatusBadRequest) return } ``` **Acceptance Criteria:** - All user input validated before use - Appropriate error messages (not exposing internal details) - Length limits on all string inputs - Type validation on all inputs - No unvalidated input reaches database **Documentation Template:** ``` ### Input Validation Audit Results **Handlers Audited:** [NUMBER] **Validation Coverage:** - Email addresses: ✅ Validated / ❌ Missing - Passwords: ✅ Validated / ❌ Missing - Numeric IDs: ✅ Validated / ❌ Missing - Blockchain addresses: ✅ Validated / ❌ Missing - Amounts: ✅ Validated / ❌ Missing **Security Features:** - Length limits: ✅ Enforced / ❌ Missing - Type checking: ✅ Present / ❌ Missing - Range validation: ✅ Present / ❌ Missing - Enum validation: ✅ Present / ❌ Missing **Weaknesses Found:** [List any missing validations] **Result:** ✅ PASS / ❌ FAIL ``` --- ### 3. Error Handling & Logging Audit **Prompt:** Verify error handling doesn't leak sensitive information and logging is appropriate. **Process:** ```bash # Find error handling patterns grep -n "http.Error\|log.Print\|fmt.Print" backend/functions/*/main.go ``` **Error Handling Check:** **Client-Facing Errors (http.Error):** - [ ] Generic messages (not exposing stack traces) - [ ] No database error details exposed - [ ] No file system paths exposed - [ ] Appropriate status codes **Examples:** ```go // ❌ BAD - Exposes internal details http.Error(w, fmt.Sprintf("Database error: %v", err), 500) // ✅ GOOD - Generic message http.Error(w, "Internal server error", http.StatusInternalServerError) log.Printf("Database error in handleUsers: %v", err) // Server-side logging ``` **Server-Side Logging:** - [ ] Errors logged with context - [ ] No passwords or secrets in logs - [ ] No credit card numbers in logs - [ ] User IDs included for tracking - [ ] Timestamp included (automatic with log package) **Examples:** ```go // ✅ GOOD - Detailed server-side logging log.Printf("Failed to hash password for user %s: %v", email, err) log.Printf("Database connection failed: %v", err) log.Printf("JWT verification failed for token: %v", err) // ❌ BAD - Logging sensitive data log.Printf("User password: %s", password) // Never log passwords log.Printf("JWT secret: %s", jwtSecret) // Never log secrets ``` **Authentication Logging:** - [ ] Successful logins logged (user ID, timestamp) - [ ] Failed login attempts logged (email, IP, timestamp) - [ ] Account creation logged - [ ] Role changes logged **Acceptance Criteria:** - Client errors are generic and safe - Server logs provide debugging details - No sensitive data in logs - Authentication events logged **Documentation Template:** ``` ### Error Handling & Logging Audit **Error Handling:** - Generic client errors: ✅ YES / ❌ NO - Detailed server logs: ✅ YES / ❌ NO - Appropriate status codes: ✅ YES / ❌ NO **Logging Coverage:** - Authentication events: ✅ Logged / ❌ Missing - Database errors: ✅ Logged / ❌ Missing - Validation failures: ✅ Logged / ❌ Missing **Security:** - Passwords in logs: ❌ NO / ⚠️ YES (CRITICAL) - Secrets in logs: ❌ NO / ⚠️ YES (CRITICAL) - Stack traces to client: ❌ NO / ⚠️ YES (BAD) **Issues Found:** [LIST or "None"] **Result:** ✅ PASS / ❌ FAIL ``` --- ### 4. CORS Configuration Audit **Prompt:** Verify CORS is properly configured for security. **Process:** ```bash # Find CORS middleware grep -A 15 "corsMiddleware\|CORS\|Access-Control" backend/functions/*/main.go ``` **What to Check:** **CORS Headers:** ```go // Find this pattern: w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") ``` **Development vs. Production:** - ⚠️ `Access-Control-Allow-Origin: *` - OK for development - ✅ `Access-Control-Allow-Origin: https://coppertone.tech` - Required for production - ✅ Environment-based configuration **Security Checks:** - [ ] Origin validation (not wildcard in production) - [ ] Methods limited to necessary ones - [ ] Headers limited to necessary ones (Content-Type, Authorization) - [ ] Credentials handling if needed - [ ] Preflight (OPTIONS) requests handled **Example Secure Implementation:** ```go // ✅ GOOD - Environment-based CORS func corsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { allowedOrigin := os.Getenv("ALLOWED_ORIGIN") if allowedOrigin == "" { allowedOrigin = "*" // Development fallback } w.Header().Set("Access-Control-Allow-Origin", allowedOrigin) w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } next.ServeHTTP(w, r) }) } ``` **Acceptance Criteria:** - CORS middleware applied to all services - Wildcard origin acceptable for development only - Production should use specific origins - OPTIONS requests handled properly **Documentation Template:** ``` ### CORS Audit Results **Services Audited:** - auth-service: [CORS config] - work-management-service: [CORS config] - payment-service: [CORS config] **Current Configuration:** - Allow-Origin: [VALUE] - Allow-Methods: [LIST] - Allow-Headers: [LIST] - Allow-Credentials: [YES/NO] **Environment Awareness:** - Configurable via env: ✅ YES / ❌ NO - Production-ready: ✅ YES / ⚠️ NEEDS CONFIGURATION **Recommendations:** - Development: Current config OK - Production: [REQUIRED CHANGES] **Result:** ✅ PASS / ⚠️ NEEDS PRODUCTION CONFIG ``` --- ### 5. Third-Party Integration Audit **Prompt:** Audit integrations with external services (Stripe, IPFS, Ethereum). #### Stripe Integration (Payment Service) **Process:** ```bash cd backend/functions/payment-service grep -n "stripe\|STRIPE" main.go ``` **What to Check:** **API Key Security:** ```go // Find this pattern: stripeKey := os.Getenv("STRIPE_SECRET_KEY") stripe.Key = stripeKey ``` **Check:** - [ ] API key from environment (not hardcoded) - [ ] Using secret key (sk_), not publishable key (pk_) - [ ] Test vs. production keys appropriately used - [ ] API version explicitly set (recommended) **Webhook Security:** ```bash # Find webhook handler grep -A 20 "webhook\|Webhook" backend/functions/payment-service/main.go ``` **Check:** - [ ] Webhook signature verification implemented - [ ] Webhook secret from environment - [ ] Event type validation - [ ] Idempotency handling **Example Secure Implementation:** ```go // ✅ GOOD - Signature verification event, err := stripe.ConstructEvent(body, signature, webhookSecret) if err != nil { http.Error(w, "Invalid signature", http.StatusBadRequest) return } ``` **Payment Intent Security:** - [ ] Amount validation before creation - [ ] Currency validation - [ ] Idempotency keys used - [ ] Customer ID verified - [ ] Error handling for failed payments **Acceptance Criteria:** - API keys from environment - Webhook signatures verified - Proper error handling - Idempotency implemented #### IPFS Integration **Process:** ```bash grep -rn "ipfs\|IPFS\|CID" backend/functions/ ``` **Check:** - [ ] IPFS client configured via environment - [ ] CID validation before storage - [ ] Error handling for upload/download failures - [ ] No sensitive data uploaded without encryption - [ ] Gateway URL configurable #### Ethereum Integration (Auth Service) **Process:** ```bash cd backend/functions/auth-service grep -n "ethereum\|crypto.Ecrecover" main.go ``` **Check:** - [ ] Official go-ethereum library used - [ ] Signature verification implemented - [ ] Address validation - [ ] No private key storage or handling - [ ] Message signing for anti-replay **Documentation Template:** ``` ### Third-Party Integration Audit **Stripe:** - API key security: ✅ Environment variable / ❌ Hardcoded - Webhook verification: ✅ Implemented / ❌ Missing / ⚠️ Placeholder - Idempotency: ✅ Implemented / ❌ Missing - Error handling: ✅ Comprehensive / ❌ Missing **IPFS:** - Configuration: ✅ Environment-based / ❌ Hardcoded - CID validation: ✅ Present / ❌ Missing - Error handling: ✅ Present / ❌ Missing **Ethereum:** - Library: go-ethereum v[VERSION] - Signature verification: ✅ Implemented / ❌ Missing - Security: ✅ No private key handling / ⚠️ Check needed **Issues Found:** [LIST or "None"] **Result:** ✅ PASS / ❌ FAIL ``` --- ## Frontend Application Audit Process ### Purpose Audit Vue.js frontend for security, code quality, and best practices. ### Files to Audit - `frontend/src/stores/*.ts` (Pinia stores) - `frontend/src/views/*.vue` (View components) - `frontend/src/components/*.vue` (Reusable components) - `frontend/src/router/index.ts` (Router configuration) - `frontend/src/App.vue` (Root component) --- ### 1. XSS (Cross-Site Scripting) Prevention **Prompt:** Verify the frontend properly escapes user input and doesn't inject raw HTML. **Process:** ```bash cd /home/administrator/projects/coppertone.tech/frontend # Search for v-html (dangerous) grep -rn "v-html" src/ # Search for innerHTML (dangerous) grep -rn "innerHTML" src/ # Search for eval (dangerous) grep -rn "eval(" src/ ``` **What to Check:** **Vue Template Safety:** - [ ] No `v-html` usage (or justified and sanitized) - [ ] All user input rendered with `{{ }}` (automatic escaping) - [ ] No `innerHTML` manipulation - [ ] No `eval()` or `Function()` usage **Safe Patterns:** ```vue