← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/lp-signing:generate-key-pair-path-options into lp-signing:master

 

Colin Watson has proposed merging ~cjwatson/lp-signing:generate-key-pair-path-options into lp-signing:master.

Commit message:
Extend generate-key-pair to take path options

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~cjwatson/lp-signing/+git/lp-signing/+merge/380014

These are helpful when generating service/client keys in an automated context.
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/lp-signing:generate-key-pair-path-options into lp-signing:master.
diff --git a/lp_signing/cli.py b/lp_signing/cli.py
index 7a52fc0..9b1d13c 100644
--- a/lp_signing/cli.py
+++ b/lp_signing/cli.py
@@ -3,6 +3,8 @@
 
 """Command-line tools for the signing service."""
 
+import os
+
 import click
 from flask.cli import FlaskGroup
 from flask_storm import store
@@ -42,7 +44,13 @@ def encode_key(key):
 
 
 @cli.command("generate-key-pair")
-def generate_key_pair():
+@click.option(
+    "--private-key-path", type=click.Path(dir_okay=False),
+    help="Output path for private key", show_default="standard output")
+@click.option(
+    "--public-key-path", type=click.Path(dir_okay=False),
+    help="Output path for public key", show_default="standard output")
+def generate_key_pair(private_key_path, public_key_path):
     """Generate a NaCl key pair.
 
     The resulting private and public keys are base64-encoded and can be
@@ -51,8 +59,19 @@ def generate_key_pair():
     necessary.
     """
     key = PrivateKey.generate()
-    print(f"Private: {encode_key(key)}")
-    print(f"Public:  {encode_key(key.public_key)}")
+    # When writing to standard output, we include "Private:" and "Public:"
+    # suffixes for disambiguation.
+    if private_key_path:
+        with open(private_key_path, "w") as private_key_file:
+            os.fchmod(private_key_file.fileno(), 0o600)
+            print(encode_key(key), file=private_key_file)
+    else:
+        print(f"Private: {encode_key(key)}")
+    if public_key_path:
+        with open(public_key_path, "w") as public_key_file:
+            print(encode_key(key.public_key), file=public_key_file)
+    else:
+        print(f"Public:  {encode_key(key.public_key)}")
 
 
 @cli.command("register-client")