-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvault.go
More file actions
2131 lines (1831 loc) · 70 KB
/
Copy pathvault.go
File metadata and controls
2131 lines (1831 loc) · 70 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package vault
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/arimxyer/pass-cli/internal/config"
"github.com/arimxyer/pass-cli/internal/crypto"
"github.com/arimxyer/pass-cli/internal/keychain"
"github.com/arimxyer/pass-cli/internal/recovery"
"github.com/arimxyer/pass-cli/internal/security"
"github.com/arimxyer/pass-cli/internal/storage"
intsync "github.com/arimxyer/pass-cli/internal/sync"
"github.com/tyler-smith/go-bip39"
"golang.org/x/crypto/argon2"
)
// KeychainStatus represents the state of keychain integration.
type KeychainStatus struct {
Available bool
PasswordStored bool
BackendName string
}
// RemoveVaultResult holds the results of a vault removal operation.
type RemoveVaultResult struct {
FileDeleted bool
KeychainDeleted bool
FileNotFound bool
KeychainNotFound bool
AuditLogDeleted bool
AuditLogNotFound bool
DirectoryDeleted bool
}
var (
// ErrVaultLocked indicates the vault is not unlocked
ErrVaultLocked = errors.New("vault is locked")
// ErrCredentialNotFound indicates the credential doesn't exist
ErrCredentialNotFound = errors.New("credential not found")
// ErrCredentialExists indicates a credential with that name already exists
ErrCredentialExists = errors.New("credential already exists")
// ErrInvalidCredential indicates the credential data is invalid
ErrInvalidCredential = errors.New("invalid credential")
// ErrKeychainAlreadyEnabled indicates that the keychain is already enabled for the vault.
ErrKeychainAlreadyEnabled = errors.New("keychain is already enabled")
// ErrKeychainNotEnabled indicates that keychain integration is not enabled for the vault.
ErrKeychainNotEnabled = errors.New("keychain integration is not enabled for this vault")
)
// UsageRecord tracks where and when a credential was accessed
type UsageRecord struct {
Location string `json:"location"` // Working directory where accessed
Timestamp time.Time `json:"timestamp"` // When it was last accessed
GitRepo string `json:"git_repo"` // Git repository if available
Count int `json:"count"` // Total number of accesses from this location (sum of all field accesses)
LineNumber int `json:"line_number,omitempty"` // Line number in file where accessed (optional)
FieldAccess map[string]int `json:"field_access"` // Per-field access counts: "password": 5, "username": 2, etc.
}
// Credential represents a stored credential with usage tracking
// T020c: Password field changed from string to []byte for secure memory handling
type Credential struct {
Service string `json:"service"`
Username string `json:"username"`
Password []byte `json:"password"` // T020c: Changed to []byte for memory security
Category string `json:"category,omitempty"`
URL string `json:"url,omitempty"`
Notes string `json:"notes"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ModifiedCount int `json:"modified_count"` // Number of times credential has been modified
UsageRecord map[string]UsageRecord `json:"usage_records"` // Map of location -> UsageRecord
// TOTP fields for 2FA support (all optional)
TOTPSecret string `json:"totp_secret,omitempty"` // Base32 encoded TOTP secret
TOTPAlgorithm string `json:"totp_algorithm,omitempty"` // SHA1, SHA256, SHA512 (default: SHA1)
TOTPDigits int `json:"totp_digits,omitempty"` // 6 or 8 (default: 6)
TOTPPeriod int `json:"totp_period,omitempty"` // Period in seconds (default: 30)
TOTPIssuer string `json:"totp_issuer,omitempty"` // Issuer name for display
}
// VaultData is the decrypted vault structure
type VaultData struct {
Credentials map[string]Credential `json:"credentials"` // Map of service name -> Credential
Version int `json:"version"`
// Audit configuration persistence (fix for DISC-013)
AuditEnabled bool `json:"audit_enabled,omitempty"` // Whether audit logging is enabled
AuditLogPath string `json:"audit_log_path,omitempty"` // Path to audit log file
VaultID string `json:"vault_id,omitempty"` // Vault identifier for audit key
}
// VaultService manages credentials with encryption and keychain integration
type VaultService struct {
vaultPath string
cryptoService *crypto.CryptoService
storageService *storage.StorageService
keychainService *keychain.KeychainService
// In-memory state
unlocked bool
masterPassword []byte // Byte array for secure memory clearing (T009)
vaultData *VaultData
recoveryDEK []byte // DEK from recovery unlock (for SetPasswordAfterRecovery)
// T066: Audit logging configuration (FR-025: default disabled)
auditEnabled bool
auditLogger *security.AuditLogger
// T051a: Rate limiting for password validation (FR-024)
rateLimiter *security.ValidationRateLimiter
// Smart sync service (nil if sync disabled)
syncService *intsync.Service
syncConflictDetected bool // prevents auto-push after conflict
}
// New creates a new VaultService
func New(vaultPath string) (*VaultService, error) {
// Expand home directory if needed
if strings.HasPrefix(vaultPath, "~") {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
vaultPath = filepath.Join(home, vaultPath[1:])
}
cryptoService := crypto.NewCryptoService()
storageService, err := storage.NewStorageService(cryptoService, vaultPath)
if err != nil {
return nil, fmt.Errorf("failed to create storage service: %w", err)
}
// Extract vault ID from path for vault-specific keychain entries
vaultDir := filepath.Dir(vaultPath)
vaultID := filepath.Base(vaultDir)
v := &VaultService{
vaultPath: vaultPath,
cryptoService: cryptoService,
storageService: storageService,
keychainService: keychain.New(vaultID),
unlocked: false,
auditEnabled: false, // T066: Default disabled per FR-025
rateLimiter: security.NewValidationRateLimiter(), // T051a: Initialize rate limiter
}
// Initialize sync service from config (if sync enabled)
cfg, _ := config.Load()
if cfg != nil && cfg.Sync.Enabled {
v.syncService = intsync.NewService(cfg.Sync)
}
// T010: Load metadata file (if exists) to enable audit logging before vault unlock
meta, err := LoadMetadata(vaultPath)
metadataFileExists := true
if err != nil {
// Metadata exists but corrupted - log warning and try fallback (T011)
fmt.Fprintf(os.Stderr, "Warning: Failed to load metadata: %v\n", err)
meta = nil
metadataFileExists = false
}
// Check if metadata file actually exists (LoadMetadata returns default if missing)
if meta != nil && !meta.AuditEnabled {
// Metadata may be default (file missing) - check if file exists
if _, statErr := os.Stat(MetadataPath(vaultPath)); os.IsNotExist(statErr) {
metadataFileExists = false
}
}
// Initialize audit from metadata
if meta != nil && meta.AuditEnabled {
// Audit is enabled in metadata - initialize it now
vaultDir := filepath.Dir(vaultPath)
auditLogPath := filepath.Join(vaultDir, "audit.log")
// Use directory name as VaultID for consistency with init command (getVaultID)
vaultID := filepath.Base(vaultDir)
if err := v.EnableAudit(auditLogPath, vaultID); err != nil {
// Non-fatal - continue without audit (graceful degradation)
fmt.Fprintf(os.Stderr, "Warning: Failed to enable audit from metadata: %v\n", err)
}
}
// T011: Fallback self-discovery if metadata missing/failed OR audit not enabled but log exists
if !metadataFileExists || (meta != nil && !meta.AuditEnabled) {
vaultDir := filepath.Dir(vaultPath)
auditLogPath := filepath.Join(vaultDir, "audit.log")
if _, err := os.Stat(auditLogPath); err == nil {
// audit.log exists, enable best-effort audit
// Use directory name as VaultID for consistency with init command (getVaultID)
vaultID := filepath.Base(vaultDir)
if err := v.EnableAudit(auditLogPath, vaultID); err != nil {
// Best-effort failed, continue without audit (non-fatal)
fmt.Fprintf(os.Stderr, "Warning: Self-discovery audit init failed: %v\n", err)
}
}
}
return v, nil
}
// SyncPull performs a smart sync pull if sync is enabled.
// Should be called before unlocking the vault.
func (v *VaultService) SyncPull() error {
if v.syncService == nil || !v.syncService.IsEnabled() {
return nil
}
err := v.syncService.SmartPull(v.vaultPath)
if errors.Is(err, intsync.ErrSyncConflict) {
v.syncConflictDetected = true
fmt.Fprintf(os.Stderr, "Warning: %v\nUse `pass-cli sync resolve` to choose which version to keep.\n", err)
return nil // Don't block operation on conflict
}
return err
}
// IsSyncEnabled returns true if sync is configured and enabled.
func (v *VaultService) IsSyncEnabled() bool {
return v.syncService != nil && v.syncService.IsEnabled()
}
// SyncConflictDetected reports whether the most recent SyncPull detected a
// conflict (both local and remote changed). Used by the concurrent-unlock path
// to re-surface the conflict cleanly after the password prompt, since SyncPull's
// own warning may print mid-prompt and read commands never re-echo it (#103).
func (v *VaultService) SyncConflictDetected() bool {
return v.syncConflictDetected
}
// SyncPush performs a smart sync push if sync is enabled.
// Should be called once at the end of a command, not per-save.
// Returns true if a push was actually performed.
func (v *VaultService) SyncPush() bool {
if v.syncService == nil || !v.syncService.IsEnabled() {
return false
}
if v.syncConflictDetected {
fmt.Fprintf(os.Stderr, "Warning: skipping push due to unresolved sync conflict. Use `pass-cli sync resolve` to resolve.\n")
return false
}
pushed, err := v.syncService.SmartPush(v.vaultPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: sync push failed: %v\n", err)
return false
}
return pushed
}
// GetStorageService returns the underlying storage service.
// Used by CLI commands that need direct access to storage operations.
func (v *VaultService) GetStorageService() *storage.StorageService {
return v.storageService
}
// T066: EnableAudit enables audit logging for this vault
// vaultID should be a unique identifier for the vault (e.g., filepath or UUID)
// DISC-013 fix: Now persists audit config to vault data
func (v *VaultService) EnableAudit(auditLogPath, vaultID string) error {
if v.auditEnabled {
return nil // Already enabled
}
logger, err := security.NewAuditLogger(auditLogPath, vaultID)
if err != nil {
return fmt.Errorf("failed to create audit logger: %w", err)
}
v.auditLogger = logger
v.auditEnabled = true
// DISC-013 fix: Persist audit configuration to vault data
if v.vaultData != nil {
v.vaultData.AuditEnabled = true
v.vaultData.AuditLogPath = auditLogPath
v.vaultData.VaultID = vaultID
// Save vault data to persist audit configuration
if err := v.save(); err != nil {
return fmt.Errorf("failed to persist audit configuration: %w", err)
}
}
// T026 (US2): Save metadata file for pre-unlock audit logging
// Only save metadata if it already exists (explicit enable) or if vault explicitly requested it
// Don't create metadata during autodiscovery (best-effort logging)
existingMeta, err := LoadMetadata(v.vaultPath)
if err == nil && existingMeta != nil {
// Check if metadata file actually exists (LoadMetadata returns default if missing)
if _, statErr := os.Stat(MetadataPath(v.vaultPath)); statErr == nil {
// Metadata exists - update it
existingMeta.AuditEnabled = true
if err := SaveMetadata(v.vaultPath, existingMeta); err != nil {
// Non-fatal: audit logger is enabled, metadata save failed
fmt.Fprintf(os.Stderr, "Warning: Failed to save metadata: %v\n", err)
}
}
// else: metadata file doesn't exist, this is autodiscovery, don't create metadata
}
return nil
}
// T066: DisableAudit disables audit logging
func (v *VaultService) DisableAudit() {
v.auditEnabled = false
v.auditLogger = nil
}
// EnableAuditPortable enables audit logging with portable password-based key derivation
// This enables audit verification across different OSes when syncing vaults
// The salt is stored in vault metadata for retrieval on other systems
func (v *VaultService) EnableAuditPortable(auditLogPath, vaultID string, password, existingSalt []byte) error {
if v.auditEnabled {
return nil // Already enabled
}
logger, newSalt, err := security.NewAuditLoggerPortable(auditLogPath, vaultID, password, existingSalt)
if err != nil {
return fmt.Errorf("failed to create portable audit logger: %w", err)
}
v.auditLogger = logger
v.auditEnabled = true
// DISC-013 fix: Persist audit configuration to vault data
if v.vaultData != nil {
v.vaultData.AuditEnabled = true
v.vaultData.AuditLogPath = auditLogPath
v.vaultData.VaultID = vaultID
// Save vault data to persist audit configuration
if err := v.save(); err != nil {
return fmt.Errorf("failed to persist audit configuration: %w", err)
}
}
// Save salt to metadata for cross-OS retrieval
existingMeta, err := LoadMetadata(v.vaultPath)
if err == nil && existingMeta != nil {
// Update metadata with salt if we generated a new one
if len(newSalt) > 0 || len(existingSalt) > 0 {
if len(newSalt) > 0 {
existingMeta.AuditSalt = newSalt
} else {
existingMeta.AuditSalt = existingSalt
}
}
existingMeta.AuditEnabled = true
if err := SaveMetadata(v.vaultPath, existingMeta); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to save audit salt to metadata: %v\n", err)
}
}
return nil
}
// T074: LogAudit logs an audit event with graceful degradation (FR-026)
// Per FR-026: System MUST continue operation even if audit logging fails
// Exported for use by keychain lifecycle commands (FR-015)
func (v *VaultService) LogAudit(eventType, outcome, credentialName string) {
if !v.auditEnabled || v.auditLogger == nil {
return // Audit not enabled
}
entry := &security.AuditLogEntry{
Timestamp: time.Now(),
EventType: eventType,
Outcome: outcome,
CredentialName: credentialName,
MachineID: security.GetMachineID(), // ARI-50: Track source machine
}
// FR-026: Log errors to stderr but continue operation
if err := v.auditLogger.Log(entry); err != nil {
fmt.Fprintf(os.Stderr, "Warning: audit logging failed (operation continues): %v\n", err)
}
}
// createAuditCallback returns a storage.ProgressCallback that logs atomic save events
// to the audit log. Returns nil if audit logging is disabled.
// T015/T022/T034: Integrate audit logging into atomic save operations
// FR-015: Log ALL atomic save state transitions
func (v *VaultService) createAuditCallback() storage.ProgressCallback {
if !v.auditEnabled || v.auditLogger == nil {
return nil // No callback if audit disabled
}
// Return closure that maps storage events to audit entries
return func(event string, metadata ...string) {
// FR-015: Log ALL atomic save state transitions
switch event {
case "atomic_save_started":
v.LogAudit("vault_save", security.OutcomeInProgress, "vault save operation initiated")
case "temp_file_created":
tempPath := ""
if len(metadata) > 0 {
tempPath = filepath.Base(metadata[0]) // Log filename only, not full path
}
v.LogAudit("vault_save", security.OutcomeInProgress, fmt.Sprintf("temporary file created: %s", tempPath))
case "verification_started":
v.LogAudit("vault_save", security.OutcomeInProgress, "vault verification started")
case "verification_passed":
v.LogAudit("vault_save", security.OutcomeInProgress, "vault verification passed")
case "verification_failed":
reason := "unknown"
if len(metadata) > 1 {
reason = metadata[1]
}
v.LogAudit("vault_save", security.OutcomeFailure, fmt.Sprintf("vault verification failed: %s", reason))
case "atomic_rename_started":
// Log rename operations (called twice during save)
oldFile := ""
newFile := ""
if len(metadata) >= 2 {
oldFile = filepath.Base(metadata[0])
newFile = filepath.Base(metadata[1])
}
v.LogAudit("vault_save", security.OutcomeInProgress, fmt.Sprintf("atomic rename: %s → %s", oldFile, newFile))
case "rollback_started":
v.LogAudit("vault_save", security.OutcomeFailure, "atomic save rollback initiated")
case "rollback_completed":
v.LogAudit("vault_save", security.OutcomeFailure, "atomic save rollback completed")
case "atomic_save_completed":
v.LogAudit("vault_save", security.OutcomeSuccess, "vault save completed successfully")
}
}
}
// Initialize creates a new vault with a master password
// T010: Updated signature to accept []byte, T014: Added deferred cleanup
// T045: Added password policy validation (FR-016)
// DISC-013 fix: Added audit parameters to set config during initialization
func (v *VaultService) Initialize(masterPassword []byte, useKeychain bool, auditLogPath, vaultID string) error {
defer crypto.ClearBytes(masterPassword) // T014: Ensure cleanup even on error
// T045 [US3]: Validate master password against policy (FR-016)
// Import security package required at top of file
passwordPolicy := &security.PasswordPolicy{
MinLength: 12,
RequireUppercase: true,
RequireLowercase: true,
RequireDigit: true,
RequireSymbol: true,
}
if err := passwordPolicy.Validate(masterPassword); err != nil {
// T051a: Record failure and check rate limit
if rateLimitErr := v.rateLimiter.CheckAndRecordFailure(); rateLimitErr != nil {
return rateLimitErr // Rate limit triggered
}
return fmt.Errorf("password does not meet requirements: %w", err)
}
// T051a: Reset rate limiter on successful validation
v.rateLimiter.Reset()
// Check if vault already exists
if _, err := os.Stat(v.vaultPath); err == nil {
return errors.New("vault already exists")
}
// DISC-013 fix: Create vault data with audit config if provided
vaultData := &VaultData{
Credentials: make(map[string]Credential),
Version: 1,
}
// Set audit configuration if provided (non-empty path means enabled)
if auditLogPath != "" && vaultID != "" {
vaultData.AuditEnabled = true
vaultData.AuditLogPath = auditLogPath
vaultData.VaultID = vaultID
// DISC-013 fix: Create audit logger for immediate use
logger, err := security.NewAuditLogger(auditLogPath, vaultID)
if err != nil {
// Don't fail init if audit logger creation fails (graceful degradation)
fmt.Fprintf(os.Stderr, "Warning: failed to create audit logger: %v\n", err)
} else {
v.auditLogger = logger
v.auditEnabled = true
}
}
// Marshal to JSON
data, err := json.Marshal(vaultData)
if err != nil {
return fmt.Errorf("failed to marshal vault data: %w", err)
}
// Convert to string for storage service (TODO: Phase 4 will update storage.go to accept []byte)
masterPasswordStr := string(masterPassword)
// Initialize storage (creates directory and vault file)
if err := v.storageService.InitializeVault(masterPasswordStr); err != nil {
return fmt.Errorf("failed to initialize vault: %w", err)
}
// Save initial empty vault
// T015: Pass audit callback for atomic save logging
if err := v.storageService.SaveVault(data, masterPasswordStr, v.createAuditCallback()); err != nil {
return fmt.Errorf("failed to save initial vault: %w", err)
}
// Store master password in keychain if requested
if useKeychain && v.keychainService.IsAvailable() {
if err := v.keychainService.Store(masterPasswordStr); err != nil {
// Log warning but don't fail initialization
fmt.Fprintf(os.Stderr, "Warning: failed to store password in keychain: %v\n", err)
}
}
// T067: Log vault creation event (FR-019)
v.LogAudit(security.EventVaultUnlock, security.OutcomeSuccess, "")
// Create metadata file to track vault configuration
metadata := &Metadata{
Version: "1.0",
AuditEnabled: vaultData.AuditEnabled,
KeychainEnabled: useKeychain && v.keychainService.IsAvailable(),
CreatedAt: time.Now(),
LastModified: time.Now(),
}
if err := SaveMetadata(v.vaultPath, metadata); err != nil {
// Log warning but don't fail initialization (graceful degradation)
fmt.Fprintf(os.Stderr, "Warning: failed to create metadata file: %v\n", err)
}
return nil
}
// T022: InitializeWithRecovery creates a new v2 vault with recovery phrase support
// This method generates a DEK, wraps it with both password and recovery KEKs,
// and stores the wrapped versions in the vault metadata.
// Parameters:
// - masterPassword: master password for the vault
// - useKeychain: whether to store password in OS keychain
// - auditLogPath: path to audit log (empty to disable)
// - vaultID: unique vault identifier for audit
// - passphrase: optional recovery passphrase (25th word)
//
// Returns: mnemonic string (24 words) for user backup, error
func (v *VaultService) InitializeWithRecovery(masterPassword []byte, useKeychain bool, auditLogPath, vaultID string, passphrase []byte) (string, error) {
defer crypto.ClearBytes(masterPassword) // Ensure cleanup even on error
if passphrase != nil {
defer crypto.ClearBytes(passphrase)
}
// Validate master password against policy
passwordPolicy := &security.PasswordPolicy{
MinLength: 12,
RequireUppercase: true,
RequireLowercase: true,
RequireDigit: true,
RequireSymbol: true,
}
if err := passwordPolicy.Validate(masterPassword); err != nil {
if rateLimitErr := v.rateLimiter.CheckAndRecordFailure(); rateLimitErr != nil {
return "", rateLimitErr
}
return "", fmt.Errorf("password does not meet requirements: %w", err)
}
v.rateLimiter.Reset()
// Check if vault already exists
if _, err := os.Stat(v.vaultPath); err == nil {
return "", errors.New("vault already exists")
}
// 1. Generate salt for password KDF
salt, err := v.cryptoService.GenerateSalt()
if err != nil {
return "", fmt.Errorf("failed to generate salt: %w", err)
}
// 2. Derive password KEK
iterations := crypto.GetIterations()
passwordKEK, err := v.cryptoService.DeriveKey(masterPassword, salt, iterations)
if err != nil {
return "", fmt.Errorf("failed to derive password KEK: %w", err)
}
defer crypto.ClearBytes(passwordKEK)
// 3. Setup challenge-based recovery (generates mnemonic and challenge data)
challengeSetup, err := recovery.SetupChallengeRecovery(&recovery.ChallengeSetupConfig{
Passphrase: passphrase,
})
if err != nil {
return "", fmt.Errorf("failed to setup recovery: %w", err)
}
defer crypto.ClearBytes(challengeSetup.RecoveryKEK)
// 4. Generate and wrap DEK with both password KEK and recovery KEK
keyWrapResult, err := crypto.GenerateAndWrapDEK(passwordKEK, challengeSetup.RecoveryKEK)
if err != nil {
return "", fmt.Errorf("failed to generate and wrap DEK: %w", err)
}
defer crypto.ClearBytes(keyWrapResult.DEK)
// 5. Initialize v2 vault with DEK
if err := v.storageService.InitializeVaultV2(
keyWrapResult.DEK,
keyWrapResult.PasswordWrapped.Ciphertext,
keyWrapResult.PasswordWrapped.Nonce,
salt,
iterations,
); err != nil {
return "", fmt.Errorf("failed to initialize v2 vault: %w", err)
}
// 6. Create vault data structure
vaultData := &VaultData{
Credentials: make(map[string]Credential),
Version: 1, // Vault data version (not vault format version)
}
// Set audit configuration if provided
if auditLogPath != "" && vaultID != "" {
vaultData.AuditEnabled = true
vaultData.AuditLogPath = auditLogPath
vaultData.VaultID = vaultID
logger, err := security.NewAuditLogger(auditLogPath, vaultID)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to create audit logger: %v\n", err)
} else {
v.auditLogger = logger
v.auditEnabled = true
}
}
// 7. Marshal and save vault data
data, err := json.Marshal(vaultData)
if err != nil {
return "", fmt.Errorf("failed to marshal vault data: %w", err)
}
// Save vault data encrypted with DEK
if err := v.storageService.SaveVaultWithDEK(data, keyWrapResult.DEK, v.createAuditCallback()); err != nil {
return "", fmt.Errorf("failed to save initial vault: %w", err)
}
// 8. Store password in keychain if requested
if useKeychain && v.keychainService.IsAvailable() {
if err := v.keychainService.Store(string(masterPassword)); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to store password in keychain: %v\n", err)
}
}
// 9. Log vault creation
v.LogAudit(security.EventVaultUnlock, security.OutcomeSuccess, "")
// 10. Complete recovery metadata with wrapped DEK
recoveryMetadata := challengeSetup.Metadata
recoveryMetadata.EncryptedRecoveryKey = keyWrapResult.RecoveryWrapped.Ciphertext
recoveryMetadata.NonceRecovery = keyWrapResult.RecoveryWrapped.Nonce
// 11. Create metadata file
metadata := &Metadata{
Version: "1.0",
AuditEnabled: vaultData.AuditEnabled,
KeychainEnabled: useKeychain && v.keychainService.IsAvailable(),
CreatedAt: time.Now(),
LastModified: time.Now(),
Recovery: recoveryMetadata,
}
if err := SaveMetadata(v.vaultPath, metadata); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to create metadata file: %v\n", err)
}
// Return mnemonic for CLI to display and verify
return challengeSetup.Mnemonic, nil
}
// Unlock opens the vault and loads credentials into memory
// T011: Updated signature to accept []byte, T015: Added deferred cleanup
// T036e: Auto-rollback on incomplete migration detection
func (v *VaultService) Unlock(masterPassword []byte) error {
defer crypto.ClearBytes(masterPassword) // T015: Ensure cleanup even on error
if v.unlocked {
return nil // Already unlocked
}
// T036e: Check for incomplete migration (vault.tmp exists)
vaultTmpPath := v.vaultPath + storage.TempSuffix
vaultBackupPath := v.vaultPath + storage.BackupSuffix
if _, err := os.Stat(vaultTmpPath); err == nil {
// T036g: Incomplete migration detected - inform user with actionable message
fmt.Fprintf(os.Stderr, "\n*** MIGRATION FAILURE DETECTED ***\n")
fmt.Fprintf(os.Stderr, "An incomplete vault migration was found (power loss or system crash).\n")
if _, err := os.Stat(vaultBackupPath); err == nil {
// Backup exists - restore it
fmt.Fprintf(os.Stderr, "Attempting automatic recovery from backup...\n")
// Read backup
backupData, err := os.ReadFile(vaultBackupPath) // #nosec G304 -- Vault backup path validated by storage layer
if err != nil {
return fmt.Errorf("failed to read backup for rollback: %w", err)
}
// Restore to main vault path
if err := os.WriteFile(v.vaultPath, backupData, storage.VaultPermissions); err != nil {
return fmt.Errorf("failed to restore backup: %w", err)
}
// Remove incomplete temp file
_ = os.Remove(vaultTmpPath)
fmt.Fprintf(os.Stderr, "SUCCESS: Vault restored from backup. Your data is safe.\n")
fmt.Fprintf(os.Stderr, "You may continue using the vault normally.\n\n")
} else {
// No backup available - just remove temp file and warn
fmt.Fprintf(os.Stderr, "WARNING: No backup file found. Cleaning up temporary files.\n")
_ = os.Remove(vaultTmpPath)
fmt.Fprintf(os.Stderr, "If you experience issues, please report this immediately.\n\n")
}
}
// Convert to string for storage service (TODO: Phase 4 will update storage.go to accept []byte)
masterPasswordStr := string(masterPassword)
// Try to load vault
data, err := v.storageService.LoadVault(masterPasswordStr)
if err != nil {
// T068: Log unlock failure (FR-019)
v.LogAudit(security.EventVaultUnlock, security.OutcomeFailure, "")
return fmt.Errorf("failed to unlock vault: %w", err)
}
// Unmarshal vault data
var vaultData VaultData
if err := json.Unmarshal(data, &vaultData); err != nil {
return fmt.Errorf("failed to parse vault data: %w", err)
}
// Store in memory (make a copy since we're clearing the parameter)
v.unlocked = true
v.masterPassword = make([]byte, len(masterPassword))
copy(v.masterPassword, masterPassword)
v.vaultData = &vaultData
// DISC-013 fix: Restore audit logging if it was enabled
if vaultData.AuditEnabled && vaultData.AuditLogPath != "" && vaultData.VaultID != "" {
// Check if sync is enabled - if so, use portable audit mode for cross-OS verification
cfg, _ := config.Load()
if cfg != nil && cfg.Sync.Enabled {
// Load audit salt from metadata for portable mode
meta, metaErr := LoadMetadata(v.vaultPath)
var auditSalt []byte
if metaErr == nil && meta != nil && len(meta.AuditSalt) > 0 {
auditSalt = meta.AuditSalt
}
// Use portable audit mode with password-derived key
if err := v.EnableAuditPortable(vaultData.AuditLogPath, vaultData.VaultID, masterPassword, auditSalt); err != nil {
// Log warning but don't fail unlock - audit logging is optional
fmt.Fprintf(os.Stderr, "Warning: failed to restore portable audit logging: %v\n", err)
}
} else {
// Use legacy keychain-based audit mode
if err := v.EnableAudit(vaultData.AuditLogPath, vaultData.VaultID); err != nil {
// Log warning but don't fail unlock - audit logging is optional
fmt.Fprintf(os.Stderr, "Warning: failed to restore audit logging: %v\n", err)
}
}
}
// T027-T029: Metadata synchronization (User Story 2)
// Load existing metadata (if any)
meta, err := LoadMetadata(v.vaultPath)
if err != nil {
// Metadata corrupted - will be recreated if audit enabled
fmt.Fprintf(os.Stderr, "Warning: Corrupted metadata, will recreate: %v\n", err)
meta = nil
}
// T028: Check for metadata/vault config mismatch
if meta != nil {
mismatch := meta.AuditEnabled != vaultData.AuditEnabled
// T029: Synchronize metadata when mismatch detected (vault settings take precedence per FR-012)
if mismatch {
updatedMeta := &Metadata{
Version: meta.Version,
AuditEnabled: vaultData.AuditEnabled,
KeychainEnabled: meta.KeychainEnabled, // Preserve keychain setting
CreatedAt: meta.CreatedAt, // Preserve original timestamp
}
if err := SaveMetadata(v.vaultPath, updatedMeta); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to sync metadata: %v\n", err)
}
}
} else if vaultData.AuditEnabled {
// T027: Create metadata if missing and audit enabled in vault
newMeta := &Metadata{
Version: "1.0",
AuditEnabled: true,
KeychainEnabled: false,
}
if err := SaveMetadata(v.vaultPath, newMeta); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to create metadata: %v\n", err)
}
}
// T036f: Remove backup file after successful unlock
// This confirms the vault is readable and migration (if any) was successful
backupPath := v.vaultPath + storage.BackupSuffix
if _, err := os.Stat(backupPath); err == nil {
if err := os.Remove(backupPath); err != nil {
// Log warning but don't fail unlock - backup cleanup is not critical
fmt.Fprintf(os.Stderr, "Warning: failed to remove backup file: %v\n", err)
}
}
// T068: Log unlock success (FR-019)
v.LogAudit(security.EventVaultUnlock, security.OutcomeSuccess, "")
return nil
}
// UnlockWithKey unlocks the vault using a provided encryption key (for recovery)
// Parameters: vaultKey (32-byte AES-256 encryption key from recovery)
// Returns: error
func (v *VaultService) UnlockWithKey(vaultKey []byte) error {
// Note: We store the DEK for SetPasswordAfterRecovery, so don't clear it here
// It will be cleared when Lock() is called or when SetPasswordAfterRecovery completes
if v.unlocked {
return nil // Already unlocked
}
// Load vault data using the recovery key
data, err := v.storageService.LoadVaultWithKey(vaultKey)
if err != nil {
// Log unlock failure
v.LogAudit(security.EventVaultUnlock, security.OutcomeFailure, "recovery")
return fmt.Errorf("failed to unlock vault with recovery key: %w", err)
}
// Unmarshal vault data
var vaultData VaultData
if err := json.Unmarshal(data, &vaultData); err != nil {
return fmt.Errorf("failed to parse vault data: %w", err)
}
// Store in memory (no master password for recovery unlock)
v.unlocked = true
v.masterPassword = nil // Recovery unlock doesn't have a password
v.vaultData = &vaultData
// Store the DEK for SetPasswordAfterRecovery
v.recoveryDEK = make([]byte, len(vaultKey))
copy(v.recoveryDEK, vaultKey)
// Restore audit logging if enabled
if vaultData.AuditEnabled && vaultData.AuditLogPath != "" && vaultData.VaultID != "" {
if err := v.EnableAudit(vaultData.AuditLogPath, vaultData.VaultID); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to restore audit logging: %v\n", err)
}
}
// Load metadata (same as regular Unlock)
meta, err := LoadMetadata(v.vaultPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: Corrupted metadata, will recreate: %v\n", err)
meta = nil
}
// Synchronize metadata if needed
if meta != nil {
mismatch := meta.AuditEnabled != vaultData.AuditEnabled
if mismatch {
updatedMeta := &Metadata{
Version: meta.Version,
AuditEnabled: vaultData.AuditEnabled,
KeychainEnabled: meta.KeychainEnabled,
Recovery: meta.Recovery, // Preserve recovery metadata
CreatedAt: meta.CreatedAt,
}
if err := SaveMetadata(v.vaultPath, updatedMeta); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to sync metadata: %v\n", err)
}
}
} else if vaultData.AuditEnabled {
newMeta := &Metadata{
Version: "1.0",
AuditEnabled: true,
KeychainEnabled: false,
}
if err := SaveMetadata(v.vaultPath, newMeta); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to create metadata: %v\n", err)
}
}
// Remove backup if exists (successful unlock = migration succeeded)
backupPath := v.vaultPath + storage.BackupSuffix
if _, err := os.Stat(backupPath); err == nil {
if err := os.Remove(backupPath); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to remove backup file: %v\n", err)
}
}
// Log unlock success
v.LogAudit(security.EventVaultUnlock, security.OutcomeSuccess, "recovery")
return nil
}
// UnlockWithKeychain attempts to unlock using keychain-stored password
func (v *VaultService) UnlockWithKeychain() error {
password, err := v.RetrieveKeychainPassword()
if err != nil {
return err
}
return v.Unlock(password)
}
// RetrieveKeychainPassword returns the master password from the OS keychain
// without decrypting the vault. It reads metadata and the keyring (and performs
// best-effort migration from a legacy global entry) but never touches the
// vault.enc ciphertext — so callers may run it concurrently with a sync pull
// that replaces vault.enc, then decrypt with the returned password afterwards
// (see the concurrent-unlock path in cmd, #103). Returns ErrKeychainNotEnabled
// when keychain unlock is not configured. The caller owns the returned bytes and
// must crypto.ClearBytes them.
func (v *VaultService) RetrieveKeychainPassword() ([]byte, error) {
// T018: Check metadata to see if keychain is enabled (FR-007)
metadata, err := v.LoadMetadata()
if err != nil {
return nil, fmt.Errorf("failed to load metadata: %w", err)
}
if !metadata.KeychainEnabled {
return nil, ErrKeychainNotEnabled
}
// Attempt to retrieve password from vault-specific keychain entry
// This uses keyring.Get() which doesn't require GUI authorization on macOS
password, err := v.keychainService.Retrieve()
// If vault-specific entry not found, try auto-migration from global entry
if err == keychain.ErrPasswordNotFound {
migrated, migrateErr := v.keychainService.MigrateFromGlobal()
if migrateErr != nil {
// Log warning but continue - migration is best-effort
fmt.Fprintf(os.Stderr, "Warning: keychain migration check failed: %v\n", migrateErr)
} else if migrated {
// Migration succeeded, try retrieve again
password, err = v.keychainService.Retrieve()
if err == nil {
fmt.Fprintf(os.Stderr, "Migrated keychain entry to vault-specific storage\n")
// Clean up global entry after successful migration and unlock
// This is safe because we have the password and can re-store if needed
_ = v.keychainService.DeleteGlobal()
}
}
}
if err != nil {
return nil, fmt.Errorf("failed to retrieve password from keychain: %w", err)
}
return []byte(password), nil
}
// Lock clears in-memory credentials and password
// T013: Fixed to properly clear []byte password using crypto.ClearBytes
// T069: Added audit logging (FR-019)
func (v *VaultService) Lock() {
// T069: Log lock event before clearing state (FR-019)
v.LogAudit(security.EventVaultLock, security.OutcomeSuccess, "")
v.unlocked = false
// Clear sensitive data from memory
if v.masterPassword != nil {
crypto.ClearBytes(v.masterPassword)
v.masterPassword = nil
}