vinix-ports / tests / feed.v
212 lines · 202 sloc · 8.37 KB
Raw
1// Build an isolated file repository and install its signed packages in a new SDK.
2module main
3
4import encoding.base64
5import x.json2
6import net.urllib
7import os
8
9fn output(argv []string) !string {
10 result := os.exec(argv)
11 if result.exit_code != 0 {
12 return error('${argv[0]} exited ${result.exit_code}: ${result.output}')
13 }
14 return result.output
15}
16
17fn gpg(keyring string, args []string) !string {
18 mut cmd := ['gpg', '--homedir', keyring, '--batch', '--no-tty']
19 cmd << args
20 return output(cmd)
21}
22
23fn trust_key(state string, key string, fingerprint string) ! {
24 trust := os.join_path(state, 'verify')
25 os.mkdir(trust, mode: 0o700)!
26 // GnuPG uses Unix sockets even for public imports. Deep SDK paths can
27 // exceed the socket name limit. Transfer only its public databases.
28 home := output(['mktemp', '-d', '/tmp/vinix-feed.XXXXXXXX'])!.trim_space()
29 defer { os.rmdir_all(home) or {} }
30 gpg(home, ['--no-autostart', '--import', key])!
31 records := gpg(home, ['--no-autostart', '--with-colons', '--fingerprint', '--list-keys'])!.split_into_lines()
32 fingerprints := records.filter(it.starts_with('fpr:'))
33 if records.filter(it.starts_with('pub:')).len != 1 || fingerprints.len == 0
34 || fingerprints[0].split(':')[9] != fingerprint {
35 return error('public key does not match the expected test signer fingerprint')
36 }
37 ownertrust := os.join_path(trust, 'fixture-ownertrust')
38 os.write_file(ownertrust, fingerprint + ':6:\n')!
39 gpg(home, ['--no-autostart', '--import-ownertrust', ownertrust])!
40 gpg(home, ['--no-autostart', '--check-trustdb'])!
41 keybox := if os.is_file(os.join_path(home, 'pubring.kbx')) { 'pubring.kbx' } else { 'pubring.gpg' }
42 for filename in [keybox, 'trustdb.gpg'] {
43 os.cp(os.join_path(home, filename), os.join_path(trust, filename))!
44 }
45}
46
47// Keep private signing material out of every repository and consumer root.
48fn keys(state string) ! {
49 os.mkdir(state, mode: 0o700)!
50 signer := os.join_path(state, 'signing')
51 os.mkdir(signer, mode: 0o700)!
52 gpg(signer, ['--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key',
53 'Vinix ports test signer <ports-test@example.invalid>', 'ed25519', 'sign', '0'])!
54 records := gpg(signer, ['--with-colons', '--fingerprint', '--list-keys'])!.split_into_lines()
55 fingerprints := records.filter(it.starts_with('fpr:'))
56 if fingerprints.len != 1 {
57 return error('expected one signing fingerprint in the new keyring')
58 }
59 fingerprint := fingerprints[0].split(':')[9]
60 os.write_file(os.join_path(state, 'signer.fingerprint'), fingerprint + '\n')!
61 public_key := os.join_path(state, 'signer.asc')
62 gpg(signer, ['--output', public_key, '--armor', '--export', fingerprint])!
63 trust_key(state, public_key, fingerprint)!
64}
65
66fn metadata_value(raw string, key string) !string {
67 prefix := key + ' = '
68 values := raw.split_into_lines().filter(it.starts_with(prefix))
69 if values.len != 1 {
70 return error('expected one ${key} in .PKGINFO')
71 }
72 return values[0][prefix.len..]
73}
74
75fn publish(state string, repo string, arch string, archives []string) ! {
76 fingerprint := os.read_file(os.join_path(state, 'signer.fingerprint'))!.trim_space()
77 signer := os.join_path(state, 'signing')
78 trust := os.join_path(state, 'verify')
79 os.mkdir(repo)!
80 stage := os.join_path(repo, '.staging')
81 os.mkdir(stage)!
82 mut names := map[string]bool{}
83 mut staged := []string{}
84 mut receipts := ['name\tversion\tarch\tarchive\tsha256']
85 mut signatures := map[string]string{}
86 for archive in archives {
87 name := os.file_name(archive)
88 target := os.join_path(stage, name)
89 if !name.ends_with('.pkg.tar.zst') || os.exists(target) {
90 return error('expected a distinct .pkg.tar.zst archive, got ${archive}')
91 }
92 os.cp(archive, target)!
93 raw := output(['bsdtar', '-xOf', target, '.PKGINFO'])!
94 id := metadata_value(raw, 'pkgname')!
95 pkg_arch := metadata_value(raw, 'arch')!
96 if id in names || pkg_arch !in [arch, 'any'] {
97 return error('duplicate package name or incompatible architecture: ${name}')
98 }
99 names[id] = true
100 digest := output(['sha256sum', target])!.all_before(' ')
101 version := metadata_value(raw, 'pkgver')!
102 receipts << [id, version, pkg_arch, name, digest].join('\t')
103 gpg(signer, ['--pinentry-mode', 'loopback', '--passphrase', '', '--local-user', fingerprint,
104 '--output', target + '.sig', '--detach-sign', target])!
105 gpg(trust, ['--verify', target + '.sig', target])!
106 signatures['${id}-${version}/desc'] = base64.encode(os.read_bytes(target + '.sig')!)
107 staged << target
108 }
109 mut repo_add := ['env', 'GNUPGHOME=' + signer, 'repo-add', '--nocolor', '--sign']
110 // Pacman 6 embeds signatures by default. Pacman 7 accepts an explicit flag.
111 if output(['repo-add', '--help'])!.contains('--include-sigs') {
112 repo_add << '--include-sigs'
113 }
114 db := os.join_path(stage, 'vinix.db.tar.gz')
115 repo_add << ['--key', fingerprint, db]
116 repo_add << staged
117 print(output(repo_add)!)
118 for member, signature in signatures {
119 if !output(['bsdtar', '-xOf', db, member])!.contains('\n%PGPSIG%\n' + signature + '\n') {
120 return error('signed database is missing the package signature in ${member}')
121 }
122 }
123 for index in ['vinix.db', 'vinix.files'] {
124 path := os.join_path(stage, index)
125 gpg(trust, ['--verify', path + '.sig', path])!
126 }
127 os.cp(os.join_path(state, 'signer.asc'), os.join_path(repo, 'test-signer.asc'))!
128 os.cp(os.join_path(state, 'signer.fingerprint'), os.join_path(repo, 'test-signer.fingerprint'))!
129 os.write_file(os.join_path(repo, 'packages.tsv'), receipts.join('\n') + '\n')!
130 os.rename(stage, os.join_path(repo, arch))!
131}
132
133fn install(state string, repo string, arch string, client string, packages []string, fakeroot bool) ! {
134 if packages.any(it.len == 0 || it.starts_with('-') || it.contains('/')) {
135 return error('expected package names from the signed repository')
136 }
137 os.mkdir(client)!
138 for subdir in ['root', 'db/local', 'db/sync', 'cache', 'hooks'] {
139 os.mkdir_all(os.join_path(client, subdir))!
140 }
141 os.write_file(os.join_path(client, 'db/local/ALPM_DB_VERSION'), '9\n')!
142 config := os.join_path(client, 'config.vile')
143 url := 'file://' + os.join_path(repo, arch).split('/').map(urllib.path_escape(it)).join('/')
144 os.write_file(config, [
145 'path-root = ' + json2.encode(os.join_path(client, 'root') + '/'),
146 'path-db = ' + json2.encode(os.join_path(client, 'db') + '/'),
147 'path-cache = [' + json2.encode(os.join_path(client, 'cache') + '/') + ']',
148 'path-gpg = ' + json2.encode(os.join_path(state, 'verify') + '/'),
149 'path-log = ' + json2.encode(os.join_path(client, 'vpac.log')),
150 'path-hook = [' + json2.encode(os.join_path(client, 'hooks') + '/') + ']',
151 'pkg-arch = ' + json2.encode(arch),
152 'network-siglevel = ["package", "database"]',
153 'network-user = ""',
154 'network-disable-sandbox = true',
155 'repositories = list(sync-repo("vinix", [' + json2.encode(url) + ']))',
156 ].join('\n') + '\n')!
157 mut cmd := if fakeroot { ['fakeroot', '--'] } else { ['unshare', '-Urn'] }
158 cmd << [os.find_abs_path_of_executable('vpac')!, '--config', config, 'i', '--noconfirm']
159 cmd << packages
160 os.setenv('LC_ALL', 'C', true)
161 result := os.exec(cmd)
162 os.write_file(os.join_path(client, 'install.log'), result.output)!
163 print(result.output)
164 if result.exit_code != 0 {
165 return error('vpac install exited ${result.exit_code}')
166 }
167 if result.output.split_into_lines().any(it.starts_with('error:')) {
168 return error('vpac reported a transaction error in the install log')
169 }
170}
171
172fn command(args []string) ! {
173 if args.len == 2 && args[0] == 'keys' {
174 keys(os.abs_path(args[1]))!
175 return
176 }
177 if args.len == 4 && args[0] == 'trust' {
178 state := os.abs_path(args[1])
179 os.mkdir(state, mode: 0o700)!
180 trust_key(state, os.abs_path(args[2]), args[3])!
181 return
182 }
183 if args.len >= 5 && args[3] in ['x86_64', 'aarch64'] {
184 state, repo := os.abs_path(args[1]), os.abs_path(args[2])
185 if args[0] == 'publish' {
186 publish(state, repo, args[3], args[4..])!
187 return
188 }
189 if args[0] == 'install' && args.len >= 6 {
190 fakeroot := args[5] == '--fakeroot'
191 first_package := if fakeroot { 6 } else { 5 }
192 packages := args[first_package..]
193 if packages.len == 0 {
194 return error('expected at least one package name')
195 }
196 install(state, repo, args[3], os.abs_path(args[4]), packages, fakeroot)!
197 return
198 }
199 }
200 eprintln('usage: feed keys NEW_KEY_STATE')
201 eprintln(' feed trust NEW_CLIENT_KEY_STATE PUBLIC_KEY EXPECTED_FINGERPRINT')
202 eprintln(' feed publish KEY_STATE NEW_REPO ARCH PACKAGE_ARCHIVE...')
203 eprintln(' feed install KEY_STATE REPO ARCH NEW_CLIENT [--fakeroot] PACKAGE_NAME...')
204 exit(2)
205}
206
207fn main() {
208 command(os.args[1..]) or {
209 eprintln(err)
210 exit(1)
211 }
212}
213