-
Notifications
You must be signed in to change notification settings - Fork 1
/
koch
executable file
·461 lines (421 loc) · 11.3 KB
/
koch
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/bin/sh
#
# Contributors:
# Fabio Pagnotta <fabiopagnotta.92@gmail.com> (author)
# Vladimir Mozharov
#
VERSION=1.2.1
# fail script when one of the command fails.
set -Eeuo pipefail # see https://stackoverflow.com/a/72103511
#
# Core logic
#
function gettoken {
# get token.
if [ $# -ne 4 ]; then
echo "Error: Token cannot be retrieved" >&2
exit 51
fi
local host="$1"
local user="$2"
local pass="$3"
local insecure="$4"
local add_comm=""
# see http://www.freekb.net/Article?id=3402
# todo improve fail scenario.
#
# openshift 3 -> location
# openshift 4 -> Location
#
if [ "$insecure" == "true" ]; then
add_comm=" --insecure "
else
add_comm=" --no-insecure "
fi
curl -s --fail $add_comm --request GET -u "$user:$pass" --header "X-CSRF-Token: xxx" --url "$host/oauth/authorize?response_type=token&client_id=openshift-challenging-client" --head | grep -i Location | perl -nle'print $& while m{(?<=implicit#access_token=).*(?=&expires_in)}g'
}
function login {
# Login using credentials
# $1 -> auth host
# $2 -> api server
# $3 -> user
# $4 -> pass
# $5 -> insecure (false,true)
local temp_token=$(gettoken $1 $3 $4 $5)
local api_access="$2"
loginwtoken "$api_access" "$temp_token" "$5"
}
function loginwtoken {
# Login using openshift token
# $1 -> api server
# $2 -> token api
# $3 -> insecure
oc login --token="$2" --server="$1" --insecure-skip-tls-verify="$3"
echo "Temp Token: $2"
}
function getprofilelist_action {
# $1 -> file name
profiles=$(yq -r '.profiles | keys | .[]' $1)
echo "$profiles"
}
function delete_action {
# Check if profile exists
ex=$(yq -r ".profiles | has(\"$2\") " $1)
if [ "${ex}" == "false" ]; then
echo "Profile not found" >&2
exit 6;
fi
# Delete profile
yq -i -r "del(.profiles.$2)" $1
}
function islogged {
# $1 - context name
#
# Probe whether pods exists.
#
set +Eeuo pipefail # see https://stackoverflow.com/a/72103511
contextres=$(oc config get-contexts "$context" > /dev/null 2>&1)
res=$?
if [ "$res" -ne 0 ]; then
echo "notexist" # context invalid
fi
# TODO this can be improved by using curl and get token from oc but it's fine.
pods=$(oc get pods --context "$1" > /dev/null 2>&1)
res=$?
if [ "$res" -eq 0 ]; then
echo "true" # Valid token
else
echo "false" # Invalid token
fi
set -Eeuo pipefail # see https://stackoverflow.com/a/72103511
}
function login_action {
# $1 -> file name
# $2 -> profile used
ex=$(yq -r ".profiles | has(\"$2\") " $1)
oauth=$(yq -r ".profiles.$2.oauth" $1)
api=$(yq -r ".profiles.$2.api" $1)
context=$(yq -r ".profiles.$2.context" $1)
insecure=$(yq -r ".profiles.$2.insecure" $1)
secrethandler=$(yq -r ".profiles.$2.secrethandler" $1)
secrethandlername=$(yq -r ".profiles.$2.secrethandlername" $1)
#echo "Ex: $ex, Auth: $oauth, api: $api, secrethandler: $secrethandler, secrethandlername: $secrethandlername"
user=""
pass=""
if [ "${ex}" == "false" ]; then
echo "Profile not found" >&2
exit 6;
fi
# This phase checks whether the context exists and the token is valid or not.
log=$(islogged "$context")
if [ "${log}" == "true" ]; then
echo "Context is already valid"
oc config use-context "$context"
exit 0;
fi
if [ "$secrethandler" == "default" ]; then
read -p "Insert username: " user
read -s -p "Insert password: " pass
elif [ "$secrethandler" == "bitwarden" ]; then
if ! command -v bw &> /dev/null
then
echo "bw command could not be found" >&2
exit 10
fi
bw sync 1>/dev/null
#Bitwarden does not sync in automatic way. We need to pull new db with updated passwords
set +Eeuo pipefail # see https://stackoverflow.com/a/72103511
item=$(bw get item "$secrethandlername")
res=$?
set -Eeuo pipefail # see https://stackoverflow.com/a/72103511
if [ "$res" -ne 0 ]; then
echo "bitwarden cannot find the secret $secrethandlername" >&2
echo "log: $item" >&2
exit 11
fi
user=$(printf "%s" "$item" | jq -r '.login.username')
pass=$(printf "%s" "$item" | jq -r '.login.password')
else
echo "Secret method $secrethandler not found"
exit 12
fi
#
# Performing authentication
#
login "$oauth" "$api" "$user" "$pass" "$insecure"
#
# Settings context.
#
if [ "${log}" == "true" ] || [ "${log}" == "false" ]; then
# means it exists, so we remove the old context
echo "Removing old context:$log"
oc config delete-context "$context"
fi
echo "Create new context"
oc config rename-context `oc config current-context` "$context"
echo "Done."
}
function psh_action {
# Create a new private shell
# $1 -> config filename
# $2 -> profile name
local kConfigfile
local kConfigTempfile
if [ -n "${KUBECONFIG+1}" ]; then
kConfigFile=$KUBECONFIG
fi
# Binds temporary kubeconfig
export KUBECONFIG=$(mktemp)
# Perform login action
login_action $1 $2
# Disables exit on error
set +Eeuo pipefail # see https://stackoverflow.com/a/72103511
echo ""
echo "Opening a new private shell"
trap "oc logout; rm -rf \"$KUBECONFIG\"; trap - EXIT; exit" INT HUP
$SHELL
echo "Closing the private shell.."
oc logout
echo "Recover the previous contexts"
# Shell closed, we can proceed
# Delete temporary file
rm $KUBECONFIG
# Recover the previous KUBECONFIG.
if [ -n "${kConfigFile+1}" ]; then
export KUBECONFIG=$kConfigFile
else
unset $KUBECONFIG
fi
# Disables exit on error
set -Eeuo pipefail # see https://stackoverflow.com/a/72103511
}
function defprofile_action {
# $1 -> file name
if [[ "${4}" != http* ]]; then
echo "Api server does not start with http: $4" >&2
exit 6;
fi
if [[ "${3}" != http* ]]; then
echo "Oauth server does not start with http" >&2
exit 6;
fi
yq -i "setpath([\"profiles\",\"$2\"]; {\"oauth\":\"$3\",\"api\":\"$4\",\"secrethandler\":\"$5\",\"secrethandlername\":\"$6\",\"context\":\"$7\",\"insecure\":\"$8\"})" $1
#yq ".profiles.$2 + {\"\": \"meow\"}" $1
}
function kinit {
[ ! -d $HOME/.koch ] && mkdir $HOME/.koch
touch $HOME/.koch/koch.yaml
}
# Set some default values:
# https://www.shellscript.sh/examples/getopt/
#
koch_config=$HOME/.koch/koch.yaml
if ! command -v jq &> /dev/null
then
echo "jq is required and is not installed." >&2
exit 11
fi
#if ! command -v bw &> /dev/null
#then
# echo "bw is required and is not installed."
# exit 11
#fi
if ! command -v yq &> /dev/null
then
echo "yq is required and is not installed." >&2
exit 11
fi
if ! command -v oc &> /dev/null
then
echo "oc is required and is not installed." >&2
exit 11
fi
if ! command -v curl &> /dev/null
then
echo "curl is required and is not installed." >&2
exit 11
fi
usage()
{
echo "Koch manages your cluster authentications and automates oc authentication."
echo "This program can request temporary token authentication on the fly without creating service accounts."
echo "Koch uses the oc client and curl to perform authentication through a proxy endpoint."
echo
echo "Commands:"
echo "version Returns the program version"
echo "config Prints cluster configurations"
echo "login Performs the login phase with the auth server and authenticates with the api server"
echo "psh Performs login command inside a Private SHell. Once the shell is closed, the context is also removed"
echo "logout Performs the logout phase"
echo "list List cluster configurations "
echo "define Defines cluster configuration "
echo "delete Delete cluster configuration "
echo "completion Generate bash and zsh scripts useful for shell completion "
echo
echo "Examples:"
echo "$0 login <context-name>"
echo "$0 psh <context-name>"
echo "$0 logout"
echo "$0 list"
echo "$0 config"
echo "$0 completion bash"
echo "$0 completion zsh"
echo "$0 define <context-name> --auth=\"\$AUTH_SERVER\" --api=\"\$API_SERVER\" --context=\"\$KUBECTL_CONTEXT\" --secrethandler=\"\$SECRETHANDLER\" --secretname=\"\$SECRETNAME\" --insecure=\"true\""
echo "$0 delete <context-name> "
echo "\$SECRETHANDLER can be "bitwarden" (bitwarden auth using bw) or "default" profile (that requests username and password by prompt)."
echo
echo "Contexts are saved in $HOME/.koch/koch.yaml"
exit 20;
}
if [ "$#" -le 0 ]; then
usage;
fi
# Action tool
action="$1"
if [ "$action" == "" ]; then
usage;
fi
# Kocube initialization
kinit;
if [ "$action" == "login" ]; then
#
# Performs login action.
#
if [ "$#" -eq 1 ]; then
usage;
fi
login_action $koch_config $2
elif [ "$action" == "delete" ]; then
#
# Delete context
#
if [ "$#" -eq 1 ]; then
usage;
fi
delete_action $koch_config $2
echo "Profile $2 deleted"
elif [ "$action" == "psh" ]; then
#
# Open a new private shell
#
if [ "$#" -eq 1 ]; then
usage;
fi
#
psh_action $koch_config $2
#
elif [ "$action" == "config" ]; then
#
# Print config file
#
cat $HOME/.koch/koch.yaml
elif [ "$action" == "completion" ]; then
#
# Completion shell
#
if [ "$#" -eq 1 ]; then
usage;
fi
shell=$2
if [ "$2" == "bash" ]; then
# Shell generate autocomplete script
# .[] removes list from yaml
cat << EOF
_dothis_completions()
{
if [ "\${#COMP_WORDS[@]}" != "2" ] && [ "\${#COMP_WORDS[@]}" != "3" ]; then
return;
fi
if [ "\${COMP_WORDS[1]}" != "login" ] && [ "\${COMP_WORDS[1]}" != "psh" ]; then
return;
fi
res=\$(yq -r '.profiles | keys | .[]' $HOME/.koch/koch.yaml )
COMPREPLY+=(\$(compgen -W "\$res" -- "\${COMP_WORDS[2]}"))
}
complete -F _dothis_completions $(basename $0)
EOF
elif [ "$2" == "zsh" ]; then
cat << EOF
_koch() {
_arguments \
'1: :->command' \
'2: :->subcommand'
if [[ \$#words[@] -ne 2 ]] && [[ \$#words[@] -ne 3 ]]; then
return;
fi
if [ "\$words[2]" != "login" ] && [ "\$words[2]" != "psh" ]; then
return;
fi
local res
res=(\$(yq -r '.profiles | keys | .[]' $HOME/.koch/koch.yaml ))
compadd "\$@" -a res
}
#compdef _koch $(basename $0)
compdef _koch $(basename $0)
EOF
else
echo "Shell not supported. Zsh and bash are available" >&2
exit 50
fi
elif [ "$action" == "version" ]; then
#
# Version
#
echo "$0 v$VERSION"
elif [ "$action" == "logout" ]; then
#
# Perform logout
#
oc logout
unset KUBECONFIG
elif [ "$action" == "list" ]; then
#
# Authenticate the user using profiles defined in yaml file.
#
getprofilelist_action $koch_config
elif [ "$action" == "define" ]; then
#
# Authenticate the user using profiles defined in yaml file.
#
PARSED_ARGUMENTS=$(getopt -n $0 -o poasci:d: --long profile:,oauth:,api:,secrethandler:,secretname:,context:,insecure: -- "$@")
VALID_ARGUMENTS=$?
# echo $VALID_ARGUMENTS
if [ "$VALID_ARGUMENTS" != "0" ]; then
usage
fi
host=unset
profile=unset
api=unset
sh=default
shn=unset
context=unset
insecure="false"
if [ "$#" -eq 1 ]; then
usage;
fi
profile="$2"
eval set -- "$PARSED_ARGUMENTS"
while :
do
case "$1" in
-o | --oauth) host="$2" ; shift 2 ;;
-a | --api) api="$2" ; shift 2 ;;
-s | --secrethandler) sh="$2" ; shift 2 ;;
-n | --secretname) shn="$2" ; shift 2 ;;
-c | --context) context="$2" ; shift 2 ;;
-i | --insecure) insecure="true" ; shift 2 ;;
--) shift; break ;;
*) echo "Unexpected option: $1 - this should not happen." >&2
usage ;;
esac
done
if [ "${profile}" == "unset" ] || [ "${host}" == "unset" ] || [ "${context}" == "unset" ] || [ "${api}" == "unset" ]; then
usage
exit 5;
fi
defprofile_action "$koch_config" "$profile" "$host" "$api" "$sh" "$shn" "$context" "$insecure"
echo "Profile $profile added"
echo "You can use it by executing $0 login $profile"
else
usage;
fi