diff --git a/AGENTS.md b/AGENTS.md index bb9e4904..90240cf5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,7 +77,7 @@ The valid layer stacks are declared in the `chains` dict in `utils/build_chain.p The `spark` layer installs the official Apache Spark distribution (`spark/scripts/install-spark.sh`)The only thing it adds is the S3A connector, whose jar versions are read from the distribution itself (the `hadoop-client-api` jar it ships, then the matching `hadoop-project` POM on Maven Central), so they are not pinned anywhere. -Tools downloaded at build time (kubectl, helm, AWS CLI, DuckDB CLI, quarto, opencode, Julia, code-server) are pinned in their install script, **not** in Dockerfiles (Dockerfiles only pin the versions the project manages: Python, R, Spark). Each script follows the same model, see `base/scripts/install-kubectl.sh`: +Tools downloaded at build time (kubectl, helm, AWS CLI, DuckDB CLI, quarto, git-credential-oauth, opencode, Julia, code-server) are pinned in their install script, **not** in Dockerfiles (Dockerfiles only pin the versions the project manages: Python, R, Spark). Each script follows the same model, see `base/scripts/install-kubectl.sh`: - a `# renovate: datasource= depName=` comment right above a `_VERSION="x.y.z"` line. One generic regex manager in `renovate.json` picks it up (in `scripts/*.sh` and in `.github/actions/*/action.yml`, where container-structure-test is pinned the same way), and all tool bumps land in a single weekly "Build tools" PR. -- the official release file is downloaded to a `mktemp -d` directory and verified before installing: against the upstream checksum file when there is one (kubectl, helm, quarto, Julia), against the SHA-256 GitHub records for the release asset (read from the GitHub API in the script, with `set -o pipefail`) when there is none (DuckDB, code-server), against the SHA-512 `integrity` the npm registry records for opencode (v2 is only published on npm), and with the PGP signature for the AWS CLI (the public key is embedded in `install-awscli.sh` and expires on 2027-07-01). +- the official release file is downloaded to a `mktemp -d` directory and verified before installing: against the upstream checksum file when there is one (kubectl, helm, quarto, git-credential-oauth, Julia), against the SHA-256 GitHub records for the release asset (read from the GitHub API in the script, with `set -o pipefail`) when there is none (DuckDB, code-server), against the SHA-512 `integrity` the npm registry records for opencode (v2 is only published on npm), and with the PGP signature for the AWS CLI (the public key is embedded in `install-awscli.sh` and expires on 2027-07-01). - amd64 only. diff --git a/README.md b/README.md index b5a31634..e01a1f55 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ If Onyxia support is checked, it means that the Onyxia product could inject auto | PIP_REPOSITORY | https://some.entreprise.mirror/repository/pypi-proxy/simple | Configure an externally managed pip repository manager | ✔️ | ✔️ | | R_REPOSITORY | https://some.entreprise.mirror/repository/cran | Configure an externally managed cran repository manager |not yet (*) | not yet (*) | | PATH_TO_CA_BUNDLE | /etc/ssl/certs/ca-certificates.crt | Configure a path to a ca bundle with autorities to support an auto-signed some.entreprise.mirror | not yet (*) | not yet (*) | +| GIT_PROVIDERS | `[{"id":"gitlab","url":"https://gitlab.example.com","user":{"name":"Jane","email":"jane@example.com"},"credentials":{"type":"token","username":"jane","token":"…"}}]` | Git forges to configure, as JSON: `git.providers` of the Onyxia context. Sets the commit identity and the credentials per forge, with a token (`credentials.type: "token"`) or OAuth through [git-credential-oauth](https://github.com/hickford/git-credential-oauth) (`credentials.type: "oauth"`). Takes over from `GIT_PERSONAL_ACCESS_TOKEN` for the forges it lists | not yet | not yet | +| GIT_REPOSITORIES | `[{"url":"https://gitlab.example.com/jane/project.git","branch":"main"}]` | Git repositories cloned at startup, as JSON: `git.repositories` of the chart values (other keys, such as `providerId`, are ignored). An empty `branch` clones the default branch. The credentials are those of `GIT_PROVIDERS`, no token goes in the URL. Takes over from `GIT_REPOSITORY`/`GIT_BRANCH` | not yet | not yet | (*) For now you should inject this another way, contact on onyxia slack for some recipes depend of your context. diff --git a/base/Dockerfile b/base/Dockerfile index 93ec1f38..957e2c03 100644 --- a/base/Dockerfile +++ b/base/Dockerfile @@ -43,6 +43,7 @@ RUN /opt/install-system-libs.sh && \ /opt/install-duckdb-cli.sh && \ /opt/install-duckdb-extensions.sh && \ /opt/install-quarto.sh && \ + /opt/install-git-credential-oauth.sh && \ # Fix user permissions /opt/fix-user-permissions.sh && \ # Clean diff --git a/base/scripts/install-git-credential-oauth.sh b/base/scripts/install-git-credential-oauth.sh new file mode 100755 index 00000000..2397606c --- /dev/null +++ b/base/scripts/install-git-credential-oauth.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e + +# renovate: datasource=github-releases depName=hickford/git-credential-oauth +GIT_CREDENTIAL_OAUTH_VERSION="0.18.0" + +# Download the official archive and verify its checksum +GIT_CREDENTIAL_OAUTH_URL="https://github.com/hickford/git-credential-oauth/releases/download/v${GIT_CREDENTIAL_OAUTH_VERSION}" +GIT_CREDENTIAL_OAUTH_ARCHIVE="git-credential-oauth_${GIT_CREDENTIAL_OAUTH_VERSION}_linux_amd64.tar.gz" +TMP_DIR=$(mktemp -d) +curl -fsSL "${GIT_CREDENTIAL_OAUTH_URL}/${GIT_CREDENTIAL_OAUTH_ARCHIVE}" -o "${TMP_DIR}/${GIT_CREDENTIAL_OAUTH_ARCHIVE}" +curl -fsSL "${GIT_CREDENTIAL_OAUTH_URL}/git-credential-oauth_${GIT_CREDENTIAL_OAUTH_VERSION}_checksums.txt" -o "${TMP_DIR}/checksums.txt" +(cd "${TMP_DIR}" && sha256sum --check --strict --ignore-missing checksums.txt) + +# Install git-credential-oauth +tar -xzf "${TMP_DIR}/${GIT_CREDENTIAL_OAUTH_ARCHIVE}" -C "${TMP_DIR}" +install -m 0755 "${TMP_DIR}/git-credential-oauth" /usr/local/bin/git-credential-oauth +rm -rf "${TMP_DIR}" diff --git a/base/scripts/onyxia-init.sh b/base/scripts/onyxia-init.sh index 9a913c64..1964f461 100755 --- a/base/scripts/onyxia-init.sh +++ b/base/scripts/onyxia-init.sh @@ -85,16 +85,161 @@ if [[ -z $ROOT_PROJECT_DIRECTORY ]]; then ROOT_PROJECT_DIRECTORY="$WORKSPACE_DIR" fi +# Some images start as root (RStudio): what is written in the home directory has to +# belong to the user, and the credential cache daemon has to run as the user. +git_as_user() { + if [[ $(id -u) = 0 ]]; then + sudo -u "$USERNAME" -H git "$@" + else + git "$@" + fi +} + +# Scheme, host and port of a URL: what git credentials are matched on. +git_url_origin() { + [[ "$1" =~ ^https?://[^/]+ ]] && echo "${BASH_REMATCH[0]}" +} + +# Configures an entry of GIT_PROVIDERS: the commit identity on this forge and the +# credentials that git uses for it. +configure_git_provider() { + local provider="$1" + local id url origin name email identity_file type + + id=$(jq -r '.id' <<< "$provider") + url=$(jq -r '.url' <<< "$provider") + origin=$(git_url_origin "$url") + if [[ -z "$origin" ]]; then + echo "skipping Git provider $id: not an http(s) URL" + return + fi + echo "configuration of the Git provider $id" + + name=$(jq -r '.user.name // empty' <<< "$provider") + email=$(jq -r '.user.email // empty' <<< "$provider") + identity_file="${HOME}/.gitconfig-onyxia-${id//[^a-zA-Z0-9_-]/_}" + [[ -n "$name" ]] && git_as_user config --file "$identity_file" user.name "$name" + [[ -n "$email" ]] && git_as_user config --file "$identity_file" user.email "$email" + if [[ -f "$identity_file" ]]; then + git_as_user config --global "includeIf.hasconfig:remote.*.url:${url}/**.path" "$identity_file" + fi + + type=$(jq -r '.credentials.type // empty' <<< "$provider") + [[ -z "$type" ]] && return + + # An empty value drops the helpers configured so far for this forge, the former + # credential.helper with a short timeout would otherwise evict the refresh token. + git_as_user config --global --replace-all "credential.${origin}.helper" "" + + case "$type" in + token) + git_as_user config --global --add "credential.${origin}.helper" store + jq -j --arg origin "$origin" \ + '"url=\($origin)\nusername=\(.credentials.username)\npassword=\(.credentials.token)\n\n"' <<< "$provider" | + git_as_user credential-store store + ;; + oauth) + local client_id scopes authorization_url token_url device_url refresh_token + client_id=$(jq -r '.credentials.clientId' <<< "$provider") + scopes=$(jq -r '.credentials.scopes | join(" ")' <<< "$provider") + authorization_url=$(jq -r '.credentials.authorizationUrl' <<< "$provider") + token_url=$(jq -r '.credentials.tokenUrl' <<< "$provider") + device_url=$(jq -r '.credentials.deviceAuthorizationUrl // empty' <<< "$provider") + refresh_token=$(jq -r '.credentials.refreshToken // empty' <<< "$provider") + + git_as_user config --global "credential.${origin}.oauthClientId" "$client_id" + git_as_user config --global "credential.${origin}.oauthScopes" "$scopes" + git_as_user config --global "credential.${origin}.oauthAuthURL" "$authorization_url" + git_as_user config --global "credential.${origin}.oauthTokenURL" "$token_url" + + # The cache keeps the access token and, unlike the store helper, the refresh + # token. It only lives in memory: long enough to outlive the service. + git_as_user config --global --add "credential.${origin}.helper" "cache --timeout=$GIT_OAUTH_CACHE_TIMEOUT" + # When it can't refresh, git-credential-oauth falls back on an interactive flow + # and waits for it without any limit: git would hang. + if [[ -n "$device_url" ]]; then + git_as_user config --global "credential.${origin}.oauthDeviceAuthURL" "$device_url" + git_as_user config --global --add "credential.${origin}.helper" "!timeout 300 git credential-oauth -device" + else + # The browser flow can't succeed from a service. + git_as_user config --global --add "credential.${origin}.helper" "!timeout 30 git credential-oauth" + fi + + # Seeds the cache with an expired password: git discards it and hands the refresh + # token to git-credential-oauth. This has to go straight to the helper, "git + # credential approve" ignores expired credentials. + if [[ -n "$refresh_token" ]]; then + printf 'url=%s\nusername=oauth2\npassword=expired\npassword_expiry_utc=1\noauth_refresh_token=%s\n\n' "$origin" "$refresh_token" | + git_as_user credential-cache --timeout="$GIT_OAUTH_CACHE_TIMEOUT" store + fi + ;; + *) + echo "Git provider $id: unknown credentials type $type" + return + ;; + esac + + GIT_PROVIDERS_ORIGINS_WITH_CREDENTIALS+=" $origin " +} + if command -v git &>/dev/null; then if [[ -n "$PATH_TO_CA_BUNDLE" ]]; then echo "configuration of git to a custom crt" git config --global http.sslVerify true git config --global http.sslCAInfo $PATH_TO_CA_BUNDLE fi - if [[ -n "$GIT_REPOSITORY" ]]; then + + # Git config + # NOTE: Before the Git providers, whose identity has to come later in the config to win. + if [ -n "$GIT_USER_NAME" ]; then + git config --global user.name "$GIT_USER_NAME" + fi + if [ -n "$GIT_USER_MAIL" ]; then + git config --global user.email "$GIT_USER_MAIL" + fi + if [ -n "$GIT_CREDENTIALS_CACHE_DURATION" ]; then + git config --global credential.helper "cache --timeout=$GIT_CREDENTIALS_CACHE_DURATION" + fi + # The ownership of the files git_as_user is about to write to, or to read + [ -f ${HOME}/.gitconfig ] && chown ${USERNAME}:${GROUPNAME} ${HOME}/.gitconfig + + # GIT_PROVIDERS: git.providers of the Onyxia context, as JSON. + GIT_OAUTH_CACHE_TIMEOUT=31536000 + GIT_PROVIDERS_ORIGINS_WITH_CREDENTIALS="" + if [[ -n "$GIT_PROVIDERS" ]] && ! jq -e 'type == "array"' <<< "$GIT_PROVIDERS" &>/dev/null; then + echo "ignoring GIT_PROVIDERS: not a JSON array" + GIT_PROVIDERS="" + fi + if [[ -n "$GIT_PROVIDERS" ]]; then + while IFS= read -r provider; do + configure_git_provider "$provider" + done < <(jq -c '.[] | select((.credentials.type == "oauth" and .credentials.refreshToken == null) | not)' <<< "$GIT_PROVIDERS") + fi + + # GIT_REPOSITORIES: git.repositories of the chart values, as JSON ([{url, branch}]). + # Takes over from GIT_REPOSITORY, which then holds the first one. + if [[ -n "$GIT_REPOSITORIES" ]] && ! jq -e 'type == "array"' <<< "$GIT_REPOSITORIES" &>/dev/null; then + echo "ignoring GIT_REPOSITORIES: not a JSON array" + GIT_REPOSITORIES="" + fi + if [[ -n "$GIT_REPOSITORIES" ]] && jq -e 'length > 0' <<< "$GIT_REPOSITORIES" &>/dev/null; then + # Nothing goes in the URL: the credentials are those of the Git providers. The + # token of GIT_PERSONAL_ACCESS_TOKEN belongs to one forge, it would be sent to all. + while IFS=$'\t' read -r url branch; do + [[ -z "$url" ]] && continue + echo "cloning $url" + if [[ -n "$branch" ]]; then + git -C "$ROOT_PROJECT_DIRECTORY" clone "$url" --branch "$branch" || echo "failed to clone $url" + else + git -C "$ROOT_PROJECT_DIRECTORY" clone "$url" || echo "failed to clone $url" + fi + done < <(jq -r '.[] | select(.url | type == "string") | [.url, (.branch // "")] | @tsv' <<< "$GIT_REPOSITORIES") + elif [[ -n "$GIT_REPOSITORY" ]]; then CLONE_URL="$GIT_REPOSITORY" - if [[ -n "$GIT_PERSONAL_ACCESS_TOKEN" ]]; then + # With the credentials of a Git provider nothing goes in the URL: it would be saved + # in .git/config, in the project directory, and outdated once the token is refreshed. + if [[ -n "$GIT_PERSONAL_ACCESS_TOKEN" && "$GIT_PROVIDERS_ORIGINS_WITH_CREDENTIALS" != *" $(git_url_origin "$GIT_REPOSITORY") "* ]]; then URL_PREFIX=$(echo "$GIT_REPOSITORY" | grep -oE '^https?://') URL_NO_PREFIX=$(echo "$GIT_REPOSITORY" | sed 's|^https\?://||') REPO_DOMAIN=$(awk -F/ '{print $3}' <<< "$GIT_REPOSITORY") @@ -115,16 +260,18 @@ if command -v git &>/dev/null; then fi fi - # Git config - if [ -n "$GIT_USER_NAME" ]; then - git config --global user.name "$GIT_USER_NAME" - fi - if [ -n "$GIT_USER_MAIL" ]; then - git config --global user.email "$GIT_USER_MAIL" - fi - if [ -n "$GIT_CREDENTIALS_CACHE_DURATION" ]; then - git config --global credential.helper "cache --timeout=$GIT_CREDENTIALS_CACHE_DURATION" + # Providers relying on the device flow only, once the project is cloned: nobody is there + # to enter the code during the startup, the clone would wait for it. Without credentials + # it fails right away on a private repository, the user can clone it from a terminal. + if [[ -n "$GIT_PROVIDERS" ]]; then + while IFS= read -r provider; do + configure_git_provider "$provider" + done < <(jq -c '.[] | select(.credentials.type == "oauth" and .credentials.refreshToken == null)' <<< "$GIT_PROVIDERS") fi + # The processes of the service have no use of these credentials, they're now in the + # helpers. The refresh token is outdated anyway after its first use. + unset GIT_PROVIDERS + # Default strategy when performing a git pull # Use Git's former default (fast-forward if possible, else merge) to avoid cryptic error message git config --global pull.rebase false diff --git a/base/tests.yaml b/base/tests.yaml index cbf4cc79..50377e46 100644 --- a/base/tests.yaml +++ b/base/tests.yaml @@ -32,9 +32,13 @@ commandTests: command: "which" args: ["duckdb"] expectedOutput: ["/usr/local/bin/duckdb"] + - name: "Does the binary exists?" + command: "which" + args: ["git-credential-oauth"] + expectedOutput: ["/usr/local/bin/git-credential-oauth"] - name: "CLI tools run" command: "bash" - args: ["-c", "aws --version && kubectl version --client && helm version && git --version && psql --version && jq --version"] + args: ["-c", "aws --version && kubectl version --client && helm version && git --version && git credential-oauth -h 2>&1 | grep -q git-credential-oauth && psql --version && jq --version"] - name: "DuckDB runs" command: "bash" args: ["-c", "duckdb --version"] @@ -49,3 +53,128 @@ commandTests: command: "ls" args: ["-A", "/home/onyxia/work"] excludedOutput: ["."] + - name: "onyxia-init.sh: Git config generated from GIT_PROVIDERS" + command: "bash" + args: + - "-c" + - | + set -e + export GIT_USER_NAME="Jane Doe" GIT_USER_MAIL="jane.doe@example.fr" GIT_CREDENTIALS_CACHE_DURATION=0 + export GIT_PROVIDERS='[ + {"id": "gitlab", "url": "https://gitlab.example.fr", "user": {"name": "Jane Doe", "email": "jane.doe@example.fr"}, + "credentials": {"type": "oauth", "clientId": "CLIENT_ID_GITLAB", "scopes": ["read_repository", "write_repository"], + "authorizationUrl": "https://gitlab.example.fr/oauth/authorize", "tokenUrl": "https://gitlab.example.fr/oauth/token", + "deviceAuthorizationUrl": "https://gitlab.example.fr/oauth/authorize_device", "refreshToken": "REFRESH_TOKEN_GITLAB"}}, + {"id": "github", "url": "https://github.com", "user": {"name": "jdoe", "email": "jdoe@users.noreply.github.com"}, + "credentials": {"type": "oauth", "clientId": "CLIENT_ID_GITHUB", "scopes": ["repo"], + "authorizationUrl": "https://github.com/login/oauth/authorize", "tokenUrl": "https://github.com/login/oauth/access_token", + "deviceAuthorizationUrl": "https://github.com/login/device/code"}}, + {"id": "forgejo", "url": "https://forge.example.org", "user": {"name": "Jane D.", "email": "jane@example.org"}, + "credentials": {"type": "oauth", "clientId": "CLIENT_ID_FORGEJO", "scopes": ["write:repository"], + "authorizationUrl": "https://forge.example.org/login/oauth/authorize", "tokenUrl": "https://forge.example.org/login/oauth/access_token", + "refreshToken": "REFRESH_TOKEN_FORGEJO"}}, + {"id": "bitbucket", "url": "https://bitbucket.org", "user": {"name": "Jane Doe", "email": "jane.doe@example.fr"}, + "credentials": {"type": "token", "username": "x-bitbucket-api-token-auth", "token": "TOKEN_BITBUCKET"}} + ]' + + # The service doesn't get the secrets in its environment + /opt/onyxia-init.sh bash -c 'test -z "${GIT_PROVIDERS:-}"' + + diff -u - ~/.gitconfig <<'EOF' + [user] + name = Jane Doe + email = jane.doe@example.fr + [credential] + helper = cache --timeout=0 + [includeIf "hasconfig:remote.*.url:https://gitlab.example.fr/**"] + path = /home/onyxia/.gitconfig-onyxia-gitlab + [credential "https://gitlab.example.fr"] + helper = + oauthClientId = CLIENT_ID_GITLAB + oauthScopes = read_repository write_repository + oauthAuthURL = https://gitlab.example.fr/oauth/authorize + oauthTokenURL = https://gitlab.example.fr/oauth/token + helper = cache --timeout=31536000 + oauthDeviceAuthURL = https://gitlab.example.fr/oauth/authorize_device + helper = !timeout 300 git credential-oauth -device + [includeIf "hasconfig:remote.*.url:https://forge.example.org/**"] + path = /home/onyxia/.gitconfig-onyxia-forgejo + [credential "https://forge.example.org"] + helper = + oauthClientId = CLIENT_ID_FORGEJO + oauthScopes = write:repository + oauthAuthURL = https://forge.example.org/login/oauth/authorize + oauthTokenURL = https://forge.example.org/login/oauth/access_token + helper = cache --timeout=31536000 + helper = !timeout 30 git credential-oauth + [includeIf "hasconfig:remote.*.url:https://bitbucket.org/**"] + path = /home/onyxia/.gitconfig-onyxia-bitbucket + [credential "https://bitbucket.org"] + helper = + helper = store + [includeIf "hasconfig:remote.*.url:https://github.com/**"] + path = /home/onyxia/.gitconfig-onyxia-github + [credential "https://github.com"] + helper = + oauthClientId = CLIENT_ID_GITHUB + oauthScopes = repo + oauthAuthURL = https://github.com/login/oauth/authorize + oauthTokenURL = https://github.com/login/oauth/access_token + helper = cache --timeout=31536000 + oauthDeviceAuthURL = https://github.com/login/device/code + helper = !timeout 300 git credential-oauth -device + [pull] + rebase = false + EOF + + diff -u - ~/.gitconfig-onyxia-forgejo <<'EOF' + [user] + name = Jane D. + email = jane@example.org + EOF + + diff -u - ~/.git-credentials <<'EOF' + https://x-bitbucket-api-token-auth:TOKEN_BITBUCKET@bitbucket.org + EOF + test "$(stat -c %a ~/.git-credentials)" = 600 + + # The refresh tokens are only in the memory of the cache + printf 'url=https://gitlab.example.fr\n\n' | git credential-cache get | grep -qx 'oauth_refresh_token=REFRESH_TOKEN_GITLAB' + printf 'url=https://forge.example.org\n\n' | git credential-cache get | grep -qx 'oauth_refresh_token=REFRESH_TOKEN_FORGEJO' + if grep -rq REFRESH_TOKEN ~/.gitconfig ~/.gitconfig-onyxia-* ~/.git-credentials; then exit 1; fi + + # Each forge's identity applies to its repositories, the default one elsewhere + git init -q /tmp/repo + test "$(git -C /tmp/repo config user.email)" = jane.doe@example.fr + git -C /tmp/repo remote add origin https://forge.example.org/jane/project.git + test "$(git -C /tmp/repo config user.email)" = jane@example.org + - name: "onyxia-init.sh: clones every repository of GIT_REPOSITORIES" + command: "bash" + args: + - "-c" + - | + set -e + for repo in first second; do + git init -q -b main "/tmp/src-$repo" + git -C "/tmp/src-$repo" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init + git -C "/tmp/src-$repo" branch dev + git clone -q --bare "/tmp/src-$repo" "/tmp/$repo.git" + done + mkdir /tmp/work + export ROOT_PROJECT_DIRECTORY=/tmp/work + export GIT_REPOSITORIES='[ + {"providerId": "a", "url": "file:///tmp/first.git", "branch": "dev"}, + {"providerId": "b", "url": "file:///tmp/second.git", "branch": ""}, + {"providerId": "c", "url": "file:///tmp/missing.git", "branch": ""} + ]' + # Set by the charts to the first repository, for what still reads it + export GIT_REPOSITORY=file:///tmp/first.git GIT_BRANCH=dev GIT_PERSONAL_ACCESS_TOKEN=SECRET_TOKEN + + # A repository that can't be cloned doesn't stop the startup + /opt/onyxia-init.sh true + + test "$(git -C /tmp/work/first branch --show-current)" = dev + test "$(git -C /tmp/work/second branch --show-current)" = main + test "$(ls /tmp/work)" = "$(printf 'first\nsecond')" + # The token of GIT_PERSONAL_ACCESS_TOKEN isn't put in the URLs + if grep -rq SECRET_TOKEN /tmp/work/*/.git/config; then exit 1; fi