Data Exposure in APIs: Prevention and Detection
Improper data exposure through APIs represents one of the main vulnerabilities in modern systems. Misconfigured or inadequately protected APIs can leak sensitive information, compromise user data, and violate privacy regulations such as LGPD and GDPR.
Types of Data Exposure in APIs
1. Excessive Data Exposure (API3:2023 - OWASP)
APIs that return more information than necessary:
- Endpoint returns the full object when only a few fields are needed
- Inclusion of sensitive fields in responses (password hashes, internal tokens)
- System metadata exposed in errors
// [ERRO] Exemplo RUIM - Expondo dados demais
GET /api/users/123
{
"id": 123,
"name": "João Silva",
"email": "[email protected]",
"password_hash": "$2b$10$...", // [AVISO] Nunca expor
"ssn": "123-45-6789", // [AVISO] Dado sensível
"internal_role_id": 42, // [AVISO] Dado interno
"created_at": "2025-01-01",
"last_login_ip": "192.168.1.1" // [AVISO] Informação sensível
}
// [OK] Exemplo BOM - Apenas dados necessários
GET /api/users/123/profile
{
"id": 123,
"name": "João Silva",
"avatar_url": "https://..."
}
2. Lack of Resource Filtering (Broken Object Level Authorization)
Users can access other users' data by changing IDs:
// [ERRO] Vulnerável a IDOR (Insecure Direct Object Reference)
GET /api/orders/456 // Usuário A pode ver pedidos do Usuário B
// [OK] Protegido - Validar autorização
app.get('/api/orders/:id', async (req, res) => {
const order = await Order.findById(req.params.id);
// Verificar se o pedido pertence ao usuário autenticado
if (order.userId !== req.user.id) {
return res.status(403).json({ error: 'Acesso negado' });
}
res.json(order);
});
3. Exposure of Sensitive Information in URLs
- Authentication tokens in query strings
- Personal data in paths
- Confidential information in server logs
Prevention Strategies
Implement Data Transfer Objects (DTOs)
// TypeScript - Definir claramente o que expor
interface UserPublicDTO {
id: number;
name: string;
avatar_url: string;
}
class UserService {
async getPublicProfile(userId: number): Promise<UserPublicDTO> {
const user = await db.users.findUnique({ where: { id: userId } });
// Retornar apenas campos permitidos
return {
id: user.id,
name: user.name,
avatar_url: user.avatar_url
};
}
}
Apply Serialization Filters
- Use libraries such as class-transformer (TypeScript)
- Decorators to mark sensitive fields (@Exclude)
- Serialization groups for different contexts (public vs. admin)
Authorization Validation
// Middleware de autorização
const checkResourceOwnership = (resourceType) => {
return async (req, res, next) => {
const resource = await db[resourceType].findById(req.params.id);
if (!resource) {
return res.status(404).json({ error: 'Recurso não encontrado' });
}
if (resource.ownerId !== req.user.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Acesso não autorizado' });
}
req.resource = resource;
next();
};
};
// Uso
app.get('/api/documents/:id',
authenticate,
checkResourceOwnership('documents'),
(req, res) => {
res.json(req.resource);
}
);
Detection Techniques
Payload Analysis
- Manually review responses from critical endpoints
- Use tools such as Burp Suite, OWASP ZAP
- Automated tests to verify exposed fields
Monitoring and Alerts
- Detect abnormal access patterns (enumeration)
- Alert on excessive denied access attempts
- Monitor the volume of data transferred per user
Code Review and Static Analysis
- Review DTOs and serialization models
- Verify authorization implementation
- Use SAST tools to identify exposures
Best Practices
- Adopt the principle of least privilege for exposed data
- Implement rate limiting to prevent scraping
- Use UUIDs instead of sequential IDs
- Encrypt sensitive data in transit and at rest
- Implement API versioning for safe changes
- Perform security testing regularly
- Clearly document which data each endpoint exposes
- Use GraphQL carefully (it can facilitate over-fetching)
Compliance and Regulation
- LGPD/GDPR: Data minimization, legal basis for processing
- PCI-DSS: Protection of credit card data
- HIPAA: Protection of health information (USA)
- SOC 2: Access controls and monitoring
