Skip to main content

Security Controls Implementation

This guide provides comprehensive technical implementation guidance for security controls across multiple compliance frameworks including SOC 2, GDPR, ISO 13485, and FDA 21 CFR Part 11.

Access Control Implementationโ€‹

Multi-Factor Authentication (MFA)โ€‹

interface MFAConfig {
providers: ('totp' | 'sms' | 'email' | 'hardware')[];
requireForRoles: string[];
gracePeriod: number;
backupCodes: boolean;
}

class MFAService {
async enableMFA(userId: string, method: string): Promise<MFASetup> {
// Generate secret for TOTP
const secret = this.generateTOTPSecret();

// Store encrypted secret
await this.storeMFASecret(userId, secret, method);

// Generate QR code for setup
const qrCode = this.generateQRCode(secret, userId);

return {
secret,
qrCode,
backupCodes: this.generateBackupCodes(userId),
};
}

async verifyMFA(userId: string, token: string): Promise<boolean> {
const userMFA = await this.getUserMFA(userId);

// Verify TOTP token
if (userMFA.method === 'totp') {
return this.verifyTOTP(userMFA.secret, token);
}

// Verify backup code
if (this.isBackupCode(token)) {
return this.verifyBackupCode(userId, token);
}

return false;
}
}

Role-Based Access Control (RBAC)โ€‹

interface Permission {
resource: string;
action: string;
conditions?: Record<string, any>;
}

interface Role {
id: string;
name: string;
permissions: Permission[];
inherits?: string[];
}

class RBACService {
async checkPermission(
userId: string,
resource: string,
action: string
): Promise<boolean> {
const userRoles = await this.getUserRoles(userId);

for (const role of userRoles) {
const hasPermission = await this.roleHasPermission(
role,
resource,
action
);

if (hasPermission) {
return true;
}
}

return false;
}

async assignRole(userId: string, roleId: string): Promise<void> {
// Validate role exists
const role = await this.getRole(roleId);
if (!role) {
throw new Error(`Role ${roleId} not found`);
}

// Check for role conflicts
await this.validateRoleAssignment(userId, roleId);

// Assign role
await this.createUserRole(userId, roleId);

// Log assignment
await this.auditLog.log({
action: 'role_assigned',
userId,
roleId,
timestamp: new Date(),
});
}
}

Data Encryption Implementationโ€‹

Encryption at Restโ€‹

interface EncryptionConfig {
algorithm: 'AES-256-GCM';
keyRotationDays: number;
keyManagement: 'aws-kms' | 'azure-keyvault' | 'hashicorp-vault';
}

class DataEncryption {
async encryptSensitiveData(
data: any,
classification: string
): Promise<EncryptedData> {
// Get appropriate encryption key based on data classification
const key = await this.getEncryptionKey(classification);

// Encrypt data
const encrypted = await this.encrypt(JSON.stringify(data), key);

// Store metadata
return {
encryptedData: encrypted.data,
iv: encrypted.iv,
keyId: key.id,
algorithm: 'AES-256-GCM',
classification,
timestamp: new Date(),
};
}

async decryptSensitiveData(encryptedData: EncryptedData): Promise<any> {
// Get decryption key
const key = await this.getDecryptionKey(encryptedData.keyId);

// Decrypt data
const decrypted = await this.decrypt(
encryptedData.encryptedData,
key,
encryptedData.iv
);

// Log access
await this.auditLog.log({
action: 'data_decrypted',
keyId: encryptedData.keyId,
classification: encryptedData.classification,
timestamp: new Date(),
});

return JSON.parse(decrypted);
}
}

Encryption in Transitโ€‹

interface TLSConfig {
minVersion: '1.2' | '1.3';
cipherSuites: string[];
certificateValidation: boolean;
hsts: boolean;
}

class SecureTransport {
configureHTTPS(): express.Application {
const app = express();

// Force HTTPS
app.use((req, res, next) => {
if (!req.secure && req.get('x-forwarded-proto') !== 'https') {
return res.redirect(301, `https://${req.get('host')}${req.url}`);
}
next();
});

// Security headers
app.use(
helmet({
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https:'],
},
},
})
);

return app;
}
}

Audit Trail Implementationโ€‹

Comprehensive Loggingโ€‹

interface AuditEvent {
eventId: string;
timestamp: Date;
userId?: string;
sessionId?: string;
action: string;
resource: string;
outcome: 'success' | 'failure';
details: Record<string, any>;
ipAddress: string;
userAgent: string;
}

class AuditTrailService {
async logEvent(event: Partial<AuditEvent>): Promise<void> {
const auditEvent: AuditEvent = {
eventId: this.generateEventId(),
timestamp: new Date(),
...event,
ipAddress: event.ipAddress || this.getClientIP(),
userAgent: event.userAgent || this.getUserAgent(),
};

// Store in tamper-evident log
await this.storeAuditEvent(auditEvent);

// Real-time monitoring
await this.processRealTimeAlerts(auditEvent);
}

async searchAuditTrail(criteria: AuditSearchCriteria): Promise<AuditEvent[]> {
// Validate search permissions
await this.validateSearchPermissions(criteria.requesterId);

// Execute search with proper indexing
const results = await this.executeSearch(criteria);

// Log the search activity
await this.logEvent({
action: 'audit_search',
userId: criteria.requesterId,
details: { criteria },
outcome: 'success',
});

return results;
}
}

Network Security Implementationโ€‹

API Securityโ€‹

interface APISecurityConfig {
rateLimiting: {
windowMs: number;
maxRequests: number;
};
authentication: {
methods: ('jwt' | 'oauth2' | 'api-key')[];
tokenExpiry: number;
};
validation: {
requestValidation: boolean;
responseValidation: boolean;
};
}

class APISecurityMiddleware {
rateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP',
standardHeaders: true,
legacyHeaders: false,
});

authenticate = async (req: Request, res: Response, next: NextFunction) => {
try {
const token = this.extractToken(req);

if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}

const decoded = await this.verifyToken(token);
req.user = decoded;

// Log successful authentication
await this.auditLog.log({
action: 'api_authentication',
userId: decoded.sub,
outcome: 'success',
});

next();
} catch (error) {
// Log failed authentication
await this.auditLog.log({
action: 'api_authentication',
outcome: 'failure',
details: { error: error.message },
});

return res.status(401).json({ error: 'Invalid token' });
}
};

validateRequest = (schema: any) => {
return (req: Request, res: Response, next: NextFunction) => {
const validation = schema.validate(req.body);

if (validation.error) {
return res.status(400).json({
error: 'Validation failed',
details: validation.error.details,
});
}

next();
};
};
}

Monitoring and Alertingโ€‹

Security Event Monitoringโ€‹

interface SecurityAlert {
severity: 'low' | 'medium' | 'high' | 'critical';
type: string;
description: string;
source: string;
timestamp: Date;
metadata: Record<string, any>;
}

class SecurityMonitoring {
async processSecurityEvent(event: AuditEvent): Promise<void> {
// Analyze event for security implications
const threats = await this.analyzeThreat(event);

for (const threat of threats) {
if (threat.severity >= this.alertThreshold) {
await this.generateAlert({
severity: threat.severity,
type: threat.type,
description: threat.description,
source: event.resource,
timestamp: event.timestamp,
metadata: {
eventId: event.eventId,
userId: event.userId,
...threat.metadata,
},
});
}
}
}

async generateAlert(alert: SecurityAlert): Promise<void> {
// Store alert
await this.storeAlert(alert);

// Send notifications based on severity
if (alert.severity === 'critical') {
await this.sendImmediateNotification(alert);
}

// Update security dashboard
await this.updateDashboard(alert);

// Trigger automated response if configured
await this.triggerAutomatedResponse(alert);
}
}

Compliance Framework Mappingโ€‹

SOC 2 Controlsโ€‹

  • CC6.1: Access control implementation with MFA and RBAC
  • CC6.2: System access monitoring and logging
  • CC6.3: Network security and API protection
  • CC7.1: Security monitoring and incident detection

GDPR Requirementsโ€‹

  • Article 32: Security of processing through encryption and access controls
  • Article 25: Privacy by design in security architecture
  • Article 33: Breach detection and notification systems

ISO 13485 Requirementsโ€‹

  • 7.5.3: Control of documented information access
  • 8.2.1: Customer communication security
  • 8.5.1: Control of production security

FDA 21 CFR Part 11 Requirementsโ€‹

  • ยง11.10: System access controls and audit trails
  • ยง11.30: Open system security controls
  • ยง11.300: Electronic signature security

Implementation Checklistโ€‹

Phase 1: Foundationโ€‹

  • Implement basic authentication and authorization
  • Set up audit logging infrastructure
  • Configure network security basics
  • Establish encryption for sensitive data

Phase 2: Advanced Controlsโ€‹

  • Deploy multi-factor authentication
  • Implement role-based access control
  • Set up comprehensive monitoring
  • Configure automated alerting

Phase 3: Compliance Integrationโ€‹

  • Map controls to compliance requirements
  • Implement compliance-specific logging
  • Set up compliance reporting
  • Conduct security assessments

Phase 4: Continuous Improvementโ€‹

  • Regular security reviews
  • Control effectiveness testing
  • Incident response procedures
  • Security awareness training

This implementation guide provides the technical foundation for security controls across multiple compliance frameworks, ensuring comprehensive protection and regulatory compliance.