-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgit-credential-s3-secrets
executable file
·94 lines (80 loc) · 2.39 KB
/
git-credential-s3-secrets
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/bash
set -eu
# The function creates global variables with the parsed results.
# It returns 0 if parsing was successful or non-zero otherwise.
#
# [schema://][user[:password]@]host[:port][/path][?[arg1=val1]...][#fragment]
#
# from http://vpalos.com/537/uri-parsing-using-bash-built-in-features/
parse_url() {
local uri="$*"
# safe escaping
uri="${uri//\`/%60}"
uri="${uri//\"/%22}"
# top level parsing
pattern='^(([a-z]{3,5})://)?((([^:\/]+)(:([^@\/]*))?@)?([^:\/?]+)(:([0-9]+))?)(\/[^?]*)?(\?[^#]*)?(#.*)?$'
[[ "$uri" =~ $pattern ]] || return 1;
# component extraction
uri=${BASH_REMATCH[0]}
export uri_schema=${BASH_REMATCH[2]}
export uri_address=${BASH_REMATCH[3]}
export uri_user=${BASH_REMATCH[5]}
export uri_password=${BASH_REMATCH[7]}
export uri_host=${BASH_REMATCH[8]}
export uri_port=${BASH_REMATCH[10]}
export uri_path=${BASH_REMATCH[11]}
export uri_query=${BASH_REMATCH[12]}
export uri_fragment=${BASH_REMATCH[13]}
# path parsing
count=0
path="$uri_path"
pattern='^/+([^/]+)'
while [[ $path =~ $pattern ]]; do
eval "uri_parts[$count]=\"${BASH_REMATCH[1]}\""
path="${path:${#BASH_REMATCH[0]}}"
(( count++ ))
done
# query parsing
count=0
query="$uri_query"
pattern='^[?&]+([^= ]+)(=([^&]*))?'
while [[ $query =~ $pattern ]]; do
eval "uri_args[$count]=\"${BASH_REMATCH[1]}\""
eval "uri_arg_${BASH_REMATCH[1]}=\"${BASH_REMATCH[3]}\""
query="${query:${#BASH_REMATCH[0]}}"
(( count++ ))
done
}
s3_download() {
local bucket="$1"
local region="$2"
local key="$3"
local aws_s3_args=("--quiet" "--region=${region}")
if [[ "${BUILDKITE_USE_KMS:-true}" =~ ^(true|1)$ ]] ; then
aws_s3_args+=("--sse" "aws:kms")
fi
local s3_uri="s3://${bucket}/${key}"
if ! aws s3 cp "${aws_s3_args[@]}" "${s3_uri}" - ; then
echo "Failed to download s3://$bucket/$key" >&2
exit 1
fi
}
bucket="$1"
region="$2"
key="$3"
action="${4:-get}"
# we only support get and we don't parse the stdin params
if [ "$action" == "get" ] ; then
# read git-credentials, which is a list of uris
s3_download "$bucket" "$region" "$key" | while read -r uri ; do
if ! parse_url "$uri" ; then
echo "Failed to parse uri $uri" >&2
exit 1
fi
# https://git-scm.com/docs/git-credential#IOFMT
echo "protocol=${uri_schema}"
echo "host=${uri_host}"
echo "username=${uri_user}"
echo "password=${uri_password}"
done
fi