Skip to content

Commit 476b790

Browse files
committed
keygen: try to export a key to find whether it exists
This seems to be much faster than `--list-secret-keys` on our production instance.
1 parent 0b7d458 commit 476b790

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

keygen/src/copr_keygen/logic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def user_exists(app, mail):
7373
:raises: GpgErrorException
7474
7575
"""
76-
cmd = gpg_cmd + ["--list-secret-keys", "--with-colons", "<{0}>".format(mail)]
76+
cmd = gpg_cmd + ["--armor", "--batch", "--export", "<{0}>".format(mail)]
7777

7878
try:
7979
handle = Popen(cmd, stdout=PIPE, stderr=PIPE)
@@ -83,12 +83,12 @@ def user_exists(app, mail):
8383
raise GpgErrorException(msg="unhandled exception during gpg call",
8484
cmd=" ".join(cmd), err=e)
8585

86-
if handle.returncode == 0:
86+
if "BEGIN PGP PUBLIC KEY BLOCK" in stdout.decode("utf-8"):
8787
# TODO: validate that the key is ultimately trusted
8888
log.debug("user {} has keys in keyring".format(mail))
8989
ensure_passphrase_exist(app, mail)
9090
return True
91-
elif "error reading key" in stderr.decode():
91+
elif "nothing exported" in stderr.decode("utf-8"):
9292
log.debug("user {} not found in keyring".format(mail))
9393
return False
9494
else:

keygen/tests/test_logic.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,15 @@ def communicate(self):
103103
@mock.patch("copr_keygen.logic.Popen")
104104
class TestUserExists(TestCase):
105105
def test_exists(self, popen, ensure_passphrase):
106-
popen.return_value = MockPopenHandle(0)
106+
stdout = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQENB..."
107+
popen.return_value = MockPopenHandle(stdout=stdout)
107108
ensure_passphrase.return_value = True
108109
assert logic.user_exists(app, TEST_EMAIL)
109110

110111
def test_not_exists(self, popen, ensure_passphrase):
111-
popen.return_value = MockPopenHandle(1, stderr="error reading key")
112+
# The exit code for the GPG command is zero even on failure
113+
stderr = "gpg: WARNING: nothing exported"
114+
popen.return_value = MockPopenHandle(0, stderr=stderr)
112115
ensure_passphrase.return_value = True
113116
assert not logic.user_exists(app, TEST_EMAIL)
114117

0 commit comments

Comments
 (0)