This repository has been archived by the owner on Mar 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
client_example.go
188 lines (158 loc) · 5.46 KB
/
client_example.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
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
// Copyright 2022-2023 VMware, Inc.
//
// This product is licensed to you under the BSD-2 license (the "License").
// You may not use this product except in compliance with the BSD-2 License.
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to
// the terms and conditions of the subcomponent's license, as noted in the
// LICENSE file.
//
// SPDX-License-Identifier: BSD-2-Clause
package main
import (
"fmt"
"io"
stdlog "log"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/go-logr/stdr"
"github.com/rdimitrov/go-tuf-metadata/metadata"
"github.com/rdimitrov/go-tuf-metadata/metadata/config"
"github.com/rdimitrov/go-tuf-metadata/metadata/updater"
)
// The following config is used to fetch a target from Jussi's GitHub repository example
const (
metadataURL = "https://jku.github.io/tuf-demo/metadata"
targetsURL = "https://jku.github.io/tuf-demo/targets"
targetName = "rdimitrov/artifact-example.md"
verbosity = 4
generateRandomFolder = false
)
func main() {
// set logger to stdout with info level
metadata.SetLogger(stdr.New(stdlog.New(os.Stdout, "client_example", stdlog.LstdFlags)))
stdr.SetVerbosity(verbosity)
log := metadata.GetLogger()
// initialize environment - temporary folders, etc.
metadataDir, err := InitEnvironment()
if err != nil {
log.Error(err, "Failed to initialize environment")
}
// initialize client with Trust-On-First-Use
err = InitTrustOnFirstUse(metadataDir)
if err != nil {
log.Error(err, "Trust-On-First-Use failed")
}
// download the desired target
err = DownloadTarget(metadataDir, targetName)
if err != nil {
log.Error(err, "Download failed")
}
}
// InitEnvironment prepares the local environment - temporary folders, etc.
func InitEnvironment() (string, error) {
var tmpDir string
// get working directory
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current working directory: %w", err)
}
if !generateRandomFolder {
tmpDir = filepath.Join(cwd, "tmp")
// create a temporary folder for storing the demo artifacts
os.Mkdir(tmpDir, 0750)
} else {
// create a temporary folder for storing the demo artifacts
tmpDir, err = os.MkdirTemp(cwd, "tmp")
if err != nil {
return "", fmt.Errorf("failed to create a temporary folder: %w", err)
}
}
// create a destination folder for storing the downloaded target
os.Mkdir(filepath.Join(tmpDir, "download"), 0750)
return tmpDir, nil
}
// InitTrustOnFirstUse initialize local trusted metadata (Trust-On-First-Use)
func InitTrustOnFirstUse(metadataDir string) error {
// check if there's already a local root.json available for bootstrapping trust
_, err := os.Stat(filepath.Join(metadataDir, "root.json"))
if err == nil {
return nil
}
// download the initial root metadata so we can bootstrap Trust-On-First-Use
rootURL, err := url.JoinPath(metadataURL, "1.root.json")
if err != nil {
return fmt.Errorf("failed to create URL path for 1.root.json: %w", err)
}
req, err := http.NewRequest("GET", rootURL, nil)
if err != nil {
return fmt.Errorf("failed to create http request: %w", err)
}
client := http.DefaultClient
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to executed the http request: %w", err)
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("failed to read the http request body: %w", err)
}
// write the downloaded root metadata to file
err = os.WriteFile(filepath.Join(metadataDir, "root.json"), data, 0644)
if err != nil {
return fmt.Errorf("failed to write root.json metadata: %w", err)
}
return nil
}
// DownloadTarget downloads the target file using Updater. The Updater refreshes the top-level metadata,
// get the target information, verifies if the target is already cached, and in case it
// is not cached, downloads the target file.
func DownloadTarget(localMetadataDir, target string) error {
log := metadata.GetLogger()
rootBytes, err := os.ReadFile(filepath.Join(localMetadataDir, "root.json"))
if err != nil {
return err
}
// create updater configuration
cfg, err := config.New(metadataURL, rootBytes) // default config
if err != nil {
return err
}
cfg.LocalMetadataDir = localMetadataDir
cfg.LocalTargetsDir = filepath.Join(localMetadataDir, "download")
cfg.RemoteTargetsURL = targetsURL
cfg.PrefixTargetsWithHash = true
// create a new Updater instance
up, err := updater.New(cfg)
if err != nil {
return fmt.Errorf("failed to create Updater instance: %w", err)
}
// try to build the top-level metadata
err = up.Refresh()
if err != nil {
return fmt.Errorf("failed to refresh trusted metadata: %w", err)
}
// search if the desired target is available
targetInfo, err := up.GetTargetInfo(target)
if err != nil {
return fmt.Errorf("target %s not found: %w", target, err)
}
// target is available, so let's see if the target is already present locally
path, _, err := up.FindCachedTarget(targetInfo, "")
if err != nil {
return fmt.Errorf("failed while finding a cached target: %w", err)
}
if path != "" {
log.Info("Target is already present", "target", target, "path", path)
}
// target is not present locally, so let's try to download it
path, _, err = up.DownloadTarget(targetInfo, "", "")
if err != nil {
return fmt.Errorf("failed to download target file %s - %w", target, err)
}
log.Info("Successfully downloaded target", "target", target, "path", path)
return nil
}