Skip to content

Authentication & SecurityΒΆ

Complete guide to authentication, authorization, and security features in the CyferWall Engage Backend.

πŸ” Authentication MethodsΒΆ

1. JWT Bearer TokensΒΆ

Primary authentication method for API access.

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Getting a JWT TokenΒΆ

// Login request
POST /auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "secure_password"
}

// Response
{
  "responseStatus": "SUCCESS",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "user_123",
    "email": "user@example.com",
    "role": "CUSTOMER"
  }
}

For browser-based applications.

Cookie: cyferwall-auth=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

3. API Key AuthenticationΒΆ

For server-to-server communication.

X-API-ID: your_app_id
X-API-GRANT: server_access

🌐 Social Authentication¢

Google Sign-InΒΆ

OAuth 2.0 integration with Google.

// Frontend: Google Sign-In button
import { GoogleAuth } from '@google-cloud/auth-library'

// Backend: Verify Google token
POST /auth/google
Content-Type: application/json

{
  "token": "google_id_token_here"
}

Apple Sign-InΒΆ

Sign in with Apple integration.

// Backend: Verify Apple token
POST /auth/apple
Content-Type: application/json

{
  "token": "apple_id_token_here",
  "user": {
    "name": "John Doe",
    "email": "john@example.com"
  }
}

πŸ‘₯ User Roles & PermissionsΒΆ

Role HierarchyΒΆ

SUPER_ADMIN
β”œβ”€β”€ ADMIN  
β”œβ”€β”€ STAFF
β”‚   β”œβ”€β”€ SENIOR_STAFF
β”‚   └── JUNIOR_STAFF
└── CUSTOMER
    β”œβ”€β”€ ENTERPRISE_CUSTOMER
    └── REGULAR_CUSTOMER

Permission MatrixΒΆ

Action Customer Staff Admin Super Admin
Create case βœ… βœ… βœ… βœ…
View own cases βœ… βœ… βœ… βœ…
View all cases ❌ βœ… βœ… βœ…
Escalate case βœ… βœ… βœ… βœ…
Cancel case βœ… βœ… βœ… βœ…
Assign cases ❌ βœ… βœ… βœ…
View metrics ❌ βœ… βœ… βœ…
System admin ❌ ❌ βœ… βœ…

πŸ›‘οΈ Security FeaturesΒΆ

1. Request ValidationΒΆ

All inputs are validated using Zod schemas.

// Example validation schema
const SupportCaseSchema = z.object({
  name: z.string().min(1).max(100),
  email: z.string().email(),
  customerType: z.enum(['INDIVIDUAL', 'STARTUP', 'ENTERPRISE']),
  urgency: z.enum(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']),
  message: z.string().min(10).max(5000)
})

2. Rate LimitingΒΆ

Prevent abuse with configurable rate limits.

// Rate limit configuration
const rateLimits = {
  general: '1000 requests per hour',
  caseCreation: '10 cases per hour per IP',
  statusCheck: '100 requests per hour per case',
  escalation: '5 escalations per hour per case'
}

3. CORS ConfigurationΒΆ

Secure cross-origin resource sharing.

const corsConfig = {
  origin: [
    'https://cyferwall.com',
    'https://*.cyferwall.com',
    'http://localhost:3000' // Development only
  ],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Authorization', 'Content-Type'],
  credentials: true
}

4. Input SanitizationΒΆ

All user inputs are sanitized to prevent XSS and injection attacks.

// Automatic sanitization
const sanitizedInput = sanitize(userInput, {
  allowedTags: [],
  allowedAttributes: {}
})

πŸ”’ Endpoint SecurityΒΆ

Public EndpointsΒΆ

No authentication required.

// Health check
GET / 

// Create support case (allows non-authenticated users)
POST /common/support/case

Protected EndpointsΒΆ

Require valid authentication.

// System metrics (staff only)
GET /metrics

// Internal statistics (staff only) 
GET /common/support/internal/stats

Role-Based EndpointsΒΆ

Require specific user roles.

// Admin only endpoints
GET /admin/users
POST /admin/system/config

// Staff only endpoints
GET /staff/dashboard
POST /staff/case/assign

🚨 Security Monitoring¢

Audit LoggingΒΆ

All security-relevant events are logged.

{
  "timestamp": "2025-01-23T15:30:00Z",
  "event": "AUTH_FAILURE",
  "ip": "192.168.1.100",
  "userAgent": "Mozilla/5.0...",
  "endpoint": "/auth/login",
  "reason": "Invalid credentials"
}

Suspicious Activity DetectionΒΆ

  • Multiple failed login attempts
  • Unusual API usage patterns
  • High-frequency requests from single IP
  • Access to unauthorized resources

DataDog IntegrationΒΆ

Security metrics and alerting through DataDog APM.

// Example security metric
dd.increment('auth.login_failure', 1, {
  ip: request.ip,
  endpoint: request.path,
  reason: 'invalid_credentials'
})

πŸ› οΈ Security Best PracticesΒΆ

For API ConsumersΒΆ

  1. Store tokens securely

    // βœ… Good: Secure storage
    localStorage.setItem('token', encryptedToken)
    
    // ❌ Bad: Plain text storage
    localStorage.setItem('token', plainTextToken)
    

  2. Use HTTPS only

    // βœ… Good: Secure connection
    const api = axios.create({
      baseURL: 'https://api.cyferwall.com'
    })
    

  3. Implement token refresh

    // Token refresh logic
    if (isTokenExpired(token)) {
      token = await refreshToken()
    }
    

  4. Handle auth errors gracefully

    api.interceptors.response.use(
      response => response,
      error => {
        if (error.response?.status === 401) {
          redirectToLogin()
        }
        return Promise.reject(error)
      }
    )
    

For Backend IntegrationΒΆ

  1. Validate all inputs
  2. Use parameterized queries
  3. Implement proper error handling
  4. Log security events
  5. Regular security audits

πŸ”„ Token ManagementΒΆ

Token LifecycleΒΆ

graph LR
    A[User Login] --> B[Generate JWT]
    B --> C[Token Issued]
    C --> D[Token Used]
    D --> E{Token Valid?}
    E -->|Yes| F[Request Processed]
    E -->|No| G[Auth Error]
    F --> D
    G --> H[Refresh Token]
    H --> B

Token ExpirationΒΆ

  • Access tokens: 1 hour
  • Refresh tokens: 30 days
  • API keys: No expiration (revocable)

Token RefreshΒΆ

POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "refresh_token_here"
}

// Response
{
  "responseStatus": "SUCCESS",
  "accessToken": "new_access_token",
  "refreshToken": "new_refresh_token"
}

🚨 Security Incidents¢

Incident ResponseΒΆ

  1. Detection - Automated monitoring alerts
  2. Assessment - Severity and impact analysis
  3. Containment - Immediate threat mitigation
  4. Investigation - Root cause analysis
  5. Recovery - System restoration
  6. Lessons Learned - Process improvement

Contact InformationΒΆ

πŸ“‹ ComplianceΒΆ

StandardsΒΆ

  • GDPR - EU data protection compliance
  • CCPA - California privacy compliance
  • SOC 2 - Security and availability controls
  • ISO 27001 - Information security management

Data ProtectionΒΆ

  • Encryption at rest and in transit
  • Regular security assessments
  • Data minimization principles
  • User consent management

πŸ§ͺ Security TestingΒΆ

Automated Security TestsΒΆ

# Run security test suite
npm run test:security

# Check for vulnerabilities
npm audit

# OWASP ZAP scan
npm run security:zap

Manual TestingΒΆ

  • Penetration testing (quarterly)
  • Code security reviews
  • Dependency vulnerability scans
  • Authentication bypass testing

πŸ”’ Security is everyone's responsibility. Report security issues immediately to security@cyferwall.com