Repository navigation
Expand file tree
/
Copy pathsecrets.sh
More file actions
executable file
·51 lines (44 loc) · 1.47 KB
/
Copy pathsecrets.sh
File metadata and controls
executable file
·51 lines (44 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/bash
# Secrets never live in files. An environment variable with the secret's name wins;
# otherwise it comes from the macOS Keychain (service "kings", account = secret name).
#
# secret_get <NAME> prints the value, fails if not set
# secret_source <NAME> prints where it comes from: env, keychain or nothing
# secret_set <NAME> stores in the Keychain, prompting for the value
# secret_delete <NAME> removes from the Keychain
KINGS_KEYCHAIN_SERVICE="kings"
# Letters, digits and _, not starting with a digit: a valid environment variable name.
secret_valid_name() {
case "$1" in
'' | [0-9]* | *[!A-Za-z0-9_]*) return 1 ;;
esac
}
_secret_keychain() {
security find-generic-password -s "$KINGS_KEYCHAIN_SERVICE" -a "$1" -w 2> /dev/null
}
secret_get() {
secret_valid_name "$1" || return 1
# ${!1} reads the variable whose name is in $1.
if [ -n "${!1}" ]; then
printf '%s\n' "${!1}"
return 0
fi
_secret_keychain "$1"
}
secret_source() {
secret_valid_name "$1" || return 1
if [ -n "${!1}" ]; then
echo env
elif _secret_keychain "$1" > /dev/null; then
echo keychain
fi
}
secret_set() {
secret_valid_name "$1" || return 1
# -U updates an existing entry; -w last makes `security` prompt for the value.
security add-generic-password -U -s "$KINGS_KEYCHAIN_SERVICE" -a "$1" -w
}
secret_delete() {
secret_valid_name "$1" || return 1
security delete-generic-password -s "$KINGS_KEYCHAIN_SERVICE" -a "$1" > /dev/null 2>&1
}