From 4274276f478c26eebd5a8d0d8d7ea48c6eb140ee Mon Sep 17 00:00:00 2001 From: MichaelHatherly Date: Mon, 22 Apr 2024 14:59:51 +0100 Subject: [PATCH] Additional utility functions for keypair importing --- Project.toml | 1 + src/PackageBundler.jl | 1 + src/openssl.jl | 61 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/Project.toml b/Project.toml index 8443a08..f03852e 100644 --- a/Project.toml +++ b/Project.toml @@ -5,6 +5,7 @@ version = "0.1.0" [deps] Artifacts = "56f22d72-fd6d-98f1-02f0-08ddc0907c33" +Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f" CodecZlib = "944b1d66-785c-5afd-91f1-9de20f533193" OpenSSL_jll = "458c3c95-2e84-50aa-8efc-19380b2a3a95" Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f" diff --git a/src/PackageBundler.jl b/src/PackageBundler.jl index 4a2e60a..1325a72 100644 --- a/src/PackageBundler.jl +++ b/src/PackageBundler.jl @@ -3,6 +3,7 @@ module PackageBundler # Imports. import Artifacts +import Base64 import CodecZlib import OpenSSL_jll import Pkg diff --git a/src/openssl.jl b/src/openssl.jl index 244b1d2..e5156c1 100644 --- a/src/openssl.jl +++ b/src/openssl.jl @@ -26,6 +26,67 @@ function keypair(dir::AbstractString = pwd()) return (; private, public) end +function print_base64_keypair(path::String) + pri = read("$path.pem", String) + pub = read("$path.pub", String) + println("PRIVATE_KEY_BASE64 = \"$(Base64.base64encode(pri))\"\n") + println("PUBLIC_KEY_BASE64 = \"$(Base64.base64encode(pub))\"\n") +end + +""" + import_keypair(; + file="key", + base64=true, + private="PRIVATE_KEY_BASE64", + public="PUBLIC_KEY_BASE64", + ) + +Import a key pair from environment variables and save them to files. The private +key is saved as `\$file.pem` and the public key is saved as `\$file.pub`. The +private key is decoded from the environment variable specified by `private` and +the public key is decoded from the environment variable specified by `public`. + +When not running in CI, this function does nothing. +""" +function import_keypair(; + file::String = "key", + base64::Bool = true, + private::String = "PRIVATE_KEY_BASE64", + public::String = "PUBLIC_KEY_BASE64", +) + if get(ENV, "CI", "false") == "false" + @warn "This function is only useful in CI." + return nothing + end + + pri = haskey(ENV, private) ? ENV[private] : error("Private key `$private` not found.") + pub = haskey(ENV, public) ? ENV[public] : error("Public key `$public` not found.") + + pri = base64 ? Base64.base64decode(pri) : pri + pub = base64 ? Base64.base64decode(pub) : pub + + private_file = "$file.pem" + public_file = "$file.pub" + + write(private_file, pri) + write(public_file, pub) + + atexit() do + try + rm(private_file, force = true) + catch error + @error "Failed to remove private key file." error + end + try + rm(public_file, force = true) + catch error + @error "Failed to remove public key file." error + end + end + + return nothing +end + function _sign_file(file, private_key) openssl = OpenSSL_jll.openssl() cmd = Cmd([