-
Notifications
You must be signed in to change notification settings - Fork 14
/
environment_variable.go
82 lines (65 loc) · 1.75 KB
/
environment_variable.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package secrets
import (
"context"
"fmt"
"os"
"time"
"github.com/brexhq/substation/config"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/internal/errors"
)
type environmentVariableConfig struct {
ID string `json:"id"`
Name string `json:"name"`
TTLOffset string `json:"ttl_offset"`
}
func (c *environmentVariableConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *environmentVariableConfig) Validate() error {
if c.ID == "" {
return fmt.Errorf("id: %v", errors.ErrMissingRequiredOption)
}
if c.Name == "" {
return fmt.Errorf("name: %v", errors.ErrMissingRequiredOption)
}
return nil
}
type env struct {
conf environmentVariableConfig
ttl int64
}
func newEnvironmentVariable(_ context.Context, cfg config.Config) (*env, error) {
conf := environmentVariableConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, fmt.Errorf("secrets: environment_variable: %v", err)
}
if err := conf.Validate(); err != nil {
return nil, fmt.Errorf("secrets: environment_variable: %v", err)
}
ttl := conf.TTLOffset
if ttl == "" {
ttl = defaultTTL
}
dur, err := time.ParseDuration(ttl)
if err != nil {
return nil, fmt.Errorf("secrets: environment_variable: %v", err)
}
return &env{
conf: conf,
ttl: time.Now().Add(dur).Unix(),
}, nil
}
func (c *env) Retrieve(ctx context.Context) error {
if v, ok := os.LookupEnv(c.conf.Name); ok {
// SetWithTTL isn't used here because the TTL is managed by
// transform/utility_secret.go.
if err := cache.Set(ctx, c.conf.ID, v); err != nil {
return fmt.Errorf("secrets: environment_variable: id %s: %v", c.conf.ID, err)
}
}
return nil
}
func (c *env) Expired() bool {
return time.Now().Unix() >= c.ttl
}