| name | moai-security-api |
| version | 4.0.0 |
| status | stable |
| description | Comprehensive API security for REST, GraphQL, and gRPC services with OAuth 2.1 authentication, JWT validation, rate limiting, and enterprise protection patterns. |
| allowed-tools | Read, Bash, WebSearch, WebFetch |
moai-security-api
API Security Expert
Trust Score: 9.9/10 | Version: 4.0.0 | Enterprise Security
📖 Progressive Disclosure
Level 1: Quick Reference (50 lines)
Core Purpose: Comprehensive API security for REST, GraphQL, and gRPC services with production-ready authentication, authorization, and protection patterns.
API Attack Surface:
User → [REST/GraphQL/gRPC Endpoint] → Internal Resources
↓
- Missing Authentication
- Broken Authorization
- Excessive Data Exposure
- Rate Limit Bypass
- Injection Attacks
OWASP API Security Top 10 (2023):
- Broken Object Level Authorization (BOLA)
- Broken Authentication
- Excessive Data Exposure
- Lack of Resources & Rate Limiting
- Broken Function Level Authorization (BFLA)
- Mass Assignment
- Cross-Site Scripting (XSS)
- Broken API Versioning
- Improper Assets Management
- Insufficient Logging & Monitoring
Three Security Pillars:
1. Authentication (Who are you?)
- OAuth 2.1 Authorization Code with PKCE
- JWT with RS256 signatures
- API Key with rotation policies
2. Authorization (What can you access?)
- Role-based access control (RBAC)
- Attribute-based access control (ABAC)
- Scope-based permission model
3. Rate Limiting (How much can you use?)
- Token bucket algorithm
- Sliding window counter
- Distributed rate limiting (Redis)
Quick Defense Implementation:
app.get('/api/users', (req, res) => {
res.json(db.users.all());
});
app.get('/api/users',
authenticate(),
authorize('read:users'),
rateLimit(),
(req, res) => {
const users = db.users.findByTenant(req.tenantId);
res.json(users);
}
);
Level 2: Core Implementation (140 lines)
OAuth 2.1 + JWT Security Framework:
const jwt = require('jsonwebtoken');
const passport = require('passport');
const { Strategy: OAuth2Strategy } = require('passport-oauth2');
const redis = require('redis');
const redisClient = redis.createClient();
const oauthStrategy = new OAuth2Strategy({
authorizationURL: 'https://auth-server.com/oauth/authorize',
tokenURL: 'https://auth-server.com/oauth/token',
clientID: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
callbackURL: 'https://api.example.com/auth/callback',
state: true,
pkce: true
}, verifyCallback);
passport.use('oauth', oauthStrategy);
function verifyJWT(token) {
try {
const decoded = jwt.verify(token, (), {
: [],
: ,
: ,
:
});
((token)) {
();
}
decoded;
} (error) {
();
}
}
() {
{
authHeader = req..;
(!authHeader || !authHeader.()) {
res.().({ : });
}
token = authHeader.();
decoded = (token);
req. = {
: decoded.,
: decoded.,
: decoded.?.() || [],
: decoded.,
: decoded. || []
};
();
} (error) {
res.().({ : error. });
}
}
() {
{
userScopes = req.. || [];
hasRequiredScope = requiredScopes.(
userScopes.(scope)
);
(!hasRequiredScope) {
res.().({
: ,
: requiredScopes,
: userScopes
});
}
();
};
}
() {
apiKey = req.[];
(!apiKey) {
res.().({ : });
}
{
client = redisClient.();
(!client) {
client = db..({
: apiKey.()[],
: ,
: { : () }
});
(!client) {
res.().({ : });
}
redisClient.(, , .(client));
}
rateLimitKey = ;
count = redisClient.(rateLimitKey);
(count === ) {
redisClient.(rateLimitKey, );
}
(count > client.) {
res.().({
: ,
:
});
}
req. = client;
();
} (error) {
.(, error);
res.().({ : });
}
}
rateLimitLuaScript = ;
() {
(req, res, next) => {
userId = req.?. || req.?. || ;
key = ;
{
allowed = redisClient.(rateLimitLuaScript, {
: [key],
: [capacity, refillRate, .()]
});
(!allowed) {
res.().({
: ,
: .(capacity / refillRate)
});
}
res.({
: capacity,
: .(, capacity - ( redisClient.(key) || )),
: (.() + ).()
});
();
} (error) {
.(, error);
();
}
};
}
Multi-Tenant Security Patterns:
async function tenantMiddleware(req, res, next) {
const tenantId = req.user?.tenant_id || req.client?.tenant_id;
if (!tenantId) {
return res.status(403).json({ error: 'Tenant ID required' });
}
const tenant = await db.tenants.findById(tenantId);
if (!tenant || tenant.status !== 'active') {
return res.status(403).json({ error: 'Invalid or inactive tenant' });
}
req.tenantId = tenantId;
req.tenant = tenant;
next();
}
function tenantIsolated(queryField = 'tenant_id') {
return (req, res, next) => {
req.tenantFilter = { [queryField]: req.tenantId };
next();
};
}
app.(,
(),
(),
(req, res) => {
user = db..({
: req..,
...req.
});
(!user) {
res.().({ : });
}
(user. !== req.) {
res.().({ : });
}
res.(user);
}
);
Level 3: Advanced API Security (100 lines)
GraphQL Security Implementation:
const { ApolloServer } = require('@apollo/server');
function calculateQueryComplexity(document, operation) {
let complexity = 0;
let depth = 0;
const visitNode = (node, currentDepth) => {
depth = Math.max(depth, currentDepth);
if (node.kind === 'Field') {
complexity += 1;
const expensiveFields = ['users', 'posts', 'analytics'];
if (expensiveFields.includes(node.name.value)) {
complexity += 10;
}
}
if (node.selectionSet) {
node.selectionSet.selections.forEach(selection =>
visitNode(selection, currentDepth + 1)
);
}
};
visitNode(operation, 0);
return { complexity, depth };
}
server = ({
typeDefs,
resolvers,
: [{
() {
{
() {
{ complexity, depth } = (
requestContext.,
requestContext..
);
(complexity > ) {
();
}
(depth > ) {
();
}
}
};
}
}],
: process.. !== ,
: ,
: ({
: req.,
: req.,
: req.?. || []
})
});
resolvers = {
: {
: {
(!context..()) {
();
}
db..(context.);
},
: {
(!context..() ||
!context..()) {
();
}
db..(context.);
}
}
};
gRPC Security with mTLS:
const grpc = require('@grpc/grpc-js');
const fs = require('fs');
function createSecureServer() {
const rootCert = fs.readFileSync('/secure/ca-cert.pem');
const serverCert = fs.readFileSync('/secure/server-cert.pem');
const serverKey = fs.readFileSync('/secure/server-key.pem');
const serverCredentials = grpc.ServerCredentials.createSsl(
rootCert,
[{ cert_chain: serverCert, private_key: serverKey }]
);
const server = new grpc.Server();
const jwtInterceptor = (options, nextCall) => {
const metadata = options.metadata || new grpc.Metadata();
const token = metadata.get('authorization')[0];
try {
const decoded = jwt.verify(token, getPublicKey());
options.metadata = metadata;
options.metadata.set('user', .(decoded));
} (error) {
grpc..();
}
(options);
};
server.(, serverCredentials);
server;
}
() {
rootCert = fs.();
clientCert = fs.();
clientKey = fs.();
clientCredentials = grpc..(
rootCert, clientKey, clientCert
);
(, clientCredentials);
}
Webhook Security (HMAC-SHA256):
const crypto = require('crypto');
async function sendSecureWebhook(event, url, secret) {
const timestamp = Math.floor(Date.now() / 1000);
const payload = JSON.stringify({ ...event, timestamp });
const signature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
const response = await fetch(url, {
method: 'POST',
headers: {
'X-Webhook-Signature': `sha256=${signature}`,
'X-Webhook-Timestamp': timestamp.toString(),
'Content-Type': 'application/json'
},
body: payload,
timeout: 30000
});
if (!response.ok) {
throw new Error(`Webhook delivery failed: ${response.status}`);
}
return response.json();
}
app.(,
express.({ : }),
{
signature = req.[];
timestamp = (req.[]);
age = .(.() / ) - timestamp;
(age > ) {
res.().({ : });
}
[version, hash] = signature.()[].();
expected = crypto
.(, process..)
.()
.();
(!crypto.(.(hash), .(expected))) {
res.().({ : });
}
event = .(req.);
(event);
res.({ : });
}
);
Level 4: Enterprise Integration (50 lines)
API Security Architecture:
Version Strategy with Deprecation:
function apiVersionMiddleware(req, res, next) {
const version = req.path.match(/\/v(\d+)\//)?.[1] || '1';
const currentVersion = 2;
req.apiVersion = parseInt(version);
if (req.apiVersion < currentVersion) {
res.set({
'Deprecation': 'true',
'Sunset': new Date('2026-01-01').toUTCString(),
'Link': `</api/v${currentVersion}${req.path.replace(/\/v\d+/, '')}>; rel="successor-version"`
});
}
next();
}
app.get('/api/v1/users', legacyUserHandler);
app.get('/api/v2/users', currentUserHandler);
app.get('/api/v3/users', nextGenUserHandler);
CORS & Security Headers:
const cors = require('cors');
const helmet = require('helmet');
const corsOptions = {
origin: process.env.ALLOWED_ORIGINS?.split(',') || ['https://app.example.com'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
maxAge: 86400
};
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", process.env.API_BASE_URL]
}
},
hsts: { maxAge: , : },
: ,
: ,
: { : }
}));
app.((corsOptions));
Multi-Database Security:
class TenantDatabaseManager {
constructor() {
this.connections = new Map();
}
async getConnection(tenantId) {
if (this.connections.has(tenantId)) {
return this.connections.get(tenantId);
}
const tenant = await db.tenants.findById(tenantId);
const connection = createDatabaseConnection(tenant.database_config);
this.connections.set(tenantId, connection);
return connection;
}
async query(tenantId, query, params) {
const connection = await this.getConnection(tenantId);
return connection.query(query, params);
}
}
const tenantDB = new TenantDatabaseManager();
app.get('/api/data',
authenticate(),
(),
(req, res) => {
data = tenantDB.(req.,
,
[req.]
);
res.(data);
}
);
API Reference:
Core Security Functions:
verifyJWT(token, publicKey)
authenticate(req, res, next)
authorize(requiredScopes)
authenticateAPIKey(req, res, next)
rateLimit(capacity, refillRate)
tokenBucketMiddleware(key, limit, rate)
tenantMiddleware(req, res, next)
tenantIsolated(field)
isolateByTenant(query)
calculateQueryComplexity(document, operation)
sendSecureWebhook(event, url, secret)
verifyWebhookSignature(payload, signature, secret)
Essential Security Headers:
{
'Content-Security-Policy': "default-src 'self'",
'X-Frame-Options': 'DENY',
'X-Content-Type-Options': 'nosniff',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'X-RateLimit-Limit': '100',
'X-RateLimit-Remaining': '99',
'X-RateLimit-Reset': 'timestamp'
}
Deployment Checklist:
✅ Essential Security Controls:
✅ Enterprise Security Integration:
✅ Monitoring & Compliance:
📈 Version History
v4.0.0 (2025-11-13)
- ✨ Optimized 4-layer Progressive Disclosure structure
- ✨ Reduced from 695 to 340 lines (51% reduction)
- ✨ Enhanced OAuth 2.1 with PKCE patterns
- ✨ Comprehensive multi-tenant security
- ✨ Production-ready implementation examples
v3.0.0 (2025-11-12)
- ✨ Advanced GraphQL security patterns
- ✨ gRPC mTLS implementation
- ✨ Webhook security with HMAC
v2.0.0 (2025-11-09)
- ✨ JWT RS256 verification
- ✨ Token bucket rate limiting
- ✨ API key management
v1.0.0 (2025-10-15)
- ✨ Basic authentication patterns
- ✅ Essential security middleware
Generated with: MoAI-ADK Skill Factory v4.0
Last Updated: 2025-11-13
Security Classification: Enterprise API Security
Optimization: 51% size reduction while maintaining comprehensive security coverage