Skip to content

Commit

Permalink
keygen: try to export a key to find whether it exists
Browse files Browse the repository at this point in the history
This seems to be much faster than `--list-secret-keys` on our
production instance.
  • Loading branch information
FrostyX committed Dec 11, 2023
1 parent 0b7d458 commit 476b790
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
6 changes: 3 additions & 3 deletions keygen/src/copr_keygen/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def user_exists(app, mail):
:raises: GpgErrorException
"""
cmd = gpg_cmd + ["--list-secret-keys", "--with-colons", "<{0}>".format(mail)]
cmd = gpg_cmd + ["--armor", "--batch", "--export", "<{0}>".format(mail)]

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

if handle.returncode == 0:
if "BEGIN PGP PUBLIC KEY BLOCK" in stdout.decode("utf-8"):
# TODO: validate that the key is ultimately trusted
log.debug("user {} has keys in keyring".format(mail))
ensure_passphrase_exist(app, mail)
return True
elif "error reading key" in stderr.decode():
elif "nothing exported" in stderr.decode("utf-8"):
log.debug("user {} not found in keyring".format(mail))
return False
else:
Expand Down
7 changes: 5 additions & 2 deletions keygen/tests/test_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,15 @@ def communicate(self):
@mock.patch("copr_keygen.logic.Popen")
class TestUserExists(TestCase):
def test_exists(self, popen, ensure_passphrase):
popen.return_value = MockPopenHandle(0)
stdout = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQENB..."
popen.return_value = MockPopenHandle(stdout=stdout)
ensure_passphrase.return_value = True
assert logic.user_exists(app, TEST_EMAIL)

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

Expand Down

0 comments on commit 476b790

Please sign in to comment.