api-security
# API Security Skill
What this skill does
# API Security Skill
> **USE WHEN:** Designing, implementing, or auditing REST, GraphQL, or gRPC APIs for security vulnerabilities.
> **DO NOT USE FOR:** General API design patterns (use rest-api/graphql skills), authentication setup (use jwt/oauth2 skills).
## OWASP API Security Top 10:2023
| Rank | Vulnerability | Description |
|------|---------------|-------------|
| **API1** | Broken Object Level Authorization (BOLA) | IDOR, accessing other users' resources |
| **API2** | Broken Authentication | Weak auth, token flaws |
| **API3** | Broken Object Property Level Authorization | Mass assignment, excessive data exposure |
| **API4** | Unrestricted Resource Consumption | No rate limiting, DoS |
| **API5** | Broken Function Level Authorization | Admin functions exposed |
| **API6** | Unrestricted Access to Sensitive Business Flows | Automated abuse |
| **API7** | Server Side Request Forgery (SSRF) | Internal resource access |
| **API8** | Security Misconfiguration | CORS, headers, verbose errors |
| **API9** | Improper Inventory Management | Shadow APIs, outdated versions |
| **API10** | Unsafe Consumption of APIs | Trusting third-party APIs |
## API1: Broken Object Level Authorization (BOLA)
```typescript
// Bad: No ownership check
app.get('/api/orders/:id', async (req, res) => {
const order = await Order.findById(req.params.id);
res.json(order);
});
// Good: Verify ownership
app.get('/api/orders/:id', authenticate, async (req, res) => {
const order = await Order.findOne({
_id: req.params.id,
userId: req.user.id // Filter by current user
});
if (!order) {
return res.status(404).json({ error: 'Order not found' });
}
res.json(order);
});
// Good: Use UUIDs instead of sequential IDs
// Harder to enumerate, though NOT a substitute for auth
GET /api/orders/550e8400-e29b-41d4-a716-446655440000
```
## API3: Broken Object Property Level Authorization
```typescript
// Bad: Mass assignment
app.put('/api/users/:id', async (req, res) => {
await User.findByIdAndUpdate(req.params.id, req.body); // Can set isAdmin!
});
// Good: Explicit field whitelist
const updateSchema = z.object({
name: z.string().optional(),
email: z.string().email().optional(),
// isAdmin NOT allowed
});
app.put('/api/users/:id', async (req, res) => {
const data = updateSchema.parse(req.body);
await User.findByIdAndUpdate(req.params.id, data);
});
// Bad: Excessive data exposure
app.get('/api/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
res.json(user); // Includes password hash, internal fields
});
// Good: DTOs with explicit fields
app.get('/api/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
res.json({
id: user.id,
name: user.name,
email: user.email
// Exclude: passwordHash, internalNotes, etc.
});
});
```
## API4: Unrestricted Resource Consumption
```typescript
// Good: Rate limiting
import rateLimit from 'express-rate-limit';
// Global rate limit
const globalLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 min
max: 100,
standardHeaders: true
});
// Stricter for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
skipSuccessfulRequests: true
});
app.use('/api/', globalLimiter);
app.use('/api/auth/', authLimiter);
// Good: Pagination limits
const listSchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(20)
});
app.get('/api/items', async (req, res) => {
const { page, limit } = listSchema.parse(req.query);
const items = await Item.find()
.skip((page - 1) * limit)
.limit(limit);
res.json({ items, page, limit });
});
// Good: Request size limits
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ limit: '100kb', extended: true }));
```
## API7: Server Side Request Forgery (SSRF)
```typescript
// Bad: Unvalidated URL fetch
app.post('/api/fetch', async (req, res) => {
const response = await fetch(req.body.url); // Can access internal services!
res.json(await response.json());
});
// Good: URL validation and allowlist
const ALLOWED_HOSTS = ['api.example.com', 'cdn.example.com'];
function validateUrl(urlString: string): URL {
const url = new URL(urlString);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('Invalid protocol');
}
if (!ALLOWED_HOSTS.includes(url.hostname)) {
throw new Error('Host not allowed');
}
// Block private IPs
const privateRanges = [
/^127\./,
/^10\./,
/^172\.(1[6-9]|2[0-9]|3[01])\./,
/^192\.168\./,
/^169\.254\./,
/^localhost$/i
];
if (privateRanges.some(r => r.test(url.hostname))) {
throw new Error('Private addresses not allowed');
}
return url;
}
```
## API8: Security Misconfiguration
```typescript
// Good: CORS configuration
import cors from 'cors';
const corsOptions = {
origin: (origin, callback) => {
const allowedOrigins = ['https://myapp.com', 'https://admin.myapp.com'];
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400 // 24 hours
};
app.use(cors(corsOptions));
// Good: Error handling without leaking info
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error('Error:', err); // Log full error internally
if (process.env.NODE_ENV === 'production') {
res.status(500).json({ error: 'Internal server error' });
} else {
res.status(500).json({
error: err.message,
stack: err.stack
});
}
});
// Good: Remove fingerprinting headers
app.disable('x-powered-by');
```
## GraphQL Security
### Query Depth & Complexity Limiting
```typescript
import { createComplexityLimitRule } from 'graphql-validation-complexity';
import depthLimit from 'graphql-depth-limit';
const server = new ApolloServer({
schema,
validationRules: [
depthLimit(5), // Max query depth
createComplexityLimitRule(1000, { // Max complexity
onCost: (cost) => console.log('Query cost:', cost),
createError: (max, actual) =>
new GraphQLError(`Query too complex: ${actual}. Max: ${max}`)
})
]
});
```
### Disable Introspection in Production
```typescript
import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginLandingPageDisabled } from '@apollo/server/plugin/disabled';
const server = new ApolloServer({
schema,
introspection: process.env.NODE_ENV !== 'production',
plugins: process.env.NODE_ENV === 'production'
? [ApolloServerPluginLandingPageDisabled()]
: []
});
```
### Batching Attack Prevention
```typescript
// Limit batch size
const server = new ApolloServer({
schema,
allowBatchedHttpRequests: true, // Or false to disable
});
// Custom batching limit
app.use('/graphql', (req, res, next) => {
if (Array.isArray(req.body) && req.body.length > 10) {
return res.status(400).json({ error: 'Batch size exceeds limit' });
}
next();
});
```
### Query Allowlisting (Persisted Queries)
```typescript
import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginUsageReporting } from '@apollo/server/plugin/usageReporting';
// In production, only allow pre-registered queries
const server = new ApolloServer({
schema,
persistedQueries: {
cache: new KeyValueCache(), // Redis recommended
},
plugins: [
{
async requestDidStart() {
return {
async didResolveOperation({ request }) {
if (process.env.NODE_ENV === 'production' && !request.extensions?.persistedQuery) {
throw new GraphQLError('Only persisted queries allowed');
}
}
};
}
}
]
});
```
## JWT Security Best Practices
```typescript
import jwt from 'jsonwebtokeRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.