构建期间的 SSH 转发仅适用于 root

SSH-forwarding during build only works for root

这是一个 Docker 有效的文件:

# syntax=docker/dockerfile:1.0.0-experimental
FROM debian:buster-slim as base

# setup APT operation for noninteractive use
# This avoids a bunch of warnings like
# "debconf: unable to initialize frontend: Dialog"
ENV DEBIAN_FRONTEND=noninteractive

# install requirements
RUN apt-get update \
    && apt-get upgrade -y \
    && apt-get install -y --no-install-recommends \
        git \
        openssh-client

# add a user
# RUN adduser --disabled-password app-user
# WORKDIR /home/app-user
# USER app-user

RUN mkdir --mode=0700 ~/.ssh
RUN printf "Host <bitbucket host>\n  StrictHostKeyChecking no\n  CheckHostIP no\n" >> ~/.ssh/config
RUN chmod 600 ~/.ssh/config
RUN --mount=type=ssh ssh-keyscan -t rsa <bitbucket host> >> ~/.ssh/known_hosts
RUN chmod 600 ~/.ssh/known_hosts

RUN --mount=type=ssh git clone --no-checkout 'ssh://git@<bitbucket host>/my/project.git'

我唯一编辑掉的是实际的 Bitbucket 主机。现在,不起作用的是激活“添加用户”注释后的三个命令。如果激活这三个命令,构建将失败并显示:

#20 [13/13] RUN --mount=type=ssh git clone --no-checkout 'ssh://git@bitbucke...
#20       digest: sha256:2ca1...
#20         name: "[13/13] RUN --mount=type=ssh git clone --no-checkout 'ssh://git@<bitbucket host>/my/project.git'"
#20      started: 2020-03-31 20:12:44.957895838 +0000 UTC
#20 0.648 Cloning into 'project'...
#20 1.170 git@<bitbucket host>: Permission denied (publickey).
#20 1.171 fatal: Could not read from remote repository.
#20 1.171 
#20 1.171 Please make sure you have the correct access rights
#20 1.171 and the repository exists.
#20    completed: 2020-03-31 20:12:46.235264455 +0000 UTC
#20     duration: 1.277368617s
#20        error: "executor failed running [/bin/sh -c git clone --no-checkout 'ssh://git@<bitbucket host>/my/project.git']: exit code: 128"

rpc error: code = Unknown desc = executor failed running [/bin/sh -c git clone --no-checkout 'ssh://git@<bitbucket host>/my/project.git']: exit code: 128

这是 Docker 中的错误吗?我是否错过了这不应该以某种方式起作用的暗示?我是否需要在根帐户和新用户帐户之间设置额外的转发级别? git/ssh 首先如何与代理建立通信?我检查了 /tmp/run、坐骑和环境,但找不到 pipe/socket。

明显的解决方法是以 root 身份克隆,然后在其上 运行 chown -R,但这看起来很不雅观。另外,我显然想了解发生了什么。

Buildkit --mount=type=ssh 指令将主机的 ssh 代理套接字重新挂载到具有特定权限的容器中。默认值由 root (uid=0, gid=0) 所有,任何其他用户都无法读取 (mode=0600)。

您可以添加一个选项,使套接字由某个已知的非根用户拥有:

# When you create the user specify its uid
RUN adduser --disabled-password --uid 999 app-user
USER app-user

# Also specify the uid as a mount option
RUN --mount=type=ssh,uid=999 ssh-keyscan ...

您还可以让其他用户访问套接字(这不是一个很大的安全问题,因为它只能在单个 RUN 命令的生命周期内访问,并且您可以控制它是什么 运行)

RUN --mount=type=ssh,mode=0666 ssh-keyscan ...