|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +# Check if any PGP key in scripts/keys expires within the next two weeks. |
| 4 | +# Exit with a non-zero status if any key is near expiration. |
| 5 | + |
| 6 | +set -euo pipefail |
| 7 | + |
| 8 | +KEY_DIR="./scripts/keys" |
| 9 | + |
| 10 | +if [[ ! -d "$KEY_DIR" ]]; then |
| 11 | + echo "ERROR: Directory $KEY_DIR does not exist" |
| 12 | + exit 1 |
| 13 | +fi |
| 14 | + |
| 15 | +shopt -s nullglob |
| 16 | +key_files=("$KEY_DIR"/*.asc) |
| 17 | +if (( ${#key_files[@]} == 0 )); then |
| 18 | + echo "ERROR: No PGP keys found in $KEY_DIR" |
| 19 | + exit 0 |
| 20 | +fi |
| 21 | + |
| 22 | +EXPIRE_THRESHOLD=$(date -d "2 weeks" +%s) |
| 23 | +exit_code=0 |
| 24 | + |
| 25 | +reset_key_vars() { |
| 26 | + current_key_type="" |
| 27 | + current_expiry="" |
| 28 | +} |
| 29 | + |
| 30 | +for key_file in "${key_files[@]}"; do |
| 31 | + gpg_output=$(gpg --with-colons --import-options show-only --import "$key_file" 2>&1) |
| 32 | + |
| 33 | + key_name=$(basename "$key_file") |
| 34 | + key_expiry_found=false |
| 35 | + |
| 36 | + # Parse GPG output line by line to find key type, expiry and fingerprint |
| 37 | + while IFS=: read -r type _ _ _ _ _ expiry _ _ fingerprint _; do |
| 38 | + if [[ "$type" == "pub" || "$type" == "sub" ]]; then |
| 39 | + # Store the key type and expiry for the next fpr line |
| 40 | + current_key_type="$type" |
| 41 | + current_expiry="$expiry" |
| 42 | + key_expiry_found=true |
| 43 | + continue |
| 44 | + fi |
| 45 | + |
| 46 | + # Skip if not a fingerprint line or no current key type |
| 47 | + if [[ "$type" != "fpr" || -z "$current_key_type" ]]; then |
| 48 | + continue |
| 49 | + fi |
| 50 | + |
| 51 | + key_info="$key_name $current_key_type fpr:${fingerprint:-unknown}" |
| 52 | + |
| 53 | + # If expiry is empty, the key does not expire |
| 54 | + if [[ -z "$current_expiry" ]]; then |
| 55 | + echo "INFO: $key_info does not expire" |
| 56 | + reset_key_vars |
| 57 | + continue |
| 58 | + fi |
| 59 | + |
| 60 | + # Convert expiry timestamp to human readable date for comparison |
| 61 | + if ! expiry_date=$(date -d "@$current_expiry" "+%Y-%m-%d" 2>/dev/null); then |
| 62 | + echo "ERROR: Invalid expiry timestamp for $key_info $current_expiry" |
| 63 | + exit_code=1 |
| 64 | + reset_key_vars |
| 65 | + continue |
| 66 | + fi |
| 67 | + |
| 68 | + # Check if key expires within settled threshold |
| 69 | + if (( current_expiry < EXPIRE_THRESHOLD )); then |
| 70 | + echo "ERROR: $key_info expires soon ($expiry_date)" |
| 71 | + exit_code=1 |
| 72 | + else |
| 73 | + echo "INFO: $key_info is valid until $expiry_date" |
| 74 | + fi |
| 75 | + |
| 76 | + reset_key_vars |
| 77 | + done <<< "$gpg_output" |
| 78 | + |
| 79 | + if [[ "$key_expiry_found" == false ]]; then |
| 80 | + echo "ERROR: Could not find any pub or sub keys for $key_name" |
| 81 | + exit_code=1 |
| 82 | + fi |
| 83 | +done |
| 84 | + |
| 85 | +exit $exit_code |
0 commit comments