Cors Wildcard in Sails with Bearer Tokens
Cors Wildcard in Sails with Bearer Tokens — how this specific combination creates or exposes the vulnerability
In Sails.js, a common configuration mistake is setting cors.allRoutes (or the equivalent CORS policy) to allow origins with a wildcard (*) while also requiring Bearer token authentication for protected endpoints. A wildcard CORS policy tells browsers to allow cross-origin requests from any domain, which can undermine token-based protections when combined with credential-bearing requests. Bearer tokens are typically sent in the Authorization header, and if CORS allows any origin, malicious sites can initiate authenticated requests from a victim’s browser and potentially observe or relay responses through crafted JavaScript.
For example, an attacker’s page can make an XMLHttpRequest or fetch call to your Sails API with the Authorization: Bearer <token> header if the server responds with Access-Control-Allow-Credentials: true and Access-Control-Allow-Origin: * (or a dynamic origin reflecting the request’s Origin). Although browsers block frontend JavaScript from reading the response due to the same-origin policy, the request itself is executed, enabling unauthorized actions such as modifying resources or triggering business logic. This setup violates the principle that wildcard CORS should not be used when credentials, including Bearer tokens, are involved, as outlined in the OWASP API Security Top 10 and broader web security guidance.
The risk is particularly pronounced in unauthenticated scan scenarios, where middleBrick tests the exposed attack surface without credentials. If the API’s CORS configuration advertises permissive origins while endpoints expect Bearer tokens, an unauthenticated scan can detect mismatches that allow unauthorized origins to interact with token-guarded routes. Attack patterns such as Cross-Site Request Forgery (CSRF) against authenticated sessions or token leakage through referrer headers may be feasible depending on how the frontend handles responses. The interplay between CORS policy and Authorization header validation is critical; misalignment can expose token-based protections to abuse.
To identify this during a scan, middleBrick evaluates CORS headers in combination with authentication mechanisms across its 12 security checks. This includes examining whether Access-Control-Allow-Origin is set to a wildcard while endpoints validate Bearer tokens, and whether credentialed requests are permitted. Because Sails applications often rely on policies or hooks to enforce CORS and authentication, discrepancies between configuration files and runtime behavior are common findings. Developers should ensure that if Bearer tokens are required, the CORS origin is explicitly set to trusted domains rather than *, and that preflight responses do not inadvertently grant broad access.
Bearer Tokens-Specific Remediation in Sails — concrete code fixes
Remediation focuses on tightening CORS settings and ensuring token validation is consistently enforced. In Sails, CORS configuration is typically managed in config/cors.js. You should avoid using a wildcard for origins when handling Bearer tokens, and explicitly specify trusted domains. Additionally, authentication policies or hooks must verify the presence and validity of the Bearer token before allowing access to protected controllers.
Below is a secure CORS configuration example for Sails that restricts origins and supports Bearer token-based workflows without exposing wildcard risks:
// config/cors.js
module.exports.cors = {
allRoutes: true,
origin: [
'https://app.yourdomain.com',
'https://admin.yourdomain.com'
],
allowCredentials: true,
allowHeaders: [
'authorization',
'content-type',
'accept',
'x-requested-with'
],
allowMethods: [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
],
maxAge: 3600
};
In this configuration, origin is set to specific trusted domains instead of *, and allowCredentials is enabled to support requests that include cookies or authorization headers. The allowHeaders list explicitly permits the authorization header so that Bearer tokens can be passed reliably. The maxAge setting reduces preflight overhead while maintaining security.
On the authentication side, you can enforce Bearer token validation in a Sails policy, such as api/policies/authenticate.js:
// api/policies/authenticate.js
module.exports = async function (req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.unauthorized('Missing or invalid Authorization header');
}
const token = authHeader.split(' ')[1];
if (!token) {
return res.unauthorized('Invalid token format');
}
try {
// Replace with your actual token verification logic, e.g., JWT verify
const decoded = await verifyBearerToken(token);
req.user = decoded;
return next();
} catch (err) {
return res.unauthorized('Invalid or expired token');
}
};
// Example helper (implementation-specific)
async function verifyBearerToken(token) {
// Example using a JWT library; adapt to your auth provider
const jwt = require('jsonwebtoken');
return jwt.verify(token, process.env.JWT_PUBLIC_KEY || 'your-public-key');
}
This policy checks for the Authorization header, validates the Bearer token format, and verifies its authenticity before allowing the request to proceed. It ensures that even with a restricted CORS origin, only properly authenticated requests are processed. You can apply this policy to relevant controllers or globally, depending on your security requirements.
For automated validation, middleBrick can scan your Sails application’s CORS and authentication setup, flagging misconfigurations where a wildcard origin coexists with token-based protections. By combining correct CORS settings with robust Bearer token validation, you reduce the attack surface and align with best practices for API security.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
Can a wildcard CORS origin be safe if I don’t allow credentials?
Access-Control-Allow-Credentials: true, a wildcard origin (*) does not automatically expose tokens to other origins because browsers do not include credentials in cross-origin requests initiated by third-party sites. However, it can still permit unsafe read-only interactions; for Bearer token workflows, it is best practice to specify trusted origins explicitly rather than relying on the absence of credentials.