From 2ac814ca4291302ab88e343bd4eaa888da4e88dd Mon Sep 17 00:00:00 2001 From: redxef Date: Mon, 29 Aug 2022 19:10:49 +0200 Subject: [PATCH] Add docker login if username/pw given. --- src/common | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/common b/src/common index c0c174a..a760f6f 100755 --- a/src/common +++ b/src/common @@ -1,11 +1,78 @@ #!/usr/bin/env sh + + +DEFAULT_DOMAIN=docker.io +LEGACY_DEFAULT_DOMAIN=index.docker.io +DOCKER_LOGIN_FILE_TMPL='{"auths": { {{REGISTRY_URL}}: { "auth": {{BASE64_UNAME_PW}} }}}' + +fail() { + echo "Error:" "$@" 1>&2 + exit 1 +} + +docker_login() { + login_name="$1" + if [ -z "$login_name" ]; then + login_name="$DEFAULT_DOMAIN" + fi + if [ "$login_name" = "$DEFAULT_DOMAIN" ]; then + login_name="$LEGACY_DEFAULT_DOMAIN/v1/" + fi + login_name="https://$login_name" + # TODO: detect registry url + mkdir -p "$HOME/.docker" + echo "$DOCKER_LOGIN_FILE_TMPL" | \ + sed -e "s|{{BASE64_UNAME_PW}}|$(printf '%s:%s' "$username" "$password" | base64)|g" \ + -e "s|{{REGISTRY_URL}}|$login_name|g" \ + > "$HOME/.docker/config.json" +} + +split_repo_domain() { + domain_part="$(echo "$1" | sed -n 's|^\([^/]*\)/.*$|\1|p')" + other_part="$(echo "$1" | sed -n "s|^$domain_part/\?\(.*\)$|\1|p")" + + if [ -z "$domain_part" ]; then + domain_part="$DEFAULT_DOMAIN" + other_part="$other_part" + elif echo "$domain_part" | grep -Evq '\.|:' && [ "$domain_part" != 'localhost' ]; then + # ^ docker sourcecode checks if $domain_part == $domain_part.lower() in effect checking if all is lower case + domain_part="$DEFAULT_DOMAIN" + other_part="$1" # we deviate here from the reference docker implementation + fi + if [ "$domain_part" = "$LEGACY_DEFAULT_DOMAIN" ]; then + domain_part="$DEFAULT_DOMAIN" + fi + if [ "$domain_part" = "$DEFAULT_DOMAIN" ] && echo "$other_part" | grep -vq /; then + other_part="library/$other_part" + fi + echo "$domain_part" + echo "$other_part" +} + INPUT_FILE="$(mktemp -t)" cat > "$INPUT_FILE" <&0 export INPUT_FILE REPOSITORY="$(jq -r .source.repository < "$INPUT_FILE")" -TAG="$(jq -r .source.tag < "$INPUT_FILE")" +TAG="$(jq -r '.source.tag // "latest"' < "$INPUT_FILE")" +USERNAME="$(jq -r .source.username < "$INPUT_FILE")" +PASSWORD="$(jq -r .source.password < "$INPUT_FILE")" export REPOSITORY export TAG + +if [ -n "$USERNAME" ]; then + if [ -z "$PASSWORD" ]; then + fail "need to also give password when logging in" + fi + if [ -z "$REPOSITORY" ]; then + docker_login '' + else + docker_login "$(split_repo_domain "$REPOSITORY" | head -n1)" + fi +fi + +if [ -z "$REPOSITORY" ]; then + fail "no repository specified" +fi