Cors Wildcard in Spring Boot with Cockroachdb
Cors Wildcard in Spring Boot with Cockroachdb — how this specific combination creates or exposes the vulnerability
A CORS wildcard in Spring Boot with a CockroachDB backend can unintentionally expose both data and control flow when credentials or sensitive headers are involved. In Spring Boot, a configuration such as @CrossOrigin(origins = "*") on a controller that queries CockroachDB allows any origin to make requests with cookies or authorization headers if allowCredentials is set to true. This combination violates the principle that wildcards and credentials should never be used together, as browsers will send cookies for cross-origin requests, potentially exposing data belonging to users authenticated against your CockroachDB instance.
When a frontend hosted on an untrusted origin calls an endpoint that returns rows from CockroachDB, the wildcard permits the browser to accept the response. If the response includes sensitive data or authentication tokens, and the request includes credentials, an attacker can craft a malicious page that reads or triggers actions on behalf of the victim. This is especially risky if session tokens or user identifiers are stored in cookies and your CockroachDB queries do not enforce origin-level checks.
Moreover, preflight requests triggered by non-simple requests (e.g., custom headers or non-GET/POST methods) can cause repeated OPTIONS calls to your Spring Boot application. If CORS mappings are broad and not tied to specific origins, these preflight responses may reveal the existence of endpoints and the structure of your API, aiding reconnaissance against your CockroachDB service. Attackers can use this information to design targeted injection or authorization bypass attempts.
Spring Boot’s CORS configuration interacts with security filters, and a misconfigured global CORS configuration can override more restrictive method-level annotations. If your application relies on role-based access control for CockroachDB queries but CORS allows any origin, an attacker may exploit the mismatch to bypass intended restrictions by sending requests from a permitted origin that should otherwise be blocked.
To assess the impact, scanners perform unauthenticated checks against the endpoint, looking for the presence of wildcard origins alongside exposed endpoints. Findings typically highlight the risk of data exposure and the potential for unauthorized access when credentials are involved, aligning with common weaknesses in API security such as broken object level authorization (BOLA) when combined with permissive CORS settings.
Cockroachdb-Specific Remediation in Spring Boot — concrete code fixes
Remediation focuses on tightening CORS configuration and ensuring that database access respects the same origin and authorization constraints. Avoid using a wildcard for origins when credentials are required. Instead, explicitly list trusted origins and configure Spring Security’s CORS support to align with CockroachDB access policies.
Explicit Origins with Credentials
Define a specific origin or set of origins in your Spring Boot configuration. Here is a Java configuration example:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("https://trusted.example.com", "https://app.example.com"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With"));
config.setExposedHeaders(Arrays.asList("X-Total-Count"));
config.setAllowCredentials(true);
return config;
}));
http.csrf().disable();
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
return http.build();
}
}
This ensures that only specified origins can make authenticated requests to endpoints that query CockroachDB, reducing the risk of unauthorized cross-origin access.
CockroachDB Repository with Row-Level Security Checks
In your repository, enforce user context to prevent unauthorized data access. Use Spring Data JPA or JDBC templates with parameterized queries to avoid injection and ensure each query respects the authenticated user. Example using JdbcTemplate:
@Repository
public class UserDataRepository {
private final JdbcTemplate jdbcTemplate;
public UserDataRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<UserProfile> findProfilesByUser(String requesterId) {
String sql = "SELECT id, email, name FROM user_profiles WHERE user_id = $1 AND tenant_id = (SELECT tenant_id FROM users WHERE id = $2)";
return jdbcTemplate.query(sql, new Object[]{requesterId, requesterId}, (rs, rowNum) -> {
UserProfile profile = new UserProfile();
profile.setId(rs.getString("id"));
profile.setEmail(rs.getString("email"));
profile.setName(rs.getString("name"));
return profile;
});
}
}
The SQL uses positional parameters ($1, $2) compatible with CockroachDB, ensuring that users can only access data tied to their tenant and identity. This approach mitigates BOLA risks even when CORS is properly restricted.
CORS and Global Configuration Discipline
Avoid a global CORS configuration that applies to all controllers. If you must define a global rule, ensure it does not permit credentials with wildcards. Prefer method-level annotations for fine-grained control:
@RestController
@RequestMapping("/api/users")
public class UserController {
@CrossOrigin(origins = {"https://trusted.example.com"}, allowCredentials = "true")
@GetMapping("/{id}")
public ResponseEntity<UserDto> getUser(@PathVariable String id, @AuthenticationPrincipal String userId) {
UserDto dto = userService.fetchById(id, userId);
return ResponseEntity.ok(dto);
}
}
Combining explicit origins, parameterized CockroachDB queries, and method-level CORS ensures that your API remains secure by default and that sensitive data is not inadvertently exposed to any origin.
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 |