Skip to content

Conversation

@ZMelliti
Copy link
Contributor

@ZMelliti ZMelliti commented Oct 26, 2025

Summary

This PR introduces a new API Security Cheat Sheet that provides comprehensive guidance for securing APIs across all technologies. The cheat sheet covers:

  • Complete OWASP API Security Top 10 2023 vulnerabilities with prevention strategies
  • Technology-agnostic security controls applicable to REST, GraphQL, gRPC, WebSocket, and SOAP APIs
  • Modern API patterns including API gateways, microservices, and zero trust architecture
  • Practical code examples in Java and JavaScript for common security implementations
  • Core security controls for authentication, authorization, input validation, and transport security
  • Testing, monitoring, and compliance guidance for API security programs

Checklist

Please make sure that for your contribution:

  • In case of a new Cheat Sheet, you have used the Cheat Sheet template.
  • All the markdown files do not raise any validation policy violation, see the policy.
  • All the markdown files follow these format rules.
  • All your assets are stored in the assets folder.
  • All the images used are in the PNG format.
  • Any references to websites have been formatted as [TEXT](URL)
  • You verified/tested the effectiveness of your contribution (e.g., the defensive code proposed is really an effective remediation? Please verify it works!).
  • The CI build of your PR pass, see the build status here.

Verification Details

  • New Cheat Sheet: Created using the official template structure with Introduction, main sections, and References
  • Link Validation: All internal references use proper [TEXT](CheatSheet.md) format and external links use [TEXT](URL) format
  • Format Compliance: Follows markdown formatting rules with proper headers, code blocks, and structure
  • No Assets: Text-based content with code examples only, no images or external assets required
  • Effectiveness: All security practices validated against OWASP API Security Top 10 2023, RFC standards, and industry best practices
  • Cross-References: Properly integrates with existing OWASP cheat sheets without duplication

This PR fixes #1865

AI Tool Usage Disclosure (required for all PRs)

Please select one of the following options:

  • I have NOT used any AI tool to generate the contents of this PR.
  • I have used AI tools to generate the contents of this PR. I have verified
    the contents and I affirm the results. The LLM used is [llm name and version]
    and the prompt used is [your prompt here]. [Feel free to add more details if needed]

Thank you 😃

@ZMelliti ZMelliti force-pushed the api-security-cheat-sheet branch from fd0ff1b to 43d47a8 Compare October 26, 2025 20:43
Copy link
Collaborator

@mackowski mackowski left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not like structure of this cheatsheet, 50% is just API top 10 (we do not need to duplicate content from different OWASP project) and there is a lot of duplication from other cheatsheets.

@jmanico
Copy link
Member

jmanico commented Oct 31, 2025

I do not like structure of this cheatsheet, 50% is just API top 10 (we do not need to duplicate content from different OWASP project) and there is a lot of duplication from other cheatsheets.

I hear you Mac. The goal here was to not duplicate content. #1865

@ZMelliti
Copy link
Contributor Author

Thanks @mackowski and @jmanico for the feedback. The goal isn’t to duplicate content from the API Top 10 or other cheat sheets — rather, to complement them with practical, implementation-focused guidance. I’ll revise the structure to make that clearer and remove any overlapping sections.

@ZMelliti ZMelliti force-pushed the api-security-cheat-sheet branch from 427c3c5 to da1e43b Compare November 3, 2025 19:34
@ZMelliti
Copy link
Contributor Author

ZMelliti commented Nov 3, 2025

@mackowski, @jmanico I've restructured the cheat sheet to eliminate content duplication by adding an explicit scope section that separates enterprise patterns from existing OWASP sheets (Authentication/Authorization/API Top 10) and added new sections for API versioning security and performance considerations with concrete metrics. The sheet now serves as a complementary enterprise reference focused on multi-tenant isolation, federation, and gateway patterns without duplicating existing OWASP resources.

@ZMelliti ZMelliti requested a review from mackowski November 3, 2025 19:47
@ZMelliti
Copy link
Contributor Author

ZMelliti commented Nov 7, 2025

Hello @jmanico and @mackowski, I'm still awaiting your review. If there are any changes needed or feedback to discuss, please let me know. Thank you.

Copy link
Collaborator

@szh szh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. I'll wait for @jmanico and @mackowski to review as well though.

Copy link
Member

@jmanico jmanico left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome

@mackowski
Copy link
Collaborator

I am still not approvig that baseuse

Centralized Gateway Security - this is not best solution for all APIs and we already have a good content here for it https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets_draft/Authorization_Patterns_Cheat_Sheet.md

Technology-Agnostic Authentication - again this is useful for some APIs but not all of them and for many it will only complicate authentication logic.

All "Enterprise Security Patterns" ale useful but there are not recommandations for all APIs...

This content drifted a lot from beeing universal API recommendation to list of possible architectual patterns for some enterprise APIs.

We could re-name this to Enterprise Security Architectual Patterns Cheat Sheet and update narrative at the beginning a little bit. In such case I would still add more patterns - one specific example is proof of possession. Also I would review content that we have in draft to not duplicate it but link to it where possible

@mackowski
Copy link
Collaborator

The content is good but, in my opinion, this are just not general purpos APIs recommendations - and that was the orginal goal.
For simpler APIs implementing all of that is overkill :-)
I personally would also make performance section less concrete - from where you took the numbers for this section? They look like LLM random generated but since you did not used LLMs you have some data or sources to back it up?

@mackowski mackowski requested a review from Copilot November 9, 2025 06:49
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces a comprehensive API Security Cheat Sheet that provides enterprise-grade security patterns applicable across all API technologies (REST, GraphQL, gRPC, WebSocket). The cheat sheet focuses on architectural security controls and universal patterns rather than protocol-specific implementations.

Key Changes:

  • Enterprise security patterns including multi-tenant isolation, cross-organization federation, centralized gateway security, and API versioning security
  • Universal security controls for cross-protocol rate limiting and technology-agnostic authentication
  • Security operations guidance for cross-protocol testing and automated threat orchestration
  • Performance considerations for security controls with optimization strategies

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

try {
TrustConfig config = TrustConfig.builder()
.mutualTLS(certificateService.exchangeCertificates(partnerOrg))
.tokenExchange(setupOAuth2Exchange(partnerOrg))
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing method definition for setupOAuth2Exchange. This method is called at line 130 but is never defined in the FederationSecurityManager class, which will cause a compilation error.

Copilot uses AI. Check for mistakes.
return true;
}
return false;
}
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incomplete CircuitBreaker implementation. The class initializes failureCount and lastFailureTime but never updates them. The isOpen() method checks these values, but there's no method to record failures, update the state to OPEN, or transition between states properly. Add methods like recordSuccess() and recordFailure() to maintain the circuit breaker state machine.

Suggested change
}
}
recordFailure() {
this.failureCount += 1;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.failureThreshold && this.state === 'CLOSED') {
this.state = 'OPEN';
} else if (this.state === 'HALF_OPEN') {
// If a failure occurs in HALF_OPEN, go back to OPEN
this.state = 'OPEN';
}
}
recordSuccess() {
if (this.state === 'HALF_OPEN') {
// Success in HALF_OPEN means recovery
this.state = 'CLOSED';
this.failureCount = 0;
this.lastFailureTime = null;
} else if (this.state === 'CLOSED') {
// Success in CLOSED just resets failure count
this.failureCount = 0;
this.lastFailureTime = null;
}
}

Copilot uses AI. Check for mistakes.

// Version-specific authentication
if (policy.isAuthRequired()) {
context.setUser(authenticateRequest(request, policy));
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing method definition for authenticateRequest. This method is called at line 364 but is never defined in the APIVersionSecurity class, which will cause a compilation error.

Copilot uses AI. Check for mistakes.
} catch (error) {
throw new InvalidTokenError(error.message);
}
}
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing method definitions in UniversalAuth class. The following methods are called but never defined:

  • getPublicKey() at line 456
  • validateClaims() at line 459
  • handleHTTPAuth, handleWebSocketAuth, handleWebhookAuth, handleGRPCAuth referenced at lines 439-442

These missing methods will cause runtime errors when the class is used.

Suggested change
}
}
// Returns the public key for JWT verification
getPublicKey() {
// In production, load from secure config or environment
return process.env.JWT_PUBLIC_KEY || "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnExampleKey\n-----END PUBLIC KEY-----";
}
// Validates universal claims in the decoded JWT
validateClaims(decoded) {
if (!decoded.sub) {
throw new InvalidTokenError("Missing subject claim");
}
if (!decoded.tenant) {
throw new InvalidTokenError("Missing tenant claim");
}
// Add more claim checks as needed
}
// Protocol-specific authentication handlers
async handleHTTPAuth(request) {
// Example: extract JWT from Authorization header
const token = request.headers?.authorization?.replace(/^Bearer\s/, "");
if (!token) throw new InvalidTokenError("Missing Authorization header");
return await this.validateJWT(token);
}
async handleWebSocketAuth(request) {
// Example: extract JWT from query or initial payload
const token = request.token || request.query?.token;
if (!token) throw new InvalidTokenError("Missing WebSocket token");
return await this.validateJWT(token);
}
async handleWebhookAuth(request) {
// Example: extract JWT from custom header or payload
const token = request.headers?.['x-webhook-token'] || request.body?.token;
if (!token) throw new InvalidTokenError("Missing Webhook token");
return await this.validateJWT(token);
}
async handleGRPCAuth(request) {
// Example: extract JWT from metadata
const token = request.metadata?.get('authorization')?.[0]?.replace(/^Bearer\s/, "");
if (!token) throw new InvalidTokenError("Missing gRPC authorization metadata");
return await this.validateJWT(token);
}

Copilot uses AI. Check for mistakes.
details: results,
securityScore: (passedTests / totalTests) * 100
};
}
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing method definitions in UniversalAPITester class. The following methods are called but never defined:

  • testAuthz() at line 492
  • testInjection() at line 493
  • testRateLimit() at line 494
  • testDataLeakage() at line 495
  • testGraphQLAuth, testWebSocketAuth, testWebhookAuth referenced at lines 513-516
  • getExpiredToken() at line 526

These missing methods will cause runtime errors when the testing functionality is used.

Suggested change
}
}
// Missing method definitions added below
async testAuthz(endpoint, protocol) {
// Simulate an authorization test
// In a real implementation, this would attempt access with insufficient privileges
return { status: 'passed', detail: 'Authorization test not implemented (stub).' };
}
async testInjection(endpoint, protocol) {
// Simulate an injection test
// In a real implementation, this would send malicious payloads
return { status: 'passed', detail: 'Injection test not implemented (stub).' };
}
async testRateLimit(endpoint, protocol) {
// Simulate a rate limiting test
// In a real implementation, this would send rapid requests and check for 429
return { status: 'passed', detail: 'Rate limit test not implemented (stub).' };
}
async testDataLeakage(endpoint, protocol) {
// Simulate a data leakage test
// In a real implementation, this would attempt to access data outside allowed scope
return { status: 'passed', detail: 'Data leakage test not implemented (stub).' };
}
async testGraphQLAuth(endpoint) {
// Simulate a GraphQL authentication test
// In a real implementation, this would send a GraphQL query with/without tokens
return [{ test: 'graphql_auth', passed: true }];
}
async testWebSocketAuth(endpoint) {
// Simulate a WebSocket authentication test
// In a real implementation, this would attempt to connect/send messages with/without tokens
return [{ test: 'websocket_auth', passed: true }];
}
async testWebhookAuth(endpoint) {
// Simulate a Webhook authentication test
// In a real implementation, this would send a webhook request with/without valid signature
return [{ test: 'webhook_auth', passed: true }];
}
getExpiredToken() {
// Return a string representing an expired token
// In a real implementation, generate a JWT or token with a past expiry
return 'expired.token.value';
}

Copilot uses AI. Check for mistakes.
Comment on lines +565 to +636
class APIThreatOrchestrator {
constructor() {
this.responseStrategies = new Map();
this.threatIntelligence = new ThreatIntelligenceEngine();
}

async orchestrateResponse(threatEvent) {
const threatContext = await this.analyzeThreat(threatEvent);
const affectedAPIs = this.identifyAffectedAPIs(threatContext);

// Coordinate response across multiple API types
const responses = await Promise.all(
affectedAPIs.map(api => this.executeResponse(api, threatContext))
);

return this.consolidateResponses(responses);
}

async executeResponse(api, threatContext) {
const strategy = this.getResponseStrategy(api.type, threatContext.severity);

return {
apiId: api.id,
actions: await strategy.execute(api, threatContext),
timestamp: Date.now()
};
}

// Adaptive security posture adjustment
async adaptSecurityPosture(threatLandscape) {
const adjustments = {
rateLimits: this.calculateRateLimitAdjustments(threatLandscape),
authStrength: this.adjustAuthRequirements(threatLandscape),
monitoring: this.enhanceMonitoring(threatLandscape)
};

return this.applyGlobalAdjustments(adjustments);
}

async analyzeThreat(threatEvent) {
return {
severity: this.calculateSeverity(threatEvent),
type: threatEvent.type,
source: threatEvent.source,
affectedProtocols: this.identifyAffectedProtocols(threatEvent)
};
}

identifyAffectedAPIs(threatContext) {
// Return APIs that match threat characteristics
return this.apiRegistry.filter(api =>
threatContext.affectedProtocols.includes(api.protocol)
);
}

getResponseStrategy(apiType, severity) {
const strategies = {
'high': new ImmediateBlockStrategy(),
'medium': new ThrottleStrategy(),
'low': new MonitorStrategy()
};
return strategies[severity] || strategies['low'];
}

consolidateResponses(responses) {
return {
totalAPIs: responses.length,
actionsExecuted: responses.reduce((sum, r) => sum + r.actions.length, 0),
timestamp: Date.now()
};
}
}
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing method definitions and uninitialized properties in APIThreatOrchestrator class. The following issues exist:

  • apiRegistry property referenced at line 615 but never initialized in constructor
  • calculateSeverity() called at line 606 but never defined
  • identifyAffectedProtocols() called at line 609 but never defined
  • calculateRateLimitAdjustments() called at line 596 but never defined
  • adjustAuthRequirements() called at line 597 but never defined
  • enhanceMonitoring() called at line 598 but never defined
  • applyGlobalAdjustments() called at line 601 but never defined

These missing implementations will cause runtime errors.

Copilot uses AI. Check for mistakes.
Comment on lines +663 to +695
class OptimizedSecurityMiddleware {
constructor() {
this.userCache = new LRUCache({ max: 10000, ttl: 300000 }); // 5min TTL
this.rateLimitCache = new Map();
}

async authenticate(token) {
// Check cache first (0.1ms vs 10ms DB lookup)
const cached = this.userCache.get(token);
if (cached && cached.expiresAt > Date.now()) {
return cached.user;
}

// Fallback to database
const user = await this.userService.validateToken(token);
this.userCache.set(token, { user, expiresAt: Date.now() + 300000 });
return user;
}

// Batch rate limit checks for better performance
async checkRateLimits(requests) {
const pipeline = this.redis.pipeline();
requests.forEach(req => {
pipeline.incr(`rate:${req.userId}:${req.endpoint}`);
});

const results = await pipeline.exec();
return results.map((result, index) => ({
allowed: result[1] <= requests[index].limit,
current: result[1]
}));
}
}
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing property initialization in OptimizedSecurityMiddleware class. The following properties are referenced but never initialized in the constructor:

  • userService at line 677 (should be injected via constructor)
  • redis at line 684 (should be injected via constructor)

These missing properties will cause runtime errors when the methods are called.

Copilot uses AI. Check for mistakes.
Comment on lines +59 to +60
if (!this.validateTenantAccess(request.user, tenantId)) {
this.auditLogger.logUnauthorizedAccess(request.user.id, tenantId);
Copy link

Copilot AI Nov 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Potential null pointer exception when request.user is null or undefined. The validateTenantAccess method returns false when user.tenants is undefined, but line 60 then tries to access request.user.id which will throw a TypeError. Add null check: if (!request.user || !this.validateTenantAccess(request.user, tenantId))

Suggested change
if (!this.validateTenantAccess(request.user, tenantId)) {
this.auditLogger.logUnauthorizedAccess(request.user.id, tenantId);
if (!request.user || !this.validateTenantAccess(request.user, tenantId)) {
this.auditLogger.logUnauthorizedAccess(request.user && request.user.id ? request.user.id : 'unknown', tenantId);

Copilot uses AI. Check for mistakes.
Copy link
Collaborator

@mackowski mackowski left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ZMelliti
Copy link
Contributor Author

ZMelliti commented Nov 9, 2025

@mackowski Thanks for the detailed review — I really appreciate your feedback.

The draft focuses on enterprise-oriented API architectural patterns, following earlier feedback that removed OWASP Top 10 references. I propose renaming it to “Enterprise API Security Architectural Patterns Cheat Sheet” and updating the introduction to clarify scope.

Code snippets were flagged by GitHub Copilot, which is expected — they are intentionally illustrative, not full implementations. Regarding the performance section, the quantitative numbers were just illustrative examples to support my point, not sourced from benchmarks or generated by an LLM. They were intended to demonstrate relative trade-offs, but I understand that this can be misleading, so I’ll revise it to qualitative guidance with references where possible.

Here’s a roadmap of the updates I plan to make:

  • Rename the cheat sheet and update the introduction to clearly reflect enterprise-focused scope.

  • Revise the performance section to be qualitative and, where possible, include references or links to real-world guidance.

  • Keep code snippets illustrative, with a note clarifying their conceptual purpose.

  • Link to existing OWASP cheat sheets to avoid duplication.

  • Add relevant additional patterns, such as Proof of Possession, to strengthen coverage.

Could you please review these proposed updates and confirm if this approach aligns with your expectations before I make the changes? Thank you :-)

@mackowski
Copy link
Collaborator

@jmanico and @szh what do you think?

@szh
Copy link
Collaborator

szh commented Nov 14, 2025

@mackowski I like the proposal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

New CS proposal: API Security Cheat Sheet

5 participants