github.com/jasoet/gopki@v1.15.0/CLAUDE.md (about) 1 # CLAUDE.md 2 3 This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. 4 5 ## Project Overview 6 7 GoPKI is a production-ready Go library for PKI (Public Key Infrastructure) operations that emphasizes **type-safe cryptography through Go generics**. The library provides comprehensive cryptographic functionality with 80.3% test coverage across 844+ tests and strict type safety throughout all APIs. 8 9 **Key Characteristics:** 10 - **Type-Safe Design**: Uses Go generics to eliminate `any`/`interface{}` types in core APIs 11 - **Security-First**: Enforces minimum key sizes, secure file permissions, and cryptographic best practices 12 - **Standards Compliant**: Full support for X.509, PKCS#7/CMS, PKCS#12, SSH formats 13 - **Production Ready**: Comprehensive testing, CI/CD pipeline, and semantic versioning 14 15 ## Development Commands 16 17 ### Using Taskfile (Recommended) 18 19 The project uses a comprehensive Taskfile for all development operations. Install Task from https://taskfile.dev/installation/ 20 21 ```bash 22 # Setup and Dependencies 23 task setup # Initial project setup and dependency verification 24 task # Show all available tasks 25 26 # Testing (Primary Development Commands) 27 task test # Run all tests with race detection (80.3% coverage) 28 task test:verbose # Verbose test output with detailed results 29 task test:coverage # Generate HTML coverage report 30 task test:specific -- TestName # Run specific test by name 31 32 # Code Quality and Analysis 33 task format # Format all Go code (go fmt) 34 task format:check # Verify code formatting without changes 35 task lint # Basic linting with go vet 36 task lint:full # Comprehensive linting with golangci-lint 37 task lint:security # Security-focused linting (gosec, ineffassign) 38 task deadcode # Find unused/dead code 39 task unused:all # Run all unused code detection tools 40 41 # Building and Examples 42 task build # Build the entire module 43 task build:examples # Build example binaries with 'example' build tag 44 task examples:run # Run all examples sequentially 45 task examples:keypair # Run keypair examples only 46 task examples:certificates # Run certificate examples only 47 task examples:signing # Run signing examples only 48 task examples:encryption # Run encryption examples only 49 50 # Module Management 51 task mod:verify # Verify module dependencies 52 task mod:tidy # Clean up dependencies 53 task mod:update # Update all dependencies to latest versions 54 55 # Cleanup Operations 56 task clean # Clean build artifacts and generated files 57 task clean:cache # Clean Go build and test cache 58 task clean:all # Clean everything including module cache 59 task examples:clean # Clean example output directories 60 61 # CI/CD Pipeline 62 task ci # Run complete CI pipeline locally 63 task ci:full # Comprehensive CI with all checks and examples 64 task pre-commit # Pre-commit checks (format, lint, basic tests) 65 task release:check # Check if ready for release 66 67 # Documentation and Development 68 task docs:generate # Generate API documentation 69 task docs:serve # Start godoc server on http://localhost:6060 70 task git:status # Show git status and current branch 71 task git:commit -- "message" # Commit with standardized message format 72 ``` 73 74 ### Manual Commands (Fallback) 75 76 If Taskfile is unavailable, use these manual commands: 77 78 ```bash 79 # Core Testing 80 go test ./... -race -coverprofile=coverage.out 81 go tool cover -html=coverage.out -o coverage.html 82 83 # Building 84 go build ./... 85 go mod verify && go mod tidy 86 87 # Code Quality 88 go fmt ./... 89 go vet ./... 90 91 # Examples (with build tags) 92 go run -tags example ./examples/keypair/main.go 93 go run -tags example ./examples/certificates/main.go 94 go run -tags example ./examples/signing/main.go 95 go run -tags example ./examples/encryption/main.go 96 ``` 97 98 ## Architecture Overview 99 100 GoPKI provides a **type-safe, generic-first approach** to PKI operations. The library is structured as five core modules with strong type relationships and comprehensive format support. 101 102 ### Core Design Principles 103 104 1. **Generic Type Safety**: Compile-time type safety through Go generics, avoiding `any` types 105 2. **Security by Default**: Enforced minimum key sizes, secure file permissions, cryptographic best practices 106 3. **Standards Compliance**: Full support for industry standards (X.509, PKCS#7, PKCS#12, SSH) 107 4. **Modular Architecture**: Independent modules with clean interfaces and integration points 108 5. **Format Agnostic**: Seamless conversion between PEM, DER, SSH, and binary formats 109 110 ### Module Structure and Dependencies 111 112 ``` 113 ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ 114 │ keypair/ │◄───┤ cert/ │◄───┤ signing/ │ 115 │ Core Key Mgmt │ │ X.509 Certs │ │ Digital Sigs │ 116 │ (75.3% coverage)│ │ (74.3% coverage) │ │ (79.8% coverage)│ 117 └─────────────────┘ └──────────────────┘ └─────────────────┘ 118 ▲ ▲ ▲ 119 │ │ │ 120 └────────┬─────────────────────────────────────────┘ 121 ▼ ▼ 122 ┌─────────────────┐ ┌──────────────────┐ 123 │ encryption/ │ │ pkcs12/ │ 124 │ Data Encryption │ │ PKCS#12 Files │ 125 │ (89.1% coverage)│ │ (79.1% coverage) │ 126 └─────────────────┘ └──────────────────┘ 127 ``` 128 129 ## Core Modules 130 131 ### 1. `keypair/` - Foundation Module (Primary) 132 133 **Purpose**: Type-safe cryptographic key pair generation and management 134 **Test Coverage**: 75.3% 135 **Key Files**: `keypair.go` (2,115 lines), `algo/rsa.go`, `algo/ecdsa.go`, `algo/ed25519.go` 136 137 **Core Generic Types:** 138 ```go 139 // Parameter constraints for key generation 140 type Param interface { 141 algo.KeySize | algo.ECDSACurve | algo.Ed25519Config 142 } 143 144 // KeyPair type constraints 145 type KeyPair interface { 146 *algo.RSAKeyPair | *algo.ECDSAKeyPair | *algo.Ed25519KeyPair 147 } 148 149 // Private key constraints (used across all modules) 150 type PrivateKey interface { 151 *rsa.PrivateKey | *ecdsa.PrivateKey | ed25519.PrivateKey 152 } 153 154 // Public key constraints 155 type PublicKey interface { 156 *rsa.PublicKey | *ecdsa.PublicKey | ed25519.PublicKey 157 } 158 ``` 159 160 **Primary APIs:** 161 ```go 162 // Unified key pair manager with full type safety 163 type Manager[K KeyPair, P PrivateKey, B PublicKey] struct { /* ... */ } 164 165 // Generic key generation factory 166 func Generate[T Param, K KeyPair, P PrivateKey, B PublicKey](param T) (*Manager[K, P, B], error) 167 168 // Algorithm-specific generation functions 169 func algo.GenerateRSAKeyPair(keySize algo.KeySize) (*algo.RSAKeyPair, error) // keySize: KeySize2048, KeySize3072, KeySize4096 170 func algo.GenerateECDSAKeyPair(curve algo.ECDSACurve) (*algo.ECDSAKeyPair, error) // curve: P224, P256, P384, P521 171 func algo.GenerateEd25519KeyPair() (*algo.Ed25519KeyPair, error) 172 173 // Format conversion with type safety 174 func keypair.ToPEMFiles[T KeyPair](keyPair T, privateFile, publicFile string) error 175 func keypair.PrivateKeyToPEM[T PrivateKey](privateKey T) (format.PEM, error) 176 func keypair.PublicKeyToSSH[T PublicKey](publicKey T, comment string) (format.SSH, error) 177 ``` 178 179 **Security Features:** 180 - **Enforced Minimum Key Sizes**: RSA keys must be ≥2048 bits (compile-time checked) 181 - **Secure File Permissions**: Private keys saved with 0600 permissions, directories with 0700 182 - **Memory Safety**: No raw cryptographic material exposure 183 - **Format Validation**: Type-safe conversions prevent format mismatches 184 185 **Supported Algorithms:** 186 - **RSA**: 2048, 3072, 4096-bit keys with PKCS#8 encoding 187 - **ECDSA**: P-224, P-256, P-384, P-521 curves 188 - **Ed25519**: 256-bit keys with high performance 189 190 ### 2. `cert/` - X.509 Certificate Management 191 192 **Purpose**: X.509 certificate creation, CA operations, and certificate chain management 193 **Test Coverage**: 74.3% 194 **Integration**: Uses `keypair/` module for all key operations 195 196 **Core Types:** 197 ```go 198 type Certificate struct { 199 Certificate *x509.Certificate // Parsed certificate 200 PEMData []byte // PEM-encoded certificate 201 DERData []byte // DER-encoded certificate 202 } 203 204 type CertificateRequest struct { 205 Subject pkix.Name // Certificate subject 206 DNSNames []string // Subject Alternative Names 207 IPAddresses []net.IP // IP address SANs 208 EmailAddress []string // Email SANs 209 ValidFrom time.Time // Certificate validity start 210 ValidFor time.Duration // Validity period 211 IsCA bool // CA certificate flag 212 MaxPathLen int // Path length constraint for CAs 213 } 214 ``` 215 216 **Primary APIs:** 217 ```go 218 // Self-signed certificate creation 219 func CreateSelfSignedCertificate[T keypair.KeyPair](keyPair T, request CertificateRequest) (*Certificate, error) 220 221 // CA certificate creation with constraints 222 func CreateCACertificate[T keypair.KeyPair](keyPair T, request CertificateRequest) (*Certificate, error) 223 224 // Certificate signing by CA 225 func SignCertificate[T keypair.KeyPair](caCert *Certificate, caKeyPair T, request CertificateRequest, publicKey crypto.PublicKey) (*Certificate, error) 226 227 // Certificate verification 228 func VerifyCertificate(cert *Certificate, caCert *Certificate) error 229 230 // File operations 231 func (c *Certificate) SaveToFile(filename string) error 232 func LoadCertificateFromFile(filename string) (*Certificate, error) 233 func ParseCertificateFromPEM(pemData []byte) (*Certificate, error) 234 ``` 235 236 **CA Features:** 237 - **Path Length Constraints**: Control intermediate CA depth in certificate chains 238 - **BasicConstraints Extension**: Proper CA flag and path length handling 239 - **Key Usage Extensions**: Automatic CertSign and CRLSign for CA certificates 240 - **Certificate Chain Validation**: Full chain verification support 241 242 ### 3. `signing/` - Digital Signatures and Verification 243 244 **Purpose**: Document signing, signature verification, and PKCS#7/CMS format support 245 **Test Coverage**: 79.8% (core), 77.2% (formats) 246 **Key Files**: `signing.go`, `signer.go`, `verifier.go`, `formats/` 247 248 **Core Types:** 249 ```go 250 type Signature struct { 251 Format SignatureFormat // raw, pkcs7, pkcs7-detached 252 Algorithm SignatureAlgorithm // rsa, ecdsa, ed25519 253 HashAlgorithm crypto.Hash // SHA256, SHA384, SHA512 254 Data []byte // Signature bytes 255 Digest []byte // Document digest 256 Certificate *x509.Certificate // Signer certificate 257 CertificateChain []*x509.Certificate // Certificate chain 258 Timestamp *Timestamp // RFC 3161 timestamp (optional) 259 Metadata map[string]any // Additional signature metadata 260 } 261 262 type SignOptions struct { 263 HashAlgorithm crypto.Hash // Hash algorithm for signing 264 Format SignatureFormat // Output signature format 265 IncludeCertificate bool // Include signer certificate 266 IncludeChain bool // Include certificate chain 267 Detached bool // Create detached signature 268 TimestampURL string // TSA URL for timestamping 269 } 270 ``` 271 272 **Primary APIs:** 273 ```go 274 // Document signing with full options 275 func SignData[T keypair.KeyPair](data []byte, keyPair T, certificate *cert.Certificate, opts SignOptions) (*Signature, error) 276 277 // Simplified signing with defaults 278 func SignDocument[T keypair.KeyPair](data []byte, keyPair T, certificate *cert.Certificate) (*Signature, error) 279 280 // Signature verification 281 func VerifySignature(data []byte, signature *Signature, opts VerifyOptions) error 282 func VerifyWithCertificate(data []byte, signature *Signature, certificate *x509.Certificate) error 283 284 // PKCS#7/CMS format operations 285 func CreatePKCS7Signature[T keypair.KeyPair](data []byte, keyPair T, certificate *cert.Certificate, detached bool) ([]byte, error) 286 func VerifyPKCS7Signature(data []byte, pkcs7Data []byte) (*PKCS7Info, error) 287 ``` 288 289 **Signature Formats:** 290 - **Raw Signatures**: Algorithm-specific binary signatures (smallest size) 291 - **PKCS#7 Attached**: Signature with embedded document data 292 - **PKCS#7 Detached**: Signature separate from document (recommended) 293 - **Certificate Integration**: Automatic certificate chain inclusion 294 - **Timestamp Authority**: RFC 3161 timestamp token support 295 296 **Multi-Algorithm Support:** 297 - **RSA-PSS and RSA-PKCS1v15**: Both padding schemes supported 298 - **ECDSA**: All supported curves with deterministic signing 299 - **Ed25519**: High-performance pure signatures 300 301 ### 4. `encryption/` - Type-Safe Data Encryption 302 303 **Purpose**: Data encryption/decryption with multiple algorithms and CMS format support 304 **Test Coverage**: 89.1% (highest coverage) 305 **Sophisticated Architecture**: 5 submodules with specialized functionality 306 307 **Submodule Structure:** 308 - `asymmetric/` (85.2%) - RSA, ECDSA, Ed25519 encryption implementations 309 - `symmetric/` (87.9%) - AES-GCM symmetric encryption 310 - `envelope/` (88.9%) - Envelope encryption for large data/multi-recipient 311 - `certificate/` (89.2%) - Certificate-based encryption workflows 312 - `cms.go` - CMS format integration with Mozilla PKCS#7 library 313 314 **Core Types:** 315 ```go 316 type EncryptedData struct { 317 Algorithm EncryptionAlgorithm // rsa-oaep, ecdh-aes-gcm, x25519-aes-gcm 318 Format EncryptionFormat // raw, pkcs7, cms 319 Data []byte // Encrypted data 320 Recipients []*RecipientInfo // Multi-recipient support 321 KeyInfo *KeyEncryptionInfo // Key derivation info 322 Metadata map[string]any // Additional encryption metadata 323 } 324 325 type RecipientInfo struct { 326 Certificate *x509.Certificate // Recipient certificate 327 KeyEncryptionAlgorithm EncryptionAlgorithm // Key encryption method 328 EncryptedKey []byte // Encrypted symmetric key 329 } 330 ``` 331 332 **Primary APIs:** 333 ```go 334 // Generic encryption interfaces 335 type Encryptor[K keypair.KeyPair] interface { 336 Encrypt(data []byte, keyPair K, opts EncryptOptions) (*EncryptedData, error) 337 SupportedAlgorithms() []EncryptionAlgorithm 338 } 339 340 // Type-safe decryption with generic constraints 341 func DecodeDataWithKey[T keypair.PrivateKey](data []byte, cert *x509.Certificate, privateKey T) (*EncryptedData, error) 342 343 // CMS format integration (external Mozilla library) 344 func EncodeToCMS(data *EncryptedData) ([]byte, error) 345 func DecodeFromCMS[T any](cmsData []byte, cert *x509.Certificate, privateKey T) (*EncryptedData, error) 346 347 // High-level encryption functions 348 func EncryptForCertificate(data []byte, cert *x509.Certificate, opts EncryptOptions) (*EncryptedData, error) 349 func DecryptWithKeyPair[T keypair.KeyPair](encData *EncryptedData, keyPair T) ([]byte, error) 350 ``` 351 352 **Encryption Algorithms:** 353 - **RSA-OAEP**: Direct RSA encryption (limited to ~190 bytes for RSA-2048) 354 - **ECDH + AES-GCM**: ECDSA key agreement + symmetric encryption (recommended) 355 - **X25519 + AES-GCM**: Ed25519-based key agreement + symmetric encryption 356 - **Envelope Encryption**: Hybrid encryption for large data with multiple recipients 357 358 **Format Support:** 359 - **Raw Binary**: Algorithm-specific encrypted output 360 - **PKCS#7 EnvelopedData**: Standards-compliant envelope format 361 - **CMS (RFC 5652)**: Full Cryptographic Message Syntax support 362 363 ### 5. `pkcs12/` - PKCS#12 File Management 364 365 **Purpose**: PKCS#12 file creation, loading, and integration with other modules 366 **Test Coverage**: 79.1% 367 **Integration**: Seamless integration with keypair and cert modules 368 369 **Core Types:** 370 ```go 371 type Container struct { 372 PrivateKey interface{} // Private key (any algorithm) 373 Certificate *x509.Certificate // Primary certificate 374 CertificateChain []*x509.Certificate // Certificate chain 375 FriendlyName string // Human-readable name 376 } 377 378 type LoadOptions struct { 379 Password string // PKCS#12 password 380 TrustedCerts []*x509.Certificate // Trusted CA certificates 381 SkipVerification bool // Skip certificate chain verification 382 } 383 384 type CreateOptions struct { 385 Password string // PKCS#12 password 386 FriendlyName string // Container friendly name 387 Iterations int // Key derivation iterations (security vs performance) 388 } 389 ``` 390 391 **Primary APIs:** 392 ```go 393 // PKCS#12 file operations 394 func LoadFromP12File(filename string, opts LoadOptions) (*Container, error) 395 func CreateP12File(filename string, privateKey interface{}, cert *x509.Certificate, chain []*x509.Certificate, opts CreateOptions) error 396 397 // Convenience functions 398 func QuickLoadP12(filename, password string) (*Container, error) 399 func GenerateTestP12(filename, password string) error 400 401 // Integration with other modules 402 func LoadKeyPairFromP12[T keypair.KeyPair](filename, password string) (T, *cert.Certificate, error) 403 func SaveKeyPairToP12[T keypair.KeyPair](keyPair T, certificate *cert.Certificate, filename, password string) error 404 ``` 405 406 ## Format Support Matrix 407 408 GoPKI provides comprehensive format conversion support across all algorithms: 409 410 | Format | RSA | ECDSA | Ed25519 | Usage | 411 |--------|-----|-------|---------|-------| 412 | **PEM** | ✅ | ✅ | ✅ | Text-based, Base64 encoded, most common | 413 | **DER** | ✅ | ✅ | ✅ | Binary format, ~30% smaller than PEM | 414 | **SSH** | ✅ | ✅ | ✅ | OpenSSH format for authorized_keys | 415 | **PKCS#12** | ✅ | ✅ | ✅ | Password-protected container format | 416 417 **Format Conversion APIs:** 418 ```go 419 // Cross-format conversion utilities 420 func keypair.ToPEMFiles[T KeyPair](keyPair T, privateFile, publicFile string) error 421 func keypair.ToDERFiles[T KeyPair](keyPair T, privateFile, publicFile string) error 422 func keypair.ToSSHFiles[T KeyPair](keyPair T, privateFile, publicFile string, comment, passphrase string) error 423 424 // Loading from different formats 425 func keypair.LoadFromPEM[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string) (*Manager[K, P, B], error) 426 func keypair.LoadFromDER[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string) (*Manager[K, P, B], error) 427 func keypair.LoadFromSSH[K KeyPair, P PrivateKey, B PublicKey](privateKeyFile string, passphrase string) (*Manager[K, P, B], error) 428 ``` 429 430 ## Examples and Usage Patterns 431 432 ### Example Build Tags 433 434 All examples use the `//go:build example` build tag to exclude them from regular builds and testing: 435 436 ```go 437 //go:build example 438 439 package main 440 ``` 441 442 **Running Examples:** 443 ```bash 444 task examples:run # Run all examples 445 task examples:keypair # Run keypair examples only 446 task examples:certificates # Run certificate examples only 447 task examples:signing # Run signing examples only 448 task examples:encryption # Run encryption examples only 449 ``` 450 451 ### 1. Key Generation Examples (`examples/keypair/main.go`) 452 453 **Demonstrates:** 454 - RSA, ECDSA, Ed25519 key generation with proper type constraints 455 - Format conversion matrix (PEM, DER, SSH) 456 - SSH key format support with comments and passphrases 457 - Certificate integration for self-signed certificates 458 - Format detection and validation 459 460 ### 2. Certificate Examples (`examples/certificates/main.go`) 461 462 **Demonstrates:** 463 - CA certificate creation with path length constraints 464 - Intermediate CA certificate signing 465 - Server certificate creation with SANs (DNS names, IP addresses) 466 - Certificate chain verification 467 - Self-signed certificate workflows 468 469 ### 3. Signing Examples (`examples/signing/main.go`) 470 471 **Demonstrates:** 472 - Multi-algorithm document signing (RSA, ECDSA, Ed25519) 473 - PKCS#7/CMS signature formats (attached and detached) 474 - Certificate chain inclusion in signatures 475 - Signature verification workflows 476 - Multi-signature document workflows 477 - Timestamp Authority integration 478 479 ### 4. Encryption Examples (`examples/encryption/main.go`) 480 481 **Demonstrates:** 482 - RSA-OAEP encryption for small data 483 - ECDH + AES-GCM hybrid encryption 484 - X25519 + AES-GCM high-performance encryption 485 - Envelope encryption for large data 486 - Multi-recipient encryption workflows 487 - CMS format encryption/decryption 488 489 ## Testing Strategy and Quality Assurance 490 491 ### Comprehensive Test Coverage 492 493 **Overall Statistics:** 494 - **Total Coverage**: 80.3% 495 - **Total Tests**: 844+ individual tests across 23 test files 496 - **Test Types**: Unit, Integration, Security, Benchmark, Edge Case 497 498 **Module Coverage Breakdown:** 499 ``` 500 encryption/ 89.1% (highest - most complex module) 501 asymmetric/ 85.2% 502 symmetric/ 87.9% 503 envelope/ 88.9% 504 certificate/ 89.2% 505 506 keypair/algo/ 87.8% (algorithm implementations) 507 signing/ 79.8% (core signing) 508 formats/ 77.2% (PKCS#7/CMS formats) 509 pkcs12/ 79.1% (PKCS#12 operations) 510 cert/ 74.3% (certificate operations) 511 keypair/ 75.3% (manager and utilities) 512 ``` 513 514 ### Test Categories 515 516 **1. Algorithm Tests:** 517 - Key generation validation across all algorithms 518 - Format conversion round-trip testing 519 - Cross-algorithm compatibility verification 520 - Security parameter enforcement (minimum key sizes) 521 522 **2. Integration Tests:** 523 - Module-to-module data flow verification 524 - Certificate signing with generated keys 525 - Document signing with certificates 526 - Encryption/decryption with certificate keys 527 528 **3. Security Tests:** 529 - Key validation and strength verification 530 - File permission enforcement testing 531 - Cryptographic parameter validation 532 - Format integrity verification 533 534 **4. Performance Tests:** 535 - Benchmark tests for all algorithms 536 - Memory usage profiling 537 - Large data handling verification 538 - Multi-recipient encryption performance 539 540 **5. Edge Case Tests:** 541 - Error handling and validation 542 - Invalid input rejection 543 - Malformed data handling 544 - Resource exhaustion scenarios 545 546 ### Quality Assurance Tools 547 548 **Linting and Static Analysis:** 549 ```bash 550 task lint:full # golangci-lint comprehensive analysis 551 task lint:security # Security-focused linting (gosec) 552 task deadcode # Unused code detection 553 task unused:all # Comprehensive unused code analysis 554 ``` 555 556 **Security Scanning:** 557 ```bash 558 task security:check # Dependency vulnerability scanning 559 ``` 560 561 ## Dependencies and External Libraries 562 563 ### Core Dependencies (Minimal and Carefully Selected) 564 565 **From `go.mod`:** 566 - `go.mozilla.org/pkcs7 v0.9.0` - Battle-tested CMS/PKCS#7 implementation 567 - `golang.org/x/crypto v0.42.0` - Extended cryptographic primitives and SSH support 568 - `software.sslmate.com/src/go-pkcs12 v0.6.0` - Standards-compliant PKCS#12 implementation 569 570 **Testing Dependencies:** 571 - `github.com/stretchr/testify v1.11.1` - Testing framework and assertions 572 573 **Design Philosophy:** 574 - **Minimal Dependencies**: Only essential, well-maintained libraries 575 - **Security Focus**: All dependencies chosen for security and standards compliance 576 - **Standard Library First**: Maximum use of Go standard library cryptographic packages 577 - **Battle-Tested Libraries**: Dependencies with proven track records in production 578 579 ### Dependency Integration Patterns 580 581 **Mozilla PKCS#7 Integration:** 582 ```go 583 // GoPKI wraps external library with type-safe interfaces 584 func EncodeToCMS(data *EncryptedData) ([]byte, error) { 585 // Convert GoPKI types to Mozilla PKCS7 format 586 // Provide type-safe wrapper around external library 587 } 588 589 func DecodeFromCMS[T any](cmsData []byte, cert *x509.Certificate, privateKey T) (*EncryptedData, error) { 590 // Parse Mozilla PKCS7 format 591 // Convert back to GoPKI types with full type safety 592 } 593 ``` 594 595 ## Security Best Practices and Compliance 596 597 ### Cryptographic Security 598 599 **Key Generation Security:** 600 - **Strong Random Sources**: Uses `crypto/rand.Reader` exclusively 601 - **Minimum Key Sizes**: RSA ≥2048 bits enforced at compile time 602 - **Secure Curves**: Only NIST P-curves and Ed25519 supported 603 - **Parameter Validation**: All cryptographic parameters validated before use 604 605 **Algorithm Security:** 606 - **RSA-OAEP**: OAEP padding prevents padding oracle attacks 607 - **ECDSA**: Deterministic signatures prevent nonce reuse vulnerabilities 608 - **Ed25519**: Immune to timing attacks and implementation errors 609 - **AES-GCM**: Authenticated encryption prevents tampering 610 611 ### File System Security 612 613 **File Permissions:** 614 ```go 615 // Enforced throughout the library 616 privateKeyFiles := 0600 // Owner read/write only 617 publicKeyFiles := 0600 // Consistent permissions 618 directories := 0700 // Owner access only 619 ``` 620 621 **Secure File Handling:** 622 - Atomic file operations where possible 623 - Temporary file cleanup 624 - Proper error handling for file operations 625 - Directory creation with secure permissions 626 627 ### Memory Security 628 629 **Secure Memory Handling:** 630 - No raw key material exposure in APIs 631 - Proper zeroing of sensitive data (where possible in Go) 632 - Defensive copying of cryptographic parameters 633 - Type safety prevents memory corruption 634 635 ### Standards Compliance 636 637 **Supported Standards:** 638 - **RFC 5652**: Cryptographic Message Syntax (CMS) 639 - **RFC 3447**: PKCS #1: RSA Cryptography Specifications 640 - **RFC 5208**: PKCS #8: Private-Key Information Syntax 641 - **RFC 7748**: Elliptic Curves for Security (Ed25519, X25519) 642 - **RFC 5280**: Internet X.509 Public Key Infrastructure Certificate 643 - **RFC 2585**: Internet X.509 Public Key Infrastructure Operational Protocols: FTP and HTTP 644 - **PKCS #7**: Cryptographic Message Syntax Standard 645 - **PKCS #12**: Personal Information Exchange Syntax Standard 646 647 ## Development Workflow and CI/CD 648 649 ### Git Workflow 650 651 **Commit Standards:** 652 ```bash 653 task git:commit -- "feat: add Ed25519 encryption support" 654 task git:commit -- "fix: resolve RSA key size validation" 655 task git:commit -- "docs: update API documentation" 656 ``` 657 658 **Pre-commit Workflow:** 659 ```bash 660 task pre-commit # Run format, lint, and basic tests 661 task format # Format code before commit 662 task lint:security # Security checks before commit 663 ``` 664 665 ### Continuous Integration 666 667 **GitHub Actions Integration:** 668 - **Semantic Release**: Automated versioning and changelog generation 669 - **Node.js 20** environment for semantic-release tooling 670 - **Automated Tagging**: Git tags created automatically for releases 671 672 **Local CI Pipeline:** 673 ```bash 674 task ci # Complete CI pipeline locally 675 task ci:full # Comprehensive CI with all checks 676 task release:check # Verify release readiness 677 ``` 678 679 ### Release Management 680 681 **Semantic Versioning:** 682 - **MAJOR**: Breaking API changes 683 - **MINOR**: New features, backward compatible 684 - **PATCH**: Bug fixes, security updates 685 686 **Release Checklist (Automated):** 687 1. All tests pass (80.3% coverage maintained) 688 2. Code formatting verified 689 3. Security linting passes 690 4. Documentation updated 691 5. Examples functional 692 6. Changelog generated automatically 693 694 ## Key Development Patterns 695 696 ### Generic-First Design 697 698 **Core Pattern:** 699 ```go 700 // Define type constraints 701 type Param interface { 702 algo.KeySize | algo.ECDSACurve | algo.Ed25519Config 703 } 704 705 type KeyPair interface { 706 *algo.RSAKeyPair | *algo.ECDSAKeyPair | *algo.Ed25519KeyPair 707 } 708 709 // Use constraints in function signatures 710 func GenerateKeyPair[T Param, K KeyPair](param T) (K, error) { 711 // Implementation with compile-time type safety 712 } 713 ``` 714 715 **Benefits:** 716 - **Compile-time Safety**: Type mismatches caught at build time 717 - **Zero Runtime Overhead**: Generics compile to efficient code 718 - **API Consistency**: Same interface pattern across all algorithms 719 - **IntelliSense Support**: Better IDE support with concrete types 720 721 ### Format Abstraction 722 723 **Type-Safe Format Definitions:** 724 ```go 725 // Package format provides type-safe format abstractions 726 type PEM []byte // PEM-encoded data with validation 727 type DER []byte // DER-encoded binary data 728 type SSH string // SSH public/private key format 729 ``` 730 731 **Conversion Pattern:** 732 ```go 733 // All format conversions follow same pattern 734 func PrivateKeyToPEM[T PrivateKey](privateKey T) (format.PEM, error) 735 func PrivateKeyToDER[T PrivateKey](privateKey T) (format.DER, error) 736 func PrivateKeyToSSH[T PrivateKey](privateKey T, comment, passphrase string) (format.SSH, error) 737 ``` 738 739 ### Error Handling Strategy 740 741 **Explicit Error Returns:** 742 - All functions return explicit error values 743 - No panics in library code 744 - Detailed error messages with context 745 - Wrapped errors preserve original error information 746 747 **Error Types:** 748 - Validation errors for invalid parameters 749 - Cryptographic errors for algorithm failures 750 - I/O errors for file operations 751 - Format errors for data parsing failures 752 753 ### Security-First Development 754 755 **Parameter Validation:** 756 ```go 757 // Example: RSA key size validation 758 func GenerateRSAKeyPair(keySize KeySize) (*RSAKeyPair, error) { 759 bits := keySize.Bits() 760 if bits < 2048 { 761 return nil, fmt.Errorf("RSA key size must be at least 2048 bits") 762 } 763 // ... secure generation 764 } 765 ``` 766 767 **Secure Defaults:** 768 - Minimum security parameters enforced 769 - Secure algorithms chosen by default 770 - Safe file permissions applied automatically 771 - Strong random number generation used exclusively 772 773 ## Integration Examples 774 775 ### Full PKI Workflow 776 777 ```go 778 // 1. Generate CA key pair 779 caKeys, _ := algo.GenerateRSAKeyPair(algo.KeySize3072) 780 781 // 2. Create CA certificate 782 caCert, _ := cert.CreateCACertificate(caKeys, cert.CertificateRequest{ 783 Subject: pkix.Name{CommonName: "My Root CA"}, 784 ValidFor: 10 * 365 * 24 * time.Hour, 785 }) 786 787 // 3. Generate server key pair 788 serverKeys, _ := algo.GenerateRSAKeyPair(algo.KeySize2048) 789 790 // 4. Create server certificate signed by CA 791 serverCert, _ := cert.SignCertificate(caCert, caKeys, cert.CertificateRequest{ 792 Subject: pkix.Name{CommonName: "server.example.com"}, 793 DNSNames: []string{"server.example.com", "api.example.com"}, 794 ValidFor: 365 * 24 * time.Hour, 795 }, serverKeys.PublicKey) 796 797 // 5. Sign a document with server certificate 798 document := []byte("Important contract") 799 signature, _ := signing.SignDocument(document, serverKeys, serverCert) 800 801 // 6. Verify signature 802 err := signing.VerifySignature(document, signature, signing.DefaultVerifyOptions()) 803 804 // 7. Encrypt data for server certificate 805 encData, _ := encryption.EncryptForCertificate([]byte("Secret data"), serverCert.Certificate, encryption.DefaultEncryptOptions()) 806 807 // 8. Decrypt data with server private key 808 decrypted, _ := encryption.DecryptWithKeyPair(encData, serverKeys) 809 810 // 9. Save everything to PKCS#12 file 811 pkcs12.CreateP12File("server.p12", serverKeys.PrivateKey, serverCert.Certificate, []*x509.Certificate{caCert.Certificate}, pkcs12.CreateOptions{Password: "secure123"}) 812 ``` 813 814 This comprehensive workflow demonstrates the seamless integration between all modules with full type safety throughout the entire process. 815 816 ## Important Instructions and Reminders 817 818 ### Code Quality Standards 819 820 **NEVER:** 821 - Use `any` or `interface{}` in core API functions (exceptions: metadata maps, external library compatibility) 822 - Create files unless absolutely necessary for functionality 823 - Add unnecessary documentation files (only if explicitly requested) 824 - Violate the generic type constraints established in the keypair module 825 - Bypass security validations (minimum key sizes, secure permissions) 826 827 **ALWAYS:** 828 - Prefer editing existing files over creating new ones 829 - Follow the established generic type patterns 830 - Use the provided type constraints (`keypair.PrivateKey`, `keypair.PublicKey`, `keypair.KeyPair`) 831 - Maintain compile-time type safety throughout all changes 832 - Run `task test` before considering work complete 833 - Use `task format` to ensure proper code formatting 834 - Follow the security best practices established in the codebase 835 836 ### Testing Requirements 837 838 **Before Any Changes:** 839 1. Run `task test` to ensure all tests pass (80.3% coverage maintained) 840 2. Run `task lint:full` for comprehensive code analysis 841 3. Run `task format:check` to verify formatting 842 4. Test examples with `task examples:run` if making API changes 843 844 **When Adding New Functionality:** 845 1. Write tests first (TDD approach preferred) 846 2. Maintain or improve code coverage 847 3. Follow established patterns for generic type constraints 848 4. Update examples if public API changes 849 5. Ensure integration tests pass across modules 850 851 ### API Design Guidelines 852 853 **Generic Functions:** 854 ```go 855 // GOOD: Specific type constraints 856 func ProcessKey[T keypair.PrivateKey](key T) error 857 858 // AVOID: Generic any types 859 func ProcessKey(key any) error 860 ``` 861 862 **Error Handling:** 863 ```go 864 // GOOD: Explicit error returns with context 865 func GenerateKey(size int) (*Key, error) { 866 if size < 2048 { 867 return nil, fmt.Errorf("key size must be at least 2048 bits, got %d", size) 868 } 869 // ... 870 } 871 872 // AVOID: Panics or silent failures 873 func GenerateKey(size int) *Key { 874 // panic on error - NEVER do this 875 } 876 ``` 877 878 **File Operations:** 879 ```go 880 // GOOD: Secure permissions and error handling 881 func SavePrivateKey(key []byte, filename string) error { 882 dir := filepath.Dir(filename) 883 if err := os.MkdirAll(dir, 0700); err != nil { 884 return fmt.Errorf("failed to create directory: %w", err) 885 } 886 return os.WriteFile(filename, key, 0600) 887 } 888 ``` 889 890 This CLAUDE.md file provides comprehensive guidance for working with the GoPKI codebase while maintaining its high standards of type safety, security, and code quality.