From 9bb198ef051fc53decf5e7a79970c6a1f5204567 Mon Sep 17 00:00:00 2001
From: "Bastien S." <3069086-babson4@users.noreply.gitlab.com>
Date: Sat, 21 Sep 2024 15:25:27 +0000
Subject: [PATCH] fix: allow Skopeo to inherit Docker auth config

---
 templates/gitlab-ci-docker.yml | 30 ++++++++++++++++++++++++++----
 1 file changed, 26 insertions(+), 4 deletions(-)

diff --git a/templates/gitlab-ci-docker.yml b/templates/gitlab-ci-docker.yml
index 4e8fd79..755e8f8 100644
--- a/templates/gitlab-ci-docker.yml
+++ b/templates/gitlab-ci-docker.yml
@@ -518,6 +518,22 @@ stages:
     done
   }
 
+  # simple JSON merge (used in Skopeo job only)
+  function merge_json() {
+    python3 -c "import json,sys
+  def merge(a,b):
+    for key in b:
+      if key in a and isinstance(a[key],dict) and isinstance(b[key],dict): a[key]=merge(a[key],b[key])
+      else: a[key]=b[key]
+    return a
+  def mergef(*files):
+    res={}
+    for f in files:
+      with open(f,'r') as rd: res=merge(res,json.load(rd))
+    return res
+  print(json.dumps(mergef(*sys.argv[1:])))" "$@"
+  }
+
   function wait_for_docker_daemon() {
     log_info "Wait for Docker daemon..."
     # shellcheck disable=SC2034
@@ -562,10 +578,16 @@ stages:
       echo "${docker_snapshot_config_json}" > "$BUILDTOOL_HOME/.docker/config.json"
     fi
 
-    # Create the configuration file for Skopeo
-    mkdir -p "$BUILDTOOL_HOME/skopeo/.docker"
-    echo "${docker_snapshot_config_json}" > "$BUILDTOOL_HOME/skopeo/.docker/src-config.json"
-    echo "${docker_release_config_json}" > "$BUILDTOOL_HOME/skopeo/.docker/dest-config.json"
+    # Create the configuration files for Skopeo
+    if command -v skopeo > /dev/null
+    then
+      mkdir -p "$BUILDTOOL_HOME/skopeo/.docker"
+      # use same auth config as the build tool for the source image
+      cp -f "$BUILDTOOL_HOME/.docker/config.json" "$BUILDTOOL_HOME/skopeo/.docker/src-config.json"
+      # use a merged auth config for the destination image
+      echo "${docker_release_config_json}" > "$BUILDTOOL_HOME/skopeo/.docker/release-only.json"
+      merge_json "$BUILDTOOL_HOME/skopeo/.docker/src-config.json" "$BUILDTOOL_HOME/skopeo/.docker/release-only.json" > "$BUILDTOOL_HOME/skopeo/.docker/dest-config.json"
+    fi
 
     log_info "Docker authentication configured for \\e[33;1m${docker_snapshot_registry_host}\\e[0m"
   }
-- 
GitLab