Debian Codegraph @

store.go

raw
1 package desync
2
3 import (
4 "context"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "time"
11 )
12
13 const DefaultErrorRetry = 3
14 const DefaultErrorRetryBaseInterval = 500 * time.Millisecond
15
16 // Store is a generic interface implemented by read-only stores, like SSH or
17 // HTTP remote stores currently.
18 type Store interface {
19 GetChunk(id ChunkID) (*Chunk, error)
20 HasChunk(id ChunkID) (bool, error)
21 io.Closer
22 fmt.Stringer
23 }
24
25 // WriteStore is implemented by stores supporting both read and write operations
26 // such as a local store or an S3 store.
27 type WriteStore interface {
28 Store
29 StoreChunk(c *Chunk) error
30 }
31
32 // PruneStore is a store that supports read, write and pruning of chunks
33 type PruneStore interface {
34 WriteStore
35 Prune(ctx context.Context, ids map[ChunkID]struct{}) error
36 }
37
38 // IndexStore is implemented by stores that hold indexes.
39 type IndexStore interface {
40 GetIndexReader(name string) (io.ReadCloser, error)
41 GetIndex(name string) (Index, error)
42 io.Closer
43 fmt.Stringer
44 }
45
46 // IndexWriteStore is used by stores that support reading and writing of indexes.
47 type IndexWriteStore interface {
48 IndexStore
49 StoreIndex(name string, idx Index) error
50 }
51
52 // StoreOptions provide additional common settings used in chunk stores, such as compression
53 // error retry or timeouts. Not all options available are applicable to all types of stores.
54 type StoreOptions struct {
55 // Concurrency used in the store. Depending on store type, it's used for
56 // the number of goroutines, processes, or connection pool size.
57 N int `json:"n,omitempty"`
58
59 // Cert file name for HTTP SSL connections that require mutual SSL.
60 ClientCert string `json:"client-cert,omitempty"`
61 // Key file name for HTTP SSL connections that require mutual SSL.
62 ClientKey string `json:"client-key,omitempty"`
63
64 // CA certificates to trust in TLS connections. If not set, the systems CA store is used.
65 CACert string `json:"ca-cert,omitempty"`
66
67 // Trust any certificate presented by the remote chunk store.
68 TrustInsecure bool `json:"trust-insecure,omitempty"`
69
70 // Authorization header value for HTTP stores
71 HTTPAuth string `json:"http-auth,omitempty"`
72
73 // Cookie header value for HTTP stores
74 HTTPCookie string `json:"http-cookie,omitempty"`
75
76 // Timeout for waiting for objects to be retrieved. Infinite if negative. Default: 1 minute
77 Timeout time.Duration `json:"timeout,omitempty"`
78
79 // Number of times object retrieval should be attempted on error. Useful when dealing
80 // with unreliable connections.
81 ErrorRetry int `json:"error-retry,omitempty"`
82
83 // Number of nanoseconds to wait before first retry attempt.
84 // Retry attempt number N for the same request will wait N times this interval.
85 ErrorRetryBaseInterval time.Duration `json:"error-retry-base-interval,omitempty"`
86
87 // If SkipVerify is true, this store will not verify the data it reads and serves up. This is
88 // helpful when a store is merely a proxy and the data will pass through additional stores
89 // before being used. Verifying the checksum of a chunk requires it be uncompressed, so if
90 // a compressed chunkstore is being proxied, all chunks would have to be decompressed first.
91 // This setting avoids the extra overhead. While this could be used in other cases, it's not
92 // recommended as a damaged chunk might be processed further leading to unpredictable results.
93 SkipVerify bool `json:"skip-verify,omitempty"`
94
95 // Store and read chunks uncompressed, without chunk file extension
96 Uncompressed bool `json:"uncompressed"`
97
98 // Encrypt chunks in storage. The key is expected to be a hex-encoded 256-bit
99 // key, for example generated with `openssl rand -hex 32`. Supported algorithms
100 // are xchacha20-poly1305 (default) and aes-256-gcm.
101 Encryption bool `json:"encryption,omitempty"`
102 EncryptionAlgorithm string `json:"encryption-algorithm,omitempty"`
103 EncryptionKey string `json:"encryption-key,omitempty"`
104 }
105
106 // NewStoreOptionsWithDefaults creates a new StoreOptions struct with the default values set
107 func NewStoreOptionsWithDefaults() (o StoreOptions) {
108 o.ErrorRetry = DefaultErrorRetry
109 o.ErrorRetryBaseInterval = DefaultErrorRetryBaseInterval
110 return o
111 }
112
113 func (o *StoreOptions) UnmarshalJSON(data []byte) error {
114 // Set all the default values before loading the JSON store options
115 o.ErrorRetry = DefaultErrorRetry
116 o.ErrorRetryBaseInterval = DefaultErrorRetryBaseInterval
117 type Alias StoreOptions
118 return json.Unmarshal(data, (*Alias)(o))
119 }
120
121 // StorageConverters returns data converters that convert between plain and
122 // storage-format. Each layer represents a modification such as compression
123 // or encryption and is applied in order depending on the direction of data.
124 // If data is written to storage, the layer's toStorage method is called in
125 // the order they are returned. If data is read, the fromStorage method is
126 // called in reverse order.
127 func (o StoreOptions) StorageConverters() (Converters, error) {
128 var c Converters
129 if !o.Uncompressed {
130 c = append(c, Compressor{})
131 }
132 if !o.Encryption && o.EncryptionConfigured() {
133 // Refuse configs that set a key or algorithm without turning encryption
134 // on. Silently writing plaintext chunks is the one failure mode this
135 // feature must not have.
136 return nil, errors.New("encryption-key or encryption-algorithm configured without setting encryption to true")
137 }
138 if o.Encryption {
139 if o.EncryptionKey == "" {
140 return nil, errors.New("no encryption key configured")
141 }
142 key, err := hex.DecodeString(o.EncryptionKey)
143 if err != nil {
144 return nil, fmt.Errorf("invalid encryption key, expected hex-encoded 256-bit key: %w", err)
145 }
146 newAEAD := NewXChaCha20Poly1305
147 switch o.EncryptionAlgorithm {
148 case "", "xchacha20-poly1305":
149 case "aes-256-gcm":
150 newAEAD = NewAES256GCM
151 default:
152 return nil, fmt.Errorf("unsupported encryption algorithm %q", o.EncryptionAlgorithm)
153 }
154 enc, err := newAEAD(key)
155 if err != nil {
156 return nil, err
157 }
158 c = append(c, enc)
159 }
160 return c, nil
161 }
162
163 // EncryptionConfigured returns true if any of the encryption options is set,
164 // regardless of whether the combination is valid.
165 func (o StoreOptions) EncryptionConfigured() bool {
166 return o.Encryption || o.EncryptionKey != "" || o.EncryptionAlgorithm != ""
167 }
168
169 // ValidateIndexOptions returns an error if the options contain settings that
170 // don't apply to index stores. Encryption only covers chunks, indexes are
171 // always stored in plain form. Index stores reject encryption options rather
172 // than silently ignoring them, which could be mistaken for indexes being
173 // stored encrypted.
174 func (o StoreOptions) ValidateIndexOptions() error {
175 if o.EncryptionConfigured() {
176 return errors.New("encryption is not supported by index stores")
177 }
178 return nil
179 }