module signaturefixtures import os pub struct Keyring { pub: path string fingerprint string } pub fn command(tool string, args []string) !string { mut process := os.new_process(tool) process.set_args(args) process.set_redirect_stdio() process.set_stdin_path('/dev/null') process.run() defer { process.close() } output := process.stdout_slurp() diagnostic := process.stderr_slurp() process.wait() if process.code != 0 { return error('${tool} exited ${process.code}: ${diagnostic}') } return output } pub fn (ring Keyring) gpg(args []string) !string { mut all := ['--homedir', ring.path, '--batch', '--no-tty'] all << args return command('gpg', all) } pub fn empty(path string) !Keyring { os.mkdir_all(path)! os.chmod(path, 0o700)! // direct trust makes every trust class testable without network or a web of trust. os.write_file(os.join_path(path, 'gpg.conf'), 'no-auto-key-retrieve\nauto-key-locate clear\ntrust-model direct\n')! ring := Keyring{ path: path } ring.gpg(['--list-keys'])! return ring } pub fn create(path string) !Keyring { ring := empty(path)! fingerprint := ring.generate('Native ALPM Fixture ')! return Keyring{ path: path, fingerprint: fingerprint } } pub fn (ring Keyring) generate(uid string) !string { ring.gpg(['--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', uid, 'ed25519', 'sign', '0'])! return ring.find_fingerprint(uid) } pub fn (ring Keyring) generate_at(uid string, timestamp i64, expiry string) !string { ring.gpg(['--faked-system-time', '${timestamp}!', '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', uid, 'ed25519', 'sign', expiry])! return ring.find_fingerprint(uid) } fn (ring Keyring) find_fingerprint(uid string) !string { listing := ring.gpg(['--with-colons', '--fingerprint', '--list-keys', uid])! for line in listing.split_into_lines() { fields := line.split(':') if fields.len > 9 && fields[0] == 'fpr' { return fields[9] } } return error('generated key has no fingerprint') } pub fn (ring Keyring) sign_at(path string, fingerprint string, timestamp i64, expiry string) ! { ring.gpg(['--yes', '--faked-system-time', '${timestamp}!', '--pinentry-mode', 'loopback', '--passphrase', '', '--default-sig-expire', expiry, '--local-user', fingerprint, '--output', path + '.sig', '--detach-sign', '--', path])! } pub fn (ring Keyring) sign(path string, fingerprints []string, armored bool) ! { mut args := ['--yes', '--pinentry-mode', 'loopback', '--passphrase', ''] if armored { args << '--armor' } for fingerprint in fingerprints { args << ['--local-user', fingerprint] } args << ['--output', path + '.sig', '--detach-sign', '--', path] ring.gpg(args)! } pub fn (ring Keyring) trust(fingerprint string, value int) ! { path := os.join_path(ring.path, 'fixture-ownertrust') os.write_file(path, '${fingerprint}:${value}:\n')! ring.gpg(['--import-ownertrust', path])! } pub fn cleanup(path string) ! { if !os.is_dir(path) { return } command('gpgconf', ['--homedir', path, '--kill', 'all'])! os.rmdir_all(path)! }