Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Enforce Generic Authorize Attribute with Typed Requirements for API Authorization: Additional Authorization Checks

These rules are ALWAYS ACTIVE for all API controller endpoints requiring authorization in the AdminConsole API surface, specifically all controllers in the Bit.Api.AdminConsole.Controllers namespace handling authenticated requests.

### Rules

- **R-AUTHZ-001** MAY: Additional authorization checks using ICurrentContext MAY be performed within endpoint methods for complex authorization logic that cannot be expressed declaratively.

### Verify

```bash
# Count Authorize<TRequirement> attributes in AdminConsole controllers
grep -r "\[Authorize<.*Requirement>\]" src/Api/AdminConsole/Controllers/ | wc -l

# Count public async Task methods without authorization attributes
grep -r "public async Task" src/Api/AdminConsole/Controllers/ | grep -v "\[Authorize" | grep -v "\[AllowAnonymous" | wc -l

# Count requirement classes in Authorization namespace
find src/Api/AdminConsole/Authorization -name "*Requirement.cs" | wc -l
```

**Accept when:**
- All controller methods in AdminConsole that access protected resources have either `[Authorize<TRequirement>]` or `[AllowAnonymous]` attributes
- All requirement classes are defined in Bit.Api.AdminConsole.Authorization namespace or subnamespaces and follow the Requirement naming suffix convention
- No controller methods use string-based `Authorize(Policy = "...")` attributes for authorization requirements
- Complex authorization logic split between declarative attributes and imperative ICurrentContext checks is documented with clear rationale

<enforcement>
Claude Code MUST NOT skip or defer verification. All controller methods must be audited for proper authorization attribute application. Violations must be flagged during code review and CI pipeline checks.
</enforcement>
38 changes: 38 additions & 0 deletions .actual/rules/cross-cutting-additional-cryptographic-key-c744.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Adopt FFI-Safe Cryptographic Key Generation with Memory Management in Rust SDK: Additional Cryptographic Key

These rules are ALWAYS ACTIVE for all cryptographic key generation functions exposed through C FFI boundaries in the Rust SDK, including all functions in `util/RustSdk/rust/src/lib.rs` that allocate or manipulate cryptographic material across language boundaries.

### Rules

- **R-FFI-CRYPTO-001** MAY: Additional cryptographic key generation functions MAY be added following the established FFI-safe pattern with paired allocation/deallocation.
- **R-FFI-CRYPTO-002** MUST: All new FFI functions that allocate memory must provide a corresponding `free_*` function and document the caller's responsibility to invoke it.
- **R-FFI-CRYPTO-003** MUST: Use `std::panic::catch_unwind` around `CString` conversions to prevent panics from crossing FFI boundaries, returning error codes instead.
- **R-FFI-CRYPTO-004** MUST: Validate all input parameters at the FFI boundary before passing to internal cryptographic functions, checking for null pointers and invalid lengths.
- **R-FFI-CRYPTO-005** SHOULD: Maintain test mocks for cipher and rsa_keys components that cover edge cases including invalid inputs, memory exhaustion, and concurrent access patterns.
- **R-FFI-CRYPTO-006** SHOULD: Maintain integration tests that exercise real cryptographic implementations alongside unit tests with mocks, and regularly audit mock behavior against production.

### Verify

```bash
# Verify all public FFI functions for key generation use c_char pointers with CString/CStr conversions
grep -r 'pub.*extern.*fn.*generate.*keys' util/RustSdk/rust/src/lib.rs | grep -c 'c_char'

# Verify free_c_string function exists in the public API for memory deallocation
grep -c 'free_c_string' util/RustSdk/rust/src/lib.rs

# Verify std::ffi types are imported and used for FFI boundary operations
grep -r 'use std::ffi::{c_char, CStr, CString}' util/RustSdk/rust/src/lib.rs
```

**Accept when:**
- All public FFI functions for key generation use `c_char` pointers with `CString`/`CStr` conversions
- A `free_c_string` function exists in the public API for memory deallocation
- `std::ffi` types are imported and used for FFI boundary operations
- All FFI functions that allocate memory have paired deallocation functions
- `CString` conversions include error handling via `std::panic::catch_unwind` or equivalent
- Input validation is performed at FFI boundaries before passing to cryptographic functions
- Test infrastructure includes mocks for cipher and rsa_keys components with edge case coverage

<enforcement>
Claude Code MUST NOT skip or defer verification. Code review of all FFI boundary functions must verify paired allocation/deallocation. Static analysis must detect `CString` conversions without corresponding error handling. Memory leak detection in CI using valgrind or similar tools on FFI integration tests is mandatory. FFI functions without paired deallocation functions must be rejected in code review. Memory leaks detected in CI must block merge until resolved. Panics at FFI boundaries must be converted to error returns before production deployment.
</enforcement>
36 changes: 36 additions & 0 deletions .actual/rules/cross-cutting-additional-diagnostic-context-304d.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Log Redis Connection Failures in Distributed Cache Extensions: Additional Diagnostic Context

These rules are ALWAYS ACTIVE for all cache service registration extensions and distributed cache initialization code that uses StackExchangeRedis or ConnectionMultiplexer.Connect operations.

### Rules

- **R-REDIS-001** MUST: Wrap all ConnectionMultiplexer.Connect calls in try-catch blocks within cache service registration extensions.
- **R-REDIS-002** MUST: Log connection failures using ILogger.LogError with the exception as the first parameter and structured logging syntax for cache name: `logger.LogError(ex, "Failed to connect to Redis for cache {CacheName}", cacheName)`.
- **R-REDIS-003** MUST: Ensure ILogger instances are injected into service collection extension methods via IServiceProvider or factory patterns.
- **R-REDIS-004** MAY: Include additional diagnostic context such as connection string (sanitized) or retry attempts in error logs.
- **R-REDIS-005** SHOULD: Consider adding correlation IDs or request context to error logs for distributed tracing integration.
- **R-REDIS-006** MUST: Sanitize connection strings before logging to avoid credential leakage in logs.

### Verify

```bash
# Verify Redis connection error logging is present
grep -r 'LogError.*Failed to connect to Redis' src/

# Count ConnectionMultiplexer.Connect calls wrapped with try-catch
grep -r 'ConnectionMultiplexer\.Connect' src/ | grep -c 'try\|catch'

# Run cache initialization tests with detailed logging
dotnet test --filter Category=CacheInitialization --logger "console;verbosity=detailed"
```

**Accept when:**
- All Redis connection attempts in cache service registration extensions are wrapped with try-catch blocks that log errors using ILogger.LogError
- Error log statements include structured parameters for cache name and exception details
- Unit tests verify that connection failures produce expected log entries with correct log levels and parameters
- Connection strings are sanitized and do not contain credentials in log output
- ILogger instances are properly injected and configured before cache service registration

<enforcement>
Claude Code MUST NOT skip or defer verification. All Redis connection initialization code MUST include error logging with structured context. Static analysis rules detecting ConnectionMultiplexer.Connect calls without surrounding try-catch blocks are treated as build failures in CI pipeline.
</enforcement>
49 changes: 49 additions & 0 deletions .actual/rules/cross-cutting-additional-fake-keys-c692.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Use Embedded Fake RSA Keys for Testing Public API Protocols: Additional Fake Keys

These rules are ALWAYS ACTIVE for all test code that exercises cryptographic operations in public API protocols, including unit tests, integration tests, protocol validation tests, and build-time test execution in the Rust SDK module and C# interop test suites.

### Rules

- **R-FAKE-RSA-001** MAY: Additional fake keys beyond the initial set MAY be added following the sequential naming convention (_FAKE_RSA_KEY_5, _FAKE_RSA_KEY_6, etc.) as test scenarios require.

- **R-FAKE-RSA-002** MUST: All fake RSA keys MUST be embedded as const string literals containing full PEM-encoded 2048-bit RSA private keys in the test fixtures module (e.g., src/test_fixtures/rsa_keys.rs).

- **R-FAKE-RSA-003** MUST: Fake RSA keys MUST NEVER appear in production source files, production code paths, or non-test modules; static analysis MUST verify this constraint.

- **R-FAKE-RSA-004** MUST: Each fake key constant MUST include a comment header explicitly stating it is a test fixture and must never be used in production.

- **R-FAKE-RSA-005** SHOULD: Fake keys SHOULD use zero-indexed sequential naming (_FAKE_RSA_KEY_0, _FAKE_RSA_KEY_1, etc.) with documented purpose if representing specific test scenarios (e.g., _FAKE_RSA_KEY_EXPIRED for expiration testing).

- **R-FAKE-RSA-006** MUST: All test code using RSA operations MUST reference _FAKE_RSA_KEY_N constants from the standardized test fixtures module.

- **R-FAKE-RSA-007** MUST: C# test code consuming the Rust SDK via csbindgen MUST use identical fake key material as Rust tests, either by copying keys to a C# test fixture class or by calling Rust test helper functions that return the fake keys.

- **R-FAKE-RSA-008** MUST: At least 5 distinct fake RSA keys MUST be available in the test fixtures module to support multi-party protocols, key rotation simulation, and edge case testing.

### Verify

```bash
# Verify no fake keys appear in production code (outside test modules)
grep -r '_FAKE_RSA_KEY_' util/RustSdk/rust/src/ --include='*.rs' | grep -v 'test' | grep -v 'rsa_keys.rs' || echo 'No fake keys in production code'

# Verify RSA key tests pass
cargo test --package rust-sdk --lib rsa_keys -- --nocapture 2>&1 | grep -q 'test result: ok' && echo 'RSA key tests pass'

# Verify minimum 5 fake keys exist
grep -c 'BEGIN PRIVATE KEY' util/RustSdk/rust/src/rsa_keys.rs | awk '$1 >= 5 {print "Found " $1 " fake keys (minimum 5 required)"}'

# Verify fake key naming convention
grep '_FAKE_RSA_KEY_[0-9]' util/RustSdk/rust/src/rsa_keys.rs | wc -l | awk '$1 >= 5 {print "Naming convention verified"}'
```

**Accept when:**
- All test code using RSA operations references _FAKE_RSA_KEY_N constants and no fake key patterns appear in production source files
- At least 5 distinct fake RSA keys are available in the test fixtures module with sequential naming
- All tests exercising FFI-exposed cryptographic functions pass using the fake keys
- C# interop tests can successfully use the same key material as Rust tests
- Static analysis confirms no _FAKE_RSA_KEY_ patterns exist outside test modules
- Each fake key constant includes a comment header identifying it as a test fixture

<enforcement>
Claude Code MUST NOT skip or defer verification. All verify commands MUST execute successfully before accepting this rule as satisfied. Static analysis checks for _FAKE_RSA_KEY_ pattern usage outside test modules MUST pass in CI. Code review MUST verify that cryptographic tests use standardized fake keys and follow the naming convention.
</enforcement>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Enforce Generic Authorize Attribute with Typed Requirements for API Authorization: Adminconsole Controller Endpoints

These rules are ALWAYS ACTIVE for all API controller endpoints requiring authorization in the AdminConsole API surface, specifically all controllers in the Bit.Api.AdminConsole.Controllers namespace and HTTP verb-decorated methods (HttpGet, HttpPost, HttpPut, HttpDelete) that handle authenticated requests.

### Rules

- **R-ADMINCONSOLE-001** MUST: All AdminConsole API controller endpoints that require authorization MUST use the generic `Authorize<TRequirement>` attribute with a typed requirement class.
- **R-ADMINCONSOLE-002** MUST: All authorization requirement classes MUST be defined in `Bit.Api.AdminConsole.Authorization` namespace or subnamespaces and follow the `Requirement` naming suffix convention (e.g., `ManageUsersRequirement`, `ManagePoliciesRequirement`).
- **R-ADMINCONSOLE-003** MUST: Controller methods MUST NOT use string-based `Authorize(Policy = "...")` attributes for authorization requirements.
- **R-ADMINCONSOLE-004** MUST: Public endpoints explicitly marked with `AllowAnonymous` MUST be documented to indicate intentional bypass of authorization.
- **R-ADMINCONSOLE-005** SHOULD: Apply `[Authorize("Application")]` at the controller class level to enforce base authentication, then apply `[Authorize<TRequirement>]` at the method level for specific authorization requirements.
- **R-ADMINCONSOLE-006** SHOULD: For endpoints requiring multiple authorization checks, combine declarative `Authorize<TRequirement>` attributes with imperative `ICurrentContext` checks, documenting the rationale for imperative checks.
- **R-ADMINCONSOLE-007** MAY: Endpoints that validate tokens or provide pre-authentication information (e.g., `GetByToken` in `PoliciesController`) are excepted from this rule (EXC-001).
- **R-ADMINCONSOLE-008** MAY: Deprecated endpoints maintaining backward compatibility (e.g., `PostDelete` methods) are excepted from this rule (EXC-002).

### Verify

```bash
# Count Authorize<TRequirement> attributes in AdminConsole controllers
grep -r "\[Authorize<.*Requirement>\]" src/Api/AdminConsole/Controllers/ | wc -l

# Count public async methods without authorization attributes
grep -r "public async Task" src/Api/AdminConsole/Controllers/ | grep -v "\[Authorize" | grep -v "\[AllowAnonymous" | wc -l

# Count requirement classes defined in Authorization namespace
find src/Api/AdminConsole/Authorization -name "*Requirement.cs" | wc -l

# Check for string-based Authorize(Policy = "...") usage
grep -r "Authorize(Policy" src/Api/AdminConsole/Controllers/ | wc -l
```

**Accept when:**
- All controller methods in AdminConsole that access protected resources have either `[Authorize<TRequirement>]` or `[AllowAnonymous]` attributes
- All requirement classes are defined in `Bit.Api.AdminConsole.Authorization` namespace or subnamespaces and follow the `Requirement` naming suffix convention
- No controller methods use string-based `Authorize(Policy = "...")` attributes for authorization requirements
- Public endpoints explicitly marked with `AllowAnonymous` are documented with security rationale

<enforcement>
Claude Code MUST NOT skip or defer verification. All new or modified AdminConsole controller endpoints MUST be verified against these rules before approval. Static analysis during CI pipeline MUST fail if controller methods lack proper authorization attributes. Code review MUST block merge until authorization attributes are properly applied.
</enforcement>
37 changes: 37 additions & 0 deletions .actual/rules/cross-cutting-authentication-failure-tests-625a.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Standardize JSON Assertion Patterns in OAuth Token Endpoint Integration Tests: Authentication Failure Tests

These rules are ALWAYS ACTIVE for all integration tests in the Identity.IntegrationTest project that validate OAuth /connect/token endpoint responses, including password grant, SSO authorization code flow, and trusted device encryption scenarios.

### Rules

- **R-AUTH-FAIL-001** MUST: Authentication failure tests MUST validate specific error message content using Assert.Equal with expected error strings (e.g., 'Username or password is incorrect. Try again.' and 'auth request flow unsupported on unknown device').
- **R-AUTH-FAIL-002** MUST: Use System.Text.Json.JsonDocument for parsing HTTP response content and validate JsonValueKind before property access.
- **R-AUTH-FAIL-003** MUST: Structure assertions to validate JsonValueKind.Object for complex properties, then extract and assert on nested values using GetProperty() methods.
- **R-AUTH-FAIL-004** MUST: Construct token requests using FormUrlEncodedContent with Dictionary<string, string> containing all required OAuth parameters (scope, client_id, grant_type, device information).
- **R-AUTH-FAIL-005** SHOULD: For SSO and trusted device encryption flows, validate userDecryptionOptions object presence and structure in addition to standard token response properties.

### Verify

```bash
# Check for System.Text.Json usage in integration tests
grep -r 'using System.Text.Json' test/Identity.IntegrationTest/ --include='*Tests.cs' | wc -l

# Verify JsonValueKind.Object assertions are present
grep -r 'JsonValueKind.Object' test/Identity.IntegrationTest/ --include='*Tests.cs'

# Check for Assert.Equal error message validation patterns
grep -r 'Assert.Equal.*error' test/Identity.IntegrationTest/RequestValidation/ --include='*Tests.cs'

# Run integration tests for OAuth token endpoint validation
dotnet test test/Identity.IntegrationTest/ --filter 'FullyQualifiedName~ResourceOwnerPasswordValidatorTests|FullyQualifiedName~IdentityServerSsoTests' --no-build
```

**Accept when:**
- System.Text.Json using statements are present in integration test files testing /connect/token endpoints
- JsonValueKind.Object assertions precede property extraction for complex JSON response objects
- Integration tests for authentication failures validate specific error message content with Assert.Equal
- All integration tests for OAuth token endpoints pass successfully with JSON assertion patterns in place

<enforcement>
Claude Code MUST NOT skip or defer verification. Code review of integration test pull requests MUST check for System.Text.Json usage and JsonValueKind assertions. CI pipeline execution of Identity.IntegrationTest suite MUST validate test pass rates. Pull requests introducing integration tests without proper JSON validation patterns MUST be flagged in code review. Test failures due to missing or incorrect JSON assertions MUST block merge until corrected.
</enforcement>
Loading
Loading