Integration Security Guide
This guide covers security best practices, authentication methods, and data protection strategies for integrating with Supernal Coding's compliance platform.
Security Overview
Security is paramount when integrating compliance systems. This guide covers:
- Authentication and authorization
- Data encryption and protection
- Secure communication protocols
- Audit logging and monitoring
- Threat detection and response
Authentication Methods
API Key Authentication
# Standard API key authentication
curl -H "Authorization: Bearer sk_live_1234567890abcdef" \
https://api.supernal-coding.com/v1/requirements
OAuth 2.0 Integration
import { OAuth2Client } from '@supernal-coding/oauth2';
const oauth2Client = new OAuth2Client({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://yourapp.com/callback',
scopes: ['read:requirements', 'write:requirements'],
});
// Authorization URL
const authUrl = oauth2Client.getAuthorizationUrl();
// Exchange code for token
const tokens = await oauth2Client.exchangeCodeForTokens(authCode);
JWT Token Validation
import jwt from 'jsonwebtoken';
function validateJWT(token: string): JWTPayload {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
return decoded as JWTPayload;
} catch (error) {
throw new Error('Invalid JWT token');
}
}
// Middleware for Express.js
function authenticateJWT(req: Request, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
try {
const user = validateJWT(token);
req.user = user;
next();
} catch (error) {
return res.status(403).json({ error: 'Invalid or expired token' });
}
}
Data Encryption
Encryption at Rest
import crypto from 'crypto';
class DataEncryption {
private algorithm = 'aes-256-gcm';
private keyDerivation = 'pbkdf2';
encrypt(data: string, password: string): EncryptedData {
const salt = crypto.randomBytes(16);
const iv = crypto.randomBytes(16);
// Derive key from password
const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
// Encrypt data
const cipher = crypto.createCipher(this.algorithm, key, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return {
encrypted,
salt: salt.toString('hex'),
iv: iv.toString('hex'),
authTag: authTag.toString('hex'),
algorithm: this.algorithm,
};
}
decrypt(encryptedData: EncryptedData, password: string): string {
const salt = Buffer.from(encryptedData.salt, 'hex');
const iv = Buffer.from(encryptedData.iv, 'hex');
const authTag = Buffer.from(encryptedData.authTag, 'hex');
// Derive key from password
const key = crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
// Decrypt data
const decipher = crypto.createDecipher(this.algorithm, key, iv);
decipher.setAuthTag(authTag);
let decrypted = decipher.update(encryptedData.encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
}
Encryption in Transit
// TLS/SSL configuration for HTTPS
const httpsOptions = {
key: fs.readFileSync('path/to/private-key.pem'),
cert: fs.readFileSync('path/to/certificate.pem'),
ca: fs.readFileSync('path/to/ca-certificate.pem'),
// Enforce strong cipher suites
ciphers: [
'ECDHE-RSA-AES128-GCM-SHA256',
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES128-SHA256',
'ECDHE-RSA-AES256-SHA384',
].join(':'),
honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method',
};
const server = https.createServer(httpsOptions, app);
Secure Communication
Certificate Pinning
import https from 'https';
import crypto from 'crypto';
class SecureAPIClient {
private expectedFingerprint: string;
constructor(expectedFingerprint: string) {
this.expectedFingerprint = expectedFingerprint;
}
async makeSecureRequest(
url: string,
options: RequestOptions
): Promise<Response> {
return new Promise((resolve, reject) => {
const req = https.request(
url,
{
...options,
checkServerIdentity: (hostname, cert) => {
const fingerprint = crypto
.createHash('sha256')
.update(cert.raw)
.digest('hex');
if (fingerprint !== this.expectedFingerprint) {
throw new Error('Certificate fingerprint mismatch');
}
return undefined; // Certificate is valid
},
},
(res) => {
// Handle response
resolve(res);
}
);
req.on('error', reject);
req.end();
});
}
}
Request Signing
import crypto from 'crypto';
class RequestSigner {
private secretKey: string;
constructor(secretKey: string) {
this.secretKey = secretKey;
}
signRequest(
method: string,
url: string,
body: string,
timestamp: number
): string {
const message = `${method}\n${url}\n${body}\n${timestamp}`;
return crypto
.createHmac('sha256', this.secretKey)
.update(message)
.digest('hex');
}
verifySignature(
signature: string,
method: string,
url: string,
body: string,
timestamp: number
): boolean {
const expectedSignature = this.signRequest(method, url, body, timestamp);
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedSignature, 'hex')
);
}
}
// Express middleware for signature verification
function verifySignature(req: Request, res: Response, next: NextFunction) {
const signature = req.headers['x-signature'] as string;
const timestamp = parseInt(req.headers['x-timestamp'] as string);
if (!signature || !timestamp) {
return res.status(400).json({ error: 'Missing signature or timestamp' });
}
// Check timestamp to prevent replay attacks
const now = Date.now();
if (Math.abs(now - timestamp) > 300000) {
// 5 minutes
return res.status(400).json({ error: 'Request timestamp too old' });
}
const signer = new RequestSigner(process.env.WEBHOOK_SECRET!);
const isValid = signer.verifySignature(
signature,
req.method,
req.url,
JSON.stringify(req.body),
timestamp
);
if (!isValid) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
}
Access Control
Role-Based Access Control (RBAC)
interface Permission {
resource: string;
action: string;
conditions?: Record<string, any>;
}
interface Role {
id: string;
name: string;
permissions: Permission[];
}
class AccessControlManager {
private roles: Map<string, Role> = new Map();
private userRoles: Map<string, string[]> = new Map();
addRole(role: Role): void {
this.roles.set(role.id, role);
}
assignRoleToUser(userId: string, roleId: string): void {
const userRoles = this.userRoles.get(userId) || [];
if (!userRoles.includes(roleId)) {
userRoles.push(roleId);
this.userRoles.set(userId, userRoles);
}
}
checkPermission(userId: string, resource: string, action: string): boolean {
const userRoles = this.userRoles.get(userId) || [];
for (const roleId of userRoles) {
const role = this.roles.get(roleId);
if (!role) continue;
for (const permission of role.permissions) {
if (permission.resource === resource && permission.action === action) {
return true;
}
}
}
return false;
}
getUserPermissions(userId: string): Permission[] {
const userRoles = this.userRoles.get(userId) || [];
const permissions: Permission[] = [];
for (const roleId of userRoles) {
const role = this.roles.get(roleId);
if (role) {
permissions.push(...role.permissions);
}
}
return permissions;
}
}
Attribute-Based Access Control (ABAC)
interface Attribute {
name: string;
value: any;
type: 'user' | 'resource' | 'environment' | 'action';
}
interface Policy {
id: string;
name: string;
effect: 'allow' | 'deny';
condition: string; // Expression to evaluate
}
class ABACEngine {
private policies: Policy[] = [];
addPolicy(policy: Policy): void {
this.policies.push(policy);
}
evaluate(attributes: Attribute[]): 'allow' | 'deny' {
const context = this.buildContext(attributes);
for (const policy of this.policies) {
if (this.evaluateCondition(policy.condition, context)) {
return policy.effect;
}
}
return 'deny'; // Default deny
}
private buildContext(attributes: Attribute[]): Record<string, any> {
const context: Record<string, any> = {};
for (const attr of attributes) {
context[`${attr.type}.${attr.name}`] = attr.value;
}
return context;
}
private evaluateCondition(
condition: string,
context: Record<string, any>
): boolean {
// Simple expression evaluator (in production, use a proper expression engine)
try {
const func = new Function(
'context',
`with(context) { return ${condition}; }`
);
return func(context);
} catch (error) {
return false;
}
}
}
Audit Logging
Security Event Logging
interface SecurityEvent {
eventType: string;
userId?: string;
resource: string;
action: string;
result: 'success' | 'failure';
timestamp: Date;
ipAddress: string;
userAgent: string;
metadata?: Record<string, any>;
}
class SecurityAuditLogger {
private logStream: WriteStream;
private encryptionKey: string;
constructor(logFile: string, encryptionKey: string) {
this.logStream = fs.createWriteStream(logFile, { flags: 'a' });
this.encryptionKey = encryptionKey;
}
async logSecurityEvent(event: SecurityEvent): Promise<void> {
const logEntry = {
...event,
id: crypto.randomUUID(),
timestamp: event.timestamp.toISOString(),
};
// Encrypt sensitive data
const encryptedEntry = await this.encryptLogEntry(logEntry);
// Write to log file
this.logStream.write(JSON.stringify(encryptedEntry) + '\n');
// Send to SIEM if configured
if (this.shouldSendToSIEM(event)) {
await this.sendToSIEM(encryptedEntry);
}
}
private async encryptLogEntry(entry: any): Promise<any> {
// Encrypt sensitive fields
const sensitiveFields = ['userId', 'ipAddress', 'metadata'];
const encrypted = { ...entry };
for (const field of sensitiveFields) {
if (encrypted[field]) {
encrypted[field] = await this.encrypt(JSON.stringify(encrypted[field]));
}
}
return encrypted;
}
private shouldSendToSIEM(event: SecurityEvent): boolean {
// Send critical security events to SIEM
const criticalEvents = [
'authentication_failure',
'authorization_failure',
'privilege_escalation',
'data_breach_attempt',
];
return criticalEvents.includes(event.eventType);
}
}
Threat Detection
Anomaly Detection
class AnomalyDetector {
private baselineMetrics: Map<string, number> = new Map();
private alertThresholds: Map<string, number> = new Map();
updateBaseline(metric: string, value: number): void {
const current = this.baselineMetrics.get(metric) || 0;
const updated = current * 0.9 + value * 0.1; // Exponential moving average
this.baselineMetrics.set(metric, updated);
}
detectAnomaly(metric: string, value: number): boolean {
const baseline = this.baselineMetrics.get(metric);
if (!baseline) return false;
const threshold = this.alertThresholds.get(metric) || 2.0;
const deviation = Math.abs(value - baseline) / baseline;
return deviation > threshold;
}
analyzeRequestPattern(requests: RequestLog[]): AnomalyReport {
const anomalies: Anomaly[] = [];
// Check request rate
const requestRate = requests.length / 60; // per minute
if (this.detectAnomaly('request_rate', requestRate)) {
anomalies.push({
type: 'high_request_rate',
severity: 'medium',
value: requestRate,
baseline: this.baselineMetrics.get('request_rate'),
});
}
// Check error rate
const errorRate =
requests.filter((r) => r.status >= 400).length / requests.length;
if (this.detectAnomaly('error_rate', errorRate)) {
anomalies.push({
type: 'high_error_rate',
severity: 'high',
value: errorRate,
baseline: this.baselineMetrics.get('error_rate'),
});
}
return {
timestamp: new Date(),
anomalies,
riskScore: this.calculateRiskScore(anomalies),
};
}
}
Security Monitoring
Real-Time Security Dashboard
class SecurityMonitor {
private eventBus: EventBus;
private alertManager: AlertManager;
private metricsCollector: MetricsCollector;
constructor() {
this.eventBus = new EventBus();
this.alertManager = new AlertManager();
this.metricsCollector = new MetricsCollector();
this.setupEventHandlers();
}
private setupEventHandlers(): void {
this.eventBus.on(
'security.authentication_failure',
this.handleAuthFailure.bind(this)
);
this.eventBus.on(
'security.suspicious_activity',
this.handleSuspiciousActivity.bind(this)
);
this.eventBus.on('security.data_access', this.handleDataAccess.bind(this));
}
private async handleAuthFailure(event: SecurityEvent): Promise<void> {
// Track failed authentication attempts
const key = `auth_failures:${event.ipAddress}`;
const count = await this.incrementCounter(key, 300); // 5 minute window
if (count > 5) {
await this.alertManager.sendAlert({
type: 'brute_force_attempt',
severity: 'high',
source: event.ipAddress,
message: `Multiple authentication failures from ${event.ipAddress}`,
});
// Temporarily block IP
await this.blockIP(event.ipAddress, 3600); // 1 hour
}
}
private async handleSuspiciousActivity(event: SecurityEvent): Promise<void> {
// Analyze activity patterns
const riskScore = await this.calculateRiskScore(event);
if (riskScore > 0.8) {
await this.alertManager.sendAlert({
type: 'suspicious_activity',
severity: 'high',
userId: event.userId,
message: `Suspicious activity detected for user ${event.userId}`,
});
}
}
}
Compliance Security Requirements
SOC 2 Security Controls
class SOC2SecurityControls {
// CC6.1 - Logical and Physical Access Controls
async implementAccessControls(): Promise<void> {
// Multi-factor authentication
await this.enableMFA();
// Role-based access control
await this.setupRBAC();
// Regular access reviews
await this.scheduleAccessReviews();
}
// CC6.2 - System Access Controls
async implementSystemControls(): Promise<void> {
// Session management
await this.configureSessionManagement();
// Password policies
await this.enforcePasswordPolicies();
// Account lockout policies
await this.setupAccountLockout();
}
// CC7.1 - System Monitoring
async implementMonitoring(): Promise<void> {
// Security event logging
await this.enableSecurityLogging();
// Intrusion detection
await this.setupIntrusionDetection();
// Vulnerability scanning
await this.scheduleVulnerabilityScans();
}
}
GDPR Data Protection
class GDPRDataProtection {
// Article 32 - Security of Processing
async implementDataSecurity(): Promise<void> {
// Encryption of personal data
await this.enableDataEncryption();
// Pseudonymization
await this.implementPseudonymization();
// Regular security testing
await this.scheduleSecurityTesting();
}
// Article 33 - Breach Notification
async setupBreachDetection(): Promise<void> {
// Automated breach detection
await this.enableBreachDetection();
// Incident response procedures
await this.setupIncidentResponse();
// Notification workflows
await this.configureNotifications();
}
}
Related Documentation
- Integration Architecture - System architecture
- API Reference - API security details
- Custom Backends - Backend security
- Performance Guide - Security performance
Security is fundamental to compliance integration. This guide provides comprehensive security measures for protecting sensitive compliance data and maintaining regulatory requirements.