11package cache
22
33import (
4+ "crypto/aes"
5+ "crypto/cipher"
6+ "crypto/rand"
7+ "encoding/base64"
48 "errors"
59 "fmt"
610 "os"
711 "path/filepath"
812 "regexp"
13+
14+ "github.com/stackitcloud/stackit-cli/internal/pkg/auth"
915)
1016
1117var (
12- cacheFolderPath string
18+ cacheFolderPath string
19+ cacheEncryptionKey []byte
1320
1421 identifierRegex = regexp .MustCompile ("^[a-zA-Z0-9-]+$" )
1522 ErrorInvalidCacheIdentifier = fmt .Errorf ("invalid cache identifier" )
@@ -21,6 +28,25 @@ func Init() error {
2128 return fmt .Errorf ("get user cache dir: %w" , err )
2229 }
2330 cacheFolderPath = filepath .Join (cacheDir , "stackit" )
31+
32+ key , _ := auth .GetAuthField (auth .CACHE_ENCRYPTION_KEY )
33+ cacheEncryptionKey = nil
34+ if key != "" {
35+ cacheEncryptionKey , _ = base64 .StdEncoding .DecodeString (key )
36+ // invalid key length
37+ if len (cacheEncryptionKey ) != 32 {
38+ cacheEncryptionKey = nil
39+ }
40+ }
41+ if len (cacheEncryptionKey ) == 0 {
42+ cacheEncryptionKey = make ([]byte , 32 )
43+ _ , err := rand .Read (cacheEncryptionKey )
44+ if err != nil {
45+ return fmt .Errorf ("cache encryption key: %v" , err )
46+ }
47+ key := base64 .StdEncoding .EncodeToString (cacheEncryptionKey )
48+ return auth .SetAuthField (auth .CACHE_ENCRYPTION_KEY , key )
49+ }
2450 return nil
2551}
2652
@@ -32,7 +58,21 @@ func GetObject(identifier string) ([]byte, error) {
3258 return nil , ErrorInvalidCacheIdentifier
3359 }
3460
35- return os .ReadFile (filepath .Join (cacheFolderPath , identifier ))
61+ data , err := os .ReadFile (filepath .Join (cacheFolderPath , identifier ))
62+ if err != nil {
63+ return nil , err
64+ }
65+
66+ block , err := aes .NewCipher (cacheEncryptionKey )
67+ if err != nil {
68+ return nil , err
69+ }
70+ aead , err := cipher .NewGCMWithRandomNonce (block )
71+ if err != nil {
72+ return nil , err
73+ }
74+
75+ return aead .Open (nil , nil , data , nil )
3676}
3777
3878func PutObject (identifier string , data []byte ) error {
@@ -48,7 +88,17 @@ func PutObject(identifier string, data []byte) error {
4888 return err
4989 }
5090
51- return os .WriteFile (filepath .Join (cacheFolderPath , identifier ), data , 0o600 )
91+ block , err := aes .NewCipher (cacheEncryptionKey )
92+ if err != nil {
93+ return err
94+ }
95+ aead , err := cipher .NewGCMWithRandomNonce (block )
96+ if err != nil {
97+ return err
98+ }
99+ encrypted := aead .Seal (nil , nil , data , nil )
100+
101+ return os .WriteFile (filepath .Join (cacheFolderPath , identifier ), encrypted , 0o600 )
52102}
53103
54104func DeleteObject (identifier string ) error {
0 commit comments