-
Notifications
You must be signed in to change notification settings - Fork 1
/
client
executable file
·151 lines (115 loc) · 4.03 KB
/
client
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
#!/usr/bin/env python3
"""TUF IPFS Client Example"""
import sys
import argparse
import os
from hashlib import sha256
from urllib import request
from tuf.api.exceptions import DownloadError, RepositoryError
from tufipfs.updater import IpfsUpdater
# constants
DOWNLOAD_DIR = "./downloads"
def ensure_trailing_slash(url: str) -> str:
"""Return url guaranteed to end in a slash."""
return url if url.endswith("/") else f"{url}/"
def build_metadata_dir(base_url: str) -> str:
"""build a unique and reproducible directory name for the repository url"""
name = sha256(base_url.encode()).hexdigest()[:8]
return f"./metadata/{name}"
def init_tofu(base_url: str) -> bool:
"""Initialize local trusted metadata (Trust-On-First-Use) and create a
directory for downloads"""
metadata_dir = build_metadata_dir(base_url)
if not os.path.isdir(metadata_dir):
os.makedirs(metadata_dir)
root_url = f"{base_url}/metadata/1.root.json"
try:
request.urlretrieve(root_url, f"{metadata_dir}/root.json")
except OSError:
print(f"Failed to download initial root from {root_url}")
return False
print(f"Trust-on-First-Use: Initialized new root in {metadata_dir}")
return True
def download(base_url: str, gateway: str, target: str) -> bool:
"""
Download the target file using ``IpfsUpdater``.
"""
metadata_dir = build_metadata_dir(base_url)
if not os.path.isfile(f"{metadata_dir}/root.json"):
print(
"Trusted local root not found. Use 'tofu' command to "
"Trust-On-First-Use or copy trusted root metadata to "
f"{metadata_dir}/root.json"
)
return False
print(f"Using trusted root in {metadata_dir}")
if not os.path.isdir(DOWNLOAD_DIR):
os.mkdir(DOWNLOAD_DIR)
try:
updater = IpfsUpdater(
metadata_dir=metadata_dir,
metadata_base_url=f"{base_url}/metadata/",
gateway=gateway,
target_base_url=f"{base_url}/targets/",
target_dir=DOWNLOAD_DIR,
)
updater.refresh()
info = updater.get_targetinfo(target)
if info is None:
print(f"Target {target} not found")
return True
path = updater.find_cached_target(info)
if path:
print(f"Target is available in {path}")
return True
path = updater.download_target(info)
print(f"Target downloaded and available in {path}")
except (OSError, RepositoryError, DownloadError) as ex:
print(f"Failed to download target {target}: {ex}")
return False
return True
def main() -> None:
"""Main TUF IPFS Client Example function"""
client_args = argparse.ArgumentParser(description="TUF IPFS Client Example")
# Global arguments
client_args.add_argument(
"-u",
"--url",
help="Base repository URL",
default="http://127.0.0.1:8001",
)
client_args.add_argument(
"-g",
"--gateway",
help="IPFS Gateway",
default="http://127.0.0.1:8081",
)
# Sub commands
sub_command = client_args.add_subparsers(dest="sub_command")
# Trust-On-First-Use
sub_command.add_parser(
"tofu",
help="Initialize client with Trust-On-First-Use",
)
# Download
download_parser = sub_command.add_parser(
"download",
help="Download a target file",
)
download_parser.add_argument(
"target",
metavar="TARGET",
help="Target file",
)
command_args = client_args.parse_args()
# initialize the TUF Client Example infrastructure
if command_args.sub_command == "tofu":
if not init_tofu(command_args.url):
return "Failed to initialize local repository"
elif command_args.sub_command == "download":
if not download(command_args.url, command_args.gateway, command_args.target):
return f"Failed to download {command_args.target}"
else:
client_args.print_help()
if __name__ == "__main__":
sys.exit(main())