feat(crypto): Complete Phase 2 - Configuration-driven crypto architecture with 100% compliance

## Summary

This commit completes Phase 2 of the configuration-driven crypto architecture, achieving
100% crypto compliance by eliminating all hardcoded cryptographic implementations.

## Key Changes

### Phase 1: Plugin Loader Infrastructure
- **Plugin Discovery System**: Created StellaOps.Cryptography.PluginLoader with manifest-based loading
- **Configuration Model**: Added CryptoPluginConfiguration with regional profiles support
- **Dependency Injection**: Extended DI to support plugin-based crypto provider registration
- **Regional Configs**: Created appsettings.crypto.{international,russia,eu,china}.yaml
- **CI Workflow**: Added .gitea/workflows/crypto-compliance.yml for audit enforcement

### Phase 2: Code Refactoring
- **API Extension**: Added ICryptoProvider.CreateEphemeralVerifier for verification-only scenarios
- **Plugin Implementation**: Created OfflineVerificationCryptoProvider with ephemeral verifier support
  - Supports ES256/384/512, RS256/384/512, PS256/384/512
  - SubjectPublicKeyInfo (SPKI) public key format
- **100% Compliance**: Refactored DsseVerifier to remove all BouncyCastle cryptographic usage
- **Unit Tests**: Created OfflineVerificationProviderTests with 39 passing tests
- **Documentation**: Created comprehensive security guide at docs/security/offline-verification-crypto-provider.md
- **Audit Infrastructure**: Created scripts/audit-crypto-usage.ps1 for static analysis

### Testing Infrastructure (TestKit)
- **Determinism Gate**: Created DeterminismGate for reproducibility validation
- **Test Fixtures**: Added PostgresFixture and ValkeyFixture using Testcontainers
- **Traits System**: Implemented test lane attributes for parallel CI execution
- **JSON Assertions**: Added CanonicalJsonAssert for deterministic JSON comparisons
- **Test Lanes**: Created test-lanes.yml workflow for parallel test execution

### Documentation
- **Architecture**: Created CRYPTO_CONFIGURATION_DRIVEN_ARCHITECTURE.md master plan
- **Sprint Tracking**: Created SPRINT_1000_0007_0002_crypto_refactoring.md (COMPLETE)
- **API Documentation**: Updated docs2/cli/crypto-plugins.md and crypto.md
- **Testing Strategy**: Created testing strategy documents in docs/implplan/SPRINT_5100_0007_*

## Compliance & Testing

-  Zero direct System.Security.Cryptography usage in production code
-  All crypto operations go through ICryptoProvider abstraction
-  39/39 unit tests passing for OfflineVerificationCryptoProvider
-  Build successful (AirGap, Crypto plugin, DI infrastructure)
-  Audit script validates crypto boundaries

## Files Modified

**Core Crypto Infrastructure:**
- src/__Libraries/StellaOps.Cryptography/CryptoProvider.cs (API extension)
- src/__Libraries/StellaOps.Cryptography/CryptoSigningKey.cs (verification-only constructor)
- src/__Libraries/StellaOps.Cryptography/EcdsaSigner.cs (fixed ephemeral verifier)

**Plugin Implementation:**
- src/__Libraries/StellaOps.Cryptography.Plugin.OfflineVerification/ (new)
- src/__Libraries/StellaOps.Cryptography.PluginLoader/ (new)

**Production Code Refactoring:**
- src/AirGap/StellaOps.AirGap.Importer/Validation/DsseVerifier.cs (100% compliant)

**Tests:**
- src/__Libraries/__Tests/StellaOps.Cryptography.Plugin.OfflineVerification.Tests/ (new, 39 tests)
- src/__Libraries/__Tests/StellaOps.Cryptography.PluginLoader.Tests/ (new)

**Configuration:**
- etc/crypto-plugins-manifest.json (plugin registry)
- etc/appsettings.crypto.*.yaml (regional profiles)

**Documentation:**
- docs/security/offline-verification-crypto-provider.md (600+ lines)
- docs/implplan/CRYPTO_CONFIGURATION_DRIVEN_ARCHITECTURE.md (master plan)
- docs/implplan/SPRINT_1000_0007_0002_crypto_refactoring.md (Phase 2 complete)

## Next Steps

Phase 3: Docker & CI/CD Integration
- Create multi-stage Dockerfiles with all plugins
- Build regional Docker Compose files
- Implement runtime configuration selection
- Add deployment validation scripts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
master
2025-12-23 18:20:00 +02:00
parent b444284be5
commit dac8e10e36
241 changed files with 22567 additions and 307 deletions

View File

@@ -0,0 +1,243 @@
# StellaOps.Cryptography.Plugin.OfflineVerification
Cryptographic provider for offline/air-gapped environments using .NET BCL cryptography.
## Overview
The `OfflineVerificationCryptoProvider` wraps `System.Security.Cryptography` in the `ICryptoProvider` abstraction, enabling configuration-driven crypto while maintaining offline verification capabilities without external dependencies.
## Supported Algorithms
### Signing & Verification
- **ECDSA**: ES256 (P-256/SHA-256), ES384 (P-384/SHA-384), ES512 (P-521/SHA-512)
- **RSA PKCS1**: RS256, RS384, RS512
- **RSA-PSS**: PS256, PS384, PS512
### Content Hashing
- **SHA-2**: SHA-256, SHA-384, SHA-512 (supports both `SHA-256` and `SHA256` formats)
## When to Use
Use `OfflineVerificationCryptoProvider` when:
1. **Offline/Air-Gapped Environments**: Systems without network access or external cryptographic services
2. **Default Cryptography**: Standard NIST-approved algorithms without regional compliance requirements
3. **Container Scanning**: AirGap module, Scanner module, and other components that need deterministic signing
4. **Testing**: Local development and testing without hardware security modules
**Do NOT use when:**
- Regional compliance required (eIDAS, GOST R 34.10, SM2) - use specialized plugins instead
- FIPS 140-2 Level 3+ hardware security required - use HSM plugins
- Key management by external providers - use cloud KMS plugins (AWS KMS, Azure Key Vault, etc.)
## Usage
### Basic Hashing
```csharp
using StellaOps.Cryptography;
using StellaOps.Cryptography.Plugin.OfflineVerification;
var provider = new OfflineVerificationCryptoProvider();
var hasher = provider.GetHasher("SHA-256");
var hash = hasher.ComputeHash(data);
```
### Signing with Stored Keys
```csharp
var provider = new OfflineVerificationCryptoProvider();
// Add key to provider
var signingKey = new CryptoSigningKey(
reference: new CryptoKeyReference("my-key"),
algorithmId: "ES256",
privateParameters: ecParameters,
createdAt: DateTimeOffset.UtcNow);
provider.UpsertSigningKey(signingKey);
// Get signer and sign data
var signer = provider.GetSigner("ES256", new CryptoKeyReference("my-key"));
var signature = await signer.SignAsync(data);
```
### Ephemeral Verification (New in 1.0)
For scenarios where you only have a public key (e.g., DSSE verification, JWT verification):
```csharp
var provider = new OfflineVerificationCryptoProvider();
// Public key in SubjectPublicKeyInfo (DER-encoded) format
byte[] publicKeyBytes = ...; // From certificate, JWKS, or inline
// Create ephemeral verifier
var verifier = provider.CreateEphemeralVerifier("PS256", publicKeyBytes);
// Verify signature
var isValid = await verifier.VerifyAsync(message, signature);
```
**Supported Algorithms for Ephemeral Verification:**
- ECDSA: ES256, ES384, ES512
- RSA PKCS1: RS256, RS384, RS512
- RSA-PSS: PS256, PS384, PS512
**Key Format:**
- Public keys must be in **SubjectPublicKeyInfo** (SPKI) format (DER-encoded)
- This is the standard format used in X.509 certificates, JWKs, and TLS
### Dependency Injection
```csharp
services.AddStellaOpsCryptoFromConfiguration(configuration);
```
Ensure `etc/crypto-plugins-manifest.json` includes:
```json
{
"id": "offline-verification",
"name": "OfflineVerificationCryptoProvider",
"assembly": "StellaOps.Cryptography.Plugin.OfflineVerification.dll",
"type": "StellaOps.Cryptography.Plugin.OfflineVerification.OfflineVerificationCryptoProvider",
"capabilities": [
"signing:ES256", "signing:ES384", "signing:ES512",
"signing:RS256", "signing:RS384", "signing:RS512",
"signing:PS256", "signing:PS384", "signing:PS512",
"hashing:SHA-256", "hashing:SHA-384", "hashing:SHA-512",
"verification:ES256", "verification:ES384", "verification:ES512",
"verification:RS256", "verification:RS384", "verification:RS512",
"verification:PS256", "verification:PS384", "verification:PS512"
],
"jurisdiction": "world",
"compliance": ["NIST", "offline-airgap"],
"platforms": ["linux", "windows", "osx"],
"priority": 45,
"enabledByDefault": true
}
```
## API Reference
### ICryptoProvider.CreateEphemeralVerifier
```csharp
ICryptoSigner CreateEphemeralVerifier(string algorithmId, ReadOnlySpan<byte> publicKeyBytes)
```
Creates a verification-only signer from raw public key bytes. Useful for:
- DSSE envelope verification with inline public keys
- JWT/JWS verification without key persistence
- Ad-hoc signature verification in offline scenarios
**Parameters:**
- `algorithmId`: Algorithm identifier (ES256, RS256, PS256, etc.)
- `publicKeyBytes`: Public key in SubjectPublicKeyInfo format (DER-encoded)
**Returns:**
- `ICryptoSigner` instance with `VerifyAsync` support only
- `SignAsync` throws `NotSupportedException`
- `KeyId` returns `"ephemeral"`
- `AlgorithmId` returns the specified algorithm
**Throws:**
- `NotSupportedException`: If algorithm not supported or public key format invalid
## Implementation Details
### Internal Architecture
```
OfflineVerificationCryptoProvider (ICryptoProvider)
├── BclHasher (ICryptoHasher)
│ └── System.Security.Cryptography.SHA256/384/512
├── EcdsaSigner (ICryptoSigner)
│ └── System.Security.Cryptography.ECDsa
├── RsaSigner (ICryptoSigner)
│ └── System.Security.Cryptography.RSA
├── EcdsaEphemeralVerifier (ICryptoSigner)
│ └── System.Security.Cryptography.ECDsa (verification-only)
└── RsaEphemeralVerifier (ICryptoSigner)
└── System.Security.Cryptography.RSA (verification-only)
```
### Plugin Boundaries
**Allowed** within this plugin:
- Direct usage of `System.Security.Cryptography` (internal implementation)
- Creation of `ECDsa`, `RSA`, `SHA256`, `SHA384`, `SHA512` instances
- Key import/export operations
**Not allowed** outside this plugin:
- Direct crypto library usage in production code
- All consumers must use `ICryptoProvider` abstraction
This boundary is enforced by:
- `scripts/audit-crypto-usage.ps1` - Static analysis
- `.gitea/workflows/crypto-compliance.yml` - CI validation
## Testing
Run unit tests:
```bash
dotnet test src/__Libraries/__Tests/StellaOps.Cryptography.Plugin.OfflineVerification.Tests
```
**Test Coverage:**
- 39 unit tests covering all algorithms and scenarios
- Provider capability matrix validation
- Known-answer tests for SHA-256/384/512
- ECDSA and RSA signing/verification roundtrips
- Ephemeral verifier creation and usage
- Error handling (unsupported algorithms, tampered data)
## Performance
The abstraction layer is designed to be zero-cost:
- No heap allocations in hot paths
- Direct delegation to .NET BCL primitives
- `ReadOnlySpan<byte>` for memory efficiency
Benchmark results should match direct `System.Security.Cryptography` usage within measurement error.
## Security Considerations
1. **Key Storage**: This provider stores keys in-memory only. For persistent key storage, integrate with a key management system.
2. **Ephemeral Verification**: Public keys for ephemeral verification are not cached or validated against a trust store. Callers must perform their own trust validation.
3. **Algorithm Hardening**:
- RSA key sizes: 2048-bit minimum recommended
- ECDSA curves: Only NIST P-256/384/521 supported
- Hash algorithms: SHA-2 family only (SHA-1 explicitly NOT supported)
4. **Offline Trust**: In offline scenarios, establish trust through:
- Pre-distributed public key fingerprints
- Certificate chains embedded in airgap bundles
- Out-of-band key verification
## Compliance
- **NIST FIPS 186-4**: ECDSA with approved curves (P-256, P-384, P-521)
- **NIST FIPS 180-4**: SHA-256, SHA-384, SHA-512
- **RFC 8017**: RSA PKCS#1 v2.2 (RSASSA-PKCS1-v1_5 and RSASSA-PSS)
- **RFC 6979**: Deterministic ECDSA (when used with BouncyCastle fallback)
**Not compliant with:**
- eIDAS (European digital signature standards) - use eIDAS plugin
- GOST R 34.10-2012 (Russian cryptographic standards) - use CryptoPro plugin
- SM2/SM3/SM4 (Chinese cryptographic standards) - use SM plugin
## Related Documentation
- [Crypto Architecture Overview](../../../docs/modules/platform/crypto-architecture.md)
- [ICryptoProvider Interface](../StellaOps.Cryptography/CryptoProvider.cs)
- [Plugin Manifest Schema](../../../etc/crypto-plugins-manifest.json)
- [AirGap Module Architecture](../../../docs/modules/airgap/architecture.md)
## License
AGPL-3.0-or-later - See LICENSE file in repository root.