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
@@ -2,10 +2,11 @@
|
||||
|
||||
Apply these rules when designing public APIs, service boundaries, or application architecture.
|
||||
|
||||
* Give APIs explicit, strongly typed contracts. Keep trusted internal paths free of checks already done at the boundary.
|
||||
* Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed. Authorization, resource ownership, and tenant scoping are never "already done": enforce them at the operation that accesses the data.
|
||||
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
|
||||
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
|
||||
* Use explicit, bounded pagination for potentially large collections.
|
||||
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries, and use `FromSql` or `FromSqlInterpolated` instead of concatenating into `FromSqlRaw`.
|
||||
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
|
||||
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
|
||||
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
|
||||
@@ -5,9 +5,11 @@ Apply these rules when adding or changing asynchronous APIs, background work, or
|
||||
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
|
||||
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
|
||||
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
|
||||
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use an appropriate queue or concurrency limiter when work must be throttled.
|
||||
* Use `ValueTask` only when profiling supports it and its usage contract is clear; otherwise prefer `Task`.
|
||||
* In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread.
|
||||
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`.
|
||||
* Use `ValueTask` only when profiling supports it. Await a `ValueTask` exactly once, never concurrently, and never read `.Result` before it completes; otherwise prefer `Task`.
|
||||
* Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation.
|
||||
* Avoid holding locks across `await`, blocking thread-pool threads, and starting background work whose lifetime is detached from its owner.
|
||||
* For producer/consumer work, apply backpressure and bound buffered items so a fast producer cannot exhaust memory.
|
||||
* Retry only transient failures, with bounded attempts and delay. Preserve idempotency and cancellation, and avoid multiplying retries across nested layers.
|
||||
* For synchronous locks on .NET 9+, prefer `System.Threading.Lock` over locking on `object`. Use `SemaphoreSlim` when a critical section contains `await`. Avoid blocking thread-pool threads and starting background work whose lifetime is detached from its owner.
|
||||
* For producer/consumer work, use `Channel.CreateBounded` so a fast producer gets backpressure and cannot exhaust memory.
|
||||
* Retry only transient failures, with bounded attempts and delay, in one layer only. Prefer the project's resilience library (`Microsoft.Extensions.Http.Resilience` or Polly v8) over hand-written loops. Preserve idempotency and cancellation.
|
||||
* Create `HttpClient` through `IHttpClientFactory` or reuse a long-lived instance with `SocketsHttpHandler.PooledConnectionLifetime`; never create one per request.
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
Apply these rules when editing C# syntax, class structure, and everyday code organization.
|
||||
|
||||
* Follow current C# and .NET conventions and the style already used in the project.
|
||||
* Prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
|
||||
* Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net10.0` defaults to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
|
||||
* Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
|
||||
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
|
||||
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
|
||||
* Avoid unnecessary wrappers, abstractions, reflection, runtime type checks, and global mutable state.
|
||||
|
||||
@@ -6,8 +6,8 @@ Apply these rules when handling external input, failures, logs, or sensitive inf
|
||||
* Validate size, range, format, and allowed values before expensive parsing or allocation. Keep validation consistent with downstream business and security constraints.
|
||||
* Fail fast for invalid arguments or impossible state. Do not use exceptions for routine control flow or swallow unexpected exceptions.
|
||||
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
|
||||
* Use structured logging and avoid excessive logging, especially in hot paths. Never log credentials, tokens, or sensitive payloads.
|
||||
* Dispose owned resources correctly, including on failure paths.
|
||||
* Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads.
|
||||
* Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container.
|
||||
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
|
||||
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
|
||||
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
|
||||
@@ -1,13 +1,12 @@
|
||||
# C# Security
|
||||
|
||||
Apply these rules when implementing or reviewing security-sensitive .NET code. Load the matching shared security rule for the affected API, identity, data, file, network, cryptographic, or dependency boundary as well.
|
||||
Apply these rules when implementing or reviewing security-sensitive .NET code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only .NET specifics.
|
||||
|
||||
* Use parameterized database APIs. If a query identifier or sort expression cannot be parameterized, select it from a fixed allowlist; never concatenate untrusted input into SQL.
|
||||
* For file access, canonicalize the resolved path and verify it remains inside the authorized root. Account for reparse points and symlinks when the attacker can affect directory contents.
|
||||
* For process execution, avoid a shell. Pass executable and arguments separately using APIs supported by the target framework, validate each argument, and restrict executable paths.
|
||||
* Deserialize into explicit DTOs or allowlisted types. Avoid unsafe polymorphic type activation and unbounded object graphs for untrusted data.
|
||||
* Apply timeouts to regular expressions that evaluate untrusted input and prefer patterns with predictable complexity.
|
||||
* Keep secrets in an approved secret store or protected configuration source. Never embed them in assemblies, client bundles, or source.
|
||||
* Use platform TLS and established cryptographic APIs. Do not create custom cryptography or disable certificate validation; use cryptographically secure randomness for security tokens.
|
||||
* Use framework output encoding and safe APIs for HTML, XML, and other interpreters. Do not build executable markup or queries from untrusted strings.
|
||||
* Review security-sensitive changes with tests for rejected, malformed, oversized, unauthenticated, and cross-tenant inputs, as applicable.
|
||||
* Use parameters with ADO.NET (`SqlParameter`) and EF Core (`FromSql` or `FromSqlInterpolated`, never concatenation into `FromSqlRaw` or `ExecuteSqlRaw`). Select dynamic identifiers and sort expressions from a fixed allowlist.
|
||||
* Resolve file paths with `Path.GetFullPath(Path.Combine(root, input))` and require the result to start with the root plus a trailing directory separator, using `StringComparison.OrdinalIgnoreCase` on Windows. Account for reparse points and symlinks when the attacker can affect directory contents.
|
||||
* For process execution, set `ProcessStartInfo.UseShellExecute = false` explicitly (its default is `true` on .NET Framework), start the executable by absolute path, and pass arguments through `ArgumentList` (.NET Core 2.1+). On .NET Framework, build `Arguments` with correct Windows argument escaping instead of ad-hoc quoting. Never pass untrusted arguments to `.bat` or `.cmd` targets, because `cmd.exe` re-parses them; validate each argument against an allowlist.
|
||||
* Deserialize into explicit DTOs or allowlisted types. Prefer `System.Text.Json` and allow polymorphism only through registered `[JsonDerivedType]` types. For untrusted data never use `BinaryFormatter` (it throws since .NET 9; do not restore it through the unsupported compatibility package), `NetDataContractSerializer`, `SoapFormatter`, `LosFormatter`, or Newtonsoft.Json `TypeNameHandling` other than `None`. Bound object-graph depth and size.
|
||||
* For regular expressions on untrusted input on .NET 7+, use `RegexOptions.NonBacktracking` when the pattern needs no backreferences or lookarounds; otherwise pass an explicit match timeout, because there is none by default. Declare regexes with `[GeneratedRegex]` on .NET 7+.
|
||||
* Use `RandomNumberGenerator` for security values and `CryptographicOperations.FixedTimeEquals` for comparing secrets. Never return `true` unconditionally from `ServerCertificateCustomValidationCallback` or `RemoteCertificateValidationCallback`.
|
||||
* Keep secrets in user secrets during development and in a secret store such as Azure Key Vault in deployed environments; use ASP.NET Core Data Protection for application-level protection of payloads. Never embed secrets in assemblies or client bundles.
|
||||
* Use Razor's automatic encoding and `System.Text.Encodings.Web` encoders; avoid `Html.Raw` and `MarkupString` with untrusted content.
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
Apply these rules when changing tests, package references, analyzers, or build diagnostics.
|
||||
|
||||
* Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, current time, or uncontrolled external services.
|
||||
* Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, or uncontrolled external services. Inject `TimeProvider` (.NET 8+) instead of reading `DateTime.Now`, and use `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing` in tests.
|
||||
* Make code testable through clear contracts and dependencies; do not add production hooks or abstractions solely for tests without a concrete need.
|
||||
* Prefer the .NET BCL and existing supported packages over new libraries when they solve the problem adequately.
|
||||
* Treat compiler, analyzer, and nullable warnings seriously. Suppress a diagnostic only for a specific, documented reason and narrow the suppression to the affected code.
|
||||
* Include analyzers in the verification of the changed path.
|
||||
* Build the changed projects with analyzers enabled and warnings visible. Where the project sets `TreatWarningsAsErrors`, `AnalysisLevel`, or `EnforceCodeStyleInBuild`, never lower them to get a green build, and respect `.editorconfig`.
|
||||
* Add or update packages through Central Package Management (`Directory.Packages.props`) when the repository uses it. Keep NuGetAudit enabled; it audits transitive packages by default only for `net10.0`+ projects, so prefer `NuGetAuditMode` `all` for older targets when the project allows it.
|
||||
@@ -5,7 +5,7 @@ Apply these rules when designing type contracts, choosing collection shapes, or
|
||||
* Prefer strongly typed models over `object`, `dynamic`, loosely typed dictionaries, or string-based contracts.
|
||||
* Write null-safe code: enable nullable reference types where supported, model nullability accurately, and check nullable values before dereferencing them. Avoid null-forgiving operators unless a nearby invariant proves the value cannot be null.
|
||||
* Prefer concrete collection types for internal parameters, properties, and local APIs when the contract does not need abstraction.
|
||||
* Expose collection interfaces such as `IReadOnlyList<T>`, `IEnumerable<T>`, `IDictionary<TKey, TValue>`, or `ICollection<T>` only when their capability is part of an intentional boundary or public contract.
|
||||
* At public boundaries, return read-only shapes (`IReadOnlyList<T>`, `IReadOnlyDictionary<TKey, TValue>`, or `ReadOnlyCollection<T>`) and accept the least capable interface the method needs (`IEnumerable<T>` or `IReadOnlyCollection<T>`). Expose mutable interfaces such as `IList<T>` or `IDictionary<TKey, TValue>` only when callers must mutate. Consider `FrozenDictionary` or `FrozenSet` (.NET 8+) for read-mostly lookups.
|
||||
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
|
||||
* Avoid large mutable structs and direct exposure of mutable internal collections.
|
||||
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
|
||||
Reference in new issue
Block a user