-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcache.go
More file actions
181 lines (159 loc) · 4.13 KB
/
cache.go
File metadata and controls
181 lines (159 loc) · 4.13 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
package cache
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/stackitcloud/stackit-cli/internal/pkg/auth"
)
var (
cacheDirOverwrite string // for testing only
cacheFolderPath string
cacheEncryptionKey []byte
identifierRegex = regexp.MustCompile("^[a-zA-Z0-9-]+$")
ErrorInvalidCacheIdentifier = fmt.Errorf("invalid cache identifier")
)
const (
cacheKeyMaxAge = 90 * 24 * time.Hour
)
func Init() error {
var cacheDir string
if cacheDirOverwrite == "" {
var err error
cacheDir, err = os.UserCacheDir()
if err != nil {
return fmt.Errorf("get user cache dir: %w", err)
}
} else {
cacheDir = cacheDirOverwrite
}
cacheFolderPath = filepath.Join(cacheDir, "stackit")
// Encryption keys should only be used a limited number of times for aes-gcm.
// Thus, refresh the key periodically. This will invalidate all cached entries.
key, _ := auth.GetAuthField(auth.CACHE_ENCRYPTION_KEY)
age, _ := auth.GetAuthField(auth.CACHE_ENCRYPTION_KEY_AGE)
cacheEncryptionKey = nil
var keyAge time.Time
if age != "" {
ageSeconds, err := strconv.ParseInt(age, 10, 64)
if err == nil {
keyAge = time.Unix(ageSeconds, 0)
}
}
if key != "" && keyAge.Add(cacheKeyMaxAge).After(time.Now()) {
cacheEncryptionKey, _ = base64.StdEncoding.DecodeString(key)
// invalid key length
if len(cacheEncryptionKey) != 32 {
cacheEncryptionKey = nil
}
}
if len(cacheEncryptionKey) == 0 {
cacheEncryptionKey = make([]byte, 32)
_, err := rand.Read(cacheEncryptionKey)
if err != nil {
return fmt.Errorf("cache encryption key: %w", err)
}
key := base64.StdEncoding.EncodeToString(cacheEncryptionKey)
err = auth.SetAuthField(auth.CACHE_ENCRYPTION_KEY, key)
if err != nil {
return fmt.Errorf("save cache encryption key: %w", err)
}
err = auth.SetAuthField(auth.CACHE_ENCRYPTION_KEY_AGE, fmt.Sprint(time.Now().Unix()))
if err != nil {
return fmt.Errorf("save cache encryption key age: %w", err)
}
// cleanup old cache entries as they won't be readable anymore
if err := cleanupCache(); err != nil {
return err
}
}
return nil
}
func GetObject(identifier string) ([]byte, error) {
if err := validateCacheFolderPath(); err != nil {
return nil, err
}
if !identifierRegex.MatchString(identifier) {
return nil, ErrorInvalidCacheIdentifier
}
data, err := os.ReadFile(filepath.Join(cacheFolderPath, identifier))
if err != nil {
return nil, err
}
block, err := aes.NewCipher(cacheEncryptionKey)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCMWithRandomNonce(block)
if err != nil {
return nil, err
}
return aead.Open(nil, nil, data, nil)
}
func PutObject(identifier string, data []byte) error {
if err := validateCacheFolderPath(); err != nil {
return err
}
if !identifierRegex.MatchString(identifier) {
return ErrorInvalidCacheIdentifier
}
err := os.MkdirAll(cacheFolderPath, 0o750)
if err != nil {
return err
}
block, err := aes.NewCipher(cacheEncryptionKey)
if err != nil {
return err
}
aead, err := cipher.NewGCMWithRandomNonce(block)
if err != nil {
return err
}
encrypted := aead.Seal(nil, nil, data, nil)
return os.WriteFile(filepath.Join(cacheFolderPath, identifier), encrypted, 0o600)
}
func DeleteObject(identifier string) error {
if err := validateCacheFolderPath(); err != nil {
return err
}
if !identifierRegex.MatchString(identifier) {
return ErrorInvalidCacheIdentifier
}
if err := os.Remove(filepath.Join(cacheFolderPath, identifier)); !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
func validateCacheFolderPath() error {
if cacheFolderPath == "" {
return errors.New("cacheFolderPath not set. Forgot to call Init()?")
}
return nil
}
func cleanupCache() error {
if err := validateCacheFolderPath(); err != nil {
return err
}
entries, err := os.ReadDir(cacheFolderPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
for _, entry := range entries {
name := entry.Name()
err := DeleteObject(name)
if err != nil && !errors.Is(err, ErrorInvalidCacheIdentifier) {
return err
}
}
return nil
}