Debian Codegraph @

v0/client/testdata/go-tuf/generator/generator.go

raw
1 package generator
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "io/fs"
8 "log"
9 "os"
10 "path/filepath"
11 "time"
12
13 tuf "github.com/theupdateframework/go-tuf"
14 "github.com/theupdateframework/go-tuf/data"
15 "github.com/theupdateframework/go-tuf/pkg/keys"
16 )
17
18 var expirationDate = time.Date(2100, time.January, 1, 0, 0, 0, 0, time.UTC)
19
20 type persistedKeys struct {
21 Encrypted bool `json:"encrypted"`
22 Data []*data.PrivateKey `json:"data"`
23 }
24
25 func assertNoError(err error) {
26 if err != nil {
27 panic(fmt.Sprintf("assertion failed: %s", err))
28 }
29 }
30
31 // copyRepo recursively copies all regular files and directories under src
32 // to dst. In the case where any destination file/directory exists
33 // (including dst itself), an error is returned.
34 func copyRepo(src string, dst string) error {
35 copyToDest := func(path string, info fs.FileInfo, err error) error {
36 if err != nil {
37 return err
38 }
39 rel, err := filepath.Rel(src, path)
40 if err != nil {
41 return err
42 }
43 target := filepath.Join(dst, rel)
44 mode := info.Mode()
45 if mode.IsDir() {
46 return os.Mkdir(target, mode.Perm())
47 } else if mode.IsRegular() {
48 sfile, err := os.Open(path)
49 if err != nil {
50 return err
51 }
52 defer sfile.Close()
53 dfile, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode.Perm())
54 if err != nil {
55 return err
56 }
57 defer dfile.Close()
58 if _, err := io.Copy(dfile, sfile); err != nil {
59 return err
60 }
61 return nil
62 }
63 return fmt.Errorf("unknown mode %v", mode)
64 }
65 return filepath.Walk(src, copyToDest)
66 }
67
68 func newRepo(dir string) *tuf.Repo {
69 repo, err := tuf.NewRepoIndent(tuf.FileSystemStore(dir, nil), "", "\t")
70 assertNoError(err)
71
72 return repo
73 }
74
75 func commit(dir string, repo *tuf.Repo) {
76 assertNoError(repo.SnapshotWithExpires(expirationDate))
77 assertNoError(repo.TimestampWithExpires(expirationDate))
78 assertNoError(repo.Commit())
79
80 // Remove the keys directory to make sure we don't accidentally use a key.
81 assertNoError(os.RemoveAll(filepath.Join(dir, "keys")))
82 }
83
84 func addKeys(repo *tuf.Repo, roleKeys map[string][]*data.PrivateKey) {
85 for role, keyList := range roleKeys {
86 for _, key := range keyList {
87 signer, err := keys.GetSigner(key)
88 assertNoError(err)
89 assertNoError(repo.AddPrivateKeyWithExpires(role, signer, expirationDate))
90 }
91 }
92 }
93
94 func addTargets(repo *tuf.Repo, dir string, files map[string][]byte) {
95 paths := []string{}
96 for file, data := range files {
97 path := filepath.Join(dir, "staged", "targets", file)
98 assertNoError(os.MkdirAll(filepath.Dir(path), 0755))
99 assertNoError(os.WriteFile(path, data, 0644))
100 paths = append(paths, file)
101 }
102 assertNoError(repo.AddTargetsWithExpires(paths, nil, expirationDate))
103 }
104
105 func revokeKeys(repo *tuf.Repo, role string, keyList []*data.PrivateKey) {
106 for _, key := range keyList {
107 signer, err := keys.GetSigner(key)
108 assertNoError(err)
109 assertNoError(repo.RevokeKeyWithExpires(role, signer.PublicData().IDs()[0], expirationDate))
110 }
111 }
112
113 func generateRepos(dir string, roleKeys map[string][][]*data.PrivateKey, consistentSnapshot bool) {
114 // Collect all the initial keys we'll use when creating repositories.
115 // We'll modify this to reflect rotated keys.
116 keys := map[string][]*data.PrivateKey{
117 "root": roleKeys["root"][0],
118 "targets": roleKeys["targets"][0],
119 "snapshot": roleKeys["snapshot"][0],
120 "timestamp": roleKeys["timestamp"][0],
121 }
122
123 // Create the initial repo.
124 dir0 := filepath.Join(dir, "0")
125 repo0 := newRepo(dir0)
126 repo0.Init(consistentSnapshot)
127 addKeys(repo0, keys)
128 addTargets(repo0, dir0, map[string][]byte{"0": []byte("0")})
129 commit(dir0, repo0)
130
131 // Rotate all the keys to make sure that works.
132 oldDir := dir0
133 i := 1
134 for _, role := range []string{"root", "targets", "snapshot", "timestamp"} {
135 // Setup the repo.
136 stepName := fmt.Sprintf("%d", i)
137 d := filepath.Join(dir, stepName)
138 assertNoError(copyRepo(oldDir, d))
139 repo := newRepo(d)
140 addKeys(repo, keys)
141
142 // Actually rotate the keys
143 revokeKeys(repo, role, roleKeys[role][0])
144 addKeys(repo, map[string][]*data.PrivateKey{
145 role: roleKeys[role][1],
146 })
147 keys[role] = roleKeys[role][1]
148
149 // Add a target to make sure that works, then commit.
150 addTargets(repo, d, map[string][]byte{stepName: []byte(stepName)})
151 commit(d, repo)
152
153 i += 1
154 oldDir = d
155 }
156
157 // Add another target file to make sure the workflow worked.
158 stepName := fmt.Sprintf("%d", i)
159 d := filepath.Join(dir, stepName)
160 assertNoError(copyRepo(oldDir, d))
161 repo := newRepo(d)
162 addKeys(repo, keys)
163 addTargets(repo, d, map[string][]byte{stepName: []byte(stepName)})
164 commit(d, repo)
165 }
166
167 func Generate(dir string, keysPath string, consistentSnapshot bool) {
168 f, err := os.Open(keysPath)
169 assertNoError(err)
170
171 var roleKeys map[string][][]*data.PrivateKey
172 assertNoError(json.NewDecoder(f).Decode(&roleKeys))
173
174 log.Printf("generating %s", dir)
175
176 generateRepos(dir, roleKeys, consistentSnapshot)
177 }