-
Notifications
You must be signed in to change notification settings - Fork 19
/
storage.go
62 lines (49 loc) · 1.43 KB
/
storage.go
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
package storage
import (
"encoding/base64"
"fmt"
"io/fs"
"strings"
"github.com/moov-io/cryptfs"
)
type Chest interface {
Open(path string) (fs.File, error)
Glob(pattern string) ([]FileStat, error)
ReadDir(name string) ([]fs.DirEntry, error)
ReplaceFile(oldpath, newpath string) error
ReplaceDir(oldpath, newpath string) error
MkdirAll(path string) error
RmdirAll(path string) error
WriteFile(path string, contents []byte) error
}
// New returns a Chest given the configuration provided. It can also wrap that Chest
// in an encryption routine on each operation.
func New(cfg Config) (Chest, error) {
underlying, err := NewFilesystem(cfg.Filesystem.Directory)
if err != nil {
return nil, fmt.Errorf("error initializing filesystem storage: %w", err)
}
if cfg.Encryption.AES != nil {
enc, err := createBase64AESCryptor(cfg.Encryption.AES.Base64Key)
if err != nil {
return nil, fmt.Errorf("error creating AES cryptor: %w", err)
}
fs, err := cryptfs.New(enc)
if err != nil {
return nil, fmt.Errorf("error creating cryptfs: %w", err)
}
switch strings.ToLower(cfg.Encryption.Encoding) {
case "base64":
fs.SetCoder(cryptfs.Base64())
}
return NewEncrypted(underlying, fs), nil
}
return underlying, nil
}
func createBase64AESCryptor(key string) (*cryptfs.AESCryptor, error) {
decoded, err := base64.RawStdEncoding.DecodeString(key)
if err != nil {
return nil, err
}
return cryptfs.NewAESCryptor(decoded)
}