| 298 | } |
| 299 | |
| 300 | func TestFileKeyProviderLoadsEnvAndCreatesKeyFile(t *testing.T) { |
| 301 | t.Parallel() |
| 302 | |
| 303 | t.Run("Should load supported AGH_VAULT_KEY encodings", func(t *testing.T) { |
| 304 | t.Parallel() |
| 305 | |
| 306 | rawKey := "01234567890123456789012345678901" |
| 307 | tests := []struct { |
| 308 | name string |
| 309 | value string |
| 310 | }{ |
| 311 | {name: "Should load raw key", value: rawKey}, |
| 312 | {name: "Should load base64 key", value: base64.StdEncoding.EncodeToString([]byte(rawKey))}, |
| 313 | {name: "Should load hex key", value: hex.EncodeToString([]byte(rawKey))}, |
| 314 | } |
| 315 | |
| 316 | for _, tc := range tests { |
| 317 | t.Run(tc.name, func(t *testing.T) { |
| 318 | t.Parallel() |
| 319 | |
| 320 | provider := NewFileKeyProvider(t.TempDir(), func(key string) (string, bool) { |
| 321 | if key == "AGH_VAULT_KEY" { |
| 322 | return tc.value, true |
| 323 | } |
| 324 | return "", false |
| 325 | }) |
| 326 | got, err := provider.Key() |
| 327 | if err != nil { |
| 328 | t.Fatalf("Key() error = %v", err) |
| 329 | } |
| 330 | if string(got) != rawKey { |
| 331 | t.Fatalf("Key() = %q, want raw key bytes", string(got)) |
| 332 | } |
| 333 | }) |
| 334 | } |
| 335 | }) |
| 336 | |
| 337 | t.Run("Should create and reuse daemon key file with restricted permissions", func(t *testing.T) { |
| 338 | t.Parallel() |
| 339 | |
| 340 | homeDir := filepath.Join(t.TempDir(), "agh-home") |
| 341 | provider := NewFileKeyProvider(homeDir, func(string) (string, bool) { return "", false }) |
| 342 | first, err := provider.Key() |
| 343 | if err != nil { |
| 344 | t.Fatalf("Key(first) error = %v", err) |
| 345 | } |
| 346 | if len(first) != keySizeBytes { |
| 347 | t.Fatalf("Key(first) length = %d, want %d", len(first), keySizeBytes) |
| 348 | } |
| 349 | info, err := os.Stat(filepath.Join(homeDir, "vault.key")) |
| 350 | if err != nil { |
| 351 | t.Fatalf("Stat(vault.key) error = %v", err) |
| 352 | } |
| 353 | if got := info.Mode().Perm(); got != 0o600 { |
| 354 | t.Fatalf("vault.key permissions = %o, want 0600", got) |
| 355 | } |
| 356 | dirInfo, err := os.Stat(homeDir) |
| 357 | if err != nil { |