Cors Wildcard in Grape with Cockroachdb
Cors Wildcard in Grape with Cockroachdb — how this specific combination creates or exposes the vulnerability
A CORS wildcard in a Grape API that serves data from Cockroachdb can unintentionally expose database-derived resources to any origin. In Grape, setting allow_origins: '*' while your endpoints proxy or expose database-backed routes removes origin restrictions. Because Cockroachdb often serves as the authoritative data source, responses may include sensitive rows or schema details when accessed cross-origin without proper validation.
When a wildcard is combined with credentials or non-simple requests, browsers send cookies or authorization headers, allowing a malicious site to make authenticated requests on behalf of a user. If your Grape routes perform row-level authorization based solely on request origin, a wildcard bypasses that safeguard. Cockroachdb’s role as the backend means that misconfigured CORS can lead to data exposure across origins, especially when preflight responses include permissive headers.
This risk is amplified when routes dynamically construct URLs or SQL-like query parameters that reflect origin values. An attacker can craft a request that leverages wildcard CORS to harvest rows intended for specific origins. The interaction between Grape’s routing and Cockroachdb’s consistent interface can unintentionally expose datasets that should be origin-scoped.
For example, consider a route that returns tenant data based on a header. With a wildcard, any site can request that route and potentially infer tenant existence through timing or error differences, even if rows are filtered later. Cockroachdb’s deterministic response times may aid an attacker in performing blind enumeration when CORS is unrestricted.
Compliance mappings such as OWASP API Top 10 A05:2023 (Security Misconfiguration) and A01:2023 (Broken Access Control) are relevant here. PCI-DSS and SOC2 controls also expect explicit allowlists for cross-origin access when sensitive data is involved. middleBrick scans detect CORS misconfigurations and map findings to these frameworks, providing prioritized remediation guidance.
Cockroachdb-Specific Remediation in Grape — concrete code fixes
Remediate CORS wildcard issues in Grape by replacing allow_origins: '*' with an explicit list of trusted origins. Combine this with Cockroachdb-aware checks that validate the request context before querying the database. Below are concrete, syntactically correct examples for Grape with Cockroachdb integration.
First, configure CORS with specific origins and ensure credentials are only allowed when necessary:
class MyAPI < Grape::API
before do
# Explicit allowlist instead of wildcard
allowed_origins = ['https://app.example.com', 'https://admin.example.com']
origin = request.env['HTTP_ORIGIN']
if allowed_origins.include?(origin)
headers['Access-Control-Allow-Origin'] = origin
else
headers['Access-Control-Allow-Origin'] = allowed_origins.first
end
headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Request-ID'
headers['Access-Control-Expose-Headers'] = 'X-Rate-Limit-Limit, X-Rate-Limit-Remaining'
headers['Access-Control-Allow-Credentials'] = 'true'
end
resource :tenants do
desc 'Get tenant data with Cockroachdb-backed validation'
params do
requires :id, type: String, desc: 'Tenant identifier'
end
get ':id' do
tenant_id = params[:id]
# Cockroachdb connection setup (using pg gem)
conn = PG.connect(
host: ENV['COCKROACHDB_HOST'],
port: ENV['COCKROACHDB_PORT'],
dbname: ENV['COCKROACHDB_DB'],
user: ENV['COCKROACHDB_USER'],
password: ENV['COCKROACHDB_PASSWORD'],
sslmode: 'require'
)
# Ensure tenant exists and belongs to the requesting origin context
result = conn.exec_params('SELECT id, name, allowed_origin FROM tenants WHERE id = $1', [tenant_id])
if result.ntuples.zero?
error!('Tenant not found', 404)
end
tenant = result.first
# Enforce origin-based row-level security at the application layer
unless tenant['allowed_origin'] == request.env['HTTP_ORIGIN']
error!('Access denied for this origin', 403)
end
{ id: tenant['id'], name: tenant['name'] }
ensure
conn&.close
end
end
end
Second, implement a reusable CORS helper that references Cockroachdb to validate origins dynamically:
class CorsHelper
def self.validate_origin!(origin)
conn = PG.connect(
host: ENV['COCKROACHDB_HOST'],
port: ENV['COCKROACHDB_PORT'],
dbname: ENV['COCKROACHDB_DB'],
user: ENV['COCKROACHDB_USER'],
password: ENV['COCKROACHDB_PASSWORD'],
sslmode: 'require'
)
result = conn.exec_params('SELECT is_origin_allowed($1, $2)', [origin, 'grape-api'])
allowed = result.first['is_origin_allowed']
conn.close
raise(Grape::Errors::Forbidden, 'Origin not allowed') unless allowed
end
end
class MyAPI < Grape::API
before do
origin = request.env['HTTP_ORIGIN']
if origin
CorsHelper.validate_origin!(origin)
headers['Access-Control-Allow-Origin'] = origin
end
headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Authorization'
end
resource :public do
get 'status' do
{ status: 'ok' }
end
end
end
These examples ensure that CORS policy is explicit and that Cockroachdb participates in origin validation. Combine this with middleBrick scans to detect wildcard CORS and receive mapped remediation aligned with OWASP and compliance standards.
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 |