docs(rules): fix contradictions, update technical rules, enforce rule structure
CI / CI configuration security checks (pull_request) Successful in 2s
CI / Capabilities and shell quality (pull_request) Successful in 15s
CI / Python tests and compilation (pull_request) Successful in 36s
CI / QMD unit tests (pull_request) Successful in 7s
CI / Build and inspect generated packages (pull_request) Successful in 16s
CI / Bash integration and installation guards (pull_request) Failing after 51s
CI / PowerShell tests on Ubuntu (pull_request) Failing after 1m45s
CI / Installed client configuration smoke tests (pull_request) Canceled after 1m24s
CI / CI configuration security checks (pull_request) Successful in 2s
CI / Capabilities and shell quality (pull_request) Successful in 15s
CI / Python tests and compilation (pull_request) Successful in 36s
CI / QMD unit tests (pull_request) Successful in 7s
CI / Build and inspect generated packages (pull_request) Successful in 16s
CI / Bash integration and installation guards (pull_request) Failing after 51s
CI / PowerShell tests on Ubuntu (pull_request) Failing after 1m45s
CI / Installed client configuration smoke tests (pull_request) Canceled after 1m24s
- Resolve contradictions: authorization is never a skipped "boundary check"; one browser token policy (BFF/HttpOnly cookies first, RFC 10017); one sanitizer-bypass rule; Angular responses are unknown until validated. - Add security rules for AI/LLM integration and Java XXE, concrete crypto and password-hashing parameters, and RFC 8725 JWT validation. - Update version-dependent guidance after checking official sources: Angular 22, TypeScript 6/7, Node 24+, .NET 10/C# 14, JDK 21-25, Spring Boot 4; add a Spring Boot and Spring Security topic. - Give every rule a unique level-1 title and scope line, keep language security files to language specifics, and fix routing for inbound vs outbound HTTP, XML parsing, and WPF/Angular parent rules. - Validate rule structure and routing in validate-config.py, with tests. - Fix CI issues found by a local run: shellcheck directive order, pinned ruff rule set, Invoke-Python test mock, CRLF-tolerant package checks, Windows-only credential test, and refreshed prompt-budget baselines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
79694fbaa2
commit
6159c6373c
62 files changed
+453
-300
No files matched your search
@@ -10,5 +10,6 @@ For Java or JVM work, open only the topic rules relevant to the task. Follow the
|
||||
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
|
||||
| Performance | `references/performance.md` | `rules-java-performance` |
|
||||
| Security | `references/security.md` | `rules-java-security` |
|
||||
| Spring Boot and Spring Security | `references/spring.md` | `rules-java-spring` |
|
||||
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
|
||||
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Apply these rules when designing public APIs, service boundaries, or application structure.
|
||||
|
||||
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant checks through trusted internal code.
|
||||
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant format checks through trusted internal code; authorization, ownership, and tenant scoping are never such redundant checks.
|
||||
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
|
||||
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
|
||||
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
Apply these rules when changing executors, threads, futures, background work, or shared state.
|
||||
|
||||
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
|
||||
* Create one virtual thread per task (`Executors.newVirtualThreadPerTaskExecutor()`); never pool virtual threads. Limit downstream concurrency with a `Semaphore`, not with a fixed pool size.
|
||||
* On JDK 21 to 23, blocking inside `synchronized` pins the carrier thread; prefer `ReentrantLock` on hot blocking paths there. JDK 24+ (JEP 491) removes that pinning, but native frames and class initialization still pin.
|
||||
* Do not cache expensive objects in `ThreadLocal` when running on virtual threads. On JDK 25+, prefer `ScopedValue` (final, JEP 506) for request-scoped context.
|
||||
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
|
||||
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
|
||||
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
|
||||
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
|
||||
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
|
||||
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
|
||||
* Use preview concurrency APIs only when the project explicitly enables them for its target release.
|
||||
* Use preview concurrency APIs only when the project explicitly enables them for its target release; `StructuredTaskScope` is still a preview API in JDK 25.
|
||||
@@ -7,5 +7,5 @@ Apply these rules when handling external input, failures, resources, or logs.
|
||||
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
|
||||
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
|
||||
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
|
||||
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths.
|
||||
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. Pass untrusted values as parameters, never as the log format string, and strip or encode CR/LF in them unless the log format is structured.
|
||||
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
|
||||
@@ -1,12 +1,13 @@
|
||||
# Java Security
|
||||
|
||||
Apply these rules to security-sensitive Java code. Load the focused shared security rule for each affected boundary as well.
|
||||
Apply these rules to security-sensitive Java code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only Java specifics, and the Spring rule covers Spring Boot and Spring Security.
|
||||
|
||||
* Validate untrusted input before expensive work and authorize the specific resource and operation. Java types and client-side validation do not establish trust.
|
||||
* Use parameterized database APIs such as `PreparedStatement`. Select dynamic identifiers or sort expressions from a fixed allowlist; never concatenate untrusted data into SQL.
|
||||
* Resolve file paths against an authorized root and account for symlinks and replacement races when an attacker can change the filesystem. Limit file size and processing work.
|
||||
* Use `ProcessBuilder` with an executable and separate arguments; avoid shell interpretation. Restrict executable paths and validate attacker-controlled arguments.
|
||||
* Deserialize into explicit allowed types. Avoid native Java serialization and unrestricted polymorphic type activation for untrusted data; bound input size and nesting.
|
||||
* Use the platform's maintained TLS, cryptographic, and secure-random APIs. Do not disable certificate validation or build custom cryptography.
|
||||
* Keep secrets out of source, logs, exception messages, and serialized responses. Use approved secret storage and clear ownership for sensitive data.
|
||||
* Use context-appropriate encoding for HTML, XML, and other interpreters. Test rejected, malformed, oversized, unauthorized, and cross-tenant inputs where relevant.
|
||||
* Resolve file paths with `root.resolve(input).normalize()` and check containment with `Path.startsWith(root)`, never `String.startsWith`, which accepts `/data/app2` for `/data/app`. `normalize()` does not resolve symlinks; use `toRealPath()` when links matter and the file exists, and account for replacement races. Check every `ZipEntry` name the same way. Limit file size and processing work.
|
||||
* Use `ProcessBuilder` with an absolute executable path and separate arguments; avoid shell interpretation. On Windows, the argument list is flattened into one command line that the target re-parses, and `.bat` or `.cmd` targets run through `cmd.exe`; never pass untrusted arguments to them, and validate attacker-controlled arguments against an allowlist.
|
||||
* Parse untrusted XML with DTDs disabled (`http://apache.org/xml/features/disallow-doctype-decl` set to `true`), or, where DTDs are required, with external entities and external DTD and schema access disabled (`XMLConstants.ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_SCHEMA` set to `""`, `XMLConstants.FEATURE_SECURE_PROCESSING` enabled). Apply this to every factory that reads untrusted XML: `DocumentBuilderFactory`, `SAXParserFactory`, `XMLInputFactory`, `TransformerFactory`, `SchemaFactory`, and JAXB unmarshallers.
|
||||
* Deserialize into explicit allowed types and bound input size and nesting. Avoid native Java serialization for untrusted data; where it is unavoidable, install an `ObjectInputFilter` allowlist. With Jackson, never enable default typing (`activateDefaultTyping`) or `@JsonTypeInfo(use = Id.CLASS)` for untrusted input; use `Id.NAME` with registered subtypes or a strict `PolymorphicTypeValidator`. Spring Boot 4 uses Jackson 3 (`tools.jackson.*` packages; annotations stay in `com.fasterxml.jackson.annotation`). Load YAML with SnakeYAML 2.x or a `SafeConstructor`. Never evaluate untrusted SpEL, OGNL, or JNDI names.
|
||||
* Use the platform's maintained TLS, cryptographic, and secure-random APIs with the parameters in the shared cryptography rule. Always specify the full `Cipher` transformation, for example `AES/GCM/NoPadding`, because `Cipher.getInstance("AES")` means ECB. Use `SecureRandom`, never `java.util.Random`, for security values, and `MessageDigest.isEqual` for constant-time comparison. Never install trust-all `X509TrustManager` or `HostnameVerifier` implementations. Do not rely on the Security Manager; JDK 24+ disables it permanently.
|
||||
* For outbound URLs, parse with `java.net.URI` (the `URL` constructors are deprecated since JDK 20) and check every resolved `InetAddress` (`isLoopbackAddress`, `isLinkLocalAddress`, `isSiteLocalAddress`, `isAnyLocalAddress`, `isMulticastAddress`); these miss IPv6 unique-local `fc00::/7`, carrier-grade NAT `100.64.0.0/10`, and IPv4-mapped IPv6, so check those explicitly. Keep `java.net.http.HttpClient` on its default `Redirect.NEVER` or revalidate every hop.
|
||||
* For regular expressions on untrusted input, bound the input length first and avoid nested or overlapping quantifiers, because `java.util.regex` has no timeout; use RE2/J for untrusted patterns.
|
||||
* Encode output with the template engine's automatic escaping or the OWASP Java Encoder for the exact context; never build HTML, XML, LDAP, or JPQL from untrusted strings.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Java Spring Boot and Spring Security
|
||||
|
||||
Apply these rules when changing Spring Boot configuration, Spring Security, Spring MVC or WebFlux endpoints, Spring Data repositories, or Actuator exposure. Follow the project's Spring Boot and Spring Security versions; Spring Boot 4 and Spring Framework 7 are current.
|
||||
|
||||
* Deny by default: end the `authorizeHttpRequests` chain with `.anyRequest().authenticated()` (or `denyAll()`) and list public routes explicitly with `permitAll`.
|
||||
* Keep CSRF protection enabled for browser clients that authenticate with cookies or sessions. Disable it only for stateless token-authenticated APIs, and say why in the configuration.
|
||||
* Expose only `health` and `info` Actuator endpoints publicly. Never expose `env`, `heapdump`, `threaddump`, `configprops`, `loggers`, `mappings`, or `beans` without authentication; `heapdump` and `env` leak secrets. Prefer a separate management port.
|
||||
* Enforce method security (`@PreAuthorize` with `@EnableMethodSecurity`) on service methods reachable from non-HTTP entry points such as messaging, schedulers, or batch jobs.
|
||||
* Bind requests to dedicated DTOs, never directly to JPA entities with `@RequestBody` or `@ModelAttribute`, to prevent mass assignment. Validate DTOs with Bean Validation (`@Valid`).
|
||||
* Use parameter binding in JPQL, HQL, and `@Query` native SQL; never concatenate untrusted input into query strings. Select dynamic sort properties from an allowlist before building `Sort` objects.
|
||||
* Store passwords through a `DelegatingPasswordEncoder` with an encoder that meets the shared cryptography rule, for example `Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()`, and upgrade legacy hashes on login.
|
||||
* Keep secrets out of `application.yml` and profiles in the repository; bind them from environment variables or a secret store.
|
||||
Reference in new issue
Block a user