This document outlines the comprehensive security measures and rate limiting mechanisms implemented in the Artisyn API. These features are designed to protect the platform from abuse, ensure fair resource allocation, and comply with OWASP security best practices.
- Rate Limiting
- IP-Based Blocking
- Security Headers
- API Key Management
- Monitoring & Alerting
- Security Logging
- Best Practices
- Troubleshooting
Rate limiting restricts the number of API requests a user or IP can make within a specific time window. The Artisyn API implements tiered rate limiting based on user authentication status and account type.
- Window: 15 minutes
- Limit: 50 requests
- Use Case: Anonymous API access
- Window: 15 minutes
- Limit: 200 requests
- Use Case: Logged-in users with standard accounts
- Window: 15 minutes
- Limit: 1000 requests
- Use Case: Premium subscription holders
- Window: 15 minutes
- Limit: 5 requests
- Use Case: Protection against brute force attacks
- Endpoints:
/auth/login,/auth/register
- Window: 1 minute
- Limit: 30 requests
- Use Case: Search operation protection
- Endpoints:
/search,/artisans
- Window: 1 hour
- Limit: 10 requests
- Use Case: Accounts flagged for suspicious behavior
All rate-limited endpoints return the following headers:
X-RateLimit-Limit: 50 # Maximum requests per window
X-RateLimit-Remaining: 45 # Remaining requests in current window
X-RateLimit-Reset: <timestamp> # ISO timestamp when limit resets
Retry-After: 300 # Seconds to wait before retrying (on 429)
- 200 OK: Request successful and within rate limit
- 429 Too Many Requests: Rate limit exceeded
- Response includes
Retry-Afterheader with seconds to wait - Response body contains retry information
- Response includes
// Rate limit is applied automatically via middleware
// No code changes required for protected endpoints
// For custom rate limiting on specific routes:
import { createRateLimiter, rateLimitConfigs } from 'src/middleware/rateLimiter';
const customLimiter = createRateLimiter({
windowMs: 5 * 60 * 1000, // 5 minutes
maxRequests: 100, // 100 requests
keyGenerator: (req) => req.user?.id || req.ip,
});
app.get('/custom-endpoint', customLimiter, (req, res) => {
// Your endpoint logic
});import { checkRateLimit } from 'src/middleware/rateLimiter';
const result = checkRateLimit('user-123', {
windowMs: 15 * 60 * 1000,
maxRequests: 100,
});
console.log(result);
// { allowed: true, remaining: 99, retryAfter: 0 }The IP blocking system automatically detects and blocks IPs exhibiting suspicious or abusive behavior.
- Threshold: 5 failed login attempts within 15 minutes
- Action: IP automatically blocked for 1 hour
- Endpoints Monitored:
/auth/login,/auth/register
import { blockIP, unblockIP, isIPBlocked, getBlockedIPs } from 'src/middleware/ipBlocking';
// Block an IP
blockIP('192.168.1.100', 'Suspicious activity detected', 60 * 60 * 1000);
// Check if IP is blocked
const status = isIPBlocked('192.168.1.100');
if (status.blocked) {
console.log(`IP blocked until: ${new Date(status.unblockTime)}`);
}
// Unblock an IP
unblockIP('192.168.1.100');
// Get all blocked IPs
const blocked = getBlockedIPs();
console.log(blocked); // Array of blocked IPs with reasonsWhen a blocked IP attempts to access the API, they receive:
{
"success": false,
"message": "Your IP has been blocked due to suspicious activity.",
"reason": "Exceeded failed attempts threshold (5 attempts)",
"unblockTime": "2026-01-30T14:30:00Z"
}import { getBlockedIPs, recordFailedAttempt } from 'src/middleware/ipBlocking';
// Get current blocked IPs
const blocked = getBlockedIPs();
blocked.forEach(entry => {
console.log(`${entry.ip}: ${entry.reason}`);
});Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; ...
- Prevents XSS attacks
- Restricts resource loading sources
- Inline policy adjustable based on requirements
X-Content-Type-Options: nosniff
- Prevents MIME type sniffing
- Forces browser to respect declared content type
X-Frame-Options: DENY
- Prevents clickjacking attacks
- Disallows framing of API responses
X-XSS-Protection: 1; mode=block
- Legacy XSS filter enabling
- Blocks page if XSS attack detected
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
- Enforces HTTPS connections
- Prevents downgrade attacks
- Duration: 1 year
Referrer-Policy: strict-origin-when-cross-origin
- Controls referrer information in requests
- Protects user privacy
Permissions-Policy: geolocation=(), microphone=(), camera=(), ...
- Restricts browser API access
- Prevents unauthorized feature use
All responses include:
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
Pragma: no-cache
Expires: 0
This prevents sensitive data from being cached by browsers or proxies.
API keys provide secure authentication for external integrations and third-party services.
import { createAPIKey } from 'src/services/apiKeyService';
// Basic API key
const apiKey = await createAPIKey(
'my-integration',
'Integration with external service'
);
console.log(apiKey);
// {
// id: 'uuid',
// key: 'artisyn_xxxxx...', // Secret key (only shown once)
// name: 'my-integration',
// status: 'active',
// createdAt: Date,
// ...
// }
// API key with expiration
const expiringKey = await createAPIKey(
'temporary-key',
'Temporary access',
undefined,
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // Expires in 7 days
);Include in request headers:
curl https://api.artisyn.com/api/endpoint \
-H "X-API-Key: artisyn_xxxxx..."Or as query parameter (less secure):
GET https://api.artisyn.com/api/endpoint?apiKey=artisyn_xxxxx...import { verifyAPIKey } from 'src/services/apiKeyService';
const apiKey = await verifyAPIKey('artisyn_xxxxx...');
if (apiKey) {
console.log(`Valid key: ${apiKey.name}`);
console.log(`Rate limit: ${apiKey.rateLimit} req/min`);
} else {
console.log('Invalid or expired key');
}import { revokeAPIKey } from 'src/services/apiKeyService';
const revoked = await revokeAPIKey('key-id-here');
if (revoked) {
console.log('API key revoked successfully');
}- Never commit API keys to version control
- Rotate keys regularly (recommended: every 3-6 months)
- Use IP whitelist to restrict key usage by IP
- Scope keys to specific endpoints only
- Monitor key usage for suspicious activity
- Revoke immediately if compromised
- Use environment variables to store keys
The monitoring system tracks API metrics and automatically generates alerts for security events.
- Triggered when user exceeds rate limit
- Severity: Medium
- Threshold: 3+ occurrences within 1 hour
- Triggered when IP is blocked
- Severity: High
- Automatic action taken on block
- Triggered on authentication failures
- Severity: Medium
- Threshold: 5+ failures within 15 minutes
- Triggered on unusual patterns
- Severity: High
- Examples: SQL injection attempts, XSS payloads
- Triggered on high error rates
- Severity: High
- Threshold: >5% error rate
import { createAlert } from 'src/services/monitoringService';
const alert = createAlert(
'rate-limit', // Alert type
'high', // Severity: low, medium, high, critical
'Rate limit exceeded', // Message
{ // Additional data
ip: '192.168.1.1',
userId: 'user-123',
limit: 100,
}
);import { getRecentAlerts, getAlertsBySeverity } from 'src/services/monitoringService';
// Get recent alerts
const recent = getRecentAlerts(10);
console.log(recent);
// Get critical alerts
const critical = getAlertsBySeverity('critical');
console.log(critical);import { resolveAlert } from 'src/services/monitoringService';
const resolved = resolveAlert('alert-id-here');import { getMonitoringDashboard } from 'src/services/monitoringService';
const dashboard = getMonitoringDashboard();
console.log(dashboard);
// {
// metrics: { /* API metrics */ },
// alerts: { /* Alert statistics */ },
// recentAlerts: [ /* Last 10 alerts */ ],
// highSeverityAlerts: [ /* Critical + High severity */ ],
// }Comprehensive logging system for security events, authentication, and data access for compliance and auditing.
import { logSecurityEvent } from 'src/utils/securityLogging';
logSecurityEvent(
'AUTH_ATTEMPT',
'info',
'User logged in successfully',
req,
{ userId: 'user-123', email: 'user@example.com' }
);import { logAuditEvent } from 'src/utils/securityLogging';
logAuditEvent(
'UPDATE_PROFILE',
'user-123',
'UserProfile',
'profile-123',
{ name: 'Old Name' -> 'New Name' },
'success',
req
);import { logRateLimitHit } from 'src/utils/securityLogging';
logRateLimitHit(req, 100, '15 minutes');import { logIPBlock } from 'src/utils/securityLogging';
logIPBlock('192.168.1.1', 'Exceeded failed attempts', req);import {
getRecentLogs,
getLogsByEventType,
getLogsBySeverity,
getLogsByIP,
getLogsByUser,
getLogsForTimeRange,
} from 'src/utils/securityLogging';
// Get recent logs
const recent = getRecentLogs(100);
// Get logs by event type
const authLogs = getLogsByEventType('AUTH_ATTEMPT');
// Get logs by severity
const errors = getLogsBySeverity('error');
// Get logs by IP
const ipLogs = getLogsByIP('192.168.1.1');
// Get logs by user
const userLogs = getLogsByUser('user-123');
// Get logs for time range
const rangeLogs = getLogsForTimeRange(
new Date('2026-01-01'),
new Date('2026-01-31')
);import { exportLogsToFile } from 'src/utils/securityLogging';
// Export recent logs to file
const logs = getRecentLogs(1000);
exportLogsToFile('logs_export_2026_01_30.log', logs);Logs are persisted to disk in the following locations:
logs/
├── security.log # All security events
└── audit.log # Compliance and audit trail
Each log entry includes:
- Timestamp (ISO format)
- Event type
- Severity level
- User ID
- Client IP
- User agent
- Endpoint
- HTTP method
- Status code
- Message
- Additional details
- Use rate limiting + IP blocking + API key validation
- Implement multiple layers of security
- Redundant authentication mechanisms
import { getMonitoringDashboard } from 'src/services/monitoringService';
// Check dashboard regularly
setInterval(() => {
const dashboard = getMonitoringDashboard();
if (dashboard.highSeverityAlerts.length > 0) {
// Send notification to security team
}
}, 5 * 60 * 1000); // Every 5 minutes- Rotate API keys every 3-6 months
- Revoke old keys after rotation period
- Maintain key rotation log
// For premium integrations, use IP whitelist
const apiKey = await createAPIKey('secure-integration', 'Restricted access');
// Set ipWhitelist: ['203.0.113.1', '203.0.113.2']
// Set allowedEndpoints: ['/api/orders', '/api/shipments']- Detect: Monitor alerts and logs
- Investigate: Review security logs and metrics
- Contain: Block IP, revoke keys, increase rate limits
- Remediate: Patch vulnerabilities, update rules
- Review: Analyze incident, improve rules
The implementation follows OWASP security principles:
- A01: Broken Authentication: Strong API key validation
- A02: Broken Access Control: IP blocking, rate limiting
- A03: Injection: Input validation, parameter checking
- A04: Insecure Design: Security by default
- A05: Security Misconfiguration: Secure headers
- A09: Logging & Monitoring: Comprehensive logging
Problem: Users report "429 Too Many Requests"
Solution:
- Check user tier:
SELECT * FROM users WHERE id = 'user-id' - Review recent requests:
getLogsByUser('user-id') - Adjust limits or whitelist if legitimate:
updateRateLimitConfig()
Problem: Legitimate IP addresses blocked
Solution:
- Check blocked IPs:
getBlockedIPs() - Verify block reason: Check
ipBlockinglogs - Unblock if necessary:
unblockIP('192.168.1.1')
Problem: "Invalid or expired API key"
Solution:
- Verify key still active:
verifyAPIKey(key) - Check expiration date:
getAPIKeyInfo(keyId) - Regenerate key if expired:
createAPIKey(name, description)
Problem: No alerts being generated
Solution:
- Check alert thresholds in
monitoringService.ts - Verify monitoring scheduler running:
startMonitoringScheduler() - Review alert statistics:
getAlertStatistics()
For security concerns or vulnerabilities, please contact the security team:
- Email: security@artisyn.com
- Report: Security Reporting Process
- v1.0.0 (2026-01-30): Initial implementation
- Rate limiting middleware
- IP blocking system
- Security headers
- API key management
- Monitoring and alerting
- Security logging
- Comprehensive tests