Debian Codegraph @

persist/file.go

raw symbols SCIP
1 package persist
2
3 import (
4 "io/ioutil"
5 "os"
6
7 "github.com/cloudflare/redoctober/config"
8 "github.com/cloudflare/redoctober/keycache"
9 "github.com/cloudflare/redoctober/passvault"
10 )
11
12 // File implements a file-backed persistence store.
13 type File struct {
14 config *config.Delegations
15 cache *keycache.Cache
16 state string
17 blob []byte
18 }
19
20 // Valid ensures the configuration is valid for a file store. Note
21 // that it won't validate the policy, it will just ensure that one
22 // is present.
23 func (f *File) Valid() bool {
24 if f.config.Persist == false {
25 return false
26 }
27
28 if f.config.Policy == "" {
29 return false
30 }
31
32 if len(f.config.Users) == 0 {
33 return false
34 }
35
36 if f.config.Mechanism != FileMechanism {
37 return false
38 }
39
40 if f.config.Location == "" {
41 return false
42 }
43
44 return true
45 }
46
47 // newFile returns a new file-backed persistence store.
48 func newFile(config *config.Delegations) (Store, error) {
49 cache := keycache.NewCache()
50 file := &File{
51 config: config,
52 cache: &cache,
53 state: Inactive,
54 }
55
56 if !file.Valid() {
57 return nil, ErrInvalidConfig
58 }
59
60 err := file.Load()
61 if err != nil {
62 return nil, err
63 }
64 return file, nil
65 }
66
67 func (f *File) Blob() []byte {
68 return f.blob
69 }
70
71 func (f *File) Policy() string {
72 return f.config.Policy
73 }
74
75 func (f *File) Users() []string {
76 return f.config.Users
77 }
78
79 func (f *File) Store(blob []byte) error {
80 if f.state == Active {
81 f.blob = blob
82 return ioutil.WriteFile(f.config.Location, blob, 0644)
83 }
84 return nil
85 }
86
87 func (f *File) Load() error {
88 if fi, err := os.Stat(f.config.Location); err != nil {
89 // If the file doesn't exist, it can be persisted
90 // immediately.
91 if os.IsNotExist(err) {
92 f.state = Active
93 return nil
94 }
95
96 return err
97 } else if fi.Size() == 0 {
98 f.state = Active
99 return nil
100 }
101
102 in, err := ioutil.ReadFile(f.config.Location)
103 if err != nil {
104 return err
105 }
106
107 f.state = Inactive
108 f.blob = in
109 return nil
110 }
111
112 func (f *File) Persist() {
113 f.state = Active
114 }
115
116 func (f *File) Cache() *keycache.Cache {
117 return f.cache
118 }
119
120 func (f *File) Delegate(record passvault.PasswordRecord, name, password string, users, labels []string, uses int, slot, durationString string) error {
121 return f.cache.AddKeyFromRecord(record, name, password, users, labels, uses, slot, durationString)
122 }
123
124 func (f *File) Status() *Status {
125 return &Status{
126 State: f.state,
127 Summary: f.cache.GetSummary(),
128 }
129 }
130
131 func (f *File) Purge() error {
132 f.state = Active
133 f.blob = nil
134 if err := os.Remove(f.config.Location); err != nil {
135 return err
136 }
137 return nil
138 }