summaryrefslogtreecommitdiff
path: root/secrets/put.sh
blob: b060255e02339e39c77a2fda31328ee9563fd465 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/bin/bash

set -euo pipefail

if [[ "$#" -gt 0 && ("$1" == "-h" || "$1" == "--help") ]]; then
    cat <<EOF
put: Store a secret, read from stdin

Encrypts stdin to the bucket's readers and the admins. Needs only public keys.

Usage:
  echo "value" | put <bucket>/<name>
  echo "value" | put <name>      the admin-only bucket, the narrowest set
  put -h|--help

Overwrites <name> where it already is. Refuses if <name> is in another bucket
(it moves with mv, never copies), if the bucket's readers or the admins changed
since its last rekey, or if there are no admins. A <name> still in the old
store is rewritten there until it moves. On a machine with no buckets, <name>
goes to the old store, as before buckets.
EOF
    exit 0
fi

this_dir="$(cd "$(dirname "$0")" && pwd)"
source "${this_dir}/common.sh"

if [[ "$#" -lt 1 ]]; then
    >&2 echo "ERROR: Need secret name"
    exit 1
fi
name="$1"

ensure_age

# Before buckets: the old store, as it always was.
if [[ -z "${buckets}" ]]; then
    [[ "${name}" != */* ]] || die "no buckets on this machine: ${name}"
    age_encrypt "${public_key}" "$(file_for "${name}")"
    exit 0
fi

if [[ "${name}" == */* ]]; then
    bucket="${name%%/*}"
    name="${name#*/}"
    [[ "${bucket}" =~ ${re_bucket} ]] || die "not a bucket's name: ${bucket}"
else
    bucket=""
fi
[[ "${name}" =~ ${re_secret} ]] || die "not a secret's name: ${name}"

found="$(locate "${name}")"
if [[ -z "${bucket}" ]]; then
    if [[ -n "${store}" && "${found}" == "${store}/${name}.age" ]]; then
        >&2 echo "szecret: ${name} is still in the old store; rewriting it there"
        age_encrypt "${public_key}" "${found}"
        exit 0
    fi
    if [[ -z "${found}" ]]; then
        bucket="admin-only"
        >&2 echo "szecret: storing ${name} in admin-only (put <bucket>/${name} for another bucket)"
    fi
fi
while read -r f; do
    [[ -n "${f}" && "${f}" != "${buckets}/${bucket}/${name}.age" ]] || continue
    if [[ -n "${store}" && "$(dirname "${f}")" == "${store}" ]]; then
        die "${name} is in the old store; szecret mv ${name} ${bucket:-<bucket>} moves it"
    fi
    die "${name} is in $(bucket_label "$(dirname "${f}")"); use $(where_is "${f}")"
done <<<"${found}"

dir="${buckets}/${bucket}"
set="$(bucket_set "${dir}")" || exit 1
age_version_ok
encrypt_to "${dir}/${name}.age" "${set}"