[
  {
    "path": ".dockerignore",
    "content": "+.*\n+docs\n+go\n+test\n+README.md\n+schema.png\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\nIf your are using the latest image tag and recently updated your image: please make sure you've checked the required read on the project's README.\n\nHTTPS does not work / certificate aren't created : please check in your acme-companion container logs if an authorization or verify error is mentioned, if it is please do the following before opening an issue:\n- check and follow the troubleshooting instructions in the docs.\n- search the existing similar issues, both opened and closed.\n\nBug description\n-----------------\n\nA clear and concise description of what the bug is.\n\nacme-companion image version\n-----------------\n\nPlease provide the container version that should be printed to the first line of log at container startup:\n```\nInfo: running acme-companion version v2.0.0\n```\n\nIf this first log line isn't present you are using a v1 image: please provide the tagged version you are using. If you are not using a tagged version latest, please try again with a tagged release before opening an issue (the last v1 tagged release is v1.13.1).\n\nnginx-proxy's Docker configuration\n-----------------\n\nPlease provide the configuration (either command line, compose file, or other) of your nginx-proxy stack and your proxied container(s).\n\nYou can obfuscate information you want to keep private (and should obfuscate configuration secrets) such as domain(s) and/or email adress(es), but other than that please provide the full configurations and not the just snippets of the parts that seem relevants to you.\n\nrendered nginx configuration\n-----------------\n\nPlease provide the rendered nginx configuration:\n\n```console\ndocker exec name-of-the-nginx-container nginx -T\n```\n\nContainers logs\n-----------------\n\nPlease provide the logs of:\n- your acme-companion container\n- your nginx-proxy container (or nginx and docker-gen container in a three containers setup)\n\n```console\ndocker logs name-of-the-companion-container\n```\n\nDocker host\n-----------------\n\n - OS: [e.g. Ubuntu 20.04]\n - Docker version: output of `docker version`\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  # Maintain dependencies for Docker\n  - package-ecosystem: \"docker\"\n    directory: \"/\"\n    schedule:\n      interval: \"daily\"\n    commit-message:\n      prefix: \"build\"\n    labels:\n      - \"type/build\"\n\n  # Maintain GitHub Actions\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    commit-message:\n      prefix: \"ci\"\n    labels:\n      - \"type/ci\"\n"
  },
  {
    "path": ".github/workflows/build-publish.yml",
    "content": "name: Build and publish Docker image\n\npermissions:\n  contents: read\n  packages: write\n\non:\n  workflow_dispatch:\n  schedule:\n    - cron: \"0 0 * * 1\"\n  push:\n    branches:\n      - main\n      - dev\n      - stable\n    tags:\n      - \"v*.*.*\"\n    paths:\n      - \".dockerignore\"\n      - \".github/workflows/build-publish.yml\"\n      - \"app/*\"\n      - \"Dockerfile\"\n      - \"install_acme.sh\"\n\njobs:\n  multiarch-build:\n    name: Build and publish Docker image\n    runs-on: ubuntu-latest\n    if: (github.event_name == 'schedule' && github.repository == 'nginx-proxy/acme-companion') || (github.event_name != 'schedule')\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Retrieve version\n        id: acme-companion_version\n        run: echo \"VERSION=$(git describe --tags)\" >> \"$GITHUB_OUTPUT\"\n\n      - name: Get Docker tags\n        id: docker_meta\n        uses: docker/metadata-action@v5\n        with:\n          images: |\n            ghcr.io/nginx-proxy/acme-companion\n            nginxproxy/acme-companion\n            jrcs/letsencrypt-nginx-proxy-companion\n          tags: |\n            type=semver,pattern={{version}}\n            type=semver,pattern={{major}}.{{minor}}\n            type=raw,value=latest,enable={{is_default_branch}}\n          labels: |\n            org.opencontainers.image.authors=Nicolas Duchon <nicolas.duchon@gmail.com> (@buchdag), Yves Blusseau\n            org.opencontainers.image.version=${{ steps.acme-companion_version.outputs.VERSION }}\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v4\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v4\n\n      - name: Login to DockerHub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n\n      - name: Log in to GitHub Container Registry\n        uses: docker/login-action@v3\n        with:\n          registry: ghcr.io\n          username: ${{ github.actor }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Build and push\n        id: docker_build\n        uses: docker/build-push-action@v7\n        with:\n          context: .\n          build-args: GIT_DESCRIBE=${{ steps.acme-companion_version.outputs.VERSION }}\n          platforms: linux/amd64,linux/arm64,linux/arm/v7\n          sbom: true\n          push: true\n          provenance: mode=max\n          tags: ${{ steps.docker_meta.outputs.tags }}\n          labels: ${{ steps.docker_meta.outputs.labels }}\n          cache-from: type=gha\n          cache-to: type=gha,mode=max\n\n      - name: Image digest\n        run: echo ${{ steps.docker_build.outputs.digest }}\n"
  },
  {
    "path": ".github/workflows/dockerhub-description.yml",
    "content": "name: Update Docker Hub Description\n\npermissions:\n  contents: read\n\non:\n  push:\n    branches:\n      - main\n    paths:\n      - README.md\n      - .github/workflows/dockerhub-description.yml\n\njobs:\n  dockerHubDescription:\n    name: Update Docker Hub Description\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Docker Hub Description\n        uses: peter-evans/dockerhub-description@v5\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN_RWD }}\n          repository: nginxproxy/acme-companion\n          short-description: ${{ github.event.repository.description }}\n          enable-url-completion: true\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Tests\n\npermissions:\n  contents: read\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    paths-ignore:\n      - \"docs/**\"\n      - \"*.md\"\n  pull_request:\n    paths-ignore:\n      - \"docs/**\"\n      - \"*.md\"\n\nenv:\n  ACME_CA: pebble\n  DOCKER_GEN_CONTAINER_NAME: nginx-proxy-gen\n  IMAGE: nginxproxy/acme-companion\n  NGINX_CONTAINER_NAME: nginx-proxy\n  TEST_DOMAINS: le1.wtf,le2.wtf,le3.wtf\n\njobs:\n  companion-build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v6\n\n      - name: Build Image\n        run: docker build -t \"$IMAGE\" .\n\n      - name: Inspect Image\n        run: docker inspect \"$IMAGE\"\n\n      - name: Get acme.sh Version\n        run: docker run --rm \"$IMAGE\" acme.sh --version\n\n      - name: List Docker Images\n        run: docker images\n\n      - name: Export Image Artifact\n        run: docker save $IMAGE > companion.tar\n\n      - name: Upload Image Artifact\n        uses: actions/upload-artifact@v7\n        with:\n          name: companion.tar\n          path: companion.tar\n\n  docker-specs-tests:\n    needs: companion-build\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout Docker official images tests\n        uses: actions/checkout@v6\n        with:\n          repository: docker-library/official-images\n          path: official-images\n\n      - name: Download Builded Image\n        uses: actions/download-artifact@v8\n        with:\n          name: companion.tar\n\n      - name: Import Builded Image\n        run: docker load < companion.tar\n\n      - name: Docker Specifications Testing\n        run: official-images/test/run.sh \"$IMAGE\"\n\n      - name: Display containers logs\n        if: ${{ failure() }}\n        run: test/github_actions/containers-logs.sh\n\n  integration-tests:\n    needs:\n      - companion-build\n    strategy:\n      fail-fast: false\n      matrix:\n        test-name:\n          [\n            docker_api,\n            docker_api_legacy,\n            location_config,\n            certs_single,\n            certs_san,\n            certs_single_domain,\n            certs_standalone,\n            force_renew,\n            acme_accounts,\n            private_keys,\n            container_restart,\n            permissions_default,\n            permissions_custom,\n            symlinks,\n            acme_hooks,\n            ocsp_must_staple,\n          ]\n        setup: [2containers, 3containers]\n        pebble-config: [pebble-config.json]\n        include:\n          - test-name: acme_eab\n            setup: 2containers\n            pebble-config: pebble-config-eab.json\n          - test-name: acme_eab\n            setup: 3containers\n            pebble-config: pebble-config-eab.json\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v6\n\n      # PREPARE RUNNER ENV\n      - name: Add Test Domains in /etc/hosts\n        run: |\n          IFS=',' read -r -a test_domains <<< \"$TEST_DOMAINS\"\n          test_domains+=(pebble pebble-challtestsrv)\n          for domain in \"${test_domains[@]}\"\n          do\n              echo \"127.0.0.1 $domain\" | sudo tee -a /etc/hosts\n          done\n\n      - name: Setup Pebble\n        env:\n          PEBBLE_CONFIG: ${{ matrix.pebble-config }}\n        run: test/setup/pebble/setup-pebble.sh\n\n      - name: Setup nginx-proxy\n        env:\n          SETUP: ${{ matrix.setup }}\n        run: test/setup/setup-nginx-proxy.sh\n\n      # ADD BUILT IMAGE\n      - name: Download Built Image\n        uses: actions/download-artifact@v8\n        with:\n          name: companion.tar\n\n      - name: Import Built Image\n        run: docker load < companion.tar\n\n      # TEST\n      - name: Integration Testing\n        env:\n          SETUP: ${{ matrix.setup }}\n          PEBBLE_CONFIG: ${{ matrix.pebble-config }}\n        run: test/run.sh -t ${{ matrix.test-name }} \"$IMAGE\"\n\n      - name: Display containers logs\n        if: ${{ failure() }}\n        env:\n          SETUP: ${{ matrix.setup }}\n        run: test/github_actions/containers-logs.sh\n"
  },
  {
    "path": ".gitignore",
    "content": ".docker\n.vscode\ncerts/\nconf.d/\ndata/\nvhost.d/\n\n# tests\ngo/\nnginx.tmpl\npebble.minica.pem\ntest/local_test_env.sh\ntest/tests/docker_api/expected-std-out.txt\ntest/tests/container_restart/docker_event_out.txt\ntest/tests/certs_standalone/letsencrypt_user_data\ntest/tests/location_config/le2.wtf\n"
  },
  {
    "path": ".shellcheckrc",
    "content": "external-sources=true\n"
  },
  {
    "path": "Dockerfile",
    "content": "# syntax=docker/dockerfile:1\nFROM docker.io/nginxproxy/docker-gen:0.16.2 AS docker-gen\n\nFROM docker.io/library/alpine:3.23.3\n\nARG GIT_DESCRIBE=\"unknown\"\nARG ACMESH_VERSION=3.1.2\n\nENV ACMESH_VERSION=${ACMESH_VERSION} \\\n    COMPANION_VERSION=${GIT_DESCRIBE} \\\n    DOCKER_HOST=unix:///var/run/docker.sock \\\n    PATH=${PATH}:/app\n\n# Install packages required by the image\nRUN apk add --no-cache --virtual .bin-deps \\\n    bash \\\n    bind-tools \\\n    coreutils \\\n    curl \\\n    jq \\\n    libidn \\\n    oath-toolkit-oathtool \\\n    openssh-client \\\n    openssl \\\n    sed \\\n    socat \\\n    tar \\\n    tzdata\n\n# Install docker-gen from the nginxproxy/docker-gen image\nCOPY --from=docker-gen /usr/local/bin/docker-gen /usr/local/bin/\n\n# Install acme.sh\nCOPY /install_acme.sh /app/install_acme.sh\nRUN chmod +rx /app/install_acme.sh \\\n    && sync \\\n    && /app/install_acme.sh \\\n    && rm -f /app/install_acme.sh\n\nCOPY app LICENSE /app/\n\nWORKDIR /app\n\nENTRYPOINT [ \"/bin/bash\", \"/app/entrypoint.sh\" ]\nCMD [ \"/bin/bash\", \"/app/start.sh\" ]\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015-2017 Yves Blusseau\nCopyright (c) 2017-2022 Nicolas Duchon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "[![Tests](https://github.com/nginx-proxy/acme-companion/actions/workflows/test.yml/badge.svg)](https://github.com/nginx-proxy/acme-companion/actions/workflows/test.yml)\r\n[![GitHub release](https://img.shields.io/github/release/nginx-proxy/acme-companion.svg)](https://github.com/nginx-proxy/acme-companion/releases)\r\n[![Docker Image Size](https://img.shields.io/docker/image-size/nginxproxy/acme-companion?sort=semver)](https://hub.docker.com/r/nginxproxy/acme-companion \"Click to view the image on Docker Hub\")\r\n[![Docker stars](https://img.shields.io/docker/stars/nginxproxy/acme-companion.svg)](https://hub.docker.com/r/nginxproxy/acme-companion \"Click to view the image on Docker Hub\")\r\n[![Docker pulls](https://img.shields.io/docker/pulls/nginxproxy/acme-companion.svg)](https://hub.docker.com/r/nginxproxy/acme-companion \"Click to view the image on Docker Hub\")\r\n\r\n**acme-companion** is a lightweight companion container for [**nginx-proxy**](https://github.com/nginx-proxy/nginx-proxy).\r\n\r\nIt handles the automated creation, renewal and use of SSL certificates for proxied Docker containers through the ACME protocol.\r\n\r\n### Features:\r\n* Automated creation/renewal of Let's Encrypt (or other ACME CAs) certificates using [**acme.sh**](https://github.com/acmesh-official/acme.sh).\r\n* Let's Encrypt / ACME domain validation through `HTTP-01` (by default) or [`DNS-01`](https://github.com/nginx-proxy/acme-companion/blob/main/docs/Let's-Encrypt-and-ACME.md#dns-01-acme-challenge) challenge.\r\n* Automated update and reload of nginx config on certificate creation/renewal.\r\n* Support creation of [Multi-Domain (SAN) Certificates](https://github.com/nginx-proxy/acme-companion/blob/main/docs/Let's-Encrypt-and-ACME.md#multi-domains-certificates).\r\n* Support creation of [Wildcard Certificates](https://community.letsencrypt.org/t/acme-v2-production-environment-wildcards/55578) (with `DNS-01` challenge only).\r\n* Creation of a strong [RFC7919 Diffie-Hellman Group](https://datatracker.ietf.org/doc/html/rfc7919#appendix-A) at startup.\r\n* Work with all versions of docker.\r\n\r\n### HTTP-01 challenge requirements:\r\n* Your host **must** be publicly reachable on **both** port [`80`](https://letsencrypt.org/docs/allow-port-80/) and [`443`](https://github.com/nginx-proxy/acme-companion/discussions/873#discussioncomment-1410225).\r\n* Check your firewall rules and [**do not attempt to block port `80`**](https://letsencrypt.org/docs/allow-port-80/) as that will prevent `HTTP-01` challenges from completing.\r\n* For the same reason, you can't use nginx-proxy's [`HTTPS_METHOD=nohttp`](https://github.com/nginx-proxy/nginx-proxy#how-ssl-support-works).\r\n* The (sub)domains you want to issue certificates for must correctly resolve to the host.\r\n* If your (sub)domains have AAAA records set, the host must be publicly reachable over IPv6 on port `80` and `443`.\r\n\r\nIf you can't meet these requirements, you can use the `DNS-01` challenge instead. Please refer to the [documentation](https://github.com/nginx-proxy/acme-companion/blob/main/docs/Let's-Encrypt-and-ACME.md#dns-01-acme-challenge) for more information.\r\n\r\nIn addition to the above, please ensure that your DNS provider answers correctly to CAA record requests. [If your DNS provider answer with an error, Let's Encrypt won't issue a certificate for your domain](https://letsencrypt.org/docs/caa/). Let's Encrypt do not require that you set a CAA record on your domain, just that your DNS provider answers correctly.\r\n\r\n![schema](https://github.com/nginx-proxy/acme-companion/blob/main/schema.png)\r\n\r\n## Basic usage (with the nginx-proxy container)\r\n\r\nTwo writable volumes must be declared on the **nginx-proxy** container so that they can be shared with the **acme-companion** container:\r\n\r\n* `/etc/nginx/certs` to store certificates and private keys (readonly for the **nginx-proxy** container).\r\n* `/usr/share/nginx/html` to write `http-01` challenge files.\r\n\r\nAdditionally, a third volume must be declared on the **acme-companion** container to store `acme.sh` configuration and state: `/etc/acme.sh`.\r\n\r\nPlease also read the doc about [data persistence](./docs/Persistent-data.md).\r\n\r\nExample of use:\r\n\r\n### Step 1 - nginx-proxy\r\n\r\nStart **nginx-proxy** with the two additional volumes declared:\r\n\r\n```shell\r\n$ docker run --detach \\\r\n    --name nginx-proxy \\\r\n    --publish 80:80 \\\r\n    --publish 443:443 \\\r\n    --volume certs:/etc/nginx/certs \\\r\n    --volume html:/usr/share/nginx/html \\\r\n    --volume /var/run/docker.sock:/tmp/docker.sock:ro \\\r\n    nginxproxy/nginx-proxy\r\n```\r\n\r\nBinding the host docker socket (`/var/run/docker.sock`) inside the container to `/tmp/docker.sock` is a requirement of **nginx-proxy**.\r\n\r\n### Step 2 - acme-companion\r\n\r\nStart the **acme-companion** container, getting the volumes from **nginx-proxy** with `--volumes-from`:\r\n\r\n```shell\r\n$ docker run --detach \\\r\n    --name nginx-proxy-acme \\\r\n    --volumes-from nginx-proxy \\\r\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\r\n    --volume acme:/etc/acme.sh \\\r\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\r\n    nginxproxy/acme-companion\r\n```\r\n\r\nThe host docker socket has to be bound inside this container too, this time to `/var/run/docker.sock`.\r\n\r\nAlbeit **optional**, it is **recommended** to provide a valid default email address through the `DEFAULT_EMAIL` environment variable, so that Let's Encrypt can warn you about expiring certificates and allow you to recover your account.\r\n\r\n### Step 3 - proxied container(s)\r\n\r\nOnce both **nginx-proxy** and **acme-companion** containers are up and running, start any container you want proxied with environment variables `VIRTUAL_HOST` and `LETSENCRYPT_HOST` both set to the domain(s) your proxied container is going to use.\r\n\r\n[`VIRTUAL_HOST`](https://github.com/nginx-proxy/nginx-proxy#usage) control proxying by **nginx-proxy** and `LETSENCRYPT_HOST` control certificate creation and SSL enabling by **acme-companion**.\r\n\r\nCertificates will only be issued for containers that have both `VIRTUAL_HOST` and `LETSENCRYPT_HOST` variables set to domain(s) that correctly resolve to the host, provided the host is publicly reachable.\r\n\r\n```shell\r\n$ docker run --detach \\\r\n    --name your-proxied-app \\\r\n    --env \"VIRTUAL_HOST=subdomain.yourdomain.tld\" \\\r\n    --env \"LETSENCRYPT_HOST=subdomain.yourdomain.tld\" \\\r\n    nginx\r\n```\r\n\r\nThe containers being proxied must expose the port to be proxied, either by using the `EXPOSE` directive in their Dockerfile or by using the `--expose` flag to `docker run` or `docker create`.\r\n\r\nIf the proxied container listen on and expose another port than the default `80`, you can force **nginx-proxy** to use this port with the [`VIRTUAL_PORT`](https://github.com/nginx-proxy/nginx-proxy#multiple-ports) environment variable.\r\n\r\nExample using [Grafana](https://hub.docker.com/r/grafana/grafana/) (expose and listen on port 3000):\r\n\r\n```shell\r\n$ docker run --detach \\\r\n    --name grafana \\\r\n    --env \"VIRTUAL_HOST=othersubdomain.yourdomain.tld\" \\\r\n    --env \"VIRTUAL_PORT=3000\" \\\r\n    --env \"LETSENCRYPT_HOST=othersubdomain.yourdomain.tld\" \\\r\n    --env \"LETSENCRYPT_EMAIL=mail@yourdomain.tld\" \\\r\n    grafana/grafana\r\n```\r\n\r\nRepeat [Step 3](#step-3---proxied-containers) for any other container you want to proxy.\r\n\r\n## Additional documentation\r\n\r\nPlease check the [docs section](https://github.com/nginx-proxy/acme-companion/tree/main/docs).\r\n"
  },
  {
    "path": "app/cert_status",
    "content": "#!/bin/bash\nfunction print_cert_info {\n  local enddate\n  local subject\n  local san_str\n\n  # Get the wanted informations with OpenSSL.\n  issuer=\"$(openssl x509 -noout -issuer -in \"$1\" | sed -n 's/.*CN = \\(.*\\)/\\1/p')\"\n  enddate=\"$(openssl x509 -noout -enddate -in \"$1\" | sed -n 's/notAfter=\\(.*$\\)/\\1/p')\"\n  subject=\"$(openssl x509 -noout -subject -in \"$1\" | sed -n 's/.*CN = \\([a-z0-9.-]*\\)/- \\1/p')\"\n  san_str=\"$(openssl x509 -text -in \"$1\" | grep 'DNS:')\"\n\n  case \"$issuer\" in\n    R3 | R4 | E1 | E2)\n      issuer=\"Let's Encrypt $issuer\"\n      ;;\n\n    *)\n      ;;\n  esac\n\n  echo \"Certificate was issued by $issuer\"\n  if [[ \"$2\" == \"expired\" ]]; then\n      echo \"Certificate was valid until $enddate\"\n  else\n      echo \"Certificate is valid until $enddate\"\n  fi\n  echo \"Subject Name:\"\n  echo \"$subject\"\n\n  # Display the SAN info only if there is more than one SAN domain.\n  while IFS=',' read -ra SAN; do\n      if [[ ${#SAN[@]} -gt 1 ]]; then\n          echo \"Subject Alternative Name:\"\n          for domain in \"${SAN[@]}\"; do\n              echo \"$domain\" | sed -n 's/.*DNS:\\([a-z0-9.-]*\\)/- \\1/p'\n          done\n      fi\n  done <<< \"$san_str\"\n}\n\necho '##### Certificate status #####'\nfor cert in /etc/nginx/certs/*/fullchain.pem; do\n    [[ -e \"$cert\" ]] || continue\n    if [[ -e \"${cert%fullchain.pem}chain.pem\" ]]; then\n        # Verify the certificate with OpenSSL.\n        if verify=$(openssl verify -untrusted \"${cert%fullchain.pem}chain.pem\" \"$cert\" 2>&1); then\n            echo \"$verify\"\n            # Print certificate info.\n            print_cert_info \"$cert\"\n        else\n            echo \"${cert}: EXPIRED\"\n            # Print certificate info.\n            print_cert_info \"$cert\" \"expired\"\n        fi\n    else\n        echo \"${cert}: no corresponding chain.pem file, unable to verify certificate\"\n        # Print certificate info.\n        print_cert_info \"$cert\"\n    fi\n\n    # Find the .crt files in /etc/nginx/certs which are\n    # symlinks pointing to the current certificate.\n    unset symlinked_domains\n    for symlink in /etc/nginx/certs/*.crt; do\n        [[ -e \"$symlink\" ]] || continue\n        if [[ \"$(readlink -f \"$symlink\")\" == \"$cert\" ]]; then\n            domain=\"${symlink%.crt}\"\n            domain=\"${domain//\\/etc\\/nginx\\/certs\\//}\"\n            symlinked_domains+=(\"$domain\")\n        fi\n    done\n\n    # Display symlinks pointing to the current cert if there is any.\n    if [[ ${#symlinked_domains[@]} -gt 0 ]]; then\n        echo \"Certificate is used by the following domain(s):\"\n        for domain in \"${symlinked_domains[@]}\"; do\n          echo \"- $domain\"\n        done\n    fi\n\n    echo '##############################'\ndone\n"
  },
  {
    "path": "app/cleanup_test_artifacts",
    "content": "#!/bin/bash\n\n# This script should not be run outside of a test container\n[[ \"$TEST_MODE\" == 'true' ]] || exit 1\n\nwhile [[ $# -gt 0 ]]; do\n    flag=\"$1\"\n\n    case $flag in\n        --location-config)\n        for domain in 'le1.wtf' '*.example.com' 'test.*' 'le3.pizza' 'subdomain.example.com' 'test.domain.tld'; do\n            [[ -f \"/etc/nginx/vhost.d/$domain\" ]] && rm -f \"/etc/nginx/vhost.d/$domain\"\n        done\n        shift\n        ;;\n\n        *) #Unknown option\n        shift\n        ;;\n    esac\ndone\n\nfor domain in le1.wtf le2.wtf le3.wtf le4.wtf lim.it; do\n    folder=\"/etc/nginx/certs/$domain\"\n    [[ -d \"$folder\" ]] && rm -rf \"$folder\"\n    folder=\"/etc/acme.sh/default/$domain\"\n    [[ -d \"$folder\" ]] && rm -rf \"$folder\"\n    folder=\"/etc/acme.sh/default/${domain}_ecc\"\n    [[ -d \"$folder\" ]] && rm -rf \"$folder\"\n    location_file=\"/etc/nginx/vhost.d/$domain\"\n    [[ -f \"$location_file\" ]] && rm -rf \"$location_file\" 2> /dev/null\n    for extension in key crt chain.pem dhparam.pem; do\n        symlink=\"/etc/nginx/certs/${domain}.${extension}\"\n        [[ -L \"$symlink\" ]] && rm -rf \"$symlink\"\n    done\ndone\n\nexit 0\n"
  },
  {
    "path": "app/dhparam/ffdhe2048.pem",
    "content": "-----BEGIN DH PARAMETERS-----\nMIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\nYdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\nssbzSibBsu/6iGtCOGEoXJf//////////wIBAg==\n-----END DH PARAMETERS-----\n"
  },
  {
    "path": "app/dhparam/ffdhe3072.pem",
    "content": "-----BEGIN DH PARAMETERS-----\nMIIBiAKCAYEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\nYdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\nssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\nnuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZsYu\nN///////////AgEC\n-----END DH PARAMETERS-----\n"
  },
  {
    "path": "app/dhparam/ffdhe4096.pem",
    "content": "-----BEGIN DH PARAMETERS-----\nMIICCAKCAgEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\nYdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\nssbzSibBsu/6iGtCOGEfz9zeNVs7ZRkDW7w09N75nAI4YbRvydbmyQd62R0mkff3\n7lmMsPrBhtkcrv4TCYUTknC0EwyTvEN5RPT9RFLi103TZPLiHnH1S/9croKrnJ32\nnuhtK8UiNjoNq8Uhl5sN6todv5pC1cRITgq80Gv6U93vPBsg7j/VnXwl5B0rZp4e\n8W5vUsMWTfT7eTDp5OWIV7asfV9C1p9tGHdjzx1VA0AEh/VbpX4xzHpxNciG77Qx\niu1qHgEtnmgyqQdgCpGBMMRtx3j5ca0AOAkpmaMzy4t6Gh25PXFAADwqTs6p+Y0K\nzAqCkc3OyX3Pjsm1Wn+IpGtNtahR9EGC4caKAH5eZV9q//////////8CAQI=\n-----END DH PARAMETERS-----\n"
  },
  {
    "path": "app/dhparam.pem.default",
    "content": "-----BEGIN DH PARAMETERS-----\nMIIBCAKCAQEAwpR+yYapElMV4DiO+BwKK2N8Ur4giZtga+dslyDMuhY+U4t/97Eq\ngdFg2RD5nqrgWCRWEYcbh1kPBOAPWXZ4+N8mZL8pJXaNi2XFA8IxQex283Sz7CX+\nqr/zb+piJLx+/6JB/NNTZtKurM3ZQgwdGqSHqeWgvRIgCQAykC1oz7muCsev1IMc\nrLig1kyvhg3L1t+uKYV0OtiXONmPglPm9pXRqMQ53Rg/D3CpUpyyTSugOFjVhLrP\nOw+kO6qXBQSDhrL2L0UjprbcVMPHv9bFmWNoTCtC8OYA1OuiA368PWhgeH/76Yu8\n4an6/vt3HowDZHKfB3Vb1VwTI+k6hzwhkwIBAg==\n-----END DH PARAMETERS-----\n"
  },
  {
    "path": "app/entrypoint.sh",
    "content": "#!/bin/bash\n\nset -u\n\n# shellcheck source=functions.sh\nsource /app/functions.sh\n\nfunction print_version {\n    if [[ -n \"${COMPANION_VERSION:-}\" ]]; then\n        echo \"Info: running acme-companion version ${COMPANION_VERSION}\"\n    fi\n}\n\nfunction check_docker_socket {\n    if [[ $DOCKER_HOST == unix://* ]]; then\n        socket_file=${DOCKER_HOST#unix://}\n        if [[ ! -S $socket_file ]]; then\n            if [[ ! -r $socket_file ]]; then\n                echo \"Warning: Docker host socket at $socket_file might not be readable. Please check user permissions\" >&2\n                echo \"If you are in a SELinux environment, try using: '-v /var/run/docker.sock:$socket_file:z'\" >&2\n            fi\n            echo \"Error: you need to share your Docker host socket with a volume at $socket_file\" >&2\n            echo \"Typically you should run your container with: '-v /var/run/docker.sock:$socket_file:ro'\" >&2\n            exit 1\n        fi\n    fi\n}\n\nfunction check_dir_is_mounted_volume {\n    local dir=\"$1\"\n    if [[ $(get_self_cid) ]]; then\n        if ! docker_api \"/containers/$(get_self_cid)/json\" | jq \".Mounts[].Destination\" | grep -q \"^\\\"$dir\\\"$\"; then\n            echo \"Warning: '$dir' does not appear to be a mounted volume.\"\n        fi\n    else\n        echo \"Warning: can't check if '$dir' is a mounted volume without self container ID.\"\n    fi\n}\n\nfunction check_writable_directory {\n    local dir=\"$1\"\n\n    check_dir_is_mounted_volume \"$dir\"\n\n    if [[ ! -d \"$dir\" ]]; then\n        echo \"Error: can't access to '$dir' directory !\" >&2\n        echo \"Check that '$dir' directory is declared as a writable volume.\" >&2\n        exit 1\n    fi\n    if ! touch \"$dir/.check_writable\" 2>/dev/null ; then\n        echo \"Error: can't write to the '$dir' directory !\" >&2\n        echo \"Check that '$dir' directory is export as a writable volume.\" >&2\n        exit 1\n    fi\n    rm -f \"$dir/.check_writable\"\n}\n\nfunction warn_html_directory {\n    local dir='/usr/share/nginx/html'\n    \n    check_dir_is_mounted_volume \"$dir\"\n\n    if [[ ! -d \"$dir\" ]] || ! touch \"$dir/.check_writable\" 2>/dev/null; then\n        echo \"Warning: can't access or write to '$dir' directory. This will prevent HTML-01 challenges from working correctly.\"\n        echo \"If you are only using DNS-01 challenges, you can ignore this warning, otherwise check that '$dir' is declared as a writable volume.\"\n    fi\n    rm -f \"$dir/.check_writable\"\n}\n\nfunction check_dh_group {\n\t# DH params will be supplied for acme-companion here:\n\tlocal DHPARAM_FILE='/etc/nginx/certs/dhparam.pem'\n\n\t# Should be 2048, 3072, or 4096 (default):\n\tlocal DHPARAM_BITS=\"${DHPARAM_BITS:=4096}\"\n\n    # Skip generation if DHPARAM_SKIP is set to true\n    if parse_true \"${DHPARAM_SKIP:=false}\"; then\n\t\techo \"Info: Skipping Diffie-Hellman group setup.\"\n\t\treturn 0\n    fi\n\n    # Let's check DHPARAM_BITS is set to a supported value\n    if [[ ! \"$DHPARAM_BITS\" =~ ^(2048|3072|4096)$ ]]; then\n        echo \"Error: Unsupported DHPARAM_BITS size: ${DHPARAM_BITS}. Supported values are 2048, 3072, or 4096 (default).\" >&2\n        exit 1\n    fi\n\n    # Use an existing pre-generated DH group from RFC7919 (https://datatracker.ietf.org/doc/html/rfc7919#appendix-A):\n    local RFC7919_DHPARAM_FILE=\"/app/dhparam/ffdhe${DHPARAM_BITS}.pem\"\n    local EXPECTED_DHPARAM_HASH; EXPECTED_DHPARAM_HASH=$(sha256sum \"$RFC7919_DHPARAM_FILE\" | cut -d ' ' -f1)\n\n\t# DH params may be provided by the user (rarely necessary)\n\tif [[ -f \"$DHPARAM_FILE\" ]]; then\n        local USER_PROVIDED_DH\n\n        # Check if the DH params file is user provided or comes from acme-companion\n        local DHPARAM_HASH; DHPARAM_HASH=$(sha256sum \"$DHPARAM_FILE\" | cut -d ' ' -f1)\n        \n        for f in /app/dhparam/ffdhe*.pem; do\n            local FFDHE_HASH; FFDHE_HASH=$(sha256sum \"$f\" | cut -d ' ' -f1)\n            if [[ \"$DHPARAM_HASH\" == \"$FFDHE_HASH\" ]]; then\n                # This is an acme-companion created DH params file\n                USER_PROVIDED_DH='false'\n\n                # Check if /etc/nginx/certs/dhparam.pem matches the expected pre-generated DH group\n                if [[ \"$DHPARAM_HASH\" == \"$EXPECTED_DHPARAM_HASH\" ]]; then\n                    set_ownership_and_permissions \"$DHPARAM_FILE\"\n                    echo \"Info: ${DHPARAM_BITS} bits RFC7919 Diffie-Hellman group found, generation skipped.\"\n                    return 0\n                fi\n            fi\n        done\n\n        if parse_true \"${USER_PROVIDED_DH:=true}\"; then\n            # This is a user provided DH params file\n            set_ownership_and_permissions \"$DHPARAM_FILE\"\n            echo \"Info: A custom dhparam.pem file was provided. Best practice is to use standardized RFC7919 Diffie-Hellman groups instead.\"\n            return 0\n        fi\n\tfi\n\n    # The RFC7919 DH params file either need to be created or replaced\n\techo \"Info: Setting up ${DHPARAM_BITS} bits RFC7919 Diffie-Hellman group...\"\n\tcp \"$RFC7919_DHPARAM_FILE\" \"${DHPARAM_FILE}.tmp\"\n    mv \"${DHPARAM_FILE}.tmp\" \"$DHPARAM_FILE\"\n    set_ownership_and_permissions \"$DHPARAM_FILE\"\n}\n\nfunction check_default_cert_key {\n    local cn='acme-companion'\n\n    echo \"Warning: there is no future support planned for the self signed default certificate creation feature and it might be removed in a future release.\"\n\n    if [[ -e /etc/nginx/certs/default.crt && -e /etc/nginx/certs/default.key ]]; then\n        default_cert_cn=\"$(openssl x509 -noout -subject -in /etc/nginx/certs/default.crt)\"\n        # Check if the existing default certificate is still valid for more\n        # than 3 months / 7776000 seconds (60 x 60 x 24 x 30 x 3).\n        check_cert_min_validity /etc/nginx/certs/default.crt 7776000\n        cert_validity=$?\n        [[ \"$DEBUG\" == 1 ]] && echo \"Debug: a default certificate with $default_cert_cn is present.\"\n    fi\n\n    # Create a default cert and private key if:\n    #   - either default.crt or default.key are absent\n    #   OR\n    #   - the existing default cert/key were generated by the container\n    #     and the cert validity is less than three months\n    if [[ ! -e /etc/nginx/certs/default.crt || ! -e /etc/nginx/certs/default.key ]] || [[ \"${default_cert_cn:-}\" =~ $cn && \"${cert_validity:-}\" -ne 0 ]]; then\n        openssl req -x509 \\\n            -newkey rsa:4096 -sha256 -nodes -days 365 \\\n            -subj \"/CN=$cn\" \\\n            -keyout /etc/nginx/certs/default.key.new \\\n            -out /etc/nginx/certs/default.crt.new \\\n        && mv /etc/nginx/certs/default.key.new /etc/nginx/certs/default.key \\\n        && mv /etc/nginx/certs/default.crt.new /etc/nginx/certs/default.crt \\\n        && reload_nginx\n        echo \"Info: a default key and certificate have been created at /etc/nginx/certs/default.key and /etc/nginx/certs/default.crt.\"\n    elif [[ \"$DEBUG\" == 1 && \"${default_cert_cn:-}\" =~ $cn ]]; then\n        echo \"Debug: the self generated default certificate is still valid for more than three months. Skipping default certificate creation.\"\n    elif [[ \"$DEBUG\" == 1 ]]; then\n        echo \"Debug: the default certificate is user provided. Skipping default certificate creation.\"\n    fi\n    set_ownership_and_permissions \"/etc/nginx/certs/default.key\"\n    set_ownership_and_permissions \"/etc/nginx/certs/default.crt\"\n}\n\nfunction check_default_account {\n    # The default account is now for empty account email\n    if [[ -f /etc/acme.sh/default/account.conf ]]; then\n        if grep -q ACCOUNT_EMAIL /etc/acme.sh/default/account.conf; then\n            sed -i '/ACCOUNT_EMAIL/d' /etc/acme.sh/default/account.conf\n        fi\n    fi\n}\n\nif [[ \"$*\" == \"/bin/bash /app/start.sh\" ]]; then\n    print_version\n    check_docker_socket\n    if [[ -z \"$(get_nginx_proxy_container)\" ]]; then\n        echo \"Error: can't get nginx-proxy container ID !\" >&2\n        echo \"Check that you are doing one of the following :\" >&2\n        echo -e \"\\t- Use the --volumes-from option to mount volumes from the nginx-proxy container.\" >&2\n        echo -e \"\\t- Set the NGINX_PROXY_CONTAINER env var on the letsencrypt-companion container to the name of the nginx-proxy container.\" >&2\n        echo -e \"\\t- Label the nginx-proxy container to use with 'com.github.nginx-proxy.nginx'.\" >&2\n        exit 1\n    elif [[ -z \"$(get_docker_gen_container)\" ]] && ! is_docker_gen_container \"$(get_nginx_proxy_container)\"; then\n        echo \"Error: can't get docker-gen container id !\" >&2\n        echo \"If you are running a three containers setup, check that you are doing one of the following :\" >&2\n        echo -e \"\\t- Set the NGINX_DOCKER_GEN_CONTAINER env var on the letsencrypt-companion container to the name of the docker-gen container.\" >&2\n        echo -e \"\\t- Label the docker-gen container to use with 'com.github.nginx-proxy.docker-gen'.\" >&2\n        exit 1\n    fi\n    check_writable_directory '/etc/nginx/certs'\n    parse_true \"${ACME_HTTP_CHALLENGE_LOCATION:=false}\" && check_writable_directory '/etc/nginx/vhost.d'\n    check_writable_directory '/etc/acme.sh'\n    warn_html_directory\n    if [[ -f /app/letsencrypt_user_data ]]; then\n        check_writable_directory '/etc/nginx/vhost.d'\n        check_writable_directory '/etc/nginx/conf.d'\n    fi\n    parse_true \"${CREATE_DEFAULT_CERTIFICATE:=false}\" && check_default_cert_key\n    check_dh_group\n    reload_nginx\n    check_default_account\nfi\n\nexec \"$@\"\n"
  },
  {
    "path": "app/force_renew",
    "content": "#!/bin/bash\n\n# shellcheck source=letsencrypt_service\nsource /app/letsencrypt_service --source-only\n\nupdate_certs --force-renew\n"
  },
  {
    "path": "app/functions.sh",
    "content": "#!/bin/bash\n\n# Convert argument to lowercase (bash 4 only)\nfunction lc {\n\techo \"${@,,}\"\n}\n\nDEBUG=\"$(lc \"${DEBUG:-}\")\"\nif [[ \"$DEBUG\" == true ]]; then\n  DEBUG=1 && export DEBUG\nfi\n\nfunction parse_true() {\n\tcase \"$1\" in\n\n\t\ttrue | True | TRUE | 1)\n\t\treturn 0\n\t\t;;\n\n\t\t*)\n\t\treturn 1\n\t\t;;\n\n\tesac\n}\n\nfunction in_array() {\n    local needle=\"$1\" item\n    local -n arrref=\"$2\"\n    for item in \"${arrref[@]}\"; do\n        [[ \"$item\" == \"$needle\" ]] && return 0\n    done\n    return 1\n}\n\n[[ -z \"${VHOST_DIR:-}\" ]] && \\\n declare -r VHOST_DIR=/etc/nginx/vhost.d\n[[ -z \"${START_HEADER:-}\" ]] && \\\n declare -r START_HEADER='## Start of configuration add by letsencrypt container'\n[[ -z \"${END_HEADER:-}\" ]] && \\\n declare -r END_HEADER='## End of configuration add by letsencrypt container'\n\nfunction check_nginx_proxy_container_run {\n    local _nginx_proxy_container; _nginx_proxy_container=$(get_nginx_proxy_container)\n    if [[ -n \"$_nginx_proxy_container\" ]]; then\n        if [[ $(docker_api \"/containers/${_nginx_proxy_container}/json\" | jq -r '.State.Status') = \"running\" ]];then\n            return 0\n        else\n            echo \"$(date \"+%Y/%m/%d %T\") Error: nginx-proxy container ${_nginx_proxy_container} isn't running.\" >&2\n            return 1\n        fi\n    else\n        echo \"$(date \"+%Y/%m/%d %T\") Error: could not get a nginx-proxy container ID.\" >&2\n        return 1\nfi\n}\n\nfunction ascending_wildcard_locations {\n    # Given foo.bar.baz.example.com as argument, will output:\n    # - *.bar.baz.example.com\n    # - *.baz.example.com\n    # - *.example.com\n    local domain=\"${1:?}\"\n    local first_label\n    tld_regex=\"^[[:alpha:]]+$\"\n    regex=\"^[^.]+\\..+$\"\n    while [[ \"$domain\" =~ $regex ]]; do\n      first_label=\"${domain%%.*}\"\n      domain=\"${domain/#\"${first_label}.\"/}\"\n      if [[ \"$domain\" == \"*\" || \"$domain\" =~ $tld_regex ]]; then\n        return\n      else\n        echo \"*.${domain}\"\n      fi\n    done\n}\n\nfunction descending_wildcard_locations {\n    # Given foo.bar.baz.example.com as argument, will output:\n    # - foo.bar.baz.example.*\n    # - foo.bar.baz.*\n    # - foo.bar.*\n    # - foo.*\n    local domain=\"${1:?}\"\n    local last_label\n    regex=\"^.+\\.[^.]+$\"\n    while [[ \"$domain\" =~ $regex ]]; do\n      last_label=\"${domain##*.}\"\n      domain=\"${domain/%\".${last_label}\"/}\"\n      if [[ \"$domain\" == \"*\" ]]; then\n        return\n      else\n        echo \"${domain}.*\"\n      fi\n    done\n}\n\nfunction enumerate_wildcard_locations {\n    # Goes through ascending then descending wildcard locations for a given FQDN\n    local domain=\"${1:?}\"\n    ascending_wildcard_locations \"$domain\"\n    descending_wildcard_locations \"$domain\"\n}\n\nfunction add_location_configuration {\n    local domain=\"${1:-}\"\n    local wildcard_domain\n    # If no domain was passed use default instead\n    [[ -z \"$domain\" ]] && domain='default'\n\n    # If the domain does not have an exact matching location file, test the possible\n    # wildcard locations files. Use default is no location file is present at all.\n    if [[ ! -f \"${VHOST_DIR}/${domain}\" ]]; then\n      while read -r wildcard_domain; do\n        if [[ -f \"${VHOST_DIR}/${wildcard_domain}\" ]]; then\n          domain=\"$wildcard_domain\"\n          break\n        fi\n        domain='default'\n      done <<< \"$(enumerate_wildcard_locations \"$domain\")\"\n    fi\n\n    if [[ -f \"${VHOST_DIR}/${domain}\" && -n $(sed -n \"/$START_HEADER/,/$END_HEADER/p\" \"${VHOST_DIR}/${domain}\") ]]; then\n        # If the config file exist and already have the location configuration, end with exit code 0\n        return 0\n    else\n        # Else write the location configuration to a temp file ...\n        echo \"$START_HEADER\" > \"${VHOST_DIR}/${domain}\".new\n        cat /app/nginx_location.conf >> \"${VHOST_DIR}/${domain}\".new\n        echo \"$END_HEADER\" >> \"${VHOST_DIR}/${domain}\".new\n        # ... append the existing file content to the temp one ...\n        [[ -f \"${VHOST_DIR}/${domain}\" ]] && cat \"${VHOST_DIR}/${domain}\" >> \"${VHOST_DIR}/${domain}\".new\n        # ... and copy the temp file to the old one (if the destination file is bind mounted, you can't change\n        # its inode from within the container, so mv won't work and cp has to be used), then remove the temp file.\n        cp -f \"${VHOST_DIR}/${domain}\".new \"${VHOST_DIR}/${domain}\" && rm -f \"${VHOST_DIR}/${domain}\".new\n        return 1\n    fi\n}\n\nfunction add_standalone_configuration {\n    local domain=\"${1:?}\"\n    if grep -q \"server_name ${domain};\" /etc/nginx/conf.d/*.conf; then\n        # If the domain is already present in nginx's conf, use the location configuration.\n        add_location_configuration \"$domain\"\n    else\n        # Else use the standalone configuration.\n        cat > \"/etc/nginx/conf.d/standalone-cert-$domain.conf\" << EOF\nserver {\n    server_name $domain;\n    listen 80;\n    access_log /var/log/nginx/access.log vhost;\n    location ^~ /.well-known/acme-challenge/ {\n        auth_basic off;\n        auth_request off;\n        allow all;\n        root /usr/share/nginx/html;\n        try_files \\$uri =404;\n        break;\n    }\n}\nEOF\n    fi\n}\n\nfunction remove_all_standalone_configurations {\n    local old_shopt_options; old_shopt_options=$(shopt -p) # Backup shopt options\n    shopt -s nullglob\n    for file in \"/etc/nginx/conf.d/standalone-cert-\"*\".conf\"; do\n      rm -f \"$file\"\n    done\n    eval \"$old_shopt_options\" # Restore shopt options\n}\n\nfunction remove_all_location_configurations {\n    for file in \"${VHOST_DIR}\"/*; do\n        [[ -e \"$file\" ]] || continue\n        if [[ -n $(sed -n \"/$START_HEADER/,/$END_HEADER/p\" \"$file\") ]]; then\n            sed \"/$START_HEADER/,/$END_HEADER/d\" \"$file\" > \"$file\".new\n            cp -f \"$file\".new \"$file\" && rm -f \"$file\".new\n        fi\n    done\n}\n\nfunction check_cert_min_validity {\n    # Check if a certificate ($1) is still valid for a given amount of time in seconds ($2).\n    # Returns 0 if the certificate is still valid for this amount of time, 1 otherwise.\n    local cert_path=\"$1\"\n    local min_validity=\"$(( $(date \"+%s\") + $2 ))\"\n\n    local cert_expiration\n    cert_expiration=\"$(openssl x509 -noout -enddate -in \"$cert_path\" | cut -d \"=\" -f 2)\"\n    cert_expiration=\"$(date --utc --date \"${cert_expiration% GMT}\" \"+%s\")\"\n\n    [[ $cert_expiration -gt $min_validity ]] || return 1\n}\n\nfunction get_self_cid {\n    local self_cid=\"\"\n\n    # Try the /proc files methods first then resort to the Docker API.\n    if [[ -f /proc/1/cpuset ]]; then\n        self_cid=\"$(grep -Eo -m 1 '[[:alnum:]]{64}' /proc/1/cpuset)\"\n    fi\n    if [[ ( ${#self_cid} != 64 ) && ( -f /proc/self/cgroup ) ]]; then\n        self_cid=\"$(grep -Eo -m 1 '[[:alnum:]]{64}' /proc/self/cgroup)\"\n    fi\n    # cgroups v2\n    if [[ ( ${#self_cid} != 64 ) && ( -f /proc/self/mountinfo ) ]]; then\n        self_cid=\"$(grep '/userdata/hostname' /proc/self/mountinfo | grep -Eo -m 1 '[[:alnum:]]{64}')\"\n    fi\n    if [[ ( ${#self_cid} != 64 ) ]]; then\n        self_cid=\"$(docker_api \"/containers/$(hostname)/json\" | jq -r '.Id')\"\n    fi\n\n    # If it's not 64 characters long, then it's probably not a container ID.\n    if [[ ${#self_cid} == 64 ]]; then\n        echo \"$self_cid\"\n    else\n        echo \"$(date \"+%Y/%m/%d %T\"), Error: can't get my container ID !\" >&2\n        return 1\n    fi\n}\n\n## Docker API\nfunction docker_api {\n    local scheme\n    local curl_opts=(-s)\n    local method=${2:-GET}\n    # data to POST\n    if [[ -n \"${3:-}\" ]]; then\n        curl_opts+=(-d \"$3\")\n    fi\n    if [[ -z \"$DOCKER_HOST\" ]];then\n        echo \"Error DOCKER_HOST variable not set\" >&2\n        return 1\n    fi\n    if [[ $DOCKER_HOST == unix://* ]]; then\n        curl_opts+=(--unix-socket \"${DOCKER_HOST#unix://}\")\n        scheme='http://localhost'\n    else\n        scheme=\"http://${DOCKER_HOST#*://}\"\n    fi\n    [[ $method = \"POST\" ]] && curl_opts+=(-H 'Content-Type: application/json')\n    curl \"${curl_opts[@]}\" -X \"${method}\" \"${scheme}$1\"\n}\n\nfunction docker_exec {\n    local id=\"${1?missing id}\"\n    local cmd=\"${2?missing command}\"\n    local data; data=$(printf '{ \"AttachStdin\": false, \"AttachStdout\": true, \"AttachStderr\": true, \"Tty\":false,\"Cmd\": %s }' \"$cmd\")\n    exec_id=$(docker_api \"/containers/$id/exec\" \"POST\" \"$data\" | jq -r .Id)\n    if [[ -n \"$exec_id\" && \"$exec_id\" != \"null\" ]]; then\n        docker_api \"/exec/${exec_id}/start\" \"POST\" '{\"Detach\": false, \"Tty\":false}'\n    else\n        echo \"$(date \"+%Y/%m/%d %T\"), Error: can't exec command ${cmd} in container ${id}. Check if the container is running.\" >&2\n        return 1\n    fi\n}\n\nfunction docker_restart {\n    local id=\"${1?missing id}\"\n    docker_api \"/containers/$id/restart\" \"POST\"\n}\n\nfunction docker_kill {\n    local id=\"${1?missing id}\"\n    local signal=\"${2?missing signal}\"\n    docker_api \"/containers/$id/kill?signal=$signal\" \"POST\"\n}\n\nfunction labeled_cid {\n    docker_api \"/containers/json\" | jq -r '.[] | select(.Labels[\"'\"$1\"'\"])|.Id'\n}\n\nfunction is_docker_gen_container {\n    local id=\"${1?missing id}\"\n    if [[ $(docker_api \"/containers/$id/json\" | jq -r '.Config.Env[]' | grep -c -E '^DOCKER_GEN_VERSION=') = \"1\" ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction get_docker_gen_container {\n    # First try to get the docker-gen container ID from the container label.\n    local legacy_docker_gen_cid; legacy_docker_gen_cid=\"$(labeled_cid com.github.jrcs.letsencrypt_nginx_proxy_companion.docker_gen)\"\n    local new_docker_gen_cid; new_docker_gen_cid=\"$(labeled_cid com.github.nginx-proxy.docker-gen)\"\n    local docker_gen_cid; docker_gen_cid=\"${new_docker_gen_cid:-$legacy_docker_gen_cid}\"\n\n    # If the labeled_cid function dit not return anything and the env var is set, use it.\n    if [[ -z \"$docker_gen_cid\" ]] && [[ -n \"${NGINX_DOCKER_GEN_CONTAINER:-}\" ]]; then\n        docker_gen_cid=\"$NGINX_DOCKER_GEN_CONTAINER\"\n    fi\n\n    # If a container ID was found, output it. The function will return 1 otherwise.\n    [[ -n \"$docker_gen_cid\" ]] && echo \"$docker_gen_cid\"\n}\n\nfunction get_nginx_proxy_container {\n    local volumes_from\n    # First try to get the nginx container ID from the container label.\n    local legacy_nginx_cid; legacy_nginx_cid=\"$(labeled_cid com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy)\"\n    local new_nginx_cid; new_nginx_cid=\"$(labeled_cid com.github.nginx-proxy.nginx)\"\n    local nginx_cid; nginx_cid=\"${new_nginx_cid:-$legacy_nginx_cid}\"\n\n    # If the labeled_cid function dit not return anything ...\n    if [[ -z \"${nginx_cid}\" ]]; then\n        # ... and the env var is set, use it ...\n        if [[ -n \"${NGINX_PROXY_CONTAINER:-}\" ]]; then\n            nginx_cid=\"$NGINX_PROXY_CONTAINER\"\n        # ... else try to get the container ID with the volumes_from method.\n        elif [[ $(get_self_cid) ]]; then\n            volumes_from=$(docker_api \"/containers/$(get_self_cid)/json\" | jq -r '.HostConfig.VolumesFrom[]' 2>/dev/null)\n            for cid in $volumes_from; do\n                cid=\"${cid%:*}\" # Remove leading :ro or :rw set by remote docker-compose (thx anoopr)\n                if [[ $(docker_api \"/containers/$cid/json\" | jq -r '.Config.Env[]' | grep -c -E '^NGINX_VERSION=') = \"1\" ]];then\n                    nginx_cid=\"$cid\"\n                    break\n                fi\n            done\n        fi\n    fi\n\n    # If a container ID was found, output it. The function will return 1 otherwise.\n    [[ -n \"$nginx_cid\" ]] && echo \"$nginx_cid\"\n}\n\n## Nginx\nfunction reload_nginx {\n    local _docker_gen_container; _docker_gen_container=$(get_docker_gen_container)\n    local _nginx_proxy_container; _nginx_proxy_container=$(get_nginx_proxy_container)\n\n    if [[ -n \"${_docker_gen_container:-}\" ]]; then\n        # Using docker-gen and nginx in separate container\n        echo \"Reloading nginx docker-gen (using separate container ${_docker_gen_container})...\"\n        docker_kill \"${_docker_gen_container}\" SIGHUP\n\n        if [[ -n \"${_nginx_proxy_container:-}\" ]]; then\n            # Reloading nginx in case only certificates had been renewed\n            echo \"Reloading nginx (using separate container ${_nginx_proxy_container})...\"\n            docker_kill \"${_nginx_proxy_container}\" SIGHUP\n        fi\n    else\n        if [[ -n \"${_nginx_proxy_container:-}\" ]]; then\n            echo \"Reloading nginx proxy (${_nginx_proxy_container})...\"\n            docker_exec \"${_nginx_proxy_container}\" \\\n                '[ \"sh\", \"-c\", \"/app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\" ]' \\\n                | sed -rn 's/^.*([0-9]{4}\\/[0-9]{2}\\/[0-9]{2}.*$)/\\1/p'\n            [[ ${PIPESTATUS[0]} -eq 1 ]] && echo \"$(date \"+%Y/%m/%d %T\"), Error: can't reload nginx-proxy.\" >&2\n        fi\n    fi\n}\n\nfunction set_ownership_and_permissions {\n  local path=\"${1:?}\"\n  # The default ownership is root:root, with 755 permissions for folders and 600 for private files.\n  local user=\"${FILES_UID:-root}\"\n  local group=\"${FILES_GID:-$user}\"\n  local f_perms=\"${FILES_PERMS:-600}\"\n  local d_perms=\"${FOLDERS_PERMS:-755}\"\n\n  if [[ ! \"$f_perms\" =~ ^[0-7]{3,4}$ ]]; then\n    echo \"Warning : the provided files permission octal ($f_perms) is incorrect. Skipping ownership and permissions check.\"\n    return 1\n  fi\n  if [[ ! \"$d_perms\" =~ ^[0-7]{3,4}$ ]]; then\n    echo \"Warning : the provided folders permission octal ($d_perms) is incorrect. Skipping ownership and permissions check.\"\n    return 1\n  fi\n\n  [[ \"$DEBUG\" == 1 ]] && echo \"Debug: checking $path ownership and permissions.\"\n\n  # Find the user numeric ID if the FILES_UID environment variable isn't numeric.\n  if [[ \"$user\" =~ ^[0-9]+$ ]]; then\n    user_num=\"$user\"\n  # Check if this user exist inside the container\n  elif id -u \"$user\" > /dev/null 2>&1; then\n    # Convert the user name to numeric ID\n    local user_num; user_num=\"$(id -u \"$user\")\"\n    [[ \"$DEBUG\" == 1 ]] && echo \"Debug: numeric ID of user $user is $user_num.\"\n  else\n    echo \"Warning: user $user not found in the container, please use a numeric user ID instead of a user name. Skipping ownership and permissions check.\"\n    return 1\n  fi\n\n  # Find the group numeric ID if the FILES_GID environment variable isn't numeric.\n  if [[ \"$group\" =~ ^[0-9]+$ ]]; then\n    group_num=\"$group\"\n  # Check if this group exist inside the container\n  elif getent group \"$group\" > /dev/null 2>&1; then\n    # Convert the group name to numeric ID\n    local group_num; group_num=\"$(getent group \"$group\" | awk -F ':' '{print $3}')\"\n    [[ \"$DEBUG\" == 1 ]] && echo \"Debug: numeric ID of group $group is $group_num.\"\n  else\n    echo \"Warning: group $group not found in the container, please use a numeric group ID instead of a group name. Skipping ownership and permissions check.\"\n    return 1\n  fi\n\n  # Check and modify ownership if required.\n  if [[ -e \"$path\" ]]; then\n    if [[ \"$(stat -c %u:%g \"$path\" )\" != \"$user_num:$group_num\" ]]; then\n      [[ \"$DEBUG\" == 1 ]] && echo \"Debug: setting $path ownership to $user:$group.\"\n      if [[ -L \"$path\" ]]; then\n        chown -h \"$user_num:$group_num\" \"$path\"\n      else\n        chown \"$user_num:$group_num\" \"$path\"\n      fi\n    fi\n    # If the path is a folder, check and modify permissions if required.\n    if [[ -d \"$path\" ]]; then\n      if [[ \"$(stat -c %a \"$path\")\" != \"$d_perms\" ]]; then\n        [[ \"$DEBUG\" == 1 ]] && echo \"Debug: setting $path permissions to $d_perms.\"\n        chmod \"$d_perms\" \"$path\"\n      fi\n    # If the path is a file, check and modify permissions if required.\n    elif [[ -f \"$path\" ]]; then\n      # Use different permissions for private files (private keys and ACME account files) ...\n      if [[ \"$path\" =~ ^.*(key\\.pem|\\.key)$ ]]; then\n        if [[ \"$(stat -c %a \"$path\")\" != \"$f_perms\" ]]; then\n          [[ \"$DEBUG\" == 1 ]] && echo \"Debug: setting $path permissions to $f_perms.\"\n          chmod \"$f_perms\" \"$path\"\n        fi\n      # ... and for public files (certificates, chains, fullchains, DH parameters).\n      else\n        if [[ \"$(stat -c %a \"$path\")\" != \"644\" ]]; then\n          [[ \"$DEBUG\" == 1 ]] && echo \"Debug: setting $path permissions to 644.\"\n          chmod \"644\" \"$path\"\n        fi\n      fi\n    fi\n  else\n    echo \"Warning: $path does not exist. Skipping ownership and permissions check.\"\n    return 1\n  fi\n}\n"
  },
  {
    "path": "app/letsencrypt_service",
    "content": "#!/bin/bash\n\n# shellcheck source=functions.sh\nsource /app/functions.sh\n\nCERTS_UPDATE_INTERVAL=\"${CERTS_UPDATE_INTERVAL:-3600}\"\nACME_CA_URI=\"${ACME_CA_URI:-\"https://acme-v02.api.letsencrypt.org/directory\"}\"\nACME_CA_TEST_URI=\"https://acme-staging-v02.api.letsencrypt.org/directory\"\nDEFAULT_KEY_SIZE=\"${DEFAULT_KEY_SIZE:-4096}\"\nRENEW_PRIVATE_KEYS=\"$(lc \"${RENEW_PRIVATE_KEYS:-true}\")\"\nDEFAULT_RENEW=\"${DEFAULT_RENEW:-60}\"\n\n# Backward compatibility environment variable\nREUSE_PRIVATE_KEYS=\"$(lc \"${REUSE_PRIVATE_KEYS:-false}\")\"\n\nfunction strip_wildcard {\n    # Remove wildcard prefix if present\n    # https://github.com/nginx-proxy/nginx-proxy/tree/main/docs#wildcard-certificates\n    local -r domain=\"${1?missing domain argument}\"\n    if [[ \"${domain:0:2}\" == \"*.\" ]]; then\n        echo \"${domain:2}\"\n    else\n        echo \"$domain\"\n    fi\n}\n\nfunction create_link {\n    local -r source=${1?missing source argument}\n    local -r target=${2?missing target argument}\n    if [[ -f \"$target\" ]] && [[ \"$(readlink \"$target\")\" == \"$source\" ]]; then\n      set_ownership_and_permissions \"$target\"\n      [[ \"$DEBUG\" == 1 ]] && echo \"$target already linked to $source\"\n      return 1\n    else\n      ln -sf \"$source\" \"$target\" \\\n        && set_ownership_and_permissions \"$target\"\n    fi\n}\n\nfunction create_links {\n    local -r base_domain=${1?missing base_domain argument}\n    local domain=${2?missing base_domain argument}\n    domain=\"$(strip_wildcard \"$domain\")\"\n\n    if [[ ! -f \"/etc/nginx/certs/$base_domain/fullchain.pem\" || \\\n          ! -f \"/etc/nginx/certs/$base_domain/key.pem\" ]]; then\n        return 1\n    fi\n    local return_code=1\n    create_link \"./$base_domain/fullchain.pem\" \"/etc/nginx/certs/$domain.crt\"\n    return_code=$(( return_code & $? ))\n    create_link \"./$base_domain/key.pem\" \"/etc/nginx/certs/$domain.key\"\n    return_code=$(( return_code & $? ))\n    if [[ -f \"/etc/nginx/certs/dhparam.pem\" ]]; then\n        create_link ./dhparam.pem \"/etc/nginx/certs/$domain.dhparam.pem\"\n        return_code=$(( return_code & $? ))\n    fi\n    if [[ -f \"/etc/nginx/certs/$base_domain/chain.pem\" ]]; then\n        create_link \"./$base_domain/chain.pem\" \"/etc/nginx/certs/$domain.chain.pem\"\n        return_code=$(( return_code & $? ))\n    fi\n    return $return_code\n}\n\nfunction cleanup_links {\n    local -a LETSENCRYPT_CONTAINERS\n    local -a LETSENCRYPT_STANDALONE_CERTS\n    local -a ENABLED_DOMAINS\n    local -a SYMLINKED_DOMAINS\n    local -a DISABLED_DOMAINS\n\n    # Create an array containing domains for which a symlinked certificate\n    # exists in /etc/nginx/certs (excluding default cert).\n    for symlinked_domain in /etc/nginx/certs/*.crt; do\n        [[ -L \"$symlinked_domain\" ]] || continue\n        symlinked_domain=\"${symlinked_domain##*/}\"\n        symlinked_domain=\"${symlinked_domain%*.crt}\"\n        [[ \"$symlinked_domain\" != \"default\" ]] || continue\n        SYMLINKED_DOMAINS+=(\"$symlinked_domain\")\n    done\n    [[ \"$DEBUG\" == 1 ]] && echo \"Symlinked domains: ${SYMLINKED_DOMAINS[*]}\"\n\n    # Create an array containing domains that are considered\n    # enabled (ie present on /app/letsencrypt_service_data or /app/letsencrypt_user_data).\n    [[ -f /app/letsencrypt_service_data ]] && source /app/letsencrypt_service_data\n    [[ -f /app/letsencrypt_user_data ]] && source /app/letsencrypt_user_data\n    LETSENCRYPT_CONTAINERS+=( \"${LETSENCRYPT_STANDALONE_CERTS[@]}\" )\n    for cid in \"${LETSENCRYPT_CONTAINERS[@]}\"; do\n      local -n hosts_array=\"LETSENCRYPT_${cid}_HOST\"\n      for domain in \"${hosts_array[@]}\"; do\n        domain=\"$(strip_wildcard \"$domain\")\"\n        # Add domain to the array storing currently enabled domains.\n        ENABLED_DOMAINS+=(\"$domain\")\n      done\n    done\n    [[ \"$DEBUG\" == 1 ]] && echo \"Enabled domains: ${ENABLED_DOMAINS[*]}\"\n\n    # Create an array containing only domains for which a symlinked private key exists\n    # in /etc/nginx/certs but that no longer have a corresponding LETSENCRYPT_HOST set\n    # on an active container or on /app/letsencrypt_user_data\n    if [[ ${#SYMLINKED_DOMAINS[@]} -gt 0 ]]; then\n        mapfile -t DISABLED_DOMAINS < <(echo \"${SYMLINKED_DOMAINS[@]}\" \\\n                                             \"${ENABLED_DOMAINS[@]}\" \\\n                                             \"${ENABLED_DOMAINS[@]}\" \\\n                                             | tr ' ' '\\n' | sort | uniq -u)\n    fi\n    [[ \"$DEBUG\" == 1 ]] && echo \"Disabled domains: ${DISABLED_DOMAINS[*]}\"\n\n\n    # Remove disabled domains symlinks if present.\n    # Return 1 if nothing was removed and 0 otherwise.\n    if [[ ${#DISABLED_DOMAINS[@]} -gt 0 ]]; then\n      [[ \"$DEBUG\" == 1 ]] && echo \"Some domains are disabled :\"\n      for disabled_domain in \"${DISABLED_DOMAINS[@]}\"; do\n          [[ \"$DEBUG\" == 1 ]] && echo \"Checking domain ${disabled_domain}\"\n          cert_folder=\"$(readlink -f \"/etc/nginx/certs/${disabled_domain}.crt\")\"\n          # If the dotfile is absent, skip domain.\n          if [[ ! -e \"${cert_folder%/*}/.companion\" ]]; then\n              [[ \"$DEBUG\" == 1 ]] && echo \"No .companion file found in ${cert_folder}. ${disabled_domain} is not managed by acme-companion. Skipping domain.\"\n              continue\n          else\n              [[ \"$DEBUG\" == 1 ]] && echo \"${disabled_domain} is managed by acme-companion. Removing unused symlinks.\"\n          fi\n\n          for extension in .crt .key .dhparam.pem .chain.pem; do\n              file=\"${disabled_domain}${extension}\"\n              if [[ -n \"${file// }\" ]] && [[ -L \"/etc/nginx/certs/${file}\" ]]; then\n                  [[ \"$DEBUG\" == 1 ]] && echo \"Removing /etc/nginx/certs/${file}\"\n                  rm -f \"/etc/nginx/certs/${file}\"\n              fi\n          done\n      done\n      return 0\n    else\n      return 1\n    fi\n}\n\nfunction update_cert {\n    local cid=\"${1:?}\"\n    local -n hosts_array=\"LETSENCRYPT_${cid}_HOST\"\n    # First domain will be our base domain\n    local base_domain=\"${hosts_array[0]}\"\n\n    local wildcard_certificate='false'\n    if [[ \"${base_domain:0:2}\" == \"*.\" ]]; then\n        wildcard_certificate='true'\n    fi\n\n    local should_restart_container='false'\n\n    # Base CLI parameters array, used for both --register-account and --issue\n    local -a params_base_arr\n    params_base_arr+=(--log /dev/null)\n    params_base_arr+=(--useragent \"nginx-proxy/acme-companion/$COMPANION_VERSION (acme.sh/$ACMESH_VERSION)\")\n    [[ \"$DEBUG\" == 1 ]] && params_base_arr+=(--debug 2)\n\n    # Alternative trusted root CA path, used for test with Pebble\n    if [[ -n \"${CA_BUNDLE// }\" ]]; then\n        if [[ -f \"$CA_BUNDLE\" ]]; then\n            params_base_arr+=(--ca-bundle \"$CA_BUNDLE\")\n            [[ \"$DEBUG\" == 1 ]] && echo \"Debug: acme.sh will use $CA_BUNDLE as trusted root CA.\"\n        else\n            echo \"Warning: the path to the alternate CA bundle ($CA_BUNDLE) is not valid, using default Alpine trust store.\"\n        fi\n    fi\n\n    # CLI parameters array used for --register-account\n    local -a params_register_arr\n\n    # CLI parameters array used for --issue\n    local -a params_issue_arr\n\n    # ACME challenge type\n    local -n acme_challenge=\"ACME_${cid}_CHALLENGE\"\n    if [[ -z \"${acme_challenge}\" ]]; then\n        acme_challenge=\"${ACME_CHALLENGE:-HTTP-01}\"\n    fi\n    \n    if [[ \"$acme_challenge\" == \"HTTP-01\" ]]; then\n        # HTTP-01 challenge\n        if [[ \"$wildcard_certificate\" == 'true' ]]; then\n            echo \"Error: wildcard certificates (${base_domain}) can't be obtained with HTTP-01 challenge\"\n            return 1\n        fi\n        params_issue_arr+=(--webroot /usr/share/nginx/html)\n    elif [[ \"$acme_challenge\" == \"DNS-01\" ]]; then\n        # DNS-01 challenge\n        local acmesh_dns_config_used='none'\n\n        local default_acmesh_dns_api=\"${DEFAULT_ACMESH_DNS_API_CONFIG[DNS_API]}\"\n        [[ -n \"$default_acmesh_dns_api\" ]] && acmesh_dns_config_used='default'\n\n        local -n acmesh_dns_config=\"ACMESH_${cid}_DNS_API_CONFIG\"\n        local acmesh_dns_api=\"${acmesh_dns_config[DNS_API]}\"\n        [[ -n \"$acmesh_dns_api\" ]] && acmesh_dns_config_used='container'\n\n        local -a dns_api_keys\n\n        case \"$acmesh_dns_config_used\" in\n            'default')\n                params_issue_arr+=(--dns \"$default_acmesh_dns_api\")\n                # Loop over defined variable for default acme.sh DNS api config\n                for key in \"${!DEFAULT_ACMESH_DNS_API_CONFIG[@]}\"; do\n                    [[ \"$key\" == \"DNS_API\" ]] && continue\n                    dns_api_keys+=(\"$key\")\n                    local value=\"${DEFAULT_ACMESH_DNS_API_CONFIG[$key]}\"\n                    local -x \"$key\"=\"$value\"\n                done\n                ;;\n            'container')\n                params_issue_arr+=(--dns \"$acmesh_dns_api\")\n                # Loop over defined variable for per container acme.sh DNS api config\n                for key in \"${!acmesh_dns_config[@]}\"; do\n                    [[ \"$key\" == \"DNS_API\" ]] && continue\n                    dns_api_keys+=(\"$key\")\n                    local value=\"${acmesh_dns_config[$key]}\"\n                    local -x \"$key\"=\"$value\"\n                done\n                ;;\n            *)\n                echo \"Error: missing acme.sh DNS API for DNS challenge\"\n                return 1\n                ;;\n        esac\n\n        echo \"Info: DNS challenge using $acmesh_dns_api DNS API with the following keys: ${dns_api_keys[*]} (${acmesh_dns_config_used} config)\"\n    else \n        echo \"Error: unknown ACME challenge method: $acme_challenge\"\n        return 1\n    fi\n\n    local -n cert_keysize=\"LETSENCRYPT_${cid}_KEYSIZE\"\n    if [[ -z \"$cert_keysize\" ]] || \\\n        [[ ! \"$cert_keysize\" =~ ^('2048'|'3072'|'4096'|'ec-256'|'ec-384')$ ]]; then\n        cert_keysize=$DEFAULT_KEY_SIZE\n    fi\n    params_issue_arr+=(--keylength \"$cert_keysize\")\n\n    # OCSP-Must-Staple extension\n    local -n ocsp=\"ACME_${cid}_OCSP\"\n    if [[ $(lc \"$ocsp\") == true ]]; then\n        params_issue_arr+=(--ocsp-must-staple)\n    fi\n\n    local -n accountemail=\"LETSENCRYPT_${cid}_EMAIL\"\n    local config_home\n    # If we don't have a LETSENCRYPT_EMAIL from the proxied container\n    # and DEFAULT_EMAIL is set to a non empty value, use the latter.\n    if [[ -z \"$accountemail\" ]]; then\n        if [[ -n \"${DEFAULT_EMAIL// }\" ]]; then\n            accountemail=\"$DEFAULT_EMAIL\"\n        else\n            unset accountemail\n        fi\n    fi\n    if [[ -n \"${accountemail// }\" ]]; then\n        # If we got an email, use it with the corresponding config home\n        config_home=\"/etc/acme.sh/$accountemail\"\n    else\n        # If we did not get any email at all, use the default (empty mail) config\n        config_home=\"/etc/acme.sh/default\"\n    fi\n\n    local -n acme_ca_uri=\"ACME_${cid}_CA_URI\"\n    if [[ -z \"$acme_ca_uri\" ]]; then\n        # Use default or user provided ACME end point\n        acme_ca_uri=\"$ACME_CA_URI\"\n    fi\n    # LETSENCRYPT_TEST overrides LETSENCRYPT_ACME_CA_URI\n    local -n test_certificate=\"LETSENCRYPT_${cid}_TEST\"\n    if [[ $(lc \"$test_certificate\") == true ]]; then\n        # Use Let's Encrypt ACME V2 staging end point\n        acme_ca_uri=\"$ACME_CA_TEST_URI\"\n    fi\n\n    # Set relevant --server parameter and ca folder name\n    params_base_arr+=(--server \"$acme_ca_uri\")\n\n    # Reproduce acme.sh logic to determine the ca account folder path\n    local ca_host_dir\n    ca_host_dir=\"$(echo \"$acme_ca_uri\" | cut -d : -f 2 | tr -s / | cut -d / -f 2)\"\n    local ca_path_dir\n    ca_path_dir=\"$(echo \"$acme_ca_uri\" | cut -d : -f 2- | tr -s / | cut -d / -f 3-)\"\n\n    local relative_certificate_dir\n    if [[ \"$wildcard_certificate\" == 'true' ]]; then\n        relative_certificate_dir=\"wildcard_${base_domain:2}\"\n    else\n        relative_certificate_dir=\"$base_domain\"\n    fi\n    # If we're going to use one of LE stating endpoints ...\n    if [[ \"$acme_ca_uri\" =~ ^https://acme-staging.* ]]; then\n        # Unset accountemail\n        # force config dir to 'staging'\n        unset accountemail\n        config_home=\"/etc/acme.sh/staging\"\n        # Prefix test certificate directory with _test_\n        relative_certificate_dir=\"_test_${relative_certificate_dir}\"\n    fi\n\n    local absolute_certificate_dir=\"/etc/nginx/certs/$relative_certificate_dir\"\n    params_issue_arr+=( \\\n        --cert-file \"${absolute_certificate_dir}/cert.pem\" \\\n        --key-file \"${absolute_certificate_dir}/key.pem\" \\\n        --ca-file \"${absolute_certificate_dir}/chain.pem\" \\\n        --fullchain-file \"${absolute_certificate_dir}/fullchain.pem\" \\\n    )\n\n    [[ ! -d \"$config_home\" ]] && mkdir -p \"$config_home\"\n    params_base_arr+=(--config-home \"$config_home\")\n    local account_file=\"${config_home}/ca/${ca_host_dir}/${ca_path_dir}/account.json\"\n\n    # External Account Binding (EAB)\n    local -n eab_kid=\"ACME_${cid}_EAB_KID\"\n    local -n eab_hmac_key=\"ACME_${cid}_EAB_HMAC_KEY\"\n    if [[ ! -f \"$account_file\" ]]; then\n        if [[ -n \"${eab_kid}\" && -n \"${eab_hmac_key}\" ]]; then\n            # Register the ACME account with the per container EAB credentials.\n            params_register_arr+=(--eab-kid \"$eab_kid\" --eab-hmac-key \"$eab_hmac_key\")\n        elif [[ -n \"${ACME_EAB_KID// }\" && -n \"${ACME_EAB_HMAC_KEY// }\" ]]; then\n            # We don't have per-container EAB kid and hmac key or Zero SSL API key.\n            # Register the ACME account with the default EAB credentials.\n            params_register_arr+=(--eab-kid \"$ACME_EAB_KID\" --eab-hmac-key \"$ACME_EAB_HMAC_KEY\")\n        elif [[ -n \"${accountemail// }\" ]]; then\n            # We don't have per container nor default EAB credentials, register a new account.\n            params_register_arr+=(--accountemail \"$accountemail\")\n        fi\n    fi\n\n    # Zero SSL\n    if [[ \"$acme_ca_uri\" == \"https://acme.zerossl.com/v2/DV90\" ]]; then\n        # Test if we already have:\n        #   - an account file\n        #   - the --accountemail account registration parameter\n        #   - the --eab-kid and --eab-hmac-key account registration parameters\n        local account_ok='false'\n        if [[ -f \"$account_file\" ]]; then\n            account_ok='true'\n        elif in_array '--accountemail' 'params_register_arr'; then\n            account_ok='true'\n        elif in_array '--eab-kid' 'params_register_arr' && in_array '--eab-hmac-key' 'params_register_arr'; then\n            account_ok='true'\n        fi\n\n        if [[ $account_ok == 'false' ]]; then\n            local -n zerossl_api_key=\"ZEROSSL_${cid}_API_KEY\"\n            if [[ -z \"$zerossl_api_key\" ]]; then\n                # Try using the default API key\n                zerossl_api_key=\"${ZEROSSL_API_KEY:-}\"\n            fi\n\n            if [[ -n \"${zerossl_api_key// }\" ]]; then\n                # Generate a set of ACME EAB credentials using the ZeroSSL API.\n                local zerossl_api_response\n                if zerossl_api_response=\"$(curl -s -X POST \"https://api.zerossl.com/acme/eab-credentials?access_key=${zerossl_api_key}\")\"; then\n                    if [[ \"$(jq -r .success <<< \"$zerossl_api_response\")\" == 'true' ]]; then\n                        eab_kid=\"$(jq -r .eab_kid <<< \"$zerossl_api_response\")\"\n                        eab_hmac_key=\"$(jq -r .eab_hmac_key <<< \"$zerossl_api_response\")\"\n                        params_register_arr+=(--eab-kid \"$eab_kid\" --eab-hmac-key \"$eab_hmac_key\")\n                        [[ \"$DEBUG\" == 1 ]] && echo \"Successfull EAB credentials request against the ZeroSSL API, got the following EAB kid : ${eab_kid}\"\n                    else\n                        # The JSON response body indicated an unsuccesfull API call.\n                        echo \"Warning: the EAB credentials request against the ZeroSSL API was not successfull.\"\n                    fi\n                else\n                    # curl failed.\n                    echo \"Warning: curl failed to make an HTTP POST request to https://api.zerossl.com/acme/eab-credentials.\"\n                fi\n            else\n                # We don't have a Zero SSL ACME account, EAB credentials, a ZeroSSL API key or an account email :\n                # skip certificate account registration and certificate issuance.\n                echo \"Error: usage of ZeroSSL require an email bound account. No EAB credentials, ZeroSSL API key or email were provided for this certificate, creation aborted.\"\n                return 1\n            fi\n        fi\n    fi\n\n    # Account registration and update if required\n    if [[ ! -f \"$account_file\" ]]; then\n        params_register_arr=(\"${params_base_arr[@]}\" \"${params_register_arr[@]}\")\n        [[ \"$DEBUG\" == 1 ]] && echo \"Calling acme.sh --register-account with the following parameters : ${params_register_arr[*]}\"\n        acme.sh --register-account \"${params_register_arr[@]}\"\n    fi\n    if [[ -n \"${accountemail// }\" ]] && ! grep -q \"mailto:$accountemail\" \"$account_file\"; then\n        local -a params_update_arr=(\"${params_base_arr[@]}\" --accountemail \"$accountemail\")\n        [[ \"$DEBUG\" == 1 ]] && echo \"Calling acme.sh --update-account with the following parameters : ${params_update_arr[*]}\"\n        acme.sh --update-account \"${params_update_arr[@]}\"\n    fi\n\n    # If we still don't have an account.json file by this point, we've got an issue\n    if [[ ! -f \"$account_file\" ]]; then\n        echo \"Error: no ACME account was found or registered for $accountemail and $acme_ca_uri, certificate creation aborted.\"\n        return 1\n    fi\n\n    # acme.sh pre and post hooks\n    local -n acme_pre_hook=\"ACME_${cid}_PRE_HOOK\"\n    if [[ -n \"${acme_pre_hook}\" ]]; then\n        # Use per-container pre hook\n\t    params_issue_arr+=(--pre-hook \"$acme_pre_hook\")\n    elif [[ -n ${ACME_PRE_HOOK// } ]]; then\n        # Use default pre hook\n        params_issue_arr+=(--pre-hook \"$ACME_PRE_HOOK\")\n    fi\n\n    local -n acme_post_hook=\"ACME_${cid}_POST_HOOK\"\n    if [[ -n \"${acme_post_hook}\" ]]; then\n        # Use per-container post hook\n\t    params_issue_arr+=(--post-hook \"$acme_post_hook\")\n    elif [[ -n ${ACME_POST_HOOK// } ]]; then\n        # Use default post hook\n        params_issue_arr+=(--post-hook \"$ACME_POST_HOOK\")\n    fi\n\n    local -n acme_preferred_chain=\"ACME_${cid}_PREFERRED_CHAIN\"\n    if [[ -n \"${acme_preferred_chain}\" ]]; then\n        # Using amce.sh --preferred-chain to select alternate chain.\n        params_issue_arr+=(--preferred-chain \"$acme_preferred_chain\")\n    fi\n    if [[ \"$RENEW_PRIVATE_KEYS\" != 'false' && \"$REUSE_PRIVATE_KEYS\" != 'true' ]]; then\n        params_issue_arr+=(--always-force-new-domain-key)\n    fi\n    [[ \"${2:-}\" == \"--force-renew\" ]] && params_issue_arr+=(--force)\n\n    # Create directory for the first domain\n    mkdir -p \"$absolute_certificate_dir\"\n    set_ownership_and_permissions \"$absolute_certificate_dir\"\n\n    for domain in \"${hosts_array[@]}\"; do\n        # Add all the domains to certificate\n        params_issue_arr+=(--domain \"$domain\")\n        # If enabled, add location configuration for the domain\n        if [[ \"$acme_challenge\" == \"HTTP-01\" ]] && parse_true \"${ACME_HTTP_CHALLENGE_LOCATION:=false}\"; then\n            add_location_configuration \"$domain\" || reload_nginx\n        fi\n    done\n\n    # Allow to override day to renew cert\n    params_issue_arr+=(--days \"$DEFAULT_RENEW\")\n\n    params_issue_arr=(\"${params_base_arr[@]}\" \"${params_issue_arr[@]}\")\n    [[ \"$DEBUG\" == 1 ]] && echo \"Calling acme.sh --issue with the following parameters : ${params_issue_arr[*]}\"\n    echo \"Creating/renewal $base_domain certificates... (${hosts_array[*]})\"\n    acme.sh --issue \"${params_issue_arr[@]}\"\n\n    local acmesh_return=$?\n\n    # 0 = success, 2 = RENEW_SKIP\n    if [[ $acmesh_return == 0 || $acmesh_return == 2 ]]; then\n        for domain in \"${hosts_array[@]}\"; do\n            create_links \"$relative_certificate_dir\" \"$domain\" \\\n                && should_reload_nginx='true' \\\n                && should_restart_container='true'\n        done\n        echo \"${COMPANION_VERSION:-}\" > \"${absolute_certificate_dir}/.companion\"\n        set_ownership_and_permissions \"${absolute_certificate_dir}/.companion\"\n        # Make private key root readable only\n        for file in cert.pem key.pem chain.pem fullchain.pem; do\n            local file_path=\"${absolute_certificate_dir}/${file}\"\n            [[ -e \"$file_path\" ]] && set_ownership_and_permissions \"$file_path\"\n        done\n        local acme_private_key\n        acme_private_key=\"$(find /etc/acme.sh -name \"*.key\" -path \"*${hosts_array[0]}*\")\"\n        [[ -e \"$acme_private_key\" ]] && set_ownership_and_permissions \"$acme_private_key\"\n        # Queue nginx reload if a certificate was issued or renewed\n        [[ $acmesh_return -eq 0 ]] \\\n            && should_reload_nginx='true' \\\n            && should_restart_container='true'\n    fi\n\n    # Restart container if certs are updated and the respective environmental variable is set\n    local -n restart_container=\"LETSENCRYPT_${cid}_RESTART_CONTAINER\"\n    if [[ $(lc \"$restart_container\") == true ]] && [[ \"$should_restart_container\" == 'true' ]]; then\n        echo \"Restarting container (${cid})...\"\n        docker_restart \"${cid}\"\n    fi\n\n    for domain in \"${hosts_array[@]}\"; do\n        if [[ -f \"/etc/nginx/conf.d/standalone-cert-$domain.conf\" ]]; then\n            [[ \"$DEBUG\" == 1 ]] && echo \"Debug: removing standalone configuration file /etc/nginx/conf.d/standalone-cert-$domain.conf\"\n            rm -f \"/etc/nginx/conf.d/standalone-cert-$domain.conf\" && should_reload_nginx='true'\n        fi\n    done\n\n    if ! parse_true \"${RELOAD_NGINX_ONLY_ONCE:-false}\" && parse_true $should_reload_nginx; then\n        reload_nginx\n    fi\n}\n\nfunction update_certs {\n    local -a LETSENCRYPT_CONTAINERS\n    local -a LETSENCRYPT_STANDALONE_CERTS\n\n    pushd /etc/nginx/certs > /dev/null || return\n    check_nginx_proxy_container_run || return\n\n    # Load relevant container settings\n    if [[ -f /app/letsencrypt_service_data ]]; then\n        source /app/letsencrypt_service_data\n    else\n        echo \"Warning: /app/letsencrypt_service_data not found, skipping data from containers.\"\n    fi\n\n    # Load settings for standalone certs\n    if [[ -f /app/letsencrypt_user_data ]]; then\n        if source /app/letsencrypt_user_data; then\n            for cid in \"${LETSENCRYPT_STANDALONE_CERTS[@]}\"; do\n                local -n hosts_array=\"LETSENCRYPT_${cid}_HOST\"\n                \n                local -n acme_challenge=\"ACME_${cid}_CHALLENGE\"\n                acme_challenge=\"${acme_challenge:-HTTP-01}\"\n                \n                if [[ \"$acme_challenge\" == \"HTTP-01\" ]]; then\n                    for domain in \"${hosts_array[@]}\"; do\n                        add_standalone_configuration \"$domain\"\n                    done\n                fi\n            done\n            reload_nginx\n            LETSENCRYPT_CONTAINERS+=( \"${LETSENCRYPT_STANDALONE_CERTS[@]}\" )\n        else\n            echo \"Warning: could not source /app/letsencrypt_user_data, skipping user data\"\n        fi\n    fi\n\n    should_reload_nginx='false'\n    for cid in \"${LETSENCRYPT_CONTAINERS[@]}\"; do\n        # Pass the eventual --force-renew arg to update_cert() as second arg\n        update_cert \"$cid\" \"${1:-}\"\n    done\n\n    cleanup_links && should_reload_nginx='true'\n\n    [[ \"$should_reload_nginx\" == 'true' ]] && reload_nginx\n\n    popd > /dev/null || return\n}\n\n# Allow the script functions to be sourced without starting the Service Loop.\nif [ \"${1}\" == \"--source-only\" ]; then\n  return 0\nfi\n\npid=\n# Service Loop: When this script exits, start it again.\ntrap '[[ $pid ]] && kill $pid; exec $0' EXIT\ntrap 'trap - EXIT' INT TERM\n\nupdate_certs \"$@\"\n\n# Wait some amount of time\necho \"Sleep for ${CERTS_UPDATE_INTERVAL}s\"\nsleep $CERTS_UPDATE_INTERVAL & pid=$!\nwait\npid=\n"
  },
  {
    "path": "app/letsencrypt_service_data.tmpl",
    "content": "#!/bin/bash\n# shellcheck disable=SC2034\n{{- $DEFAULT_ACMESH_DNS_API_CONFIG := fromYaml (coalesce $.Env.ACMESH_DNS_API_CONFIG \"\") }}\n{{- if $DEFAULT_ACMESH_DNS_API_CONFIG }}\n    {{- \"\\n\" }}declare -A DEFAULT_ACMESH_DNS_API_CONFIG=(\n    {{- range $key, $value := $DEFAULT_ACMESH_DNS_API_CONFIG }}\n        {{- \"\\n\\t\" }}['{{ $key }}']='{{ $value }}'\n    {{- end }}\n    {{- \"\\n\" }})\n{{- end }}\n\n\nLETSENCRYPT_CONTAINERS=(\n{{ $orderedContainers := sortObjectsByKeysDesc $ \"Created\" }}\n{{ range $_, $container := whereExist $orderedContainers \"Env.LETSENCRYPT_HOST\" }}\n    {{ if trim $container.Env.LETSENCRYPT_HOST }}\n        {{ if parseBool (coalesce $container.Env.LETSENCRYPT_SINGLE_DOMAIN_CERTS \"false\") }}\n            {{/* Explicit per-domain splitting of the certificate */}}\n            {{ range $host := split $container.Env.LETSENCRYPT_HOST \",\" }}\n                {{ $host := trim $host }}\n                {{- \"\\n\\t\" }}'{{ printf \"%.12s\" $container.ID }}_{{ sha1 $host }}' # {{ $container.Name }}, created at {{ $container.Created }}\n            {{ end }}\n        {{ else }}\n            {{/* Default: multi-domain (SAN) certificate */}}\n            {{- \"\\n\\t\" }}'{{ printf \"%.12s\" $container.ID }}' # {{ $container.Name }}, created at {{ $container.Created }}\n        {{ end }}\n    {{ end }}\n{{ end }}\n)\n\n{{ range $hosts, $containers := groupBy $ \"Env.LETSENCRYPT_HOST\" }}\n    {{ $hosts := trimSuffix \",\" $hosts }}\n    {{ range $container := $containers }}\n        {{/* Trim spaces and set empty values on per-container environment variables */}}\n        {{ $KEYSIZE := trim (coalesce $container.Env.LETSENCRYPT_KEYSIZE \"\") }}\n        {{ $STAGING := trim (coalesce $container.Env.LETSENCRYPT_TEST \"\") }}\n        {{ $EMAIL := trim (coalesce $container.Env.LETSENCRYPT_EMAIL \"\") }}\n        {{ $CA_URI := trim (coalesce $container.Env.ACME_CA_URI \"\") }}\n        {{ $ACME_CHALLENGE := trim (coalesce $container.Env.ACME_CHALLENGE \"\") }}\n        {{ $ACMESH_DNS_API_CONFIG := fromYaml (coalesce $container.Env.ACMESH_DNS_API_CONFIG \"\") }}\n        {{ $PREFERRED_CHAIN := trim (coalesce $container.Env.ACME_PREFERRED_CHAIN \"\") }}\n        {{ $OCSP := trim (coalesce $container.Env.ACME_OCSP \"\") }}\n        {{ $EAB_KID := trim (coalesce $container.Env.ACME_EAB_KID \"\") }}\n        {{ $EAB_HMAC_KEY := trim (coalesce $container.Env.ACME_EAB_HMAC_KEY \"\") }}\n        {{ $ZEROSSL_API_KEY := trim (coalesce $container.Env.ZEROSSL_API_KEY \"\") }}\n        {{ $RESTART_CONTAINER := trim (coalesce $container.Env.LETSENCRYPT_RESTART_CONTAINER \"\") }}\n        {{ $PRE_HOOK := trim (coalesce $container.Env.ACME_PRE_HOOK \"\") }}\n        {{ $POST_HOOK := trim (coalesce $container.Env.ACME_POST_HOOK \"\") }}\n        {{ $cid := printf \"%.12s\" $container.ID }}\n        {{- \"\\n\" }}# Container {{ $cid }} ({{ $container.Name }})\n        {{ if parseBool (coalesce $container.Env.LETSENCRYPT_SINGLE_DOMAIN_CERTS \"false\") }}\n            {{/* Explicit per-domain splitting of the certificate */}}\n            {{ range $host := split $hosts \",\" }}\n                {{ $host := trim $host }}\n                {{ $host := trimSuffix \".\" $host }}\n                {{ $hostHash := sha1 $host }}\n                {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_{{ $hostHash }}_HOST=('{{ $host }}')\n                {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_{{ $hostHash }}_KEYSIZE=\"{{ $KEYSIZE }}\"\n                {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_{{ $hostHash }}_TEST=\"{{ $STAGING }}\"\n                {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_{{ $hostHash }}_EMAIL=\"{{ $EMAIL }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_CA_URI=\"{{ $CA_URI }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_CHALLENGE=\"{{ $ACME_CHALLENGE }}\"\n                {{- if $ACMESH_DNS_API_CONFIG }}\n                    {{- \"\\n\" }}declare -A ACMESH_{{ $cid }}_{{ $hostHash }}_DNS_API_CONFIG=(\n                    {{- range $key, $value := $ACMESH_DNS_API_CONFIG }}\n                        {{- \"\\n\\t\" }}['{{ $key }}']='{{ $value }}'\n                    {{- end }}\n                    {{- \"\\n\" }})\n                {{- end }}\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_PREFERRED_CHAIN=\"{{ $PREFERRED_CHAIN }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_OCSP=\"{{ $OCSP }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_EAB_KID=\"{{ $EAB_KID }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_EAB_HMAC_KEY=\"{{ $EAB_HMAC_KEY }}\"\n                {{- \"\\n\" }}ZEROSSL_{{ $cid }}_{{ $hostHash }}_API_KEY=\"{{ $ZEROSSL_API_KEY }}\"\n                {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_{{ $hostHash }}_RESTART_CONTAINER=\"{{ $RESTART_CONTAINER }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_PRE_HOOK=\"{{ $PRE_HOOK }}\"\n                {{- \"\\n\" }}ACME_{{ $cid }}_{{ $hostHash }}_POST_HOOK=\"{{ $POST_HOOK }}\"\n            {{ end }}\n        {{ else }}\n            {{/* Default: multi-domain (SAN) certificate */}}\n            {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_HOST=( \n                    {{- range $host := split $hosts \",\" }}\n                        {{- $host := trim $host }}\n                        {{- $host := trimSuffix \".\" $host }}\n                        {{- \"\\n\\t\" }}'{{ $host }}'\n                    {{- end }}\n            {{- \"\\n\" }})\n            {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_KEYSIZE=\"{{ $KEYSIZE }}\"\n            {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_TEST=\"{{ $STAGING }}\"\n            {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_EMAIL=\"{{ $EMAIL }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_CA_URI=\"{{ $CA_URI }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_CHALLENGE=\"{{ $ACME_CHALLENGE }}\"\n            {{- if $ACMESH_DNS_API_CONFIG }}\n                {{- \"\\n\" }}declare -A ACMESH_{{ $cid }}_DNS_API_CONFIG=(\n                {{- range $key, $value := $ACMESH_DNS_API_CONFIG }}\n                    {{- \"\\n\\t\" }}['{{ $key }}']='{{ $value }}'\n                {{- end }}\n                {{- \"\\n\" }})\n            {{- end }}\n            {{- \"\\n\" }}ACME_{{ $cid }}_PREFERRED_CHAIN=\"{{ $PREFERRED_CHAIN }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_OCSP=\"{{ $OCSP }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_EAB_KID=\"{{ $EAB_KID }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_EAB_HMAC_KEY=\"{{ $EAB_HMAC_KEY }}\"\n            {{- \"\\n\" }}ZEROSSL_{{ $cid }}_API_KEY=\"{{ $ZEROSSL_API_KEY }}\"\n            {{- \"\\n\" }}LETSENCRYPT_{{ $cid }}_RESTART_CONTAINER=\"{{ $RESTART_CONTAINER }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_PRE_HOOK=\"{{ $PRE_HOOK }}\"\n            {{- \"\\n\" }}ACME_{{ $cid }}_POST_HOOK=\"{{ $POST_HOOK }}\"\n        {{ end }}\n    {{ end }}\n{{ end }}\n"
  },
  {
    "path": "app/nginx_location.conf",
    "content": "location ^~ /.well-known/acme-challenge/ {\n    auth_basic off;\n    auth_request off;\n    allow all;\n    root /usr/share/nginx/html;\n    try_files $uri =404;\n    break;\n}\n"
  },
  {
    "path": "app/signal_le_service",
    "content": "#!/bin/bash\n\n# Using busybox pkill\npkill -USR1 -f /app/letsencrypt_service\n"
  },
  {
    "path": "app/start.sh",
    "content": "#!/bin/bash\n\n# SIGTERM-handler\nterm_handler() {\n    [[ -n \"$docker_gen_pid\" ]] && kill \"$docker_gen_pid\"\n    [[ -n \"$letsencrypt_service_pid\" ]] && kill \"$letsencrypt_service_pid\"\n\n    # shellcheck source=functions.sh\n    source /app/functions.sh\n    remove_all_location_configurations\n    remove_all_standalone_configurations\n\n    exit 0\n}\n\ntrap 'term_handler' INT QUIT TERM\n\n/app/letsencrypt_service &\nletsencrypt_service_pid=$!\n\nwait_default=\"5s:20s\"\nDOCKER_GEN_WAIT=\"${DOCKER_GEN_WAIT:-$wait_default}\"\ndocker-gen -watch -notify '/app/signal_le_service' -wait \"$DOCKER_GEN_WAIT\" /app/letsencrypt_service_data.tmpl /app/letsencrypt_service_data &\ndocker_gen_pid=$!\n\n# wait \"indefinitely\"\nwhile [[ -e /proc/$docker_gen_pid ]]; do\n    wait $docker_gen_pid # Wait for any signals or end of execution of docker-gen\ndone\n\n# Stop container properly\nterm_handler\n"
  },
  {
    "path": "docs/Advanced-usage.md",
    "content": "## Advanced usage (with the nginx and docker-gen containers)\n\n**nginx-proxy** can also be run as two separate containers using the [nginx-proxy/**docker-gen**](https://github.com/nginx-proxy/docker-gen) image and the official [**nginx**](https://hub.docker.com/_/nginx/) image. You may want to do this to prevent having the docker socket bound to a publicly exposed container service (ie avoid mounting the docker socket in the nginx exposed container).\n\nPlease read and try [basic usage](./Basic-usage.md), and **validate that you have a working two containers setup** before using the three containers setup. In addition to the steps described there, running **nginx-proxy** as two separate containers with **acme-companion** requires the following:\n\n1) Download and mount the template file [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/main/nginx.tmpl) into the **docker-gen** container. You can get the nginx.tmpl file with a command like:\n\n```\ncurl https://raw.githubusercontent.com/nginx-proxy/nginx-proxy/main/nginx.tmpl > /path/to/nginx.tmpl\n```\n\n2) Use the `com.github.nginx-proxy.docker-gen` label on the **docker-gen** container, or explicitly set the `NGINX_DOCKER_GEN_CONTAINER` environment variable on the **acme-companion** container to the name or id of the **docker-gen** container (we'll use the later method in the example).\n\n3) Declare `/etc/nginx/conf.d` as a volume on the nginx container so that it can be shared with the **docker-gen** container.\n\nExample:\n\n### Step 1 - nginx\n\n* Start nginx [(official image)](https://hub.docker.com/_/nginx/) with the required volumes:\n\n```shell\n$ docker run --detach \\\n    --name nginx-proxy \\\n    --publish 80:80 \\\n    --publish 443:443 \\\n    --volume conf:/etc/nginx/conf.d  \\\n    --volume html:/usr/share/nginx/html \\\n    --volume certs:/etc/nginx/certs \\\n    nginx\n```\n\n### Step 2 - docker-gen\n\n* Start the **docker-gen** container with the shared volumes (with `--volume-from`), the template file and the docker socket:\n\n```shell\n$ docker run --detach \\\n    --name nginx-proxy-gen \\\n    --volumes-from nginx-proxy \\\n    --volume /path/to/nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro \\\n    --volume /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/docker-gen \\\n    -notify-sighup nginx-proxy -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf\n```\n\nNote that you must pass the exact name of the **nginx** container to **docker-gen** `-notify-sighup` argument (here `nginx-proxy`).\n\n\n### Step 3 - acme-companion\n\n* Start the **acme-companion** container with the `NGINX_DOCKER_GEN_CONTAINER` environment variable correctly set:\n\n```shell\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume acme:/etc/acme.sh \\\n    --env \"NGINX_DOCKER_GEN_CONTAINER=nginx-proxy-gen\" \\\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\n    nginxproxy/acme-companion\n```\n\n### Step 4 - proxyed container(s)\n\n* Once the three containers are up, start any containers to be proxied as described in [basic usage](./Basic-usage.md).\n\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=subdomain.yourdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=subdomain.yourdomain.tld\" \\\n    nginx\n```\n\nIf you are experiencing issues with this setup, fall back to the [basic setup](./Basic-usage.md). The advanced setup is not meant to be obligatory.\n"
  },
  {
    "path": "docs/Basic-usage.md",
    "content": "## Basic usage (with the nginx-proxy container)\n\nTwo writable volumes must be declared on the **nginx-proxy** container so that they can be shared with the **acme-companion** container:\n\n* `/etc/nginx/certs` to store certificates and private keys (readonly for the **nginx-proxy** container).\n* `/usr/share/nginx/html` to write `HTTP-01` challenge files.\n\nAdditionally, a third volume must be declared on the **acme-companion** container to store `acme.sh` configuration and state: `/etc/acme.sh`.\n\nPlease also read the doc about [data persistence](./Persistent-data.md).\n\nExample of use:\n\n### Step 1 - nginx-proxy\n\nStart **nginx-proxy** with the two additional volumes declared:\n\n```shell\n$ docker run --detach \\\n    --name nginx-proxy \\\n    --publish 80:80 \\\n    --publish 443:443 \\\n    --volume certs:/etc/nginx/certs \\\n    --volume html:/usr/share/nginx/html \\\n    --volume /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy\n```\n\nBinding the host docker socket (`/var/run/docker.sock`) inside the container to `/tmp/docker.sock` is a requirement of **nginx-proxy**.\n\n### Step 2 - acme-companion\n\nStart the **acme-companion** container, getting the volumes from **nginx-proxy** with `--volumes-from`:\n\n```shell\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume acme:/etc/acme.sh \\\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\n    nginxproxy/acme-companion\n```\n\nThe host docker socket has to be bound inside this container too, this time to `/var/run/docker.sock`.\n\nAlbeit **optional**, it is **recommended** to provide a valid default email address through the `DEFAULT_EMAIL` environment variable, so that Let's Encrypt can warn you about expiring certificates and allow you to recover your account.\n\n### Step 3 - proxyed container(s)\n\nOnce both **nginx-proxy** and **acme-companion** containers are up and running, start any container you want proxyed with environment variables `VIRTUAL_HOST` and `LETSENCRYPT_HOST` both set to the domain(s) your proxyed container is going to use. Multiple hosts can be separated using commas.\n\n[`VIRTUAL_HOST`](https://github.com/nginx-proxy/nginx-proxy#usage) control proxying by **nginx-proxy** and `LETSENCRYPT_HOST` control certificate creation and SSL enabling by **acme-companion**.\n\nCertificates will only be issued for containers that have both `VIRTUAL_HOST` and `LETSENCRYPT_HOST` variables set to domain(s) that correctly resolve to the host, provided the host is publicly reachable.\n\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=subdomain.yourdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=subdomain.yourdomain.tld\" \\\n    nginx\n```\n\nThe containers being proxied must expose the port to be proxied, either by using the `EXPOSE` directive in their Dockerfile or by using the `--expose` flag to `docker run` or `docker create`.\n\nIf the proxyed container listen on and expose another port than the default `80`, you can force **nginx-proxy** to use this port with the [`VIRTUAL_PORT`](https://github.com/nginx-proxy/nginx-proxy#multiple-ports) environment variable.\n\nExample using [Grafana](https://hub.docker.com/r/grafana/grafana/) (expose and listen on port 3000):\n\n```shell\n$ docker run --detach \\\n    --name grafana \\\n    --env \"VIRTUAL_HOST=othersubdomain.yourdomain.tld\" \\\n    --env \"VIRTUAL_PORT=3000\" \\\n    --env \"LETSENCRYPT_HOST=othersubdomain.yourdomain.tld\" \\\n    --env \"LETSENCRYPT_EMAIL=mail@yourdomain.tld\" \\\n    grafana/grafana\n```\n\nRepeat [Step 3](#step-3---proxyed-containers) for any other container you want to proxy.\n"
  },
  {
    "path": "docs/Container-configuration.md",
    "content": "## Optional container environment variables for custom configuration.\n\n* `ACME_CA_URI` - Directory URI for the CA ACME API endpoint (defaults to ``https://acme-v02.api.letsencrypt.org/directory``).\n\nIf you set this environment variable value to `https://acme-staging-v02.api.letsencrypt.org/directory` the container will obtain its certificates from Let's Encrypt test API endpoint that don't have the [5 certs/week/domain limit](https://letsencrypt.org/docs/rate-limits/) (but are not trusted by browsers).\n\nFor example\n\n```bash\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume certs:/etc/nginx/certs:rw \\\n    --volume acme:/etc/acme.sh \\\n    --env \"ACME_CA_URI=https://acme-staging-v02.api.letsencrypt.org/directory\" \\\n    nginxproxy/acme-companion\n```\nYou can also create test certificates per container (see [Test certificates](./Let's-Encrypt-and-ACME.md#test-certificates))\n\n* `DEBUG` - Set it to `1` to enable debugging of the entrypoint script and generation of LetsEncrypt certificates, which could help you pin point any configuration issues.\n\n* `RENEW_PRIVATE_KEYS` - Set it to `false` to make `acme.sh` reuse previously generated private key for each certificate instead of creating a new one on certificate renewal. Reusing private keys can help if you intend to use [HPKP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning), but please note that HPKP has been deprecated by Google's Chrome and that it is therefore strongly discouraged to use it at all.\n\n* `DHPARAM_BITS` - Change the key size of the RFC7919 Diffie-Hellman group used by the container from the default value of 4096 bits. Supported values are `2048`, `3072` and `4096`. The DH group file will be located in the container at `/etc/nginx/certs/dhparam.pem`. Mounting a different `dhparam.pem` file at that location will override the RFC7919 group creation by the acme-companion container. **COMPATIBILITY WARNING**: some older clients (like Java 6 and 7) do not support DH keys with over 1024 bits. In order to support these clients, you must provide your own `dhparam.pem`.\n\n* `DHPARAM_SKIP` - Set it to `true` to disable the Diffie-Hellman group creation by the container entirely.\n\n* `CA_BUNDLE` - This is a test only variable [for use with Pebble](https://github.com/letsencrypt/pebble#avoiding-client-https-errors). It changes the trusted root CA used by `acme.sh`, from the default Alpine trust store to the CA bundle file located at the provided path (inside the container). Do **not** use it in production unless you are running your own ACME CA.\n\n* `CERTS_UPDATE_INTERVAL` - 3600 seconds by default, this defines how often the container will check if the certificates require update.\n\n* `ACME_PRE_HOOK` - The provided command will be run before every certificate issuance. The action is limited to the commands available inside the **acme-companion** container. For example `--env \"ACME_PRE_HOOK=echo 'start'\"`. For more information see [Pre- and Post-Hook](./Hooks.md)\n\n* `ACME_POST_HOOK` - The provided command will be run after every certificate issuance. The action is limited to the commands available inside the **acme-companion** container. For example `--env \"ACME_POST_HOOK=echo 'end'\"`. For more information see [Pre- and Post-Hook](./Hooks.md)\n\n* `DEFAULT_RENEW` - 60 days by default, this defines the number of days between certificate renewals attempts. For certificates issued by certain Certificate Authorities, such as Buypass, which have a lifespan of 180 days, it may be advisable to initiate the renewal process on day 170 rather than the default day 60. See [BuyPass.com CA](https://github.com/acmesh-official/acme.sh/wiki/BuyPass.com-CA) for more detail.\n\n* `ACME_HTTP_CHALLENGE_LOCATION` - Previously **acme-companion** automatically added the ACME HTTP challenge location to the nginx configuration through files generated in `/etc/nginx/vhost.d`. Recent versions of **nginx-proxy** (>= `1.6`) already include the required location configuration, which remove the need for **acme-companion** to attempt to dynamically add them. If you're running and older version of **nginx-proxy** (or **docker-gen** with an older version of the `nginx.tmpl` file), you can re-enable this behaviour by setting `ACME_HTTP_CHALLENGE_LOCATION` to `true`.\n\n* `RELOAD_NGINX_ONLY_ONCE` - The companion reload nginx configuration after every new or renewed certificate. Previously this was done only once per service loop, at the end of the loop (this was causing delayed availability of HTTPS enabled application when multiple new certificates where requested at once, see [issue #1147](https://github.com/nginx-proxy/acme-companion/issues/1147)). You can restore the previous behaviour if needed by setting the environment variable `RELOAD_NGINX_ONLY_ONCE` to `true`.\n\n* `DOCKER_CONTAINER_FILTERS` -  You can filter which containers are considered by acme-companion by using the `DOCKER_CONTAINER_FILTERS` environment variable (by default, acme-companion will consider all running containers). It takes a comma separated list of `key=value` pairs. For example, setting `DOCKER_CONTAINER_FILTERS` environment variable to `network=mynetwork` will cause acme-companion to consider only containers connected to the `mynetwork` network. See the [Docker CLI documentation](https://docs.docker.com/reference/cli/docker/container/ls/#filter) for details on available filters.\n"
  },
  {
    "path": "docs/Container-utilities.md",
    "content": "The container provide the following utilities (replace `nginx-proxy-acme` with the name or ID of your **acme-companion** container when executing the commands):\n\n### Force certificates renewal\nIf needed, you can force a running **acme-companion** container to renew all certificates that are currently in use with the following command:\n\n```bash\n$ docker exec nginx-proxy-acme /app/force_renew\n```\n\n### Manually trigger the service loop\nYou can trigger the execution of the service loop before the hourly execution with:\n\n```bash\n$ docker exec nginx-proxy-acme /app/signal_le_service\n```\nUnlike the previous command, this won't force renewal of certificates that don't need to be renewed.\n\n### Show certificates informations\nTo display informations about your existing certificates, use the following command:\n\n```bash\n$ docker exec nginx-proxy-acme /app/cert_status\n```"
  },
  {
    "path": "docs/Docker-Compose.md",
    "content": "## Usage with Docker Compose\n\nAs stated by its repository, [Docker Compose](https://github.com/docker/compose) is a tool for defining and running multi-container Docker applications using a single _Compose file_. This Wiki page is not meant to be a definitive reference on how to run **nginx-proxy** and **acme-companion** with Docker Compose, as the number of possible setups is quite extensive and they can't be all covered.\n\n### Before your start\n\nBe sure to be familiar with both the [basic](./Basic-usage.md) and [advanced](./Advanced-usage.md) non compose setups, and Docker Compose usage.\n\nPlease read [getting container IDs](./Getting-containers-IDs.md) and be aware that the `--volumes-from method` is **only** available on compose file version 2.\n\nThe following examples are minimal, clean starting points using compose file version 2. Again they are not intended as a definitive reference.\n\nThe use of named containers and volume is not required but helps keeping everything clear and organized.\n\n### Two containers example\n\n```yaml\nservices:\n  nginx-proxy:\n    image: nginxproxy/nginx-proxy\n    container_name: nginx-proxy\n    ports:\n      - \"80:80\"\n      - \"443:443\"\n    volumes:\n      # The vhost and conf volumes are only required\n      # if you plan to obtain standalone certificates\n      # - vhost:/etc/nginx/vhost.d\n      # - conf:/etc/nginx/conf.d\n      - html:/usr/share/nginx/html\n      - certs:/etc/nginx/certs:ro\n      - /var/run/docker.sock:/tmp/docker.sock:ro\n\n  acme-companion:\n    image: nginxproxy/acme-companion\n    container_name: nginx-proxy-acme\n    environment:\n      - DEFAULT_EMAIL=mail@yourdomain.tld\n    volumes_from:\n      - nginx-proxy\n    volumes:\n      - certs:/etc/nginx/certs:rw\n      - acme:/etc/acme.sh\n      - /var/run/docker.sock:/var/run/docker.sock:ro\n\n#networks:\n#    default:\n#        name: nginx-proxy\n\nvolumes:\n  # vhost:\n  # conf:\n  html:\n  certs:\n  acme:\n```\n\n### Three containers example\n\n```yaml\nservices:\n  nginx-proxy:\n    image: nginx:alpine\n    container_name: nginx-proxy\n    ports:\n      - \"80:80\"\n      - \"443:443\"\n    volumes:\n      # The vhost volume is only required if you\n      # plan to obtain standalone certificates\n      # - vhost:/etc/nginx/vhost.d\n      - conf:/etc/nginx/conf.d\n      - html:/usr/share/nginx/html\n      - certs:/etc/nginx/certs:ro\n\n  docker-gen:\n    image: nginxproxy/docker-gen\n    container_name: nginx-proxy-gen\n    command: -notify-sighup nginx-proxy -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf\n    volumes_from:\n      - nginx-proxy\n    volumes:\n      - /path/to/nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro\n      - /var/run/docker.sock:/tmp/docker.sock:ro\n    labels:\n      - \"com.github.nginx-proxy.docker-gen\"\n\n  acme-companion:\n    image: nginxproxy/acme-companion\n    container_name: nginx-proxy-acme\n    environment:\n      - DEFAULT_EMAIL=mail@yourdomain.tld\n    volumes_from:\n      - nginx-proxy\n    volumes:\n      - certs:/etc/nginx/certs:rw\n      - acme:/etc/acme.sh\n      - /var/run/docker.sock:/var/run/docker.sock:ro\n\n#networks:\n#    default:\n#        name: nginx-proxy\n\nvolumes:\n  # vhost:\n  conf:\n  html:\n  certs:\n  acme:\n```\n\n**Note:** don't forget to replace `/path/to/nginx.tmpl` with the actual path to the [`nginx.tmpl`](https://raw.githubusercontent.com/nginx-proxy/nginx-proxy/main/nginx.tmpl) file you downloaded.\n\n### Other (external) examples\n\n**Warning:** some of those examples might be outdated and not working properly with version >= `2.0` of this project.\n\nIf you want other examples how to use this container with Docker Compose, look at:\n\n* [Nicolas Duchon's Examples](https://github.com/buchdag/letsencrypt-nginx-proxy-companion-compose) - with automated testing\n* [Evert Ramos's Examples](https://github.com/evertramos/docker-compose-letsencrypt-nginx-proxy-companion) - using docker-compose version '3'\n* [Karl Fathi's Examples](https://github.com/fatk/docker-letsencrypt-nginx-proxy-companion-examples)\n* [More examples from Karl](https://github.com/pixelfordinner/pixelcloud-docker-apps/tree/master/nginx-proxy)\n* [George Ilyes' Examples](https://github.com/gilyes/docker-nginx-letsencrypt-sample)\n* [Dmitry's simple docker-compose example](https://github.com/dmitrym0/simple-lets-encrypt-docker-compose-sample)\n* [Radek's docker-compose jenkins example](https://github.com/dataminelab/docker-jenkins-nginx-letsencrypt)\n"
  },
  {
    "path": "docs/Getting-containers-IDs.md",
    "content": "## Getting nginx-proxy/nginx/docker-gen containers IDs\n\nFor **acme-companion** to work properly, it needs to know the ID of the **nginx**/**nginx-proxy** container (in both [two](./Basic-usage.md) and [three](./Advanced-usage.md) containers setups), plus the ID of the **docker-gen** container in a [three container setup](./Advanced-usage.md).\n\nThere are three methods to inform the **acme-companion** container of the **nginx**/**nginx-proxy** container ID:\n\n* `label` method: add the label `com.github.nginx-proxy.nginx` to the **nginx**/**nginx-proxy** container.\n\n* `environment variable` method: assign a fixed name to the **nginx**/**nginx-proxy** container with `container_name:` and set the environment variable `NGINX_PROXY_CONTAINER` to this name on the **acme-companion** container.\n\n* `volumes_from` method. Using this method, the **acme-companion** container will get the **nginx**/**nginx-proxy** container ID from the volumes it got using the `volumes_from` option.\n\nAnd two methods to inform the **acme-companion** container of the **docker-gen** container ID:\n\n* `label` method: add the label `com.github.nginx-proxy.docker-gen` to the **docker-gen** container.\n\n* `environment variable` method: assign a fixed name to the **docker-gen** container with `container_name:` and set the environment variable `NGINX_DOCKER_GEN_CONTAINER` to this name on the **acme-companion** container.\n\nThe methods for each container are sorted by order of precedence, meaning that if you use both the label and the volumes_from method, the ID of the **nginx**/**nginx-proxy** container that will be used will be the one found using the label. **There is no point in using more than one method at a time for either the nginx/nginx-proxy or docker-gen container beside potentially confusing yourself**.\n\nThe advantage the `label` methods have over the `environment variable` (and `volumes_from`) methods is enabling the use of the **acme-companion** in environments where containers names are dynamic, like in Swarm Mode or in Docker Cloud. However if you intend to do so, as upstream **docker-gen** lacks the ability to identify containers from labels, you'll need both to either use the two containers setup or to replace nginx-proxy/docker-gen with a fork that has this ability like [herlderco/docker-gen](https://github.com/helderco/docker-gen). Be advised that for now, this works to a very limited extent [(everything has to be on the same node)](https://github.com/nginx-proxy/acme-companion/pull/231#issuecomment-330624331).\n\n#### Examples with three containers setups:\n\n`label` method.\n```\n$ docker run --detach \\\n    [...]\n    --label com.github.nginx-proxy.nginx \\\n    nginx\n\n$ docker run --detach \\\n    [...]\n    --label com.github.nginx-proxy.docker-gen \\\n    nginxproxy/docker-gen\n\n$ docker run --detach \\\n    [...]\n    nginxproxy/acme-companion\n```\n\n`environment variable` method\n```\n$ docker run --detach \\\n    [...]\n    --name unique-container-name \\\n    nginx\n\n$ docker run --detach \\\n    [...]\n    --name another-unique-container-name \\\n    nginxproxy/docker-gen\n\n$ docker run --detach \\\n    [...]\n    --env NGINX_PROXY_CONTAINER=unique-container-name \\\n    --env NGINX_DOCKER_GEN_CONTAINER=another-unique-container-name \\\n    nginxproxy/acme-companion\n```\n\n`volumes_from` (**nginx**) + `label` (**docker-gen**) method\n```\n$ docker run --detach \\\n    [...]\n    --name unique-container-name \\\n    nginx\n\n$ docker run --detach \\\n    [...]\n    --label com.github.nginx-proxy.docker-gen \\\n    nginxproxy/docker-gen\n\n$ docker run --detach \\\n    [...]\n    --volumes-from unique-container-name \\\n    nginxproxy/acme-companion\n```\n\n`volumes_from` (**nginx**) + `environment variable` (**docker-gen**) method\n```\n$ docker run --detach \\\n    [...]\n    --name unique-container-name \\\n    nginx\n\n$ docker run --detach \\\n    [...]\n    --name another-unique-container-name \\\n    nginxproxy/docker-gen\n\n$ docker run --detach \\\n    [...]\n    --volumes-from unique-container-name \\\n    --env NGINX_DOCKER_GEN_CONTAINER=another-unique-container-name \\\n    nginxproxy/acme-companion\n```\n"
  },
  {
    "path": "docs/Google-Trust-Services.md",
    "content": "## Google Trust Services\n\n[Google Trust Service](https://pki.goog/) is an ACME CA with generous default quota and high ubiquity. \n\nUsing Google Trust Services through an ACME client, like in this container, allows for unlimited 90 days and multi-domains (SAN) certificates.\n\n### Activation\n\nGoogle Trust Services support is activated when the `ACME_CA_URI` environment variable is set to the Google Trust Services ACME endpoint (`https://dv.acme-v02.api.pki.goog/directory`).\n\n### Account\n\nGoogle Trust Services requires the use of an externally bound account. First create a [Google Trust Services account](https://cloud.google.com/certificate-manager/docs/public-ca-tutorial#request-key-hmac):\n\n- provide the pre-generated [EAB credentials](https://tools.ietf.org/html/rfc8555#section-7.3.4) using the `ACME_EAB_KID` and `ACME_EAB_HMAC_KEY` environment variables.\n\nThese variables can be set on the proxied containers or directly on the **acme-companion** container.\n"
  },
  {
    "path": "docs/Hooks.md",
    "content": "## Pre-Hooks and Post-Hooks\n\nThe Pre- and Post-Hooks of [acme.sh](https://github.com/acmesh-official/acme.sh/) are available through the corresponding environment variables. This allows to trigger actions just before and after certificates are issued (see [acme.sh documentation](https://github.com/acmesh-official/acme.sh/wiki/Using-pre-hook-post-hook-renew-hook-reloadcmd)).\n\nIf you set `ACME_PRE_HOOK` and/or `ACME_POST_HOOK` on the **acme-companion** container, **the actions for all certificates will be the same**. If you want specific actions to be run for specific certificates, set the `ACME_PRE_HOOK` / `ACME_POST_HOOK` environment variable(s) on the proxied container(s) instead. Default (on the **acme-companion** container) and per-container `ACME_PRE_HOOK` / `ACME_POST_HOOK` environment variables aren't combined : if both default and per-container variables are set for a given proxied container, the per-container variables will take precedence over the default.\n\nIf you want to run the same default hooks for most containers but not for some of them, you can set the `ACME_PRE_HOOK` / `ACME_POST_HOOK` environment variables to the Bash noop operator (ie, `ACME_PRE_HOOK=:`) on those containers.\n\n#### Pre-Hook: `ACME_PRE_HOOK`\nThis command will be run before certificates are issued.\n\nFor example `echo 'start'` on the **acme-companion** container (setting a default Pre-Hook):\n```shell\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume acme:/etc/acme.sh \\\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\n    --env \"ACME_PRE_HOOK=echo 'start'\" \\\n    nginxproxy/acme-companion\n```\n\nAnd on a proxied container (setting a per-container Pre-Hook):\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=yourdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=yourdomain.tld\" \\\n    --env \"ACME_PRE_HOOK=echo 'start'\" \\\n    nginx\n```\n\n#### Post-Hook: `ACME_POST_HOOK`\nThis command will be run after certificates are issued.\n\nFor example `echo 'end'` on the **acme-companion** container (setting a default Post-Hook):\n```shell\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume acme:/etc/acme.sh \\\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\n    --env \"ACME_POST_HOOK=echo 'end'\" \\\n    nginxproxy/acme-companion\n```\n\nAnd on a proxied container (setting a per-container Post-Hook):\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=yourdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=yourdomain.tld\" \\\n    --env \"ACME_POST_HOOK=echo 'start'\" \\\n    nginx\n```\n\n#### Verification:\nIf you want to check wether the hook-command is delivered properly to [acme.sh](https://github.com/acmesh-official/acme.sh/), you should check `/etc/acme.sh/[EMAILADDRESS]/[DOMAIN]/[DOMAIN].conf`.\nThe variable `Le_PreHook` contains the Pre-Hook-Command base64 encoded.\nThe variable `Le_PostHook` contains the Post-Hook-Command base64 encoded.\n\n#### Limitations\n* The commands that can be used in the hooks are limited to the commands available inside the **acme-companion** container. `curl` and `wget` are available, therefore it is possible to communicate with tools outside the container via HTTP, allowing for complex actions to be implemented outside or in other containers.\n\n#### Use-cases\n* Changing some firewall rules just for the ACME authorization, so the ports 80 and/or 443 don't have to be publicly reachable at all time.\n* Certificate \"post processing\" / conversion to another format.\n* Monitoring.\n"
  },
  {
    "path": "docs/Invalid-authorizations.md",
    "content": "## Troubleshooting failing authorizations\n\nThe first two things to do in case of failing authorization are to run the **acme-companion** container with the environment variable `DEBUG=1` to enable the more detailed error messages, and to [request test certificates](./Let's-Encrypt-and-ACME.md#test-certificates) while troubleshooting the issue.\n\nCommon causes of of failing authorizations:\n\n#### port `80` or `443` on your host are closed / filtered from the outside, possibly because of a misconfigured firewall.\n\nCheck your host `80` and `443` ports **from the outside** (as in from a host having a different public IP) with `nmap` or a similar tool.\n\n#### your domain name does not resolve to your host IPv4 and/or IPv6.\n\nCheck that your domain name A (and AAAA, if present) records points to the correct adresses using `drill`, `dig` or `nslookup`.\n\n#### your domain name advertise an AAAA (IPv6) record, but your host or your host's docker isn't actually reachable over IPv6.\n\nCreate a test nginx container on your host and try to reach it over both IPv4 and IPv6.\n\n```bash\nyou@remotedockerhost$ docker run -d -p 80:80 nginx:alpine\n\nyou@localcomputer$ curl http://your.domain.tld\n<!DOCTYPE html>\n<html>\n<head>\n<title>Welcome to nginx!</title>\n[...]\n</html>\n\nyou@localcomputer$ curl -6 http://your.domain.tld\n<!DOCTYPE html>\n<html>\n<head>\n<title>Welcome to nginx!</title>\n[...]\n</html>\n```\n\nIf you are unsure of your host/hosts's docker IPv6 connectivity, drop the AAAA record from your domain name and wait for the modification to propagate.\n\n#### your domain name DNS provider answers incorrectly to CAA record requests.\n\nRead https://letsencrypt.org/docs/caa/ and test with https://unboundtest.com/\n\n#### the **nginx-proxy**/**nginx**/**docker-gen**/**acme-companion** containers were misconfigured.\n\nReview [basic usage](./Basic-usage.md) or [advanced usage](./Advanced-usage.md), plus the [nginx-proxy documentation](https://github.com/nginx-proxy/nginx-proxy).\n\nPay special attention to the fact that the volumes **MUST** be shared between the different containers.\n\n#### you forgot to set both `VIRTUAL_HOST` and `LETSENCRYPT_HOST` on the proxyed container.\n\nBoth are required. Every domain on `LETSENCRYPT_HOST`**must** be on `VIRTUAL_HOST`too.\n\n#### you are using an outdated version of either **acme-companion** or the nginx.tmpl file (if running a 3 containers setup)\n\nPull `nginxproxy/acme-companion:latest` again and get the latest [latest nginx.tmpl](https://raw.githubusercontent.com/nginx-proxy/nginx-proxy/main/nginx.tmpl).\n\n\n***\n\n\nWhen not in debug mode, the challenge files are automatically cleaned up **after** the authorization process, wether it succeeded or failed, so trying to `curl` them from the outside if you didn't enable debug mode won't yeld any result. If don't want to enable debug mode, you can however create a test file inside the same folder and use it to test the challenge files reachability from the outside (over both IPv4 and IPv6 if you want to use the latter):\n\n```\nyou@remotedockerhost$ docker exec your-le-container bash -c 'echo \"Hello world!\" > /usr/share/nginx/html/.well-known/acme-challenge/hello-world'\n\nyou@localcomputer$ curl http://yourdomain.tld/.well-known/acme-challenge/hello-world\nHello world!\nyou@localcomputer$ curl -6 http://yourdomain.tld/.well-known/acme-challenge/hello-world\nHello world!\n```\n\nIf you have issues with the [advanced setup](./Advanced-usage.md), fall back to the [basic setup](./Basic-usage.md). The advanced setup is not meant to be obligatory.\n"
  },
  {
    "path": "docs/Let's-Encrypt-and-ACME.md",
    "content": "## Let's Encrypt / ACME\n\n**NOTE on CAA**: Please ensure that your DNS provider answers correctly to CAA record requests. [If your DNS provider answer with an error, Let's Encrypt won't issue a certificate for your domain](https://letsencrypt.org/docs/caa/). Let's Encrypt do not require that you set a CAA record on your domain, just that your DNS provider answers correctly.\n\n**NOTE on IPv6**: If the domain or sub domain you want to issue certificate for has an AAAA record set, Let's Encrypt will favor challenge validation over IPv6. [There is an IPv6 to IPv4 fallback in place but Let's Encrypt can't guarantee it'll work in every possible case](https://github.com/letsencrypt/boulder/issues/2770#issuecomment-340489871), so bottom line is **if you are not sure of both your host and your host's Docker reachability over IPv6, do not advertise an AAAA record** or LE challenge validation might fail.\n\nAs described on [basic usage](./Basic-usage.md), the `LETSENCRYPT_HOST` environment variables needs to be declared in each to-be-proxied application containers for which you want to enable SSL and create certificate. It most likely needs to be the same as the `VIRTUAL_HOST` variable and must resolve to your host (which has to be publicly reachable).\n\nThe following environment variables are optional and parametrize the way the Let's Encrypt client works.\n\n### per proxyed container\n\n#### DNS-01 ACME challenge\n\nIn order to switch to the DNS-01 ACME challenge, set the `ACME_CHALLENGE` environment variable to `DNS-01` on your acme-companion container. This will also require you to set the `ACMESH_DNS_API_CONFIG` environment variable to a JSON or YAML string containing the configuration for the DNS provider you are using. Inside the JSON or YAML string, the `DNS_API` property is always required and should be set to the name of the [acme.sh DNS API](https://github.com/acmesh-official/acme.sh/tree/3.1.2/dnsapi) you want to use.\n\nThe other properties required will depend on the DNS provider you are using. For more information on the required properties for each DNS provider, please refer to the [acme.sh documentation](https://github.com/acmesh-official/acme.sh/wiki/dnsapi) (please keep in mind that nginxproxy/acme-companion is using a fixed version of acme.sh, so the documentation might include DNS providers that are not yet available in the version used by this image).\n\nBoth `ACME_CHALLENGE` and `ACMESH_DNS_API_CONFIG` environment variables can also be set on the proxied application container, in which case they will override the values set on the acme-companion container, if any.\n\nNot: if you do not plan on using the `HTTP-01` challenge at all, you won't need to share `/usr/share/nginx/html` between the **nginx-proxy** and **acme-companion** containers, and can remove this volume from both.\n\nExample using [Cloudflare DNS](https://github.com/acmesh-official/acme.sh/blob/master/dnsapi/dns_cf.sh):\n```console\ndocker run --detach \\\n    --name nginx-proxy-acme \\\n    --volume certs:/etc/nginx/certs \\\n    --volume acme:/etc/acme.sh \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --env \"DEFAULT_EMAIL=mail@yourdomain.tld\" \\\n    --env \"ACME_CHALLENGE=DNS-01\" \\\n    --env \"ACMESH_DNS_API_CONFIG={'DNS_API': 'dns_cf', 'CF_Key': 'yourCloudflareGlobalApiKey', 'CF_Email': 'yourCloudflareAccountEmail'}\" \\\n    nginxproxy/acme-companion\n```\n\nSame example on a Docker compose file:\n```yaml\nservices:\n  # nginx proxy container omitted\n    \n  acme:\n    image: nginxproxy/acme-companion\n    container_name: nginx-proxy-acme\n    volumes:\n      - certs:/etc/nginx/certs\n      - acme:/etc/acme.sh\n      - /var/run/docker.sock:/var/run/docker.sock:ro\n    environment:\n      DEFAULT_EMAIL: mail@yourdomain.tld\n      ACME_CHALLENGE: DNS-01\n      ACMESH_DNS_API_CONFIG: |-\n        DNS_API: dns_cf\n        CF_Key: yourCloudflareGlobalApiKey\n        CF_Email: yourCloudflareAccountEmail\n    \n    # app container omitted\n\nvolumes:\n  certs:\n  acme:\n```\n\nIf you experience issues with the DNS-01 ACME challenge, please try to get it working outside of the container before opening an issue. If you can't get it working outside of the container, please seek support on the [acme.sh repository](https://github.com/acmesh-official).\n\n#### Multi-domains certificates\n\nSpecify multiple hosts with a comma delimiter to create multi-domains ([SAN](https://www.digicert.com/subject-alternative-name.htm)) certificates (the first domain in the list will be the base domain).\n\nExample:\n\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=yourdomain.tld,www.yourdomain.tld,anotherdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=yourdomain.tld,www.yourdomain.tld,anotherdomain.tld\" \\\n    nginx\n```\n\nLet's Encrypt has a limit of [100 domains per certificate](https://letsencrypt.org/fr/docs/rate-limits/), while Buypass limit is [15 domains per certificate](https://www.buypass.com/ssl/products/go-ssl-campaign).\n\n#### Separate certificate for each domain\n\nThe example above will issue a single domain certificate for all the domains listed in the `LETSENCRYPT_HOST` environment variable. If you need to have a separate certificate for each of the domains, you can add set the `LETSENCRYPT_SINGLE_DOMAIN_CERTS` environment variable to `true`.\n\nExample:\n\n```shell\n$ docker run --detach \\\n    --name your-proxyed-app \\\n    --env \"VIRTUAL_HOST=yourdomain.tld,www.yourdomain.tld,anotherdomain.tld\" \\\n    --env \"LETSENCRYPT_HOST=yourdomain.tld,www.yourdomain.tld,anotherdomain.tld\" \\\n    --env \"LETSENCRYPT_SINGLE_DOMAIN_CERTS=true\" \\\n    nginx\n```\n\n#### Automatic certificate renewal\nEvery hour (3600 seconds) the certificates are checked and per default every certificate that have been issued at least [60 days](https://github.com/acmesh-official/acme.sh/blob/f2d350002e7c387fad9777a42cf9befe34996c35/acme.sh#L61) ago is renewed. For Let's Encrypt certificates, that mean they will be renewed 30 days before expiration.\n\n#### Contact address\n\nThe `LETSENCRYPT_EMAIL` environment variable must be a valid email and can be used to recover an account.\n\n#### Private key size\n\nThe `LETSENCRYPT_KEYSIZE` environment variable determines the type and size of the requested key. Supported values are `2048`, `3072` and `4096` for RSA keys, and `ec-256` or `ec-384` for elliptic curve keys. The default is RSA 4096.  \nTo change the global default set the `DEFAULT_KEY_SIZE` environment variable on the **acme-companion** container to one of the supported values specified above.\n\n#### OCSP stapling\n\nThe `ACME_OCSP` environment variable, when set to `true` on a proxied application container, will add the [OCSP Must-Staple extension](https://blog.apnic.net/2019/01/15/is-the-web-ready-for-ocsp-must-staple/) to the issued certificate. Please read about OCSP Must-Staple support in Nginx if you intend to use this feature (https://trac.nginx.org/nginx/ticket/812 and https://trac.nginx.org/nginx/ticket/1830)\n\n#### Test certificates\n\nThe `LETSENCRYPT_TEST` environment variable, when set to `true` on a proxied application container, will create a test certificates that don't have the [5 certs/week/domain limits](https://letsencrypt.org/docs/rate-limits/) and are signed by an untrusted intermediate (they won't be trusted by browsers).\n\nIf you want to do this globally for all containers, set `ACME_CA_URI` on the **acme-companion** container as described in [Container configuration](./Container-configuration.md).\n\n#### ACME CA URI\n\nThe `ACME_CA_URI` environment variable is used to set the ACME API endpoint from which the container's certificate(s) will be requested (defaults to ``https://acme-v02.api.letsencrypt.org/directory``).\n\n#### Preferred chain\n\nIf the ACME CA provides multiple cert chain, you can use the `ACME_PREFERRED_CHAIN` environment variable to select one. See [`acme.sh --preferred-chain` documentation](https://github.com/acmesh-official/acme.sh/wiki/Preferred-Chain) for more info.\n\n#### Container restart on cert renewal\n\nThe `LETSENCRYPT_RESTART_CONTAINER` environment variable, when set to `true` on an application container, will restart this container whenever the corresponding cert (`LETSENCRYPT_HOST`) is renewed. This is useful when certificates are directly used inside a container for other purposes than HTTPS (e.g. an FTPS server), to make sure those containers always use an up to date certificate.\n\n#### Pre-Hook and Post-Hook\n\nThe `ACME_PRE_HOOK` and `ACME_POST_HOOK` let you use the [`acme.sh` Pre- and Post-Hooks feature](https://github.com/acmesh-official/acme.sh/wiki/Using-pre-hook-post-hook-renew-hook-reloadcmd) to run commands respectively before and after the container's certificate has been issued. For more information see [Pre- and Post-Hook](./Hooks.md)\n\n\n### global (set on acme-companion container)\n\n#### Default contact address\n\nThe `DEFAULT_EMAIL` variable must be a valid email and, when set on the **acme-companion** container, will be used as a fallback when no email address is provided using proxyed container's `LETSENCRYPT_EMAIL` environment variables. It is highly recommended to set this variable to a valid email address that you own.\n\n#### Private key re-utilization\n\nThe `RENEW_PRIVATE_KEYS` environment variable, when set to `false` on the **acme-companion** container, will set `acme.sh` to reuse previously generated private key instead of generating a new one at renewal for all domains.\n\nReusing private keys can help if you intend to use [HPKP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning), but please note that HPKP has been deprecated by Google's Chrome and that it is therefore strongly discouraged to use it at all.\n\n#### ACME accounts handling\n\n- Use one `acme.sh` configuration directory (`--config-home`) per account email address.\n- Each `acme.sh` configuration directory can hold several accounts on different ACME service providers. But only one per service provider.\n- The `default` configuration directory holds the configuration for empty account email address.\n- When in testing mode (`LETSENCRYPT_TEST=true`):\n    1. The container will use the special purpose `staging` configuration directory.\n    1. The directory URI is forced to The Let's Encrypt v2 staging one (`ACME_CA_URI` is ignored)\n    2. The account email address is forced empty (`DEFAULT_EMAIL` and `LETSENCRYPT_EMAIL` are ignored)\n\n#### Self signed default certificate\n\nIf you want **acme-companio** to create a self signed certificate as default certificate for **nginx-proxy**, you can set the `CREATE_DEFAULT_CERTIFICATE` environment variable to `true`. This will generate a self signed cert / key pair to `/etc/nginx/certs/default.crt` and `/etc/nginx/certs/default.key`, with `acme-companion` as Common Name. Please note that no future support is planned for this feature and it might be removed in a future release.\n"
  },
  {
    "path": "docs/Persistent-data.md",
    "content": "## Persistent data\n\n### Named volumes (recommended)\n\nWhen you follow instructions from Basic usage or Advanced usage, Docker will automatically create **named volumes** for every `--volume` / `-v` argument passed. Named volume will make it easy for you to mount the same persisted data even if you delete then re-create the container:\n\n```shell\n$ docker run -d \\\n    --name nginx-proxy \\\n    -p 80:80 \\\n    -p 443:443 \\\n    -v certs:/etc/nginx/certs \\\n    -v html:/usr/share/nginx/html \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy\n\n$ docker volume ls\nDRIVER              VOLUME NAME\nlocal               certs\nlocal               html\n```\n\n### Anonymous volumes (not recommended)\n\nIf you don't prefix your volumes with a name, Docker will instead create **anonymous volumes** (volumes with a random name). Those volume persist after the container is deleted but aren't automatically re-mounted when you re-create the container. Their usage is **not recommended** as they don't provide any advantages over named volumes and make keeping tracks of what volume store which data way harder.\n\n```shell\n$ docker run -d \\\n    --name nginx-proxy \\\n    -p 80:80 \\\n    -p 443:443 \\\n    -v /etc/nginx/certs \\\n    -v /usr/share/nginx/html \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy\n\n$ docker volume ls\nDRIVER              VOLUME NAME\nlocal               287be3abd610e5566500d719ceb8b952952f12c9324ef02d05785d4ee9737ae9\nlocal               f260f71fefadcdfc311d285d69151f2312915174d3fb1fab89949ec5ec871a54\n```\n\n### Host volumes\n\nAlternatively, you might want to store the certificates on a local folder rather than letting Docker create and manage a volume for them. This is easily achieved by using a **host volume** (binding an absolute path on your host to the `/ect/nginx/certs` folder on your containers):\n\n`-v /path/to/certificates:/etc/nginx/certs`\n\nNo matter the type of volume you choose, if you set them on the nginx-proxy or nginx container and use `--volumes_from` on the others containers, they will automatically be mounted inside the container to the path your first defined.\n\n### Restraining other containers write permission\n\nIf you want to restrain the **nginx** and **docker-gen** processes to read only access on the certificates, you'll have to use different volume flags depending on the container.\n\nExample with named volumes:\n\n`-v certs:/etc/nginx/certs:ro` on the **nginx-proxy** or **nginx** + **docker-gen** container(s).\n\n`-v certs:/etc/nginx/certs:rw` on the **acme-companion** container.\n\n## Ownership & permissions of private and ACME account keys\n\nBy default, the **acme-companion** container will enforce the following ownership and permissions scheme on the files it creates and manage:\n\n```\n[drwxr-xr-x]  /etc/nginx/certs\n├── [-rw-r--r-- root root]  dhparam.pem\n├── [drwxr-xr-x root root]  domain.tld\n│   ├── [-rw-r--r-- root root]  cert.pem\n│   ├── [-rw-r--r-- root root]  chain.pem\n│   ├── [-rw-r--r-- root root]  fullchain.pem\n│   └── [-rw------- root root]  key.pem\n├── [lrwxrwxrwx root root]  domain.tld.chain.pem -> ./domain.tld/chain.pem\n├── [lrwxrwxrwx root root]  domain.tld.crt -> ./domain.tld/fullchain.pem\n├── [lrwxrwxrwx root root]  domain.tld.dhparam.pem -> ./dhparam.pem\n└── [lrwxrwxrwx root root]  domain.tld.key -> ./domain.tld/key.pem\n```\n\nThis behavior can be customized using the following environment variable on the **acme-companion** container:\n\n* `FILES_UID` - Set the user owning the files and folders managed by the container. The variable can be either a user name if this user exists inside the container or a user numeric ID. Default to `root` (user ID `0`).\n* `FILES_GID` - Set the group owning the files and folders managed by the container. The variable can be either a group name if this group exists inside the container or a group numeric ID. Default to the same value as `FILES_UID`.\n* `FILES_PERMS` - Set the permissions of the private keys. The variable must be a valid octal permission setting and defaults to `600`.\n* `FOLDERS_PERMS` - Set the permissions of the folders managed by the container. The variable must be a valid octal permission setting and defaults to `755`.\n\nFor example, `FILES_UID=1000`, `FILES_PERMS=644` and `FOLDERS_PERMS=700` will result in the following:\n\n```\n[drwxr-xr-x]  /etc/nginx/certs\n├── [-rw-r--r-- 1000 1000]  dhparam.pem\n├── [drwx------ 1000 1000]  domain.tld\n│   ├── [-rw-r--r-- 1000 1000]  cert.pem\n│   ├── [-rw-r--r-- 1000 1000]  chain.pem\n│   ├── [-rw-r--r-- 1000 1000]  fullchain.pem\n│   └── [-rw-r--r-- 1000 1000]  key.pem\n├── [lrwxrwxrwx 1000 1000]  domain.tld.chain.pem -> ./domain.tld/chain.pem\n├── [lrwxrwxrwx 1000 1000]  domain.tld.crt -> ./domain.tld/fullchain.pem\n├── [lrwxrwxrwx 1000 1000]  domain.tld.dhparam.pem -> ./dhparam.pem\n└── [lrwxrwxrwx 1000 1000]  domain.tld.key -> ./domain.tld/key.pem\n```\n"
  },
  {
    "path": "docs/README.md",
    "content": "#### Usage:\n\n[Basic (two containers).](./Basic-usage.md)\n\n[Advanced (three containers).](./Advanced-usage.md)\n\n[Getting containers IDs](./Getting-containers-IDs.md)\n\n[with Docker Compose](./Docker-Compose.md)\n\n[Container utilities](./Container-utilities.md)\n\n#### Additional configuration:\n\n[Let's Encrypt / ACME](./Let's-Encrypt-and-ACME.md)\n\n[Container configuration](./Container-configuration.md)\n\n[Google Trust Services](./Google-Trust-Services.md)\n\n[Persistent data](./Persistent-data.md)\n\n[Standalone certificates](./Standalone-certificates.md)\n\n[Zero SSL](./Zero-SSL.md)\n\n[Pre-Hooks and Post-Hooks](./Hooks.md)\n\n#### Troubleshooting:\n\n[Invalid / failing authorizations](./Invalid-authorizations.md)\n"
  },
  {
    "path": "docs/Standalone-certificates.md",
    "content": "## Standalone certificates\n\nYou can generate certificate that are not tied to containers environment variable by mounting a user configuration file inside the container at `/app/letsencrypt_user_data`. This feature also require sharing the `/etc/nginx/vhost.d` and `/etc/nginx/conf.d` folder between the **nginx-proxy** and **acme-companion** container (and the **docker-gen** container if you are running a [three container setup](./Advanced-usage.md)):\n\n```bash\n$ docker run --detach \\\n    --name nginx-proxy \\\n    --publish 80:80 \\\n    --publish 443:443 \\\n    --volume certs:/etc/nginx/certs \\\n    --volume vhost:/etc/nginx/vhost.d \\\n    --volume conf:/etc/nginx/conf.d \\\n    --volume html:/usr/share/nginx/html \\\n    --volume /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy\n```\n\n```bash\n$ docker run --detach \\\n    --name nginx-proxy-acme \\\n    --volumes-from nginx-proxy \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volume acme:/etc/acme.sh \\\n    --volume /path/to/your/config_file:/app/letsencrypt_user_data:ro \\\n    nginxproxy/acme-companion\n```\n\nThe user configuration file is a collection of bash variables and array, and follows the syntax of the `/app/letsencrypt_service_data` file that get created by **docker-gen**.\n\n### Required configuration parameters:\n\n`LETSENCRYPT_STANDALONE_CERTS` : a bash array containing identifier(s) for you standalone certificate(s). Each element in the array has to be unique. Those identifiers are internal to the container process and won't ever be visible to the outside world or appear on your certificate.\n\n`LETSENCRYPT_uniqueidentifier_HOST` : a bash array containing domain(s) that will be covered by the certificate corresponding to `uniqueidentifier`.\n\nEach identifier in `LETSENCRYPT_STANDALONE_CERTS` must have its own corresponding `LETSENCRYPT_uniqueidentifier_HOST` array, where the string `uniqueidentifier` has to be identical to that identifier. \n\n**Minimal example generating a single certificate for a single domain:**\n\n```bash\nLETSENCRYPT_STANDALONE_CERTS=('uniqueidentifier')\nLETSENCRYPT_uniqueidentifier_HOST=('yourdomain.tld')\n```\n\n**Example with multiple certificates and domains:**\n\n```bash\nLETSENCRYPT_STANDALONE_CERTS=('web' 'app' 'othersite')\nLETSENCRYPT_web_HOST=('yourdomain.tld' 'www.yourdomain.tld')\nLETSENCRYPT_app_HOST=('myapp.yourdomain.tld' 'myapp.yourotherdomain.tld' 'service.yourotherdomain.tld')\nLETSENCRYPT_othersite_HOST=('yetanotherdomain.tld')\n```\n\n**Example using DNS-01 verification:**\n\nIn this example: `web` and `app` generate a certificate using the global/default configuration. However `othersite` will perform it's certificate verification using a specific DNS-01 API configuration.\n\n```bash\nLETSENCRYPT_STANDALONE_CERTS=('web' 'app' 'othersite')\nLETSENCRYPT_web_HOST=('yourdomain.tld' 'www.yourdomain.tld')\nLETSENCRYPT_app_HOST=('myapp.yourdomain.tld' 'myapp.yourotherdomain.tld' 'service.yourotherdomain.tld')\nLETSENCRYPT_othersite_HOST=('yetanotherdomain.tld')\n\nACME_othersite_CHALLENGE=DNS-01\ndeclare -A ACMESH_othersite_DNS_API_CONFIG=(\n    ['DNS_API']='dns_cf'\n    ['CF_Token']='<CLOUDFLARE_TOKEN>'\n    ['CF_Account_ID']='<CLOUDFLARE_ACCOUNT_ID>'\n    ['CF_Zone_ID']='<CLOUDFLARE_ZONE_ID>'\n)\n```\n\n### Optional configuration parameters:\n\nSingle bash variables:\n\n`LETSENCRYPT_uniqueidentifier_EMAIL` : must be a valid email and will be used by Let's Encrypt to warn you of impeding certificate expiration (should the automated renewal fail).\n\n`LETSENCRYPT_uniqueidentifier_KEYSIZE` : determines the size of the requested private key. See [private key size](./Let's-Encrypt-and-ACME.md#private-key-size) for accepted values.\n\n`LETSENCRYPT_uniqueidentifier_TEST` : if set to true, the corresponding certificate will be a test certificates: it won't have the 5 certs/week/domain limits and will be signed by an untrusted intermediate (ie it won't be trusted by browsers).\n\nDNS-01 related variables:\n\n`ACME_uniqueidentifier_CHALLENGE`: Defaults to HTTP-01. In order to switch to the DNS-01 ACME challenge set it to `DNS-01`\n\n`ACMESH_uniqueidentifier_DNS_API_CONFIG`: Defaults to the values of DNS_API_CONFIG. However if you wish to specify a specific DNS-01 verification method on a particular standalone certificate. It must be defined as a bash associative array.\n\nExample\n```bash\ndeclare -A ACMESH_alt_DNS_API_CONFIG=(\n    ['DNS_API']='dns_cf'\n    ['CF_Token']='<CLOUDFLARE_TOKEN>'\n    ['CF_Account_ID']='<CLOUDFLARE_ACCOUNT_ID>'\n    ['CF_Zone_ID']='<CLOUDFLARE_ZONE_ID>'\n)\n```\n\n### Picking up changes to letsencrypt_user_data\n\nThe container does not actively watch the `/app/letsencrypt_user_data` file for changes.\n\nChanges will either be picked up every hour when the service loop execute again, or by using `docker exec your-le-container-name-or-id /app/signal_le_service` to manually trigger the service loop execution.\n\n### Proxying to something else than a Docker container\n\nPlease see the [**nginx-proxy** documentation](https://github.com/nginx-proxy/nginx-proxy#proxy-wide).\n\nNo support will be provided on the **acme-companion** repo for proxying related issues or questions.\n"
  },
  {
    "path": "docs/Zero-SSL.md",
    "content": "## Zero SSL\n\n[Zero SSL](https://zerossl.com/) is an ACME CA that offer some advantages over Let's Encrypt:\n- no staging endpoint and [no rate limiting on the production endpoint](https://zerossl.com/features/acme/).\n- web based [management console](https://zerossl.com/features/console/) to keep track of your SSL certificates.\n\nUsing Zero SSL through an ACME client, like in this container, allows for unlimited 90 days and multi-domains (SAN) certificates.\n\n### Activation\n\nThe Zero SSL support is activated when the `ACME_CA_URI` environment variable is set to the Zero SSL ACME endpoint (`https://acme.zerossl.com/v2/DV90`).\n\n### Account\n\nUnlike Let's Encrypt, Zero SSL requires the use of an email bound account. If you already created a Zero SSL account, you can either:\n\n- provide pre-generated [EAB credentials](https://tools.ietf.org/html/rfc8555#section-7.3.4) using the `ACME_EAB_KID` and `ACME_EAB_HMAC_KEY` environment variables.\n- provide your ZeroSSL API key using the `ZEROSSL_API_KEY` environment variable.\n\nThese variables can be set on the proxied containers or directly on the **acme-companion** container.\n\nIf you don't have a ZeroSSL account, you can let **acme-companion** create a Zero SSL account with the address provided in the `ACME_EMAIL` or `DEFAULT_EMAIL` environment variable. Note that the address that will be used must be a valid email address that you actually own.\n"
  },
  {
    "path": "install_acme.sh",
    "content": "#!/bin/bash\n\nset -e\n\n# Install git (required to fetch acme.sh)\napk --no-cache --virtual .acmesh-deps add git\n\n# Get acme.sh ACME client source\nmkdir /src\ngit -C /src clone https://github.com/acmesh-official/acme.sh.git\ncd /src/acme.sh\nif [[ \"$ACMESH_VERSION\" != \"master\" ]]; then\n  git -c advice.detachedHead=false checkout \"$ACMESH_VERSION\"\nfi\n\n# Install acme.sh in /app\n./acme.sh --install \\\n  --nocron \\\n  --auto-upgrade 0 \\\n  --home /app \\\n  --config-home /etc/acme.sh/default\n\n# Make house cleaning\ncd /\nrm -rf /src\napk del .acmesh-deps\n"
  },
  {
    "path": "test/README.md",
    "content": "### acme-companion test suite\n\nThe test suite can be run locally on a Linux or macOS host.\n\nTo prepare the test setup:\n\n```bash\ngit clone https://github.com/nginx-proxy/acme-companion.git\ncd acme-companion\ntest/setup/setup-local.sh --setup\n```\n\nThen build the docker image and run the tests:\n\n```bash\ndocker build -t nginxproxy/acme-companion .\ntest/run.sh nginxproxy/acme-companion\n```\n\nYou can limit the test run to specific test(s) with the `-t` flag:\n\n```bash\ntest/run.sh -t docker_api nginxproxy/acme-companion\n```\n\nWhen running the test suite, the standard output of each individual test is captured and compared to its expected-std-out.txt file. When developing or modifying a test, you can use the `-d` flag to disable the standard output capture by the test suite.\n\n```bash\ntest/run.sh -d nginxproxy/acme-companion\n```\n\nTo remove the test setup:\n\n```bash\ntest/setup/setup-local.sh --teardown\n```\n"
  },
  {
    "path": "test/config.sh",
    "content": "#!/bin/bash\nset -e\n\nglobalTests+=(\n\tdocker_api\n\tdocker_api_legacy\n\tlocation_config\n\tcerts_single\n\tcerts_san\n\tcerts_single_domain\n\tcerts_standalone\n\tforce_renew\n\tacme_accounts\n\tprivate_keys\n\tcontainer_restart\n\tpermissions_default\n\tpermissions_custom\n\tsymlinks\n\tacme_hooks\n\tcerts_default_renew\n\tocsp_must_staple\n)\n\n# The acme_eab test requires Pebble with a specific configuration\nif [[ \"$ACME_CA\" == 'pebble' && \"$PEBBLE_CONFIG\" == 'pebble-config-eab.json' ]]; then\n\tglobalTests+=(\n\t\tacme_eab\n\t)\nfi\n"
  },
  {
    "path": "test/github_actions/containers-logs.sh",
    "content": "#!/bin/bash\n\nbold_echo() {\n  echo -e \"\\033[33;1m$1\\033[0m\"\n}\n\nif [[ -f \"$GITHUB_WORKSPACE/test/github_actions/failed_tests.txt\" ]]; then\n  mapfile -t containers < \"$GITHUB_WORKSPACE/test/github_actions/failed_tests.txt\"\nfi\n\ncontainers+=(\"$NGINX_CONTAINER_NAME\")\n[[ $SETUP = \"3containers\" ]] && containers+=(\"$DOCKER_GEN_CONTAINER_NAME\")\n[[ $ACME_CA = \"boulder\" ]] && containers+=(boulder)\n[[ $ACME_CA = \"pebble\" ]] && containers+=(pebble challtestserv)\n\nfor container in \"${containers[@]}\"; do\n  bold_echo \"Docker container output for $container\"\n  docker logs \"$container\"\n  docker inspect \"$container\"\n  if [[ \"$container\" == \"acme_accounts\" ]]; then\n    bold_echo \"Docker container output for ${container}_default\"\n    docker logs \"${container}_default\"\n    docker inspect \"${container}_default\"\n  fi\ndone\n"
  },
  {
    "path": "test/run.sh",
    "content": "#!/usr/bin/env bash\n#shellcheck disable=SC2068,SC2206\n\n# This file is adapted from the Docker official images test suite\n# under Apache 2.0 License and as such includes of copy of the license\n# https://github.com/docker-library/official-images/tree/master/test\n#\n#                               Apache License\n#                         Version 2.0, January 2004\n#                      http://www.apache.org/licenses/\n#\n# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n#\n# 1. Definitions.\n#\n#    \"License\" shall mean the terms and conditions for use, reproduction,\n#    and distribution as defined by Sections 1 through 9 of this document.\n#\n#    \"Licensor\" shall mean the copyright owner or entity authorized by\n#    the copyright owner that is granting the License.\n#\n#    \"Legal Entity\" shall mean the union of the acting entity and all\n#    other entities that control, are controlled by, or are under common\n#    control with that entity. For the purposes of this definition,\n#    \"control\" means (i) the power, direct or indirect, to cause the\n#    direction or management of such entity, whether by contract or\n#    otherwise, or (ii) ownership of fifty percent (50%) or more of the\n#    outstanding shares, or (iii) beneficial ownership of such entity.\n#\n#    \"You\" (or \"Your\") shall mean an individual or Legal Entity\n#    exercising permissions granted by this License.\n#\n#    \"Source\" form shall mean the preferred form for making modifications,\n#    including but not limited to software source code, documentation\n#    source, and configuration files.\n#\n#    \"Object\" form shall mean any form resulting from mechanical\n#    transformation or translation of a Source form, including but\n#    not limited to compiled object code, generated documentation,\n#    and conversions to other media types.\n#\n#    \"Work\" shall mean the work of authorship, whether in Source or\n#    Object form, made available under the License, as indicated by a\n#    copyright notice that is included in or attached to the work\n#    (an example is provided in the Appendix below).\n#\n#    \"Derivative Works\" shall mean any work, whether in Source or Object\n#    form, that is based on (or derived from) the Work and for which the\n#    editorial revisions, annotations, elaborations, or other modifications\n#    represent, as a whole, an original work of authorship. For the purposes\n#    of this License, Derivative Works shall not include works that remain\n#    separable from, or merely link (or bind by name) to the interfaces of,\n#    the Work and Derivative Works thereof.\n#\n#    \"Contribution\" shall mean any work of authorship, including\n#    the original version of the Work and any modifications or additions\n#    to that Work or Derivative Works thereof, that is intentionally\n#    submitted to Licensor for inclusion in the Work by the copyright owner\n#    or by an individual or Legal Entity authorized to submit on behalf of\n#    the copyright owner. For the purposes of this definition, \"submitted\"\n#    means any form of electronic, verbal, or written communication sent\n#    to the Licensor or its representatives, including but not limited to\n#    communication on electronic mailing lists, source code control systems,\n#    and issue tracking systems that are managed by, or on behalf of, the\n#    Licensor for the purpose of discussing and improving the Work, but\n#    excluding communication that is conspicuously marked or otherwise\n#    designated in writing by the copyright owner as \"Not a Contribution.\"\n#\n#    \"Contributor\" shall mean Licensor and any individual or Legal Entity\n#    on behalf of whom a Contribution has been received by Licensor and\n#    subsequently incorporated within the Work.\n#\n# 2. Grant of Copyright License. Subject to the terms and conditions of\n#    this License, each Contributor hereby grants to You a perpetual,\n#    worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n#    copyright license to reproduce, prepare Derivative Works of,\n#    publicly display, publicly perform, sublicense, and distribute the\n#    Work and such Derivative Works in Source or Object form.\n#\n# 3. Grant of Patent License. Subject to the terms and conditions of\n#    this License, each Contributor hereby grants to You a perpetual,\n#    worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n#    (except as stated in this section) patent license to make, have made,\n#    use, offer to sell, sell, import, and otherwise transfer the Work,\n#    where such license applies only to those patent claims licensable\n#    by such Contributor that are necessarily infringed by their\n#    Contribution(s) alone or by combination of their Contribution(s)\n#    with the Work to which such Contribution(s) was submitted. If You\n#    institute patent litigation against any entity (including a\n#    cross-claim or counterclaim in a lawsuit) alleging that the Work\n#    or a Contribution incorporated within the Work constitutes direct\n#    or contributory patent infringement, then any patent licenses\n#    granted to You under this License for that Work shall terminate\n#    as of the date such litigation is filed.\n#\n# 4. Redistribution. You may reproduce and distribute copies of the\n#    Work or Derivative Works thereof in any medium, with or without\n#    modifications, and in Source or Object form, provided that You\n#    meet the following conditions:\n#\n#    (a) You must give any other recipients of the Work or\n#        Derivative Works a copy of this License; and\n#\n#    (b) You must cause any modified files to carry prominent notices\n#        stating that You changed the files; and\n#\n#    (c) You must retain, in the Source form of any Derivative Works\n#        that You distribute, all copyright, patent, trademark, and\n#        attribution notices from the Source form of the Work,\n#        excluding those notices that do not pertain to any part of\n#        the Derivative Works; and\n#\n#    (d) If the Work includes a \"NOTICE\" text file as part of its\n#        distribution, then any Derivative Works that You distribute must\n#        include a readable copy of the attribution notices contained\n#        within such NOTICE file, excluding those notices that do not\n#        pertain to any part of the Derivative Works, in at least one\n#        of the following places: within a NOTICE text file distributed\n#        as part of the Derivative Works; within the Source form or\n#        documentation, if provided along with the Derivative Works; or,\n#        within a display generated by the Derivative Works, if and\n#        wherever such third-party notices normally appear. The contents\n#        of the NOTICE file are for informational purposes only and\n#        do not modify the License. You may add Your own attribution\n#        notices within Derivative Works that You distribute, alongside\n#        or as an addendum to the NOTICE text from the Work, provided\n#        that such additional attribution notices cannot be construed\n#        as modifying the License.\n#\n#    You may add Your own copyright statement to Your modifications and\n#    may provide additional or different license terms and conditions\n#    for use, reproduction, or distribution of Your modifications, or\n#    for any such Derivative Works as a whole, provided Your use,\n#    reproduction, and distribution of the Work otherwise complies with\n#    the conditions stated in this License.\n#\n# 5. Submission of Contributions. Unless You explicitly state otherwise,\n#    any Contribution intentionally submitted for inclusion in the Work\n#    by You to the Licensor shall be under the terms and conditions of\n#    this License, without any additional terms or conditions.\n#    Notwithstanding the above, nothing herein shall supersede or modify\n#    the terms of any separate license agreement you may have executed\n#    with Licensor regarding such Contributions.\n#\n# 6. Trademarks. This License does not grant permission to use the trade\n#    names, trademarks, service marks, or product names of the Licensor,\n#    except as required for reasonable and customary use in describing the\n#    origin of the Work and reproducing the content of the NOTICE file.\n#\n# 7. Disclaimer of Warranty. Unless required by applicable law or\n#    agreed to in writing, Licensor provides the Work (and each\n#    Contributor provides its Contributions) on an \"AS IS\" BASIS,\n#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n#    implied, including, without limitation, any warranties or conditions\n#    of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n#    PARTICULAR PURPOSE. You are solely responsible for determining the\n#    appropriateness of using or redistributing the Work and assume any\n#    risks associated with Your exercise of permissions under this License.\n#\n# 8. Limitation of Liability. In no event and under no legal theory,\n#    whether in tort (including negligence), contract, or otherwise,\n#    unless required by applicable law (such as deliberate and grossly\n#    negligent acts) or agreed to in writing, shall any Contributor be\n#    liable to You for damages, including any direct, indirect, special,\n#    incidental, or consequential damages of any character arising as a\n#    result of this License or out of the use or inability to use the\n#    Work (including but not limited to damages for loss of goodwill,\n#    work stoppage, computer failure or malfunction, or any and all\n#    other commercial damages or losses), even if such Contributor\n#    has been advised of the possibility of such damages.\n#\n# 9. Accepting Warranty or Additional Liability. While redistributing\n#    the Work or Derivative Works thereof, You may choose to offer,\n#    and charge a fee for, acceptance of support, warranty, indemnity,\n#    or other liability obligations and/or rights consistent with this\n#    License. However, in accepting such obligations, You may act only\n#    on Your own behalf and on Your sole responsibility, not on behalf\n#    of any other Contributor, and only if You agree to indemnify,\n#    defend, and hold each Contributor harmless for any liability\n#    incurred by, or claims asserted against, such Contributor by reason\n#    of your accepting any such warranty or additional liability.\n#\n# END OF TERMS AND CONDITIONS\n#\n# Copyright 2014 Docker, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n## Next twelve lines were added by nginxproxy/acme-companion\ndir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nself=\"$(basename \"$0\")\"\nfailed_tests=()\n\nif [[ -z $GITHUB_ACTIONS ]] && [[ -f \"$dir/local_test_env.sh\" ]]; then\n\t# shellcheck source=/dev/null\n\tsource \"$dir/local_test_env.sh\"\nfi\n\n# shellcheck source=./tests/test-functions.sh\nsource \"$dir/tests/test-functions.sh\"\n## End of additional code\n\nusage() {\n\tcat <<EOUSAGE\n\nusage: $self [-t test ...] image:tag [...]\n   ie: $self debian:stretch\n       $self -t utc python:3\n       $self -t utc python:3 -t python-hy\n\nThis script processes the specified Docker images to test their running\nenvironments.\nEOUSAGE\n}\n\n# arg handling\n## Next nine lines were added or modified by nginxproxy/acme-companion\ncase \"$(uname)\" in\n\tLinux)\n\topts=\"$(getopt -o 'hdkt:c:?' --long 'dry-run,help,test:,config:,keep-namespace' -- \"$@\" || { usage >&2 && false; })\"\n\t;;\n\n\tDarwin)\n\topts=\"$(getopt hdkt:c:? \"$@\" || { usage >&2 && false; })\"\n\t;;\nesac\n## End of additional or modified code\neval set -- \"$opts\"\n\ndeclare -A argTests=()\ndeclare -a configs=()\ndryRun=\nkeepNamespace=\nwhile true; do\n\tflag=$1\n\tshift\n\tcase \"$flag\" in\n\t\t## Next line was modified by nginxproxy/acme-companion\n\t\t--dry-run|-d) dryRun=1 && export DRY_RUN=1 ;;\n\t\t--help|-h|'-?') usage && exit 0 ;;\n\t\t--test|-t) argTests[\"$1\"]=1 && shift ;;\n\t\t--config|-c) configs+=(\"$(readlink -f \"$1\")\") && shift ;;\n\t\t## Next line was modified by nginxproxy/acme-companion\n\t\t--keep-namespace|-k) keepNamespace=1 ;;\n\t\t--) break ;;\n\t\t*)\n\t\t\t{\n\t\t\t\techo \"error: unknown flag: $flag\"\n\t\t\t\tusage\n\t\t\t} >&2\n\t\t\texit 1\n\t\t\t;;\n\tesac\ndone\n\nif [ $# -eq 0 ]; then\n\tusage >&2\n\texit 1\nfi\n\n# declare configuration variables\ndeclare -a globalTests=()\ndeclare -A testAlias=()\ndeclare -A imageTests=()\ndeclare -A globalExcludeTests=()\ndeclare -A explicitTests=()\n\n# if there are no user-specified configs, use the default config\nif [ ${#configs} -eq 0 ]; then\n\tconfigs+=(\"$dir/config.sh\")\nfi\n\n# load the configs\ndeclare -A testPaths=()\nfor conf in \"${configs[@]}\"; do\n\t## Next two line were modified by nginxproxy/acme-companion\n  # shellcheck source=./config.sh\n\tsource \"$conf\"\n\t## End of modifications\n\n\t# Determine the full path to any newly-declared tests\n\tconfDir=\"$(dirname \"$conf\")\"\n\n\tfor testName in ${globalTests[@]} ${imageTests[@]}; do\n\t\t[ \"${testPaths[$testName]}\" ] && continue\n\n\t\tif [ -d \"$confDir/tests/$testName\" ]; then\n\t\t\t# Test directory found relative to the conf file\n\t\t\ttestPaths[$testName]=\"$confDir/tests/$testName\"\n\t\telif [ -d \"$dir/tests/$testName\" ]; then\n\t\t\t# Test directory found in the main tests/ directory\n\t\t\ttestPaths[$testName]=\"$dir/tests/$testName\"\n\t\tfi\n\tdone\ndone\n\ndidFail=\nfor dockerImage in \"$@\"; do\n\techo \"testing $dockerImage\"\n\n\tif ! docker inspect \"$dockerImage\" &> /dev/null; then\n\t\techo $'\\timage does not exist!'\n\t\tdidFail=1\n\t\tcontinue\n\tfi\n\n\trepo=\"${dockerImage%:*}\"\n\ttagVar=\"${dockerImage#*:}\"\n\t#version=\"${tagVar%-*}\"\n\tvariant=\"${tagVar##*-}\"\n\n\t## Irrelevant code was removed here by nginxproxy/acme-companion\n\n\ttestRepo=\"$repo\"\n\tif [ -z \"$keepNamespace\" ]; then\n\t\ttestRepo=\"${testRepo##*/}\"\n\tfi\n\t[ -z \"${testAlias[$repo]}\" ] || testRepo=\"${testAlias[$repo]}\"\n\n\texplicitVariant=\n\t## Next four lines were modified by nginxproxy/acme-companion\n\tif [ \"${explicitTests[:$variant]}\" ] \\\n\t|| [ \"${explicitTests[$repo:$variant]}\" ] \\\n\t|| [ \"${explicitTests[$testRepo:$variant]}\" ]\n\tthen\n\t## End of modified code\n\t\texplicitVariant=1\n\tfi\n\n\ttestCandidates=()\n\tif [ -z \"$explicitVariant\" ]; then\n\t\ttestCandidates+=( \"${globalTests[@]}\" )\n\tfi\n\ttestCandidates+=(\n\t\t${imageTests[:$variant]}\n\t)\n\tif [ -z \"$explicitVariant\" ]; then\n\t\ttestCandidates+=(\n\t\t\t${imageTests[$testRepo]}\n\t\t)\n\tfi\n\ttestCandidates+=(\n\t\t${imageTests[$testRepo:$variant]}\n\t)\n\tif [ \"$testRepo\" != \"$repo\" ]; then\n\t\tif [ -z \"$explicitVariant\" ]; then\n\t\t\ttestCandidates+=(\n\t\t\t\t${imageTests[$repo]}\n\t\t\t)\n\t\tfi\n\t\ttestCandidates+=(\n\t\t\t${imageTests[$repo:$variant]}\n\t\t)\n\tfi\n\n\ttests=()\n\tfor t in \"${testCandidates[@]}\"; do\n\t\t## Next line was modified by nginxproxy/acme-companion\n\t\tif [ ${#argTests[@]} -gt 0 ] && [ -z \"${argTests[$t]}\" ]; then\n\t\t## End of modified code\n\t\t\t# skipping due to -t\n\t\t\tcontinue\n\t\tfi\n\n\t\t## Next seven lines were modified by nginxproxy/acme-companion\n\t\tif [ -n \"${globalExcludeTests[${testRepo}_$t]}\" ] \\\n\t\t|| [ -n \"${globalExcludeTests[${testRepo}:${variant}_$t]}\" ] \\\n\t\t|| [ -n \"${globalExcludeTests[:${variant}_$t]}\" ] \\\n\t\t|| [ -n \"${globalExcludeTests[${repo}_$t]}\" ] \\\n\t\t|| [ -n \"${globalExcludeTests[${repo}:${variant}_$t]}\" ] \\\n\t\t|| [ -n \"${globalExcludeTests[:${variant}_$t]}\" ]\n\t\tthen\n\t\t## End of modified code\n\t\t\t# skipping due to exclude\n\t\t\tcontinue\n\t\tfi\n\n\t\ttests+=( \"$t\" )\n\tdone\n\n\tcurrentTest=0\n\ttotalTest=\"${#tests[@]}\"\n\tfor t in \"${tests[@]}\"; do\n\t\t(( currentTest+=1 ))\n\t\techo -ne \"\\t'$t' [$currentTest/$totalTest]...\"\n\n\t\t# run test against dockerImage here\n\t\t# find the script for the test\n\t\tscriptDir=\"${testPaths[$t]}\"\n\t\tif [ -d \"$scriptDir\" ]; then\n\t\t\tscript=\"$scriptDir/run.sh\"\n\t\t\t## Next nine lines were modified or added by nginxproxy/acme-companion\n\t\t\tif [ -x \"$script\" ] && [ ! -d \"$script\" ]; then\n\t\t\t\tif [ $dryRun ]; then\n\t\t\t\t\tif \"$script\" \"$dockerImage\"; then\n\t\t\t\t\t\techo 'passed'\n\t\t\t\t\telse\n\t\t\t\t\t\techo 'failed'\n\t\t\t\t\t\tdidFail=1\n\t\t\t\t\tfi\n\t\t\t\telse\n\t\t\t\t## End of modified / additional code\n\t\t\t\t\tif output=\"$(\"$script\" \"$dockerImage\")\"; then\n\t\t\t\t\t\tif [ -f \"$scriptDir/expected-std-out.txt\" ] && ! d=\"$(echo \"$output\" | diff -u \"$scriptDir/expected-std-out.txt\" - 2>/dev/null)\"; then\n\t\t\t\t\t\t\techo 'failed; unexpected output:'\n\t\t\t\t\t\t\techo \"$d\"\n\t\t\t\t\t\t\t## Next line was added by nginxproxy/acme-companion\n\t\t\t\t\t\t\tfailed_tests+=(\"$(basename \"$scriptDir\")\")\n\t\t\t\t\t\t\t## End of additional code\n\t\t\t\t\t\t\tdidFail=1\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\techo 'passed'\n\t\t\t\t\t\tfi\n\t\t\t\t\telse\n\t\t\t\t\t\techo 'failed'\n\t\t\t\t\t\t## Next line was added by nginxproxy/acme-companion\n\t\t\t\t\t\tfailed_tests+=(\"$(basename \"$scriptDir\")\")\n\t\t\t\t\t\t## End of additional code\n\t\t\t\t\t\tdidFail=1\n\t\t\t\t\tfi\n\t\t\t\tfi\n\t\t\telse\n\t\t\t\techo \"skipping\"\n\t\t\t\techo >&2 \"error: $script missing, not executable or is a directory\"\n\t\t\t\tdidFail=1\n\t\t\t\tcontinue\n\t\t\tfi\n\t\telse\n\t\t\techo \"skipping\"\n\t\t\techo >&2 \"error: unable to locate test '$t'\"\n\t\t\tdidFail=1\n\t\t\tcontinue\n\t\tfi\n\tdone\ndone\n\nif [ \"$didFail\" ]; then\n\t## Next five lines were added by nginxproxy/acme-companion\n\tif [[ $GITHUB_ACTIONS == 'true' ]]; then\n\t\tfor test in \"${failed_tests[@]}\"; do\n\t\t\techo \"$test\" >> \"$dir/github_actions/failed_tests.txt\"\n\t\tdone\n\tfi\n\t## End of additional code\n\texit 1\nfi\n"
  },
  {
    "path": "test/setup/pebble/compose.yaml",
    "content": "services:\n  pebble:\n    image: \"ghcr.io/letsencrypt/pebble:${PEBBLE_VERSION}\"\n    container_name: pebble\n    volumes:\n      - \"./${PEBBLE_CONFIG}:/test/config/pebble-config.json\"\n    environment:\n      - PEBBLE_VA_NOSLEEP=1\n    command: -config /test/config/pebble-config.json -dnsserver 10.30.50.3:8053\n    ports:\n      - 14000:14000 # HTTPS ACME API\n      - 15000:15000 # HTTPS Management API\n    networks:\n      acme_net:\n        ipv4_address: 10.30.50.2\n\n  challtestsrv:\n    image: \"ghcr.io/letsencrypt/pebble-challtestsrv:${PEBBLE_VERSION}\"\n    container_name: challtestserv\n    command: -defaultIPv6 \"\" -defaultIPv4 10.30.50.3\n    ports:\n      - 8055:8055 # HTTP Management API\n    networks:\n      acme_net:\n        ipv4_address: 10.30.50.3\n\nnetworks:\n  acme_net:\n    name: acme_net\n    driver: bridge\n    ipam:\n      driver: default\n      config:\n        - subnet: 10.30.50.0/24\n"
  },
  {
    "path": "test/setup/pebble/pebble-config-eab.json",
    "content": "{\n  \"pebble\": {\n    \"listenAddress\": \"0.0.0.0:14000\",\n    \"managementListenAddress\": \"0.0.0.0:15000\",\n    \"certificate\": \"test/certs/localhost/cert.pem\",\n    \"privateKey\": \"test/certs/localhost/key.pem\",\n    \"httpPort\": 80,\n    \"tlsPort\": 443,\n    \"ocspResponderURL\": \"\",\n    \"externalAccountBindingRequired\": true,\n    \"externalAccountMACKeys\": {\n      \"kid-1\": \"zWNDZM6eQGHWpSRTPal5eIUYFTu7EajVIoguysqZ9wG44nMEtx3MUAsUDkMTQ12W\",\n      \"kid-2\": \"b10lLJs8l1GPIzsLP0s6pMt8O0XVGnfTaCeROxQM0BIt2XrJMDHJZBM5NuQmQJQH\"\n    },\n    \"retryAfter\": {\n      \"authz\": 3,\n      \"order\": 5\n    },\n    \"certificateValidityPeriod\": 157766400\n  }\n}\n"
  },
  {
    "path": "test/setup/pebble/pebble-config.json",
    "content": "{\n  \"pebble\": {\n    \"listenAddress\": \"0.0.0.0:14000\",\n    \"managementListenAddress\": \"0.0.0.0:15000\",\n    \"certificate\": \"test/certs/localhost/cert.pem\",\n    \"privateKey\": \"test/certs/localhost/key.pem\",\n    \"httpPort\": 80,\n    \"tlsPort\": 443,\n    \"ocspResponderURL\": \"\",\n    \"externalAccountBindingRequired\": false,\n    \"retryAfter\": {\n      \"authz\": 3,\n      \"order\": 5\n    },\n    \"certificateValidityPeriod\": 157766400\n  }\n}\n"
  },
  {
    "path": "test/setup/pebble/setup-pebble.sh",
    "content": "#!/bin/bash\n\nset -e\n\nsetup_pebble() {\n    curl --silent --show-error https://raw.githubusercontent.com/letsencrypt/pebble/refs/tags/v2.10.0/test/certs/pebble.minica.pem > \"${GITHUB_WORKSPACE}/pebble.minica.pem\"\n    cat \"${GITHUB_WORKSPACE}/pebble.minica.pem\"\n    docker compose --file \"${GITHUB_WORKSPACE}/test/setup/pebble/compose.yaml\" up --detach\n}\n\nwait_for_pebble() {\n    for endpoint in 'https://pebble:14000/dir' 'http://pebble-challtestsrv:8055'; do\n        while ! curl --cacert \"${GITHUB_WORKSPACE}/pebble.minica.pem\" \"$endpoint\" >/dev/null 2>&1; do\n            if [ $((i * 5)) -gt $((5 * 60)) ]; then\n                echo \"$endpoint was not available under 5 minutes, timing out.\"\n                exit 1\n            fi\n            i=$((i + 1))\n            sleep 5\n        done\n    done\n}\n\nsetup_pebble_challtestserv() {\n    curl --silent --show-error --data '{\"ip\":\"10.30.50.1\"}' http://pebble-challtestsrv:8055/set-default-ipv4\n    curl --silent --show-error --data '{\"ip\":\"\"}' http://pebble-challtestsrv:8055/set-default-ipv6\n    curl --silent --show-error --data '{\"host\":\"lim.it\", \"addresses\":[\"10.0.0.0\"]}' http://pebble-challtestsrv:8055/add-a\n}\n\nsetup_pebble\nwait_for_pebble\nsetup_pebble_challtestserv\ndocker compose --file \"${GITHUB_WORKSPACE}/test/setup/pebble/compose.yaml\" logs\n"
  },
  {
    "path": "test/setup/setup-boulder.sh",
    "content": "#!/bin/bash\n\nset -e\n\nacme_endpoint='http://boulder:4001/directory'\n\nsetup_boulder() {\n  export GOPATH=${GITHUB_WORKSPACE}/go\n  [[ ! -d $GOPATH/src/github.com/letsencrypt/boulder ]] \\\n    && git clone https://github.com/letsencrypt/boulder \\\n      \"$GOPATH/src/github.com/letsencrypt/boulder\"\n  pushd \"$GOPATH/src/github.com/letsencrypt/boulder\"\n  git checkout release-2023-12-04\n  if [[ \"$(uname)\" == 'Darwin' ]]; then\n    # Set Standard Ports\n    for file in test/config/va.json test/config/va-remote-a.json test/config/va-remote-b.json; do\n      sed -i '' 's/ 5002/ 80/g' \"$file\"\n      sed -i '' 's/ 5001/ 443/g' \"$file\"\n    done\n    # Modify custom rate limit\n    sed -i '' 's/le.wtf,le1.wtf/le1.wtf,le2.wtf,le3.wtf/g' test/rate-limit-policies.yml\n  else\n    # Set Standard Ports\n    for file in test/config/va.json test/config/va-remote-a.json test/config/va-remote-b.json; do\n      sed --in-place 's/ 5002/ 80/g' \"$file\"\n      sed --in-place 's/ 5001/ 443/g' \"$file\"\n    done\n    # Modify custom rate limit\n    sed --in-place 's/le.wtf,le1.wtf/le1.wtf,le2.wtf,le3.wtf/g' test/rate-limit-policies.yml\n  fi\n  docker compose build --pull\n  docker compose run -d \\\n    --use-aliases \\\n    --name boulder \\\n    -e FAKE_DNS=10.77.77.1 \\\n    --service-ports \\\n    boulder\n  popd\n}\n\nwait_for_boulder() {\n  i=0\n  until docker exec boulder bash -c \"curl ${acme_endpoint:?} >/dev/null 2>&1\"; do\n    if [ $i -gt 300 ]; then\n      echo \"Boulder has not started for 5 minutes, timing out.\"\n      exit 1\n    fi\n    i=$((i + 5))\n    echo \"$acme_endpoint : connection refused, Boulder isn't ready yet. Waiting.\"\n    sleep 5\n  done\n}\n\nsetup_boulder\nwait_for_boulder\n"
  },
  {
    "path": "test/setup/setup-local.sh",
    "content": "#!/bin/bash\n\nset -e\n\nfunction get_environment {\n  dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n  LOCAL_BUILD_DIR=\"$(cd \"$dir/../..\" && pwd)\"\n  export GITHUB_WORKSPACE=\"$LOCAL_BUILD_DIR\"\n\n  # shellcheck source=/dev/null\n  [[ -f \"${GITHUB_WORKSPACE}/test/local_test_env.sh\" ]] && \\\n    source \"${GITHUB_WORKSPACE}/test/local_test_env.sh\"\n\n  # Get the environment variables from the .github/workflows/test.yml file with sed\n  declare -a ci_test_yml\n  ci_test_yml[0]=\"$(sed -n 's/.* NGINX_CONTAINER_NAME: //p' \"$LOCAL_BUILD_DIR/.github/workflows/test.yml\")\"\n  ci_test_yml[1]=\"$(sed -n 's/.* DOCKER_GEN_CONTAINER_NAME: //p' \"$LOCAL_BUILD_DIR/.github/workflows/test.yml\")\"\n  ci_test_yml[2]=\"$(sed -n 's/.* TEST_DOMAINS: //p' \"$LOCAL_BUILD_DIR/.github/workflows/test.yml\")\"\n\n  # If environment variable where sourced or manually set use them, else use those from \n  # .github/workflows/test.yml\n  export NGINX_CONTAINER_NAME=\"${NGINX_CONTAINER_NAME:-${ci_test_yml[0]}}\"\n  export DOCKER_GEN_CONTAINER_NAME=\"${DOCKER_GEN_CONTAINER_NAME:-${ci_test_yml[1]}}\"\n  export TEST_DOMAINS=\"${TEST_DOMAINS:-${ci_test_yml[2]}}\"\n\n  # Build the array containing domains to add to /etc/hosts\n  IFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n  if [[ -z $SETUP ]]; then\n    while true; do\n      echo \"Which nginx-proxy setup do you want to test or remove ?\"\n      echo \"\"\n      echo \"    1) Two containers setup (nginx-proxy + le-companion)\"\n      echo \"    2) Three containers setup (nginx + docker-gen + le-companion)\"\n      read -re -p \"Select an option [1-2]: \" option\n      case $option in\n        1)\n        setup=\"2containers\"\n        break\n        ;;\n        2)\n        setup=\"3containers\"\n        break\n        ;;\n        *)\n        exit 1\n        ;;\n      esac\n    done\n  fi\n  export SETUP=\"${SETUP:-$setup}\"\n\n  if [[ -z $ACME_CA ]]; then\n    while true; do\n      echo \"Which ACME CA do you want to use or remove ?\"\n      echo \"\"\n      echo \"    1) Boulder                        https://github.com/letsencrypt/boulder\"\n      echo \"    2) Pebble with base configuration https://github.com/letsencrypt/pebble\"\n      echo \"    3) Pebble with EAB configuration  https://github.com/letsencrypt/pebble\"\n      read -re -p \"Select an option [1-3]: \" option\n      case $option in\n        1)\n        acme_ca=\"boulder\"\n        break\n        ;;\n        2)\n        acme_ca=\"pebble\"\n        pebble_config=\"pebble-config.json\"\n        break\n        ;;\n        3)\n        acme_ca=\"pebble\"\n        pebble_config=\"pebble-config-eab.json\"\n        break\n        ;;\n        *)\n        exit 1\n        ;;\n      esac\n    done\n  fi\n  export ACME_CA=\"${ACME_CA:-$acme_ca}\"\n  export PEBBLE_CONFIG=\"${PEBBLE_CONFIG:-$pebble_config}\"\n}\n\ncase $1 in\n  --setup)\n    get_environment\n\n    # Prepare the env file that run.sh will source\n    cat > \"${GITHUB_WORKSPACE}/test/local_test_env.sh\" <<EOF\nexport GITHUB_WORKSPACE=\"$LOCAL_BUILD_DIR\"\nexport NGINX_CONTAINER_NAME=\"$NGINX_CONTAINER_NAME\"\nexport DOCKER_GEN_CONTAINER_NAME=\"$DOCKER_GEN_CONTAINER_NAME\"\nexport TEST_DOMAINS=\"$TEST_DOMAINS\"\nexport SETUP=\"$SETUP\"\nexport ACME_CA=\"$ACME_CA\"\nexport PEBBLE_CONFIG=\"$PEBBLE_CONFIG\"\nEOF\n\n    # Add the required custom entries to /etc/hosts\n    echo \"Adding custom entries to /etc/hosts (requires sudo).\"\n    declare -a hosts=(\"${domains[@]}\")\n    if [[ \"$ACME_CA\" == 'pebble' ]]; then\n      hosts+=(pebble pebble-challtestsrv)\n    fi\n    for host in \"${hosts[@]}\"; do\n      grep -q \"127.0.0.1 $host # le-companion test suite\" /etc/hosts \\\n        || echo \"127.0.0.1 $host # le-companion test suite\" \\\n        | sudo tee -a /etc/hosts\n    done\n\n    # Pull nginx:alpine\n    docker pull nginx:alpine\n\n    # Prepare the test setup using the setup scripts\n    if [[ \"$ACME_CA\" == 'boulder' ]]; then\n      \"${GITHUB_WORKSPACE}/test/setup/setup-boulder.sh\"\n    elif [[ \"$ACME_CA\" == 'pebble' ]]; then\n      \"${GITHUB_WORKSPACE}/test/setup/pebble/setup-pebble.sh\"\n    else\n      echo \"ACME_CA is not set, aborting.\"\n      exit 1\n    fi\n    \"${GITHUB_WORKSPACE}/test/setup/setup-nginx-proxy.sh\"\n    ;;\n\n  --teardown)\n    get_environment\n\n    # Stop and remove nginx-proxy and (if required) docker-gen\n    for cid in $(docker ps -a --filter \"label=com.github.nginx-proxy.acme-companion.test-suite\" --format \"{{.ID}}\"); do\n      docker stop \"$cid\"\n      docker rm --volumes \"$cid\"\n    done\n\n    if [[ \"$ACME_CA\" == 'boulder' ]]; then\n      # Stop and remove Boulder\n      docker stop boulder\n      docker compose --project-name 'boulder' \\\n        --file \"${GITHUB_WORKSPACE}/go/src/github.com/letsencrypt/boulder/docker-compose.yml\" \\\n        down --volumes\n      docker rm boulder\n    elif [[ \"$ACME_CA\" == 'pebble' ]]; then\n      # Stop and remove Pebble\n      docker compose --file \"${GITHUB_WORKSPACE}/test/setup/pebble/compose.yaml\" down\n      [[ -f \"${GITHUB_WORKSPACE}/pebble.minica.pem\" ]] && rm \"${GITHUB_WORKSPACE}/pebble.minica.pem\"\n    fi\n\n    # Cleanup files created by the setup\n    if [[ -n \"${GITHUB_WORKSPACE// }\" ]]; then\n      [[ -f \"${GITHUB_WORKSPACE}/nginx.tmpl\" ]] && rm \"${GITHUB_WORKSPACE}/nginx.tmpl\"\n      rm \"${GITHUB_WORKSPACE}/test/local_test_env.sh\"\n      echo \"The ${GITHUB_WORKSPACE}/go folder require superuser permission to fully remove.\"\n      echo \"Doing sudo rm -rf in scripts is dangerous, so the folder won't be automatically removed.\"\n    fi\n\n    # Remove custom entries to /etc/hosts\n    echo \"Removing custom entries from /etc/hosts (requires sudo).\"\n    declare -a hosts=(\"${domains[@]}\")\n    if [[ \"$ACME_CA\" == 'pebble' ]]; then\n      hosts+=(pebble pebble-challtestsrv)\n    fi\n    for host in \"${hosts[@]}\"; do\n      if [[ \"$(uname)\" == 'Darwin' ]]; then\n        sudo sed -i '' \"/127\\.0\\.0\\.1 $host # le-companion test suite/d\" /etc/hosts\n      else\n        sudo sed --in-place \"/127\\.0\\.0\\.1 $host # le-companion test suite/d\" /etc/hosts\n      fi\n    done\n    ;;\n\n    *)\n    echo \"Usage:\"\n    echo \"\"\n    echo \"    --setup : setup the test suite.\"\n    echo \"    --teardown : remove the test suite containers, configuration and files.\"\n    echo \"\"\n    ;;\nesac\n"
  },
  {
    "path": "test/setup/setup-nginx-proxy.sh",
    "content": "#!/bin/bash\n\nset -e\n\ncase $ACME_CA in\n\n  pebble)\n    test_net='acme_net'\n  ;;\n\n  boulder)\n    test_net='boulder_bluenet'\n  ;;\n\n  *)\n    echo \"$0 $ACME_CA: invalid option.\"\n    exit 1\n\nesac\n\ncase $SETUP in\n\n  2containers)\n    docker run -d -p 80:80 -p 443:443 \\\n      --name \"$NGINX_CONTAINER_NAME\" \\\n      -v /etc/nginx/certs \\\n      -v /etc/nginx/conf.d \\\n      -v /etc/nginx/vhost.d \\\n      -v /usr/share/nginx/html \\\n      -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n      --label com.github.nginx-proxy.acme-companion.test-suite \\\n      --network \"$test_net\" \\\n      nginxproxy/nginx-proxy\n    ;;\n\n  3containers)\n    curl https://raw.githubusercontent.com/nginx-proxy/nginx-proxy/main/nginx.tmpl > \"${GITHUB_WORKSPACE}/nginx.tmpl\"\n\n    docker run -d -p 80:80 -p 443:443 \\\n      --name \"$NGINX_CONTAINER_NAME\" \\\n      -v /etc/nginx/certs \\\n      -v /etc/nginx/conf.d \\\n      -v /etc/nginx/vhost.d \\\n      -v /usr/share/nginx/html \\\n      --label com.github.nginx-proxy.acme-companion.test-suite \\\n      --network \"$test_net\" \\\n      nginx:alpine\n\n    docker run -d \\\n      --name \"$DOCKER_GEN_CONTAINER_NAME\" \\\n      --volumes-from \"$NGINX_CONTAINER_NAME\" \\\n      -v \"${GITHUB_WORKSPACE}/nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro\" \\\n      -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n      --label com.github.nginx-proxy.acme-companion.test-suite \\\n      --network \"$test_net\" \\\n      nginxproxy/docker-gen \\\n      -notify-sighup \"$NGINX_CONTAINER_NAME\" -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf\n    ;;\n\n  *)\n    echo \"$0 $SETUP: invalid option.\"\n    exit 1\n\nesac\n"
  },
  {
    "path": "test/tests/acme_accounts/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/acme_accounts/run.sh",
    "content": "#!/bin/bash\n\n## Test for ACME accounts handling.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  for domain in \"${domains[@]}\"; do\n    docker rm --force \"$domain\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run an nginx container for ${domains[0]}.\nrun_nginx_container --hosts \"${domains[0]}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\n# Hard set the account dir based on the test ACME CA used.\ncase $ACME_CA in\n  pebble)\n    account_dir=\"pebble/dir\"\n    ;;\n  boulder)\n    account_dir=\"boulder/directory\"\n    ;;\n  *)\n    echo \"$0 $ACME_CA: invalid option.\"\n    exit 1\nesac\n\n# Test if the expected folder / file / content are there.\njson_file=\"/etc/acme.sh/default/ca/$account_dir/account.json\"\nif [[ \"$ACME_CA\" == 'boulder' ]]; then\n  no_mail_str='[]'\nelif [[ \"$ACME_CA\" == 'pebble' ]]; then\n  no_mail_str='null'\nfi\nif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/default\" ]]; then\n  echo \"The /etc/acme.sh/default folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -f \"$json_file\" ]]; then\n  echo \"The $json_file file does not exist.\"\nelif [[ \"$(docker exec \"$le_container_name\" jq .contact \"$json_file\")\" != \"$no_mail_str\" ]]; then\n  echo \"There is an address set on ${json_file}.\"\n  docker exec \"$le_container_name\" jq . \"$json_file\"\n  docker exec \"$le_container_name\" jq .contact \"$json_file\"\nfi\n\n# Stop the nginx and companion containers silently.\ndocker stop \"${domains[0]}\" &> /dev/null\ndocker stop \"$le_container_name\" &> /dev/null\n\n# Run the companion container with the DEFAULT_EMAIL env var set.\ndefault_email=\"contact@${domains[1]}\"\nle_container_name=\"${le_container_name}_default\"\nrun_le_container \"${1:?}\" \"$le_container_name\" \"--env DEFAULT_EMAIL=${default_email}\"\n\n# Run an nginx container for ${domains[1]} without LETSENCRYPT_EMAIL set.\nrun_nginx_container --hosts \"${domains[1]}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[1]}.crt\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\"\n\n# Test if the expected folder / file / content are there.\njson_file=\"/etc/acme.sh/${default_email}/ca/$account_dir/account.json\"\nif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/$default_email\" ]]; then\n  echo \"The /etc/acme.sh/$default_email folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -f \"$json_file\" ]]; then\n  echo \"The $json_file file does not exist.\"\nelif [[ \"$(docker exec \"$le_container_name\" jq -r '.contact|.[0]' \"$json_file\")\" != \"mailto:${default_email}\" ]]; then\n  echo \"$default_email is not set on ${json_file}.\"\n  docker exec \"$le_container_name\" jq . \"$json_file\"\nfi\n\n# Run an nginx container for ${domains[2]} with LETSENCRYPT_EMAIL set.\ncontainer_email=\"contact@${domains[2]}\"\nrun_nginx_container --hosts \"${domains[2]}\" --cli-args \"--env LETSENCRYPT_EMAIL=${container_email}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[2]}.crt\nwait_for_symlink \"${domains[2]}\" \"$le_container_name\"\n\n# Test if the expected folder / file / content are there.\njson_file=\"/etc/acme.sh/${container_email}/ca/$account_dir/account.json\"\nif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/$container_email\" ]]; then\n  echo \"The /etc/acme.sh/$container_email folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -f \"$json_file\" ]]; then\n  echo \"The $json_file file does not exist.\"\nelif [[ \"$(docker exec \"$le_container_name\" jq -r '.contact|.[0]' \"$json_file\")\" != \"mailto:${container_email}\" ]]; then\n  echo \"$default_email is not set on ${json_file}.\"\n  docker exec \"$le_container_name\" jq . \"$json_file\"\nfi\n\n# Stop the nginx containers silently.\ndocker stop \"${domains[1]}\" &> /dev/null\ndocker stop \"${domains[2]}\" &> /dev/null\n"
  },
  {
    "path": "test/tests/acme_eab/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/acme_eab/run.sh",
    "content": "#!/bin/bash\n\n## Test for ACME External Account Binding (EAB).\n\ndeclare -A eab=( \\\n  [kid-1]=zWNDZM6eQGHWpSRTPal5eIUYFTu7EajVIoguysqZ9wG44nMEtx3MUAsUDkMTQ12W \\\n  [kid-2]=b10lLJs8l1GPIzsLP0s6pMt8O0XVGnfTaCeROxQM0BIt2XrJMDHJZBM5NuQmQJQH \\\n)\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\" \\\n  --cli-args \"--env ACME_EAB_KID=kid-1\" \\\n  --cli-args \"--env ACME_EAB_HMAC_KEY=${eab[kid-1]}\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  for domain in \"${domains[@]}\"; do\n    docker rm --force \"$domain\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run an nginx container for ${domains[0]}.\nrun_nginx_container --hosts \"${domains[0]}\"\n\n# Run an nginx container for ${domains[1]} with LETSENCRYPT_EMAIL and ACME_EAB_* set.\ncontainer_email=\"contact@${domains[1]}\"\nrun_nginx_container --hosts \"${domains[1]}\"  \\\n  --cli-args \"--env LETSENCRYPT_EMAIL=${container_email}\" \\\n  --cli-args \"--env ACME_EAB_KID=kid-2\" \\\n  --cli-args \"--env ACME_EAB_HMAC_KEY=${eab[kid-2]}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\n# Test if the expected file is there.\nconfig_path=\"/etc/acme.sh/default/ca/$ACME_CA/dir\"\njson_file=\"${config_path}/account.json\"\nconf_file=\"${config_path}/ca.conf\"\nif docker exec \"$le_container_name\" [[ ! -f \"$json_file\" ]]; then\n  echo \"The $json_file file does not exist.\"\nelif ! docker exec \"$le_container_name\" grep -q \"${eab[kid-1]}\" \"$conf_file\"; then\n  echo \"There correct EAB HMAC key isn't on ${conf_file}.\"\nfi\n\n# Wait for a symlink at /etc/nginx/certs/${domains[1]}.crt\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\"\n\n# Test if the expected file is there.\nconfig_path=\"/etc/acme.sh/${container_email}/ca/$ACME_CA/dir\"\njson_file=\"${config_path}/account.json\"\nconf_file=\"${config_path}/ca.conf\"\nif docker exec \"$le_container_name\" [[ ! -f \"$json_file\" ]]; then\n  echo \"The $json_file file does not exist.\"\nelif ! docker exec \"$le_container_name\" grep -q \"${eab[kid-2]}\" \"$conf_file\"; then\n  echo \"There correct EAB HMAC key isn't on ${conf_file}.\"\nfi\n\n# Stop the nginx containers silently.\ndocker stop \"${domains[0]}\" &> /dev/null\ndocker stop \"${domains[1]}\" &> /dev/null\n"
  },
  {
    "path": "test/tests/acme_hooks/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/acme_hooks/run.sh",
    "content": "#!/bin/bash\n\n## Test for the hooks of acme.sh\n\ndefault_pre_hook_file=\"/tmp/default_prehook\"\ndefault_pre_hook_command=\"touch $default_pre_hook_file\"\ndefault_post_hook_file=\"/tmp/default_posthook\"\ndefault_post_hook_command=\"touch $default_post_hook_file\"\n\npercontainer_pre_hook_file=\"/tmp/percontainer_prehook\"\npercontainer_pre_hook_command=\"touch $percontainer_pre_hook_file\"\npercontainer_post_hook_file=\"/tmp/percontainer_posthook\"\npercontainer_post_hook_command=\"touch $percontainer_post_hook_file\"\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\" \\\n  --cli-args \"--env ACME_PRE_HOOK=$default_pre_hook_command\" \\\n  --cli-args \"--env ACME_POST_HOOK=$default_post_hook_command\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the Nginx container silently.\n  docker rm --force \"${domains[0]}\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\ncontainer_email=\"contact@${domains[0]}\"\n\n# Run an nginx container for ${domains[0]} with LETSENCRYPT_EMAIL set.\nrun_nginx_container --hosts \"${domains[0]}\" \\\n  --cli-args \"--env LETSENCRYPT_EMAIL=${container_email}\"\n\n# Run an nginx container for ${domains[1]} with LETSENCRYPT_EMAIL, ACME_PRE_HOOK and ACME_POST_HOOK set.\nrun_nginx_container --hosts \"${domains[1]}\" \\\n  --cli-args \"--env LETSENCRYPT_EMAIL=${container_email}\" \\\n  --cli-args \"--env ACME_PRE_HOOK=$percontainer_pre_hook_command\" \\\n  --cli-args \"--env ACME_POST_HOOK=$percontainer_post_hook_command\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\nacme_pre_hook_key=\"Le_PreHook=\"\nacme_post_hook_key=\"Le_PostHook=\"\nacme_base64_start=\"'__ACME_BASE64__START_\"\nacme_base64_end=\"__ACME_BASE64__END_'\"\n\n# Check if the default command is deliverd properly in /etc/acme.sh\nif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/$container_email\" ]]; then\n  echo \"The /etc/acme.sh/$container_email folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/$container_email/${domains[0]}\" ]]; then\n  echo \"The /etc/acme.sh/$container_email/${domains[0]} folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -f \"/etc/acme.sh/$container_email/${domains[0]}/${domains[0]}.conf\" ]]; then\n  echo \"The /etc/acme.sh/$container_email/${domains[0]}/${domains[0]}.conf file does not exist.\"\nfi\n\ndefault_pre_hook_command_base64=\"${acme_pre_hook_key}${acme_base64_start}$(echo -n \"$default_pre_hook_command\" | base64)${acme_base64_end}\"\ndefault_post_hook_command_base64=\"${acme_post_hook_key}${acme_base64_start}$(echo -n \"$default_post_hook_command\" | base64)${acme_base64_end}\"\n\ndefault_acme_pre_hook=\"$(docker exec \"$le_container_name\" grep \"$acme_pre_hook_key\" \"/etc/acme.sh/$container_email/${domains[0]}/${domains[0]}.conf\")\"\ndefault_acme_post_hook=\"$(docker exec \"$le_container_name\" grep \"$acme_post_hook_key\" \"/etc/acme.sh/$container_email/${domains[0]}/${domains[0]}.conf\")\"\n\nif [[ \"$default_pre_hook_command_base64\" != \"$default_acme_pre_hook\" ]]; then \n  echo \"Default prehook command not saved properly\"\nfi\nif [[ \"$default_post_hook_command_base64\" != \"$default_acme_post_hook\" ]]; then \n  echo \"Default posthook command not saved properly\"\nfi\n\n\n# Check if the default action is performed \nif docker exec \"$le_container_name\" [[ ! -f \"$default_pre_hook_file\" ]]; then\n  echo \"Default prehook action failed\"\nfi\nif docker exec \"$le_container_name\" [[ ! -f \"$default_post_hook_file\" ]]; then\n  echo \"Default posthook action failed\"\nfi\n\n# Wait for a symlink at /etc/nginx/certs/${domains[1]}.crt\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\"\n\n# Check if the per-container command is deliverd properly in /etc/acme.sh\nif docker exec \"$le_container_name\" [[ ! -d \"/etc/acme.sh/$container_email/${domains[1]}\" ]]; then\n  echo \"The /etc/acme.sh/$container_email/${domains[1]} folder does not exist.\"\nelif docker exec \"$le_container_name\" [[ ! -f \"/etc/acme.sh/$container_email/${domains[1]}/${domains[1]}.conf\" ]]; then\n  echo \"The /etc/acme.sh/$container_email/${domains[1]}/${domains[1]}.conf file does not exist.\"\nfi\n\npercontainer_pre_hook_command_base64=\"${acme_pre_hook_key}${acme_base64_start}$(echo -n \"$percontainer_pre_hook_command\" | base64)${acme_base64_end}\"\npercontainer_post_hook_command_base64=\"${acme_post_hook_key}${acme_base64_start}$(echo -n \"$percontainer_post_hook_command\" | base64)${acme_base64_end}\"\n\npercontainer_acme_pre_hook=\"$(docker exec \"$le_container_name\" grep \"$acme_pre_hook_key\" \"/etc/acme.sh/$container_email/${domains[1]}/${domains[1]}.conf\")\"\npercontainer_acme_post_hook=\"$(docker exec \"$le_container_name\" grep \"$acme_post_hook_key\" \"/etc/acme.sh/$container_email/${domains[1]}/${domains[1]}.conf\")\"\n\nif [[ \"$percontainer_pre_hook_command_base64\" != \"$percontainer_acme_pre_hook\" ]]; then \n  echo \"Per-container prehook command not saved properly\"\nfi\nif [[ \"$percontainer_post_hook_command_base64\" != \"$percontainer_acme_post_hook\" ]]; then \n  echo \"Per-container posthook command not saved properly\"\nfi\n\n\n# Check if the percontainer action is performed \nif docker exec \"$le_container_name\" [[ ! -f \"$percontainer_pre_hook_file\" ]]; then\n  echo \"Per-container prehook action failed\"\nfi\nif docker exec \"$le_container_name\" [[ ! -f \"$percontainer_post_hook_file\" ]]; then\n  echo \"Per-container posthook action failed\"\nfi\n"
  },
  {
    "path": "test/tests/certs_default_renew/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/certs_default_renew/run.sh",
    "content": "#!/bin/bash\n\n## Test for the DEFAULT_RENEW function.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\n\ndefault_renew=170\nrun_le_container \"${1:?}\" \"$le_container_name\" \\\n  --cli-args \"--env DEFAULT_RENEW=$default_renew\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the Nginx container silently.\n  docker rm --force \"${domains[0]}\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\ncontainer_email=\"contact@${domains[0]}\"\nacme_config_file=\"/etc/acme.sh/$container_email/${domains[0]}/${domains[0]}.conf\"\n\n# Run a nginx container for ${domains[0]} with LETSENCRYPT_EMAIL set.\nrun_nginx_container --hosts \"${domains[0]}\" \\\n  --cli-args \"--env LETSENCRYPT_EMAIL=${container_email}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\nacme_cert_create_time_key=\"Le_CertCreateTime=\"\nacme_renewal_days_key=\"Le_RenewalDays=\"\nacme_next_renew_time_key=\"Le_NextRenewTime=\"\n\n# Check if the default command is deliverd properly in /etc/acme.sh\nif docker exec \"$le_container_name\" [[ ! -f \"$acme_config_file\" ]]; then\n  echo \"The $acme_config_file file does not exist.\"\nfi\n\ncert_create_time=\"$(docker exec \"$le_container_name\" grep \"$acme_cert_create_time_key\" \"$acme_config_file\" | cut -f2 -d\\')\"\nexpected_renewal_days=\"${acme_renewal_days_key}'$default_renew'\"\nexpected_next_renew_time=\"${acme_next_renew_time_key}'$(($cert_create_time + $default_renew * 24 * 60 * 60 - 86400))'\"\nactual_renewal_days=\"$(docker exec \"$le_container_name\" grep \"$acme_renewal_days_key\" \"$acme_config_file\")\"\nactual_next_renew_time=\"$(docker exec \"$le_container_name\" grep \"$acme_next_renew_time_key\" \"$acme_config_file\")\"\n\nif [[ \"$expected_renewal_days\" != \"$actual_renewal_days\" ]]; then\n  echo \"Renewal days is not correct\"\nfi\nif [[ \"$expected_next_renew_time\" != \"$actual_next_renew_time\" ]]; then\n  echo \"Next renewal time is not correct\"\nfi\n"
  },
  {
    "path": "test/tests/certs_san/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/certs_san/run.sh",
    "content": "#!/bin/bash\n\n## Test for SAN (Subject Alternative Names) certificates.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  i=1\n  for hosts in \"${letsencrypt_hosts[@]}\"; do\n    docker rm --force \"test$i\" &> /dev/null\n    i=$(( i + 1 ))\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Create three different comma separated list from the first three domains in $domains.\n# testing for regression on spaced lists https://github.com/nginx-proxy/acme-companion/issues/288\n# with trailing comma https://github.com/nginx-proxy/acme-companion/issues/254\n# and with trailing dot https://github.com/nginx-proxy/acme-companion/issues/676\nletsencrypt_hosts=( \\\n  [0]=\"${domains[0]},${domains[1]},${domains[2]}\" \\     #straight comma separated list\n  [1]=\"${domains[1]}, ${domains[2]}, ${domains[0]}\" \\   #comma separated list with spaces\n  [2]=\"${domains[2]}, ${domains[0]}, ${domains[1]},\" \\  #comma separated list with spaces and a trailing comma\n  [3]=\"${domains[0]}.,${domains[2]}.,${domains[1]}\" )   #trailing dots\n\ni=1\n\nfor hosts in \"${letsencrypt_hosts[@]}\"; do\n\n  # Get the base domain (first domain of the list).\n  base_domain=\"$(get_base_domain \"$hosts\")\"\n  container=\"test$i\"\n\n  # Run an Nginx container passing one of the comma separated list as LETSENCRYPT_HOST env var.\n  run_nginx_container --hosts \"$hosts\" --name \"$container\"\n\n  # Wait for a symlink at /etc/nginx/certs/$base_domain.crt\n  if wait_for_symlink \"$base_domain\" \"$le_container_name\" \"./${base_domain}/fullchain.pem\"; then\n    # then grab the certificate in text form ...\n    created_cert=\"$(docker exec \"$le_container_name\" \\\n      openssl x509 -in \"/etc/nginx/certs/${base_domain}/cert.pem\" -text -noout)\"\n    # ... as well as the certificate fingerprint.\n    created_cert_fingerprint=\"$(docker exec \"$le_container_name\" \\\n      openssl x509 -in \"/etc/nginx/certs/${base_domain}/cert.pem\" -fingerprint -noout)\"\n  fi\n\n  for domain in \"${domains[@]}\"; do\n  ## For all the domains in the $domains array ...\n\n    # Check if the domain is on the certificate.\n    if ! grep -q \"$domain\" <<< \"$created_cert\"; then\n      echo \"$domain did not appear on certificate.\"\n    elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n      echo \"$domain is on certificate.\"\n    fi\n\n    # Wait for a connection to https://domain then grab the served certificate in text form.\n    wait_for_conn --domain \"$domain\"\n    served_cert_fingerprint=\"$(echo \\\n      | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n      | openssl x509 -fingerprint -noout)\"\n\n\n    # Compare the cert on file and what we got from the https connection.\n    # If not identical, display a full diff.\n    if [ \"$created_cert_fingerprint\" != \"$served_cert_fingerprint\" ]; then\n      echo \"Nginx served an incorrect certificate for $domain.\"\n      served_cert=\"$(echo \\\n        | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n        | openssl x509 -text -noout \\\n        | sed 's/ = /=/g' )\"\n      diff -u <(echo \"${created_cert// = /=}\") <(echo \"$served_cert\")\n    elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n       echo \"The correct certificate for $domain was served by Nginx.\"\n    fi\n  done\n\n  docker stop \"$container\" &> /dev/null\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  i=$(( i + 1 ))\n\ndone\n"
  },
  {
    "path": "test/tests/certs_single/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/certs_single/run.sh",
    "content": "#!/bin/bash\n\n## Test for single domain certificates.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  for domain in \"${domains[@]}\"; do\n    docker rm --force \"$domain\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run a separate nginx container for each domain in the $domains array.\n# Start all the containers in a row so that docker-gen debounce timers fire only once.\nfor domain in \"${domains[@]}\"; do\n  run_nginx_container --hosts \"$domain\"\ndone\n\nfor domain in \"${domains[@]}\"; do\n\n  # Wait for a symlink at /etc/nginx/certs/$domain.crt\n  if wait_for_symlink \"$domain\" \"$le_container_name\" \"./${domain}/fullchain.pem\" ; then\n    # then grab the certificate in text form from the file ...\n    created_cert=\"$(docker exec \"$le_container_name\" \\\n      openssl x509 -in \"/etc/nginx/certs/${domain}/cert.pem\" -text -noout)\"\n    # ... as well as the certificate fingerprint.\n    created_cert_fingerprint=\"$(docker exec \"$le_container_name\" \\\n      openssl x509 -in \"/etc/nginx/certs/${domain}/cert.pem\" -fingerprint -noout)\"\n  fi\n\n\n  # Check if the domain is on the certificate.\n  if ! grep -q \"$domain\" <<< \"$created_cert\"; then\n    echo \"Domain $domain isn't on certificate.\"\n  elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n    echo \"Domain $domain is on certificate.\"\n  fi\n\n  # Wait for a connection to https://domain then grab the served certificate fingerprint.\n  wait_for_conn --domain \"$domain\"\n  served_cert_fingerprint=\"$(echo \\\n    | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n    | openssl x509 -fingerprint -noout)\"\n\n  # Compare fingerprints from the cert on file and what we got from the https connection.\n  # If not identical, display a full diff.\n  if [ \"$created_cert_fingerprint\" != \"$served_cert_fingerprint\" ]; then\n    echo \"Nginx served an incorrect certificate for $domain.\"\n    served_cert=\"$(echo \\\n      | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n      | openssl x509 -text -noout \\\n      | sed 's/ = /=/g' )\"\n    diff -u <(echo \"${created_cert// = /=}\") <(echo \"$served_cert\")\n  elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n    echo \"The correct certificate for $domain was served by Nginx.\"\n  fi\n\n  # Stop the Nginx container silently.\n  docker stop \"$domain\" > /dev/null\ndone\n"
  },
  {
    "path": "test/tests/certs_single_domain/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/certs_single_domain/run.sh",
    "content": "#!/bin/bash\n\n## Test for spliting SAN certificates into single domain certificates by NGINX container env variables\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  i=1\n  for hosts in \"${letsencrypt_hosts[@]}\"; do\n    docker rm --force \"test$i\" &> /dev/null\n    i=$(( i + 1 ))\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Create three different comma separated list from the first three domains in $domains.\n# testing for regression on spaced lists https://github.com/nginx-proxy/acme-companion/issues/288\n# and with trailing comma https://github.com/nginx-proxy/acme-companion/issues/254\nletsencrypt_hosts=( \\\n  [0]=\"${domains[0]},${domains[1]},${domains[2]}\" \\     #straight comma separated list\n  [1]=\"${domains[1]}, ${domains[2]}, ${domains[0]}\" \\   #comma separated list with spaces\n  [2]=\"${domains[2]}, ${domains[0]}, ${domains[1]},\" )  #comma separated list with spaces and a trailing comma\n\ni=1\n\nfor hosts in \"${letsencrypt_hosts[@]}\"; do\n\n  container=\"test$i\"\n\n  # Run an Nginx container passing one of the comma separated list as LETSENCRYPT_HOST env var.\n  run_nginx_container --hosts \"${hosts}\" --name \"$container\" --cli-args \"--env LETSENCRYPT_SINGLE_DOMAIN_CERTS=true\"\n\n  for domain in \"${domains[@]}\"; do\n      ## For all the domains in the $domains array ...\n      # Wait for a symlink at /etc/nginx/certs/$domain.crt\n      if wait_for_symlink \"${domain}\" \"$le_container_name\" \"./${domain}/fullchain.pem\"; then\n        # then grab the certificate in text form from the file ...\n        created_cert=\"$(docker exec \"$le_container_name\" \\\n          openssl x509 -in \"/etc/nginx/certs/${domain}/cert.pem\" -text -noout)\"\n        # ... as well as the certificate fingerprint.\n        created_cert_fingerprint=\"$(docker exec \"$le_container_name\" \\\n          openssl x509 -in \"/etc/nginx/certs/${domain}/cert.pem\" -fingerprint -noout)\"\n    fi\n\n    # Check if the domain is on the certificate.\n    if grep -q \"$domain\" <<< \"$created_cert\"; then\n      if [[ \"${DRY_RUN:-}\" == 1 ]]; then\n        echo \"$domain is on certificate.\"\n      fi\n      for otherdomain in \"${domains[@]}\"; do\n        if [ \"$domain\" != \"$otherdomain\" ]; then\n          if grep -q \"$otherdomain\" <<< \"$created_cert\"; then\n            echo \"$otherdomain is on certificate for $domain, but it must not!\"\n          elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n            echo \"$otherdomain did not appear on certificate for $domain.\"\n          fi\n        fi\n      done\n    else\n      echo \"$domain did not appear on certificate.\"\n    fi\n\n    # Wait for a connection to https://domain then grab the served certificate in text form.\n    wait_for_conn --domain \"$domain\"\n    served_cert_fingerprint=\"$(echo \\\n      | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n      | openssl x509 -fingerprint -noout)\"\n\n\n    # Compare the cert on file and what we got from the https connection.\n    # If not identical, display a full diff.\n    if [ \"$created_cert_fingerprint\" != \"$served_cert_fingerprint\" ]; then\n      echo \"Nginx served an incorrect certificate for $domain.\"\n      served_cert=\"$(echo \\\n        | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n        | openssl x509 -text -noout \\\n        | sed 's/ = /=/g' )\"\n      diff -u <(echo \"${created_cert// = /=}\") <(echo \"$served_cert\")\n    elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n       echo \"The correct certificate for $domain was served by Nginx.\"\n    fi\n  done\n\n  docker stop \"$container\" &> /dev/null\n  i=$(( i + 1 ))\n\ndone\n"
  },
  {
    "path": "test/tests/certs_standalone/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/certs_standalone/run.sh",
    "content": "#!/bin/bash\n\n## Test for standalone certificates.\n\ncase $ACME_CA in\n  pebble)\n    test_net='acme_net'\n  ;;\n  boulder)\n    test_net='boulder_bluenet'\n  ;;\n  *)\n    echo \"$0 $ACME_CA: invalid option.\"\n    exit 1\nesac\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\nsubdomain=\"sub.${domains[0]}\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the Nginx container silently.\n  docker rm --force \"$subdomain\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Create letsencrypt_user_data with a single domain cert\ncat > \"${GITHUB_WORKSPACE}/test/tests/certs_standalone/letsencrypt_user_data\" <<EOF\nLETSENCRYPT_STANDALONE_CERTS=('single')\nLETSENCRYPT_single_HOST=('${domains[0]}')\nEOF\n\n# Run an nginx container with a VIRTUAL_HOST set to a subdomain of ${domains[0]} in order to check for\n# this regression : https://github.com/nginx-proxy/acme-companion/issues/674\nif ! docker run --rm -d \\\n    --name \"$subdomain\" \\\n    -e \"VIRTUAL_HOST=$subdomain\" \\\n    --network \"$test_net\" \\\n    nginx:alpine > /dev/null;\nthen\n  echo \"Could not start test web server for $subdomain\"\nelif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n  echo \"Started test web server for $subdomain\"\nfi\n\nrun_le_container \"${1:?}\" \"$le_container_name\" \\\n  \"--volume ${GITHUB_WORKSPACE}/test/tests/certs_standalone/letsencrypt_user_data:/app/letsencrypt_user_data\"\n\n# Wait for a file at /etc/nginx/conf.d/standalone-cert-${domains[0]}.conf\nwait_for_standalone_conf \"${domains[0]}\" \"$le_container_name\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\nif wait_for_symlink \"${domains[0]}\" \"$le_container_name\"; then\n  # then grab the certificate in text form ...\n  created_cert=\"$(docker exec \"$le_container_name\" \\\n    openssl x509 -in \"/etc/nginx/certs/${domains[0]}/cert.pem\" -text -noout)\"\nfi\n\n# Check if the domain is on the certificate.\nif ! grep -q \"${domains[0]}\" <<< \"$created_cert\"; then\n  echo \"Domain ${domains[0]} did not appear on certificate.\"\nelif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n  echo \"Domain ${domains[0]} is on certificate.\"\nfi\n\ndocker exec \"$le_container_name\" bash -c \"[[ -f /etc/nginx/conf.d/standalone-cert-${domains[0]}.conf ]]\" \\\n  && echo \"Standalone configuration for ${domains[0]} wasn't correctly removed.\"\n\n# Add another (SAN) certificate to letsencrypt_user_data\ncat > \"${GITHUB_WORKSPACE}/test/tests/certs_standalone/letsencrypt_user_data\" <<EOF\nLETSENCRYPT_STANDALONE_CERTS=('single' 'san')\nLETSENCRYPT_single_HOST=('${domains[0]}')\nLETSENCRYPT_san_HOST=('${domains[1]}' '${domains[2]}')\nEOF\n\n# Manually trigger the service loop\ndocker exec \"$le_container_name\" /app/signal_le_service > /dev/null\n\nfor domain in \"${domains[1]}\" \"${domains[2]}\"; do\n  # Wait for a file at /etc/nginx/conf.d/standalone-cert-$domain.conf\n  wait_for_standalone_conf \"$domain\" \"$le_container_name\"\ndone\n\n# Wait for a symlink at /etc/nginx/certs/${domains[1]}.crt\nif wait_for_symlink \"${domains[1]}\" \"$le_container_name\"; then\n  # then grab the certificate in text form ...\n  created_cert=\"$(docker exec \"$le_container_name\" \\\n    openssl x509 -in \"/etc/nginx/certs/${domains[1]}/cert.pem\" -text -noout)\"\nfi\n\nfor domain in \"${domains[1]}\" \"${domains[2]}\"; do\n  # Check if the domain is on the certificate.\n  if ! grep -q \"$domain\" <<< \"$created_cert\"; then\n    echo \"Domain $domain did not appear on certificate.\"\n  elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n    echo \"Domain $domain is on certificate.\"\n  fi\ndone\n\ndocker exec \"$le_container_name\" bash -c \"[[ ! -f /etc/nginx/conf.d/standalone-cert-${domains[1]}.conf ]]\" \\\n  || echo \"Standalone configuration for ${domains[1]} wasn't correctly removed.\"\n"
  },
  {
    "path": "test/tests/container_restart/expected-std-out.txt",
    "content": "Container le1.wtf restarted\nContainer le2.wtf restarted\nContainer le3.wtf restarted\n"
  },
  {
    "path": "test/tests/container_restart/run.sh",
    "content": "#!/bin/bash\n\n## Test for LETSENCRYPT_RESTART_CONTAINER variable.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Listen for Docker restart events\ndocker events \\\n  --filter event=restart \\\n  --format 'Container {{.Actor.Attributes.name}} restarted' > \"${GITHUB_WORKSPACE}/test/tests/container_restart/docker_event_out.txt\" &\ndocker_events_pid=$!\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Kill the Docker events listener\n  kill $docker_events_pid && wait $docker_events_pid 2>/dev/null\n  # Remove temporary files\n  rm -f \"${GITHUB_WORKSPACE}/test/tests/container_restart/docker_event_out.txt\"\n  # Remove any remaining Nginx container(s) silently.\n  for domain in \"${domains[@]}\"; do\n    docker rm --force \"$domain\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run a separate nginx container for each domain in the $domains array.\nfor domain in \"${domains[@]}\"; do\n  run_nginx_container --hosts \"$domain\" --cli-args \"--env LETSENCRYPT_RESTART_CONTAINER=true\"\n\n  # Check if container restarted\n  timeout=\"$(date +%s)\"\n  timeout=\"$((timeout + 120))\"\n  until grep \"$domain\" \"${GITHUB_WORKSPACE}\"/test/tests/container_restart/docker_event_out.txt; do\n    if [[ \"$(date +%s)\" -gt \"$timeout\" ]]; then\n      echo \"Container $domain didn't restart in under one minute.\"\n      break\n    fi\n    sleep 0.1\n  done\ndone\n"
  },
  {
    "path": "test/tests/docker_api/run.sh",
    "content": "#!/bin/bash\n\n## Test for the Docker API.\n\nnginx_vol='nginx-volumes-from'\nnginx_env='nginx-env-var'\nnginx_lbl='nginx-label'\ndocker_gen='docker-gen-no-label'\ndocker_gen_lbl='docker-gen-label'\n\ncase $SETUP in\n\n  2containers)\n  # Cleanup function with EXIT trap\n  function cleanup {\n    # Kill the Docker events listener\n    kill \"$docker_events_pid\" && wait \"$docker_events_pid\" 2>/dev/null\n    # Remove the remaining containers silently\n    docker rm --force \\\n      \"$nginx_vol\" \\\n      \"$nginx_env\" \\\n      \"$nginx_lbl\" \\\n      &> /dev/null\n  }\n  trap cleanup EXIT\n\n  # Set the commands to be passed to docker exec\n  commands='source /app/functions.sh; reload_nginx > /dev/null; check_nginx_proxy_container_run; get_nginx_proxy_container'\n\n  # Listen to Docker exec_start events\n  docker events \\\n    --filter event=exec_start \\\n    --format 'Container {{.Actor.Attributes.name}} received {{.Action}}' &\n  docker_events_pid=$!\n\n  # Run a nginx-proxy container named nginx-volumes-from, without the nginx_proxy label\n  docker run --rm -d \\\n    --name \"$nginx_vol\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy > /dev/null\n\n  # Run a nginx-proxy container named nginx-env-var, without the nginx_proxy label\n  docker run --rm -d \\\n    --name \"$nginx_env\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy > /dev/null\n\n  # This should target the nginx-proxy container obtained with\n  # the --volume-from argument (nginx-volumes-from)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx-proxy container obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Run a nginx-proxy container named nginx-label, with the nginx_proxy label.\n  # Store the container id in the labeled_nginx_cid variable.\n  labeled_nginx_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    --label com.github.nginx-proxy.nginx \\\n    nginxproxy/nginx-proxy)\"\n\n  # This should target the nginx-proxy container with the label (nginx-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  cat > \"${GITHUB_WORKSPACE}/test/tests/docker_api/expected-std-out.txt\" <<EOF\nContainer $nginx_vol received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$nginx_vol\nContainer $nginx_env received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$nginx_env\nContainer $nginx_lbl received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$labeled_nginx_cid\nEOF\n  ;;\n\n  3containers)\n  # Cleanup function with EXIT trap\n  function cleanup {\n    # Kill the Docker events listener\n    kill $docker_events_pid && wait $docker_events_pid 2>/dev/null\n    # Remove the remaining containers silently\n    docker stop \\\n      \"$nginx_vol\" \\\n      \"$nginx_env\" \\\n      \"$nginx_lbl\" \\\n      \"$docker_gen\" \\\n      \"$docker_gen_lbl\" \\\n      &> /dev/null\n  }\n  trap cleanup EXIT\n\n  # Set the commands to be passed to docker exec\n  commands='source /app/functions.sh; reload_nginx > /dev/null; check_nginx_proxy_container_run; get_docker_gen_container; get_nginx_proxy_container'\n\n  # Listen to Docker kill events\n  docker events \\\n    --filter event=kill \\\n    --format 'Container {{.Actor.Attributes.name}} received signal {{.Actor.Attributes.signal}}' &\n  docker_events_pid=$!\n\n  # Run a nginx container named nginx-volumes-from, without the nginx_proxy label.\n  docker run --rm -d \\\n    --name \"$nginx_vol\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginx:alpine > /dev/null\n\n  # Run a nginx container named nginx-env-var, without the nginx_proxy label.\n  docker run --rm -d \\\n    --name \"$nginx_env\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginx:alpine > /dev/null\n\n  # Spawn a \"fake docker-gen\" container named docker-gen-nolabel, without the docker_gen label.\n  docker run --rm -d \\\n    --name \"$docker_gen\" \\\n    nginx:alpine > /dev/null\n\n  # This should target the nginx container whose id or name was obtained with\n  # the --volumes-from argument (nginx-volumes-from)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel).\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx container whose id or name was obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Spawn a nginx container named nginx-label, with the nginx_proxy label.\n  labeled_nginx1_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    --label com.github.nginx-proxy.nginx \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the nginx_proxy label (nginx-label)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  docker stop \"$nginx_lbl\" > /dev/null\n\n  # Spawn a \"fake docker-gen\" container named docker-gen-label, with the docker_gen label.\n  labeled_docker_gen_cid=\"$(docker run --rm -d \\\n    --name \"$docker_gen_lbl\" \\\n    --label com.github.nginx-proxy.docker-gen \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the --volumes-from argument (nginx-volumes-from)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx container whose id or name was obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Spawn a nginx container named nginx-label, with the nginx_proxy label.\n  labeled_nginx2_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    --label com.github.nginx-proxy.nginx \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the nginx_proxy label (nginx-label)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n    cat > \"${GITHUB_WORKSPACE}/test/tests/docker_api/expected-std-out.txt\" <<EOF\nContainer $docker_gen received signal 1\nContainer $nginx_vol received signal 1\n$docker_gen\n$nginx_vol\nContainer $docker_gen received signal 1\nContainer $nginx_env received signal 1\n$docker_gen\n$nginx_env\nContainer $docker_gen received signal 1\nContainer $nginx_lbl received signal 1\n$docker_gen\n$labeled_nginx1_cid\nContainer $nginx_lbl received signal 3\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_vol received signal 1\n$labeled_docker_gen_cid\n$nginx_vol\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_env received signal 1\n$labeled_docker_gen_cid\n$nginx_env\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_lbl received signal 1\n$labeled_docker_gen_cid\n$labeled_nginx2_cid\nEOF\n  ;;\n\nesac\n"
  },
  {
    "path": "test/tests/docker_api_legacy/run.sh",
    "content": "#!/bin/bash\n\n## Test for the Docker API with legacy labels.\n\nnginx_vol='nginx-volumes-from-legacy'\nnginx_env='nginx-env-var-legacy'\nnginx_lbl='nginx-label-legacy'\ndocker_gen='docker-gen-no-label-legacy'\ndocker_gen_lbl='docker-gen-label-legacy'\n\ncase $SETUP in\n\n  2containers)\n  # Cleanup function with EXIT trap\n  function cleanup {\n    # Kill the Docker events listener\n    kill \"$docker_events_pid\" && wait \"$docker_events_pid\" 2>/dev/null\n    # Remove the remaining containers silently\n    docker rm --force \\\n      \"$nginx_vol\" \\\n      \"$nginx_env\" \\\n      \"$nginx_lbl\" \\\n      &> /dev/null\n  }\n  trap cleanup EXIT\n\n  # Set the commands to be passed to docker exec\n  commands='source /app/functions.sh; reload_nginx > /dev/null; check_nginx_proxy_container_run; get_nginx_proxy_container'\n\n  # Listen to Docker exec_start events\n  docker events \\\n    --filter event=exec_start \\\n    --format 'Container {{.Actor.Attributes.name}} received {{.Action}}' &\n  docker_events_pid=$!\n\n  # Run a nginx-proxy container named nginx-volumes-from, without the nginx_proxy label\n  docker run --rm -d \\\n    --name \"$nginx_vol\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy > /dev/null\n\n  # Run a nginx-proxy container named nginx-env-var, without the nginx_proxy label\n  docker run --rm -d \\\n    --name \"$nginx_env\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginxproxy/nginx-proxy > /dev/null\n\n  # This should target the nginx-proxy container obtained with\n  # the --volume-from argument (nginx-volumes-from)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx-proxy container obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Run a nginx-proxy container named nginx-label, with the nginx_proxy label.\n  # Store the container id in the labeled_nginx_cid variable.\n  labeled_nginx_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    --label com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy \\\n    nginxproxy/nginx-proxy)\"\n\n  # This should target the nginx-proxy container with the label (nginx-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  cat > \"${GITHUB_WORKSPACE}/test/tests/docker_api_legacy/expected-std-out.txt\" <<EOF\nContainer $nginx_vol received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$nginx_vol\nContainer $nginx_env received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$nginx_env\nContainer $nginx_lbl received exec_start: sh -c /app/docker-entrypoint.sh /usr/local/bin/docker-gen /app/nginx.tmpl /etc/nginx/conf.d/default.conf; /usr/sbin/nginx -s reload\n$labeled_nginx_cid\nEOF\n  ;;\n\n  3containers)\n  # Cleanup function with EXIT trap\n  function cleanup {\n    # Kill the Docker events listener\n    kill $docker_events_pid && wait $docker_events_pid 2>/dev/null\n    # Remove the remaining containers silently\n    docker stop \\\n      \"$nginx_vol\" \\\n      \"$nginx_env\" \\\n      \"$nginx_lbl\" \\\n      \"$docker_gen\" \\\n      \"$docker_gen_lbl\" \\\n      &> /dev/null\n  }\n  trap cleanup EXIT\n\n  # Set the commands to be passed to docker exec\n  commands='source /app/functions.sh; reload_nginx > /dev/null; check_nginx_proxy_container_run; get_docker_gen_container; get_nginx_proxy_container'\n\n  # Listen to Docker kill events\n  docker events \\\n    --filter event=kill \\\n    --format 'Container {{.Actor.Attributes.name}} received signal {{.Actor.Attributes.signal}}' &\n  docker_events_pid=$!\n\n  # Run a nginx container named nginx-volumes-from, without the nginx_proxy label.\n  docker run --rm -d \\\n    --name \"$nginx_vol\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginx:alpine > /dev/null\n\n  # Run a nginx container named nginx-env-var, without the nginx_proxy label.\n  docker run --rm -d \\\n    --name \"$nginx_env\" \\\n    -v /var/run/docker.sock:/tmp/docker.sock:ro \\\n    nginx:alpine > /dev/null\n\n  # Spawn a \"fake docker-gen\" container named docker-gen-nolabel, without the docker_gen label.\n  docker run --rm -d \\\n    --name \"$docker_gen\" \\\n    nginx:alpine > /dev/null\n\n  # This should target the nginx container whose id or name was obtained with\n  # the --volumes-from argument (nginx-volumes-from)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel).\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx container whose id or name was obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Spawn a nginx container named nginx-label, with the nginx_proxy label.\n  labeled_nginx1_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    --label com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the nginx_proxy label (nginx-label)\n  # and the docker-gen container whose id or name was obtained with\n  # the NGINX_DOCKER_GEN_CONTAINER environment variable (docker-gen-nolabel)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  docker stop \"$nginx_lbl\" > /dev/null\n\n  # Spawn a \"fake docker-gen\" container named docker-gen-label, with the docker_gen label.\n  labeled_docker_gen_cid=\"$(docker run --rm -d \\\n    --name \"$docker_gen_lbl\" \\\n    --label com.github.jrcs.letsencrypt_nginx_proxy_companion.docker_gen \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the --volumes-from argument (nginx-volumes-from)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # This should target the nginx container whose id or name was obtained with\n  # the NGINX_PROXY_CONTAINER environment variable (nginx-env-var)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n  # Spawn a nginx container named nginx-label, with the nginx_proxy label.\n  labeled_nginx2_cid=\"$(docker run --rm -d \\\n    --name \"$nginx_lbl\" \\\n    --label com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy \\\n    nginx:alpine)\"\n\n  # This should target the nginx container whose id or name was obtained with\n  # the nginx_proxy label (nginx-label)\n  # and the docker-gen container whose id or name was obtained with\n  # the docker_gen label (docker-gen-label)\n  docker run --rm \\\n    -v /var/run/docker.sock:/var/run/docker.sock:ro \\\n    --volumes-from \"$nginx_vol\" \\\n    -e \"NGINX_PROXY_CONTAINER=$nginx_env\" \\\n    -e \"NGINX_DOCKER_GEN_CONTAINER=$docker_gen\" \\\n    \"$1\" \\\n    bash -c \"$commands\" 2>&1\n\n    cat > \"${GITHUB_WORKSPACE}/test/tests/docker_api_legacy/expected-std-out.txt\" <<EOF\nContainer $docker_gen received signal 1\nContainer $nginx_vol received signal 1\n$docker_gen\n$nginx_vol\nContainer $docker_gen received signal 1\nContainer $nginx_env received signal 1\n$docker_gen\n$nginx_env\nContainer $docker_gen received signal 1\nContainer $nginx_lbl received signal 1\n$docker_gen\n$labeled_nginx1_cid\nContainer $nginx_lbl received signal 3\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_vol received signal 1\n$labeled_docker_gen_cid\n$nginx_vol\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_env received signal 1\n$labeled_docker_gen_cid\n$nginx_env\nContainer $docker_gen_lbl received signal 1\nContainer $nginx_lbl received signal 1\n$labeled_docker_gen_cid\n$labeled_nginx2_cid\nEOF\n  ;;\n\nesac\n"
  },
  {
    "path": "test/tests/force_renew/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/force_renew/run.sh",
    "content": "#!/bin/bash\n\n## Test for the /app/force_renew script.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the Nginx container silently.\n  docker rm --force \"${domains[0]}\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run a nginx container for ${domains[0]}.\nrun_nginx_container --hosts \"${domains[0]}\"\n\n# Wait for a symlink at /etc/nginx/certs/${domains[0]}.crt\n# Grab the expiration time of the certificate\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\nfirst_cert_expire=\"$(get_cert_expiration_epoch \"${domains[0]}\" \"$le_container_name\")\"\n\n# Just to be sure\nsleep 5\n\n# Issue a forced renewal\n# Grab the expiration time of the renewed certificate\ndocker exec \"$le_container_name\" /app/force_renew &> /dev/null\nsecond_cert_expire=\"$(get_cert_expiration_epoch \"${domains[0]}\" \"$le_container_name\")\"\n\nif ! [[ $second_cert_expire -gt $first_cert_expire ]]; then\n  echo \"Certificate for ${domains[0]} was not correctly renewed.\"\n  echo \"First certificate expiration epoch : $first_cert_expire.\"\n  echo \"Second certificate expiration epoch : $second_cert_expire.\"\nelif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n  echo \"Certificate for ${domains[0]} was correctly renewed.\"\nfi\n"
  },
  {
    "path": "test/tests/location_config/expected-std-out.txt",
    "content": "*.bar.baz.com.example.com\n*.baz.com.example.com\n*.com.example.com\n*.example.com\nfoo.bar.baz.com.example.*\nfoo.bar.baz.com.*\nfoo.bar.baz.*\nfoo.bar.*\nfoo.*\n"
  },
  {
    "path": "test/tests/location_config/run.sh",
    "content": "#!/bin/bash\n\n## Test for automatic location configuration.\n\n# Set variables\ntest_comment='### This is a test comment'\nvhost_path='/etc/nginx/vhost.d'\n\n# Create custom location configuration file to be bind mounted\nlocation_file=\"${GITHUB_WORKSPACE}/test/tests/location_config/le2.wtf\"\necho \"$test_comment\" > \"$location_file\"\n\n# Create le1.wtf configuration file, *.le3.wtf and test.* from inside the nginx container\ndocker exec \"$NGINX_CONTAINER_NAME\" sh -c \"echo '### This is a test comment' > /etc/nginx/vhost.d/le1.wtf\"\ndocker exec \"$NGINX_CONTAINER_NAME\" sh -c \"echo '### This is a test comment' > /etc/nginx/vhost.d/\\*.example.com\"\ndocker exec \"$NGINX_CONTAINER_NAME\" sh -c \"echo '### This is a test comment' > /etc/nginx/vhost.d/test.\\*\"\n\n# Zero the default configuration file.\ndocker exec \"$NGINX_CONTAINER_NAME\" sh -c \"echo '' > /etc/nginx/vhost.d/default\"\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\" \"--volume $location_file:$vhost_path/le2.wtf\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts --location-config\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Check if the ACME location configuration was correctly applied (ie only once) to the target file\nfunction check_location {\n  local container=\"${1:?}\"\n  local path=\"${2:?}\"\n  local start_comment='## Start of configuration add by letsencrypt container'\n  local end_comment='## End of configuration add by letsencrypt container'\n\n  if [[ \"$(docker exec \"$container\" grep -c \"$start_comment\" \"$path\")\" != 1 ]]; then\n    return 1\n  elif [[ \"$(docker exec \"$container\" grep -c \"$end_comment\" \"$path\")\" != 1 ]]; then\n    return 1\n  else\n    return 0\n  fi\n}\n\n# check the wildcard location enumeration function\ndocker exec \"$le_container_name\" bash -c 'source /app/functions.sh; enumerate_wildcard_locations foo.bar.baz.com.example.com'\n\n# default configuration file should be empty\nconfig_path=\"$vhost_path/default\"\nif docker exec \"$le_container_name\" [ ! -s \"$config_path\" ]; then\n  echo \"$config_path should be empty at container startup:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# custom configuration files should only contains the test comment\nfor domain in \"${domains[@]:0:2}\" '*.example.com' 'test.*'; do\n  config_path=\"$vhost_path/$domain\"\n  if check_location \"$le_container_name\" \"$config_path\"; then\n    echo \"Unexpected location configuration on $config_path at container startup:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  elif ! docker exec \"$le_container_name\" grep -q \"$test_comment\" \"$config_path\"; then\n    echo \"$config_path should have test comment at container startup:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  fi\ndone\n\n# le3.wtf configuration file should not exist\nconfig_path=\"$vhost_path/${domains[2]}\"\nif docker exec \"$le_container_name\" [ -e \"$config_path\" ]; then\n  echo \"$config_path should not exist at container startup :\"\n  docker exec \"$le_container_name\" ls -lh \"$config_path\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# Add default location configuration then check\nconfig_path=\"$vhost_path/default\"\ndocker exec \"$le_container_name\" bash -c 'source /app/functions.sh; add_location_configuration'\nif ! check_location \"$le_container_name\" \"$config_path\" ; then\n  echo \"Unexpected location configuration on $config_path after call to add_location_configuration:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# Add le1.wtf and le2.wtf location configurations then check\nfor domain in \"${domains[@]:0:2}\"; do\n  config_path=\"$vhost_path/$domain\"\n  docker exec \"$le_container_name\" bash -c \"source /app/functions.sh; add_location_configuration $domain\"\n  if ! check_location \"$le_container_name\" \"$config_path\" ; then\n    echo \"Unexpected location configuration on $config_path after call to add_location_configuration $domain:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  elif ! docker exec \"$le_container_name\" grep -q \"$test_comment\" \"$config_path\"; then\n    echo \"$config_path should still have test comment after call to add_location_configuration $domain:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  fi\ndone\n\n# Adding subdomain.example.com location configurations should use the *.example.com file\ndomain=\"subdomain.example.com\"\nconfig_path=\"$vhost_path/*.example.com\"\ndocker exec \"$le_container_name\" bash -c \"source /app/functions.sh; add_location_configuration $domain\"\nif ! check_location \"$le_container_name\" \"$config_path\" ; then\n  echo \"Unexpected location configuration on $config_path after call to add_location_configuration $domain:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nelif ! docker exec \"$le_container_name\" grep -q \"$test_comment\" \"$config_path\"; then\n  echo \"$config_path should still have test comment after call to add_location_configuration $domain:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# Adding test.domain.tld location configurations should use the test.* file\ndomain=\"test.domain.tld\"\nconfig_path=\"$vhost_path/test.*\"\ndocker exec \"$le_container_name\" bash -c \"source /app/functions.sh; add_location_configuration $domain\"\nif ! check_location \"$le_container_name\" \"$config_path\" ; then\n  echo \"Unexpected location configuration on $config_path after call to add_location_configuration $domain:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nelif ! docker exec \"$le_container_name\" grep -q \"$test_comment\" \"$config_path\"; then\n  echo \"$config_path should still have test comment after call to add_location_configuration $domain:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# Remove all location configurations\ndocker exec \"$le_container_name\" bash -c \"source /app/functions.sh; remove_all_location_configurations\"\n\n# default configuration file should be empty again\nconfig_path=\"$vhost_path/default\"\nif docker exec \"$le_container_name\" [ ! -s \"$config_path\" ]; then\n  echo \"$config_path should be empty after call to remove_all_location_configurations:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\n# Custom configuration files should have reverted to only containing the test comment\nfor domain in \"${domains[@]:0:2}\" '*.example.com' 'test.*'; do\n  config_path=\"$vhost_path/$domain\"\n  if check_location \"$le_container_name\" \"$config_path\"; then\n    echo \"Unexpected location configuration on $config_path after call to remove_all_location_configurations:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  elif ! docker exec \"$le_container_name\" grep -q \"$test_comment\" \"$config_path\"; then\n    echo \"$config_path should still have test comment after call to remove_all_location_configurations:\"\n    docker exec \"$le_container_name\" cat \"$config_path\"\n  fi\ndone\n\n# Should not be used by anything, but potentially matches an enumerate_wildcard_locations file glob.\ndocker exec \"$NGINX_CONTAINER_NAME\" touch /etc/nginx/vhost.d/le3.pizza\ndocker exec \"$le_container_name\" touch le3.pizza\n\n# Trying to add location configuration to non existing le3.wtf should only configure default\ndocker exec \"$le_container_name\" bash -c \"source /app/functions.sh; add_location_configuration ${domains[2]}\"\n\nconfig_path=\"$vhost_path/${domains[2]}\"\nif docker exec \"$le_container_name\" [ -e \"$config_path\" ]; then\n  echo \"$config_path should not exist after call to add_location_configuration ${domains[2]}:\"\n  docker exec \"$le_container_name\" ls -lh \"$config_path\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n\nconfig_path=\"$vhost_path/default\"\nif ! check_location \"$le_container_name\" \"$config_path\" ; then\n  echo \"Unexpected location configuration on $config_path after call to add_location_configuration ${domains[2]}:\"\n  docker exec \"$le_container_name\" cat \"$config_path\"\nfi\n"
  },
  {
    "path": "test/tests/ocsp_must_staple/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/ocsp_must_staple/run.sh",
    "content": "#!/bin/bash\n\n## Test for OCSP Must-Staple extension.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  for domain in \"${domains[0]}\" \"${domains[1]}\"; do\n    docker rm --force \"$domain\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run an nginx container with ACME_OCSP=true\nrun_nginx_container --hosts \"${domains[0]}\" --cli-args \"--env ACME_OCSP=true\"\n\n# Run an second nginx container without ACME_OCSP=true\nrun_nginx_container --hosts \"${domains[1]}\"\n\n# Wait for the symlink to the ${domains[0]} certificate\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\n# Check if the OCSP Must-Staple extension is present in the ${domains[0]} certificate\nif docker exec \"$le_container_name\" openssl x509 -in \"/etc/nginx/certs/${domains[0]}/cert.pem\" -text -noout | grep -q -E '1\\.3\\.6\\.1\\.5\\.5\\.7\\.1\\.24|status_request'; then\n  [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"The OCSP Must-Staple extension is present on the ${domains[0]} certificate.\"\nelse\n  echo \"The OCSP Must-Staple extension is absent from the ${domains[0]} certificate.\"\nfi\n\n# Wait for the symlink to the ${domains[1]} certificate\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\"\n\n# Check if the OCSP Must-Staple extension is absent from the ${domains[1]} certificate\nif docker exec \"$le_container_name\" openssl x509 -in \"/etc/nginx/certs/${domains[1]}/cert.pem\" -text -noout | grep -q -E '1\\.3\\.6\\.1\\.5\\.5\\.7\\.1\\.24|status_request'; then\n  echo \"The OCSP Must-Staple extension is present on the ${domains[1]} certificate.\"\nelif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n  echo \"The OCSP Must-Staple extension is absent from the ${domains[1]} certificate.\"\nfi\n"
  },
  {
    "path": "test/tests/permissions_custom/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/permissions_custom/run.sh",
    "content": "#!/bin/bash\n\n## Test for sensitive files and folders permissions\n\nfiles_uid=1000\nfiles_gid=1001\nfiles_perms=644\nfolders_perms=750\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\" \\\n  \"--env FILES_UID=$files_uid --env FILES_GID=$files_gid --env FILES_PERMS=$files_perms --env FOLDERS_PERMS=$folders_perms\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the ${domains[0]} Nginx container silently.\n  docker rm --force \"${domains[0]}\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run an nginx container for ${domains[0]}.\nrun_nginx_container --hosts \"${domains[0]}\"\n\n# Wait for the cert symlink.\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\n# Array of folder paths to test\nfolders=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}\" \\\n  )\n\n# Test folder paths\nfor folder in  \"${folders[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$folder\")\"\n  if [[ \"$ownership_and_permissions\" != ${files_uid}:${files_gid}:${folders_perms} ]]; then\n    echo \"Expected ${files_uid}:${files_gid}:${folders_perms} on ${folder}, found ${ownership_and_permissions}.\"\n  fi\ndone\n\n# Array of symlinks paths to test\nsymlinks=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}.crt\" \\\n  [1]=\"/etc/nginx/certs/${domains[0]}.key\" \\\n  [2]=\"/etc/nginx/certs/${domains[0]}.chain.pem\" \\\n  [3]=\"/etc/nginx/certs/${domains[0]}.dhparam.pem\" \\\n  )\n\n# Test symlinks paths\nfor symlink in  \"${symlinks[@]}\"; do\n  ownership=\"$(docker exec \"$le_container_name\" stat -c %u:%g \"$symlink\")\"\n  if [[ \"$ownership\" != ${files_uid}:${files_gid} ]]; then\n    echo \"Expected ${files_uid}:${files_gid} on ${symlink}, found ${ownership}.\"\n  fi\ndone\n\n# Array of private file paths to test\nprivate_files=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}/key.pem\" \\\n  [1]=\"/etc/acme.sh/default/${domains[0]}/${domains[0]}.key\" \\\n  )\n\n# Test private file paths\nfor file in  \"${private_files[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$file\")\"\n  if [[ \"$ownership_and_permissions\" != ${files_uid}:${files_gid}:${files_perms} ]]; then\n    echo \"Expected ${files_uid}:${files_gid}:${files_perms} on ${file}, found ${ownership_and_permissions}.\"\n  fi\ndone\n\n# Array of public files paths to test\npublic_files=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}/.companion\" \\\n  [1]=\"/etc/nginx/certs/${domains[0]}/cert.pem\" \\\n  [2]=\"/etc/nginx/certs/${domains[0]}/chain.pem\" \\\n  [3]=\"/etc/nginx/certs/${domains[0]}/fullchain.pem\" \\\n  [4]=\"/etc/nginx/certs/dhparam.pem\" \\\n  )\n\n# Test public file paths\nfor file in  \"${public_files[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$file\")\"\n  if [[ \"$ownership_and_permissions\" != ${files_uid}:${files_gid}:644 ]]; then\n    echo \"Expected ${files_uid}:${files_gid}:644 on ${file}, found ${ownership_and_permissions}.\"\n  fi\ndone\n"
  },
  {
    "path": "test/tests/permissions_default/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/permissions_default/run.sh",
    "content": "#!/bin/bash\n\n## Test for sensitive files and folders permissions\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove the ${domains[0]} Nginx container silently.\n  docker rm --force \"${domains[0]}\" &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run an nginx container for ${domains[0]}.\nrun_nginx_container --hosts \"${domains[0]}\"\n\n# Wait for the cert symlink.\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\"\n\n# Array of folder paths to test\nfolders=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}\" \\\n  )\n\n# Test folder paths\nfor folder in  \"${folders[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$folder\")\"\n  if [[ \"$ownership_and_permissions\" != 0:0:755 ]]; then\n    echo \"Expected 0:0:755 on ${folder}, found ${ownership_and_permissions}.\"\n  fi\ndone\n\n# Array of symlinks paths to test\nsymlinks=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}.crt\" \\\n  [1]=\"/etc/nginx/certs/${domains[0]}.key\" \\\n  [2]=\"/etc/nginx/certs/${domains[0]}.chain.pem\" \\\n  [3]=\"/etc/nginx/certs/${domains[0]}.dhparam.pem\" \\\n  )\n\n# Test symlinks paths\nfor symlink in  \"${symlinks[@]}\"; do\n  ownership=\"$(docker exec \"$le_container_name\" stat -c %u:%g \"$symlink\")\"\n  if [[ \"$ownership\" != 0:0 ]]; then\n    echo \"Expected 0:0 on ${symlink}, found ${ownership}.\"\n  fi\ndone\n\n# Array of private file paths to test\nprivate_files=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}/key.pem\" \\\n  [1]=\"/etc/acme.sh/default/${domains[0]}/${domains[0]}.key\" \\\n  )\n\n# Test private file paths\nfor file in  \"${private_files[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$file\")\"\n  if [[ \"$ownership_and_permissions\" != 0:0:600 ]]; then\n    echo \"Expected 0:0:600 on ${file}, found ${ownership_and_permissions}.\"\n  fi\ndone\n\n# Array of public files paths to test\npublic_files=( \\\n  [0]=\"/etc/nginx/certs/${domains[0]}/.companion\" \\\n  [1]=\"/etc/nginx/certs/${domains[0]}/cert.pem\" \\\n  [2]=\"/etc/nginx/certs/${domains[0]}/chain.pem\" \\\n  [3]=\"/etc/nginx/certs/${domains[0]}/fullchain.pem\" \\\n  [4]=\"/etc/nginx/certs/dhparam.pem\" \\\n  )\n\n# Test public file paths\nfor file in  \"${public_files[@]}\"; do\n  ownership_and_permissions=\"$(docker exec \"$le_container_name\" stat -c %u:%g:%a \"$file\")\"\n  if [[ \"$ownership_and_permissions\" != 0:0:644 ]]; then\n    echo \"Expected 0:0:644 on ${file}, found ${ownership_and_permissions}.\"\n  fi\ndone\n"
  },
  {
    "path": "test/tests/private_keys/expected-std-out.txt",
    "content": "\n"
  },
  {
    "path": "test/tests/private_keys/run.sh",
    "content": "#!/usr/bin/env bash\n\n## Test for private keys types\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove any remaining Nginx container(s) silently.\n  for key in \"${!key_types[@]}\"; do\n    docker rm --force \"${key}\" &> /dev/null\n  done\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\ndeclare -A key_types\nkey_types=( \\\n  ['2048']='Public-Key: (2048 bit)' \\\n  ['3072']='Public-Key: (3072 bit)' \\\n  ['4096']='Public-Key: (4096 bit)' \\\n  ['ec-256']='prime256v1' \\\n  ['ec-384']='secp384r1' \\\n)\n\nfor key in \"${!key_types[@]}\"; do\n\n  # Run an Nginx container with the wanted key type.\n  run_nginx_container --hosts \"${domains[0]}\" --name \"${key}\" --cli-args \"--env LETSENCRYPT_KEYSIZE=${key}\"\n\n  # Grep the expected string from the public key in text form.\n  if wait_for_symlink \"${domains[0]}\" \"$le_container_name\"; then\n    public_key=$(docker exec \"$le_container_name\" openssl pkey -in \"/etc/nginx/certs/${domains[0]}.key\" -noout -text_pub)\n    if ! grep -q \"${key_types[$key]}\" <<< \"$public_key\"; then\n      echo \"Keys for test $key were not of the correct type, expected ${key_types[$key]} and got the following:\"\n      echo \"$public_key\"\n    fi\n  else\n    echo \"${key_types[$key]} key test timed out\"\n  fi\n\n  docker stop \"${key}\" &> /dev/null\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n\ndone\n"
  },
  {
    "path": "test/tests/symlinks/expected-std-out.txt",
    "content": "Symlink for lim.it certificate was not generated under one minute, timing out.\n"
  },
  {
    "path": "test/tests/symlinks/run.sh",
    "content": "#!/bin/bash\n\n## Test for symlink creation / removal.\n\nif [[ -z $GITHUB_ACTIONS ]]; then\n  le_container_name=\"$(basename \"${0%/*}\")_$(date \"+%Y-%m-%d_%H.%M.%S\")\"\nelse\n  le_container_name=\"$(basename \"${0%/*}\")\"\nfi\nrun_le_container \"${1:?}\" \"$le_container_name\"\n\n# Create the $domains array from comma separated domains in TEST_DOMAINS.\nIFS=',' read -r -a domains <<< \"$TEST_DOMAINS\"\n\n# Cleanup function with EXIT trap\nfunction cleanup {\n  # Remove all remaining nginx containers silently\n  docker rm --force \\\n    symlink-le1-le2 \\\n    symlink-le1-le2-le3 \\\n    symlink-le2 \\\n    symlink-le3 \\\n    symlink-lim-le2 \\\n    &> /dev/null\n  # Cleanup the files created by this run of the test to avoid foiling following test(s).\n  docker exec \"$le_container_name\" /app/cleanup_test_artifacts\n  # Stop the LE container\n  docker stop \"$le_container_name\" > /dev/null\n}\ntrap cleanup EXIT\n\n# Run a nginx container for the firs two domain in the $domains array ...\nrun_nginx_container --hosts \"${domains[0]},${domains[1]}\" --name \"symlink-le1-le2\"\n\n# ... plus another nginx container for the third domain.\nrun_nginx_container --hosts \"${domains[2]}\" --name \"symlink-le3\"\n\n# Wait for a file at /etc/nginx/certs/$domain/cert.pem\nwait_for_symlink \"${domains[0]}\" \"$le_container_name\" \"./${domains[0]}/fullchain.pem\"\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\" \"./${domains[0]}/fullchain.pem\"\nwait_for_symlink \"${domains[2]}\" \"$le_container_name\" \"./${domains[2]}/fullchain.pem\"\n\n# Create a fake le4.wtf custom certificate and key\ndocker exec \"$le_container_name\" mkdir -p /etc/nginx/certs/le4.wtf\ndocker exec \"$le_container_name\" cp /etc/nginx/certs/le1.wtf/fullchain.pem /etc/nginx/certs/le4.wtf/\ndocker exec \"$le_container_name\" cp /etc/nginx/certs/le1.wtf/key.pem /etc/nginx/certs/le4.wtf/\ndocker exec \"$le_container_name\" bash -c 'cd /etc/nginx/certs; ln -s ./le4.wtf/fullchain.pem ./le4.wtf.crt'\ndocker exec \"$le_container_name\" bash -c 'cd /etc/nginx/certs; ln -s ./le4.wtf/key.pem ./le4.wtf.key'\n\n# Symlink default certificate to le1.wtf certificate\ndocker exec \"$le_container_name\" bash -c 'cd /etc/nginx/certs; ln -s ./le1.wtf/fullchain.pem ./default.crt'\ndocker exec \"$le_container_name\" bash -c 'cd /etc/nginx/certs; ln -s ./le1.wtf/key.pem ./default.key'\n\n# Stop the nginx containers for ${domains[0]} and ${domains[1]} silently,\n# then check if the corresponding symlinks are removed.\ndocker stop \"symlink-le1-le2\" > /dev/null\nfor domain in \"${domains[@]::2}\"; do\n  wait_for_symlink_rm \"$domain\" \"$le_container_name\"\ndone\n\n# Check if ${domains[2]} symlink is still there\ndocker exec \"$le_container_name\" [ -L \"/etc/nginx/certs/${domains[2]}.crt\" ] \\\n  || echo \"Symlink to ${domains[2]} certificate was removed.\"\n\n# Stop the nginx containers for ${domains[2]} silently,\n# then check if the corresponding symlink is removed.\ndocker stop \"symlink-le3\" > /dev/null\nwait_for_symlink_rm \"${domains[2]}\" \"$le_container_name\"\n\n# Start the nginx containers for ${domains[2]} again,\n# and check if the corresponding symlink is re-created.\nrun_nginx_container --hosts \"${domains[2]}\" --name \"symlink-le3\"\nwait_for_symlink \"${domains[2]}\" \"$le_container_name\" \"./${domains[2]}/fullchain.pem\"\n\n# Stop the nginx containers for ${domains[2]} silently and wait for symlink removal.\ndocker stop \"symlink-le3\" > /dev/null\nwait_for_symlink_rm \"${domains[2]}\" \"$le_container_name\"\n\n# Move ${domains[2]} to a san certificate with ${domains[0]} and ${domains[1]}\nrun_nginx_container --hosts \"${domains[0]},${domains[1]},${domains[2]}\" --name \"symlink-le1-le2-le3\"\n\n# Check where the symlink points (should be ./le1.wtf/fullchain.pem)\nwait_for_symlink \"${domains[2]}\" \"$le_container_name\" \"./${domains[0]}/fullchain.pem\"\n\n# Stop the nginx container silently.\ndocker stop \"symlink-le1-le2-le3\" > /dev/null\n\n# Check if the symlinks are correctly removed\nfor domain in \"${domains[@]}\"; do\n  wait_for_symlink_rm \"$domain\" \"$le_container_name\"\ndone\n\n# Move ${domains[1]} to a new single domain certificate\nrun_nginx_container --hosts \"${domains[1]}\" --name \"symlink-le2\"\n\n# Check where the symlink points (should be ./le2.wtf/fullchain.pem)\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\" \"./${domains[1]}/fullchain.pem\"\n\n# Stop the nginx container silently and try to put ${domains[1]} on a\n# san certificate whose authorization will fail.\ndocker stop \"symlink-le2\" > /dev/null\nrun_nginx_container --hosts \"lim.it,${domains[1]}\" --name \"symlink-lim-le2\"\n\n# The symlink creation for lim.it should time out, and the ${domains[1]}\n# symlink should still point to ./le2.wtf/fullchain.pem\nwait_for_symlink \"lim.it\" \"$le_container_name\"\nwait_for_symlink \"${domains[1]}\" \"$le_container_name\" \"./${domains[1]}/fullchain.pem\"\n\n# Aaaaaand stop the container.\ndocker stop \"symlink-lim-le2\" > /dev/null\n\n# Check if the custom certificate is still there\ndocker exec \"$le_container_name\" [ -f /etc/nginx/certs/le4.wtf.crt ] \\\n  || echo \"Custom certificate for le4.wtf was removed.\"\n\n# Check if the default certificate is still there\ndocker exec \"$le_container_name\" [ -f /etc/nginx/certs/default.crt ] \\\n  || echo \"Default certificate was removed.\"\n"
  },
  {
    "path": "test/tests/test-functions.sh",
    "content": "#!/bin/bash\n\nset -e\n\n# Get the first domain of a comma separated list.\nfunction get_base_domain {\n  awk -F ',' '{print $1}' <<< \"${1:?}\" | tr -d ' ' | sed 's/\\.$//'\n}\nexport -f get_base_domain\n\n\n# Run a acme-companion container\nfunction run_le_container {\n  local image=\"${1:?}\"\n  local name=\"${2:?}\"\n  shift 2\n  local -a cli_args_arr\n  \n  while [[ $# -gt 0 ]]; do\n  local flag=\"$1\"\n\n    case $flag in\n      -c|--cli-args) #only one value per flag. Multiple args = use flag multiple times \n      local cli_args_arr_tmp\n      IFS=' ' read -r -a cli_args_arr_tmp <<< \"${2:?}\"\n      cli_args_arr+=(\"${cli_args_arr_tmp[0]}\") #Head\n      cli_args_arr+=(\"${cli_args_arr_tmp[*]:1}\") #Tail\n      shift 2\n      ;;\n\n      *) #Legacy Option\n      local cli_args_str=\"${1:?}\"\n      for arg in $cli_args_str; do\n        cli_args_arr+=(\"$arg\")\n      done\n      shift\n      ;;\n    esac\n\n  done\n\n  if [[ \"$SETUP\" == '3containers' ]]; then\n    cli_args_arr+=(--env \"NGINX_DOCKER_GEN_CONTAINER=$DOCKER_GEN_CONTAINER_NAME\")\n  fi\n\n  if [[ \"$ACME_CA\" == 'boulder' ]]; then\n    cli_args_arr+=(--env \"ACME_CA_URI=http://boulder:4001/directory\")\n    cli_args_arr+=(--network boulder_bluenet)\n  elif [[ \"$ACME_CA\" == 'pebble' ]]; then\n    cli_args_arr+=(--env \"ACME_CA_URI=https://pebble:14000/dir\")\n    cli_args_arr+=(--env \"CA_BUNDLE=/pebble.minica.pem\")\n    cli_args_arr+=(--network acme_net)\n    cli_args_arr+=(--volume \"${GITHUB_WORKSPACE}/pebble.minica.pem:/pebble.minica.pem\")\n  else\n    return 1\n  fi\n\n  if docker run -d \\\n    --name \"$name\" \\\n    --volumes-from \"$NGINX_CONTAINER_NAME\" \\\n    --volume /var/run/docker.sock:/var/run/docker.sock:ro \\\n    \"${cli_args_arr[@]}\" \\\n    --env \"DOCKER_GEN_WAIT=500ms:2s\" \\\n    --env \"TEST_MODE=true\" \\\n    --env \"DEBUG=1\" \\\n    --label com.github.nginx-proxy.acme-companion.test-suite \\\n    \"$image\" > /dev/null; \\\n  then\n    [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Started letsencrypt container for test ${name%%_2*}\"\n  else\n    echo \"Could not start letsencrypt container for test ${name%%_2*}\"\n    return 1\n  fi\n  return 0\n}\nexport -f run_le_container\n\n# Run an nginx container\nfunction run_nginx_container {\n  local -a cli_args_arr\n\n  while [[ $# -gt 0 ]]; do\n  local flag=\"$1\"\n\n    case $flag in\n      -h|--hosts)\n      local le_host=\"${2:?}\"\n      local virtual_host=\"${le_host// /}\"; virtual_host=\"${virtual_host//.,/,}\"; virtual_host=\"${virtual_host%,}\"\n      shift 2\n      ;;\n\n      -n|--name)\n      local container_name=\"${2:?}\"\n      shift 2\n      ;;\n\n      -c|--cli-args)\n      local cli_args_arr_tmp\n      IFS=' ' read -r -a cli_args_arr_tmp <<< \"${2:?}\"\n      cli_args_arr+=(\"${cli_args_arr_tmp[0]}\") #Head\n      cli_args_arr+=(\"${cli_args_arr_tmp[*]:1}\") #Tail\n      shift 2\n      ;;\n\n      *) #Unknown option\n      shift\n      ;;\n    esac\n  done\n\n  if [[ \"$ACME_CA\" == 'boulder' ]]; then\n    cli_args_arr+=(--network boulder_bluenet)\n  elif [[ \"$ACME_CA\" == 'pebble' ]]; then\n    cli_args_arr+=(--network acme_net)\n  else\n    return 1\n  fi\n\n  [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Starting $container_name nginx container, with VIRTUAL_HOST=$virtual_host, LETSENCRYPT_HOST=$le_host and the following cli arguments : ${cli_args_arr[*]}.\"\n  \n  if docker run --rm -d \\\n    --name \"${container_name:-$virtual_host}\" \\\n    -e \"VIRTUAL_HOST=$virtual_host\" \\\n    -e \"LETSENCRYPT_HOST=$le_host\" \\\n    --label com.github.nginx-proxy.acme-companion.test-suite \\\n    \"${cli_args_arr[@]}\" \\\n    nginx:alpine > /dev/null ; \\\n  then\n    [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Started $container_name nginx container.\"\n  else\n    echo \"Failed to start $container_name nginx container, with VIRTUAL_HOST=$virtual_host, LETSENCRYPT_HOST=$le_host and the following cli arguments : ${cli_args_arr[*]}.\"\n    return 1\n  fi\n  return 0\n}\nexport -f run_nginx_container\n\n\n# Wait for the /etc/nginx/conf.d/standalone-cert-$1.conf file to exist inside container $2\nfunction wait_for_standalone_conf {\n  local domain=\"${1:?}\"\n  local name=\"${2:?}\"\n  local timeout\n  timeout=\"$(date +%s)\"\n  timeout=\"$((timeout + 120))\"\n  local target\n  until docker exec \"$name\" [ -f \"/etc/nginx/conf.d/standalone-cert-$domain.conf\" ]; do\n    if [[ \"$(date +%s)\" -gt \"$timeout\" ]]; then\n      echo \"Standalone configuration file for $domain was not generated under one minute, timing out.\"\n      return 1\n    fi\n    sleep 0.1\n  done\n}\nexport -f wait_for_standalone_conf\n\n\n# Wait for the /etc/nginx/certs/$1.crt symlink to exist inside container $2\nfunction wait_for_symlink {\n  local domain=\"${1:?}\"\n  local name=\"${2:?}\"\n  local expected_target=\"${3:-}\"\n  local timeout\n  timeout=\"$(date +%s)\"\n  timeout=\"$((timeout + 120))\"\n  local target\n  until docker exec \"$name\" [ -L \"/etc/nginx/certs/$domain.crt\" ]; do\n    if [[ \"$(date +%s)\" -gt \"$timeout\" ]]; then\n      echo \"Symlink for $domain certificate was not generated under one minute, timing out.\"\n      return 1\n    fi\n    sleep 0.1\n  done\n  [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Symlink to $domain certificate has been generated.\"\n  if [[ -n \"$expected_target\" ]]; then\n    target=\"$(docker exec \"$name\" readlink \"/etc/nginx/certs/$domain.crt\")\"\n    if [[ \"$target\" != \"$expected_target\" ]]; then\n      echo \"The symlink to the $domain certificate is expected to point to $expected_target but point to $target instead.\"\n      return 1\n    elif [[ \"${DRY_RUN:-}\" == 1 ]]; then\n      echo \"The symlink is pointing to the file $target\"\n    fi\n  fi\n  return 0\n}\nexport -f wait_for_symlink\n\n\n# Wait for the /etc/nginx/certs/$1.crt symlink to be removed inside container $2\nfunction wait_for_symlink_rm {\n  local domain=\"${1:?}\"\n  local name=\"${2:?}\"\n  local timeout\n  timeout=\"$(date +%s)\"\n  timeout=\"$((timeout + 120))\"\n  until docker exec \"$name\" [ ! -L \"/etc/nginx/certs/$domain.crt\" ]; do\n    if [[ \"$(date +%s)\" -gt \"$timeout\" ]]; then\n      echo \"Certificate symlink for $domain was not removed under one minute, timing out.\"\n      return 1\n    fi\n    sleep 0.1\n  done\n  [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Symlink to $domain certificate has been removed.\"\n  return 0\n}\nexport -f wait_for_symlink_rm\n\n\n# Attempt to grab the certificate from domain passed with -d/--domain\n# then check if the subject either match or doesn't match the pattern\n# passed with either -m/--match or -nm/--no-match\n# If domain can't be reached return 1\nfunction check_cert_subj {\n  while [[ $# -gt 0 ]]; do\n  local flag=\"$1\"\n\n    case $flag in\n      -d|--domain)\n      local domain=\"${2:?}\"\n      shift\n      shift\n      ;;\n\n      -m|--match)\n      local re=\"${2:?}\"\n      local match_rc=0\n      local no_match_rc=1\n      shift\n      shift\n      ;;\n\n      -n|--no-match)\n      local re=\"${2:?}\"\n      local match_rc=1\n      local no_match_rc=0\n      shift\n      shift\n      ;;\n\n      *) #Unknown option\n      shift\n      ;;\n    esac\n  done\n\n  if curl -k https://\"$domain\" &> /dev/null; then\n    local cert_subject\n    cert_subject=\"$(echo \\\n      | openssl s_client -showcerts -servername \"$domain\" -connect \"$domain:443\" 2>/dev/null \\\n      | openssl x509 -subject -noout)\"\n  else\n    return 1\n  fi\n\n  if [[ \"$cert_subject\" =~ $re ]]; then\n    return $match_rc\n  else\n    return $no_match_rc\n  fi\n}\nexport -f check_cert_subj\n\n\n# Wait for a successful https connection to domain passed with -d/--domain then wait\n#   - until the served certificate isn't the default one (default behavior)\n#   - until the served certificate subject match a string (--subject-match)\nfunction wait_for_conn {\n  local action\n  local domain\n  local string\n\n  while [[ $# -gt 0 ]]; do\n  local flag=\"$1\"\n\n    case $flag in\n      -d|--domain)\n      domain=\"${2:?}\"\n      shift\n      shift\n      ;;\n\n      --subject-match)\n      action='--match'\n      string=\"$2\"\n      shift\n      shift\n      ;;\n\n      *) #Unknown option\n      shift\n      ;;\n    esac\n  done\n\n  local timeout\n  timeout=\"$(date +%s)\"\n  timeout=\"$((timeout + 120))\"\n  action=\"${action:---no-match}\"\n  string=\"${string:-letsencrypt-nginx-proxy-companion}\"\n\n  until check_cert_subj --domain \"$domain\" \"$action\" \"$string\"; do\n    if [[ \"$(date +%s)\" -gt \"$timeout\" ]]; then\n      echo \"Could not connect to $domain using https under two minutes, timing out.\"\n      return 1\n    fi\n    sleep 0.1\n  done\n  [[ \"${DRY_RUN:-}\" == 1 ]] && echo \"Connection to $domain using https was successful.\"\n  return 0\n}\nexport -f wait_for_conn\n\n\n# Get the expiration date in unix epoch of domain $1 inside container $2\nfunction get_cert_expiration_epoch {\n  local domain=\"${1:?}\"\n  local name=\"${2:?}\"\n  local cert_expiration\n  cert_expiration=\"$(docker exec \"$name\" openssl x509 -noout -enddate -in \"/etc/nginx/certs/$domain.crt\")\"\n  cert_expiration=\"$(echo \"$cert_expiration\" | cut -d \"=\" -f 2)\"\n  if [[ \"$(uname)\" == 'Darwin' ]]; then\n    cert_expiration=\"$(date -j -f \"%b %d %T %Y %Z\" \"$cert_expiration\" \"+%s\")\"\n  else\n    cert_expiration=\"$(date -d \"$cert_expiration\" \"+%s\")\"\n  fi\n  echo \"$cert_expiration\"\n}\nexport -f get_cert_expiration_epoch\n"
  },
  {
    "path": "test/tests/unit_tests/expected-std-out.txt",
    "content": "\n"
  }
]