-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
388 lines (361 loc) · 12.5 KB
/
config.go
File metadata and controls
388 lines (361 loc) · 12.5 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package app
import (
"fmt"
"log/slog"
"math"
"net/url"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/google/go-tpm/tpm2"
"github.com/spf13/viper"
)
// CosignBuildSignerConfig holds optional overrides for BuildSignerURI
// matching during cosign OID validation. When set, BuildSignerDigest is
// also skipped (it changes per-commit). When unset, both fields are
// compared for exact match against BuildInfo.
type CosignBuildSignerConfig struct {
URI string
URIRegex *regexp.Regexp // compiled from string config; nil if unset
}
// Config holds the resolved server configuration.
type Config struct {
BindHost string
BindPort int
LogFormat string
LogLevel slog.Level
BuildInfoPath string
EndorsementsPath string
PublicTLSCertPath string
PublicTLSKeyPath string
PublicTLSSkipVerify bool
PrivateTLSCertPath string
PrivateTLSKeyPath string
PrivateTLSCAPath string
ReportEvidence EvidenceConfig
ReportEnvVars []string
SecureBootEnforce bool
TPM TPMConfig
DependencyEndpoints []*url.URL
EndorsementDNSSEC bool
EndorsementAllowedDomains []string
EndorsementClientTimeout time.Duration
HTTPAllowProxy bool
HTTPCacheSize int64
HTTPCacheDefaultTTL time.Duration
RevocationEnabled bool
RevocationRefreshInterval time.Duration
RateLimitEnabled bool
RateLimitRPS float64
RateLimitBurst int
RateLimitStallTimeout time.Duration
CosignVerify bool
CosignURLSuffix string
CosignTUFCachePath string
CosignBuildSigner CosignBuildSignerConfig
}
// TPMConfig holds the configuration for generic TPM PCR reading.
type TPMConfig struct {
Enabled bool
Algorithm tpm2.TPMAlgID
AlgorithmName string
}
// EvidenceConfig holds the evidence type flags.
type EvidenceConfig struct {
NitroNSM bool
NitroTPM bool
SEVSNP bool
SEVSNPVMPL int
TDX bool
}
// LoadConfig reads configuration from viper (config file / env vars / pflags / defaults).
func LoadConfig() (*Config, error) {
evidence := EvidenceConfig{
NitroNSM: viper.GetBool("report.evidence.nitronsm"),
NitroTPM: viper.GetBool("report.evidence.nitrotpm"),
SEVSNP: viper.GetBool("report.evidence.sevsnp"),
SEVSNPVMPL: viper.GetInt("report.evidence.sevsnp_vmpl"),
TDX: viper.GetBool("report.evidence.tdx"),
}
if err := validateEvidence(evidence); err != nil {
return nil, err
}
tpmAlg, err := parseTPMAlgorithm(viper.GetString("tpm.algorithm"))
if err != nil {
return nil, err
}
tpmAlgName := strings.ToUpper(viper.GetString("tpm.algorithm"))
tpmCfg := TPMConfig{
Enabled: viper.GetBool("tpm.enabled"),
Algorithm: tpmAlg,
AlgorithmName: tpmAlgName,
}
envVars := splitCommaValues(viper.GetStringSlice("report.user_data.env"))
if err := validateEnvNames(envVars); err != nil {
return nil, err
}
depEndpoints, err := parseDependencyEndpoints(splitCommaValues(viper.GetStringSlice("dependencies.endpoints")))
if err != nil {
return nil, err
}
endorsementDomains := splitCommaValues(viper.GetStringSlice("endorsements.allowed_domains"))
if err := validateDomainAllowlist(endorsementDomains); err != nil {
return nil, err
}
endorsementTimeout, err := parseDuration("endorsements.client.timeout")
if err != nil {
return nil, err
}
if endorsementTimeout == 0 {
return nil, fmt.Errorf("endorsements.client.timeout: must be positive")
}
httpCacheSize, err := parseByteSize(viper.GetString("http.cache.size"))
if err != nil {
return nil, fmt.Errorf("http.cache.size: %w", err)
}
httpCacheDefaultTTL, err := parseDuration("http.cache.default_ttl")
if err != nil {
return nil, err
}
revocationRefreshInterval, err := parseDuration("revocation.refresh_interval")
if err != nil {
return nil, err
}
if revocationRefreshInterval == 0 {
return nil, fmt.Errorf("revocation.refresh_interval: must be positive")
}
rateLimitStallTimeout, err := parseDuration("ratelimit.stall_timeout")
if err != nil {
return nil, err
}
if rateLimitStallTimeout == 0 {
return nil, fmt.Errorf("ratelimit.stall_timeout: must be positive")
}
cosignBuildSigner := CosignBuildSignerConfig{
URI: viper.GetString("endorsements.cosign.build_signer.uri"),
}
if regexStr := viper.GetString("endorsements.cosign.build_signer.uri_regex"); regexStr != "" {
compiled, err := regexp.Compile(regexStr)
if err != nil {
return nil, fmt.Errorf("endorsements.cosign.build_signer.uri_regex: invalid regex: %w", err)
}
cosignBuildSigner.URIRegex = compiled
}
return &Config{
BindHost: viper.GetString("server.host"),
BindPort: viper.GetInt("server.port"),
LogFormat: viper.GetString("log.format"),
LogLevel: parseLogLevel(viper.GetString("log.level")),
BuildInfoPath: viper.GetString("paths.build_info"),
EndorsementsPath: viper.GetString("paths.endorsements"),
PublicTLSCertPath: absPath(viper.GetString("tls.public.cert_path")),
PublicTLSKeyPath: absPath(viper.GetString("tls.public.key_path")),
PublicTLSSkipVerify: viper.GetBool("tls.public.skip_verify"),
PrivateTLSCertPath: absPath(viper.GetString("tls.private.cert_path")),
PrivateTLSKeyPath: absPath(viper.GetString("tls.private.key_path")),
PrivateTLSCAPath: absPath(viper.GetString("tls.private.ca_path")),
ReportEvidence: evidence,
ReportEnvVars: envVars,
SecureBootEnforce: viper.GetBool("secure_boot.enforce"),
TPM: tpmCfg,
RevocationEnabled: viper.GetBool("revocation.enabled"),
RevocationRefreshInterval: revocationRefreshInterval,
RateLimitEnabled: viper.GetBool("ratelimit.enabled"),
RateLimitRPS: viper.GetFloat64("ratelimit.requests_per_second"),
RateLimitBurst: viper.GetInt("ratelimit.burst"),
RateLimitStallTimeout: rateLimitStallTimeout,
DependencyEndpoints: depEndpoints,
EndorsementDNSSEC: viper.GetBool("endorsements.dnssec"),
EndorsementAllowedDomains: endorsementDomains,
EndorsementClientTimeout: endorsementTimeout,
HTTPAllowProxy: viper.GetBool("http.allow_proxy"),
HTTPCacheSize: httpCacheSize,
HTTPCacheDefaultTTL: httpCacheDefaultTTL,
CosignVerify: viper.GetBool("endorsements.cosign.verify"),
CosignURLSuffix: viper.GetString("endorsements.cosign.url_suffix"),
CosignTUFCachePath: viper.GetString("endorsements.cosign.tuf_cache_path"),
CosignBuildSigner: cosignBuildSigner,
}, nil
}
// validateEvidence checks that at least one evidence type is enabled and that
// exclusive types (NitroNSM, TDX) are not combined with others.
func validateEvidence(e EvidenceConfig) error {
if !e.NitroNSM && !e.NitroTPM && !e.SEVSNP && !e.TDX {
return fmt.Errorf("report.evidence: at least one evidence type must be enabled")
}
if e.NitroNSM && (e.NitroTPM || e.SEVSNP || e.TDX) {
return fmt.Errorf("report.evidence: nitronsm cannot be combined with other evidence types")
}
if e.TDX && (e.NitroNSM || e.NitroTPM || e.SEVSNP) {
return fmt.Errorf("report.evidence: tdx cannot be combined with other evidence types")
}
return nil
}
var envNameRe = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
func validateEnvNames(names []string) error {
if dup := findDuplicate(names); dup != "" {
return fmt.Errorf("report.user_data.env contains duplicate value %q", dup)
}
for _, n := range names {
if !envNameRe.MatchString(n) {
return fmt.Errorf("report.user_data.env contains invalid environment variable name %q", n)
}
}
return nil
}
func findDuplicate(vals []string) string {
seen := make(map[string]bool, len(vals))
for _, v := range vals {
if seen[v] {
return v
}
seen[v] = true
}
return ""
}
// splitCommaValues expands a string slice so that comma-separated values
// within a single element are split into separate entries. This allows
// env vars (which viper delivers as a single string) to specify multiple
// values: VAR=a,b,c. TOML arrays already produce individual elements so
// the split is a no-op there.
func splitCommaValues(raw []string) []string {
var out []string
for _, s := range raw {
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part != "" {
out = append(out, part)
}
}
}
return out
}
// absPath converts a path to absolute. Returns the original on error or
// empty input. Used to normalize TLS cert paths for consistent directory
// comparison in validateTLSConfig and fsnotify watchers.
func absPath(p string) string {
if p == "" {
return ""
}
abs, err := filepath.Abs(p)
if err != nil {
return p
}
return abs
}
// parseDependencyEndpoints parses and validates dependency endpoint URLs.
// Only http and https schemes are allowed; http endpoints are expected to
// be reachable through a local mTLS-enabling proxy on the loopback interface.
func parseDependencyEndpoints(raw []string) ([]*url.URL, error) {
seen := make(map[string]bool, len(raw))
urls := make([]*url.URL, 0, len(raw))
for i, s := range raw {
if s == "" {
continue
}
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("dependencies.endpoints[%d]: invalid URL %q: %w", i, s, err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return nil, fmt.Errorf("dependencies.endpoints[%d]: scheme must be http or https, got %q", i, u.Scheme)
}
if u.Host == "" {
return nil, fmt.Errorf("dependencies.endpoints[%d]: missing host in %q", i, s)
}
if seen[s] {
return nil, fmt.Errorf("dependencies.endpoints contains duplicate value %q", s)
}
seen[s] = true
urls = append(urls, u)
}
return urls, nil
}
func parseTPMAlgorithm(s string) (tpm2.TPMAlgID, error) {
switch strings.ToLower(s) {
case "sha1":
return tpm2.TPMAlgSHA1, nil
case "sha256":
return tpm2.TPMAlgSHA256, nil
case "sha384":
return tpm2.TPMAlgSHA384, nil
case "sha512":
return tpm2.TPMAlgSHA512, nil
default:
return 0, fmt.Errorf("tpm.algorithm: unsupported algorithm %q (valid: sha1, sha256, sha384, sha512)", s)
}
}
func parseLogLevel(s string) slog.Level {
switch strings.ToLower(s) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}
// parseDuration reads a viper string key and parses it as a time.Duration.
// Returns an error if the value is empty, unparseable, or negative.
func parseDuration(key string) (time.Duration, error) {
s := viper.GetString(key)
d, err := time.ParseDuration(s)
if err != nil {
return 0, fmt.Errorf("%s: invalid duration %q: %w", key, s, err)
}
if d < 0 {
return 0, fmt.Errorf("%s: negative duration %q", key, s)
}
return d, nil
}
// parseByteSize parses a human-readable byte size string into a byte count
// using github.com/dustin/go-humanize. Supports both SI (KB, MB, GB, TB) and
// IEC (KiB, MiB, GiB, TiB) suffixes, fractional values, and flexible
// whitespace.
func parseByteSize(s string) (int64, error) {
s = strings.TrimSpace(s)
if s == "" {
return 0, fmt.Errorf("empty byte size")
}
n, err := humanize.ParseBytes(s)
if err != nil {
return 0, fmt.Errorf("invalid byte size %q: %w", s, err)
}
if n > uint64(math.MaxInt64) {
return 0, fmt.Errorf("byte size %q overflows int64", s)
}
return int64(n), nil
}
// domainNameRe matches valid DNS domain names (no ports, no paths).
var domainNameRe = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
// validateDomainAllowlist checks that all entries are valid DNS names with
// no duplicates.
func validateDomainAllowlist(domains []string) error {
if dup := findDuplicate(domains); dup != "" {
return fmt.Errorf("endorsements.allowed_domains contains duplicate %q", dup)
}
for _, d := range domains {
if !domainNameRe.MatchString(d) {
return fmt.Errorf("endorsements.allowed_domains: invalid domain name %q", d)
}
}
return nil
}
// CheckEndorsementDomain verifies that the hostname is in the allowed
// domains list. Returns nil if the allowlist is empty (unrestricted) or
// if the hostname exactly matches one of the allowed domains.
func CheckEndorsementDomain(host string, allowedDomains []string) error {
if len(allowedDomains) == 0 {
return nil
}
for _, d := range allowedDomains {
if strings.EqualFold(host, d) {
return nil
}
}
return fmt.Errorf("endorsement host %q not in allowed domains", host)
}